260813_01_FST: First Commit

This commit is contained in:
2026-08-13 17:15:17 +09:00
commit 7c9da4517c
142 changed files with 18135 additions and 0 deletions

18
.agent/profile.yml Normal file
View File

@@ -0,0 +1,18 @@
schema_version: 1
project:
id: epolicy-dash-front
name: "epolicy-dash-front"
type: requested-project
layer: frontend
legacy: false
stack:
- typescript
- react
- nextjs
shared_contracts:
consumes:
- kri-front-common
- kri-ui-registry

48
.agent/project.md Normal file
View File

@@ -0,0 +1,48 @@
## Generated Next.js Repository Rules
- This frontend application was generated by `@kri/create-next-app`.
- Keep the generated Next.js routing, server/client boundary, authentication, environment, state, query, and application-shell conventions unless an approved task changes them.
- Prefer shadcn and approved KRI UI Registry components over new local primitives when a suitable component exists.
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
- Consume shared frontend behavior from `@kri/common` and the KRI UI Registry instead of copying provider implementations into this repository.
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
- Run `npm run typecheck` and `npm run build` after relevant source or configuration changes.
## Survey Dashboard Data Schema (source: `public/tmp-doc/테이블 스키마.xlsx`)
Use these backend table/column names as the source of truth for frontend type, variable, and component naming (e.g. TanStack Query keys, DTO-free response types, prop names) so terminology stays consistent between frontend and backend.
- `t_wave` (분기/회차): `wave_cd`(PK, 예: `2601` = 2026년 1분기), `year`, `wave`, `label`(예: "1분기 재생에너지"), `is_open`.
- `wave_cd` 인코딩: 연도 뒤 2자리 + 분기 2자리(zero-padded), 예: 2026년 1분기 → `2601`.
- `t_wave_info` (조사 개요 항목, "조사 목적" 등): `wave_info_idx`(PK), `wave_cd`(FK), `wave_info_order`, `wave_info_title`, `wave_info_content`.
- `t_survey` (조사 대상군: 일반국민/전문가): `wave_cd`+`survey_cd`(PK), `survey_order`, `survey_title`(예: "일반국민 전화조사"), `survey_alias`(예: "일반국민").
- `t_survey_item` (조사 개요 세부 항목: 조사대상/조사지역/조사방법/조사기간/표본규모/표본오차): `survey_item_idx`(PK), `wave_cd`+`survey_cd`(FK), `survey_item_order`, `survey_item_title`, `survey_item_content`.
- `t_file` (결과보고서/인포그래픽 다운로드): `file_idx`(PK), `wave_cd`(FK), `file_order`, `file_title`, `file_type`(예: "PDF"), `file_name`.
- `t_part` (Ⅰ~Ⅳ 대분류): `wave_cd`+`part_cd`(PK), `part_order`, `part_title`(예: "Ⅰ. 에너지 및 재생에너지 정책").
- `t_part_item` (문항, 예: "1 재생에너지 중심의 에너지 전환 정책 평가"): `wave_cd`+`part_cd`+`part_item_cd`(PK), `part_item_order`, `part_item_title`, `chart_type`(예: "bar"), `part_item_comment`(각주 텍스트).
- `t_part_item_sub` (문항 아래 서브 그룹, 예: 3-1의 "확대 이유"/"감소 이유"): `wave_cd`+`part_cd`+`part_item_cd`+`part_item_sub_cd`(PK), `part_item_sub_title`.
- `t_part_item_base` (응답 모집단 N/보조 문구): `part_item_base_idx`(PK), `wave_cd`+`part_cd`+`part_item_cd`+`survey_cd`+`part_item_sub_cd`(nullable, FK), `base_count`(예: 1640), `base_pre_text`/`base_post_text`(nullable).
- `t_part_item_data` (차트 데이터 값): PK 컬럼명이 `t_part_item_data_idx`로 다른 테이블과 달리 테이블명 접두사가 붙어 있음(스키마 내 유일한 예외 — 연동 코드 작성 시 오탈자로 오인하지 말 것). `wave_cd`+`part_cd`+`part_item_cd`+`survey_cd`+`part_item_sub_cd`(nullable, FK), `part_item_data_order`, `part_item_data_label`(예: "매우 잘하고 있다"), `part_item_data_value`(`decimal(14,10)`, 예: `39.9` — 퍼센트 값으로 추정).
- 계층 구조: `t_wave` → (`t_wave_info` | `t_survey` → `t_survey_item` | `t_file` | `t_part` → `t_part_item` → (`t_part_item_sub`, `t_part_item_base`, `t_part_item_data`)).
- 복합키 패턴: 대부분 상위 테이블의 코드 컬럼(`wave_cd`, `part_cd`, `part_item_cd`, `survey_cd`, `part_item_sub_cd`)을 그대로 이어받는 자연복합키. 별도 대리키(`_idx`)는 `t_wave_info`, `t_survey_item`, `t_file`, `t_part_item_base`, `t_part_item_data`에만 존재.
## Backend API Integration (epolicy-dash-back, `http://localhost:6107`, OpenAPI at `/v3/api-docs`)
백엔드 연동이 완료되어 위 "프론트엔드 명명과의 정합성" 문제는 해소됨 — 영문 slug 라우팅(`survey.data.ts`/`menu.data.ts`)을 전부 제거하고 실제 `waveCd`/`partCd` 기반 동적 라우트와 API 응답 데이터로 완전히 교체했다.
- **라우트**: `/dashboard/[waveCd]` (조사 개요), `/dashboard/[waveCd]/[partCd]` (Part 상세, 하위 문항은 `#item-{partItemCd}` 앵커). 루트 `/`는 `GET /waves`를 서버에서 조회해 접근 가능한 첫 Wave로 리다이렉트한다.
- **헤더 분기탭·좌측 메뉴**는 하드코딩 config가 아니라 `GET /waves`(헤더)와 `GET /waves/{waveCd}`(사이드바, `parts[].items[]`)를 그대로 데이터 소스로 사용한다 (`AppMainLayout.tsx`). 새 분기/Part/문항이 추가돼도 프론트 코드 변경이 필요 없다.
- **BFF 프록시 패턴**: 브라우저 → `src/app/api/waves/[[...slug]]/route.ts`(GET 전용, CUD 없음) → `createServerApi()`(httpOnly 쿠키의 accessToken을 Bearer로 자동 첨부) → 실제 백엔드. `example` 리소스와 동일한 패턴이며, 신규 리소스 추가 시 이 구조를 그대로 복제하면 된다.
- **`userContext`/`ctx` 쿼리파라미터**: Swagger상 로그인/로그아웃/Wave API에 필수 파라미터로 보이지만, 실제로는 서버가 인증 헤더에서 자동으로 채우는 값이다 (curl로 직접 검증함 — 파라미터 없이 호출해도 정상 동작). 프론트에서 절대 수동으로 구성해 보내면 안 된다(클라이언트가 자기 `userRole`을 조작할 수 있게 되는 보안 문제).
- **Wave 접근 정책**: `GET /waves`는 `accessible` 플래그와 함께 모든 Wave를 반환한다 — 헤더 탭은 `accessible=false`면 `disabled` 처리만 하고 숨기지 않는다. Wave/Part 상세 API는 비공개 접근 시 `403 WAVE_ACCESS_DENIED`를 반환하며, `nextApi`의 기본 403 핸들러(로그아웃 리다이렉트)를 쓰면 안 되므로 `skipForbiddenHandler: true`를 지정하고 화면에서 직접 에러 메시지를 표시한다 (`src/lib/api-error-message.ts`).
- **파일 다운로드**: Wave 상세 응답의 `files[].downloadUrl`은 백엔드 서버 origin 기준 상대 경로이며 프론트 앱 origin과 다르다. `NEXT_PUBLIC_FILE_ORIGIN` 환경변수(백엔드와 동일 호스트, `.env.local`/`.env.development`/`.env.production`에 정의)와 결합해서 사용한다 (`src/lib/file-download.ts`). 경로를 직접 조합하지 않는다.
- **차트 라이브러리**: 프로젝트에 없었으므로 KriUiRegistry(`https://ui-registry.kric.com/r/kri-chart.json`)의 echarts 래퍼(`kri-chart`, `KriBarChart` 등)를 shadcn CLI로 설치했다 (`src/components/chart/`). 새 의존성(`echarts`, `echarts-for-react`)이 추가됐다.
- **차트/통계표 데이터 해석**: `resultGroups`가 렌더링 단위. 통계표는 모든 `categories`/`series.values`를 그대로 쓰고, 차트는 `category.chartVisible === true`인 인덱스만 category/series를 함께 필터링해서 사용한다 (`src/lib/chart-utils.ts`의 `toChartData`). `categories[i]`와 각 `series[n].values[i]`는 항상 같은 인덱스로 정렬되어 있다는 전제.
- **에러 응답**: RFC 7807(`application/problem+json`)이며 `errorToResponse`(`@kri/common/http`)가 그대로 BFF 응답에 프록시한다. 프론트는 `detail`보다 `code`(예: `WAVE_ACCESS_DENIED`, `WAVE_NOT_FOUND`, `PART_NOT_FOUND`)로 분기하는 걸 우선한다.
- **로그인 필터 vs 업무 오류 403 구분**: 인증 필터 단계에서 막힌 요청(토큰 없음/무효)은 바디 없는 401/403으로 온다. `WAVE_ACCESS_DENIED` 같은 업무 오류는 RFC7807 `code`가 있는 정상 JSON 응답이다. `code`가 없는 401/403은 세션이 실제로 무효하다는 뜻이므로 `/logout`으로 보내야 한다 (`src/lib/api-error-message.ts`의 `isSessionInvalid`). 반대로 클라이언트가 이미 로그아웃 상태(`useAuth()`의 `auth.user`가 없음)라면 애초에 API를 호출하지 않고 즉시 `/logout`으로 보낸다 (`AppMainLayout.tsx`) — 두 체크는 서로 다른 계층(클라이언트가 아는 상태 vs 서버가 판정한 토큰 유효성)이라 둘 다 필요하다.
### ⚠️ `nextApi`(브라우저 클라이언트) 필수 수정 사항 — 스캐폴딩 버그
`NEXT_PUBLIC_API_BASE=/api`(상대 경로)를 `createHttpClient`에 그대로 넘기면 **브라우저의 모든 API 호출이 예외 없이 즉시 실패**한다. `@kri/common`의 `createBaseUrl`이 내부적으로 `new URL(baseUrl)`을 base 인자 없이 호출하는데(`node_modules/@kri/common/dist/http/http-client.js`), 상대 경로만 단독으로 넘기면 브라우저 `URL` 생성자가 `document.baseURI`로 자동 보정해주지 않고 `TypeError: Failed to construct 'URL': Invalid URL`을 던진다. 원래 스캐폴딩(`@kri/create-next-app`)은 이 버그를 가진 채로 생성되며, `example` CRUD가 실사용된 적이 없어 지금까지 드러나지 않았었다.
`src/lib/http-client.ts`에서 브라우저에서는 `window.location.origin`과 결합해 절대 URL로 변환한 뒤 `createHttpClient`에 넘기도록 고쳐뒀다 — 이 파일을 재생성하거나 유사 패턴(`nextApi` 스타일 클라이언트)을 다른 프로젝트에 복제할 때 이 처리를 빠뜨리지 말 것.

3
.env Normal file
View File

@@ -0,0 +1,3 @@
NEXT_PUBLIC_API_BASE=/api
NEXT_PUBLIC_STORE_KEY=epolicy-dash-store-key-2026-kri!
NEXT_PUBLIC_STORE_IV=epolicy-dash-iv1

4
.env.development Normal file
View File

@@ -0,0 +1,4 @@
NEXT_PUBLIC_ENV=development
ENV=development
API_SERVER=http://127.0.0.1:6107/api/v1
NEXT_PUBLIC_FILE_ORIGIN=http://127.0.0.1:6107

4
.env.local Normal file
View File

@@ -0,0 +1,4 @@
NEXT_PUBLIC_ENV=local
ENV=local
API_SERVER=http://localhost:6107/api/v1
NEXT_PUBLIC_FILE_ORIGIN=http://localhost:6107

4
.env.production Normal file
View File

@@ -0,0 +1,4 @@
NEXT_PUBLIC_ENV=production
ENV=production
API_SERVER=http://127.0.0.1:6107/api/v1
NEXT_PUBLIC_FILE_ORIGIN=http://127.0.0.1:6107

4
.gitattributes vendored Normal file
View File

@@ -0,0 +1,4 @@
/AGENTS.md text eol=lf
/CLAUDE.md text eol=lf
/.agent/*.md text eol=lf
/.agent/*.yml text eol=lf

20
.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
/node_modules
/.next
/out
/build
/coverage
/.pnp
.pnp.*
.vercel
.DS_Store
*.pem
*.tsbuildinfo
next-env.d.ts
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
.idea/
*.iml
.claude/
docs/

3
.npmrc Normal file
View File

@@ -0,0 +1,3 @@
registry=https://registry.npmjs.org/
@kri:registry=https://gitea.kric.com/api/packages/KRi/npm/
//gitea.kric.com/api/packages/KRi/npm/:_authToken=${GITEA_NPM_TOKEN}

334
AGENTS.md Normal file
View File

@@ -0,0 +1,334 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: epolicy-dash-front
Schema version: 1
Edit the source fragments or repository .agent files, then recompose.
-->
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
- Include intended validation in the discussion-phase plan.
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
- Limit formatting to files within the approved scope.
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
- Do not claim that a check passed unless it was executed successfully.
- If a check cannot be run, state the exact reason.
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
- Do not fix unrelated failures without expanding the approved scope.
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
## Artifacts and Session Records
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
- Store durable information in the repository's existing documentation structure.
- Do not place generated reports or temporary analysis files in the repository root.
- Remove task-specific temporary files created by the current task after validation when removal is safe.
## Completion Report
When implementation is complete, report in Korean:
- what changed and why;
- the main affected files or components;
- validation commands actually executed and their results;
- checks not executed and the reason;
- remaining risks, assumptions, or follow-up work;
- database, deployment, dependency, encoding, and compatibility impact when applicable.
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
- Keep the report concise and do not include a full session transcript.
## Requested Project Rules
- Treat the approved requirements, acceptance criteria, and recorded decisions as the primary scope boundary.
- Do not infer a requirement solely from a file name, folder date, or apparently newer document.
- When requirements conflict, report the exact sources and request a decision.
- Preserve original customer, partner, and planning documents as read-only evidence unless document editing is explicitly approved.
- Summarize durable implementation requirements inside the repository rather than relying only on files outside the repository.
- Do not expand the deliverable with speculative features, infrastructure, or architectural changes.
- Record material assumptions and unresolved decisions in the project-specific rules or existing project documentation.
- Define observable acceptance criteria before implementation.
- Treat separately managed Frontend and Backend repositories as independent deliverables with a coordinated contract.
- Protect customer, partner, survey, and field data as sensitive information.
- Keep handoff, operation, configuration, and validation instructions usable by the requesting team.
- Report deviations from the requested scope and obtain approval before proceeding.
## TypeScript
- Treat the repository's current TypeScript version, `tsconfig` files, module system, path aliases, and package manager as authoritative.
- Preserve or strengthen existing strictness. Do not weaken compiler options or hide errors with broad `any`, `@ts-ignore`, or unsafe assertions.
- Prefer narrow domain types, discriminated unions, and explicit boundary types over duplicated or overly generic shapes.
- Validate untrusted runtime input even when a compile-time type exists.
- Keep imports, exports, aliases, and generated-code boundaries consistent with the repository.
- Do not introduce a JavaScript-to-TypeScript conversion outside the approved scope.
- Run the repository's focused type-check, lint, test, and build commands as applicable.
## React
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
- Treat any planned Next.js migration as a separate policy and task; the current React application remains authoritative until that migration slice is approved.
## Next.js
- Treat the repository's current Next.js and React versions, routing model, rendering model, and package manager as authoritative.
- Preserve server and client component boundaries. Add `use client` only when browser APIs, state, effects, or client-only libraries require it.
- Keep secrets, privileged data access, and server-only modules out of client bundles.
- Preserve established route, layout, middleware, authentication, authorization, caching, revalidation, and error-handling conventions.
- Validate request parameters, payloads, headers, cookies, and external responses at runtime.
- Do not create new frontend TypeScript type or interface names ending in `Dto` or `DTO`. Use domain- or purpose-specific names such as `User`, `UserInput`, `UserRequest`, or `UserResponse`; do not rename existing types solely to enforce this rule outside the approved scope.
- Use the approved KRI frontend and UI contracts when the project profile includes them; do not copy shared implementations into an application.
- Avoid incidental routing-model or rendering-strategy migrations.
- Run the repository's focused lint, type-check, test, and production build commands as applicable.
## KriFrontCommon Consumer Contract
### Package Usage
- Consume this contract through the published `@kri/common` package and only through entry points declared in its `package.json` `exports` map.
- Use the package root for runtime-neutral object, URL, date, string, and shared type utilities.
- Use a focused subpath such as `@kri/common/http`, `@kri/common/browser`, `@kri/common/server`, `@kri/common/security`, `@kri/common/hooks`, `@kri/common/query`, `@kri/common/config`, `@kri/common/jotai`, or `@kri/common/noti-hub` for the corresponding capability.
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
- Do not copy or fork a shared utility locally merely to avoid using an available public entry point. Propose a backward-compatible library addition when the shared contract is genuinely missing.
### Runtime and Optional Integrations
- Keep browser, server, and runtime-neutral imports on their intended side of the application boundary.
- A consumer that uses React hooks, TanStack Query, or Jotai integrations must provide the compatible optional peer dependency required by its selected entry point.
- Preserve the project's established HTTP client, authentication, error-policy, query-client, storage, and environment conventions when adopting a shared helper.
- Validate external data at runtime; a shared TypeScript type alone does not validate an API response or persisted value.
- Prefer named public exports and retain the consumer project's current module system and bundler conventions.
### Change Safety
- Pin or constrain the package version according to the consumer repository's dependency policy and commit its lockfile changes.
- Review release notes and the actual affected API before upgrading. Run the consumer's focused type-check, test, and build commands after an upgrade.
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
## KriUiRegistry Consumer Contract
### UI Component Selection
When implementing or changing frontend UI, use this order:
1. Reuse an existing shared component in the project when it already meets the requirement.
2. Prefer an approved component from KriUiRegistry.
3. Otherwise, prefer a suitable shadcn/ui component.
4. Create a new custom component only when the preceding options cannot meet the requirement without an unsafe or misleading adaptation.
### Installation and Ownership
- Inspect the registry item and its dependencies before installation. Use the shadcn CLI with the approved registry endpoint under `https://ui-registry.kric.com/r/` instead of copying files from `dist/r` manually.
- `kri-data-table` uses the TanStack Table v8 API. Keep `@tanstack/react-table` within the supported `^8.21.3` range and do not upgrade it to v9 until KriUiRegistry provides an explicitly migrated component contract.
- Respect the consumer project's component aliases, target paths, package manager, styling system, React version, and existing design tokens.
- The shadcn workflow copies component source into the consumer repository. After installation, treat that copy as project-owned code; do not assume registry updates propagate automatically.
- Do not overwrite an existing project component without reviewing the diff and confirming that local behavior and accessibility are preserved.
- Keep package and lockfile changes produced by an installation within the approved scope.
### Adaptation and Verification
- Adapt business data and application behavior outside the shared component when possible. Avoid embedding project-specific API, route, authentication, or environment logic into a reusable component.
- Preserve the installed component's public props, accessibility, keyboard behavior, responsive layout, and loading, empty, error, and disabled states unless the task explicitly changes them.
- If the registry lacks a generally reusable capability, propose it in KriUiRegistry; do not modify that repository unless it is explicitly in scope.
- Run the consumer repository's focused type-check, lint, tests, and build after installation or upgrade.
## Generated Next.js Repository Rules
- This frontend application was generated by `@kri/create-next-app`.
- Keep the generated Next.js routing, server/client boundary, authentication, environment, state, query, and application-shell conventions unless an approved task changes them.
- Prefer shadcn and approved KRI UI Registry components over new local primitives when a suitable component exists.
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
- Consume shared frontend behavior from `@kri/common` and the KRI UI Registry instead of copying provider implementations into this repository.
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
- Run `npm run typecheck` and `npm run build` after relevant source or configuration changes.
## Survey Dashboard Data Schema (source: `public/tmp-doc/테이블 스키마.xlsx`)
Use these backend table/column names as the source of truth for frontend type, variable, and component naming (e.g. TanStack Query keys, DTO-free response types, prop names) so terminology stays consistent between frontend and backend.
- `t_wave` (분기/회차): `wave_cd`(PK, 예: `2601` = 2026년 1분기), `year`, `wave`, `label`(예: "1분기 재생에너지"), `is_open`.
- `wave_cd` 인코딩: 연도 뒤 2자리 + 분기 2자리(zero-padded), 예: 2026년 1분기 → `2601`.
- `t_wave_info` (조사 개요 항목, "조사 목적" 등): `wave_info_idx`(PK), `wave_cd`(FK), `wave_info_order`, `wave_info_title`, `wave_info_content`.
- `t_survey` (조사 대상군: 일반국민/전문가): `wave_cd`+`survey_cd`(PK), `survey_order`, `survey_title`(예: "일반국민 전화조사"), `survey_alias`(예: "일반국민").
- `t_survey_item` (조사 개요 세부 항목: 조사대상/조사지역/조사방법/조사기간/표본규모/표본오차): `survey_item_idx`(PK), `wave_cd`+`survey_cd`(FK), `survey_item_order`, `survey_item_title`, `survey_item_content`.
- `t_file` (결과보고서/인포그래픽 다운로드): `file_idx`(PK), `wave_cd`(FK), `file_order`, `file_title`, `file_type`(예: "PDF"), `file_name`.
- `t_part` (Ⅰ~Ⅳ 대분류): `wave_cd`+`part_cd`(PK), `part_order`, `part_title`(예: "Ⅰ. 에너지 및 재생에너지 정책").
- `t_part_item` (문항, 예: "1 재생에너지 중심의 에너지 전환 정책 평가"): `wave_cd`+`part_cd`+`part_item_cd`(PK), `part_item_order`, `part_item_title`, `chart_type`(예: "bar"), `part_item_comment`(각주 텍스트).
- `t_part_item_sub` (문항 아래 서브 그룹, 예: 3-1의 "확대 이유"/"감소 이유"): `wave_cd`+`part_cd`+`part_item_cd`+`part_item_sub_cd`(PK), `part_item_sub_title`.
- `t_part_item_base` (응답 모집단 N/보조 문구): `part_item_base_idx`(PK), `wave_cd`+`part_cd`+`part_item_cd`+`survey_cd`+`part_item_sub_cd`(nullable, FK), `base_count`(예: 1640), `base_pre_text`/`base_post_text`(nullable).
- `t_part_item_data` (차트 데이터 값): PK 컬럼명이 `t_part_item_data_idx`로 다른 테이블과 달리 테이블명 접두사가 붙어 있음(스키마 내 유일한 예외 — 연동 코드 작성 시 오탈자로 오인하지 말 것). `wave_cd`+`part_cd`+`part_item_cd`+`survey_cd`+`part_item_sub_cd`(nullable, FK), `part_item_data_order`, `part_item_data_label`(예: "매우 잘하고 있다"), `part_item_data_value`(`decimal(14,10)`, 예: `39.9` — 퍼센트 값으로 추정).
- 계층 구조: `t_wave` → (`t_wave_info` | `t_survey` → `t_survey_item` | `t_file` | `t_part` → `t_part_item` → (`t_part_item_sub`, `t_part_item_base`, `t_part_item_data`)).
- 복합키 패턴: 대부분 상위 테이블의 코드 컬럼(`wave_cd`, `part_cd`, `part_item_cd`, `survey_cd`, `part_item_sub_cd`)을 그대로 이어받는 자연복합키. 별도 대리키(`_idx`)는 `t_wave_info`, `t_survey_item`, `t_file`, `t_part_item_base`, `t_part_item_data`에만 존재.
## Backend API Integration (epolicy-dash-back, `http://localhost:6107`, OpenAPI at `/v3/api-docs`)
백엔드 연동이 완료되어 위 "프론트엔드 명명과의 정합성" 문제는 해소됨 — 영문 slug 라우팅(`survey.data.ts`/`menu.data.ts`)을 전부 제거하고 실제 `waveCd`/`partCd` 기반 동적 라우트와 API 응답 데이터로 완전히 교체했다.
- **라우트**: `/dashboard/[waveCd]` (조사 개요), `/dashboard/[waveCd]/[partCd]` (Part 상세, 하위 문항은 `#item-{partItemCd}` 앵커). 루트 `/`는 `GET /waves`를 서버에서 조회해 접근 가능한 첫 Wave로 리다이렉트한다.
- **헤더 분기탭·좌측 메뉴**는 하드코딩 config가 아니라 `GET /waves`(헤더)와 `GET /waves/{waveCd}`(사이드바, `parts[].items[]`)를 그대로 데이터 소스로 사용한다 (`AppMainLayout.tsx`). 새 분기/Part/문항이 추가돼도 프론트 코드 변경이 필요 없다.
- **BFF 프록시 패턴**: 브라우저 → `src/app/api/waves/[[...slug]]/route.ts`(GET 전용, CUD 없음) → `createServerApi()`(httpOnly 쿠키의 accessToken을 Bearer로 자동 첨부) → 실제 백엔드. `example` 리소스와 동일한 패턴이며, 신규 리소스 추가 시 이 구조를 그대로 복제하면 된다.
- **`userContext`/`ctx` 쿼리파라미터**: Swagger상 로그인/로그아웃/Wave API에 필수 파라미터로 보이지만, 실제로는 서버가 인증 헤더에서 자동으로 채우는 값이다 (curl로 직접 검증함 — 파라미터 없이 호출해도 정상 동작). 프론트에서 절대 수동으로 구성해 보내면 안 된다(클라이언트가 자기 `userRole`을 조작할 수 있게 되는 보안 문제).
- **Wave 접근 정책**: `GET /waves`는 `accessible` 플래그와 함께 모든 Wave를 반환한다 — 헤더 탭은 `accessible=false`면 `disabled` 처리만 하고 숨기지 않는다. Wave/Part 상세 API는 비공개 접근 시 `403 WAVE_ACCESS_DENIED`를 반환하며, `nextApi`의 기본 403 핸들러(로그아웃 리다이렉트)를 쓰면 안 되므로 `skipForbiddenHandler: true`를 지정하고 화면에서 직접 에러 메시지를 표시한다 (`src/lib/api-error-message.ts`).
- **파일 다운로드**: Wave 상세 응답의 `files[].downloadUrl`은 백엔드 서버 origin 기준 상대 경로이며 프론트 앱 origin과 다르다. `NEXT_PUBLIC_FILE_ORIGIN` 환경변수(백엔드와 동일 호스트, `.env.local`/`.env.development`/`.env.production`에 정의)와 결합해서 사용한다 (`src/lib/file-download.ts`). 경로를 직접 조합하지 않는다.
- **차트 라이브러리**: 프로젝트에 없었으므로 KriUiRegistry(`https://ui-registry.kric.com/r/kri-chart.json`)의 echarts 래퍼(`kri-chart`, `KriBarChart` 등)를 shadcn CLI로 설치했다 (`src/components/chart/`). 새 의존성(`echarts`, `echarts-for-react`)이 추가됐다.
- **차트/통계표 데이터 해석**: `resultGroups`가 렌더링 단위. 통계표는 모든 `categories`/`series.values`를 그대로 쓰고, 차트는 `category.chartVisible === true`인 인덱스만 category/series를 함께 필터링해서 사용한다 (`src/lib/chart-utils.ts`의 `toChartData`). `categories[i]`와 각 `series[n].values[i]`는 항상 같은 인덱스로 정렬되어 있다는 전제.
- **에러 응답**: RFC 7807(`application/problem+json`)이며 `errorToResponse`(`@kri/common/http`)가 그대로 BFF 응답에 프록시한다. 프론트는 `detail`보다 `code`(예: `WAVE_ACCESS_DENIED`, `WAVE_NOT_FOUND`, `PART_NOT_FOUND`)로 분기하는 걸 우선한다.
- **로그인 필터 vs 업무 오류 403 구분**: 인증 필터 단계에서 막힌 요청(토큰 없음/무효)은 바디 없는 401/403으로 온다. `WAVE_ACCESS_DENIED` 같은 업무 오류는 RFC7807 `code`가 있는 정상 JSON 응답이다. `code`가 없는 401/403은 세션이 실제로 무효하다는 뜻이므로 `/logout`으로 보내야 한다 (`src/lib/api-error-message.ts`의 `isSessionInvalid`). 반대로 클라이언트가 이미 로그아웃 상태(`useAuth()`의 `auth.user`가 없음)라면 애초에 API를 호출하지 않고 즉시 `/logout`으로 보낸다 (`AppMainLayout.tsx`) — 두 체크는 서로 다른 계층(클라이언트가 아는 상태 vs 서버가 판정한 토큰 유효성)이라 둘 다 필요하다.
### ⚠️ `nextApi`(브라우저 클라이언트) 필수 수정 사항 — 스캐폴딩 버그
`NEXT_PUBLIC_API_BASE=/api`(상대 경로)를 `createHttpClient`에 그대로 넘기면 **브라우저의 모든 API 호출이 예외 없이 즉시 실패**한다. `@kri/common`의 `createBaseUrl`이 내부적으로 `new URL(baseUrl)`을 base 인자 없이 호출하는데(`node_modules/@kri/common/dist/http/http-client.js`), 상대 경로만 단독으로 넘기면 브라우저 `URL` 생성자가 `document.baseURI`로 자동 보정해주지 않고 `TypeError: Failed to construct 'URL': Invalid URL`을 던진다. 원래 스캐폴딩(`@kri/create-next-app`)은 이 버그를 가진 채로 생성되며, `example` CRUD가 실사용된 적이 없어 지금까지 드러나지 않았었다.
`src/lib/http-client.ts`에서 브라우저에서는 `window.location.origin`과 결합해 절대 URL로 변환한 뒤 `createHttpClient`에 넘기도록 고쳐뒀다 — 이 파일을 재생성하거나 유사 패턴(`nextApi` 스타일 클라이언트)을 다른 프로젝트에 복제할 때 이 처리를 빠뜨리지 말 것.

1
CLAUDE.md Normal file
View File

@@ -0,0 +1 @@
@AGENTS.md

43
README.md Normal file
View File

@@ -0,0 +1,43 @@
# 한국에너지정보문화재단 대시보드
한국에너지정보문화재단 대시보드 시스템
## 실행
```powershell
npm run dev
```
기본 포트: `6106`
## 환경변수
프로젝트 생성 시 `.env`, `.env.local`, `.env.development`, `.env.production`, `.env.example`이 함께 생성됩니다.
- `.env`: 모든 환경 공통값
- `.env.local`: 개발자 PC 전용값(Git 제외)
- `.env.development`: 개발 빌드값
- `.env.production`: 운영 빌드값
- `.env.example`: 환경변수 작성 예시
`.env.local`은 다른 환경 파일보다 우선 적용되므로 운영 빌드에서는 제거하거나 Jenkins 정책에 맞게 관리합니다.
## 공통 자원
- npm package: `@kri/common`
- UI Registry: `https://ui-registry.kric.com/r`
## 검증
```powershell
npm run typecheck
npm run build
```
## Agent Harness
- 프로젝트 ID: `epolicy-dash-front`
- 프로젝트 유형: `requested-project`
- 권위 원본: `.agent/profile.yml`, `.agent/project.md`
`AGENTS.md`와 `CLAUDE.md`는 중앙 Agent Harness가 합성합니다. 두 파일을 직접 수정하지 않습니다.

22
components.json Normal file
View File

@@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

17
eslint.config.mjs Normal file
View File

@@ -0,0 +1,17 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
export default defineConfig([
...nextVitals,
...nextTs,
globalIgnores([".next/**", "out/**", "build/**", "next-env.d.ts"]),
{
rules: {
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-explicit-any": "warn",
"react-hooks/exhaustive-deps": "off",
"react-hooks/set-state-in-effect": "off"
}
}
]);

6
next.config.ts Normal file
View File

@@ -0,0 +1,6 @@
import type { NextConfig } from "next";
import { createKriNextConfig } from "@kri/common/config";
const nextConfig = createKriNextConfig({}) satisfies NextConfig;
export default nextConfig;

9667
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

62
package.json Normal file
View File

@@ -0,0 +1,62 @@
{
"name": "epolicy-dash-front",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 6106",
"build": "next build",
"start": "next start -p 6106",
"lint": "eslint",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@kri/common": "0.18.1",
"@tanstack/react-query": "latest",
"@tanstack/react-table": "^8.21.3",
"@tiptap/extension-color": "^3.30.0",
"@tiptap/extension-font-family": "^3.13.0",
"@tiptap/extension-highlight": "^3.30.0",
"@tiptap/extension-image": "^3.30.0",
"@tiptap/extension-link": "^3.30.0",
"@tiptap/extension-placeholder": "^3.30.0",
"@tiptap/extension-table": "^3.30.0",
"@tiptap/extension-table-cell": "^3.30.0",
"@tiptap/extension-table-header": "^3.30.0",
"@tiptap/extension-table-row": "^3.30.0",
"@tiptap/extension-text-align": "^3.30.0",
"@tiptap/extension-text-style": "^3.30.0",
"@tiptap/extension-underline": "^3.30.0",
"@tiptap/react": "^3.30.0",
"@tiptap/starter-kit": "^3.30.0",
"class-variance-authority": "latest",
"clsx": "latest",
"cmdk": "^1.1.1",
"date-fns": "^4.4.0",
"dompurify": "^3.4.13",
"echarts": "^6.1.0",
"echarts-for-react": "^3.0.6",
"jotai": "latest",
"lucide-react": "latest",
"next": "latest",
"prettier": "^3.9.6",
"radix-ui": "^1.6.7",
"react": "latest",
"react-day-picker": "^10.0.1",
"react-dom": "latest",
"server-only": "latest",
"sonner": "latest",
"tailwind-merge": "latest"
},
"devDependencies": {
"@tailwindcss/postcss": "latest",
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
"babel-plugin-react-compiler": "latest",
"eslint": "^9",
"eslint-config-next": "latest",
"tailwindcss": "latest",
"tw-animate-css": "latest",
"typescript": "^5"
}
}

7
postcss.config.mjs Normal file
View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {}
}
};
export default config;

BIN
public/epolicy-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

View File

@@ -0,0 +1,120 @@
"use client";
import { useParams, useRouter } from "next/navigation";
import { useEffect } from "react";
import { KriBarChart } from "@/components/chart";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toChartData } from "@/lib/chart-utils";
import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message";
import { usePartDetailQuery } from "@/query/waves";
import type { ResultGroup } from "@/types/wave";
function ResultGroupBlock({ group }: { group: ResultGroup }) {
const chartData = toChartData(group.categories, group.series);
const hasChartData = chartData.categories.length > 0 && chartData.series.length > 0;
return (
<div className="space-y-3">
{group.subItem ? <p className="text-sm font-medium">{group.subItem.title}</p> : null}
{hasChartData ? (
<KriBarChart
categories={chartData.categories}
series={chartData.series.map((item) => ({ name: item.label, data: item.values }))}
height={280}
/>
) : null}
{group.categories.length ? (
<div className="overflow-x-auto rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>구분</TableHead>
{group.categories.map((category) => (
<TableHead key={category.label} className="text-right">
{category.label}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{group.series.map((series) => (
<TableRow key={series.surveyCd}>
<TableCell className="font-medium whitespace-normal">
{series.label}
{series.baseCount !== null ? (
<span className="ml-1 text-xs text-muted-foreground">
({series.baseText ? `${series.baseText} ` : ""}N={series.baseCount})
</span>
) : null}
</TableCell>
{series.values.map((value, index) => (
<TableCell key={group.categories[index]?.label ?? index} className="text-right">
{value}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<p className="text-sm text-muted-foreground">데이터가 없습니다.</p>
)}
</div>
);
}
export default function PartDetailPage() {
const params = useParams<{ waveCd: string; partCd: string }>();
const router = useRouter();
const waveCd = Number(params.waveCd);
const partCd = Number(params.partCd);
const { data, isPending, isError, error } = usePartDetailQuery(waveCd, partCd);
useEffect(() => {
if (isError && isSessionInvalid(error)) router.replace("/logout");
}, [isError, error, router]);
if (isPending) {
return <p className="text-sm text-muted-foreground">불러오는 중입니다...</p>;
}
if (isError) {
if (isSessionInvalid(error)) return null;
return (
<div className="space-y-6">
<AppPageTitle title="문항" />
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<p className="text-sm text-destructive">{resolveApiErrorMessage(error)}</p>
</div>
</div>
);
}
return (
<div className="space-y-6">
<AppPageTitle title={data.title} />
{data.items.map((item) => (
<div key={item.partItemCd} id={`item-${item.partItemCd}`} className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="font-medium">{item.title}</p>
<Badge variant={item.audience.type === "COMMON" ? "secondary" : "outline"}>{item.audience.label}</Badge>
</div>
<div className="mt-4 space-y-6">
{item.resultGroups.map((group, index) => (
<ResultGroupBlock key={group.subItem?.partItemSubCd ?? index} group={group} />
))}
</div>
{item.comment ? <p className="mt-4 text-xs text-muted-foreground">{item.comment}</p> : null}
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,88 @@
"use client";
import { FileDown } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect } from "react";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { Button } from "@/components/ui/button";
import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message";
import { toFileDownloadUrl } from "@/lib/file-download";
import { useWaveDetailQuery } from "@/query/waves";
export default function WaveOverviewPage() {
const params = useParams<{ waveCd: string }>();
const router = useRouter();
const waveCd = Number(params.waveCd);
const { data, isPending, isError, error } = useWaveDetailQuery(waveCd);
useEffect(() => {
if (isError && isSessionInvalid(error)) router.replace("/logout");
}, [isError, error, router]);
if (isPending) {
return <p className="text-sm text-muted-foreground">불러오는 중입니다...</p>;
}
if (isError) {
if (isSessionInvalid(error)) return null;
return (
<div className="space-y-6">
<AppPageTitle title="조사 개요" />
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<p className="text-sm text-destructive">{resolveApiErrorMessage(error)}</p>
</div>
</div>
);
}
return (
<div className="space-y-6">
<AppPageTitle title="조사 개요" />
{data.overview.length ? (
<div className="space-y-4 rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
{data.overview.map((item) => (
<div key={item.title}>
<p className="font-medium">{item.title}</p>
<p className="mt-1 text-sm whitespace-pre-line text-muted-foreground">{item.content}</p>
</div>
))}
</div>
) : null}
{data.surveys.length ? (
<div className="grid gap-4 md:grid-cols-2">
{data.surveys.map((survey) => (
<div
key={survey.surveyCd}
className="rounded-lg border-2 border-brand-blue/30 bg-card p-6 text-card-foreground shadow-sm"
>
<p className="font-semibold text-brand-blue-dark">{survey.title}</p>
<dl className="mt-3 space-y-2">
{survey.items.map((item) => (
<div key={item.title} className="flex gap-3 text-sm">
<dt className="w-20 shrink-0 text-muted-foreground">{item.title}</dt>
<dd className="min-w-0 flex-1">{item.content}</dd>
</div>
))}
</dl>
</div>
))}
</div>
) : null}
{data.files.length ? (
<div className="flex flex-wrap gap-2">
{data.files.map((file) => (
<Button key={file.fileIdx} variant="outline" asChild>
<a href={toFileDownloadUrl(file.downloadUrl)} target="_blank" rel="noreferrer">
<FileDown className="size-4" />
{file.title} ({file.type})
</a>
</Button>
))}
</div>
) : null}
</div>
);
}

View File

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

View File

@@ -0,0 +1,24 @@
import { redirect } from "next/navigation";
import { createServerApi } from "@/lib/http-server";
import type { WaveSummaryResponse } from "@/types/wave";
export default async function MainPage() {
const serverApi = await createServerApi();
let waves: WaveSummaryResponse[];
try {
waves = await serverApi.get<WaveSummaryResponse[]>("/waves");
} catch {
redirect("/logout");
}
const target = waves.find((wave) => wave.isOpen);
if (!target) {
return (
<div className="space-y-6">
<p className="text-sm text-muted-foreground">표시할 조사 회차가 없습니다.</p>
</div>
);
}
redirect(`/dashboard/${target.waveCd}`);
}

View File

@@ -0,0 +1,81 @@
"use client";
import Image from "next/image";
import type React from "react";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { apiError, NONE_HTTP_ERROR } from "@kri/common/http";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useLoginMutation } from "@/query/auth";
export default function LoginPage() {
const router = useRouter();
const loginMutation = useLoginMutation();
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const [userId, setUserId] = useState("");
const [userPw, setUserPw] = useState("");
const [error, setError] = useState<string | null>(null);
const tryLogin = async () => {
if (!userId.trim()) return window.alert("아이디를 입력해 주세요.");
if (!userPw) return window.alert("비밀번호를 입력해 주세요.");
setError(null);
try {
await loginMutation.mutateAsync({ userId: userId.trim(), userPw });
} catch (cause: unknown) {
const errorInfo = apiError(cause, { fallbackMessage: "로그인에 실패했습니다." });
if (errorInfo.status === 401 || errorInfo.status === 403) setError("아이디 또는 비밀번호를 다시 확인해 주세요.");
else if (errorInfo.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
else setError(`로그인에 실패했습니다. (${errorInfo.message})`);
}
};
useEffect(() => {
if (loginMutation.isSuccess) router.replace("/");
}, [loginMutation.isSuccess, router]);
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
if (event.key === "Enter") {
event.preventDefault();
passwordInputRef.current?.focus();
}
};
const handlePasswordKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
if (event.key === "Enter") {
event.preventDefault();
void tryLogin();
}
};
return (
<main className="flex min-h-screen items-center justify-center bg-gradient-to-br from-slate-50 via-sky-50 to-blue-50 p-4">
<Card className="w-full max-w-md rounded-2xl border-0 py-8 shadow-2xl">
<CardHeader className="pb-6">
<div className="flex justify-center">
<Image src="/epolicy-logo.png" alt="한국에너지정보문화재단" width={280} height={34} className="h-9 w-auto object-contain" priority />
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<label htmlFor="userId" className="text-sm font-medium">ID</label>
<Input id="userId" autoComplete="username" placeholder="아이디를 입력하세요" value={userId} onChange={(event) => setUserId(event.currentTarget.value)} onKeyDown={handleIdKeyDown} />
</div>
<div className="space-y-2">
<label htmlFor="userPw" className="text-sm font-medium">Password</label>
<Input ref={passwordInputRef} id="userPw" type="password" autoComplete="current-password" placeholder="비밀번호를 입력하세요" value={userPw} onChange={(event) => setUserPw(event.currentTarget.value)} onKeyDown={handlePasswordKeyDown} />
</div>
{error ? <p className="text-sm text-destructive">{error}</p> : null}
<Button className="mt-6 h-11 w-full" disabled={loginMutation.isPending} onClick={() => void tryLogin()}>
{loginMutation.isPending ? "로그인 중..." : "로그인"}
</Button>
</div>
</CardContent>
</Card>
</main>
);
}

View File

@@ -0,0 +1,20 @@
"use client";
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { useLogoutMutation } from "@/query/auth";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
export default function LogoutPage() {
const router = useRouter();
const logoutMutation = useLogoutMutation();
const started = useRef(false);
useEffect(() => {
if (started.current) return;
started.current = true;
void logoutMutation.mutateAsync().finally(() => router.replace("/login"));
}, [logoutMutation, router]);
return <LoadingOverlayAdapter force label="로그아웃 중" />;
}

View File

@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApi } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/example${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result);
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createServerApi();
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
return toResponse(await serverApi.postForm<unknown>(apiPath(slug), await request.formData()));
}
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.post<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PUT(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
return toResponse(await serverApi.putForm<unknown>(apiPath(slug), await request.formData()));
}
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.put<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PATCH(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.patch<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function DELETE(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.del<unknown>(apiPath(slug), body === undefined ? undefined : { json: body }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
// createHttpClient의 FormData 전용 메서드는 postForm과 putForm입니다.
// PATCH/DELETE multipart가 필요하면 공용 HTTP Client 정책을 확인한 뒤 별도 구현하세요.

View File

@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from "next/server";
import type { LoginRequest, LoginUser } from "@kri/common";
import { errorToResponse } from "@kri/common/http";
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
import { serverEnv } from "@/lib/env.server";
import { createServerApi } from "@/lib/http-server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
import type { RouteContext } from "@/types/common";
type LoginResponse = { accessToken: string; user: LoginUser };
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const body = (await request.json()) as LoginRequest;
const suffix = slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : "";
const result = await serverApi.post<LoginResponse>(`/auth/login${suffix}`, body);
const response = NextResponse.json(result.user, { status: 200 });
response.cookies.set(CookieKeys.AuthToken, result.accessToken, {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: AUTH_COOKIE_MAX_AGE,
});
return response;
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { serverEnv } from "@/lib/env.server";
import { createServerApi } from "@/lib/http-server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
import type { RouteContext } from "@/types/common";
export async function POST(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const suffix = slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : "";
await serverApi.post<boolean>(`/auth/logout${suffix}`);
const response = NextResponse.json({ ok: true });
response.cookies.set(CookieKeys.AuthToken, "", {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return response;
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApi } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/waves${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createServerApi();
return NextResponse.json(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}

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

@@ -0,0 +1,103 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--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);
--color-brand-blue: var(--brand-blue);
--color-brand-blue-dark: var(--brand-blue-dark);
--color-brand-green: var(--brand-green);
--color-brand-green-dark: var(--brand-green-dark);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
/* KEIA brand palette */
--brand-blue: #00b2db;
--brand-blue-dark: #047884;
--brand-green: #3bad62;
--brand-green-dark: #338949;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: var(--brand-blue);
--primary-foreground: oklch(1 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.96 0.02 205);
--accent-foreground: var(--brand-blue-dark);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: var(--brand-blue);
}
.dark {
--brand-blue: #00b2db;
--brand-blue-dark: #047884;
--brand-green: #3bad62;
--brand-green-dark: #338949;
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: var(--brand-blue);
--primary-foreground: oklch(0.145 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.32 0.04 205);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: var(--brand-blue);
}
@layer base {
* { @apply border-border outline-ring/50; }
body { @apply bg-background text-foreground; }
}
.ProseMirror img { cursor: pointer; }
.ProseMirror .ProseMirror-selectednode img { outline: 5px solid #0ea5e9; outline-offset: -5px; }
.ProseMirror [data-resize-container] { position: relative; display: inline-block; }
.ProseMirror [data-resize-handle] { position: absolute; width: 10px; height: 10px; box-sizing: border-box; background: #fff; border: 1px solid #0ea5e9; z-index: 10; opacity: 0; pointer-events: none; transition: opacity .12s ease-out; }
.ProseMirror [data-resize-container]:hover [data-resize-handle] { opacity: 1; pointer-events: auto; }
.ProseMirror [data-resize-handle="bottom-right"] { right: -5px; bottom: -5px; cursor: se-resize !important; }
.ProseMirror [data-resize-handle="bottom-left"] { left: -5px; bottom: -5px; cursor: sw-resize !important; }
.ProseMirror [data-resize-handle="top-right"] { right: -5px; top: -5px; cursor: ne-resize !important; }
.ProseMirror [data-resize-handle="top-left"] { left: -5px; top: -5px; cursor: nw-resize !important; }

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

@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { Toaster } from "sonner";
import { AppProvider } from "@/components/providers/AppProvider";
import "./globals.css";
export const metadata: Metadata = {
title: "2026년 에너지 국민인식조사 대시보드",
description: "한국에너지정보문화재단 2026년 에너지 국민인식조사 대시보드",
icons: { icon: "/favicon.ico" }
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="ko">
<body className="min-h-screen antialiased">
<AppProvider>{children}</AppProvider>
<Toaster />
</body>
</html>
);
}

11
src/app/not-found.tsx Normal file
View File

@@ -0,0 +1,11 @@
import Link from "next/link";
export default function NotFound() {
return (
<main className="flex min-h-screen flex-col items-center justify-center gap-4 p-6 text-center">
<p className="text-sm text-muted-foreground">404</p>
<h1 className="text-2xl font-bold">페이지를 찾을 수 없습니다.</h1>
<Link href="/" className="text-sm underline underline-offset-4">홈으로 이동</Link>
</main>
);
}

View File

@@ -0,0 +1,58 @@
"use client";
import Image from "next/image";
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { KriHeader } from "@/components/layout/KriHeader";
import type { KriNavigationItem } from "@/components/layout/types";
import type { LoginUser } from "@kri/common";
interface AppHeaderProps {
menuOpen: boolean;
showMenuButton: boolean;
activeMenuId?: string;
topMenus: KriNavigationItem[];
user?: LoginUser | null;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
}
export function AppHeader({ menuOpen, showMenuButton, activeMenuId, topMenus, user, onToggleMenu, onNavigate }: AppHeaderProps) {
return (
<KriHeader
logo={
<div className="flex flex-col items-start gap-1.5">
<Image
src="/epolicy-logo.png"
alt="한국에너지정보문화재단"
width={280}
height={34}
className="h-6 w-auto object-contain brightness-0 invert"
priority
/>
<span className="text-lg font-bold tracking-tight text-white">2026년 에너지 국민인식조사</span>
</div>
}
menus={topMenus}
activeMenuId={activeMenuId}
menuOpen={menuOpen}
showMenuButton={showMenuButton}
onToggleMenu={onToggleMenu}
onNavigate={onNavigate}
right={
<>
<span className="hidden text-sm text-white/80 sm:inline">{user?.userName ?? ""}</span>
<Button
variant="ghost"
size="sm"
className="gap-2 text-white hover:bg-white/10 hover:text-white"
onClick={() => onNavigate("/logout")}
>
<LogOut className="size-4" />
<span className="hidden sm:inline">로그아웃</span>
</Button>
</>
}
/>
);
}

View File

@@ -0,0 +1,125 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { usePathname, useParams, useRouter } from "next/navigation";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import type { KriNavigationItem } from "@/components/layout/types";
import { AppHeader } from "./AppHeader";
import { AppSidebar } from "./AppSidebar";
import { useAuth } from "@/hooks/useAuth";
import { useWaveDetailQuery, useWavesQuery } from "@/query/waves";
function scrollToHash(hash: string) {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
document.getElementById(hash)?.scrollIntoView({ behavior: "smooth", block: "start" });
});
});
}
function toNumberOrUndefined(value: string | string[] | undefined): number | undefined {
if (typeof value !== "string") return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
export function AppMainLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const params = useParams<{ waveCd?: string; partCd?: string }>();
const { auth } = useAuth();
const [menuOpen, setMenuOpen] = useState(true);
const pendingHashRef = useRef<string | null>(null);
const isAuthenticated = Boolean(auth.user);
const waveCd = toNumberOrUndefined(params?.waveCd);
const { data: waves } = useWavesQuery(isAuthenticated);
const { data: waveDetail, isError: waveDetailError } = useWaveDetailQuery(waveCd, isAuthenticated);
useEffect(() => {
if (!isAuthenticated) router.replace("/logout");
}, [isAuthenticated, router]);
const topMenus = useMemo<KriNavigationItem[]>(
() =>
(waves ?? [])
.slice()
.sort((a, b) => a.waveCd - b.waveCd)
.map((wave) => ({
id: String(wave.waveCd),
label: wave.label,
path: `/dashboard/${wave.waveCd}`,
disabled: !wave.accessible,
match: (path: string) => path === `/dashboard/${wave.waveCd}` || path.startsWith(`/dashboard/${wave.waveCd}/`),
})),
[waves],
);
const sideMenus = useMemo<KriNavigationItem[]>(() => {
if (!waveCd || waveDetailError || !waveDetail) return [];
return [
{ id: "overview", label: "조사 개요", path: `/dashboard/${waveCd}` },
...waveDetail.parts.map((part) => ({
id: String(part.partCd),
label: part.title,
path: `/dashboard/${waveCd}/${part.partCd}`,
children: part.items.map((item) => ({
id: `${part.partCd}-${item.partItemCd}`,
label: item.title,
path: `/dashboard/${waveCd}/${part.partCd}#item-${item.partItemCd}`,
})),
})),
];
}, [waveCd, waveDetail, waveDetailError]);
const activeMenuId = useMemo(() => topMenus.find((item) => item.match?.(pathname))?.id, [topMenus, pathname]);
const navigate = (path: string) => {
const hashIndex = path.indexOf("#");
if (hashIndex === -1) {
router.push(path);
return;
}
const targetPath = path.slice(0, hashIndex) || "/";
const hash = path.slice(hashIndex + 1);
if (targetPath === pathname) {
scrollToHash(hash);
return;
}
pendingHashRef.current = hash;
router.push(path);
};
useEffect(() => {
if (!pendingHashRef.current) return;
const hash = pendingHashRef.current;
pendingHashRef.current = null;
scrollToHash(hash);
}, [pathname]);
const hasSidebar = sideMenus.length > 0;
return (
<KriMainLayout
sidebarOpen={hasSidebar && menuOpen}
onSidebarOpenChange={setMenuOpen}
header={
<AppHeader
menuOpen={menuOpen}
showMenuButton={hasSidebar}
activeMenuId={activeMenuId}
topMenus={topMenus}
user={auth.user}
onToggleMenu={() => setMenuOpen((current) => !current)}
onNavigate={navigate}
/>
}
sidebar={hasSidebar ? <AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} onNavigate={navigate} /> : undefined}
>
{children}
</KriMainLayout>
);
}

View File

@@ -0,0 +1,10 @@
import { KriPageTitle } from "@/components/layout/KriPageTitle";
export interface AppPageTitleProps {
title: string;
description?: string;
}
export function AppPageTitle({ title, description }: AppPageTitleProps) {
return <KriPageTitle title={title} description={description} />;
}

View File

@@ -0,0 +1,15 @@
"use client";
import { KriSidebar } from "@/components/layout/KriSidebar";
import type { KriNavigationItem } from "@/components/layout/types";
interface AppSidebarProps {
items: KriNavigationItem[];
isOpen: boolean;
pathname: string;
onNavigate: (path: string) => void;
}
export function AppSidebar({ items, isOpen, pathname, onNavigate }: AppSidebarProps) {
return <KriSidebar items={items} isOpen={isOpen} pathname={pathname} onNavigate={onNavigate} />;
}

View File

@@ -0,0 +1,12 @@
"use client";
import { useAtomValue } from "jotai";
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
import { loadingAtom } from "@/store/jotai/loading";
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & { force?: boolean };
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
const open = useAtomValue(loadingAtom);
return <KriLoadingOverlay open={force || open} {...props} />;
}

View File

@@ -0,0 +1,5 @@
export { AppHeader } from "./AppHeader";
export { AppMainLayout } from "./AppMainLayout";
export { AppPageTitle } from "./AppPageTitle";
export { AppSidebar } from "./AppSidebar";
export { LoadingOverlayAdapter } from "./LoadingOverlayAdapter";

View File

@@ -0,0 +1,147 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import type { ComponentType, CSSProperties } from 'react'
import type { EChartsOption } from 'echarts'
import { CHART_HEIGHTS } from './chart.config'
import { useResizeKey } from './useResizeKey'
type EChartsSeries = NonNullable<EChartsOption['series']>
type ReactEChartsProps = {
option: EChartsOption
className?: string
style?: CSSProperties
notMerge?: boolean
lazyUpdate?: boolean
onEvents?: Record<string, (params: unknown) => void>
}
export type BaseEChartProps = {
option: EChartsOption
height?: number | string
className?: string
contentClassName?: string
chartClassName?: string
style?: CSSProperties
contentStyle?: CSSProperties
chartStyle?: CSSProperties
notMerge?: boolean
lazyUpdate?: boolean
onEvents?: Record<string, (params: unknown) => void>
resizeDebounceMs?: number
normalizeValues?: boolean
decimalPlaces?: number
}
const roundNumber = (value: number, decimalPlaces: number) => {
const factor = 10 ** decimalPlaces
return Math.round((value + Number.EPSILON) * factor) / factor
}
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
if (typeof value === 'number') {
return roundNumber(value, decimalPlaces)
}
if (Array.isArray(value)) {
return value.map((item) => normalizeDataValue(item, decimalPlaces))
}
if (value && typeof value === 'object' && 'value' in value) {
const dataItem = value as Record<string, unknown>
return {
...dataItem,
value: normalizeDataValue(dataItem.value, decimalPlaces),
}
}
return value
}
const normalizeSeries = (
series: EChartsOption['series'] | undefined,
decimalPlaces: number,
): EChartsOption['series'] => {
if (!series) return series
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
const candidate = seriesOption as Record<string, unknown>
const data = candidate.data
if (!Array.isArray(data)) {
return seriesOption
}
return {
...candidate,
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
} as EChartsSeries
}
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
}
export function BaseEChart({
option,
height = CHART_HEIGHTS.DEFAULT,
className,
contentClassName,
chartClassName,
style,
contentStyle,
chartStyle,
notMerge = true,
lazyUpdate = false,
onEvents,
resizeDebounceMs = 150,
normalizeValues = true,
decimalPlaces = 2,
}: BaseEChartProps) {
const resizeKey = useResizeKey(resizeDebounceMs)
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
useEffect(() => {
let cancelled = false
void import('echarts-for-react').then((module) => {
if (!cancelled) {
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
}
})
return () => {
cancelled = true
}
}, [])
const normalizedOption = useMemo<EChartsOption>(() => {
if (!normalizeValues) return option
return {
...option,
series: normalizeSeries(option.series, decimalPlaces),
}
}, [decimalPlaces, normalizeValues, option])
return (
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
{ReactECharts ? (
<ReactECharts
key={resizeKey}
option={normalizedOption}
className={chartClassName}
style={{ width: '100%', height: '100%', ...chartStyle }}
notMerge={notMerge}
lazyUpdate={lazyUpdate}
onEvents={onEvents}
/>
) : null}
</div>
</div>
)
}
export default BaseEChart

View File

@@ -0,0 +1,59 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriCartesianChartProps } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriBarChartProps = KriCartesianChartProps & {
isHorizontal?: boolean
barWidth?: number | string
barMaxWidth?: number | string
}
export function KriBarChart({
categories,
series,
isHorizontal = false,
barWidth,
barMaxWidth,
title,
legend,
tooltip,
grid,
xAxis,
yAxis,
option,
...baseChartProps
}: KriBarChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const categoryAxis = { type: 'category', data: categories }
const valueAxis = { type: 'value' }
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'bar',
name: item.name,
data: item.data,
...(barWidth ? { barWidth } : {}),
...(barMaxWidth ? { barMaxWidth } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriBarChart

View File

@@ -0,0 +1,58 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriCartesianChartProps } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriLineChartProps = KriCartesianChartProps & {
smooth?: boolean
area?: boolean
showSymbol?: boolean
}
export function KriLineChart({
categories,
series,
smooth = false,
area = false,
showSymbol = true,
title,
legend,
tooltip,
grid,
xAxis,
yAxis,
option,
...baseChartProps
}: KriLineChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'axis' },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption({ type: 'category', data: categories, boundaryGap: false }, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'line',
name: item.name,
data: item.data,
smooth,
showSymbol,
...(area ? { areaStyle: {} } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [area, categories, grid, legend, option, series, showSymbol, smooth, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriLineChart

View File

@@ -0,0 +1,50 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriChartBaseProps, KriPieChartSeries } from './chart.types'
import { defaultLegend, mergeChartOptions } from './chart.utils'
export type KriPieChartProps = KriChartBaseProps & {
series: KriPieChartSeries[]
}
const getPieCenter = (index: number, count: number) => {
if (count === 1) return ['50%', '55%']
return [`${((index + 0.5) / count) * 100}%`, '55%']
}
export function KriPieChart({
series,
title,
legend,
tooltip,
option,
...baseChartProps
}: KriPieChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'item' },
legend: legend ?? defaultLegend(series.length),
series: series.map((item, index) => ({
type: 'pie',
name: item.name,
data: item.data,
radius: item.radius ?? (series.length > 1 ? ['32%', '52%'] : '65%'),
center: item.center ?? getPieCenter(index, series.length),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [legend, option, series, title, tooltip])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriPieChart

View File

@@ -0,0 +1,55 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriChartBaseProps, KriRadarChartSeries, KriRadarDataItem, KriRadarIndicator } from './chart.types'
import { defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriRadarChartProps = KriChartBaseProps & {
indicators: KriRadarIndicator[]
series: KriRadarChartSeries[]
radar?: EChartsOption['radar']
}
const normalizeRadarData = (series: KriRadarChartSeries): KriRadarDataItem[] => {
if (series.data.every((value) => typeof value === 'number')) {
return [{ name: series.name, value: series.data as number[] }]
}
return series.data as KriRadarDataItem[]
}
export function KriRadarChart({
indicators,
series,
radar,
title,
legend,
tooltip,
option,
...baseChartProps
}: KriRadarChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'item' },
legend: legend ?? defaultLegend(series.length),
radar: mergeObjectOption({ indicator: indicators }, radar) as EChartsOption['radar'],
series: series.map((item) => ({
type: 'radar',
name: item.name,
data: normalizeRadarData(item),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [indicators, legend, option, radar, series, title, tooltip])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriRadarChart

View File

@@ -0,0 +1,55 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriChartBaseProps, KriScatterChartSeries } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriScatterChartProps = KriChartBaseProps & {
series: KriScatterChartSeries[]
grid?: EChartsOption['grid']
xAxis?: EChartsOption['xAxis']
yAxis?: EChartsOption['yAxis']
symbolSize?: number | ((value: unknown, params: unknown) => number)
}
export function KriScatterChart({
series,
grid,
xAxis,
yAxis,
symbolSize,
title,
legend,
tooltip,
option,
...baseChartProps
}: KriScatterChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'item' },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption({ type: 'value' }, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'scatter',
name: item.name,
data: item.data,
...(symbolSize ? { symbolSize } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [grid, legend, option, series, symbolSize, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriScatterChart

View File

@@ -0,0 +1,62 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriCartesianChartProps } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriStackedBarChartProps = KriCartesianChartProps & {
isHorizontal?: boolean
stackName?: string
barWidth?: number | string
barMaxWidth?: number | string
}
export function KriStackedBarChart({
categories,
series,
isHorizontal = false,
stackName = 'total',
barWidth,
barMaxWidth,
title,
legend,
tooltip,
grid,
xAxis,
yAxis,
option,
...baseChartProps
}: KriStackedBarChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const categoryAxis = { type: 'category', data: categories }
const valueAxis = { type: 'value' }
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'bar',
name: item.name,
data: item.data,
stack: item.stack ?? stackName,
...(barWidth ? { barWidth } : {}),
...(barMaxWidth ? { barMaxWidth } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, stackName, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriStackedBarChart

View File

@@ -0,0 +1,6 @@
export const CHART_HEIGHTS = {
DEFAULT: 320,
SMALL: 240,
LARGE: 420,
} as const

View File

@@ -0,0 +1,71 @@
import type { EChartsOption } from 'echarts'
import type { BaseEChartProps } from './BaseEChart'
export type KriChartBaseProps = Omit<BaseEChartProps, 'option'> & {
option?: EChartsOption
title?: EChartsOption['title']
legend?: EChartsOption['legend']
tooltip?: EChartsOption['tooltip']
}
export type KriCategoryValue = string | number
export type KriCategoryChartSeries = {
name: string
data: unknown[]
color?: string
stack?: string
option?: Record<string, unknown>
}
export type KriCartesianChartProps = KriChartBaseProps & {
categories: KriCategoryValue[]
series: KriCategoryChartSeries[]
grid?: EChartsOption['grid']
xAxis?: EChartsOption['xAxis']
yAxis?: EChartsOption['yAxis']
}
export type KriNamedChartData = {
name: string
value: unknown
[key: string]: unknown
}
export type KriPieChartSeries = {
name?: string
data: KriNamedChartData[]
radius?: string | number | Array<string | number>
center?: Array<string | number>
option?: Record<string, unknown>
}
export type KriRadarIndicator = {
name: string
max?: number
min?: number
color?: string
}
export type KriRadarDataItem = {
name?: string
value: number[]
[key: string]: unknown
}
export type KriRadarChartSeries = {
name: string
data: number[] | KriRadarDataItem[]
option?: Record<string, unknown>
}
export type KriScatterDataItem = [number, number] | [string, number] | KriNamedChartData
export type KriScatterChartSeries = {
name: string
data: KriScatterDataItem[]
color?: string
option?: Record<string, unknown>
}

View File

@@ -0,0 +1,34 @@
import type { EChartsOption } from 'echarts'
export const mergeChartOptions = (generated: EChartsOption, option?: EChartsOption): EChartsOption => {
if (!option) return generated
return {
...generated,
...option,
series: option.series ?? generated.series,
}
}
export const mergeObjectOption = <TOption>(defaults: Record<string, unknown>, option?: TOption): TOption | Record<string, unknown> => {
if (!option) return defaults
if (Array.isArray(option)) return option
if (typeof option === 'object') return { ...defaults, ...(option as Record<string, unknown>) }
return option
}
export const defaultLegend = (seriesCount: number): EChartsOption['legend'] | undefined => {
return seriesCount > 1 ? { top: 0 } : undefined
}
export const defaultGrid = (seriesCount: number): EChartsOption['grid'] => {
return {
top: seriesCount > 1 ? 44 : 24,
right: 24,
bottom: 24,
left: 24,
containLabel: true,
}
}

View File

@@ -0,0 +1,29 @@
export { BaseEChart, default } from './BaseEChart'
export type { BaseEChartProps } from './BaseEChart'
export { KriBarChart } from './KriBarChart'
export type { KriBarChartProps } from './KriBarChart'
export { KriLineChart } from './KriLineChart'
export type { KriLineChartProps } from './KriLineChart'
export { KriPieChart } from './KriPieChart'
export type { KriPieChartProps } from './KriPieChart'
export { KriRadarChart } from './KriRadarChart'
export type { KriRadarChartProps } from './KriRadarChart'
export { KriScatterChart } from './KriScatterChart'
export type { KriScatterChartProps } from './KriScatterChart'
export { KriStackedBarChart } from './KriStackedBarChart'
export type { KriStackedBarChartProps } from './KriStackedBarChart'
export { CHART_HEIGHTS } from './chart.config'
export type {
KriCartesianChartProps,
KriCategoryChartSeries,
KriCategoryValue,
KriChartBaseProps,
KriNamedChartData,
KriPieChartSeries,
KriRadarChartSeries,
KriRadarDataItem,
KriRadarIndicator,
KriScatterChartSeries,
KriScatterDataItem,
} from './chart.types'
export { useResizeKey } from './useResizeKey'

View File

@@ -0,0 +1,31 @@
'use client'
import { useEffect, useState } from 'react'
export function useResizeKey(delay = 150) {
const [resizeKey, setResizeKey] = useState(0)
useEffect(() => {
if (typeof window === 'undefined') return
let timer: number | undefined
const handleResize = () => {
if (timer) window.clearTimeout(timer)
timer = window.setTimeout(() => {
setResizeKey((key) => key + 1)
}, delay)
}
window.addEventListener('resize', handleResize)
return () => {
if (timer) window.clearTimeout(timer)
window.removeEventListener('resize', handleResize)
}
}, [delay])
return resizeKey
}

View File

@@ -0,0 +1,232 @@
'use client'
import * as React from 'react'
import { cn } from '@/lib/utils'
import { MultiSelect } from '@/components/common/multi-select'
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
export interface KriAutoCompleteBaseProps<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
withInfo?: boolean
disabled?: boolean
'aria-invalid'?: boolean
modalPopover?: boolean
}
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
value: string[]
onChange: (value: string[]) => void
maxCount?: number
maxSelected?: number
hideSelectAll?: boolean
onItemsChange?: (items: T[]) => void
onOptionsChange?: (options: MultiSelectOption<T>[]) => void
}
function toOptions<T>(
items: T[],
getValue: ((item: T) => string) | undefined,
getLabel: ((item: T) => string) | undefined,
withInfo: boolean,
): MultiSelectOption<T>[] {
return items.map((item) => ({
value: getValue ? getValue(item) : String(item),
label: getLabel ? getLabel(item) : String(item),
...(withInfo ? { info: item } : {}),
}))
}
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 = 'text-base',
badgeClassName = 'text-base',
className,
getValue,
getLabel,
withInfo = false,
onItemsChange,
onOptionsChange,
disabled,
'aria-invalid': ariaInvalid,
modalPopover = true,
}: KriMultiSelectProps<T>) {
const options = React.useMemo(
() => toOptions(items, getValue, getLabel, withInfo),
[getLabel, getValue, items, withInfo],
)
return (
<div className={cn('flex-none', widthClassName, heightClassName)}>
<MultiSelect<T>
options={options}
defaultValue={value}
onValueChange={onChange}
onOptionChange={onOptionsChange}
onInfoChange={onItemsChange}
maxSelected={maxSelected}
placeholder={placeholder}
className={cn('bg-background text-base', className)}
spanClassName={spanClassName}
badgeClassName={badgeClassName}
searchable={searchable}
searchMode={searchMode}
defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange}
maxCount={maxCount}
hideSelectAll={hideSelectAll}
autoSize={!widthClassName}
singleLine
resetOnDefaultValueChange
deduplicateOptions
disabled={disabled}
aria-invalid={ariaInvalid}
modalPopover={modalPopover}
/>
</div>
)
}
export interface KriSingleSelectProps<T = unknown> extends KriAutoCompleteBaseProps<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
}
function KriSingleSelectInner<T>({
items,
value,
onChange,
searchable = true,
searchMode = 'filter',
defaultSearchValue = '',
onSearchValueChange,
placeholder = 'Select an option',
heightClassName,
widthClassName,
spanClassName = 'text-base',
badgeClassName = 'text-base',
className,
getValue,
getLabel,
withInfo = false,
onItemChange,
onOptionChange,
preventDeselect = false,
hideOptionCheck = false,
showSelectedTooltip = false,
useClear = false,
clearLabel = '선택 해제',
clearValue = '__CLEAR__',
disabled,
'aria-invalid': ariaInvalid,
modalPopover = true,
}: KriSingleSelectProps<T>, forwardedRef: React.ForwardedRef<MultiSelectRef>) {
const ref = React.useRef<MultiSelectRef>(null)
React.useImperativeHandle(
forwardedRef,
() => ({
reset: () => ref.current?.reset(),
getSelectedValues: () => ref.current?.getSelectedValues() ?? [],
setSelectedValues: (values) => ref.current?.setSelectedValues(values),
clear: () => ref.current?.clear(),
focus: () => ref.current?.focus(),
}),
[],
)
const options = React.useMemo(() => {
const normal = toOptions(items, getValue, getLabel, withInfo)
return useClear ? [{ value: clearValue, label: clearLabel }, ...normal] : normal
}, [clearLabel, clearValue, getLabel, getValue, items, useClear, withInfo])
const selectedLabel = options.find((option) => option.value === value)?.label
return (
<div className={cn('flex-none', widthClassName, heightClassName)}>
<MultiSelect<T>
ref={ref}
options={options}
defaultValue={value ? [value] : []}
onValueChange={(next) => {
const selected = next[0] ?? ''
if (selected === clearValue) {
ref.current?.clear()
onChange('')
onOptionChange?.(null)
onItemChange?.(null)
return
}
onChange(selected)
}}
onOptionChange={(next) => {
const option = next[0] ?? null
if (option?.value === clearValue) {
onOptionChange?.(null)
onItemChange?.(null)
return
}
onOptionChange?.(option)
onItemChange?.(option?.info ?? null)
}}
selectionMode="single"
maxCount={1}
maxSelected={1}
placeholder={placeholder}
className={cn('bg-background text-base', className)}
spanClassName={spanClassName}
badgeClassName={badgeClassName}
searchable={searchable}
searchMode={searchMode}
defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange}
preventDeselect={preventDeselect}
hideOptionCheck={hideOptionCheck}
hideSelectAll
autoSize={!widthClassName}
singleLine
closeOnSelect
resetOnDefaultValueChange
deduplicateOptions
disabled={disabled}
aria-invalid={ariaInvalid}
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
modalPopover={modalPopover}
/>
</div>
)
}
export const KriSingleSelect = React.forwardRef(KriSingleSelectInner) as <T = unknown>(
props: KriSingleSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
) => React.ReactElement

View File

@@ -0,0 +1,122 @@
'use client'
import { CalendarIcon, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Calendar } from '@/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
export type KriDateRange = {
from: string
to: string
}
export type KriDateRangePickerProps = {
value: KriDateRange
onChange: (value: KriDateRange) => void
placeholder?: string
className?: string
triggerClassName?: string
contentClassName?: string
disabled?: boolean
}
const parseDate = (value: string) => {
if (!value) return undefined
const [year, month, day] = value.split('-').map(Number)
if (!year || !month || !day) return undefined
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return undefined
}
return date
}
const formatDate = (date: Date | undefined) => {
if (!date) return ''
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export function KriDateRangePicker({
value,
onChange,
placeholder = '조회 기간 선택',
className,
triggerClassName,
contentClassName,
disabled = false,
}: KriDateRangePickerProps) {
const selected = {
from: parseDate(value.from),
to: parseDate(value.to),
}
const selectedRange = selected.from || selected.to ? selected : undefined
const displayText = value.from && value.to
? `${value.from} ~ ${value.to}`
: value.from
? `${value.from} ~`
: value.to
? `~ ${value.to}`
: placeholder
const hasValue = value.from.length > 0 || value.to.length > 0
return (
<div className={cn('relative', className)}>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className={cn(
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
!hasValue && 'text-muted-foreground',
triggerClassName,
)}
>
<CalendarIcon className="h-4 w-4" />
<span className="truncate">{displayText}</span>
</Button>
</PopoverTrigger>
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
<Calendar
mode="range"
selected={selectedRange}
onSelect={(range) => {
onChange({
from: formatDate(range?.from),
to: formatDate(range?.to),
})
}}
/>
</PopoverContent>
</Popover>
{hasValue && !disabled ? (
<button
type="button"
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={(event) => {
event.stopPropagation()
onChange({ from: '', to: '' })
}}
aria-label="조회 기간 초기화"
>
<X className="h-3.5 w-3.5" />
</button>
) : null}
</div>
)
}
export default KriDateRangePicker

View File

@@ -0,0 +1,76 @@
'use client'
import type { ReactNode } from 'react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { cn } from '@/lib/utils'
export interface KriDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
title: ReactNode
description?: ReactNode
children?: ReactNode
footer?: ReactNode
showDefaultFooter?: boolean
closeLabel?: string
showCloseButton?: boolean
contentClassName?: string
bodyClassName?: string
footerClassName?: string
}
export function KriDialog({
open,
onOpenChange,
title,
description,
children,
footer,
showDefaultFooter = true,
closeLabel = '닫기',
showCloseButton = true,
contentClassName,
bodyClassName,
footerClassName,
}: KriDialogProps) {
const renderFooter = () => {
if (footer !== undefined) {
if (footer === null) return null
return <DialogFooter className={footerClassName}>{footer}</DialogFooter>
}
if (!showDefaultFooter) return null
return (
<DialogFooter className={footerClassName}>
<DialogClose asChild>
<Button type="button" variant="outline">
{closeLabel}
</Button>
</DialogClose>
</DialogFooter>
)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className={contentClassName} showCloseButton={showCloseButton}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description ? <DialogDescription>{description}</DialogDescription> : null}
</DialogHeader>
<div className={cn('min-h-0', bodyClassName)}>{children}</div>
{renderFooter()}
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,29 @@
'use client'
import { cn } from '@/lib/utils'
export interface KriLoadingOverlayProps {
open: boolean
label?: string
className?: string
spinnerClassName?: string
}
export function KriLoadingOverlay({ open, label = '로딩 중', className, spinnerClassName }: KriLoadingOverlayProps) {
if (!open) return null
return (
<div
role="status"
aria-live="polite"
aria-label={label}
className={cn('fixed inset-0 z-[9999] flex items-center justify-center bg-black/70', className)}
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
>
<div className={cn('size-12 animate-spin rounded-full border-4 border-gray-400 border-t-white', spinnerClassName)} />
<span className="sr-only">{label}</span>
</div>
)
}

View File

@@ -0,0 +1,118 @@
'use client'
import { useId, useMemo, useState } from 'react'
import { CheckIcon, EyeIcon, EyeOffIcon, XIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { cn } from '@/lib/utils'
export const ALLOWED_SPECIALS_TEXT = `! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
export const ONLY_ALLOWED_REGEX = /^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/
const requirements = [
{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
{ test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' },
{ test: (value: string) => value.length >= 8 && value.length <= 20, text: '8~20자' },
{ test: (value: string) => !value || ONLY_ALLOWED_REGEX.test(value), text: '허용 문자만 사용' },
]
export interface KriPasswordProps {
value: string
onChange: (value: string) => void
id?: string
label?: string
placeholder?: string
disabled?: boolean
className?: string
showStrength?: boolean
}
export function KriPassword({
value,
onChange,
id,
label = '비밀번호',
placeholder = '비밀번호를 입력하세요',
disabled,
className,
showStrength = true,
}: KriPasswordProps) {
const [isVisible, setIsVisible] = useState(false)
const autoId = useId()
const inputId = id ?? autoId
const isValid = useMemo(() => KRI_PW_REGEX.test(value), [value])
const hasOnlyAllowedChars = useMemo(() => (value ? ONLY_ALLOWED_REGEX.test(value) : true), [value])
const checks = useMemo(() => requirements.map((item) => ({ met: item.test(value), text: item.text })), [value])
const score = checks.filter((item) => item.met).length
const statusText = useMemo(() => {
if (!value) return '비밀번호를 입력하세요'
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요'
return isValid ? '사용 가능한 비밀번호입니다' : '영문과 숫자를 포함한 8~20자로 입력하세요'
}, [hasOnlyAllowedChars, isValid, value])
const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
return (
<div className={cn('w-full space-y-2', className)}>
{label ? <Label htmlFor={inputId}>{label}</Label> : null}
<div className="relative">
<Input
id={inputId}
type={isVisible ? 'text' : 'password'}
placeholder={placeholder}
value={value}
onChange={(event) => onChange(event.target.value)}
className="pr-9"
disabled={disabled}
autoComplete="new-password"
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => setIsVisible((current) => !current)}
disabled={disabled}
className="text-muted-foreground absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
>
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
</Button>
</div>
{showStrength ? (
<>
<div className="flex h-1 w-full gap-1">
{requirements.map((item, index) => (
<span
key={item.text}
className={cn(
'h-full flex-1 rounded-full transition-colors',
index < score && value ? barClass : 'bg-border',
)}
/>
))}
</div>
<div className="flex items-start gap-2">
{value ? (
isValid ? (
<CheckIcon className="mt-0.5 size-4 text-green-600" />
) : (
<XIcon className="text-destructive mt-0.5 size-4" />
)
) : (
<span className="mt-0.5 size-4" />
)}
<p className={cn('text-xs', !value ? 'text-muted-foreground' : isValid ? 'text-green-600' : 'text-destructive')}>
{statusText}
</p>
</div>
</>
) : null}
</div>
)
}
export default KriPassword

View File

@@ -0,0 +1,98 @@
'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
}
export 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
disabled?: 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,
contentClassName,
itemClassName,
getValue,
getLabel,
useAll = true,
disabled,
}: 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}
disabled={disabled}
onValueChange={(selectedValue) => {
onChange?.(selectedValue)
const selected = items.find((item) => extractValue(item) === selectedValue)
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 value="ALL" className={itemClassName}>
전체
</SelectItem>
) : null}
{items.map((item, index) => {
const itemValue = extractValue(item)
const label = extractLabel(item)
return (
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
{label}
</SelectItem>
)
})}
</SelectContent>
</Select>
)
}

View File

@@ -0,0 +1,220 @@
'use client'
import * as React from 'react'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
import { MultiSelectContent } from './MultiSelectContent'
import { MultiSelectTrigger } from './MultiSelectTrigger'
import type { MultiSelectOption, MultiSelectProps, MultiSelectRef } from './types'
import { arraysEqual, deduplicateOptions, flattenOptions } from './utils'
import { useResponsiveSettings } from './use-responsive-settings'
function MultiSelectInner<T>(
{
options: rawOptions,
onValueChange,
onOptionChange,
onInfoChange,
defaultValue = [],
stickySelectedOptions = [],
onStickySelectedOptionsChange,
placeholder = 'Select options',
maxCount = 3,
maxSelected,
selectionMode = 'multiple',
modalPopover = false,
variant = 'default',
className,
spanClassName,
badgeClassName,
hideSelectAll = false,
searchable = true,
searchMode = 'filter',
defaultSearchValue = '',
onSearchValueChange,
emptyIndicator = '검색 결과가 없습니다.',
autoSize = false,
singleLine = false,
popoverClassName,
disabled = false,
responsive,
minWidth,
maxWidth,
deduplicateOptions: shouldDeduplicate = false,
resetOnDefaultValueChange = true,
closeOnSelect = false,
preventDeselect = false,
hideOptionCheck = false,
style,
...buttonProps
}: MultiSelectProps<T>,
ref: React.ForwardedRef<MultiSelectRef>,
) {
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
const [searchValue, setSearchValue] = React.useState(defaultSearchValue)
const [open, setOpen] = React.useState(false)
const buttonRef = React.useRef<HTMLButtonElement>(null)
const [triggerWidth, setTriggerWidth] = React.useState<number>()
const options = React.useMemo(
() => (shouldDeduplicate ? deduplicateOptions(rawOptions) : rawOptions),
[rawOptions, shouldDeduplicate],
)
const flatOptions = React.useMemo(() => flattenOptions(options), [options])
const responsiveSettings = useResponsiveSettings(responsive, maxCount)
const optionMap = React.useMemo(() => {
const map = new Map<string, MultiSelectOption<T>>()
for (const option of stickySelectedOptions) map.set(option.value, option)
for (const option of flatOptions) map.set(option.value, option)
return map
}, [flatOptions, stickySelectedOptions])
const selectedOptions = React.useMemo(
() => selectedValues.map((value) => optionMap.get(value) ?? { value, label: value }),
[optionMap, selectedValues],
)
const emit = React.useCallback(
(next: string[]) => {
setSelectedValues(next)
onValueChange(next)
const nextOptions = next.map((value) => optionMap.get(value) ?? { value, label: value })
onOptionChange?.(nextOptions)
onInfoChange?.(
nextOptions.flatMap((option) => (option.info === undefined ? [] : [option.info])),
)
},
[onInfoChange, onOptionChange, onValueChange, optionMap],
)
React.useEffect(() => {
if (!resetOnDefaultValueChange || arraysEqual(defaultValue, selectedValues)) return
setSelectedValues(defaultValue)
}, [defaultValue, resetOnDefaultValueChange, selectedValues])
React.useEffect(() => {
if (!onStickySelectedOptionsChange) return
const refreshed = selectedValues
.map((value) => optionMap.get(value))
.filter((option): option is MultiSelectOption<T> => Boolean(option))
onStickySelectedOptionsChange(refreshed)
}, [onStickySelectedOptionsChange, optionMap, selectedValues])
React.useEffect(() => {
const element = buttonRef.current
if (!element || !('ResizeObserver' in window)) return
const update = () => setTriggerWidth(Math.round(element.getBoundingClientRect().width))
update()
const observer = new ResizeObserver(update)
observer.observe(element)
return () => observer.disconnect()
}, [])
React.useImperativeHandle(
ref,
() => ({
reset: () => {
emit(defaultValue)
setSearchValue(defaultSearchValue)
setOpen(false)
},
getSelectedValues: () => selectedValues,
setSelectedValues: emit,
clear: () => emit([]),
focus: () => buttonRef.current?.focus(),
}),
[defaultSearchValue, defaultValue, emit, selectedValues],
)
const toggleOption = React.useCallback(
(option: MultiSelectOption<T>) => {
if (option.disabled) return
const selected = selectedValues.includes(option.value)
if (selected) {
if (preventDeselect) return
emit(selectedValues.filter((value) => value !== option.value))
return
}
if (selectionMode === 'single') {
emit([option.value])
if (closeOnSelect) setOpen(false)
return
}
if (maxSelected !== undefined && selectedValues.length >= maxSelected) return
emit([...selectedValues, option.value])
if (closeOnSelect) setOpen(false)
},
[closeOnSelect, emit, maxSelected, preventDeselect, selectedValues, selectionMode],
)
const toggleAll = React.useCallback(() => {
const values = flatOptions.filter((option) => !option.disabled).map((option) => option.value)
const allSelected = values.length > 0 && values.every((value) => selectedValues.includes(value))
if (allSelected) {
if (!preventDeselect) emit([])
return
}
emit(maxSelected === undefined ? values : values.slice(0, maxSelected))
}, [emit, flatOptions, maxSelected, preventDeselect, selectedValues])
const handleSearchChange = (value: string) => {
setSearchValue(value)
onSearchValueChange?.(value)
}
return (
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
<PopoverTrigger asChild>
<MultiSelectTrigger
ref={buttonRef}
selectedOptions={selectedOptions}
placeholder={placeholder}
maxCount={responsiveSettings.maxCount}
compactMode={responsiveSettings.compactMode}
hideIcons={responsiveSettings.hideIcons}
singleLine={singleLine}
preventDeselect={preventDeselect}
variant={variant}
spanClassName={spanClassName}
badgeClassName={badgeClassName}
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
onClear={() => emit([])}
className={cn(autoSize && 'w-auto', className)}
disabled={disabled}
style={{ minWidth, maxWidth, ...style }}
{...buttonProps}
/>
</PopoverTrigger>
<PopoverContent
align="start"
className={cn('w-[var(--radix-popover-trigger-width)] min-w-64 p-0', popoverClassName)}
style={{ width: triggerWidth ? `${triggerWidth}px` : undefined }}
>
<MultiSelectContent
options={options}
selectedValues={selectedValues}
searchable={searchable}
searchMode={searchMode}
searchValue={searchValue}
onSearchValueChange={handleSearchChange}
hideSelectAll={hideSelectAll}
hideOptionCheck={hideOptionCheck}
selectionMode={selectionMode}
emptyIndicator={emptyIndicator}
onToggleOption={toggleOption}
onToggleAll={toggleAll}
/>
</PopoverContent>
</Popover>
)
}
const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as <T = unknown>(
props: MultiSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
) => React.ReactElement
export const MultiSelect = ForwardedMultiSelect

View File

@@ -0,0 +1,169 @@
'use client'
import { CheckIcon } from 'lucide-react'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from '@/components/ui/command'
import { cn } from '@/lib/utils'
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
import { isGroupedOptions } from './utils'
interface MultiSelectContentProps<T> {
options: MultiSelectOptions<T>
selectedValues: string[]
searchable: boolean
searchMode: 'filter' | 'inputOnly'
searchValue: string
onSearchValueChange: (value: string) => void
hideSelectAll: boolean
hideOptionCheck: boolean
selectionMode: 'single' | 'multiple'
emptyIndicator: React.ReactNode
onToggleOption: (option: MultiSelectOption<T>) => void
onToggleAll: () => void
}
function OptionItem<T>({
option,
selected,
hideOptionCheck,
onToggle,
}: {
option: MultiSelectOption<T>
selected: boolean
hideOptionCheck: boolean
onToggle: () => void
}) {
const Icon = option.icon
return (
<CommandItem
value={`${option.label} ${option.value}`}
disabled={option.disabled}
onSelect={onToggle}
className="flex items-center cursor-pointer"
>
{!hideOptionCheck ? (
<span
className={cn(
'border-primary flex size-4 items-center justify-center rounded-sm border',
selected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
)}
>
<CheckIcon className="size-3" />
</span>
) : null}
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
<span className="truncate">{option.label}</span>
</CommandItem>
)
}
function OptionsGroup<T>({
group,
selectedValues,
hideOptionCheck,
onToggleOption,
}: {
group: MultiSelectGroup<T>
selectedValues: string[]
hideOptionCheck: boolean
onToggleOption: (option: MultiSelectOption<T>) => void
}) {
return (
<CommandGroup heading={group.heading}>
{group.options.map((option) => (
<OptionItem
key={option.value}
option={option}
selected={selectedValues.includes(option.value)}
hideOptionCheck={hideOptionCheck}
onToggle={() => onToggleOption(option)}
/>
))}
</CommandGroup>
)
}
export function MultiSelectContent<T>({
options,
selectedValues,
searchable,
searchMode,
searchValue,
onSearchValueChange,
hideSelectAll,
hideOptionCheck,
selectionMode,
emptyIndicator,
onToggleOption,
onToggleAll,
}: MultiSelectContentProps<T>) {
const grouped = isGroupedOptions(options)
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
const selectableOptions = flatOptions.filter((option) => !option.disabled)
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
return (
<Command shouldFilter={searchMode === 'filter'}>
{searchable ? (
<CommandInput
value={searchValue}
onValueChange={onSearchValueChange}
placeholder="검색..."
/>
) : null}
<CommandList>
<CommandEmpty>{emptyIndicator}</CommandEmpty>
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
<>
<CommandGroup>
<CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
<span
className={cn(
'border-primary flex size-4 items-center justify-center rounded-sm border',
allSelected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
)}
>
<CheckIcon className="size-3" />
</span>
전체 선택
</CommandItem>
</CommandGroup>
<CommandSeparator />
</>
) : null}
{grouped ? (
options.map((group) => (
<OptionsGroup
key={group.heading}
group={group}
selectedValues={selectedValues}
hideOptionCheck={hideOptionCheck}
onToggleOption={onToggleOption}
/>
))
) : (
<CommandGroup>
{options.map((option) => (
<OptionItem
key={option.value}
option={option}
selected={selectedValues.includes(option.value)}
hideOptionCheck={hideOptionCheck}
onToggle={() => onToggleOption(option)}
/>
))}
</CommandGroup>
)}
</CommandList>
</Command>
)
}

View File

@@ -0,0 +1,143 @@
'use client'
import * as React from 'react'
import { ChevronDown, XCircle, XIcon } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import type { MultiSelectOption, MultiSelectVariant } from './types'
import { getVariantClass } from './utils'
interface MultiSelectTriggerProps<T> extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
selectedOptions: MultiSelectOption<T>[]
placeholder: string
maxCount: number
singleLine: boolean
compactMode: boolean
hideIcons: boolean
preventDeselect: boolean
variant: MultiSelectVariant
spanClassName?: string
badgeClassName?: string
onRemove: (value: string) => void
onClear: () => void
}
export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerInner<T>(
{
selectedOptions,
placeholder,
maxCount,
singleLine,
compactMode,
hideIcons,
preventDeselect,
variant,
spanClassName,
badgeClassName,
className,
disabled,
onRemove,
onClear,
...buttonProps
}: MultiSelectTriggerProps<T>,
ref: React.ForwardedRef<HTMLButtonElement>,
) {
const visible = selectedOptions.slice(0, maxCount)
const hiddenCount = Math.max(0, selectedOptions.length - visible.length)
return (
<Button
ref={ref}
type="button"
variant="outline"
role="combobox"
aria-haspopup="listbox"
disabled={disabled}
className={cn(
'h-auto min-h-9 w-full justify-between gap-2 px-3 py-1.5 font-normal',
getVariantClass(variant),
className,
)}
{...buttonProps}
>
<span
className={cn(
'flex min-w-0 flex-1 items-center gap-1 text-left',
singleLine ? 'overflow-x-auto whitespace-nowrap' : 'flex-wrap',
spanClassName,
)}
>
{selectedOptions.length === 0 ? (
<span className="text-muted-foreground truncate">{placeholder}</span>
) : compactMode ? (
<span>{selectedOptions.length}개 선택</span>
) : (
<>
{visible.map((option) => {
const Icon = option.icon
return (
<Badge
key={option.value}
variant="secondary"
className={cn('max-w-full gap-1', badgeClassName)}
style={{ background: option.style?.gradient ?? option.style?.badgeColor }}
>
{!hideIcons && Icon ? <Icon className="size-3.5" /> : null}
<span className="max-w-48 truncate">{option.label}</span>
{!preventDeselect ? (
<span
role="button"
tabIndex={0}
aria-label={`${option.label} 선택 해제`}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
onRemove(option.value)
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
event.stopPropagation()
onRemove(option.value)
}
}}
>
<XIcon className="size-3" />
</span>
) : null}
</Badge>
)
})}
{hiddenCount > 0 ? <Badge variant="secondary">+{hiddenCount}</Badge> : null}
</>
)}
</span>
<span className="flex shrink-0 items-center gap-1">
{selectedOptions.length > 0 && !preventDeselect ? (
<span
role="button"
tabIndex={0}
aria-label="전체 선택 해제"
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
onClear()
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
event.stopPropagation()
onClear()
}
}}
>
<XCircle className="text-muted-foreground size-4" />
</span>
) : null}
<ChevronDown className="text-muted-foreground size-4" />
</span>
</Button>
)
}) as <T>(props: MultiSelectTriggerProps<T> & { ref?: React.ForwardedRef<HTMLButtonElement> }) => React.ReactElement

View File

@@ -0,0 +1,13 @@
export { MultiSelect } from './MultiSelect'
export type {
AnimationConfig,
MultiSelectGroup,
MultiSelectOption,
MultiSelectOptions,
MultiSelectProps,
MultiSelectRef,
MultiSelectResponsiveConfig,
MultiSelectResponsiveSettings,
MultiSelectSelectionMode,
MultiSelectVariant,
} from './types'

View File

@@ -0,0 +1,89 @@
import type * as React from 'react'
export interface AnimationConfig {
badgeAnimation?: 'bounce' | 'pulse' | 'wiggle' | 'fade' | 'slide' | 'none'
popoverAnimation?: 'scale' | 'slide' | 'fade' | 'flip' | 'none'
optionHoverAnimation?: 'highlight' | 'scale' | 'glow' | 'none'
duration?: number
delay?: number
}
export interface MultiSelectOption<T = unknown> {
label: string
value: string
info?: T
icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>
disabled?: boolean
style?: {
badgeColor?: string
iconColor?: string
gradient?: string
}
}
export interface MultiSelectGroup<T = unknown> {
heading: string
options: MultiSelectOption<T>[]
}
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
export type MultiSelectSelectionMode = 'single' | 'multiple'
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
export interface MultiSelectResponsiveSettings {
maxCount?: number
hideIcons?: boolean
compactMode?: boolean
}
export interface MultiSelectResponsiveConfig {
mobile?: MultiSelectResponsiveSettings
tablet?: MultiSelectResponsiveSettings
desktop?: MultiSelectResponsiveSettings
}
export interface MultiSelectProps<T = unknown>
extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'defaultValue' | 'onChange'> {
options: MultiSelectOptions<T>
onValueChange: (value: string[]) => void
onOptionChange?: (selectedOptions: MultiSelectOption<T>[]) => void
onInfoChange?: (infos: T[]) => void
defaultValue?: string[]
stickySelectedOptions?: MultiSelectOption<T>[]
onStickySelectedOptionsChange?: (options: MultiSelectOption<T>[]) => void
placeholder?: string
animation?: number
animationConfig?: AnimationConfig
maxCount?: number
maxSelected?: number
selectionMode?: MultiSelectSelectionMode
modalPopover?: boolean
variant?: MultiSelectVariant
spanClassName?: string
badgeClassName?: string
hideSelectAll?: boolean
searchable?: boolean
searchMode?: 'filter' | 'inputOnly'
defaultSearchValue?: string
onSearchValueChange?: (value: string) => void
emptyIndicator?: React.ReactNode
autoSize?: boolean
singleLine?: boolean
popoverClassName?: string
responsive?: boolean | MultiSelectResponsiveConfig
minWidth?: string
maxWidth?: string
deduplicateOptions?: boolean
resetOnDefaultValueChange?: boolean
closeOnSelect?: boolean
preventDeselect?: boolean
hideOptionCheck?: boolean
}
export interface MultiSelectRef {
reset: () => void
getSelectedValues: () => string[]
setSelectedValues: (values: string[]) => void
clear: () => void
focus: () => void
}

View File

@@ -0,0 +1,43 @@
'use client'
import * as React from 'react'
import type { MultiSelectProps, MultiSelectResponsiveSettings } from './types'
export function useResponsiveSettings(
responsive: MultiSelectProps['responsive'],
defaultMaxCount: number,
): Required<MultiSelectResponsiveSettings> {
const [screen, setScreen] = React.useState<'mobile' | 'tablet' | 'desktop'>('desktop')
React.useEffect(() => {
const update = () => {
if (window.innerWidth < 640) setScreen('mobile')
else if (window.innerWidth < 1024) setScreen('tablet')
else setScreen('desktop')
}
update()
window.addEventListener('resize', update)
return () => window.removeEventListener('resize', update)
}, [])
if (!responsive) {
return { maxCount: defaultMaxCount, hideIcons: false, compactMode: false }
}
if (responsive === true) {
const defaults = {
mobile: { maxCount: 2, hideIcons: false, compactMode: true },
tablet: { maxCount: 4, hideIcons: false, compactMode: false },
desktop: { maxCount: 6, hideIcons: false, compactMode: false },
}
return defaults[screen]
}
const current = responsive[screen]
return {
maxCount: current?.maxCount ?? defaultMaxCount,
hideIcons: current?.hideIcons ?? false,
compactMode: current?.compactMode ?? false,
}
}

View File

@@ -0,0 +1,48 @@
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
export function isGroupedOptions<T>(options: MultiSelectOptions<T>): options is MultiSelectGroup<T>[] {
return options.length > 0 && 'heading' in options[0]
}
export function flattenOptions<T>(options: MultiSelectOptions<T>): MultiSelectOption<T>[] {
return isGroupedOptions(options) ? options.flatMap((group) => group.options) : options
}
export function deduplicateOptions<T>(options: MultiSelectOptions<T>): MultiSelectOptions<T> {
const seen = new Set<string>()
if (isGroupedOptions(options)) {
return options.map((group) => ({
...group,
options: group.options.filter((option) => {
if (seen.has(option.value)) return false
seen.add(option.value)
return true
}),
}))
}
return options.filter((option) => {
if (seen.has(option.value)) return false
seen.add(option.value)
return true
})
}
export function arraysEqual(left: string[], right: string[]): boolean {
if (left.length !== right.length) return false
return left.every((value, index) => value === right[index])
}
export function getVariantClass(variant: 'default' | 'secondary' | 'destructive' | 'inverted'): string {
switch (variant) {
case 'secondary':
return 'bg-secondary text-secondary-foreground'
case 'destructive':
return 'bg-destructive text-destructive-foreground'
case 'inverted':
return 'bg-foreground text-background'
default:
return 'bg-background text-foreground'
}
}

View File

@@ -0,0 +1,295 @@
'use client'
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import type { OnChangeFn, PaginationState, Row, RowPinningState, RowSelectionState, SortingState } from '@tanstack/react-table'
import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { cn } from '@/lib/utils'
import type { DataTableColumn, DataTableProps } from './DataTable.type'
import { DataTablePagination } from './DataTablePagination'
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
const EMPTY_PINNED_ROWS: never[] = []
export function DataTable<TData, TValue = unknown>({
columns,
data,
getRowId,
highlightRowIds,
isClient = true,
pageCount: serverPageCount,
totalCount: serverTotalCount,
pagination: externalPagination,
onPaginationChange: onServerPaginationChange,
onSortingChange: onServerSortingChange,
selectMode = 'none',
onRowClick,
onRowSelectionChange,
defaultPageSize = 10,
pageSizeOptions = [5, 10, 25, 50],
paginationItemsToDisplay = 5,
emptyText = '데이터가 없습니다.',
className,
maxBodyHeight,
disablePagination = false,
topPinnedRows = EMPTY_PINNED_ROWS,
bottomPinnedRows = EMPTY_PINNED_ROWS,
}: Readonly<DataTableProps<TData, TValue>>) {
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
const [sorting, setSorting] = useState<SortingState>([])
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const drag = usePreventClickOnDrag()
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
if (!selectionEnabled) return columns
const selectionColumn = {
id: 'select',
header: ({ table }) => selectMode === 'multi' ? (
<Checkbox
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate')}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(Boolean(value))}
aria-label="전체 선택"
/>
) : null,
cell: ({ row }) => row.getIsPinned() ? null : (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => {
if (selectMode === 'single') table.resetRowSelection()
row.toggleSelected(Boolean(value))
}}
aria-label="행 선택"
onClick={(event) => event.stopPropagation()}
/>
),
size: 28,
enableSorting: false,
} as DataTableColumn<TData, TValue>
return [selectionColumn, ...columns]
}, [columns, selectMode, selectionEnabled])
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
useEffect(() => {
setRowSelection({})
}, [pagination.pageIndex, pagination.pageSize, sorting])
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
(updater) => {
if (isClient) {
setInternalPagination(updater)
return
}
if (onServerPaginationChange) {
onServerPaginationChange(updater)
return
}
setInternalPagination(updater)
},
[isClient, onServerPaginationChange],
)
const combinedData = useMemo(
() => [...topPinnedRows, ...data, ...bottomPinnedRows],
[topPinnedRows, data, bottomPinnedRows],
)
const internalGetRowId = useCallback((row: TData, index: number) => {
if (index < topPinnedRows.length) return `__top-pinned-${index}`
if (index >= topPinnedRows.length + data.length) {
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`
}
const originalIndex = index - topPinnedRows.length
return getRowId ? getRowId(data[originalIndex], originalIndex) : String(originalIndex)
}, [topPinnedRows.length, data, getRowId])
const rowPinning = useMemo<RowPinningState>(() => ({
top: topPinnedRows.map((_, i) => `__top-pinned-${i}`),
bottom: bottomPinnedRows.map((_, i) => `__bottom-pinned-${i}`),
}), [topPinnedRows, bottomPinnedRows])
const table = useReactTable({
data: combinedData,
columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount,
state: { sorting, pagination, rowSelection, rowPinning },
enableRowSelection: (row) => selectionEnabled && !row.getIsPinned(),
enableRowPinning: true,
keepPinnedRows: true,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onPaginationChange: handlePaginationChange,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined,
manualPagination: !isClient,
manualSorting: !isClient,
enableSortingRemoval: false,
getRowId: internalGetRowId,
})
useEffect(() => {
if (!isClient) onServerSortingChange?.(sorting)
}, [isClient, onServerSortingChange, sorting])
useEffect(() => {
if (!selectionEnabled) return
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
const handleRowClick = (row: Row<TData>) => {
if (selectMode === 'none') return
if (selectMode === 'click-event') {
onRowClick?.(row.original)
return
}
if (selectMode === 'single') {
table.resetRowSelection()
row.toggleSelected(true)
return
}
row.toggleSelected(!row.getIsSelected())
}
const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
const topRows = table.getTopRows()
const centerRows = table.getCenterRows()
const bottomRows = table.getBottomRows()
const scrollContainerRef = useRef<HTMLDivElement>(null)
const [topOffsets, setTopOffsets] = useState<number[]>([])
const [bottomOffsets, setBottomOffsets] = useState<number[]>([])
useLayoutEffect(() => {
if (!maxBodyHeight) return
const container = scrollContainerRef.current
if (!container) return
const headerHeight = container.querySelector('thead')?.getBoundingClientRect().height ?? 0
const bodyRows = Array.from(container.querySelectorAll('tbody > tr'))
const topRowEls = bodyRows.slice(0, topRows.length)
const bottomRowEls = bottomRows.length ? bodyRows.slice(-bottomRows.length) : []
let topAcc = headerHeight
setTopOffsets(topRowEls.map((element) => {
const offset = topAcc
topAcc += element.getBoundingClientRect().height
return offset
}))
let bottomAcc = 0
const offsets: number[] = []
for (let index = bottomRowEls.length - 1; index >= 0; index -= 1) {
offsets[index] = bottomAcc
bottomAcc += bottomRowEls[index].getBoundingClientRect().height
}
setBottomOffsets(offsets)
}, [maxBodyHeight, topRows.length, bottomRows.length, centerRows.length])
return (
<div className={cn('w-full space-y-4', className)}>
<div className="rounded-md border">
<div
ref={scrollContainerRef}
className={cn('relative w-full overflow-x-auto', maxBodyHeight && 'overflow-y-auto')}
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
>
<table className="w-full caption-bottom text-sm">
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-20 bg-background')}>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => {
const column = header.column
const sorted = column.getIsSorted()
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
return (
<TableHead
key={header.id}
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
>
{!header.isPlaceholder && column.getCanSort() ? (
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
<span>{content}</span>
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />}
</Button>
) : content}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{topRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
{centerRows.length ? centerRows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() ? 'selected' : undefined}
onPointerDown={drag.onPointerDown}
onPointerMove={drag.onPointerMove}
onPointerUp={drag.onPointerUp}
onPointerCancel={drag.onPointerCancel}
onClick={drag.wrapClick(() => handleRowClick(row))}
className={cn(
'text-sm [&>td]:px-2 [&>td]:py-0',
selectMode !== 'none' && 'cursor-pointer',
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
highlightRowIds?.includes(row.id) && '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">{emptyText}</TableCell></TableRow>
)}
{bottomRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
</TableBody>
</table>
</div>
</div>
{!disablePagination && (
<DataTablePagination
table={table}
isClient={isClient}
totalCount={totalCount}
pageSizeOptions={pageSizeOptions}
paginationItemsToDisplay={paginationItemsToDisplay}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,41 @@
import type { ColumnDef, PaginationState, SortingState, Updater } from '@tanstack/react-table'
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
export interface ServerPaginationParams {
pageIndex: number
pageSize: number
sorting?: SortingState
}
export interface ServerPaginationResponse<TData> {
data: TData[]
totalCount: number
pageCount: number
}
export interface DataTableProps<TData, TValue = unknown> {
columns: DataTableColumn<TData, TValue>[]
data: TData[]
getRowId?: (row: TData, index: number) => string
highlightRowIds?: string[]
isClient?: boolean
pageCount?: number
totalCount?: number
pagination?: PaginationState
onPaginationChange?: (updater: Updater<PaginationState>) => void
onSortingChange?: (sorting: SortingState) => void
selectMode?: SelectMode
onRowClick?: (row: TData) => void
onRowSelectionChange?: (rows: TData[]) => void
defaultPageSize?: number
pageSizeOptions?: number[]
paginationItemsToDisplay?: number
emptyText?: string
className?: string
maxBodyHeight?: string
disablePagination?: boolean
topPinnedRows?: TData[]
bottomPinnedRows?: TData[]
}

View File

@@ -0,0 +1,98 @@
'use client'
import type { Table } from '@tanstack/react-table'
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { usePagination } from './hooks/usePagination'
interface DataTablePaginationProps<TData> {
table: Table<TData>
isClient: boolean
totalCount: number
pageSizeOptions: number[]
paginationItemsToDisplay: number
}
export function DataTablePagination<TData>({
table,
isClient,
totalCount,
pageSizeOptions,
paginationItemsToDisplay,
}: DataTablePaginationProps<TData>) {
'use no memo'
const currentPage = table.getState().pagination.pageIndex + 1
const pageCount = table.getPageCount()
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
currentPage,
totalPages: pageCount,
paginationItemsToDisplay,
})
return (
<div className="flex items-center justify-between gap-3 p-2 pt-0 max-sm:flex-col">
<p className="text-muted-foreground flex-1 whitespace-nowrap text-sm" aria-live="polite">
Page <span className="text-foreground">{currentPage}</span> of{' '}
<span className="text-foreground">{pageCount}</span>
{!isClient && totalCount > 0 ? (
<span className="ml-2">(총 <span className="text-foreground">{totalCount}</span>건)</span>
) : null}
</p>
<div className="grow">
<Pagination>
<PaginationContent>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.firstPage()} disabled={!table.getCanPreviousPage()} aria-label="첫 페이지">
<ChevronsLeftIcon aria-hidden="true" />
</Button>
</PaginationItem>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} aria-label="이전 페이지">
<ChevronLeftIcon aria-hidden="true" />
</Button>
</PaginationItem>
{showLeftEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
{pages.map((page) => (
<PaginationItem key={page}>
<Button
size="icon"
variant={page === currentPage ? 'default' : 'ghost'}
onClick={() => table.setPageIndex(page - 1)}
aria-current={page === currentPage ? 'page' : undefined}
>
{page}
</Button>
</PaginationItem>
))}
{showRightEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} aria-label="다음 페이지">
<ChevronRightIcon aria-hidden="true" />
</Button>
</PaginationItem>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.lastPage()} disabled={!table.getCanNextPage()} aria-label="마지막 페이지">
<ChevronsRightIcon aria-hidden="true" />
</Button>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
<div className="flex flex-1 justify-end">
<Select value={String(table.getState().pagination.pageSize)} onValueChange={(value) => table.setPageSize(Number(value))}>
<SelectTrigger className="w-fit whitespace-nowrap" aria-label="페이지당 개수">
<SelectValue placeholder="페이지당 개수" />
</SelectTrigger>
<SelectContent>
{pageSizeOptions.map((size) => <SelectItem key={size} value={String(size)}>{size} / page</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
)
}

View File

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

View File

@@ -0,0 +1,37 @@
import * as React from 'react'
export function usePreventClickOnDrag(thresholdPx = 6) {
const state = React.useRef({ x: 0, y: 0, dragging: false })
const onPointerDown = React.useCallback((event: React.PointerEvent) => {
if (event.button !== 0) return
state.current = { x: event.clientX, y: event.clientY, dragging: false }
}, [])
const onPointerMove = React.useCallback((event: React.PointerEvent) => {
if (event.buttons === 0) return
const dx = event.clientX - state.current.x
const dy = event.clientY - state.current.y
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) state.current.dragging = true
}, [thresholdPx])
const onPointerUp = React.useCallback(() => {
setTimeout(() => {
state.current.dragging = false
}, 0)
}, [])
const wrapClick = React.useCallback(
(callback: () => void) => (event: React.MouseEvent) => {
if (state.current.dragging) {
event.preventDefault()
event.stopPropagation()
return
}
callback()
},
[],
)
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick }
}

View File

@@ -0,0 +1,8 @@
export { DataTable } from './DataTable'
export type {
DataTableColumn,
DataTableProps,
SelectMode,
ServerPaginationParams,
ServerPaginationResponse,
} from './DataTable.type'

View File

@@ -0,0 +1,24 @@
"use client";
import type { KriEditorProps, KriEditorMode } from "./types";
import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
import {KriEditorSms} from "./KriEditorSms";
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
return mode ?? editorMode ?? "wysiwyg";
}
export function KriEditor(props: KriEditorProps) {
const mode = resolveMode(props.mode, props.editorMode);
if (mode === "html") {
return <KriEditorHtmlOnly {...props} mode={mode} />;
}
if(mode === "sms") {
return <KriEditorSms {...props} mode={mode} />
}
return <KriEditorWysiwyg {...props} mode={mode} />;
}

View File

@@ -0,0 +1,197 @@
'use client'
import * as React from 'react'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import type { KriEditorProps } from './types'
import { resolveUploadUrl } from './types'
import { compressImage } from './utils/imageCompression'
import { useDebouncedChange } from './hooks/useDebouncedChange'
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
import { preserveEmptyParagraphs } from './utils/emptyParagraph'
import { formatHtmlSource } from './utils/formatHtml'
import { useTextareaInsert } from './hooks/useTextareaInsert'
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
export function KriEditorHtmlOnly({
label,
value,
onChange,
placeholder = 'HTML을 입력하세요...',
className,
showPreview,
previewClassName,
rows = 14,
debounceMs = 350,
onImageUpload,
onImageUploadError,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = 'image/webp',
onEditorReady,
onCommandReady,
}: HtmlOnlyProps) {
const [html, setHtml] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
const fileRef = React.useRef<HTMLInputElement | null>(null)
const latestHtmlRef = React.useRef(html)
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
const textareaInsert = useTextareaInsert(textareaRef)
const commitHtml = React.useCallback((next: string, immediate = false) => {
setHtml(next)
latestHtmlRef.current = next
if (immediate) flushChange(next)
else scheduleChange(next)
}, [flushChange, scheduleChange])
// 사용자가 타이핑한 값이 아니라 외부에서 새로 세팅된 데이터일 때만(최초 마운트 포함)
// prettier로 포맷팅해서 반영한다 — 편집 중(commitHtml 경로)에는 절대 재포맷하지 않는다.
const applyExternalValue = React.useCallback((next: string) => {
setHtml(next)
latestHtmlRef.current = next
formatHtmlSource(next)
.then((formatted) => {
if (latestHtmlRef.current !== next) return // 그 사이 값이 또 바뀌었으면 건너뜀
setHtml(formatted)
latestHtmlRef.current = formatted
})
.catch(() => {})
}, [])
React.useEffect(() => {
applyExternalValue(value || '')
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
React.useEffect(() => {
if ((value || '') !== latestHtmlRef.current) {
applyExternalValue(value || '')
}
}, [value, applyExternalValue])
React.useEffect(() => {
onEditorReady?.(textareaRef.current)
}, [onEditorReady])
React.useEffect(() => {
if (!onCommandReady) return
onCommandReady({
focus: () => textareaRef.current?.focus(),
insertText: (text) => {
textareaInsert.insertText(
text,
latestHtmlRef.current,
(next) => commitHtml(next),
(next) => commitHtml(next, true),
)
},
})
return () => onCommandReady(null)
}, [commitHtml, onCommandReady, textareaInsert])
const handleFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
try {
const file = event.target.files?.[0]
event.target.value = ''
if (!file || !onImageUpload) return
if (!file.type.startsWith('image/')) {
toast.error('이미지 파일만 업로드할 수 있습니다.')
return
}
const compressed = await compressImage(file, {
maxBytes: maxImageBytes,
maxWidth: imageMaxWidth,
maxHeight: imageMaxHeight,
mimeType: imageMimeType,
quality: imageQuality,
})
if (compressed.size > maxImageBytes) {
toast.error('이미지 용량이 제한을 초과합니다.')
return
}
const url = resolveUploadUrl(await onImageUpload(compressed))
if (!url) {
toast.error('이미지 업로드 응답이 올바르지 않습니다.')
return
}
const current = latestHtmlRef.current
const textarea = textareaRef.current
const imageTag = `<img src="${url}" alt="" />`
const start = textarea?.selectionStart ?? current.length
const end = textarea?.selectionEnd ?? current.length
const next = `${current.slice(0, start)}${imageTag}${current.slice(end)}`
commitHtml(next)
requestAnimationFrame(() => {
const position = start + imageTag.length
textarea?.focus()
textarea?.setSelectionRange(position, position)
})
} catch (error) {
if (onImageUploadError) onImageUploadError(error)
else toast.error('이미지 업로드에 실패했습니다.')
}
}
const handleFormatHtml = React.useCallback(async () => {
try {
const formatted = await formatHtmlSource(latestHtmlRef.current)
commitHtml(formatted)
} catch (error) {
toast.error('HTML 정렬에 실패했습니다.')
console.error(error)
}
}, [commitHtml])
const previewHtml = React.useMemo(
() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)),
[html],
)
return (
<div className={cn('rounded-md border bg-background', className)}>
{label ? <div className="border-b px-3 py-2 text-sm font-semibold">{label}</div> : null}
<div className="flex flex-col gap-2 px-3 py-2">
<div className="text-muted-foreground flex items-center justify-between text-xs">
<span>HTML 모드</span>
<div className="flex items-center gap-2">
<button type="button" onClick={handleFormatHtml} className="rounded border px-2 py-1 hover:bg-muted">
정렬
</button>
{onImageUpload ? (
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
이미지 업로드
</button>
) : null}
</div>
</div>
<textarea
ref={textareaRef}
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
value={html}
onChange={(event) => commitHtml(event.target.value)}
onBlur={() => flushChange(latestHtmlRef.current)}
placeholder={placeholder}
rows={rows}
{...textareaInsert.bindSelectionHandlers}
/>
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
</div>
{showPreview ? (
<div className={cn('border-t p-3', previewClassName)}>
<div className="mb-2 text-sm font-semibold">미리보기</div>
<div className="rounded-md border bg-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
) : null}
</div>
)
}

View File

@@ -0,0 +1,119 @@
'use client'
import * as React from 'react'
import { cn } from '@/lib/utils'
import type { KriEditorProps } from './types'
import { useDebouncedChange } from './hooks/useDebouncedChange'
import { useTextareaInsert } from './hooks/useTextareaInsert'
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
function calculateBytes(value: string): number {
return Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 127 ? 2 : 1), 0)
}
export function KriEditorSms({
label,
value,
onChange,
placeholder = '문자 내용을 입력하세요...',
className,
debounceMs = 350,
smsTitle = '',
changeSmsType,
onEditorReady,
onCommandReady,
isSmsReadOnly = false,
smsMaxBytes = 90,
lmsMaxBytes = 2000,
}: SmsEditorProps) {
const [text, setText] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
const latestTextRef = React.useRef(text)
const lastTypeRef = React.useRef<'SMS' | 'LMS' | null>(null)
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
const textareaInsert = useTextareaInsert(textareaRef)
const byteSize = React.useMemo(() => calculateBytes(text), [text])
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
const commitText = React.useCallback((next: string, immediate = false) => {
setText(next)
latestTextRef.current = next
if (immediate) flushChange(next)
else scheduleChange(next)
}, [flushChange, scheduleChange])
React.useEffect(() => {
if ((value || '') !== latestTextRef.current) {
setText(value || '')
latestTextRef.current = value || ''
}
}, [value])
React.useEffect(() => {
if (lastTypeRef.current === messageType) return
lastTypeRef.current = messageType
changeSmsType?.(messageType)
}, [changeSmsType, messageType])
React.useEffect(() => {
onEditorReady?.(textareaRef.current)
}, [onEditorReady])
React.useEffect(() => {
if (!onCommandReady) return
onCommandReady({
focus: () => textareaRef.current?.focus(),
insertText: (insertedText) => {
textareaInsert.insertText(
insertedText,
latestTextRef.current,
(next) => commitText(next),
(next) => commitText(next, true),
)
},
})
return () => onCommandReady(null)
}, [commitText, onCommandReady, textareaInsert])
return (
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
<div className="mb-3 flex items-center justify-between px-2">
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}>
{messageType}
</span>
</div>
<div className="flex flex-1 flex-col overflow-hidden rounded-2xl bg-white shadow-sm">
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
<textarea
ref={textareaRef}
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
value={text}
onChange={(event) => {
const next = event.target.value
if (calculateBytes(next) <= lmsMaxBytes) commitText(next)
}}
onBlur={() => flushChange(latestTextRef.current)}
placeholder={placeholder}
readOnly={isSmsReadOnly}
style={{ minHeight: smsTitle ? '320px' : '360px' }}
{...textareaInsert.bindSelectionHandlers}
/>
</div>
{byteSize > maxBytes ? (
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
최대 용량을 {byteSize - maxBytes}byte 초과했습니다.
</p>
) : null}
</div>
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
</div>
</div>
)
}

View File

@@ -0,0 +1,697 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { EditorContent, useEditor, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import { TextStyle } from "@tiptap/extension-text-style";
import FontFamily from "@tiptap/extension-font-family";
import Color from "@tiptap/extension-color";
import Highlight from "@tiptap/extension-highlight";
import TiptapImage from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import Link from "@tiptap/extension-link";
import TextAlign from "@tiptap/extension-text-align";
import { Table } from "@tiptap/extension-table";
import TableRow from "@tiptap/extension-table-row";
import TableHeader from "@tiptap/extension-table-header";
import TableCell from "@tiptap/extension-table-cell";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import type { KriEditorCommand, KriEditorProps, ToolbarState } from "./types";
import { resolveUploadUrl } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
import { DEFAULT_FONT_FAMILY_OPTIONS } from "./utils/fontFamilyOptions";
import { formatHtmlSource } from "./utils/formatHtml";
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { useTextareaInsert } from "./hooks/useTextareaInsert";
type ViewMode = "wysiwyg" | "html";
function getToolbarState(editor: Editor): ToolbarState {
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
const hl = editor.getAttributes("highlight") as { color?: string | null };
const fontFamily = (ts?.fontFamily ?? null) as string | null;
const fontSize = (ts?.fontSize ?? "16px") as string;
const textColor = (ts?.color ?? null) as string | null;
const highlightColor = (hl?.color ?? null) as string | null;
const align =
(editor.isActive({ textAlign: "center" }) && "center") ||
(editor.isActive({ textAlign: "right" }) && "right") ||
"left";
return {
fontFamily,
fontSize,
textColor,
highlightColor,
isBold: editor.isActive("bold"),
isItalic: editor.isActive("italic"),
isUnderline: editor.isActive("underline"),
isStrike: editor.isActive("strike"),
align,
isBulletList: editor.isActive("bulletList"),
isOrderedList: editor.isActive("orderedList"),
isLink: editor.isActive("link"),
inTable: editor.isActive("table"),
};
}
export function KriEditorWysiwyg(props: KriEditorProps) {
const {
label,
value,
onChange,
placeholder = "내용을 입력하세요…",
className,
showPreview = false,
previewClassName,
mode = "wysiwyg",
debounceMs = 350,
onImageUpload,
onImageUploadError,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = "image/webp",
allowBase64 = false,
sanitizeHtml: sanitizeHtmlOpt = true,
toolbar = {},
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
editorExtensions = [],
allowedCustomHtml,
transformPreviewHtml,
} = props;
const showHtmlToggle = mode === "both";
const LINK_HTML_ATTRS = {
rel: "noopener noreferrer",
target: "_blank",
} as const;
const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs);
const fileRef = useRef<HTMLInputElement | null>(null);
const htmlTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const htmlTi = useTextareaInsert(htmlTextareaRef);
const { insertText: insertTextareaText } = htmlTi;
const [view, setView] = useState<ViewMode>("wysiwyg");
const [previewSource, setPreviewSource] = useState(value ?? "");
const viewRef = useRef<ViewMode>("wysiwyg");
useEffect(() => {
viewRef.current = view;
}, [view]);
const htmlDraftRef = useRef<string>(value ?? "");
const canImageUpload = Boolean(onImageUpload);
const selectionRef = useRef<{ from: number; to: number } | null>(null);
const [tb, setTb] = useState<ToolbarState>({
fontFamily: null,
fontSize: "16px",
textColor: null,
highlightColor: null,
isBold: false,
isItalic: false,
isUnderline: false,
isStrike: false,
align: "left",
isBulletList: false,
isOrderedList: false,
isLink: false,
inTable: false,
});
const editor = useEditor({
immediatelyRender: false,
extensions: [
StarterKit.configure({
heading: false,
blockquote: false,
codeBlock: false,
code: false,
}),
Underline,
TextStyle,
FontSize,
FontFamily,
Color,
Highlight.configure({ multicolor: true }),
Div,
Link.configure({
autolink: true,
openOnClick: false,
linkOnPaste: true,
HTMLAttributes: {
class: KRI_EDITOR_LINK_CLASS,
...LINK_HTML_ATTRS,
},
}),
TextAlign.configure({ types: ["paragraph", "divBlock"] }),
Table.configure({ resizable: true }),
TableRow,
TableHeader,
TableCell,
TiptapImage.configure({
inline: true,
allowBase64,
HTMLAttributes: {
class: "max-w-full h-auto",
"data-kri-image": "true",
},
resize: {
enabled: true,
alwaysPreserveAspectRatio: true,
},
}),
Placeholder.configure({ placeholder }),
...editorExtensions,
],
content: value || "<p></p>",
onUpdate: ({ editor }) => {
if (viewRef.current === "html") return;
const nextHtml = editor.getHTML();
setPreviewSource(nextHtml);
scheduleChange(preserveEmptyParagraphs(nextHtml));
},
editorProps: {
attributes: {
class: cn(
"min-h-[180px] max-h-[420px] overflow-y-auto px-3 py-2 focus:outline-none",
"[&_p]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0",
"[&_ul]:list-disc [&_ul]:pl-6 [&_ol]:list-decimal [&_ol]:pl-6",
"[&_li]:my-1",
"[&_a]:text-blue-600 [&_a]:underline [&_a]:underline-offset-2",
"[&_table]:w-full [&_table]:border-collapse [&_table]:table-fixed",
"[&_th]:border [&_th]:bg-muted [&_th]:p-2 [&_th]:text-left",
"[&_td]:border [&_td]:p-2 [&_td]:align-top [&_td]:min-w-[90px]"
),
},
handleDOMEvents: {
click: (view, event) => {
const e = event as MouseEvent;
// Alt + 좌클릭만
if (!e.altKey || e.button !== 0) return false;
// 이미지(또는 리사이즈 컨테이너) 클릭일 때만
const target = e.target as HTMLElement | null;
const isImageClick = !!target?.closest?.("img, [data-resize-container]");
if (!isImageClick) return false;
// 1) 문서 상태에서 link mark의 href 찾기 (NodeView/리사이즈 DOM에서도 안전)
const pos = view.posAtCoords({ left: e.clientX, top: e.clientY });
const linkType = view.state.schema.marks.link;
let href: string | undefined;
if (pos && linkType) {
const $pos = view.state.doc.resolve(pos.pos);
const pickHref = (marks: readonly { type: unknown; attrs?: Record<string, unknown> }[] | null | undefined) => {
const mark = marks?.find((candidate) => candidate.type === linkType);
const value = mark?.attrs?.href;
return typeof value === "string" ? value : undefined;
};
href =
pickHref($pos.marks()) ||
pickHref($pos.nodeAfter?.marks) ||
pickHref($pos.nodeBefore?.marks);
}
// 2) DOM fallback (실제 <a>가 있는 경우)
if (!href) {
const a = target?.closest?.("a") as HTMLAnchorElement | null;
if (a?.href) href = a.href;
}
if (!href) return false;
// 링크 열기 + 에디터 클릭 처리(커서 이동 등) 막기
e.preventDefault();
e.stopPropagation();
window.open(href, LINK_HTML_ATTRS.target, LINK_HTML_ATTRS.rel.replaceAll(" ",","));
return true;
},
},
},
}, []);
const restoreSelection = useCallback(() => {
if (!editor) return;
const s = selectionRef.current;
if (!s) return;
editor.commands.setTextSelection(s);
}, [editor]);
const setFontSize = useCallback(
(px: string) => {
if (!editor) return;
restoreSelection();
editor.chain().focus().setFontSize(px).run();
},
[editor, restoreSelection]
);
const setFontFamily = useCallback(
(value: string) => {
if (!editor) return;
restoreSelection();
if (!value) {
editor.chain().focus().unsetFontFamily().run();
return;
}
editor.chain().focus().setFontFamily(value).run();
},
[editor, restoreSelection]
);
const setTextColor = useCallback(
(hex: string) => {
if (!editor) return;
restoreSelection();
editor.chain().focus().setColor(hex).run();
},
[editor, restoreSelection]
);
const unsetTextColor = useCallback(() => {
if (!editor) return;
restoreSelection();
editor.chain().focus().unsetColor().run();
}, [editor, restoreSelection]);
const setHighlight = useCallback(
(hex: string) => {
if (!editor) return;
restoreSelection();
editor.chain().focus().setHighlight({ color: hex }).run();
},
[editor, restoreSelection]
);
const unsetHighlight = useCallback(() => {
if (!editor) return;
restoreSelection();
editor.chain().focus().unsetHighlight().run();
}, [editor, restoreSelection]);
const normalizeLinkUrl = (raw: string): string => {
const trimmed = raw.trim();
if (!trimmed) return "";
if (/^https?:\/\//i.test(trimmed) || /^mailto:/i.test(trimmed) || /^tel:/i.test(trimmed)) {
return trimmed;
}
return `https://${trimmed}`;
};
const setLink = useCallback((url: string) => {
if (!editor) return;
restoreSelection();
const normalized = normalizeLinkUrl(url);
if (!normalized) return;
editor.chain().focus().extendMarkRange("link").setLink({ href: normalized }).run();
}, [editor, restoreSelection]);
const unsetLink = useCallback(() => {
if (!editor) return;
restoreSelection();
editor.chain().focus().extendMarkRange("link").unsetLink().run();
}, [editor, restoreSelection]);
const insertTable = useCallback(() => {
if (!editor) return;
restoreSelection();
editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();
}, [editor, restoreSelection]);
const addRow = useCallback(() => {
if (!editor) return;
restoreSelection();
if (!editor.isActive("table")) {
toast.message("표 안에서 셀을 클릭한 뒤 사용해 주세요.");
return;
}
const ok = editor.chain().focus().addRowAfter().run();
if (!ok) toast.error("행 추가에 실패했습니다.");
}, [editor, restoreSelection]);
const addColumn = useCallback(() => {
if (!editor) return;
restoreSelection();
if (!editor.isActive("table")) {
toast.message("표 안에서 셀을 클릭한 뒤 사용해 주세요.");
return;
}
const ok = editor.chain().focus().addColumnAfter().run();
if (!ok) toast.error("열 추가에 실패했습니다.");
}, [editor, restoreSelection]);
const deleteTable = useCallback(() => {
if (!editor) return;
restoreSelection();
if (!editor.isActive("table")) return;
editor.chain().focus().deleteTable().run();
}, [editor, restoreSelection]);
const handlePickImage = useCallback(() => {
if (!canImageUpload) return;
fileRef.current?.click();
}, [canImageUpload]);
const handleFile = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
try {
const file = e.target.files?.[0];
e.target.value = "";
if (!file || !editor) return;
if (!canImageUpload || !onImageUpload) return;
if (!file.type.startsWith("image/")) {
toast.error("이미지 파일만 업로드할 수 있습니다.");
return;
}
const compressed = await compressImage(file, {
maxBytes: maxImageBytes,
maxWidth: imageMaxWidth,
maxHeight: imageMaxHeight,
mimeType: imageMimeType,
quality: imageQuality,
});
if (compressed.size > maxImageBytes) {
toast.error("이미지 용량이 제한을 초과합니다.", {
description: `최대 ${(maxImageBytes / (1024 * 1024)).toFixed(0)}MB`,
});
return;
}
const url = resolveUploadUrl(await onImageUpload(compressed));
if (!url || typeof url !== "string") {
toast.error("이미지 업로드 응답이 올바르지 않습니다.");
return;
}
restoreSelection();
editor.chain().focus().setImage({ src: url }).run();
} catch (err) {
if(onImageUploadError){
onImageUploadError(err);
}else{
toast.error("이미지 업로드에 실패했습니다.");
console.error(err);
}
}
},
[
editor,
canImageUpload,
onImageUpload,
maxImageBytes,
imageMaxWidth,
imageMaxHeight,
imageMimeType,
imageQuality,
restoreSelection,
]
);
const onToggleHtmlView = useCallback(() => {
if (!editor) return;
if (viewRef.current === "wysiwyg") {
const raw = editor.getHTML();
htmlDraftRef.current = raw;
setView("html");
// WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로
// 화면 표시용으로만 정렬한다(onChange는 호출하지 않음 — 저장값은 그대로 유지).
formatHtmlSource(raw)
.then((formatted) => {
if (viewRef.current !== "html" || htmlDraftRef.current !== raw) return;
htmlDraftRef.current = formatted;
if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted;
setPreviewSource(formatted);
})
.catch(() => {});
return;
}
const raw = htmlDraftRef.current;
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(preserveEmptyParagraphs(editor.getHTML()));
setView("wysiwyg");
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
const formatHtmlView = useCallback(async () => {
try {
const formatted = await formatHtmlSource(htmlDraftRef.current);
htmlDraftRef.current = formatted;
if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted;
setPreviewSource(formatted);
scheduleChange(preserveEmptyParagraphs(formatted));
} catch (err) {
toast.error("HTML 정렬에 실패했습니다.");
console.error(err);
}
}, [scheduleChange]);
useEffect(() => {
if (!editor) return;
const sync = () => {
selectionRef.current = { from: editor.state.selection.from, to: editor.state.selection.to };
setTb(getToolbarState(editor));
};
sync();
editor.on("selectionUpdate", sync);
editor.on("transaction", sync);
return () => {
editor.off("selectionUpdate", sync);
editor.off("transaction", sync);
};
}, [editor]);
useEffect(() => {
if (!props.onEditorReady || !editor) return;
if (viewRef.current === "html") {
props.onEditorReady(htmlTextareaRef.current);
} else {
props.onEditorReady(editor);
}
}, [editor, view, props.onEditorReady]);
useEffect(() => {
setPreviewSource(value ?? "");
if (!editor) return;
if (viewRef.current === "html") return;
if (value == null) return;
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
const normalizedValue = value || "<p></p>";
const current = editor.getHTML();
if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) {
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
editor.commands.setContent(normalizedValue, {
emitUpdate: false,
parseOptions: {preserveWhitespace: "full"},
});
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
if (normalizedValue.includes("<img")) {
editor.createNodeViews();
}
}
}, [value, editor, view]);
useEffect(() => {
if (!editor) return;
const onBlur = () => {
if (viewRef.current === "html") flushChange(preserveEmptyParagraphs(htmlDraftRef.current));
else flushChange(preserveEmptyParagraphs(editor.getHTML()));
};
editor.on("blur", onBlur);
return () => {
editor.off("blur", onBlur);
};
}, [editor, flushChange]);
const command = useMemo<KriEditorCommand>(
() => ({
focus: () => {
if (viewRef.current === "html") htmlTextareaRef.current?.focus();
else editor?.chain().focus().run();
},
insertText: (text: string) => {
if (viewRef.current === "html") {
const current = htmlDraftRef.current ?? "";
insertTextareaText(
text,
current,
(next) => {
htmlDraftRef.current = next;
if (htmlTextareaRef.current) htmlTextareaRef.current.value = next;
},
(next) => {
flushChange(next);
}
);
return;
}
if (!editor) return;
restoreSelection();
editor.chain().focus().insertContent(text).run();
flushChange(preserveEmptyParagraphs(editor.getHTML()));
},
}),
[editor, restoreSelection, flushChange, insertTextareaText]
);
useEffect(() => {
if (!props.onCommandReady) return;
// editor가 아직 없으면 null 전달
if (!editor) {
props.onCommandReady(null);
return;
}
props.onCommandReady(command);
return () => props.onCommandReady?.(null);
}, [command, editor, props.onCommandReady]);
const previewHtml = useMemo(() => {
const preserved = preserveEmptyParagraphs(previewSource);
const sanitized = sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
const withLinkStyle = applyLinkPreviewClass(sanitized);
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
}, [allowedCustomHtml, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
if (!editor) {
return (
<div className={cn("rounded-lg border bg-background", className)}>
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
<div className="p-3 text-sm text-muted-foreground">에디터 로딩 중…</div>
</div>
);
}
return (
<div className={cn("rounded-lg border bg-background", className)}>
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
{toolbar !== false ? (
<div className="border-b">
<Toolbar
editor={editor}
state={tb}
config={toolbar}
className="flex-nowrap"
canImageUpload={canImageUpload}
onPickImage={handlePickImage}
showHtmlToggle={showHtmlToggle}
isHtmlView={view === "html"}
onToggleHtmlView={onToggleHtmlView}
onFormatHtml={formatHtmlView}
fontFamilyOptions={fontFamilyOptions}
onSetFontFamily={setFontFamily}
onSetFontSize={setFontSize}
onSetTextColor={setTextColor}
onUnsetTextColor={unsetTextColor}
onSetHighlight={setHighlight}
onUnsetHighlight={unsetHighlight}
linkUrl={(editor.getAttributes("link").href as string | undefined) ?? ""}
onSetLink={setLink}
onUnsetLink={unsetLink}
onInsertTable={insertTable}
onAddRow={addRow}
onAddColumn={addColumn}
onDeleteTable={deleteTable}
customContent={props.renderToolbarEnd?.({ editor, command, view })}
/>
</div>
) : null}
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} disabled={!canImageUpload} />
{view === "wysiwyg" ? (
<EditorContent editor={editor} />
) : (
<div className="p-2">
<textarea
ref={htmlTextareaRef}
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
defaultValue={htmlDraftRef.current}
onMouseDown={(e) => e.stopPropagation()}
onChange={(e) => {
htmlDraftRef.current = e.target.value;
setPreviewSource(htmlDraftRef.current);
scheduleChange(htmlDraftRef.current);
}}
onBlur={() => flushChange(htmlDraftRef.current)}
placeholder={placeholder}
{...htmlTi.bindSelectionHandlers}
/>
</div>
)}
{showPreview && (
<div className={cn("border-t p-3", previewClassName)}>
<div className="mb-2 text-sm font-semibold">미리보기</div>
<div className="rounded-md border bg-muted/30 p-3">
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,31 @@
import { Node, mergeAttributes } from "@tiptap/core";
export const Div = Node.create({
name: "divBlock",
group: "block",
content: "block+",
defining: true,
addAttributes() {
return {
class: {
default: null as string | null,
parseHTML: (el) => (el as HTMLElement).getAttribute("class"),
renderHTML: (attrs) => (attrs.class ? { class: attrs.class } : {}),
},
style: {
default: null as string | null,
parseHTML: (el) => (el as HTMLElement).getAttribute("style"),
renderHTML: (attrs) => (attrs.style ? { style: attrs.style } : {}),
},
};
},
parseHTML() {
return [{ tag: "div" }];
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes), 0];
},
});

View File

@@ -0,0 +1,46 @@
import { Extension } from "@tiptap/core";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
fontSize: {
setFontSize: (fontSize: string) => ReturnType;
unsetFontSize: () => ReturnType;
};
}
}
export const FontSize = Extension.create({
name: "fontSize",
addGlobalAttributes() {
return [
{
types: ["textStyle"],
attributes: {
fontSize: {
default: null as string | null,
parseHTML: (element) => (element).style.fontSize || null,
renderHTML: (attributes) => {
if (!attributes.fontSize) return {};
return { style: `font-size:${attributes.fontSize}` };
},
},
},
},
];
},
addCommands() {
return {
setFontSize:
(fontSize) =>
({ chain }) => {
return chain().setMark("textStyle", { fontSize }).run();
},
unsetFontSize:
() =>
({ chain }) => {
return chain().setMark("textStyle", { fontSize: null }).removeEmptyTextStyle().run();
},
};
},
});

View File

@@ -0,0 +1,42 @@
"use client";
import { useCallback, useEffect, useRef } from "react";
export function useDebouncedChange(onChange: (html: string) => void, debounceMs: number) {
const timerRef = useRef<number | null>(null);
const optimisticHtmlRef = useRef<string>("");
const flushChange = useCallback(
(nextHtml: string) => {
optimisticHtmlRef.current = nextHtml;
onChange(nextHtml);
},
[onChange]
);
const scheduleChange = useCallback(
(nextHtml: string) => {
optimisticHtmlRef.current = nextHtml;
if (!debounceMs || debounceMs <= 0) {
onChange(nextHtml);
return;
}
if (timerRef.current) window.clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(() => {
timerRef.current = null;
onChange(optimisticHtmlRef.current);
}, debounceMs);
},
[debounceMs, onChange]
);
useEffect(() => {
return () => {
if (timerRef.current) window.clearTimeout(timerRef.current);
};
}, []);
return { scheduleChange, flushChange, optimisticHtmlRef };
}

View File

@@ -0,0 +1,61 @@
import * as React from "react";
type Selection = { start: number; end: number };
export function useTextareaInsert(textareaRef: React.RefObject<HTMLTextAreaElement | null>) {
const selectionRef = React.useRef<Selection>({start: 0, end: 0});
const saveSelection = React.useCallback(() => {
const el = textareaRef.current;
if (!el) return;
selectionRef.current = {
start: el.selectionStart ?? 0,
end: el.selectionEnd ?? 0,
};
}, [textareaRef]);
const bindSelectionHandlers = React.useMemo(
() => ({
onSelect: saveSelection,
onKeyUp: saveSelection,
onMouseUp: saveSelection,
onClick: saveSelection,
onFocus: saveSelection,
}),
[saveSelection],
);
/**
* 실제 삽입/치환 로직 (컴포넌트에서 currentText를 제공해야 함)
* - apply(nextText): 로컬 state 반영 + latestRef 반영
* - commit(nextText): 부모 onChange 즉시 반영(가능하면 flushChange 사용 권장)
*/
const insertText = React.useCallback(
(placeholder: string, currentText: string, apply: (next: string) => void, commit?: (next: string) => void) => {
const {start, end} = selectionRef.current;
const next = currentText.slice(0, start) + placeholder + currentText.slice(end);
const nextPos = start + placeholder.length;
apply(next);
commit?.(next);
// 렌더 반영 후 커서 복원
requestAnimationFrame(() => {
const el = textareaRef.current;
if (!el) return;
el.focus();
el.setSelectionRange(nextPos, nextPos);
selectionRef.current = {start: nextPos, end: nextPos};
});
},
[textareaRef],
);
return {
selectionRef,
saveSelection,
bindSelectionHandlers,
insertText,
};
}

View File

@@ -0,0 +1,19 @@
export { KriEditor } from './KriEditor'
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
export { DEFAULT_FONT_FAMILY_OPTIONS } from './utils/fontFamilyOptions'
export type {
KriEditorAllowedHtml,
KriEditorCommand,
KriEditorFontFamilyOption,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,
KriEditorToolbarContext,
KriEditorToolbarFeature,
KriEditorUploadResult,
ToolbarState,
} from './types'
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'

View File

@@ -0,0 +1,315 @@
'use client'
import { useEffect, useState, type ReactNode } from 'react'
import type { Editor } from '@tiptap/react'
import {
AlignCenter,
AlignLeft,
AlignRight,
Bold,
Code2,
Highlighter,
Image as ImageIcon,
IndentIncrease,
Italic,
Link2,
List,
ListOrdered,
Palette,
Strikethrough,
Table2,
Underline,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Separator } from '@/components/ui/separator'
import { cn } from '@/lib/utils'
import type { KriEditorFontFamilyOption, KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
import { ToolbarButton } from './ToolbarButton'
interface ToolbarProps {
editor: Editor
state: ToolbarState
config?: KriEditorToolbarConfig
className?: string
canImageUpload: boolean
onPickImage: () => void
showHtmlToggle: boolean
isHtmlView: boolean
onToggleHtmlView: () => void
onFormatHtml: () => void
fontFamilyOptions: KriEditorFontFamilyOption[]
onSetFontFamily: (value: string) => void
onSetFontSize: (value: string) => void
onSetTextColor: (value: string) => void
onUnsetTextColor: () => void
onSetHighlight: (value: string) => void
onUnsetHighlight: () => void
linkUrl: string
onSetLink: (url: string) => void
onUnsetLink: () => void
onInsertTable: () => void
onAddRow: () => void
onAddColumn: () => void
onDeleteTable: () => void
customContent?: ReactNode
}
const PRESET_COLORS = [
'#111827', '#374151', '#6B7280', '#9CA3AF', '#D1D5DB', '#EF4444', '#F97316', '#F59E0B',
'#84CC16', '#22C55E', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899',
]
const HIGHLIGHT_COLORS = ['#FEF3C7', '#FDE68A', '#A7F3D0', '#BAE6FD', '#DDD6FE', '#FBCFE8', '#FFE4E6', '#E5E7EB', '#F5F5F4', '#FFFFFF']
function Swatch({ color }: { color: string | null }) {
return <span className="ml-1 inline-block size-2 rounded-full border" style={{ backgroundColor: color ?? 'transparent' }} />
}
export function Toolbar({
editor,
state,
config,
className,
canImageUpload,
onPickImage,
showHtmlToggle,
isHtmlView,
onToggleHtmlView,
onFormatHtml,
fontFamilyOptions,
onSetFontFamily,
onSetFontSize,
onSetTextColor,
onUnsetTextColor,
onSetHighlight,
onUnsetHighlight,
linkUrl,
onSetLink,
onUnsetLink,
onInsertTable,
onAddRow,
onAddColumn,
onDeleteTable,
customContent,
}: ToolbarProps) {
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
const showFontControls = enabled('fontFamily') || enabled('fontSize')
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
const showColors = enabled('textColor') || enabled('highlight')
const showLists = enabled('bulletList') || enabled('orderedList')
const [linkOpen, setLinkOpen] = useState(false)
const [linkDraft, setLinkDraft] = useState(linkUrl)
useEffect(() => {
if (linkOpen) setLinkDraft(linkUrl)
}, [linkOpen, linkUrl])
const applyLink = () => {
const next = linkDraft.trim()
if (!next) return
onSetLink(next)
setLinkOpen(false)
}
return (
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
{enabled('fontFamily') ? (
<select
className="h-8 w-[150px] rounded-md border bg-background px-2 text-sm"
value={state.fontFamily ?? ''}
onChange={(event) => onSetFontFamily(event.target.value)}
title="글꼴"
>
{fontFamilyOptions.map((option) => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : null}
{enabled('fontSize') ? (
<select
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
value={state.fontSize}
onChange={(event) => onSetFontSize(event.target.value)}
title="폰트 크기"
>
{['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px'].map((value) => (
<option key={value} value={value}>{value.replace('px', '')}</option>
))}
</select>
) : null}
{showFontControls && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('bold') ? (
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">
<Bold className="size-4" />
</ToolbarButton>
) : null}
{enabled('italic') ? (
<ToolbarButton active={state.isItalic} disabled={!editor.can().chain().focus().toggleItalic().run()} onClick={() => editor.chain().focus().toggleItalic().run()} title="기울임">
<Italic className="size-4" />
</ToolbarButton>
) : null}
{enabled('underline') ? (
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
<Underline className="size-4" />
</ToolbarButton>
) : null}
{enabled('strike') ? (
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
<Strikethrough className="size-4" />
</ToolbarButton>
) : null}
{showTextStyle && showColors ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('textColor') ? (
<Popover>
<PopoverTrigger asChild>
<span>
<ToolbarButton title="텍스트 색상" active={Boolean(state.textColor)}>
<Palette className="size-4" /><Swatch color={state.textColor} />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-56" align="start">
<div className="text-muted-foreground mb-2 text-xs">텍스트 색상</div>
<div className="grid grid-cols-5 gap-2">
{PRESET_COLORS.map((color) => (
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetTextColor(color)} aria-label={`색상 ${color}`} />
))}
</div>
<div className="mt-3 flex items-center gap-2">
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetTextColor(event.target.value)} aria-label="사용자 지정 텍스트 색상" />
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetTextColor}>색상 제거</button>
</div>
</PopoverContent>
</Popover>
) : null}
{enabled('highlight') ? (
<Popover>
<PopoverTrigger asChild>
<span>
<ToolbarButton title="하이라이트" active={Boolean(state.highlightColor)}>
<Highlighter className="size-4" /><Swatch color={state.highlightColor} />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-56" align="start">
<div className="text-muted-foreground mb-2 text-xs">하이라이트</div>
<div className="grid grid-cols-5 gap-2">
{HIGHLIGHT_COLORS.map((color) => (
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetHighlight(color)} aria-label={`하이라이트 ${color}`} />
))}
</div>
<div className="mt-3 flex items-center gap-2">
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetHighlight(event.target.value)} aria-label="사용자 지정 하이라이트" />
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetHighlight}>하이라이트 제거</button>
</div>
</PopoverContent>
</Popover>
) : null}
{showColors && enabled('align') ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('align') ? (
<>
<ToolbarButton active={state.align === 'left'} onClick={() => editor.chain().focus().setTextAlign('left').run()} title="왼쪽 정렬"><AlignLeft className="size-4" /></ToolbarButton>
<ToolbarButton active={state.align === 'center'} onClick={() => editor.chain().focus().setTextAlign('center').run()} title="가운데 정렬"><AlignCenter className="size-4" /></ToolbarButton>
<ToolbarButton active={state.align === 'right'} onClick={() => editor.chain().focus().setTextAlign('right').run()} title="오른쪽 정렬"><AlignRight className="size-4" /></ToolbarButton>
</>
) : null}
{enabled('align') && showLists ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('bulletList') ? <ToolbarButton active={state.isBulletList} onClick={() => editor.chain().focus().toggleBulletList().run()} title="불릿"><List className="size-4" /></ToolbarButton> : null}
{enabled('orderedList') ? <ToolbarButton active={state.isOrderedList} onClick={() => editor.chain().focus().toggleOrderedList().run()} title="번호"><ListOrdered className="size-4" /></ToolbarButton> : null}
{showLists && (enabled('link') || enabled('image') || enabled('table')) ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('link') ? (
<Popover open={linkOpen} onOpenChange={setLinkOpen}>
<PopoverTrigger asChild>
<span>
<ToolbarButton active={state.isLink} title={state.isLink ? '링크 수정' : '링크 삽입'}>
<Link2 className="size-4" />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-80" align="start">
<form
className="space-y-3"
onSubmit={(event) => {
event.preventDefault()
applyLink()
}}
>
<div className="space-y-1.5">
<label htmlFor="kri-editor-link-url" className="text-sm font-medium">링크 URL</label>
<Input
id="kri-editor-link-url"
value={linkDraft}
onChange={(event) => setLinkDraft(event.target.value)}
placeholder="https://example.com"
autoFocus
/>
</div>
<div className="flex justify-end gap-2">
{state.isLink ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
onUnsetLink()
setLinkOpen(false)
}}
>
링크 해제
</Button>
) : null}
<Button type="submit" size="sm" disabled={!linkDraft.trim()}>적용</Button>
</div>
</form>
</PopoverContent>
</Popover>
) : null}
{enabled('image') ? <ToolbarButton title={canImageUpload ? '이미지 업로드' : 'onImageUpload 미설정'} disabled={!canImageUpload} onClick={onPickImage}><ImageIcon className="size-4" /></ToolbarButton> : null}
{enabled('table') ? (
<DropdownMenu>
<DropdownMenuTrigger asChild><span><ToolbarButton title="표"><Table2 className="size-4" /></ToolbarButton></span></DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onInsertTable() }}>표 삽입</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddRow() }} disabled={!state.inTable}>행 추가</DropdownMenuItem>
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddColumn() }} disabled={!state.inTable}>열 추가</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onDeleteTable() }} disabled={!state.inTable} className="text-destructive">표 삭제</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
{showHtmlToggle && enabled('html') ? (
<>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
{isHtmlView ? (
<ToolbarButton title="HTML 정렬" onClick={onFormatHtml}><IndentIncrease className="size-4" /></ToolbarButton>
) : null}
</>
) : null}
{customContent ? (
<>
<Separator orientation="vertical" className="mx-1 h-6" />
{customContent}
</>
) : null}
</div>
)
}

View File

@@ -0,0 +1,35 @@
"use client";
import type { ReactNode, MouseEvent } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export type KriEditorToolbarButtonProps = {
active?: boolean;
disabled?: boolean;
title?: string;
onClick?: () => void;
children: ReactNode;
className?: string;
};
export function ToolbarButton({ active, disabled, title, onClick, children, className }: KriEditorToolbarButtonProps) {
const onMouseDown = (e: MouseEvent) => {
e.preventDefault();
};
return (
<Button
type="button"
variant={active ? "secondary" : "ghost"}
size="sm"
disabled={disabled}
onMouseDown={onMouseDown}
onClick={onClick}
title={title}
className={cn("h-8 w-8 p-0", className)}
>
{children}
</Button>
);
}

View File

@@ -0,0 +1,103 @@
import type { Extensions } from '@tiptap/core'
import type { Editor } from '@tiptap/react'
import type { ReactNode } from 'react'
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
export type KriEditorUploadResult = string | { url: string }
export type KriEditorToolbarFeature =
| 'fontFamily'
| 'fontSize'
| 'bold'
| 'italic'
| 'underline'
| 'strike'
| 'textColor'
| 'highlight'
| 'align'
| 'bulletList'
| 'orderedList'
| 'link'
| 'image'
| 'table'
| 'html'
export type KriEditorToolbarConfig = Partial<Record<KriEditorToolbarFeature, boolean>>
export type KriEditorCommand = {
focus: () => void
insertText: (text: string) => void
}
export type KriEditorToolbarContext = {
editor: Editor
command: KriEditorCommand
view: 'wysiwyg' | 'html'
}
export type KriEditorAllowedHtml = {
tags?: string[]
attributes?: string[]
}
export type KriEditorFontFamilyOption = {
label: string
value: string
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
label?: string
value: string
onChange: (html: string) => void
placeholder?: string
className?: string
showPreview?: boolean
previewClassName?: string
mode?: KriEditorMode
/** @deprecated mode를 사용하세요. */
editorMode?: KriEditorMode
onImageUpload?: (file: File) => Promise<KriEditorUploadResult>
maxImageBytes?: number
imageMaxWidth?: number
imageMaxHeight?: number
imageQuality?: number
imageMimeType?: 'image/webp' | 'image/jpeg'
allowBase64?: boolean
sanitizeHtml?: boolean
rows?: number
onImageUploadError?: (error: unknown) => void
debounceMs?: number
smsTitle?: string
changeSmsType?: (type: 'SMS' | 'LMS') => void
isSmsReadOnly?: boolean
smsMaxBytes?: number
lmsMaxBytes?: number
toolbar?: KriEditorToolbarConfig | false
fontFamilyOptions?: KriEditorFontFamilyOption[]
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
editorExtensions?: Extensions
allowedCustomHtml?: KriEditorAllowedHtml
transformPreviewHtml?: (html: string) => string
}
export type ToolbarState = {
fontFamily: string | null
fontSize: string
textColor: string | null
highlightColor: string | null
isBold: boolean
isItalic: boolean
isUnderline: boolean
isStrike: boolean
align: 'left' | 'center' | 'right'
isBulletList: boolean
isOrderedList: boolean
isLink: boolean
inTable: boolean
}
export function resolveUploadUrl(result: KriEditorUploadResult): string {
return typeof result === 'string' ? result : result.url
}

View File

@@ -0,0 +1,9 @@
import type { Editor } from '@tiptap/react'
export function isTipTapEditor(value: unknown): value is Editor {
return Boolean(value && typeof value === 'object' && 'chain' in value && typeof value.chain === 'function')
}
export function isTextAreaElement(value: unknown): value is HTMLTextAreaElement {
return typeof HTMLTextAreaElement !== 'undefined' && value instanceof HTMLTextAreaElement
}

View File

@@ -0,0 +1,9 @@
const EMPTY_PARAGRAPH_PATTERN = /<p((?:\s+[^>]*)?)>\s*<\/p>/gi;
/**
* TipTap이 빈 줄을 <p></p>로 직렬화하면 이메일 클라이언트에서 margin collapse로 사라진다.
* 눈에 보이지 않는 콘텐츠(&nbsp;)를 채워 실제 발송 HTML에서도 빈 줄이 유지되게 한다.
*/
export function preserveEmptyParagraphs(html: string): string {
return html.replace(EMPTY_PARAGRAPH_PATTERN, (_match, attrs: string) => `<p${attrs}>&nbsp;</p>`);
}

View File

@@ -0,0 +1,29 @@
import type { KriEditorFontFamilyOption } from "../types";
/**
* OS/이메일 클라이언트에 기본 설치돼 있어 별도 @font-face 로딩 없이 바로 렌더링되는 웹 세이프 폰트 목록.
* "자동"은 fontFamily 속성을 제거(unset)해 상위 스타일을 상속한다.
*/
export const DEFAULT_FONT_FAMILY_OPTIONS: KriEditorFontFamilyOption[] = [
{ label: "없음", value: "" },
{ label: "맑은 고딕", value: "'Malgun Gothic', sans-serif" },
{ label: "돋움", value: "Dotum, sans-serif" },
{ label: "굴림", value: "Gulim, sans-serif" },
{ label: "바탕", value: "Batang, serif" },
{ label: "궁서", value: "Gungsuh, serif" },
{ label: "Apple SD 고딕", value: "'Apple SD Gothic Neo', sans-serif" },
{ label: "Arial", value: "Arial, Helvetica, sans-serif" },
{ label: "Helvetica", value: "Helvetica, Arial, sans-serif" },
{ label: "Verdana", value: "Verdana, Geneva, sans-serif" },
{ label: "Tahoma", value: "Tahoma, Geneva, sans-serif" },
{ label: "Trebuchet MS", value: "'Trebuchet MS', Helvetica, sans-serif" },
{ label: "Century Gothic", value: "'Century Gothic', sans-serif" },
{ label: "Georgia", value: "Georgia, 'Times New Roman', serif" },
{ label: "Times New Roman", value: "'Times New Roman', Times, serif" },
{ label: "Palatino Linotype", value: "'Palatino Linotype', 'Book Antiqua', Palatino, serif" },
{ label: "Garamond", value: "Garamond, serif" },
{ label: "Courier New", value: "'Courier New', Courier, monospace" },
{ label: "Lucida Console", value: "'Lucida Console', Monaco, monospace" },
{ label: "Comic Sans MS", value: "'Comic Sans MS', cursive" },
{ label: "Impact", value: "Impact, Charcoal, sans-serif" },
];

View File

@@ -0,0 +1,16 @@
export async function formatHtmlSource(html: string): Promise<string> {
if (!html.trim()) return html;
const [{ format }, htmlPlugin] = await Promise.all([
import("prettier/standalone"),
import("prettier/plugins/html"),
]);
return format(html, {
parser: "html",
plugins: [htmlPlugin],
printWidth: 100,
// 인라인 요소(span/a/mark 등) 사이 공백은 실제 렌더링에 영향을 주므로 보존한다.
htmlWhitespaceSensitivity: "css",
});
}

View File

@@ -0,0 +1,85 @@
export type CompressOptions = {
maxBytes: number;
maxWidth: number;
maxHeight: number;
mimeType: "image/webp" | "image/jpeg";
quality: number; // 0~1
};
async function canvasToBlob(canvas: HTMLCanvasElement, mimeType: string, quality: number): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob(
(b) => (b ? resolve(b) : reject(new Error("canvas.toBlob returned null"))),
mimeType,
quality
);
});
}
async function loadImageFromBlob(blob: Blob): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(blob);
const img = document.createElement("img");
img.onload = () => {
URL.revokeObjectURL(url);
resolve(img);
};
img.onerror = (e) => {
URL.revokeObjectURL(url);
reject(e);
};
img.src = url;
});
}
export async function compressImage(file: File, opts: CompressOptions): Promise<File> {
const img = await loadImageFromBlob(file);
const srcW = img.naturalWidth || img.width;
const srcH = img.naturalHeight || img.height;
const ratio = Math.min(1, opts.maxWidth / srcW, opts.maxHeight / srcH);
const targetW = Math.max(1, Math.round(srcW * ratio));
const targetH = Math.max(1, Math.round(srcH * ratio));
if (ratio === 1 && file.size <= opts.maxBytes) return file;
const canvas = document.createElement("canvas");
canvas.width = targetW;
canvas.height = targetH;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("canvas 2d context is null");
ctx.drawImage(img, 0, 0, targetW, targetH);
let q = opts.quality;
let blob = await canvasToBlob(canvas, opts.mimeType, q);
while (blob.size > opts.maxBytes && q > 0.5) {
q = Math.max(0.5, q - 0.1);
blob = await canvasToBlob(canvas, opts.mimeType, q);
}
if (blob.size > opts.maxBytes && (targetW > 900 || targetH > 900)) {
const w2 = Math.round(targetW * 0.85);
const h2 = Math.round(targetH * 0.85);
canvas.width = Math.max(1, w2);
canvas.height = Math.max(1, h2);
const ctx2 = canvas.getContext("2d");
if (!ctx2) throw new Error("canvas 2d context is null (2)");
ctx2.drawImage(img, 0, 0, canvas.width, canvas.height);
q = opts.quality;
blob = await canvasToBlob(canvas, opts.mimeType, q);
while (blob.size > opts.maxBytes && q > 0.5) {
q = Math.max(0.5, q - 0.1);
blob = await canvasToBlob(canvas, opts.mimeType, q);
}
}
const ext = opts.mimeType === "image/webp" ? "webp" : "jpg";
const safeName = file.name.replace(/\.[^.]+$/, `.${ext}`);
return new File([blob], safeName, { type: blob.type });
}

View File

@@ -0,0 +1,29 @@
export const KRI_EDITOR_LINK_CLASS = "cursor-pointer text-blue-600 underline underline-offset-2";
const CLASS_ATTR_PATTERN = /class\s*=\s*"([^"]*)"|class\s*=\s*'([^']*)'/i;
/**
* 미리보기(dangerouslySetInnerHTML)에 쓰이는 원본 HTML은 예전 템플릿이거나
* HTML 모드에서 직접 작성된 경우 에디터의 링크 스타일 클래스가 없을 수 있다.
* <a> 태그에 KRI_EDITOR_LINK_CLASS를 보정해 항상 동일하게 보이도록 한다.
*/
export function applyLinkPreviewClass(html: string): string {
if (!html) return html;
return html.replace(/<a\b([^>]*)>/gi, (match, attrs: string) => {
const classMatch = attrs.match(CLASS_ATTR_PATTERN);
if (!classMatch) {
return `<a${attrs} class="${KRI_EDITOR_LINK_CLASS}">`;
}
const existingClasses = (classMatch[1] ?? classMatch[2] ?? "").split(/\s+/).filter(Boolean);
const missingClasses = KRI_EDITOR_LINK_CLASS.split(" ").filter((c) => !existingClasses.includes(c));
if (missingClasses.length === 0) return match;
const mergedClass = [...existingClasses, ...missingClasses].join(" ");
const newAttrs = attrs.replace(CLASS_ATTR_PATTERN, `class="${mergedClass}"`);
return `<a${newAttrs}>`;
});
}

View File

@@ -0,0 +1,53 @@
"use client";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
export type SanitizeHtmlOptions = {
tags?: string[];
attributes?: string[];
};
// Next.js SSR(Node) 환경에서는 dompurify가 window에 바인딩된 인스턴스가 아니라
// (window: Window) => DOMPurify 형태의 factory만 노출한다. window가 없으면
// factory를 호출할 방법이 없으므로, 여기서 안전하게 null로 폴백한다.
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
export function sanitizeHtml(
input: string,
options?: SanitizeHtmlOptions,
): string {
if (!input) {
return "";
}
const purifier = resolvePurifier();
if (!purifier) {
// DOM이 없어 실제 sanitize를 수행할 수 없는 환경(SSR 등)에서는
// 검증되지 않은 HTML을 그대로 노출하지 않도록 태그를 모두 제거한 텍스트만 반환한다.
// 브라우저에서 하이드레이션된 이후 재계산될 때 실제 sanitize 결과로 대체된다.
return input.replace(/<[^>]*>/g, "");
}
return purifier.sanitize(
input,
{
USE_PROFILES: {
html: true,
},
ADD_TAGS: options?.tags ?? [],
ADD_ATTR: options?.attributes ?? [],
},
);
}
export function sanitizeHtmlForPreview(
input: string,
options?: SanitizeHtmlOptions,
): string {
return sanitizeHtml(input, options);
}

View File

@@ -0,0 +1,96 @@
'use client'
import type { ReactNode } from 'react'
import { Menu, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import type { KriNavigationItem } from './types'
export interface KriHeaderProps {
logo?: ReactNode
homePath?: string
menus?: KriNavigationItem[]
activeMenuId?: string
menuOpen?: boolean
showMenuButton?: boolean
onToggleMenu?: () => void
onNavigate?: (path: string, item?: KriNavigationItem) => void
center?: ReactNode
right?: ReactNode
sticky?: boolean
className?: string
innerClassName?: string
}
export function KriHeader({
logo,
homePath = '/',
menus = [],
activeMenuId,
menuOpen = false,
showMenuButton = true,
onToggleMenu,
onNavigate,
center,
right,
sticky = true,
className,
innerClassName,
}: KriHeaderProps) {
return (
<header
className={cn(
'border-b border-white/10 bg-brand-blue-dark text-white',
sticky && 'sticky top-0 z-40',
className,
)}
>
<div className={cn('flex h-20 items-center justify-between gap-4 px-4', innerClassName)}>
<div className="flex min-w-0 items-center gap-4">
{showMenuButton && onToggleMenu ? (
<Button
type="button"
variant="ghost"
size="icon"
className="text-white hover:bg-white/10 hover:text-white"
onClick={onToggleMenu}
aria-label={menuOpen ? '메뉴 닫기' : '메뉴 열기'}
>
{menuOpen ? <X className="size-5" /> : <Menu className="size-5" />}
</Button>
) : null}
{logo ? (
<button type="button" className="flex shrink-0 items-center cursor-pointer" onClick={() => onNavigate?.(homePath)}>
{logo}
</button>
) : null}
{menus.length ? (
<nav className="hidden items-center gap-1 md:flex">
{menus.map((item) => (
<Button
key={item.id}
type="button"
variant={activeMenuId === item.id ? 'default' : 'ghost'}
className={cn(
activeMenuId === item.id
? 'bg-white text-brand-blue-dark shadow-none hover:bg-white/90'
: 'text-white/70 hover:bg-white/10 hover:text-white',
)}
disabled={item.disabled || !item.path}
onClick={() => item.path && onNavigate?.(item.path, item)}
>
{item.label}
</Button>
))}
</nav>
) : null}
</div>
<div className="min-w-0 flex-1 text-center">{center}</div>
<div className="flex shrink-0 items-center gap-2">{right}</div>
</div>
</header>
)
}

View File

@@ -0,0 +1,50 @@
'use client'
import type { CSSProperties, ReactNode } from 'react'
import { cn } from '@/lib/utils'
export interface KriMainLayoutProps {
children: ReactNode
header?: ReactNode
sidebar?: ReactNode
sidebarOpen?: boolean
onSidebarOpenChange?: (open: boolean) => void
fullHeight?: boolean
className?: string
bodyClassName?: string
mainClassName?: string
mainStyle?: CSSProperties
}
export function KriMainLayout({
children,
header,
sidebar,
sidebarOpen = false,
onSidebarOpenChange,
fullHeight = true,
className,
bodyClassName,
mainClassName,
mainStyle,
}: KriMainLayoutProps) {
return (
<div className={cn('flex flex-col bg-muted/30', fullHeight && 'h-screen', className)}>
{header}
<div className={cn('flex min-h-0 flex-1 overflow-hidden', bodyClassName)}>
{sidebar}
<main className={cn('min-w-0 flex-1 overflow-y-auto p-4 lg:p-6', mainClassName)} style={mainStyle}>
{children}
</main>
</div>
{sidebar && sidebarOpen ? (
<button
type="button"
aria-label="사이드바 닫기"
className="fixed inset-0 z-20 bg-black/20 lg:hidden"
onClick={() => onSidebarOpenChange?.(false)}
/>
) : null}
</div>
)
}

View File

@@ -0,0 +1,22 @@
import type { ReactNode } from 'react'
import { cn } from '@/lib/utils'
export interface KriPageTitleProps {
title: ReactNode
description?: ReactNode
actions?: ReactNode
className?: string
titleClassName?: string
}
export function KriPageTitle({ title, description, actions, className, titleClassName }: KriPageTitleProps) {
return (
<div className={cn('flex items-start justify-between gap-4', className)}>
<div className="min-w-0">
<h1 className={cn('text-2xl font-bold tracking-tight', titleClassName)}>{title}</h1>
{description ? <div className="text-muted-foreground mt-1 text-sm">{description}</div> : null}
</div>
{actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}
</div>
)
}

View File

@@ -0,0 +1,123 @@
'use client'
import { ChevronDown } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import type { KriNavigationItem } from './types'
export interface KriSidebarProps {
items: KriNavigationItem[]
isOpen: boolean
pathname?: string
header?: React.ReactNode
onNavigate?: (path: string, item: KriNavigationItem) => void
className?: string
contentClassName?: string
}
function isActive(item: KriNavigationItem, pathname: string): boolean {
if (item.match) return item.match(pathname)
if (item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`))) return true
return item.children?.some((child) => isActive(child, pathname)) ?? false
}
export function KriSidebar({
items,
isOpen,
pathname = '',
header,
onNavigate,
className,
contentClassName,
}: KriSidebarProps) {
return (
<aside
className={cn(
'fixed top-20 left-0 z-30 h-[calc(100vh-5rem)] overflow-y-auto border-r bg-background transition-all duration-300 lg:static lg:top-0 lg:h-full lg:translate-x-0',
isOpen ? 'w-80 translate-x-0' : 'w-80 -translate-x-full lg:w-0 lg:border-r-0',
className,
)}
>
<div className={cn('h-full space-y-4 overflow-y-auto p-4', contentClassName)}>
{header}
<nav className="space-y-1">
{items.map((item) => {
const active = isActive(item, pathname)
const hasChildren = Boolean(item.children?.length)
const opened = hasChildren && active
const Icon = item.icon
if (!hasChildren) {
return (
<Button
key={item.id}
type="button"
variant={active ? 'secondary' : 'ghost'}
className={cn(
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-words',
active &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}
disabled={item.disabled || !item.path}
onClick={() => item.path && onNavigate?.(item.path, item)}
>
{Icon ? <Icon className="size-4 shrink-0" /> : null}
<span>{item.label}</span>
</Button>
)
}
const questionCount = item.children?.length ?? 0
return (
<div key={item.id} className="space-y-1">
<Button
type="button"
variant={active ? 'secondary' : 'ghost'}
className={cn(
'h-auto w-full justify-start gap-1.5 rounded-md px-3 py-2 text-left whitespace-normal break-words',
active &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}
disabled={item.disabled}
onClick={() => item.path && onNavigate?.(item.path, item)}
>
{Icon ? <Icon className="size-4 shrink-0" /> : null}
<span className="min-w-0 flex-1">{item.label}</span>
<span className="shrink-0 text-xs whitespace-nowrap text-muted-foreground">{questionCount}문항</span>
<ChevronDown className={cn('size-4 shrink-0 transition-transform', opened && 'rotate-180')} />
</Button>
{opened ? (
<div className="ml-6 space-y-1">
{item.children?.map((child) => {
const childActive = isActive(child, pathname)
const ChildIcon = child.icon
return (
<Button
key={child.id}
type="button"
variant={childActive ? 'secondary' : 'ghost'}
className={cn(
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-words',
childActive &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}
disabled={child.disabled || !child.path}
onClick={() => child.path && onNavigate?.(child.path, child)}
>
{ChildIcon ? <ChildIcon className="size-4 shrink-0" /> : null}
<span>{child.label}</span>
</Button>
)
})}
</div>
) : null}
</div>
)
})}
</nav>
</div>
</aside>
)
}

View File

@@ -0,0 +1,9 @@
export { KriHeader } from './KriHeader'
export { KriMainLayout } from './KriMainLayout'
export { KriPageTitle } from './KriPageTitle'
export { KriSidebar } from './KriSidebar'
export type { KriNavigationItem } from './types'
export type { KriHeaderProps } from './KriHeader'
export type { KriMainLayoutProps } from './KriMainLayout'
export type { KriPageTitleProps } from './KriPageTitle'
export type { KriSidebarProps } from './KriSidebar'

View File

@@ -0,0 +1,11 @@
import type { ComponentType, ReactNode } from 'react'
export interface KriNavigationItem {
id: string
label: ReactNode
path?: string
icon?: ComponentType<{ className?: string }>
children?: KriNavigationItem[]
disabled?: boolean
match?: (pathname: string) => boolean
}

View File

@@ -0,0 +1,18 @@
"use client";
import { Provider as JotaiProvider } from "jotai";
import { QueryProvider } from "@kri/common/query";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { QueryLoadingSync } from "./QueryLoadingSync";
export function AppProvider({ children }: { children: React.ReactNode }) {
return (
<JotaiProvider>
<QueryProvider>
<QueryLoadingSync />
<LoadingOverlayAdapter />
{children}
</QueryProvider>
</JotaiProvider>
);
}

View File

@@ -0,0 +1,10 @@
"use client";
import { QueryLoadingSync as CommonQueryLoadingSync } from "@kri/common/query";
import { useSetAtom } from "jotai";
import { queryLoadingAtom } from "@/store/jotai/loading";
export function QueryLoadingSync() {
const setQueryLoading = useSetAtom(queryLoadingAtom);
return <CommonQueryLoadingSync onLoadingChange={setQueryLoading} />;
}

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(
"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 cursor-pointer",
{
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,220 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import {
DayPicker,
getDefaultClassNames,
type DayButton,
} from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_next
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute inset-0 bg-popover opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"font-medium select-none",
captionLayout === "label"
? "text-sm"
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
defaultClassNames.caption_label
),
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
defaultClassNames.weekday
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] text-muted-foreground select-none",
defaultClassNames.week_number
),
day: cn(
"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

Some files were not shown because too many files have changed in this diff Show More