260821_01_FST: First Commit

This commit is contained in:
2026-08-21 15:13:07 +09:00
commit f0461861c1
172 changed files with 20292 additions and 0 deletions

18
.agent/profile.yml Normal file
View File

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

89
.agent/project.md Normal file
View File

@@ -0,0 +1,89 @@
# Frontend Project Rules
- After every `.agent/project.md` change, run `cd "D:\_____Dev\_________AgentHarnessBase"`, then `.\scripts\agent-harness.ps1 compose --project ksif-manage-front` and `.\scripts\agent-harness.ps1 verify --project ksif-manage-front` to keep the generated agent documents current and verified.
## 1. Scope
Project-specific rules for the Sejong Institute dashboard frontend. Follow the approved screen design and backend API contract. Do not invent undefined permissions, fields, APIs, or calculation rules. Reuse the existing authentication implementation.
## 2. User Roles
- `1001`, `2001` → Admin
- `3001` → Center
- Center users may access only their own `center_cd` scope.
- Backend authorization based on the authenticated user is authoritative. Do not allow Center users to query another Center by changing `center_cd`.
- Do not expose Admin-only create/update/delete actions to Center users.
## 3. Notice / Popup Targeting
```text
0 center mappings → All Centers
1+ center mappings → Mapped Centers only
```
Admin UI must support `All` or selected Centers. Do not introduce a separate `is_all` concept.
## 4. Q&A
```text
Question 1 : Answer 0..1
```
- A question can have at most one answer.
- Do not implement multiple answers, comments, or threaded replies.
- When a Center user first opens a question detail containing an answer, the backend updates the answer-view status.
- Reflect the state returned by the backend.
## 5. File Upload
Applies to Notice, Q&A Question, and Q&A Answer:
- Maximum 5 files
- Maximum 5 MB per file
- `.exe` is not allowed
- Validate on the frontend for UX; backend validation is authoritative.
- Keep question attachments and answer attachments separate.
- Physical file paths are a backend concern.
## 6. Pagination
- Use the existing company pagination module.
- Do not implement another pagination system.
- Preserve search/filter/page state when returning from detail/edit/delete where practical.
## 7. Report Header
Multi-level headers use:
```text
report_header_group
→ variable_group
→ variable_name
→ report_header_label
```
- Use `report_header_order` for column order.
- Do not infer display order from IDs or alphabetical sorting.
- Merge adjacent identical headers using `rowSpan` / `colSpan`.
- `7-point` and `100-point` are fixed child display values under one logical report header, not separate report headers.
- Backend calculates both values; frontend only renders them.
## 8. Progress Report
- Backend calculates Progress Report values in real time from the external survey DB.
- Do not implement survey calculations or 7-point/100-point conversion in the frontend.
- Center users can view only their own Center.
- Implement Admin filters only when defined by the approved screen/API.
## 9. Final Report
- Final Report values are pre-calculated and stored before display.
- Frontend must not recalculate them.
- Build the screen from report header/result data returned by the backend.
## 10. Excel Download
- Export must use the **current screen query/filter conditions**.
- Send the same active conditions with the download request.
- Backend generates the Excel file; frontend uses the existing common download utility.
## 11. Common Rules
- Build screens from API DTOs; do not expose DB structures directly.
- Backend is authoritative for permissions, Center scope, Notice/Popup eligibility, Q&A access, and report calculations.
- Follow backend soft-delete behavior; do not manipulate deletion DB fields directly.
- Reuse existing common HTTP/Auth/Error/File Download modules.
- Do not add features not present in the approved screen design.
## 12. Open Decisions
Do not invent behavior for unresolved items:
- Detailed permission differences between Admin roles `1001` and `2001`
- Final API endpoints and request/response field names
- Exact Admin report filters
- Rich Text Editor / HTML sanitization policy
- Numeric rounding/display rules not defined by the backend
Check existing code and screen design first. If still unclear, ask the user before implementation.

4
.env.development Normal file
View File

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

4
.env.production Normal file
View File

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

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

21
.gitignore vendored Normal file
View File

@@ -0,0 +1,21 @@
/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*
.env
.env.local
.env.*.local
.idea/
*.iml

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}

375
AGENTS.md Normal file
View File

@@ -0,0 +1,375 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: ksif-manage-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.
# Frontend Project Rules
- After every `.agent/project.md` change, run `cd "D:\_____Dev\_________AgentHarnessBase"`, then `.\scripts\agent-harness.ps1 compose --project ksif-manage-front` and `.\scripts\agent-harness.ps1 verify --project ksif-manage-front` to keep the generated agent documents current and verified.
## 1. Scope
Project-specific rules for the Sejong Institute dashboard frontend. Follow the approved screen design and backend API contract. Do not invent undefined permissions, fields, APIs, or calculation rules. Reuse the existing authentication implementation.
## 2. User Roles
- `1001`, `2001` → Admin
- `3001` → Center
- Center users may access only their own `center_cd` scope.
- Backend authorization based on the authenticated user is authoritative. Do not allow Center users to query another Center by changing `center_cd`.
- Do not expose Admin-only create/update/delete actions to Center users.
## 3. Notice / Popup Targeting
```text
0 center mappings → All Centers
1+ center mappings → Mapped Centers only
```
Admin UI must support `All` or selected Centers. Do not introduce a separate `is_all` concept.
## 4. Q&A
```text
Question 1 : Answer 0..1
```
- A question can have at most one answer.
- Do not implement multiple answers, comments, or threaded replies.
- When a Center user first opens a question detail containing an answer, the backend updates the answer-view status.
- Reflect the state returned by the backend.
## 5. File Upload
Applies to Notice, Q&A Question, and Q&A Answer:
- Maximum 5 files
- Maximum 5 MB per file
- `.exe` is not allowed
- Validate on the frontend for UX; backend validation is authoritative.
- Keep question attachments and answer attachments separate.
- Physical file paths are a backend concern.
## 6. Pagination
- Use the existing company pagination module.
- Do not implement another pagination system.
- Preserve search/filter/page state when returning from detail/edit/delete where practical.
## 7. Report Header
Multi-level headers use:
```text
report_header_group
→ variable_group
→ variable_name
→ report_header_label
```
- Use `report_header_order` for column order.
- Do not infer display order from IDs or alphabetical sorting.
- Merge adjacent identical headers using `rowSpan` / `colSpan`.
- `7-point` and `100-point` are fixed child display values under one logical report header, not separate report headers.
- Backend calculates both values; frontend only renders them.
## 8. Progress Report
- Backend calculates Progress Report values in real time from the external survey DB.
- Do not implement survey calculations or 7-point/100-point conversion in the frontend.
- Center users can view only their own Center.
- Implement Admin filters only when defined by the approved screen/API.
## 9. Final Report
- Final Report values are pre-calculated and stored before display.
- Frontend must not recalculate them.
- Build the screen from report header/result data returned by the backend.
## 10. Excel Download
- Export must use the **current screen query/filter conditions**.
- Send the same active conditions with the download request.
- Backend generates the Excel file; frontend uses the existing common download utility.
## 11. Common Rules
- Build screens from API DTOs; do not expose DB structures directly.
- Backend is authoritative for permissions, Center scope, Notice/Popup eligibility, Q&A access, and report calculations.
- Follow backend soft-delete behavior; do not manipulate deletion DB fields directly.
- Reuse existing common HTTP/Auth/Error/File Download modules.
- Do not add features not present in the approved screen design.
## 12. Open Decisions
Do not invent behavior for unresolved items:
- Detailed permission differences between Admin roles `1001` and `2001`
- Final API endpoints and request/response field names
- Exact Admin report filters
- Rich Text Editor / HTML sanitization policy
- Numeric rounding/display rules not defined by the backend
Check existing code and screen design first. If still unclear, ask the user before implementation.

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
```
기본 포트: `6108`
## 환경변수
프로젝트 생성 시 `.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: `ksif-manage-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": {}
}

BIN
docs/색상규정.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

BIN
docs/화면 설계.pptx Normal file

Binary file not shown.

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;

9744
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

61
package.json Normal file
View File

@@ -0,0 +1,61 @@
{
"name": "ksif-manage-front",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 6108",
"build": "next build",
"start": "next start -p 6108",
"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.2",
"@tiptap/extension-font-family": "^3.13.0",
"@tiptap/extension-highlight": "^3.30.2",
"@tiptap/extension-image": "^3.30.2",
"@tiptap/extension-link": "^3.30.2",
"@tiptap/extension-placeholder": "^3.30.2",
"@tiptap/extension-table": "^3.30.2",
"@tiptap/extension-table-cell": "^3.30.2",
"@tiptap/extension-table-header": "^3.30.2",
"@tiptap/extension-table-row": "^3.30.2",
"@tiptap/extension-text-align": "^3.30.2",
"@tiptap/extension-text-style": "^3.30.2",
"@tiptap/extension-underline": "^3.30.2",
"@tiptap/react": "^3.30.2",
"@tiptap/starter-kit": "^3.30.2",
"class-variance-authority": "latest",
"clsx": "latest",
"cmdk": "^1.1.1",
"date-fns": "^4.4.0",
"dompurify": "^3.4.14",
"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",
"xlsx": "^0.18.5"
},
"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/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
public/icon-excel.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

BIN
public/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -0,0 +1,71 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { useMenusQuery, useUpdateMenuExposureMutation } from "@/query/menu";
import type { Menu } from "@/types/menu";
export function AdminMenuExposureCard() {
const menusQuery = useMenusQuery();
const updateMutation = useUpdateMenuExposureMutation();
const [draft, setDraft] = useState<Menu[]>([]);
useEffect(() => {
if (menusQuery.data) setDraft(menusQuery.data);
}, [menusQuery.data]);
const toggle = (menuId: number, userOpen: boolean) => {
setDraft((current) => current.map((menu) => (menu.menuId === menuId ? { ...menu, userOpen } : menu)));
};
const handleSave = async () => {
try {
await updateMutation.mutateAsync({ menus: draft.map((menu) => ({ menuId: menu.menuId, userOpen: menu.userOpen })) });
toast.success("메뉴 노출 설정을 저장했습니다.");
} catch (cause) {
toast.error(apiError(cause, { fallbackMessage: "저장에 실패했습니다." }).message);
}
};
return (
<Card className="w-70">
<CardHeader>
<CardTitle>메뉴 노출 설정</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="rounded-md border">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-muted">
<th className="p-2 text-left font-semibold">메뉴 명</th>
<th className="w-20 p-2 text-center font-semibold">오픈</th>
</tr>
</thead>
<tbody>
{draft.map((menu) => (
<tr key={menu.menuId} className="border-b last:border-0">
<td className="p-2">{menu.title}</td>
<td className="p-2 text-center">
<Checkbox checked={menu.userOpen} onCheckedChange={(checked) => toggle(menu.menuId, Boolean(checked))} />
</td>
</tr>
))}
{draft.length === 0 ? (
<tr><td colSpan={2} className="p-4 text-center text-muted-foreground">메뉴가 없습니다.</td></tr>
) : null}
</tbody>
</table>
</div>
<div className="flex justify-end">
<Button type="button" onClick={() => void handleSave()} disabled={updateMutation.isPending}>
{updateMutation.isPending ? "저장 중..." : "저장"}
</Button>
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,134 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { KriDialog } from "@/components/common/KriDialog";
import { KriDateTimePicker } from "@/components/common/KriDateTimePicker";
import { MultiSelect } from "@/components/common/multi-select";
import { KriEditor } from "@/components/kri-editor";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useDialog } from "@/hooks/useDialog";
import { useCentersQuery } from "@/query/center";
import { useCreatePopupMutation, usePopupDetailQuery, useUpdatePopupMutation } from "@/query/popup";
import type { Popup } from "@/types/popup";
export interface PopupFormDialogProps {
popupId: number | null;
onSaved: () => void;
}
const toDatetimeLocal = (value?: string) => (value ? value.slice(0, 16) : "");
export function PopupFormDialog({ popupId, onSaved }: PopupFormDialogProps) {
const { isDialogOpen, hideDialog } = useDialog();
const open = isDialogOpen("popupForm");
const isEdit = popupId !== null;
const centersQuery = useCentersQuery();
const detailQuery = usePopupDetailQuery(isEdit ? popupId : null);
const createMutation = useCreatePopupMutation();
const updateMutation = useUpdatePopupMutation(popupId ?? 0);
const [title, setTitle] = useState("");
const [contentHtml, setContentHtml] = useState("");
const [centerCds, setCenterCds] = useState<string[]>([]);
const [startDt, setStartDt] = useState("");
const [endDt, setEndDt] = useState("");
const resetFrom = (popup: Popup | undefined) => {
setTitle(popup?.title ?? "");
setContentHtml(popup?.contentHtml ?? "");
setCenterCds((popup?.centerCds ?? []).map(String));
setStartDt(toDatetimeLocal(popup?.startDt));
setEndDt(toDatetimeLocal(popup?.endDt));
};
useEffect(() => {
if (!open) return;
resetFrom(isEdit ? detailQuery.data : undefined);
}, [open, isEdit, detailQuery.data]);
const centerOptions = (centersQuery.data ?? [])
.filter((center) => center.centerCd !== 0)
.map((center) => ({ label: center.centerName, value: String(center.centerCd) }));
const saving = createMutation.isPending || updateMutation.isPending;
const handleSave = async () => {
if (!title.trim()) return toast.error("제목을 입력해 주세요.");
if (!contentHtml.trim()) return toast.error("내용을 입력해 주세요.");
if (!startDt || !endDt) return toast.error("팝업 기간을 입력해 주세요.");
if (startDt > endDt) return toast.error("시작일은 종료일보다 늦을 수 없습니다.");
const request = {
title: title.trim(),
contentHtml,
centerCds: centerCds.map(Number),
startDt: `${startDt}:00`,
endDt: `${endDt}:00`,
};
try {
if (isEdit) await updateMutation.mutateAsync(request);
else await createMutation.mutateAsync(request);
toast.success(isEdit ? "팝업을 수정했습니다." : "팝업을 등록했습니다.");
hideDialog("popupForm");
onSaved();
} catch (cause) {
toast.error(apiError(cause, { fallbackMessage: "저장에 실패했습니다." }).message);
}
};
return (
<KriDialog
open={open}
onOpenChange={(next) => !next && hideDialog("popupForm")}
title={isEdit ? "팝업 수정" : "팝업 등록"}
contentClassName="w-[calc(100vw-2rem)] max-w-[84rem] sm:max-w-[84rem] max-h-[calc(100vh-2rem)]"
bodyClassName="min-w-0 overflow-x-hidden"
footer={
<>
<Button type="button" variant="outline" onClick={() => hideDialog("popupForm")}>취소</Button>
<Button type="button" onClick={() => void handleSave()} disabled={saving}>{saving ? "저장 중..." : "저장"}</Button>
</>
}
>
<div className="min-w-0 space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">팝업 대상</label>
<MultiSelect
className="w-200 ml-2"
modalPopover={false}
options={centerOptions}
defaultValue={centerCds}
onValueChange={setCenterCds}
placeholder="전체 (선택 안 함)"
/>
</div>
<div className="grid w-150 grid-cols-2 gap-3">
<div className="space-y-2">
<label className="text-sm font-medium">시작</label>
<KriDateTimePicker value={startDt} onChange={setStartDt} modalPopover={false} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium">종료</label>
<KriDateTimePicker value={endDt} onChange={setEndDt} modalPopover={false} />
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">제목</label>
<Input value={title} onChange={(event) => setTitle(event.currentTarget.value)} maxLength={128} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium">내용</label>
<KriEditor
value={contentHtml}
onChange={setContentHtml}
/>
</div>
</div>
</KriDialog>
);
}

View File

@@ -0,0 +1,66 @@
"use client";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { CenterTargetCell } from "@/components/common/CenterTargetCell";
import { KriDialog } from "@/components/common/KriDialog";
import { Button } from "@/components/ui/button";
import { useDialog } from "@/hooks/useDialog";
import { useDeletePopupMutation, usePopupDetailQuery } from "@/query/popup";
import { useCentersQuery } from "@/query/center";
export interface PopupViewDialogProps {
popupId: number | null;
onEdit: (popupId: number) => void;
onDeleted: () => void;
}
export function PopupViewDialog({ popupId, onEdit, onDeleted }: PopupViewDialogProps) {
const { isDialogOpen, hideDialog } = useDialog();
const open = isDialogOpen("popupView");
const detailQuery = usePopupDetailQuery(open ? popupId : null);
const centersQuery = useCentersQuery();
const deleteMutation = useDeletePopupMutation();
const popup = detailQuery.data;
const handleDelete = async () => {
if (popupId === null) return;
if (!window.confirm("삭제되면 복구할 수 없습니다. 계속 진행하시겠습니까?")) return;
try {
await deleteMutation.mutateAsync(popupId);
toast.success("팝업을 삭제했습니다.");
hideDialog("popupView");
onDeleted();
} catch (cause) {
toast.error(apiError(cause, { fallbackMessage: "삭제에 실패했습니다." }).message);
}
};
return (
<KriDialog
open={open}
onOpenChange={(next) => !next && hideDialog("popupView")}
title={popup?.title ?? "팝업"}
contentClassName="max-w-2xl"
footer={
<>
<Button type="button" variant="destructive" onClick={() => void handleDelete()} disabled={deleteMutation.isPending}>삭제</Button>
<Button type="button" variant="outline" onClick={() => popupId !== null && onEdit(popupId)}>수정</Button>
<Button type="button" variant="outline" onClick={() => hideDialog("popupView")}>닫기</Button>
</>
}
>
{!popup ? (
<p className="text-sm text-muted-foreground">불러오는 중...</p>
) : (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-1 text-sm text-muted-foreground">
<span>팝업 대상:</span>
<CenterTargetCell centerCds={popup.centerCds} centers={centersQuery.data ?? []} />
<span>· 기간: {popup.startDt?.slice(0, 16).replace("T", " ")} ~ {popup.endDt?.slice(0, 16).replace("T", " ")}</span>
</div>
<div className="rounded-md border p-3" dangerouslySetInnerHTML={{ __html: popup.contentHtml }} />
</div>
)}
</KriDialog>
);
}

View File

@@ -0,0 +1,122 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import type { ColumnDef, PaginationState, SortingState } from "@tanstack/react-table";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { ContentSearchBar } from "@/components/common/ContentSearchBar";
import { CenterTargetCell } from "@/components/common/CenterTargetCell";
import { DataTable } from "@/components/data-table";
import { Button } from "@/components/ui/button";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { usePopupSearchQuery } from "@/query/popup";
import { useCentersQuery } from "@/query/center";
import { isAdminRole } from "@/types/auth";
import type { Popup } from "@/types/popup";
import { AdminMenuExposureCard } from "./AdminMenuExposureCard";
import { PopupFormDialog } from "./PopupFormDialog";
import { PopupViewDialog } from "./PopupViewDialog";
export default function AdminSettingsPage() {
const router = useRouter();
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const { showDialog } = useDialog();
const centersQuery = useCentersQuery();
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
const [sorting, setSorting] = useState<SortingState>([{ id: "regDt", desc: true }]);
const [keywordInput, setKeywordInput] = useState("");
const [searchKeyword, setSearchKeyword] = useState("");
const [targetCenterCds, setTargetCenterCds] = useState<string[]>([]);
const [selectedPopupId, setSelectedPopupId] = useState<number | null>(null);
const [editingPopupId, setEditingPopupId] = useState<number | null>(null);
useEffect(() => {
if (auth.user && !admin) router.replace("/");
}, [auth.user, admin, router]);
const searchQuery = usePopupSearchQuery({
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
sortBy: sorting[0]?.id ?? "regDt",
sortDir: sorting[0]?.desc === false ? "ASC" : "DESC",
searchKeyword: searchKeyword.trim() || undefined,
targetCenterCds: targetCenterCds.length ? targetCenterCds.map(Number) : undefined,
});
const totalElements = searchQuery.data?.totalElements ?? 0;
const centerOptions = useMemo(
() => (centersQuery.data ?? []).filter((center) => center.centerCd !== 0).map((center) => ({ label: center.centerName, value: String(center.centerCd) })),
[centersQuery.data],
);
const columns = useMemo<ColumnDef<Popup>[]>(() => [
{ id: "popupId", header: "No.", accessorFn: (row) => row.popupId, size: 70, cell: ({ row }) => totalElements - pagination.pageIndex * pagination.pageSize - row.index },
{ accessorKey: "title", header: "팝업 제목" },
{ id: "target", header: "팝업 대상", size: 120, cell: ({ row }) => <CenterTargetCell centerCds={row.original.centerCds} centers={centersQuery.data ?? []} /> },
{ accessorKey: "startDt", header: "팝업 시작", size: 110, cell: ({ row }) => row.original.startDt?.slice(0, 10) },
{ accessorKey: "endDt", header: "팝업 종료", size: 110, cell: ({ row }) => row.original.endDt?.slice(0, 10) },
{ accessorKey: "regUser", header: "게시자", size: 100 },
{ accessorKey: "regDt", header: "게시일", size: 110, cell: ({ row }) => row.original.regDt?.slice(0, 10) },
], [totalElements, pagination.pageIndex, pagination.pageSize, centersQuery.data]);
if (!admin) return null;
return (
<div className="space-y-6">
<AppPageTitle title="관리자 설정" description="메뉴 노출 및 팝업을 관리합니다." />
<div className="grid items-start gap-6 lg:grid-cols-[17.5rem_minmax(0,1fr)]">
<AdminMenuExposureCard />
<Card>
<CardHeader className="space-y-4">
<div>
<CardTitle>팝업</CardTitle>
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-end">
<div className="min-w-0 flex-1">
<ContentSearchBar
keyword={keywordInput}
onKeywordChange={setKeywordInput}
onSubmit={() => { setSearchKeyword(keywordInput); setPagination((current) => ({ ...current, pageIndex: 0 })); }}
targetCenterCds={targetCenterCds}
onTargetCenterCdsChange={(values) => { setTargetCenterCds(values); setPagination((current) => ({ ...current, pageIndex: 0 })); }}
centerOptions={centerOptions}
showTargetFilter
placeholder="No., 제목, 게시자 검색"
/>
</div>
<Button className="shrink-0" type="button" onClick={() => { setEditingPopupId(null); showDialog("popupForm"); }}>등록</Button>
</div>
</CardHeader>
<CardContent className="pt-0">
<DataTable
columns={columns}
data={searchQuery.data?.content ?? []}
getRowId={(row) => String(row.popupId)}
isClient={false}
pagination={pagination}
onPaginationChange={setPagination}
onSortingChange={setSorting}
pageCount={searchQuery.data?.totalPages ?? 0}
totalCount={totalElements}
selectMode="click-event"
onRowClick={(row) => { setSelectedPopupId(row.popupId); showDialog("popupView"); }}
emptyText="등록된 팝업이 없습니다."
/>
</CardContent>
</Card>
</div>
<PopupViewDialog
popupId={selectedPopupId}
onEdit={(popupId) => { setEditingPopupId(popupId); showDialog("popupForm"); }}
onDeleted={() => searchQuery.refetch()}
/>
<PopupFormDialog popupId={editingPopupId} onSaved={() => searchQuery.refetch()} />
</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,124 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { FileAttachmentField } from "@/components/common/FileAttachmentField";
import { KriDialog } from "@/components/common/KriDialog";
import { MultiSelect } from "@/components/common/multi-select";
import { KriEditor } from "@/components/kri-editor";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useDialog } from "@/hooks/useDialog";
import { useCentersQuery } from "@/query/center";
import { useCreateNoticeMutation, useNoticeDetailQuery, useUpdateNoticeMutation } from "@/query/notice";
import type { Notice } from "@/types/notice";
export interface NoticeFormDialogProps {
noticeId: number | null;
onSaved: () => void;
}
export function NoticeFormDialog({ noticeId, onSaved }: NoticeFormDialogProps) {
const { isDialogOpen, hideDialog } = useDialog();
const open = isDialogOpen("noticeForm");
const isEdit = noticeId !== null;
const centersQuery = useCentersQuery();
const detailQuery = useNoticeDetailQuery(isEdit ? noticeId : null);
const createMutation = useCreateNoticeMutation();
const updateMutation = useUpdateNoticeMutation(noticeId ?? 0);
const [title, setTitle] = useState("");
const [contentHtml, setContentHtml] = useState("");
const [centerCds, setCenterCds] = useState<string[]>([]);
const [keptFileIds, setKeptFileIds] = useState<number[]>([]);
const [newFiles, setNewFiles] = useState<File[]>([]);
const resetFrom = (notice: Notice | undefined) => {
setTitle(notice?.title ?? "");
setContentHtml(notice?.contentHtml ?? "");
setCenterCds((notice?.centerCds ?? []).map(String));
setKeptFileIds((notice?.files ?? []).map((file) => file.fileId));
setNewFiles([]);
};
useEffect(() => {
if (!open) return;
resetFrom(isEdit ? detailQuery.data : undefined);
}, [open, isEdit, detailQuery.data]);
const centerOptions = (centersQuery.data ?? [])
.filter((center) => center.centerCd !== 0)
.map((center) => ({ label: center.centerName, value: String(center.centerCd) }));
const saving = createMutation.isPending || updateMutation.isPending;
const handleSave = async () => {
if (!title.trim()) return toast.error("제목을 입력해 주세요.");
if (!contentHtml.trim()) return toast.error("내용을 입력해 주세요.");
const request = {
title: title.trim(),
contentHtml,
centerCds: centerCds.map(Number),
...(isEdit ? { keepFileIds: keptFileIds } : {}),
};
try {
if (isEdit) await updateMutation.mutateAsync({ request, files: newFiles });
else await createMutation.mutateAsync({ request, files: newFiles });
toast.success(isEdit ? "공지사항을 수정했습니다." : "공지사항을 등록했습니다.");
hideDialog("noticeForm");
onSaved();
} catch (cause) {
toast.error(apiError(cause, { fallbackMessage: "저장에 실패했습니다." }).message);
}
};
return (
<KriDialog
open={open}
onOpenChange={(next) => !next && hideDialog("noticeForm")}
title={isEdit ? "공지사항 수정" : "공지사항 등록"}
contentClassName="w-[calc(100vw-2rem)] max-w-[84rem] sm:max-w-[84rem] max-h-[calc(100vh-2rem)]"
bodyClassName="min-w-0 overflow-x-hidden"
footer={
<>
<Button type="button" variant="outline" onClick={() => hideDialog("noticeForm")}>취소</Button>
<Button type="button" onClick={() => void handleSave()} disabled={saving}>{saving ? "저장 중..." : "저장"}</Button>
</>
}
>
<div className="min-w-0 space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">공지 대상</label>
<MultiSelect
className="w-200 ml-2"
modalPopover={false}
options={centerOptions}
defaultValue={centerCds}
onValueChange={setCenterCds}
placeholder="전체 (선택 안 함)"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">제목</label>
<Input value={title} onChange={(event) => setTitle(event.currentTarget.value)} maxLength={128} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium">내용</label>
<KriEditor value={contentHtml} onChange={setContentHtml} />
</div>
<FileAttachmentField
existingFiles={detailQuery.data?.files ?? []}
keptFileIds={keptFileIds}
onKeptFileIdsChange={setKeptFileIds}
newFiles={newFiles}
onNewFilesChange={setNewFiles}
downloadPath={(fileId) => `/api/notices/${noticeId}/files/${fileId}`}
/>
</div>
</KriDialog>
);
}

View File

@@ -0,0 +1,90 @@
"use client";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { CenterTargetCell } from "@/components/common/CenterTargetCell";
import { FileAttachmentField } from "@/components/common/FileAttachmentField";
import { KriDialog } from "@/components/common/KriDialog";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { useDeleteNoticeMutation, useNoticeDetailQuery } from "@/query/notice";
import { useCentersQuery } from "@/query/center";
import { isAdminRole } from "@/types/auth";
export interface NoticeViewDialogProps {
noticeId: number | null;
onEdit: (noticeId: number) => void;
onDeleted: () => void;
}
export function NoticeViewDialog({ noticeId, onEdit, onDeleted }: NoticeViewDialogProps) {
const { isDialogOpen, hideDialog } = useDialog();
const open = isDialogOpen("noticeView");
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const detailQuery = useNoticeDetailQuery(open ? noticeId : null);
const centersQuery = useCentersQuery();
const deleteMutation = useDeleteNoticeMutation();
const notice = detailQuery.data;
const handleDelete = async () => {
if (noticeId === null) return;
if (!window.confirm("삭제되면 복구할 수 없습니다. 계속 진행하시겠습니까?")) return;
try {
await deleteMutation.mutateAsync(noticeId);
toast.success("공지사항을 삭제했습니다.");
hideDialog("noticeView");
onDeleted();
} catch (cause) {
toast.error(apiError(cause, { fallbackMessage: "삭제에 실패했습니다." }).message);
}
};
return (
<KriDialog
open={open}
onOpenChange={(next) => !next && hideDialog("noticeView")}
title={notice?.title ?? "공지사항"}
contentClassName="max-w-2xl"
footer={
admin ? (
<>
<Button type="button" variant="destructive" onClick={() => void handleDelete()} disabled={deleteMutation.isPending}>삭제</Button>
<Button type="button" variant="outline" onClick={() => noticeId !== null && onEdit(noticeId)}>수정</Button>
<Button type="button" variant="outline" onClick={() => hideDialog("noticeView")}>닫기</Button>
</>
) : (
<Button type="button" variant="outline" onClick={() => hideDialog("noticeView")}>닫기</Button>
)
}
>
{!notice ? (
<p className="text-sm text-muted-foreground">불러오는 중...</p>
) : (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-1 text-sm text-muted-foreground">
<span>{notice.regUser} · {notice.regDt?.slice(0, 10)}</span>
{admin ? (
<>
<span>· 공지 대상:</span>
<CenterTargetCell centerCds={notice.centerCds} centers={centersQuery.data ?? []} />
</>
) : null}
</div>
<div className="rounded-md border p-3" dangerouslySetInnerHTML={{ __html: notice.contentHtml }} />
<FileAttachmentField
existingFiles={notice.files}
keptFileIds={notice.files.map((file) => file.fileId)}
onKeptFileIdsChange={() => {}}
newFiles={[]}
onNewFilesChange={() => {}}
downloadPath={(fileId) => `/api/notices/${notice.noticeId}/files/${fileId}`}
disabled
/>
</div>
)}
</KriDialog>
);
}

View File

@@ -0,0 +1,135 @@
"use client";
import { useMemo, useState } from "react";
import type { ColumnDef, PaginationState, SortingState } from "@tanstack/react-table";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { ContentSearchBar } from "@/components/common/ContentSearchBar";
import { CenterTargetCell } from "@/components/common/CenterTargetCell";
import { DataTable } from "@/components/data-table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { useNoticeSearchQuery } from "@/query/notice";
import { useCentersQuery } from "@/query/center";
import { isAdminRole } from "@/types/auth";
import type { Notice } from "@/types/notice";
import { NoticeFormDialog } from "./NoticeFormDialog";
import { NoticeViewDialog } from "./NoticeViewDialog";
export default function NoticesPage() {
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const { showDialog } = useDialog();
const centersQuery = useCentersQuery();
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
const [sorting, setSorting] = useState<SortingState>([{ id: "regDt", desc: true }]);
const [keywordInput, setKeywordInput] = useState("");
const [searchKeyword, setSearchKeyword] = useState("");
const [targetCenterCds, setTargetCenterCds] = useState<string[]>([]);
const [selectedNoticeId, setSelectedNoticeId] = useState<number | null>(null);
const [editingNoticeId, setEditingNoticeId] = useState<number | null>(null);
const searchQuery = useNoticeSearchQuery({
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
sortBy: sorting[0]?.id ?? "regDt",
sortDir: sorting[0]?.desc === false ? "ASC" : "DESC",
searchKeyword: searchKeyword.trim() || undefined,
targetCenterCds: targetCenterCds.length ? targetCenterCds.map(Number) : undefined,
});
const totalElements = searchQuery.data?.totalElements ?? 0;
const centerOptions = useMemo(
() => (centersQuery.data ?? []).filter((center) => center.centerCd !== 0).map((center) => ({ label: center.centerName, value: String(center.centerCd) })),
[centersQuery.data],
);
const columns = useMemo<ColumnDef<Notice>[]>(() => {
const base: ColumnDef<Notice>[] = [
{
id: "noticeId",
header: "No.",
accessorFn: (row) => row.noticeId,
size: 70,
cell: ({ row }) => totalElements - pagination.pageIndex * pagination.pageSize - row.index,
},
{
accessorKey: "title",
header: "공지 제목",
cell: ({ row }) => (
<span className="flex items-center gap-2">
<span className="truncate">{row.original.title}</span>
{!admin && !row.original.viewed ? <Badge>N</Badge> : null}
</span>
),
},
];
if (admin) {
base.push({
id: "target",
header: "공지 대상",
size: 120,
cell: ({ row }) => <CenterTargetCell centerCds={row.original.centerCds} centers={centersQuery.data ?? []} />,
});
}
base.push(
{ accessorKey: "regUser", header: "게시자", size: 100 },
{ accessorKey: "regDt", header: "게시일", size: 110, cell: ({ row }) => row.original.regDt?.slice(0, 10) },
);
return base;
}, [admin, totalElements, pagination.pageIndex, pagination.pageSize, centersQuery.data]);
return (
<div className="space-y-4">
<AppPageTitle title="공지사항" description="세종학당재단 공지사항입니다." />
<Card>
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div className="min-w-0 flex-1">
<ContentSearchBar
keyword={keywordInput}
onKeywordChange={setKeywordInput}
onSubmit={() => { setSearchKeyword(keywordInput); setPagination((current) => ({ ...current, pageIndex: 0 })); }}
targetCenterCds={targetCenterCds}
onTargetCenterCdsChange={(values) => { setTargetCenterCds(values); setPagination((current) => ({ ...current, pageIndex: 0 })); }}
centerOptions={centerOptions}
showTargetFilter={admin}
placeholder="No., 제목, 게시자 검색"
/>
</div>
{admin ? (
<Button type="button" onClick={() => { setEditingNoticeId(null); showDialog("noticeForm"); }}>등록</Button>
) : null}
</CardHeader>
<CardContent className="px-4 bp-4">
<DataTable
columns={columns}
data={searchQuery.data?.content ?? []}
getRowId={(row) => String(row.noticeId)}
isClient={false}
pagination={pagination}
onPaginationChange={setPagination}
onSortingChange={setSorting}
pageCount={searchQuery.data?.totalPages ?? 0}
totalCount={totalElements}
selectMode="click-event"
onRowClick={(row) => { setSelectedNoticeId(row.noticeId); showDialog("noticeView"); }}
emptyText="등록된 공지사항이 없습니다."
/>
</CardContent>
</Card>
<NoticeViewDialog
noticeId={selectedNoticeId}
onEdit={(noticeId) => { setEditingNoticeId(noticeId); showDialog("noticeForm"); }}
onDeleted={() => searchQuery.refetch()}
/>
<NoticeFormDialog noticeId={editingNoticeId} onSaved={() => searchQuery.refetch()} />
</div>
);
}

View File

@@ -0,0 +1,22 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { AppPageTitle } from "@/components/app-shell";
import { useVisibleTopMenus } from "@/hooks/useVisibleTopMenus";
export default function MainPage() {
const router = useRouter();
const topMenus = useVisibleTopMenus();
const firstPath = topMenus[0]?.path;
useEffect(() => {
if (firstPath) router.replace(firstPath);
}, [firstPath, router]);
if (!firstPath) {
return <AppPageTitle title="사이트 준비중" description="사이트 오픈 준비중입니다." />;
}
return null;
}

View File

@@ -0,0 +1,80 @@
"use client";
import { useMemo, useState } from "react";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { MultiSelect } from "@/components/common/multi-select";
import { ExcelDownloadButton } from "@/components/report/ExcelDownloadButton";
import { exportReportToExcel } from "@/components/report/exportReportToExcel";
import { ReportTable, type ReportLeadingColumn } from "@/components/report/ReportTable";
import { useAuth } from "@/hooks/useAuth";
import { useCentersQuery } from "@/query/center";
import { useProgressReportQuery } from "@/query/report";
import { isAdminRole } from "@/types/auth";
const LEADING_COLUMNS: ReportLeadingColumn[] = [
{ key: "centerCd", label: "id", width: 64, sticky: true, render: (row) => row.centerCd },
{ key: "centerName", label: "학당명", width: 200, sticky: true, render: (row) => row.centerName },
{ key: "targetCount", label: "목표 표본", width: 100, render: (row) => row.targetCount },
{ key: "completeCount", label: "완료 수", width: 100, render: (row) => row.completeCount ?? "-" },
];
export default function ProgressPage() {
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const [selectedCenterCds, setSelectedCenterCds] = useState<string[]>([]);
const centersQuery = useCentersQuery();
const centerOptions = useMemo(
() => (centersQuery.data ?? []).filter((center) => center.centerCd !== 0).map((center) => ({ label: center.centerName, value: String(center.centerCd) })),
[centersQuery.data],
);
const reportQuery = useProgressReportQuery();
const content = useMemo(() => {
const rows = reportQuery.data?.content ?? [];
if (!admin || selectedCenterCds.length === 0) return rows;
const selected = new Set(selectedCenterCds.map(Number));
// centerCd 0(전체 집계 행)은 MultiSelect 선택 항목이 아니므로 항상 노출한다.
return rows.filter((row) => row.centerCd === 0 || selected.has(row.centerCd));
}, [reportQuery.data, admin, selectedCenterCds]);
const handleDownload = () => {
if (!reportQuery.data) return;
exportReportToExcel({
fileName: `진행현황_${new Date().toISOString().slice(0, 10)}.xlsx`,
sheetName: "진행현황",
headers: reportQuery.data.headers,
content,
scale: "current",
leadingColumns: LEADING_COLUMNS,
});
};
return (
<div className="space-y-4">
<AppPageTitle title="진행 현황" description="학당별 목표 표본 대비 설문 완료 현황입니다." />
<div className="flex items-center justify-between gap-2">
{admin ? (
<MultiSelect className="w-105" maxCount={2} options={centerOptions} defaultValue={selectedCenterCds} onValueChange={setSelectedCenterCds} placeholder="학당 선택 (전체)" />
) : (
<span />
)}
<ExcelDownloadButton disabled={!reportQuery.data} onClick={handleDownload} />
</div>
{reportQuery.isLoading ? (
<p className="text-sm text-muted-foreground">불러오는 중...</p>
) : (
<ReportTable
headers={reportQuery.data?.headers ?? []}
content={content}
scale="current"
leadingColumns={LEADING_COLUMNS}
mergeLeadingColumnsWhen={(row) => row.centerCd === 0}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,121 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { FileAttachmentField } from "@/components/common/FileAttachmentField";
import { KriEditor } from "@/components/kri-editor";
import { Button } from "@/components/ui/button";
import { useCreateQnaAnswerMutation, useDeleteQnaAnswerMutation, useUpdateQnaAnswerMutation } from "@/query/qna";
import type { QnaAnswer } from "@/types/qna";
export interface QnaAnswerSectionProps {
questionId: number;
answer: QnaAnswer | null;
admin: boolean;
onChanged: () => void;
}
export function QnaAnswerSection({ questionId, answer, admin, onChanged }: QnaAnswerSectionProps) {
const [editing, setEditing] = useState(false);
const [contentHtml, setContentHtml] = useState("");
const [keptFileIds, setKeptFileIds] = useState<number[]>([]);
const [newFiles, setNewFiles] = useState<File[]>([]);
const createMutation = useCreateQnaAnswerMutation(questionId);
const updateMutation = useUpdateQnaAnswerMutation(questionId);
const deleteMutation = useDeleteQnaAnswerMutation(questionId);
useEffect(() => {
setContentHtml(answer?.contentHtml ?? "");
setKeptFileIds((answer?.files ?? []).map((file) => file.fileId));
setNewFiles([]);
setEditing(false);
}, [answer]);
const canModify = admin && !answer?.viewed;
const saving = createMutation.isPending || updateMutation.isPending;
const handleSave = async () => {
if (!contentHtml.trim()) return toast.error("답변 내용을 입력해 주세요.");
const request = { contentHtml, ...(answer ? { keepFileIds: keptFileIds } : {}) };
try {
if (answer) await updateMutation.mutateAsync({ request, files: newFiles });
else await createMutation.mutateAsync({ request, files: newFiles });
toast.success("답변을 저장했습니다.");
setEditing(false);
onChanged();
} catch (cause) {
const errorInfo = apiError(cause, { fallbackMessage: "답변 저장에 실패했습니다." });
if (errorInfo.status === 409) toast.error("이미 확인된 답변은 수정할 수 없습니다.");
else toast.error(errorInfo.message);
}
};
const handleDelete = async () => {
if (!window.confirm("답변을 삭제하시겠습니까?")) return;
try {
await deleteMutation.mutateAsync();
toast.success("답변을 삭제했습니다.");
onChanged();
} catch (cause) {
const errorInfo = apiError(cause, { fallbackMessage: "답변 삭제에 실패했습니다." });
if (errorInfo.status === 409) toast.error("이미 확인된 답변은 삭제할 수 없습니다.");
else toast.error(errorInfo.message);
}
};
if (!answer && !admin) {
return <p className="text-sm text-muted-foreground">아직 등록된 답변이 없습니다.</p>;
}
if (!answer && admin && !editing) {
return (
<Button type="button" variant="outline" onClick={() => setEditing(true)}>답변 작성</Button>
);
}
if (editing) {
return (
<div className="space-y-3 rounded-md border p-3">
<KriEditor value={contentHtml} onChange={setContentHtml} />
<FileAttachmentField
existingFiles={answer?.files ?? []}
keptFileIds={keptFileIds}
onKeptFileIdsChange={setKeptFileIds}
newFiles={newFiles}
onNewFilesChange={setNewFiles}
downloadPath={(fileId) => `/api/qna-questions/${questionId}/answer/files/${fileId}`}
/>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={() => setEditing(false)}>취소</Button>
<Button type="button" onClick={() => void handleSave()} disabled={saving}>{saving ? "저장 중..." : "저장"}</Button>
</div>
</div>
);
}
return (
<div className="space-y-3 rounded-md border p-3">
<div className="text-sm text-muted-foreground">
답변자: {answer?.regUser} · {answer?.regDt?.slice(0, 10)}
</div>
<div dangerouslySetInnerHTML={{ __html: answer?.contentHtml ?? "" }} />
<FileAttachmentField
existingFiles={answer?.files ?? []}
keptFileIds={(answer?.files ?? []).map((file) => file.fileId)}
onKeptFileIdsChange={() => {}}
newFiles={[]}
onNewFilesChange={() => {}}
downloadPath={(fileId) => `/api/qna-questions/${questionId}/answer/files/${fileId}`}
disabled
/>
{canModify ? (
<div className="flex justify-end gap-2">
<Button type="button" variant="destructive" size="sm" onClick={() => void handleDelete()}>삭제</Button>
<Button type="button" variant="outline" size="sm" onClick={() => setEditing(true)}>수정</Button>
</div>
) : null}
</div>
);
}

View File

@@ -0,0 +1,105 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { FileAttachmentField } from "@/components/common/FileAttachmentField";
import { KriDialog } from "@/components/common/KriDialog";
import { KriEditor } from "@/components/kri-editor";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useDialog } from "@/hooks/useDialog";
import { useCreateQnaQuestionMutation, useQnaQuestionDetailQuery, useUpdateQnaQuestionMutation } from "@/query/qna";
import type { QnaQuestion } from "@/types/qna";
export interface QnaFormDialogProps {
questionId: number | null;
onSaved: () => void;
}
export function QnaFormDialog({ questionId, onSaved }: QnaFormDialogProps) {
const { isDialogOpen, hideDialog } = useDialog();
const open = isDialogOpen("qnaForm");
const isEdit = questionId !== null;
const detailQuery = useQnaQuestionDetailQuery(isEdit ? questionId : null);
const createMutation = useCreateQnaQuestionMutation();
const updateMutation = useUpdateQnaQuestionMutation(questionId ?? 0);
const [title, setTitle] = useState("");
const [contentHtml, setContentHtml] = useState("");
const [keptFileIds, setKeptFileIds] = useState<number[]>([]);
const [newFiles, setNewFiles] = useState<File[]>([]);
const resetFrom = (question: QnaQuestion | undefined) => {
setTitle(question?.title ?? "");
setContentHtml(question?.contentHtml ?? "");
setKeptFileIds((question?.files ?? []).map((file) => file.fileId));
setNewFiles([]);
};
useEffect(() => {
if (!open) return;
resetFrom(isEdit ? detailQuery.data : undefined);
}, [open, isEdit, detailQuery.data]);
const saving = createMutation.isPending || updateMutation.isPending;
const handleSave = async () => {
if (!title.trim()) return toast.error("제목을 입력해 주세요.");
if (!contentHtml.trim()) return toast.error("내용을 입력해 주세요.");
const request = {
title: title.trim(),
contentHtml,
...(isEdit ? { keepFileIds: keptFileIds } : {}),
};
try {
if (isEdit) await updateMutation.mutateAsync({ request, files: newFiles });
else await createMutation.mutateAsync({ request, files: newFiles });
toast.success(isEdit ? "문의를 수정했습니다." : "문의를 등록했습니다.");
hideDialog("qnaForm");
onSaved();
} catch (cause) {
const errorInfo = apiError(cause, { fallbackMessage: "저장에 실패했습니다." });
if (errorInfo.status === 409) toast.error("이미 답변이 등록되어 수정할 수 없습니다.");
else toast.error(errorInfo.message);
}
};
return (
<KriDialog
open={open}
onOpenChange={(next) => !next && hideDialog("qnaForm")}
title={isEdit ? "문의 수정" : "문의 등록"}
contentClassName="w-[calc(100vw-2rem)] max-w-[84rem] sm:max-w-[84rem] max-h-[calc(100vh-2rem)]"
bodyClassName="min-w-0 overflow-x-hidden"
footer={
<>
<Button type="button" variant="outline" onClick={() => hideDialog("qnaForm")}>취소</Button>
<Button type="button" onClick={() => void handleSave()} disabled={saving}>{saving ? "저장 중..." : "저장"}</Button>
</>
}
>
<div className="min-w-0 space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">제목</label>
<Input value={title} onChange={(event) => setTitle(event.currentTarget.value)} maxLength={128} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium">내용</label>
<KriEditor value={contentHtml} onChange={setContentHtml} />
</div>
<FileAttachmentField
existingFiles={detailQuery.data?.files ?? []}
keptFileIds={keptFileIds}
onKeptFileIdsChange={setKeptFileIds}
newFiles={newFiles}
onNewFilesChange={setNewFiles}
downloadPath={(fileId) => `/api/qna-questions/${questionId}/files/${fileId}`}
/>
</div>
</KriDialog>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import { toast } from "sonner";
import { apiError } from "@kri/common/http";
import { FileAttachmentField } from "@/components/common/FileAttachmentField";
import { KriDialog } from "@/components/common/KriDialog";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { useDeleteQnaQuestionMutation, useQnaQuestionDetailQuery } from "@/query/qna";
import { isAdminRole } from "@/types/auth";
import { QnaAnswerSection } from "./QnaAnswerSection";
export interface QnaViewDialogProps {
questionId: number | null;
onEdit: (questionId: number) => void;
onChanged: () => void;
}
export function QnaViewDialog({ questionId, onEdit, onChanged }: QnaViewDialogProps) {
const { isDialogOpen, hideDialog } = useDialog();
const open = isDialogOpen("qnaView");
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const detailQuery = useQnaQuestionDetailQuery(open ? questionId : null);
const deleteMutation = useDeleteQnaQuestionMutation();
const question = detailQuery.data;
const canModifyQuestion = !admin && !question?.answer;
const handleDelete = async () => {
if (questionId === null) return;
if (!window.confirm("삭제되면 복구할 수 없습니다. 계속 진행하시겠습니까?")) return;
try {
await deleteMutation.mutateAsync(questionId);
toast.success("문의를 삭제했습니다.");
hideDialog("qnaView");
onChanged();
} catch (cause) {
const errorInfo = apiError(cause, { fallbackMessage: "삭제에 실패했습니다." });
if (errorInfo.status === 409) toast.error("이미 답변이 등록되어 삭제할 수 없습니다.");
else toast.error(errorInfo.message);
}
};
return (
<KriDialog
open={open}
onOpenChange={(next) => !next && hideDialog("qnaView")}
title={question?.title ?? "1:1 문의"}
contentClassName="max-w-2xl"
footer={
<>
{canModifyQuestion ? (
<>
<Button type="button" variant="destructive" onClick={() => void handleDelete()} disabled={deleteMutation.isPending}>삭제</Button>
<Button type="button" variant="outline" onClick={() => questionId !== null && onEdit(questionId)}>수정</Button>
</>
) : null}
<Button type="button" variant="outline" onClick={() => hideDialog("qnaView")}>닫기</Button>
</>
}
>
{!question ? (
<p className="text-sm text-muted-foreground">불러오는 중...</p>
) : (
<div className="space-y-4">
<div className="text-sm text-muted-foreground">
{question.regUser} · {question.regDt?.slice(0, 10)}
{admin ? ` · ${question.centerName}` : ""}
</div>
<div className="rounded-md border p-3" dangerouslySetInnerHTML={{ __html: question.contentHtml }} />
<FileAttachmentField
existingFiles={question.files}
keptFileIds={question.files.map((file) => file.fileId)}
onKeptFileIdsChange={() => {}}
newFiles={[]}
onNewFilesChange={() => {}}
downloadPath={(fileId) => `/api/qna-questions/${question.questionId}/files/${fileId}`}
disabled
/>
<div className="space-y-2">
<p className="text-sm font-medium">답변</p>
<QnaAnswerSection
questionId={question.questionId}
answer={question.answer}
admin={admin}
onChanged={() => { detailQuery.refetch(); onChanged(); }}
/>
</div>
</div>
)}
</KriDialog>
);
}

View File

@@ -0,0 +1,136 @@
"use client";
import { useMemo, useState } from "react";
import type { ColumnDef, PaginationState, SortingState } from "@tanstack/react-table";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { ContentSearchBar } from "@/components/common/ContentSearchBar";
import { DataTable } from "@/components/data-table";
import { Button } from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { useQnaQuestionSearchQuery } from "@/query/qna";
import { useCentersQuery } from "@/query/center";
import { isAdminRole, isCenterRole } from "@/types/auth";
import type { QnaQuestion } from "@/types/qna";
import { QnaFormDialog } from "./QnaFormDialog";
import { QnaViewDialog } from "./QnaViewDialog";
export default function QnaPage() {
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const center = isCenterRole(auth.user?.userRole);
const { showDialog } = useDialog();
const centersQuery = useCentersQuery();
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
const [sorting, setSorting] = useState<SortingState>([{ id: "regDt", desc: true }]);
const [keywordInput, setKeywordInput] = useState("");
const [searchKeyword, setSearchKeyword] = useState("");
const [targetCenterCds, setTargetCenterCds] = useState<string[]>([]);
const [selectedQuestionId, setSelectedQuestionId] = useState<number | null>(null);
const [editingQuestionId, setEditingQuestionId] = useState<number | null>(null);
const searchQuery = useQnaQuestionSearchQuery({
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
sortBy: sorting[0]?.id ?? "regDt",
sortDir: sorting[0]?.desc === false ? "ASC" : "DESC",
searchKeyword: searchKeyword.trim() || undefined,
targetCenterCds: targetCenterCds.length ? targetCenterCds.map(Number) : undefined,
});
const totalElements = searchQuery.data?.totalElements ?? 0;
const centerOptions = useMemo(
() => (centersQuery.data ?? []).filter((center) => center.centerCd !== 0).map((center) => ({ label: center.centerName, value: String(center.centerCd) })),
[centersQuery.data],
);
const columns = useMemo<ColumnDef<QnaQuestion>[]>(() => {
const base: ColumnDef<QnaQuestion>[] = [
{
id: "questionId",
header: "No.",
accessorFn: (row) => row.questionId,
size: 70,
cell: ({ row }) => totalElements - pagination.pageIndex * pagination.pageSize - row.index,
},
{ accessorKey: "title", header: "문의 제목" },
{ accessorKey: "regUser", header: "게시자", size: 100 },
{ accessorKey: "regDt", header: "게시일", size: 110, cell: ({ row }) => row.original.regDt?.slice(0, 10) },
];
if (admin) {
base.push({ accessorKey: "centerName", header: "학당명", size: 140 });
}
base.push({
id: "answerDt",
header: "답변일",
accessorFn: (row) => row.answer?.regDt ?? "",
size: 110,
cell: ({ row }) => row.original.answer?.regDt?.slice(0, 10) ?? "-",
});
if (admin) {
base.push({
id: "viewDt",
header: "확인일",
accessorFn: (row) => row.answer?.viewDt ?? "",
size: 110,
cell: ({ row }) => (row.original.answer?.viewed ? (row.original.answer.viewDt?.slice(0, 10) ?? "-") : "-"),
});
}
return base;
}, [admin, totalElements, pagination.pageIndex, pagination.pageSize]);
return (
<div className="space-y-4">
<AppPageTitle title="1:1 문의" description="학당별 문의와 답변입니다." />
<Card>
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div className="min-w-0 flex-1">
<ContentSearchBar
keyword={keywordInput}
onKeywordChange={setKeywordInput}
onSubmit={() => { setSearchKeyword(keywordInput); setPagination((current) => ({ ...current, pageIndex: 0 })); }}
targetCenterCds={targetCenterCds}
onTargetCenterCdsChange={(values) => { setTargetCenterCds(values); setPagination((current) => ({ ...current, pageIndex: 0 })); }}
centerOptions={centerOptions}
showTargetFilter={admin}
placeholder="No., 제목, 게시자 검색"
/>
</div>
{center ? (
<Button type="button" onClick={() => { setEditingQuestionId(null); showDialog("qnaForm"); }}>등록</Button>
) : null}
</CardHeader>
<CardContent className="px-4 pb-4">
<DataTable
columns={columns}
data={searchQuery.data?.content ?? []}
getRowId={(row) => String(row.questionId)}
isClient={false}
pagination={pagination}
onPaginationChange={setPagination}
onSortingChange={setSorting}
pageCount={searchQuery.data?.totalPages ?? 0}
totalCount={totalElements}
selectMode="click-event"
onRowClick={(row) => { setSelectedQuestionId(row.questionId); showDialog("qnaView"); }}
emptyText="등록된 문의가 없습니다."
/>
</CardContent>
</Card>
<QnaViewDialog
questionId={selectedQuestionId}
onEdit={(questionId) => { setEditingQuestionId(questionId); showDialog("qnaForm"); }}
onChanged={() => searchQuery.refetch()}
/>
<QnaFormDialog questionId={editingQuestionId} onSaved={() => searchQuery.refetch()} />
</div>
);
}

View File

@@ -0,0 +1,72 @@
"use client";
import { useMemo, useState } from "react";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { MultiSelect } from "@/components/common/multi-select";
import { ExcelDownloadButton } from "@/components/report/ExcelDownloadButton";
import { exportReportToExcel } from "@/components/report/exportReportToExcel";
import { ReportTable, type ReportLeadingColumn } from "@/components/report/ReportTable";
import { useAuth } from "@/hooks/useAuth";
import { useCentersQuery } from "@/query/center";
import { useFinalReportQuery } from "@/query/report";
import { isAdminRole } from "@/types/auth";
const LEADING_COLUMNS: ReportLeadingColumn[] = [
{ key: "centerName", label: "학당명", width: 200, sticky: true, render: (row) => row.centerName },
{ key: "completeCount", label: "완료 수", width: 100, render: (row) => row.completeCount ?? 0 },
];
export default function ReportPage() {
const { auth } = useAuth();
const admin = isAdminRole(auth.user?.userRole);
const [selectedCenterCds, setSelectedCenterCds] = useState<string[]>([]);
const centersQuery = useCentersQuery();
const centerOptions = useMemo(
() => (centersQuery.data ?? []).filter((center) => center.centerCd !== 0).map((center) => ({ label: center.centerName, value: String(center.centerCd) })),
[centersQuery.data],
);
const reportQuery = useFinalReportQuery();
const content = useMemo(() => {
const rows = reportQuery.data?.content ?? [];
if (!admin || selectedCenterCds.length === 0) return rows;
const selected = new Set(selectedCenterCds.map(Number));
// centerCd 0(전체 집계 행)은 MultiSelect 선택 항목이 아니므로 항상 노출한다.
return rows.filter((row) => row.centerCd === 0 || selected.has(row.centerCd));
}, [reportQuery.data, admin, selectedCenterCds]);
const handleDownload = () => {
if (!reportQuery.data) return;
exportReportToExcel({
fileName: `종합결과_${new Date().toISOString().slice(0, 10)}.xlsx`,
sheetName: "종합결과",
headers: reportQuery.data.headers,
content,
scale: "final",
leadingColumns: LEADING_COLUMNS,
});
};
return (
<div className="space-y-4">
<AppPageTitle title="종합 결과" description="학당별 최종 만족도 결과입니다." />
<div className="flex items-center justify-between gap-2">
{admin ? (
<MultiSelect className="w-105" maxCount={2} options={centerOptions} defaultValue={selectedCenterCds} onValueChange={setSelectedCenterCds} placeholder="학당 선택 (전체)" />
) : (
<span />
)}
<ExcelDownloadButton disabled={!reportQuery.data} onClick={handleDownload} />
</div>
{reportQuery.isLoading ? (
<p className="text-sm text-muted-foreground">불러오는 중...</p>
) : (
<ReportTable headers={reportQuery.data?.headers ?? []} content={content} scale="final" leadingColumns={LEADING_COLUMNS} />
)}
</div>
);
}

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-muted/40 p-4">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="pb-8">
<div className="flex justify-center">
<Image src="/logo.png" alt="로고" width={240} height={120} className="h-24 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,12 @@
import { NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApi } from "@/lib/http-server";
export async function GET() {
try {
const serverApi = await createServerApi();
return NextResponse.json(await serverApi.get<unknown>("/centers"));
} catch (error: unknown) {
return errorToResponse(error);
}
}

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,33 @@
import { NextRequest, NextResponse } from "next/server";
import type { LoginRequest } 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";
import type { AuthUser } from "@/types/auth";
type LoginResponse = { accessToken: string; user: AuthUser };
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,27 @@
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[]) => `/menus${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
export async function GET(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
return NextResponse.json(await serverApi.get<unknown>(apiPath(slug)));
} 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 body = await request.json().catch(() => undefined);
return NextResponse.json(await serverApi.put<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApi, proxyBinaryDownload } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/notices${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result);
const isFileDownload = (slug: string[]) => slug.length === 3 && slug[1] === "files";
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
if (isFileDownload(slug)) return proxyBinaryDownload(apiPath(slug));
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 DELETE(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
return toResponse(await serverApi.del<unknown>(apiPath(slug)));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,58 @@
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[]) => `/popups${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 DELETE(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
return toResponse(await serverApi.del<unknown>(apiPath(slug)));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApi, proxyBinaryDownload } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/qna-questions${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result);
const isFileDownload = (slug: string[]) =>
(slug.length === 3 && slug[1] === "files") ||
(slug.length === 4 && slug[1] === "answer" && slug[2] === "files");
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
if (isFileDownload(slug)) return proxyBinaryDownload(apiPath(slug));
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 DELETE(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
return toResponse(await serverApi.del<unknown>(apiPath(slug)));
} 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[]) => `/reports${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);
}
}

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

@@ -0,0 +1,88 @@
@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);
--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;
--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: #004C97;
--primary-foreground: oklch(0.985 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.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
}
.dark {
--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: #004C97;
--primary-foreground: oklch(0.985 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.269 0 0);
--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: oklch(0.556 0 0);
}
@layer base {
* { @apply border-border outline-ring/50; }
body { @apply bg-background text-foreground; }
button:not(:disabled) { cursor: pointer; }
}
.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: "세종학당재단 만족도 조사 시스템",
description: "세종학당재단 만족도 조사 시스템",
icons: { icon: "/favicon.ico" }
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="ko">
<body className="h-screen overflow-hidden 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,78 @@
"use client";
import { useEffect, useState } from "react";
import { KriDialog } from "@/components/common/KriDialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { useAuth } from "@/hooks/useAuth";
import { useActivePopupsQuery } from "@/query/popup";
import { CookieKeys } from "@/store/cookie/cookie-keys";
import { cookieStore } from "@/store/cookie/client-cookie";
import { isCenterRole } from "@/types/auth";
const readHiddenPopupIds = () => {
const raw = cookieStore.get(CookieKeys.PopupHideToday);
if (!raw) return [];
try {
const parsed: unknown = JSON.parse(raw);
return Array.isArray(parsed) ? parsed.filter((value): value is number => typeof value === "number") : [];
} catch {
return [];
}
};
const getEndOfToday = () => {
const end = new Date();
end.setHours(24, 0, 0, 0);
return end;
};
export function ActivePopupGate() {
const { auth } = useAuth();
// 활성 팝업 조회 API는 백엔드에서 Center 역할 전용이며, 관리자로 호출하면 403이 발생해
// 공용 HTTP 클라이언트의 기본 403 처리(로그아웃)가 실행되어 로그인 화면으로 튕겨나간다.
const activePopupsQuery = useActivePopupsQuery(isCenterRole(auth.user?.userRole));
const [dismissedIds, setDismissedIds] = useState<number[]>([]);
const [hiddenIds] = useState<number[]>(() => readHiddenPopupIds());
const [hideTodayChecked, setHideTodayChecked] = useState(false);
const popups = activePopupsQuery.data ?? [];
const current = popups.find((popup) => !dismissedIds.includes(popup.popupId) && !hiddenIds.includes(popup.popupId));
useEffect(() => {
setHideTodayChecked(false);
}, [current?.popupId]);
if (!current) return null;
const dismiss = () => setDismissedIds((ids) => [...ids, current.popupId]);
const hideToday = () => {
const nextHiddenIds = [...new Set([...readHiddenPopupIds(), current.popupId])];
cookieStore.set(CookieKeys.PopupHideToday, JSON.stringify(nextHiddenIds), { expires: getEndOfToday() });
setHideTodayChecked(true);
};
return (
<KriDialog
open
onOpenChange={(next) => !next && dismiss()}
onInteractOutside={(event) => event.preventDefault()}
title={current.title}
contentClassName="max-w-lg"
footerClassName="sm:justify-between"
footer={
<>
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<Checkbox checked={hideTodayChecked} onCheckedChange={(checked) => checked === true && hideToday()} />
오늘 하루 보지 않기
</label>
<Button type="button" onClick={dismiss}>닫기</Button>
</>
}
>
<div dangerouslySetInnerHTML={{ __html: current.contentHtml }} />
</KriDialog>
);
}

View File

@@ -0,0 +1,51 @@
"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 { TopMenuItem } from "@/config/menu.type";
import type { AuthUser } from "@/types/auth";
interface AppHeaderProps {
menus: TopMenuItem[];
menuOpen: boolean;
showMenuButton: boolean;
activeMenuId?: string;
user?: AuthUser | null;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
}
export function AppHeader({ menus, menuOpen, showMenuButton, activeMenuId, user, onToggleMenu, onNavigate }: AppHeaderProps) {
return (
<KriHeader
logo={<Image src="/logo.png" alt="로고" width={120} height={40} className="h-10 w-auto object-contain" priority />}
menus={menus}
activeMenuId={activeMenuId}
menuOpen={menuOpen}
showMenuButton={showMenuButton}
onToggleMenu={onToggleMenu}
onNavigate={onNavigate}
/*
center={
<p
className="absolute left-1/2 top-1/2 max-w-[32rem] -translate-x-1/2 -translate-y-1/2 truncate text-lg font-semibold text-primary md:text-lg"
title="세종학당재단 2026년 한국어교육 수요 및 만족도 조사"
>
세종학당재단 2026년 한국어교육 수요 및 만족도 조사
</p>
}
*/
right={
<>
<span className="hidden text-sm text-muted-foreground sm:inline">{user?.userName ?? ""}</span>
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
<LogOut className="size-4" />
<span className="hidden sm:inline">로그아웃</span>
</Button>
</>
}
/>
);
}

View File

@@ -0,0 +1,49 @@
"use client";
import { useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import { ActivePopupGate } from "./ActivePopupGate";
import { AppHeader } from "./AppHeader";
import { AppSidebar } from "./AppSidebar";
import { sideMenus } from "@/config/menu.data";
import { useAuth } from "@/hooks/useAuth";
import { useVisibleTopMenus } from "@/hooks/useVisibleTopMenus";
export function AppMainLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const { auth } = useAuth();
const topMenus = useVisibleTopMenus();
const [menuOpen, setMenuOpen] = useState(true);
const activeMenuId = useMemo(
() => topMenus.find((item) => item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)))?.id,
[pathname, topMenus],
);
const navigate = (path: string) => router.push(path);
const hasSidebar = sideMenus.length > 0;
return (
<KriMainLayout
sidebarOpen={hasSidebar && menuOpen}
onSidebarOpenChange={setMenuOpen}
header={
<AppHeader
menus={topMenus}
menuOpen={menuOpen}
showMenuButton={hasSidebar}
activeMenuId={activeMenuId}
user={auth.user}
onToggleMenu={() => setMenuOpen((current) => !current)}
onNavigate={navigate}
/>
}
sidebar={hasSidebar ? <AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} onNavigate={navigate} /> : undefined}
>
{children}
<ActivePopupGate />
</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 { SideMenuItem } from "@/config/menu.type";
interface AppSidebarProps {
items: SideMenuItem[];
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,53 @@
"use client";
import { useState, type MouseEvent } from "react";
import type { Center } from "@/types/center";
interface CenterTargetCellProps {
centerCds: number[];
centers: Center[];
}
export function CenterTargetCell({ centerCds, centers }: CenterTargetCellProps) {
const [tooltipPosition, setTooltipPosition] = useState<{ top: number; left: number } | null>(null);
if (centerCds.length === 0) return <span>전체</span>;
const centerNameByCd = new Map(centers.map((center) => [center.centerCd, center.centerName]));
const centerNames = centerCds.map((centerCd) => centerNameByCd.get(centerCd) ?? String(centerCd));
const handleTargetMouseEnter = (event: MouseEvent<HTMLSpanElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
const width = Math.min(672, window.innerWidth - 32);
const left = Math.min(
Math.max(rect.left + rect.width / 2 - width / 2, 16),
window.innerWidth - width - 16,
);
setTooltipPosition({ top: rect.bottom + 4, left });
};
return (
<span className="group relative inline-flex">
<span
className="cursor-help underline decoration-dotted underline-offset-4"
aria-label={`대상 학당 ${centerCds.length}개`}
onMouseEnter={handleTargetMouseEnter}
>
{centerCds.length}개 학당
</span>
<span
role="tooltip"
className="pointer-events-auto invisible fixed z-50 max-h-64 w-[min(42rem,calc(100vw-2rem))] overflow-x-hidden overflow-y-auto rounded-md border bg-popover px-3 py-2 text-left text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-hover:visible group-hover:opacity-100"
style={tooltipPosition ? { top: tooltipPosition.top, left: tooltipPosition.left } : undefined}
>
<span className="grid grid-cols-1 gap-x-6 gap-y-1 sm:grid-cols-2">
{centerNames.map((name, index) => (
<span key={`${name}-${index}`} className="min-w-0 break-words leading-5">
<span className="mr-1 text-muted-foreground">•</span>
{name}
</span>
))}
</span>
</span>
</span>
);
}

View File

@@ -0,0 +1,60 @@
"use client";
import type { FormEvent } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { MultiSelect } from "@/components/common/multi-select";
export interface ContentSearchBarProps {
keyword: string;
onKeywordChange: (value: string) => void;
onSubmit: () => void;
targetCenterCds: string[];
onTargetCenterCdsChange: (values: string[]) => void;
centerOptions: { label: string; value: string }[];
showTargetFilter: boolean;
placeholder: string;
}
export function ContentSearchBar({
keyword,
onKeywordChange,
onSubmit,
targetCenterCds,
onTargetCenterCdsChange,
centerOptions,
showTargetFilter,
placeholder,
}: ContentSearchBarProps) {
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSubmit();
};
return (
<form className="flex flex-wrap items-end gap-2" onSubmit={handleSubmit}>
<div className="min-w-60 flex-1 space-y-1">
<label htmlFor="content-search-keyword" className="text-sm font-medium">검색</label>
<Input
id="content-search-keyword"
value={keyword}
onChange={(event) => onKeywordChange(event.currentTarget.value)}
placeholder={placeholder}
/>
</div>
{showTargetFilter ? (
<div className="w-72 space-y-1">
<label className="text-sm font-medium">대상 학당</label>
<MultiSelect
modalPopover={false}
options={centerOptions}
defaultValue={targetCenterCds}
onValueChange={onTargetCenterCdsChange}
placeholder="전체 학당"
/>
</div>
) : null}
<Button type="submit" variant="secondary">검색</Button>
</form>
);
}

View File

@@ -0,0 +1,109 @@
"use client";
import { useRef } from "react";
import { Paperclip, X } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { downloadFromProxy } from "@/lib/download";
import type { FileItem } from "@/types/file";
const MAX_FILES = 5;
const MAX_FILE_BYTES = 5 * 1024 * 1024;
const BLOCKED_EXTENSIONS = [".exe"];
export interface FileAttachmentFieldProps {
existingFiles: FileItem[];
keptFileIds: number[];
onKeptFileIdsChange: (ids: number[]) => void;
newFiles: File[];
onNewFilesChange: (files: File[]) => void;
downloadPath: (fileId: number) => string;
disabled?: boolean;
}
export function FileAttachmentField({
existingFiles,
keptFileIds,
onKeptFileIdsChange,
newFiles,
onNewFilesChange,
downloadPath,
disabled = false,
}: FileAttachmentFieldProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
const keptFiles = existingFiles.filter((file) => keptFileIds.includes(file.fileId));
const totalCount = keptFiles.length + newFiles.length;
const handlePick = (event: React.ChangeEvent<HTMLInputElement>) => {
const picked = Array.from(event.target.files ?? []);
event.target.value = "";
if (!picked.length) return;
const accepted: File[] = [];
for (const file of picked) {
if (totalCount + accepted.length >= MAX_FILES) {
toast.error(`첨부파일은 최대 ${MAX_FILES}개까지 등록할 수 있습니다.`);
break;
}
if (BLOCKED_EXTENSIONS.some((ext) => file.name.toLowerCase().endsWith(ext))) {
toast.error(`${file.name}: .exe 파일은 첨부할 수 없습니다.`);
continue;
}
if (file.size > MAX_FILE_BYTES) {
toast.error(`${file.name}: 파일 용량은 최대 5MB까지 첨부할 수 있습니다.`);
continue;
}
accepted.push(file);
}
if (accepted.length) onNewFilesChange([...newFiles, ...accepted]);
};
return (
<div className="space-y-2">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">첨부 파일</span>
{!disabled ? (
<Button type="button" variant="outline" size="sm" onClick={() => inputRef.current?.click()} disabled={totalCount >= MAX_FILES}>
<Paperclip className="size-3.5" />
파일 추가
</Button>
) : null}
<input ref={inputRef} type="file" multiple className="hidden" onChange={handlePick} />
</div>
{totalCount === 0 ? (
<p className="text-sm text-muted-foreground">첨부된 파일이 없습니다.</p>
) : (
<ul className="space-y-1">
{keptFiles.map((file) => (
<li key={`existing-${file.fileId}`} className="flex w-fit max-w-full items-center gap-2 rounded-md border px-2 py-1 text-sm">
<button
type="button"
className="min-w-0 flex-1 break-all text-left text-primary underline-offset-2 hover:underline"
onClick={() => downloadFromProxy(downloadPath(file.fileId), file.fileName).catch(() => toast.error("파일을 다운로드하지 못했습니다."))}
>
{file.fileName}
</button>
{!disabled ? (
<button type="button" aria-label="첨부 제거" onClick={() => onKeptFileIdsChange(keptFileIds.filter((id) => id !== file.fileId))}>
<X className="size-4 text-red-500 hover:text-red-700" />
</button>
) : null}
</li>
))}
{newFiles.map((file, index) => (
<li key={`new-${index}-${file.name}`} className="flex w-fit max-w-full items-center gap-2 rounded-md border px-2 py-1 text-sm">
<span className="min-w-0 flex-1 break-all">{file.name}</span>
{!disabled ? (
<button type="button" aria-label="첨부 제거" onClick={() => onNewFilesChange(newFiles.filter((_, i) => i !== index))}>
<X className="size-4 text-red-500 hover:text-red-700" />
</button>
) : null}
</li>
))}
</ul>
)}
</div>
);
}

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,152 @@
'use client'
import * as React from 'react'
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 { KriTimePicker } from '@/components/common/KriTimePicker'
import { cn } from '@/lib/utils'
export type KriDateTimePickerProps = {
value: string
onChange: (value: string) => void
placeholder?: string
className?: string
triggerClassName?: string
contentClassName?: string
disabled?: boolean
modalPopover?: boolean
startHour?: number
endHour?: number
minuteStep?: number
hourLabel?: string
minuteLabel?: string
}
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
if (!value) return { date: undefined, time: '' }
const [datePart, timePart = ''] = value.split('T')
const [year, month, day] = datePart.split('-').map(Number)
if (!year || !month || !day) return { date: undefined, time: timePart }
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return { date: undefined, time: timePart }
}
return { date, time: timePart }
}
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}`
}
const toValue = (date: Date | undefined, time: string): string => {
const dateText = formatDate(date)
if (!dateText) return ''
return `${dateText}T${time || '00:00'}`
}
const toDisplayText = (date: Date | undefined, time: string, placeholder: string) => {
const dateText = formatDate(date)
if (!dateText) return placeholder
return `${dateText} ${time || '00:00'}`
}
export function KriDateTimePicker({
value,
onChange,
placeholder = '날짜/시간 선택',
className,
triggerClassName,
contentClassName,
disabled = false,
modalPopover = true,
startHour,
endHour,
minuteStep,
hourLabel,
minuteLabel,
}: KriDateTimePickerProps) {
const [open, setOpen] = React.useState(false)
const { date, time } = parseDateTime(value)
const hasValue = date !== undefined
const handleDateSelect = (nextDate: Date | undefined) => {
if (!nextDate) return
onChange(toValue(nextDate, time || '00:00'))
}
const handleTimeChange = (nextTime: string) => {
if (!date) return
onChange(toValue(date, nextTime))
}
return (
<div className={cn('relative', className)}>
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
<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="mr-2 h-4 w-4" />
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
</Button>
</PopoverTrigger>
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
<div className="sm:flex">
<Calendar
mode="single"
selected={date}
onSelect={handleDateSelect}
autoFocus
/>
<KriTimePicker
value={time || '00:00'}
onChange={handleTimeChange}
disabled={!date}
startHour={startHour}
endHour={endHour}
minuteStep={minuteStep}
hourLabel={hourLabel}
minuteLabel={minuteLabel}
/>
</div>
</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('')
}}
aria-label="날짜/시간 초기화"
>
<X className="h-3.5 w-3.5" />
</button>
) : null}
</div>
)
}
export default KriDateTimePicker

View File

@@ -0,0 +1,78 @@
'use client'
import type { ComponentProps, 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
onInteractOutside?: ComponentProps<typeof DialogContent>["onInteractOutside"]
}
export function KriDialog({
open,
onOpenChange,
title,
description,
children,
footer,
showDefaultFooter = true,
closeLabel = '닫기',
showCloseButton = true,
contentClassName,
bodyClassName,
footerClassName,
onInteractOutside,
}: KriDialogProps) {
const renderFooter = () => {
if (footer !== undefined) {
if (footer === null) return null
return <DialogFooter className={cn('border-t border-primary/20 bg-primary/5 px-6 py-3', footerClassName)}>{footer}</DialogFooter>
}
if (!showDefaultFooter) return null
return (
<DialogFooter className={cn('border-t border-primary/20 bg-primary/5 px-6 py-3', footerClassName)}>
<DialogClose asChild>
<Button type="button" variant="outline">
{closeLabel}
</Button>
</DialogClose>
</DialogFooter>
)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className={cn('p-0', contentClassName)} showCloseButton={showCloseButton} onInteractOutside={onInteractOutside}>
<DialogHeader className="border-b border-primary/20 bg-primary/10 px-6 pb-3 pt-6">
<DialogTitle>{title}</DialogTitle>
{description ? <DialogDescription>{description}</DialogDescription> : null}
</DialogHeader>
<div className={cn('min-h-0 overflow-y-auto px-6 py-4 bg-white', 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,128 @@
'use client'
import { Button } from '@/components/ui/button'
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
import { cn } from '@/lib/utils'
export type KriTimePickerProps = {
value?: string
onChange: (value: string) => void
disabled?: boolean
minuteStep?: number
startHour?: number
endHour?: number
hourLabel?: string
minuteLabel?: string
className?: string
}
const parseTime = (value: string | undefined) => {
if (!value) return { hour: undefined, minute: undefined }
const [hour, minute] = value.split(':').map(Number)
return {
hour: Number.isInteger(hour) && hour >= 0 && hour < 24 ? hour : undefined,
minute: Number.isInteger(minute) && minute >= 0 && minute < 60 ? minute : undefined,
}
}
const formatTime = (hour: number, minute: number) => {
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
}
const normalizeHour = (hour: number, fallback: number) => {
return Number.isFinite(hour) ? Math.min(23, Math.max(0, Math.trunc(hour))) : fallback
}
export function KriTimePicker({
value,
onChange,
disabled = false,
minuteStep = 5,
startHour = 0,
endHour = 23,
hourLabel = '시',
minuteLabel = '분',
className,
}: KriTimePickerProps) {
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
? Math.min(Math.floor(minuteStep), 60)
: 5
const clampedStartHour = normalizeHour(startHour, 0)
const clampedEndHour = normalizeHour(endHour, 23)
// startHour > endHour로 잘못 지정된 경우, 두 값을 뒤바꿔 유효한 범위로 되돌린다.
const [normalizedStartHour, normalizedEndHour] = clampedStartHour > clampedEndHour
? [clampedEndHour, clampedStartHour]
: [clampedStartHour, clampedEndHour]
const hours = Array.from(
{ length: normalizedEndHour - normalizedStartHour + 1 },
(_, index) => normalizedStartHour + index,
)
const minutes = Array.from(
{ length: Math.ceil(60 / normalizedMinuteStep) },
(_, index) => index * normalizedMinuteStep,
).filter((minute) => minute < 60)
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
if (disabled) return
const nextHour = type === 'hour' ? nextValue : selectedHour ?? normalizedStartHour
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
onChange(formatTime(nextHour, nextMinute))
}
return (
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
<div className="flex min-h-0 flex-1 flex-col">
<div className="mt-1 p-1 align-middle text-center text-base border-b">{hourLabel}</div>
<ScrollArea className="min-h-0 w-64 flex-1 sm:w-auto">
<div className="flex p-2 sm:flex-col">
{hours.map((hour) => (
<Button
key={hour}
type="button"
size="icon"
variant={selectedHour === hour ? 'default' : 'ghost'}
className="aspect-square shrink-0 sm:w-full"
disabled={disabled}
onClick={() => handleTimeChange('hour', hour)}
>
{hour}
</Button>
))}
</div>
<ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea>
</div>
<div className="flex min-h-0 flex-1 flex-col">
<div className="mt-1 p-1 align-middle text-center text-base border-b">{minuteLabel}</div>
<ScrollArea className="min-h-0 w-64 flex-1 sm:w-auto">
<div className="flex p-2 sm:flex-col">
{minutes.map((minute) => (
<Button
key={minute}
type="button"
size="icon"
variant={selectedMinute === minute ? 'default' : 'ghost'}
className="aspect-square shrink-0 sm:w-full"
disabled={disabled}
onClick={() => handleTimeChange('minute', minute)}
>
{String(minute).padStart(2, '0')}
</Button>
))}
</div>
<ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea>
</div>
</div>
)
}
export default KriTimePicker

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,174 @@
'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
onWheel={(event) => {
event.stopPropagation();
event.currentTarget.scrollTop += event.deltaY;
}}
>
<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="relative w-full overflow-visible"
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 [&>th]:py-3">
{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-3',
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-3',
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-3',
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,196 @@
'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가 처리한다.
}, [])
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,717 @@
"use client";
import { useCallback, useEffect, useLayoutEffect, 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";
interface ToolbarEndContentProps {
renderToolbarEnd: NonNullable<KriEditorProps["renderToolbarEnd"]>;
editor: Editor;
command: KriEditorCommand;
view: ViewMode;
}
function ToolbarEndContent({ renderToolbarEnd, editor, command, view }: ToolbarEndContentProps) {
return renderToolbarEnd({ editor, command, view });
}
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);
useLayoutEffect(() => {
if (view === "html" && htmlTextareaRef.current) {
htmlTextareaRef.current.value = htmlDraftRef.current;
}
}, [view]);
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, setPreviewSource, setView]);
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, setPreviewSource]);
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 ? (
<ToolbarEndContent renderToolbarEnd={props.renderToolbarEnd} editor={editor} command={command} view={view} />
) : null
}
/>
</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"
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) => feature !== 'image' && feature !== 'table' && 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);
}

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