261012_01_FST: first commit
This commit is contained in:
@@ -0,0 +1,13 @@
|
|||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Contract: kri-front-common
|
||||||
|
Source: .agent/consumer-references/change-and-verification.md
|
||||||
|
-->
|
||||||
|
|
||||||
|
# KriFrontCommon Change and Verification
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- Keep `.agent/project.md` near 2-3 KiB as a routing document. Move conditional schemas, endpoint inventories, examples, and issue history to routed `.agent/references/` documents instead of deleting them.
|
||||||
|
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Contract: kri-front-common
|
||||||
|
Source: .agent/consumer-references/package-and-runtime.md
|
||||||
|
-->
|
||||||
|
|
||||||
|
# KriFrontCommon Package and Runtime Contract
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
13
.agent-harness/references/kri-front-common/react-compiler.md
Normal file
13
.agent-harness/references/kri-front-common/react-compiler.md
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Contract: kri-front-common
|
||||||
|
Source: .agent/consumer-references/react-compiler.md
|
||||||
|
-->
|
||||||
|
|
||||||
|
# React Compiler and Manual Memoization
|
||||||
|
|
||||||
|
- `createKriNextConfig` enables `reactCompiler: true` unless the project overrides it; confirm the effective configuration.
|
||||||
|
- When enabled, rely on React Compiler instead of adding `useMemo`, `useCallback`, or `React.memo` as a routine performance precaution.
|
||||||
|
- Use manual memoization only for required reference stability, an Effect or third-party contract, compiler-incompatible code, or a measured performance problem.
|
||||||
|
- Preserve existing memoization unless approved and verified for removal.
|
||||||
|
- Use `"use memo"` or `"use no memo"` only for a documented compiler boundary.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Contract: kri-ui-registry
|
||||||
|
Source: .agent/consumer-references/editor-html-compatibility.md
|
||||||
|
-->
|
||||||
|
|
||||||
|
# KriEditor HTML Compatibility
|
||||||
|
|
||||||
|
- `enableImageMap` opt-in preserves `map`, nested `area`, and `img.usemap` HTML in WYSIWYG mode; consumers remain responsible for sanitizing URLs and attributes according to their server policy.
|
||||||
|
- Use `htmlSanitizer` when a consumer must apply a stricter HTML policy than the editor's default DOMPurify profile.
|
||||||
|
- Use `getWysiwygCompatibility` to keep lossy HTML in HTML mode. The callback must return `compatible: false` when WYSIWYG parsing would remove or materially rewrite content.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Contract: kri-ui-registry
|
||||||
|
Source: .agent/consumer-references/installation-and-adaptation.md
|
||||||
|
-->
|
||||||
|
|
||||||
|
# KriUiRegistry Installation and 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.
|
||||||
18
.agent/profile.yml
Normal file
18
.agent/profile.yml
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
schema_version: 1
|
||||||
|
|
||||||
|
project:
|
||||||
|
id: kart-front-next
|
||||||
|
name: "kart-front"
|
||||||
|
type: internal-service
|
||||||
|
layer: frontend
|
||||||
|
legacy: false
|
||||||
|
|
||||||
|
stack:
|
||||||
|
- typescript
|
||||||
|
- react
|
||||||
|
- nextjs
|
||||||
|
|
||||||
|
shared_contracts:
|
||||||
|
consumes:
|
||||||
|
- kri-front-common
|
||||||
|
- kri-ui-registry
|
||||||
18
.agent/project.md
Normal file
18
.agent/project.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# kart-front Project Instruction Router
|
||||||
|
|
||||||
|
## Required Project References
|
||||||
|
|
||||||
|
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
|
||||||
|
|
||||||
|
| Task scope | Required reference |
|
||||||
|
|---|---|
|
||||||
|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
|
||||||
|
|
||||||
|
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
|
||||||
|
|
||||||
|
## Harness Workflow
|
||||||
|
|
||||||
|
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
|
||||||
|
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
|
||||||
|
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
|
||||||
|
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.
|
||||||
9
.agent/references/repository-rules.md
Normal file
9
.agent/references/repository-rules.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
## Generated Next.js Repository Rules
|
||||||
|
|
||||||
|
- This frontend application was generated by `@kri/create-next-app`.
|
||||||
|
- Keep the generated Next.js routing, server/client boundary, authentication, environment, state, query, and application-shell conventions unless an approved task changes them.
|
||||||
|
- Prefer shadcn and approved KRI UI Registry components over new local primitives when a suitable component exists.
|
||||||
|
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
|
||||||
|
- Consume shared frontend behavior from `@kri/common` and the KRI UI Registry instead of copying provider implementations into this repository.
|
||||||
|
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
|
||||||
|
- Run `npm run typecheck` and `npm run build` after relevant source or configuration changes.
|
||||||
41
.agents/skills/attention-aware-communication/SKILL.md
Normal file
41
.agents/skills/attention-aware-communication/SKILL.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
---
|
||||||
|
name: attention-aware-communication
|
||||||
|
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/attention-aware-communication/SKILL.md
|
||||||
|
-->
|
||||||
|
# Attention-Aware Communication
|
||||||
|
|
||||||
|
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
|
||||||
|
|
||||||
|
## Default: Attention-kind
|
||||||
|
|
||||||
|
- Put the bottom line in the first sentence and use plain Korean.
|
||||||
|
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
|
||||||
|
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
|
||||||
|
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
|
||||||
|
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
|
||||||
|
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
|
||||||
|
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
|
||||||
|
|
||||||
|
## Progress and Completion: Rundown
|
||||||
|
|
||||||
|
Use Rundown formatting when a task has multiple steps or mixed states:
|
||||||
|
|
||||||
|
- Start with a one-line outcome that includes any blocker.
|
||||||
|
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
|
||||||
|
- Put each blocker or material risk on its own line.
|
||||||
|
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
|
||||||
|
- End with the next action or a small numbered choice only when the user must decide.
|
||||||
|
|
||||||
|
## Explicit-Only: Spartan
|
||||||
|
|
||||||
|
Use Spartan style only when the user explicitly asks for it:
|
||||||
|
|
||||||
|
- Lead with the complete answer in one sentence.
|
||||||
|
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
|
||||||
|
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
|
||||||
|
- If the user also asks for depth, provide the full detail in short, separated blocks.
|
||||||
37
.agents/skills/karpathy-guidelines/SKILL.md
Normal file
37
.agents/skills/karpathy-guidelines/SKILL.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
name: karpathy-guidelines
|
||||||
|
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/karpathy-guidelines/SKILL.md
|
||||||
|
-->
|
||||||
|
# Karpathy Guidelines
|
||||||
|
|
||||||
|
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
|
||||||
|
|
||||||
|
## Think Before Coding
|
||||||
|
|
||||||
|
- Inspect the relevant code and repository conventions before choosing a solution.
|
||||||
|
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
|
||||||
|
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
|
||||||
|
|
||||||
|
## Simplicity First
|
||||||
|
|
||||||
|
- Implement the smallest complete solution that satisfies the observable requirement.
|
||||||
|
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
|
||||||
|
- Prefer an existing repository pattern or standard-library capability over a new local framework.
|
||||||
|
|
||||||
|
## Surgical Changes
|
||||||
|
|
||||||
|
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
|
||||||
|
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
|
||||||
|
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
|
||||||
|
|
||||||
|
## Goal-Driven Execution
|
||||||
|
|
||||||
|
- Translate the request into observable success criteria before implementation.
|
||||||
|
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
|
||||||
|
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
|
||||||
|
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.
|
||||||
29
.agents/skills/project-reference-loader/SKILL.md
Normal file
29
.agents/skills/project-reference-loader/SKILL.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
name: project-reference-loader
|
||||||
|
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/project-reference-loader/SKILL.md
|
||||||
|
-->
|
||||||
|
# Project Reference Loader
|
||||||
|
|
||||||
|
Use the repository's generated `AGENTS.md` as the routing entrypoint.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
|
||||||
|
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
|
||||||
|
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
|
||||||
|
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
|
||||||
|
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
|
||||||
|
|
||||||
|
## Change Handling
|
||||||
|
|
||||||
|
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
|
||||||
|
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
|
||||||
|
- Never edit generated `.agent-harness/references/` copies directly.
|
||||||
|
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
|
||||||
|
|
||||||
|
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.
|
||||||
38
.agents/skills/verification-before-completion/SKILL.md
Normal file
38
.agents/skills/verification-before-completion/SKILL.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
name: verification-before-completion
|
||||||
|
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/verification-before-completion/SKILL.md
|
||||||
|
-->
|
||||||
|
# Verification Before Completion
|
||||||
|
|
||||||
|
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
|
||||||
|
|
||||||
|
## Verification Gate
|
||||||
|
|
||||||
|
Before making a success claim:
|
||||||
|
|
||||||
|
1. State the exact claim internally and identify which observable check can prove or disprove it.
|
||||||
|
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
|
||||||
|
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
|
||||||
|
4. Compare the evidence with the claim and the approved acceptance criteria.
|
||||||
|
5. Report only the status supported by that evidence.
|
||||||
|
|
||||||
|
## Evidence Rules
|
||||||
|
|
||||||
|
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
|
||||||
|
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
|
||||||
|
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
|
||||||
|
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
|
||||||
|
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
|
||||||
|
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
|
||||||
|
|
||||||
|
## Reporting
|
||||||
|
|
||||||
|
- Cite the commands or inspections actually run and summarize their observed results.
|
||||||
|
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
|
||||||
|
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
|
||||||
|
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.
|
||||||
41
.claude/skills/attention-aware-communication/SKILL.md
Normal file
41
.claude/skills/attention-aware-communication/SKILL.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
---
|
||||||
|
name: attention-aware-communication
|
||||||
|
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/attention-aware-communication/SKILL.md
|
||||||
|
-->
|
||||||
|
# Attention-Aware Communication
|
||||||
|
|
||||||
|
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
|
||||||
|
|
||||||
|
## Default: Attention-kind
|
||||||
|
|
||||||
|
- Put the bottom line in the first sentence and use plain Korean.
|
||||||
|
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
|
||||||
|
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
|
||||||
|
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
|
||||||
|
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
|
||||||
|
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
|
||||||
|
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
|
||||||
|
|
||||||
|
## Progress and Completion: Rundown
|
||||||
|
|
||||||
|
Use Rundown formatting when a task has multiple steps or mixed states:
|
||||||
|
|
||||||
|
- Start with a one-line outcome that includes any blocker.
|
||||||
|
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
|
||||||
|
- Put each blocker or material risk on its own line.
|
||||||
|
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
|
||||||
|
- End with the next action or a small numbered choice only when the user must decide.
|
||||||
|
|
||||||
|
## Explicit-Only: Spartan
|
||||||
|
|
||||||
|
Use Spartan style only when the user explicitly asks for it:
|
||||||
|
|
||||||
|
- Lead with the complete answer in one sentence.
|
||||||
|
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
|
||||||
|
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
|
||||||
|
- If the user also asks for depth, provide the full detail in short, separated blocks.
|
||||||
37
.claude/skills/karpathy-guidelines/SKILL.md
Normal file
37
.claude/skills/karpathy-guidelines/SKILL.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
name: karpathy-guidelines
|
||||||
|
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/karpathy-guidelines/SKILL.md
|
||||||
|
-->
|
||||||
|
# Karpathy Guidelines
|
||||||
|
|
||||||
|
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
|
||||||
|
|
||||||
|
## Think Before Coding
|
||||||
|
|
||||||
|
- Inspect the relevant code and repository conventions before choosing a solution.
|
||||||
|
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
|
||||||
|
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
|
||||||
|
|
||||||
|
## Simplicity First
|
||||||
|
|
||||||
|
- Implement the smallest complete solution that satisfies the observable requirement.
|
||||||
|
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
|
||||||
|
- Prefer an existing repository pattern or standard-library capability over a new local framework.
|
||||||
|
|
||||||
|
## Surgical Changes
|
||||||
|
|
||||||
|
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
|
||||||
|
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
|
||||||
|
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
|
||||||
|
|
||||||
|
## Goal-Driven Execution
|
||||||
|
|
||||||
|
- Translate the request into observable success criteria before implementation.
|
||||||
|
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
|
||||||
|
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
|
||||||
|
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.
|
||||||
29
.claude/skills/project-reference-loader/SKILL.md
Normal file
29
.claude/skills/project-reference-loader/SKILL.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
name: project-reference-loader
|
||||||
|
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/project-reference-loader/SKILL.md
|
||||||
|
-->
|
||||||
|
# Project Reference Loader
|
||||||
|
|
||||||
|
Use the repository's generated `AGENTS.md` as the routing entrypoint.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
|
||||||
|
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
|
||||||
|
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
|
||||||
|
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
|
||||||
|
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
|
||||||
|
|
||||||
|
## Change Handling
|
||||||
|
|
||||||
|
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
|
||||||
|
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
|
||||||
|
- Never edit generated `.agent-harness/references/` copies directly.
|
||||||
|
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
|
||||||
|
|
||||||
|
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.
|
||||||
38
.claude/skills/verification-before-completion/SKILL.md
Normal file
38
.claude/skills/verification-before-completion/SKILL.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
name: verification-before-completion
|
||||||
|
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
|
||||||
|
---
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Source: skills/verification-before-completion/SKILL.md
|
||||||
|
-->
|
||||||
|
# Verification Before Completion
|
||||||
|
|
||||||
|
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
|
||||||
|
|
||||||
|
## Verification Gate
|
||||||
|
|
||||||
|
Before making a success claim:
|
||||||
|
|
||||||
|
1. State the exact claim internally and identify which observable check can prove or disprove it.
|
||||||
|
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
|
||||||
|
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
|
||||||
|
4. Compare the evidence with the claim and the approved acceptance criteria.
|
||||||
|
5. Report only the status supported by that evidence.
|
||||||
|
|
||||||
|
## Evidence Rules
|
||||||
|
|
||||||
|
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
|
||||||
|
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
|
||||||
|
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
|
||||||
|
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
|
||||||
|
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
|
||||||
|
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
|
||||||
|
|
||||||
|
## Reporting
|
||||||
|
|
||||||
|
- Cite the commands or inspections actually run and summarize their observed results.
|
||||||
|
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
|
||||||
|
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
|
||||||
|
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.
|
||||||
9
.env.example
Normal file
9
.env.example
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# 모든 환경 공통
|
||||||
|
NEXT_PUBLIC_API_BASE=/api
|
||||||
|
NEXT_PUBLIC_STORE_KEY=change-this-storage-key-32-bytes
|
||||||
|
NEXT_PUBLIC_STORE_IV=change-this-iv-16
|
||||||
|
|
||||||
|
# 환경별 값 (.env.local / .env.development / .env.production)
|
||||||
|
NEXT_PUBLIC_ENV=local
|
||||||
|
ENV=local
|
||||||
|
API_SERVER=http://localhost:8080
|
||||||
5
.gitattributes
vendored
Normal file
5
.gitattributes
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
/AGENTS.md text eol=lf
|
||||||
|
/CLAUDE.md text eol=lf
|
||||||
|
/.agent/*.md text eol=lf
|
||||||
|
/.agent/**/*.md text eol=lf
|
||||||
|
/.agent/*.yml text eol=lf
|
||||||
23
.gitignore
vendored
Normal file
23
.gitignore
vendored
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
/node_modules
|
||||||
|
/.next
|
||||||
|
/out
|
||||||
|
/build
|
||||||
|
/coverage
|
||||||
|
/.pnp
|
||||||
|
.pnp.*
|
||||||
|
.vercel
|
||||||
|
.DS_Store
|
||||||
|
*.pem
|
||||||
|
*.tsbuildinfo
|
||||||
|
next-env.d.ts
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
.pnpm-debug.log*
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
|
||||||
|
# Local environment files
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
3
.npmrc
Normal file
3
.npmrc
Normal 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}
|
||||||
305
AGENTS.md
Normal file
305
AGENTS.md
Normal file
@@ -0,0 +1,305 @@
|
|||||||
|
<!--
|
||||||
|
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||||
|
Project: kart-front-next
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Attention-Aware Response Style
|
||||||
|
|
||||||
|
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
|
||||||
|
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
|
||||||
|
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
|
||||||
|
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
## Workflow Skills
|
||||||
|
|
||||||
|
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
|
||||||
|
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
|
||||||
|
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
|
||||||
|
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
## Internal Service Project Rules
|
||||||
|
|
||||||
|
- Internal-only usage does not reduce security, privacy, compatibility, or validation requirements.
|
||||||
|
- Preserve authentication, authorization, role boundaries, auditability, and personal-data protections.
|
||||||
|
- Identify affected user workflows before changing visible behavior.
|
||||||
|
- Treat Frontend and Backend repositories as separate deployable systems with an explicit API contract between them.
|
||||||
|
- Coordinate request, response, authentication, error, and versioning changes across both sides when the approved scope includes both repositories.
|
||||||
|
- Do not silently require a simultaneous Frontend and Backend deployment.
|
||||||
|
- Prefer backward-compatible transitions when deployments may occur independently.
|
||||||
|
- Include migration and rollback considerations for database, API, and configuration changes.
|
||||||
|
- Do not modernize legacy code as an unrelated side effect.
|
||||||
|
- Apply Classic ASP text-safety rules only when the project profile declares the `classic-asp` stack.
|
||||||
|
- Do not access or modify production data merely because the service is internal.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
- Consume the published `@kri/common` package only through entry points declared by its `package.json` `exports` map.
|
||||||
|
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
|
||||||
|
- Prefer a public shared helper or an approved backward-compatible library addition over copying or forking shared behavior locally.
|
||||||
|
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
||||||
|
|
||||||
|
### Required Shared References
|
||||||
|
|
||||||
|
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
||||||
|
|
||||||
|
| Task scope | Required reference |
|
||||||
|
|---|---|
|
||||||
|
| Package entry points, runtime boundaries, HTTP, authentication, state, storage, environment, or optional peer integrations | `.agent-harness/references/kri-front-common/package-and-runtime.md` |
|
||||||
|
| React rendering performance, memoization, or React Compiler behavior | `.agent-harness/references/kri-front-common/react-compiler.md` |
|
||||||
|
| Package upgrade, dependency changes, lockfile, or verification | `.agent-harness/references/kri-front-common/change-and-verification.md` |
|
||||||
|
|
||||||
|
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
|
||||||
|
|
||||||
|
## KriUiRegistry Consumer Contract
|
||||||
|
|
||||||
|
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 custom component only when the preceding options cannot meet the requirement safely.
|
||||||
|
|
||||||
|
### Required Shared References
|
||||||
|
|
||||||
|
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
||||||
|
|
||||||
|
| Task scope | Required reference |
|
||||||
|
|---|---|
|
||||||
|
| Installing, upgrading, adapting, or verifying a registry component | `.agent-harness/references/kri-ui-registry/installation-and-adaptation.md` |
|
||||||
|
| KriEditor HTML, image-map, sanitizer, or WYSIWYG compatibility | `.agent-harness/references/kri-ui-registry/editor-html-compatibility.md` |
|
||||||
|
|
||||||
|
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriUiRegistry's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
|
||||||
|
|
||||||
|
# kart-front Project Instruction Router
|
||||||
|
|
||||||
|
## Required Project References
|
||||||
|
|
||||||
|
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
|
||||||
|
|
||||||
|
| Task scope | Required reference |
|
||||||
|
|---|---|
|
||||||
|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
|
||||||
|
|
||||||
|
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
|
||||||
|
|
||||||
|
## Harness Workflow
|
||||||
|
|
||||||
|
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
|
||||||
|
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
|
||||||
|
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
|
||||||
|
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.
|
||||||
43
README.md
Normal file
43
README.md
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
# KART
|
||||||
|
|
||||||
|
KART 보고서 시스템
|
||||||
|
|
||||||
|
## 실행
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
기본 포트: `4014`
|
||||||
|
|
||||||
|
## 환경변수
|
||||||
|
|
||||||
|
프로젝트 생성 시 `.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: `kart-front`
|
||||||
|
- 프로젝트 유형: `internal-service`
|
||||||
|
- 권위 원본: `.agent/profile.yml`, `.agent/project.md`, `.agent/references/*.md`
|
||||||
|
|
||||||
|
`AGENTS.md`와 `CLAUDE.md`는 중앙 Agent Harness가 합성합니다. 두 파일을 직접 수정하지 않습니다.
|
||||||
22
components.json
Normal file
22
components.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"rsc": true,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "src/app/globals.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
17
eslint.config.mjs
Normal file
17
eslint.config.mjs
Normal 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
6
next.config.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import type { NextConfig } from "next";
|
||||||
|
import { createKriNextConfig } from "@kri/common/config";
|
||||||
|
|
||||||
|
const nextConfig = createKriNextConfig({}) satisfies NextConfig;
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
9633
package-lock.json
generated
Normal file
9633
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
61
package.json
Normal file
61
package.json
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"name": "kart-front",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev -p 4014",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start -p 4014",
|
||||||
|
"lint": "eslint",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@kri/common": "0.19.0",
|
||||||
|
"@tanstack/react-query": "latest",
|
||||||
|
"@tanstack/react-table": "^8.21.3",
|
||||||
|
"@tiptap/extension-color": "^3.31.4",
|
||||||
|
"@tiptap/extension-font-family": "^3.13.0",
|
||||||
|
"@tiptap/extension-highlight": "^3.31.4",
|
||||||
|
"@tiptap/extension-image": "^3.31.4",
|
||||||
|
"@tiptap/extension-link": "^3.31.4",
|
||||||
|
"@tiptap/extension-placeholder": "^3.31.4",
|
||||||
|
"@tiptap/extension-table": "^3.31.4",
|
||||||
|
"@tiptap/extension-table-cell": "^3.31.4",
|
||||||
|
"@tiptap/extension-table-header": "^3.31.4",
|
||||||
|
"@tiptap/extension-table-row": "^3.31.4",
|
||||||
|
"@tiptap/extension-text-align": "^3.31.4",
|
||||||
|
"@tiptap/extension-text-style": "^3.31.4",
|
||||||
|
"@tiptap/extension-underline": "^3.31.4",
|
||||||
|
"@tiptap/react": "^3.31.4",
|
||||||
|
"@tiptap/starter-kit": "^3.31.4",
|
||||||
|
"class-variance-authority": "latest",
|
||||||
|
"clsx": "latest",
|
||||||
|
"cmdk": "^1.1.1",
|
||||||
|
"cn": "^0.4.0",
|
||||||
|
"date-fns": "^4.4.0",
|
||||||
|
"dompurify": "^3.4.16",
|
||||||
|
"jotai": "latest",
|
||||||
|
"lucide-react": "latest",
|
||||||
|
"next": "latest",
|
||||||
|
"prettier": "^3.9.10",
|
||||||
|
"radix-ui": "^1.8.0",
|
||||||
|
"react": "latest",
|
||||||
|
"react-day-picker": "^10.0.2",
|
||||||
|
"react-dom": "latest",
|
||||||
|
"server-only": "latest",
|
||||||
|
"sonner": "latest",
|
||||||
|
"tailwind-merge": "latest"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/postcss": "latest",
|
||||||
|
"@types/node": "latest",
|
||||||
|
"@types/react": "latest",
|
||||||
|
"@types/react-dom": "latest",
|
||||||
|
"babel-plugin-react-compiler": "latest",
|
||||||
|
"eslint": "^9",
|
||||||
|
"eslint-config-next": "latest",
|
||||||
|
"tailwindcss": "latest",
|
||||||
|
"tw-animate-css": "latest",
|
||||||
|
"typescript": "^5"
|
||||||
|
}
|
||||||
|
}
|
||||||
7
postcss.config.mjs
Normal file
7
postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
const config = {
|
||||||
|
plugins: {
|
||||||
|
"@tailwindcss/postcss": {}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
BIN
public/favicon.ico
Normal file
BIN
public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
public/logo.png
Normal file
BIN
public/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
11
src/app/(pages)/(main)/layout.tsx
Normal file
11
src/app/(pages)/(main)/layout.tsx
Normal 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>;
|
||||||
|
}
|
||||||
13
src/app/(pages)/(main)/page.tsx
Normal file
13
src/app/(pages)/(main)/page.tsx
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
|
||||||
|
|
||||||
|
export default function MainPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<AppPageTitle title="KART" description="프로젝트 기본 구성이 완료되었습니다." />
|
||||||
|
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
|
||||||
|
<p className="font-medium">다음 작업</p>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">메뉴와 API 경로를 프로젝트 업무에 맞게 확장하세요.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
81
src/app/(pages)/login/page.tsx
Normal file
81
src/app/(pages)/login/page.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
20
src/app/(pages)/logout/page.tsx
Normal file
20
src/app/(pages)/logout/page.tsx
Normal 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="로그아웃 중" />;
|
||||||
|
}
|
||||||
73
src/app/api/example/[[...slug]]/route.ts
Normal file
73
src/app/api/example/[[...slug]]/route.ts
Normal 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 정책을 확인한 뒤 별도 구현하세요.
|
||||||
32
src/app/api/login/[[...slug]]/route.ts
Normal file
32
src/app/api/login/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import type { LoginRequest, LoginUser } from "@kri/common";
|
||||||
|
import { errorToResponse } from "@kri/common/http";
|
||||||
|
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
||||||
|
import { serverEnv } from "@/lib/env.server";
|
||||||
|
import { createServerApi } from "@/lib/http-server";
|
||||||
|
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||||
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
|
type LoginResponse = { accessToken: string; user: LoginUser };
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest, context: RouteContext) {
|
||||||
|
try {
|
||||||
|
const { slug = [] } = await context.params;
|
||||||
|
const serverApi = await createServerApi();
|
||||||
|
const body = (await request.json()) as LoginRequest;
|
||||||
|
const suffix = slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : "";
|
||||||
|
const result = await serverApi.post<LoginResponse>(`/auth/login${suffix}`, body);
|
||||||
|
|
||||||
|
const response = NextResponse.json(result.user, { status: 200 });
|
||||||
|
response.cookies.set(CookieKeys.AuthToken, result.accessToken, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: serverEnv.ENV === "prod",
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
maxAge: AUTH_COOKIE_MAX_AGE,
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return errorToResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
27
src/app/api/logout/[[...slug]]/route.ts
Normal file
27
src/app/api/logout/[[...slug]]/route.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
87
src/app/globals.css
Normal file
87
src/app/globals.css
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
@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: oklch(0.205 0 0);
|
||||||
|
--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: oklch(0.922 0 0);
|
||||||
|
--primary-foreground: oklch(0.205 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; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.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
21
src/app/layout.tsx
Normal 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: "KART",
|
||||||
|
description: "KART 보고서 시스템",
|
||||||
|
icons: { icon: "/favicon.ico" }
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||||
|
return (
|
||||||
|
<html lang="ko">
|
||||||
|
<body className="min-h-screen antialiased">
|
||||||
|
<AppProvider>{children}</AppProvider>
|
||||||
|
<Toaster />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
11
src/app/not-found.tsx
Normal file
11
src/app/not-found.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
40
src/components/app-shell/AppHeader.tsx
Normal file
40
src/components/app-shell/AppHeader.tsx
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
"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 { topMenus } from "@/config/menu.data";
|
||||||
|
import type { LoginUser } from "@kri/common";
|
||||||
|
|
||||||
|
interface AppHeaderProps {
|
||||||
|
menuOpen: boolean;
|
||||||
|
showMenuButton: boolean;
|
||||||
|
activeMenuId?: string;
|
||||||
|
user?: LoginUser | null;
|
||||||
|
onToggleMenu: () => void;
|
||||||
|
onNavigate: (path: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AppHeader({ 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={topMenus}
|
||||||
|
activeMenuId={activeMenuId}
|
||||||
|
menuOpen={menuOpen}
|
||||||
|
showMenuButton={showMenuButton}
|
||||||
|
onToggleMenu={onToggleMenu}
|
||||||
|
onNavigate={onNavigate}
|
||||||
|
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>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
45
src/components/app-shell/AppMainLayout.tsx
Normal file
45
src/components/app-shell/AppMainLayout.tsx
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { Route } from "next";
|
||||||
|
import { useMemo, useState, type ReactNode } from "react";
|
||||||
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
|
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||||
|
import { AppHeader } from "./AppHeader";
|
||||||
|
import { AppSidebar } from "./AppSidebar";
|
||||||
|
import { sideMenus, topMenus } from "@/config/menu.data";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
|
||||||
|
export function AppMainLayout({ children }: { children: ReactNode }) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const router = useRouter();
|
||||||
|
const { auth } = useAuth();
|
||||||
|
const [menuOpen, setMenuOpen] = useState(true);
|
||||||
|
|
||||||
|
const activeMenuId = useMemo(
|
||||||
|
() => topMenus.find((item) => item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)))?.id,
|
||||||
|
[pathname],
|
||||||
|
);
|
||||||
|
|
||||||
|
const navigate = (path: string) => router.push(path as Route);
|
||||||
|
const hasSidebar = sideMenus.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<KriMainLayout
|
||||||
|
sidebarOpen={hasSidebar && menuOpen}
|
||||||
|
onSidebarOpenChange={setMenuOpen}
|
||||||
|
header={
|
||||||
|
<AppHeader
|
||||||
|
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}
|
||||||
|
</KriMainLayout>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
src/components/app-shell/AppPageTitle.tsx
Normal file
10
src/components/app-shell/AppPageTitle.tsx
Normal 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} />;
|
||||||
|
}
|
||||||
15
src/components/app-shell/AppSidebar.tsx
Normal file
15
src/components/app-shell/AppSidebar.tsx
Normal 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} />;
|
||||||
|
}
|
||||||
12
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
12
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal 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} />;
|
||||||
|
}
|
||||||
5
src/components/app-shell/index.ts
Normal file
5
src/components/app-shell/index.ts
Normal 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";
|
||||||
232
src/components/common/KriAutoComplete.tsx
Normal file
232
src/components/common/KriAutoComplete.tsx
Normal 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
|
||||||
122
src/components/common/KriDateRangePicker.tsx
Normal file
122
src/components/common/KriDateRangePicker.tsx
Normal 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
|
||||||
76
src/components/common/KriDialog.tsx
Normal file
76
src/components/common/KriDialog.tsx
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export interface KriDialogProps {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
title: ReactNode
|
||||||
|
description?: ReactNode
|
||||||
|
children?: ReactNode
|
||||||
|
footer?: ReactNode
|
||||||
|
showDefaultFooter?: boolean
|
||||||
|
closeLabel?: string
|
||||||
|
showCloseButton?: boolean
|
||||||
|
contentClassName?: string
|
||||||
|
bodyClassName?: string
|
||||||
|
footerClassName?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function KriDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
children,
|
||||||
|
footer,
|
||||||
|
showDefaultFooter = true,
|
||||||
|
closeLabel = '닫기',
|
||||||
|
showCloseButton = true,
|
||||||
|
contentClassName,
|
||||||
|
bodyClassName,
|
||||||
|
footerClassName,
|
||||||
|
}: KriDialogProps) {
|
||||||
|
const renderFooter = () => {
|
||||||
|
if (footer !== undefined) {
|
||||||
|
if (footer === null) return null
|
||||||
|
return <DialogFooter className={footerClassName}>{footer}</DialogFooter>
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!showDefaultFooter) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DialogFooter className={footerClassName}>
|
||||||
|
<DialogClose asChild>
|
||||||
|
<Button type="button" variant="outline">
|
||||||
|
{closeLabel}
|
||||||
|
</Button>
|
||||||
|
</DialogClose>
|
||||||
|
</DialogFooter>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className={contentClassName} showCloseButton={showCloseButton}>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{title}</DialogTitle>
|
||||||
|
{description ? <DialogDescription>{description}</DialogDescription> : null}
|
||||||
|
</DialogHeader>
|
||||||
|
<div className={cn('min-h-0', bodyClassName)}>{children}</div>
|
||||||
|
{renderFooter()}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
29
src/components/common/KriLoadingOverlay.tsx
Normal file
29
src/components/common/KriLoadingOverlay.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
118
src/components/common/KriPassword.tsx
Normal file
118
src/components/common/KriPassword.tsx
Normal 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
|
||||||
98
src/components/common/KriSelect.tsx
Normal file
98
src/components/common/KriSelect.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
220
src/components/common/multi-select/MultiSelect.tsx
Normal 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
|
||||||
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { CheckIcon } from 'lucide-react'
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandInput,
|
||||||
|
CommandItem,
|
||||||
|
CommandList,
|
||||||
|
CommandSeparator,
|
||||||
|
} from '@/components/ui/command'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||||
|
import { isGroupedOptions } from './utils'
|
||||||
|
|
||||||
|
interface MultiSelectContentProps<T> {
|
||||||
|
options: MultiSelectOptions<T>
|
||||||
|
selectedValues: string[]
|
||||||
|
searchable: boolean
|
||||||
|
searchMode: 'filter' | 'inputOnly'
|
||||||
|
searchValue: string
|
||||||
|
onSearchValueChange: (value: string) => void
|
||||||
|
hideSelectAll: boolean
|
||||||
|
hideOptionCheck: boolean
|
||||||
|
selectionMode: 'single' | 'multiple'
|
||||||
|
emptyIndicator: React.ReactNode
|
||||||
|
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||||
|
onToggleAll: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function OptionItem<T>({
|
||||||
|
option,
|
||||||
|
selected,
|
||||||
|
hideOptionCheck,
|
||||||
|
onToggle,
|
||||||
|
}: {
|
||||||
|
option: MultiSelectOption<T>
|
||||||
|
selected: boolean
|
||||||
|
hideOptionCheck: boolean
|
||||||
|
onToggle: () => void
|
||||||
|
}) {
|
||||||
|
const Icon = option.icon
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CommandItem
|
||||||
|
value={`${option.label} ${option.value}`}
|
||||||
|
disabled={option.disabled}
|
||||||
|
onSelect={onToggle}
|
||||||
|
className="flex items-center cursor-pointer"
|
||||||
|
>
|
||||||
|
{!hideOptionCheck ? (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||||
|
selected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3" />
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
||||||
|
<span className="truncate">{option.label}</span>
|
||||||
|
</CommandItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function OptionsGroup<T>({
|
||||||
|
group,
|
||||||
|
selectedValues,
|
||||||
|
hideOptionCheck,
|
||||||
|
onToggleOption,
|
||||||
|
}: {
|
||||||
|
group: MultiSelectGroup<T>
|
||||||
|
selectedValues: string[]
|
||||||
|
hideOptionCheck: boolean
|
||||||
|
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<CommandGroup heading={group.heading}>
|
||||||
|
{group.options.map((option) => (
|
||||||
|
<OptionItem
|
||||||
|
key={option.value}
|
||||||
|
option={option}
|
||||||
|
selected={selectedValues.includes(option.value)}
|
||||||
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
onToggle={() => onToggleOption(option)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MultiSelectContent<T>({
|
||||||
|
options,
|
||||||
|
selectedValues,
|
||||||
|
searchable,
|
||||||
|
searchMode,
|
||||||
|
searchValue,
|
||||||
|
onSearchValueChange,
|
||||||
|
hideSelectAll,
|
||||||
|
hideOptionCheck,
|
||||||
|
selectionMode,
|
||||||
|
emptyIndicator,
|
||||||
|
onToggleOption,
|
||||||
|
onToggleAll,
|
||||||
|
}: MultiSelectContentProps<T>) {
|
||||||
|
const grouped = isGroupedOptions(options)
|
||||||
|
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
|
||||||
|
const selectableOptions = flatOptions.filter((option) => !option.disabled)
|
||||||
|
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Command shouldFilter={searchMode === 'filter'}>
|
||||||
|
{searchable ? (
|
||||||
|
<CommandInput
|
||||||
|
value={searchValue}
|
||||||
|
onValueChange={onSearchValueChange}
|
||||||
|
placeholder="검색..."
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<CommandList>
|
||||||
|
<CommandEmpty>{emptyIndicator}</CommandEmpty>
|
||||||
|
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
|
||||||
|
<>
|
||||||
|
<CommandGroup>
|
||||||
|
<CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||||
|
allSelected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3" />
|
||||||
|
</span>
|
||||||
|
전체 선택
|
||||||
|
</CommandItem>
|
||||||
|
</CommandGroup>
|
||||||
|
<CommandSeparator />
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{grouped ? (
|
||||||
|
options.map((group) => (
|
||||||
|
<OptionsGroup
|
||||||
|
key={group.heading}
|
||||||
|
group={group}
|
||||||
|
selectedValues={selectedValues}
|
||||||
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
onToggleOption={onToggleOption}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<CommandGroup>
|
||||||
|
{options.map((option) => (
|
||||||
|
<OptionItem
|
||||||
|
key={option.value}
|
||||||
|
option={option}
|
||||||
|
selected={selectedValues.includes(option.value)}
|
||||||
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
onToggle={() => onToggleOption(option)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
)}
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
)
|
||||||
|
}
|
||||||
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal 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
|
||||||
13
src/components/common/multi-select/index.ts
Normal file
13
src/components/common/multi-select/index.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
export { MultiSelect } from './MultiSelect'
|
||||||
|
export type {
|
||||||
|
AnimationConfig,
|
||||||
|
MultiSelectGroup,
|
||||||
|
MultiSelectOption,
|
||||||
|
MultiSelectOptions,
|
||||||
|
MultiSelectProps,
|
||||||
|
MultiSelectRef,
|
||||||
|
MultiSelectResponsiveConfig,
|
||||||
|
MultiSelectResponsiveSettings,
|
||||||
|
MultiSelectSelectionMode,
|
||||||
|
MultiSelectVariant,
|
||||||
|
} from './types'
|
||||||
89
src/components/common/multi-select/types.ts
Normal file
89
src/components/common/multi-select/types.ts
Normal 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
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
48
src/components/common/multi-select/utils.ts
Normal file
48
src/components/common/multi-select/utils.ts
Normal 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'
|
||||||
|
}
|
||||||
|
}
|
||||||
295
src/components/data-table/DataTable.tsx
Normal file
295
src/components/data-table/DataTable.tsx
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import type { OnChangeFn, PaginationState, Row, RowPinningState, RowSelectionState, SortingState } from '@tanstack/react-table'
|
||||||
|
import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'
|
||||||
|
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
|
import { TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { DataTableColumn, DataTableProps } from './DataTable.type'
|
||||||
|
import { DataTablePagination } from './DataTablePagination'
|
||||||
|
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
|
||||||
|
|
||||||
|
const EMPTY_PINNED_ROWS: never[] = []
|
||||||
|
|
||||||
|
export function DataTable<TData, TValue = unknown>({
|
||||||
|
columns,
|
||||||
|
data,
|
||||||
|
getRowId,
|
||||||
|
highlightRowIds,
|
||||||
|
isClient = true,
|
||||||
|
pageCount: serverPageCount,
|
||||||
|
totalCount: serverTotalCount,
|
||||||
|
pagination: externalPagination,
|
||||||
|
onPaginationChange: onServerPaginationChange,
|
||||||
|
onSortingChange: onServerSortingChange,
|
||||||
|
selectMode = 'none',
|
||||||
|
onRowClick,
|
||||||
|
onRowSelectionChange,
|
||||||
|
defaultPageSize = 10,
|
||||||
|
pageSizeOptions = [5, 10, 25, 50],
|
||||||
|
paginationItemsToDisplay = 5,
|
||||||
|
emptyText = '데이터가 없습니다.',
|
||||||
|
className,
|
||||||
|
maxBodyHeight,
|
||||||
|
disablePagination = false,
|
||||||
|
topPinnedRows = EMPTY_PINNED_ROWS,
|
||||||
|
bottomPinnedRows = EMPTY_PINNED_ROWS,
|
||||||
|
}: Readonly<DataTableProps<TData, TValue>>) {
|
||||||
|
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
|
||||||
|
const [sorting, setSorting] = useState<SortingState>([])
|
||||||
|
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||||
|
const drag = usePreventClickOnDrag()
|
||||||
|
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
|
||||||
|
|
||||||
|
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
|
||||||
|
if (!selectionEnabled) return columns
|
||||||
|
|
||||||
|
const selectionColumn = {
|
||||||
|
id: 'select',
|
||||||
|
header: ({ table }) => selectMode === 'multi' ? (
|
||||||
|
<Checkbox
|
||||||
|
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate')}
|
||||||
|
onCheckedChange={(value) => table.toggleAllPageRowsSelected(Boolean(value))}
|
||||||
|
aria-label="전체 선택"
|
||||||
|
/>
|
||||||
|
) : null,
|
||||||
|
cell: ({ row }) => row.getIsPinned() ? null : (
|
||||||
|
<Checkbox
|
||||||
|
checked={row.getIsSelected()}
|
||||||
|
onCheckedChange={(value) => {
|
||||||
|
if (selectMode === 'single') table.resetRowSelection()
|
||||||
|
row.toggleSelected(Boolean(value))
|
||||||
|
}}
|
||||||
|
aria-label="행 선택"
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
size: 28,
|
||||||
|
enableSorting: false,
|
||||||
|
} as DataTableColumn<TData, TValue>
|
||||||
|
|
||||||
|
return [selectionColumn, ...columns]
|
||||||
|
}, [columns, selectMode, selectionEnabled])
|
||||||
|
|
||||||
|
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setRowSelection({})
|
||||||
|
}, [pagination.pageIndex, pagination.pageSize, sorting])
|
||||||
|
|
||||||
|
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
|
||||||
|
(updater) => {
|
||||||
|
if (isClient) {
|
||||||
|
setInternalPagination(updater)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (onServerPaginationChange) {
|
||||||
|
onServerPaginationChange(updater)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setInternalPagination(updater)
|
||||||
|
},
|
||||||
|
[isClient, onServerPaginationChange],
|
||||||
|
)
|
||||||
|
|
||||||
|
const combinedData = useMemo(
|
||||||
|
() => [...topPinnedRows, ...data, ...bottomPinnedRows],
|
||||||
|
[topPinnedRows, data, bottomPinnedRows],
|
||||||
|
)
|
||||||
|
|
||||||
|
const internalGetRowId = useCallback((row: TData, index: number) => {
|
||||||
|
if (index < topPinnedRows.length) return `__top-pinned-${index}`
|
||||||
|
if (index >= topPinnedRows.length + data.length) {
|
||||||
|
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`
|
||||||
|
}
|
||||||
|
const originalIndex = index - topPinnedRows.length
|
||||||
|
return getRowId ? getRowId(data[originalIndex], originalIndex) : String(originalIndex)
|
||||||
|
}, [topPinnedRows.length, data, getRowId])
|
||||||
|
|
||||||
|
const rowPinning = useMemo<RowPinningState>(() => ({
|
||||||
|
top: topPinnedRows.map((_, i) => `__top-pinned-${i}`),
|
||||||
|
bottom: bottomPinnedRows.map((_, i) => `__bottom-pinned-${i}`),
|
||||||
|
}), [topPinnedRows, bottomPinnedRows])
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: combinedData,
|
||||||
|
columns: enhancedColumns,
|
||||||
|
pageCount: isClient ? undefined : serverPageCount,
|
||||||
|
state: { sorting, pagination, rowSelection, rowPinning },
|
||||||
|
enableRowSelection: (row) => selectionEnabled && !row.getIsPinned(),
|
||||||
|
enableRowPinning: true,
|
||||||
|
keepPinnedRows: true,
|
||||||
|
onRowSelectionChange: setRowSelection,
|
||||||
|
onSortingChange: setSorting,
|
||||||
|
onPaginationChange: handlePaginationChange,
|
||||||
|
getCoreRowModel: getCoreRowModel(),
|
||||||
|
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
||||||
|
getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined,
|
||||||
|
manualPagination: !isClient,
|
||||||
|
manualSorting: !isClient,
|
||||||
|
enableSortingRemoval: false,
|
||||||
|
getRowId: internalGetRowId,
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isClient) onServerSortingChange?.(sorting)
|
||||||
|
}, [isClient, onServerSortingChange, sorting])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectionEnabled) return
|
||||||
|
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
||||||
|
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
|
||||||
|
|
||||||
|
const handleRowClick = (row: Row<TData>) => {
|
||||||
|
if (selectMode === 'none') return
|
||||||
|
if (selectMode === 'click-event') {
|
||||||
|
onRowClick?.(row.original)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (selectMode === 'single') {
|
||||||
|
table.resetRowSelection()
|
||||||
|
row.toggleSelected(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
row.toggleSelected(!row.getIsSelected())
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
|
||||||
|
|
||||||
|
const topRows = table.getTopRows()
|
||||||
|
const centerRows = table.getCenterRows()
|
||||||
|
const bottomRows = table.getBottomRows()
|
||||||
|
|
||||||
|
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||||
|
const [topOffsets, setTopOffsets] = useState<number[]>([])
|
||||||
|
const [bottomOffsets, setBottomOffsets] = useState<number[]>([])
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!maxBodyHeight) return
|
||||||
|
const container = scrollContainerRef.current
|
||||||
|
if (!container) return
|
||||||
|
|
||||||
|
const headerHeight = container.querySelector('thead')?.getBoundingClientRect().height ?? 0
|
||||||
|
const bodyRows = Array.from(container.querySelectorAll('tbody > tr'))
|
||||||
|
const topRowEls = bodyRows.slice(0, topRows.length)
|
||||||
|
const bottomRowEls = bottomRows.length ? bodyRows.slice(-bottomRows.length) : []
|
||||||
|
|
||||||
|
let topAcc = headerHeight
|
||||||
|
setTopOffsets(topRowEls.map((element) => {
|
||||||
|
const offset = topAcc
|
||||||
|
topAcc += element.getBoundingClientRect().height
|
||||||
|
return offset
|
||||||
|
}))
|
||||||
|
|
||||||
|
let bottomAcc = 0
|
||||||
|
const offsets: number[] = []
|
||||||
|
for (let index = bottomRowEls.length - 1; index >= 0; index -= 1) {
|
||||||
|
offsets[index] = bottomAcc
|
||||||
|
bottomAcc += bottomRowEls[index].getBoundingClientRect().height
|
||||||
|
}
|
||||||
|
setBottomOffsets(offsets)
|
||||||
|
}, [maxBodyHeight, topRows.length, bottomRows.length, centerRows.length])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('w-full space-y-4', className)}>
|
||||||
|
<div className="rounded-md border">
|
||||||
|
<div
|
||||||
|
ref={scrollContainerRef}
|
||||||
|
className={cn('relative w-full overflow-x-auto', maxBodyHeight && 'overflow-y-auto')}
|
||||||
|
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
|
||||||
|
>
|
||||||
|
<table className="w-full caption-bottom text-sm">
|
||||||
|
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-20 bg-background')}>
|
||||||
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
|
<TableRow key={headerGroup.id} className="hover:bg-transparent">
|
||||||
|
{headerGroup.headers.map((header) => {
|
||||||
|
const column = header.column
|
||||||
|
const sorted = column.getIsSorted()
|
||||||
|
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TableHead
|
||||||
|
key={header.id}
|
||||||
|
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
|
||||||
|
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
|
||||||
|
>
|
||||||
|
{!header.isPlaceholder && column.getCanSort() ? (
|
||||||
|
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
|
||||||
|
<span>{content}</span>
|
||||||
|
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />}
|
||||||
|
</Button>
|
||||||
|
) : content}
|
||||||
|
</TableHead>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{topRows.map((row, index) => (
|
||||||
|
<TableRow
|
||||||
|
key={row.id}
|
||||||
|
className={cn(
|
||||||
|
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
|
||||||
|
maxBodyHeight && 'sticky z-10',
|
||||||
|
)}
|
||||||
|
style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined}
|
||||||
|
>
|
||||||
|
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
{centerRows.length ? centerRows.map((row) => (
|
||||||
|
<TableRow
|
||||||
|
key={row.id}
|
||||||
|
data-state={row.getIsSelected() ? 'selected' : undefined}
|
||||||
|
onPointerDown={drag.onPointerDown}
|
||||||
|
onPointerMove={drag.onPointerMove}
|
||||||
|
onPointerUp={drag.onPointerUp}
|
||||||
|
onPointerCancel={drag.onPointerCancel}
|
||||||
|
onClick={drag.wrapClick(() => handleRowClick(row))}
|
||||||
|
className={cn(
|
||||||
|
'text-sm [&>td]:px-2 [&>td]:py-0',
|
||||||
|
selectMode !== 'none' && 'cursor-pointer',
|
||||||
|
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
|
||||||
|
highlightRowIds?.includes(row.id) && 'bg-emerald-50',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
|
||||||
|
</TableRow>
|
||||||
|
)) : (
|
||||||
|
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
|
||||||
|
)}
|
||||||
|
{bottomRows.map((row, index) => (
|
||||||
|
<TableRow
|
||||||
|
key={row.id}
|
||||||
|
className={cn(
|
||||||
|
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
|
||||||
|
maxBodyHeight && 'sticky z-10',
|
||||||
|
)}
|
||||||
|
style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined}
|
||||||
|
>
|
||||||
|
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!disablePagination && (
|
||||||
|
<DataTablePagination
|
||||||
|
table={table}
|
||||||
|
isClient={isClient}
|
||||||
|
totalCount={totalCount}
|
||||||
|
pageSizeOptions={pageSizeOptions}
|
||||||
|
paginationItemsToDisplay={paginationItemsToDisplay}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
41
src/components/data-table/DataTable.type.ts
Normal file
41
src/components/data-table/DataTable.type.ts
Normal 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[]
|
||||||
|
}
|
||||||
98
src/components/data-table/DataTablePagination.tsx
Normal file
98
src/components/data-table/DataTablePagination.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
30
src/components/data-table/hooks/usePagination.ts
Normal file
30
src/components/data-table/hooks/usePagination.ts
Normal 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])
|
||||||
|
}
|
||||||
37
src/components/data-table/hooks/usePreventClickOnDrag.ts
Normal file
37
src/components/data-table/hooks/usePreventClickOnDrag.ts
Normal 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 }
|
||||||
|
}
|
||||||
8
src/components/data-table/index.ts
Normal file
8
src/components/data-table/index.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
export { DataTable } from './DataTable'
|
||||||
|
export type {
|
||||||
|
DataTableColumn,
|
||||||
|
DataTableProps,
|
||||||
|
SelectMode,
|
||||||
|
ServerPaginationParams,
|
||||||
|
ServerPaginationResponse,
|
||||||
|
} from './DataTable.type'
|
||||||
29
src/components/kri-editor/KriEditor.tsx
Normal file
29
src/components/kri-editor/KriEditor.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { KriEditorProps, KriEditorMode } from "./types";
|
||||||
|
import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
|
||||||
|
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
|
||||||
|
import {KriEditorSms} from "./KriEditorSms";
|
||||||
|
import { KriEditorKko } from "./KriEditorKko";
|
||||||
|
|
||||||
|
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} />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === "kko") {
|
||||||
|
return <KriEditorKko {...props} mode={mode} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <KriEditorWysiwyg {...props} mode={mode} />;
|
||||||
|
}
|
||||||
197
src/components/kri-editor/KriEditorHtmlOnly.tsx
Normal file
197
src/components/kri-editor/KriEditorHtmlOnly.tsx
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { KriEditorProps } from './types'
|
||||||
|
import { resolveUploadUrl } from './types'
|
||||||
|
import { compressImage } from './utils/imageCompression'
|
||||||
|
import { useDebouncedChange } from './hooks/useDebouncedChange'
|
||||||
|
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
|
||||||
|
import { preserveEmptyParagraphs } from './utils/emptyParagraph'
|
||||||
|
import { formatHtmlSource } from './utils/formatHtml'
|
||||||
|
import { useTextareaInsert } from './hooks/useTextareaInsert'
|
||||||
|
|
||||||
|
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
|
||||||
|
|
||||||
|
export function KriEditorHtmlOnly({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder = 'HTML을 입력하세요...',
|
||||||
|
className,
|
||||||
|
showPreview,
|
||||||
|
previewClassName,
|
||||||
|
rows = 14,
|
||||||
|
debounceMs = 350,
|
||||||
|
onImageUpload,
|
||||||
|
onImageUploadError,
|
||||||
|
maxImageBytes = 5 * 1024 * 1024,
|
||||||
|
imageMaxWidth = 1600,
|
||||||
|
imageMaxHeight = 1600,
|
||||||
|
imageQuality = 0.82,
|
||||||
|
imageMimeType = 'image/webp',
|
||||||
|
onEditorReady,
|
||||||
|
onCommandReady,
|
||||||
|
}: HtmlOnlyProps) {
|
||||||
|
const [html, setHtml] = React.useState(value || '')
|
||||||
|
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
||||||
|
const fileRef = React.useRef<HTMLInputElement | null>(null)
|
||||||
|
const latestHtmlRef = React.useRef(html)
|
||||||
|
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
||||||
|
const textareaInsert = useTextareaInsert(textareaRef)
|
||||||
|
|
||||||
|
const commitHtml = React.useCallback((next: string, immediate = false) => {
|
||||||
|
setHtml(next)
|
||||||
|
latestHtmlRef.current = next
|
||||||
|
if (immediate) flushChange(next)
|
||||||
|
else scheduleChange(next)
|
||||||
|
}, [flushChange, scheduleChange])
|
||||||
|
|
||||||
|
// 사용자가 타이핑한 값이 아니라 외부에서 새로 세팅된 데이터일 때만(최초 마운트 포함)
|
||||||
|
// prettier로 포맷팅해서 반영한다 — 편집 중(commitHtml 경로)에는 절대 재포맷하지 않는다.
|
||||||
|
const applyExternalValue = React.useCallback((next: string) => {
|
||||||
|
setHtml(next)
|
||||||
|
latestHtmlRef.current = next
|
||||||
|
formatHtmlSource(next)
|
||||||
|
.then((formatted) => {
|
||||||
|
if (latestHtmlRef.current !== next) return // 그 사이 값이 또 바뀌었으면 건너뜀
|
||||||
|
setHtml(formatted)
|
||||||
|
latestHtmlRef.current = formatted
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
applyExternalValue(value || '')
|
||||||
|
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if ((value || '') !== latestHtmlRef.current) {
|
||||||
|
applyExternalValue(value || '')
|
||||||
|
}
|
||||||
|
}, [value, applyExternalValue])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
onEditorReady?.(textareaRef.current)
|
||||||
|
}, [onEditorReady])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!onCommandReady) return
|
||||||
|
onCommandReady({
|
||||||
|
focus: () => textareaRef.current?.focus(),
|
||||||
|
insertText: (text) => {
|
||||||
|
textareaInsert.insertText(
|
||||||
|
text,
|
||||||
|
latestHtmlRef.current,
|
||||||
|
(next) => commitHtml(next),
|
||||||
|
(next) => commitHtml(next, true),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => onCommandReady(null)
|
||||||
|
}, [commitHtml, onCommandReady, textareaInsert])
|
||||||
|
|
||||||
|
const handleFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
try {
|
||||||
|
const file = event.target.files?.[0]
|
||||||
|
event.target.value = ''
|
||||||
|
if (!file || !onImageUpload) return
|
||||||
|
if (!file.type.startsWith('image/')) {
|
||||||
|
toast.error('이미지 파일만 업로드할 수 있습니다.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const compressed = await compressImage(file, {
|
||||||
|
maxBytes: maxImageBytes,
|
||||||
|
maxWidth: imageMaxWidth,
|
||||||
|
maxHeight: imageMaxHeight,
|
||||||
|
mimeType: imageMimeType,
|
||||||
|
quality: imageQuality,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (compressed.size > maxImageBytes) {
|
||||||
|
toast.error('이미지 용량이 제한을 초과합니다.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = resolveUploadUrl(await onImageUpload(compressed))
|
||||||
|
if (!url) {
|
||||||
|
toast.error('이미지 업로드 응답이 올바르지 않습니다.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = latestHtmlRef.current
|
||||||
|
const textarea = textareaRef.current
|
||||||
|
const imageTag = `<img src="${url}" alt="" />`
|
||||||
|
const start = textarea?.selectionStart ?? current.length
|
||||||
|
const end = textarea?.selectionEnd ?? current.length
|
||||||
|
const next = `${current.slice(0, start)}${imageTag}${current.slice(end)}`
|
||||||
|
commitHtml(next)
|
||||||
|
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
const position = start + imageTag.length
|
||||||
|
textarea?.focus()
|
||||||
|
textarea?.setSelectionRange(position, position)
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (onImageUploadError) onImageUploadError(error)
|
||||||
|
else toast.error('이미지 업로드에 실패했습니다.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFormatHtml = React.useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const formatted = await formatHtmlSource(latestHtmlRef.current)
|
||||||
|
commitHtml(formatted)
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('HTML 정렬에 실패했습니다.')
|
||||||
|
console.error(error)
|
||||||
|
}
|
||||||
|
}, [commitHtml])
|
||||||
|
|
||||||
|
const previewHtml = React.useMemo(
|
||||||
|
() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)),
|
||||||
|
[html],
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('rounded-md border bg-background', className)}>
|
||||||
|
{label ? <div className="border-b px-3 py-2 text-sm font-semibold">{label}</div> : null}
|
||||||
|
<div className="flex flex-col gap-2 px-3 py-2">
|
||||||
|
<div className="text-muted-foreground flex items-center justify-between text-xs">
|
||||||
|
<span>HTML 모드</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button type="button" onClick={handleFormatHtml} className="rounded border px-2 py-1 hover:bg-muted">
|
||||||
|
정렬
|
||||||
|
</button>
|
||||||
|
{onImageUpload ? (
|
||||||
|
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
|
||||||
|
이미지 업로드
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
ref={textareaRef}
|
||||||
|
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
|
||||||
|
value={html}
|
||||||
|
onChange={(event) => commitHtml(event.target.value)}
|
||||||
|
onBlur={() => flushChange(latestHtmlRef.current)}
|
||||||
|
placeholder={placeholder}
|
||||||
|
rows={rows}
|
||||||
|
{...textareaInsert.bindSelectionHandlers}
|
||||||
|
/>
|
||||||
|
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
|
||||||
|
</div>
|
||||||
|
{showPreview ? (
|
||||||
|
<div className={cn('border-t p-3', previewClassName)}>
|
||||||
|
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||||
|
<div className="rounded-md border bg-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
59
src/components/kri-editor/KriEditorKko.tsx
Normal file
59
src/components/kri-editor/KriEditorKko.tsx
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { User } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { KriEditorProps } from './types'
|
||||||
|
|
||||||
|
type KkoEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'kko' }
|
||||||
|
|
||||||
|
export function KriEditorKko({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
placeholder = '미리볼 내용이 없습니다.',
|
||||||
|
className,
|
||||||
|
kkoTitle = '',
|
||||||
|
kkoSenderName = '',
|
||||||
|
kkoHeaderLabel = '알림톡 도착',
|
||||||
|
}: KkoEditorProps) {
|
||||||
|
const body = value ?? ''
|
||||||
|
|
||||||
|
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-[#d6e4f7] pt-8 pb-4">
|
||||||
|
{kkoSenderName ? (
|
||||||
|
<div className="border-b border-black/10 px-4 pb-3 text-center text-sm font-bold text-gray-900">{kkoSenderName}</div>
|
||||||
|
) : null}
|
||||||
|
<div className="flex-1 overflow-y-auto px-3 py-3">
|
||||||
|
{kkoSenderName ? (
|
||||||
|
<div className="mb-1 flex items-center gap-2">
|
||||||
|
<span aria-hidden="true" className="flex size-8 shrink-0 items-center justify-center rounded-full bg-gray-300 text-white">
|
||||||
|
<User className="size-5" />
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-gray-600">{kkoSenderName}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<div className="relative mr-3 ml-10 rounded-xl bg-white shadow-sm">
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="absolute -top-3 -right-3 flex size-8 items-center justify-center rounded-full bg-gray-800 text-[9px] font-bold text-white"
|
||||||
|
>
|
||||||
|
kakao
|
||||||
|
</span>
|
||||||
|
<div className="rounded-t-xl bg-[#FEE500] px-4 py-3 text-sm font-bold text-gray-900">{kkoHeaderLabel}</div>
|
||||||
|
{kkoTitle ? <div className="px-4 pt-3 text-sm font-bold break-words whitespace-pre-wrap text-gray-800">{kkoTitle}</div> : null}
|
||||||
|
{body.trim() ? (
|
||||||
|
<div className="px-4 py-3 text-sm leading-relaxed break-words whitespace-pre-wrap text-gray-700">{body}</div>
|
||||||
|
) : (
|
||||||
|
<div className="px-4 py-3 text-sm text-gray-400">{placeholder}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
137
src/components/kri-editor/KriEditorSms.tsx
Normal file
137
src/components/kri-editor/KriEditorSms.tsx
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
'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,
|
||||||
|
smsPreviewSuffix = '',
|
||||||
|
smsHasAttachment = false,
|
||||||
|
smsImages = [],
|
||||||
|
}: 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 previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text
|
||||||
|
const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText])
|
||||||
|
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) || smsHasAttachment ? '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 === 'LMS' ? 'LMS/MMS' : 'SMS'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className={cn('flex flex-1 flex-col rounded-2xl bg-white shadow-sm', smsImages.length > 0 ? 'overflow-y-auto' : 'overflow-hidden')}>
|
||||||
|
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
|
||||||
|
{smsImages.length > 0 ? (
|
||||||
|
<div className="flex shrink-0 flex-col gap-2 px-4 pt-3">
|
||||||
|
{smsImages.map((image) => (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element -- data/Object URL 미리보기라 next/image 최적화 대상이 아님
|
||||||
|
<img key={image.fileName} src={image.src} alt={image.fileName} title={image.fileName} className="w-full rounded-md object-contain" />
|
||||||
|
))}
|
||||||
|
</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
|
||||||
|
const nextPreview = smsPreviewSuffix ? `${next}\n${smsPreviewSuffix}` : next
|
||||||
|
if (calculateBytes(nextPreview) <= lmsMaxBytes) commitText(next)
|
||||||
|
}}
|
||||||
|
onBlur={() => flushChange(latestTextRef.current)}
|
||||||
|
placeholder={placeholder}
|
||||||
|
readOnly={isSmsReadOnly}
|
||||||
|
style={{ minHeight: smsImages.length > 0 ? '160px' : smsTitle ? '320px' : '360px' }}
|
||||||
|
{...textareaInsert.bindSelectionHandlers}
|
||||||
|
/>
|
||||||
|
{smsPreviewSuffix ? (
|
||||||
|
<div className="whitespace-pre-wrap px-4 pb-4 text-sm leading-relaxed text-gray-700">
|
||||||
|
{smsPreviewSuffix}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
746
src/components/kri-editor/KriEditorWysiwyg.tsx
Normal file
746
src/components/kri-editor/KriEditorWysiwyg.tsx
Normal file
@@ -0,0 +1,746 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { EditorContent, useEditor, type Editor } from "@tiptap/react";
|
||||||
|
import StarterKit from "@tiptap/starter-kit";
|
||||||
|
import Underline from "@tiptap/extension-underline";
|
||||||
|
import { TextStyle } from "@tiptap/extension-text-style";
|
||||||
|
import FontFamily from "@tiptap/extension-font-family";
|
||||||
|
import Color from "@tiptap/extension-color";
|
||||||
|
import Highlight from "@tiptap/extension-highlight";
|
||||||
|
import TiptapImage from "@tiptap/extension-image";
|
||||||
|
import Placeholder from "@tiptap/extension-placeholder";
|
||||||
|
import Link from "@tiptap/extension-link";
|
||||||
|
import TextAlign from "@tiptap/extension-text-align";
|
||||||
|
|
||||||
|
import { Table } from "@tiptap/extension-table";
|
||||||
|
import TableRow from "@tiptap/extension-table-row";
|
||||||
|
import TableHeader from "@tiptap/extension-table-header";
|
||||||
|
import TableCell from "@tiptap/extension-table-cell";
|
||||||
|
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
import type { KriEditorCommand, KriEditorProps, ToolbarState } from "./types";
|
||||||
|
import { resolveUploadUrl } from "./types";
|
||||||
|
import { FontSize } from "./extensions/font-size";
|
||||||
|
import { Div } from "./extensions/div";
|
||||||
|
import { ImageMap, ImageWithMap } from "./extensions/image-map";
|
||||||
|
import { compressImage } from "./utils/imageCompression";
|
||||||
|
import { sanitizeHtml } from "./utils/sanitizeHtml";
|
||||||
|
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
|
||||||
|
import { DEFAULT_FONT_FAMILY_OPTIONS } from "./utils/fontFamilyOptions";
|
||||||
|
import { formatHtmlSource } from "./utils/formatHtml";
|
||||||
|
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
|
||||||
|
import { Toolbar } from "./toolbar/Toolbar";
|
||||||
|
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||||
|
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||||
|
|
||||||
|
type ViewMode = "wysiwyg" | "html";
|
||||||
|
|
||||||
|
function getToolbarState(editor: Editor): ToolbarState {
|
||||||
|
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
|
||||||
|
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
||||||
|
|
||||||
|
const fontFamily = (ts?.fontFamily ?? null) as string | null;
|
||||||
|
const fontSize = (ts?.fontSize ?? "16px") as string;
|
||||||
|
const textColor = (ts?.color ?? null) as string | null;
|
||||||
|
const highlightColor = (hl?.color ?? null) as string | null;
|
||||||
|
|
||||||
|
const align =
|
||||||
|
(editor.isActive({ textAlign: "center" }) && "center") ||
|
||||||
|
(editor.isActive({ textAlign: "right" }) && "right") ||
|
||||||
|
"left";
|
||||||
|
|
||||||
|
return {
|
||||||
|
fontFamily,
|
||||||
|
fontSize,
|
||||||
|
textColor,
|
||||||
|
highlightColor,
|
||||||
|
isBold: editor.isActive("bold"),
|
||||||
|
isItalic: editor.isActive("italic"),
|
||||||
|
isUnderline: editor.isActive("underline"),
|
||||||
|
isStrike: editor.isActive("strike"),
|
||||||
|
align,
|
||||||
|
isBulletList: editor.isActive("bulletList"),
|
||||||
|
isOrderedList: editor.isActive("orderedList"),
|
||||||
|
isLink: editor.isActive("link"),
|
||||||
|
inTable: editor.isActive("table"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||||
|
const {
|
||||||
|
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder = "내용을 입력하세요…",
|
||||||
|
className,
|
||||||
|
|
||||||
|
showPreview = false,
|
||||||
|
previewClassName,
|
||||||
|
|
||||||
|
mode = "wysiwyg",
|
||||||
|
debounceMs = 350,
|
||||||
|
|
||||||
|
onImageUpload,
|
||||||
|
onImageUploadError,
|
||||||
|
maxImageBytes = 5 * 1024 * 1024,
|
||||||
|
imageMaxWidth = 1600,
|
||||||
|
imageMaxHeight = 1600,
|
||||||
|
imageQuality = 0.82,
|
||||||
|
imageMimeType = "image/webp",
|
||||||
|
|
||||||
|
allowBase64 = false,
|
||||||
|
sanitizeHtml: sanitizeHtmlOpt = true,
|
||||||
|
toolbar = {},
|
||||||
|
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
|
||||||
|
editorExtensions = [],
|
||||||
|
allowedCustomHtml,
|
||||||
|
enableImageMap = false,
|
||||||
|
htmlSanitizer,
|
||||||
|
getWysiwygCompatibility,
|
||||||
|
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 getCompatibility = useCallback(
|
||||||
|
(html: string) => getWysiwygCompatibility?.(html) ?? { compatible: true },
|
||||||
|
[getWysiwygCompatibility],
|
||||||
|
);
|
||||||
|
const initialView: ViewMode = showHtmlToggle && !getCompatibility(value ?? "").compatible ? "html" : "wysiwyg";
|
||||||
|
const [view, setView] = useState<ViewMode>(initialView);
|
||||||
|
const [previewSource, setPreviewSource] = useState(value ?? "");
|
||||||
|
const viewRef = useRef<ViewMode>(initialView);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
viewRef.current = view;
|
||||||
|
}, [view]);
|
||||||
|
|
||||||
|
const htmlDraftRef = useRef<string>(value ?? "");
|
||||||
|
const canImageUpload = Boolean(onImageUpload);
|
||||||
|
|
||||||
|
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
||||||
|
|
||||||
|
const [tb, setTb] = useState<ToolbarState>({
|
||||||
|
fontFamily: null,
|
||||||
|
fontSize: "16px",
|
||||||
|
textColor: null,
|
||||||
|
highlightColor: null,
|
||||||
|
isBold: false,
|
||||||
|
isItalic: false,
|
||||||
|
isUnderline: false,
|
||||||
|
isStrike: false,
|
||||||
|
align: "left",
|
||||||
|
isBulletList: false,
|
||||||
|
isOrderedList: false,
|
||||||
|
isLink: false,
|
||||||
|
inTable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const editor = useEditor({
|
||||||
|
immediatelyRender: false,
|
||||||
|
|
||||||
|
extensions: [
|
||||||
|
StarterKit.configure({
|
||||||
|
heading: false,
|
||||||
|
blockquote: false,
|
||||||
|
codeBlock: false,
|
||||||
|
code: false,
|
||||||
|
}),
|
||||||
|
|
||||||
|
Underline,
|
||||||
|
TextStyle,
|
||||||
|
FontSize,
|
||||||
|
FontFamily,
|
||||||
|
Color,
|
||||||
|
Highlight.configure({ multicolor: true }),
|
||||||
|
Div,
|
||||||
|
|
||||||
|
Link.configure({
|
||||||
|
autolink: true,
|
||||||
|
openOnClick: false,
|
||||||
|
linkOnPaste: true,
|
||||||
|
HTMLAttributes: {
|
||||||
|
class: KRI_EDITOR_LINK_CLASS,
|
||||||
|
...LINK_HTML_ATTRS,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
|
||||||
|
TextAlign.configure({ types: ["paragraph", "divBlock"] }),
|
||||||
|
|
||||||
|
Table.configure({ resizable: true }),
|
||||||
|
TableRow,
|
||||||
|
TableHeader,
|
||||||
|
TableCell,
|
||||||
|
|
||||||
|
(enableImageMap ? ImageWithMap : TiptapImage).configure({
|
||||||
|
inline: true,
|
||||||
|
allowBase64,
|
||||||
|
HTMLAttributes: {
|
||||||
|
class: "max-w-full h-auto",
|
||||||
|
"data-kri-image": "true",
|
||||||
|
},
|
||||||
|
resize: {
|
||||||
|
enabled: true,
|
||||||
|
alwaysPreserveAspectRatio: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
...(enableImageMap ? [ImageMap] : []),
|
||||||
|
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 compatibility = getCompatibility(raw);
|
||||||
|
if (!compatibility.compatible) {
|
||||||
|
toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const safe = htmlSanitizer
|
||||||
|
? htmlSanitizer(raw)
|
||||||
|
: sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
|
||||||
|
|
||||||
|
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
|
||||||
|
flushChange(preserveEmptyParagraphs(editor.getHTML()));
|
||||||
|
setView("wysiwyg");
|
||||||
|
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]);
|
||||||
|
|
||||||
|
const formatHtmlView = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const formatted = await formatHtmlSource(htmlDraftRef.current);
|
||||||
|
htmlDraftRef.current = formatted;
|
||||||
|
if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted;
|
||||||
|
setPreviewSource(formatted);
|
||||||
|
scheduleChange(preserveEmptyParagraphs(formatted));
|
||||||
|
} catch (err) {
|
||||||
|
toast.error("HTML 정렬에 실패했습니다.");
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
}, [scheduleChange]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editor) return;
|
||||||
|
|
||||||
|
const sync = () => {
|
||||||
|
selectionRef.current = { from: editor.state.selection.from, to: editor.state.selection.to };
|
||||||
|
setTb(getToolbarState(editor));
|
||||||
|
};
|
||||||
|
|
||||||
|
sync();
|
||||||
|
editor.on("selectionUpdate", sync);
|
||||||
|
editor.on("transaction", sync);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
editor.off("selectionUpdate", sync);
|
||||||
|
editor.off("transaction", sync);
|
||||||
|
};
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!props.onEditorReady || !editor) return;
|
||||||
|
|
||||||
|
if (viewRef.current === "html") {
|
||||||
|
props.onEditorReady(htmlTextareaRef.current);
|
||||||
|
} else {
|
||||||
|
props.onEditorReady(editor);
|
||||||
|
}
|
||||||
|
}, [editor, view, props.onEditorReady]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPreviewSource(value ?? "");
|
||||||
|
if (!editor) return;
|
||||||
|
if (value == null) return;
|
||||||
|
|
||||||
|
const compatibility = getCompatibility(value);
|
||||||
|
if (showHtmlToggle && !compatibility.compatible) {
|
||||||
|
htmlDraftRef.current = value;
|
||||||
|
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value;
|
||||||
|
if (viewRef.current !== "html") {
|
||||||
|
viewRef.current = "html";
|
||||||
|
setView("html");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (viewRef.current === "html") {
|
||||||
|
if (getWysiwygCompatibility && value !== optimisticHtmlRef.current && value !== htmlDraftRef.current) {
|
||||||
|
htmlDraftRef.current = value;
|
||||||
|
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value;
|
||||||
|
}
|
||||||
|
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, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
|
||||||
|
|
||||||
|
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 = htmlSanitizer
|
||||||
|
? htmlSanitizer(preserved)
|
||||||
|
: sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
|
||||||
|
const withLinkStyle = applyLinkPreviewClass(sanitized);
|
||||||
|
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
|
||||||
|
}, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
|
||||||
|
|
||||||
|
const wysiwygCompatibility = useMemo(
|
||||||
|
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
|
||||||
|
[editor, getCompatibility, previewSource, view],
|
||||||
|
);
|
||||||
|
|
||||||
|
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"}
|
||||||
|
htmlToWysiwygDisabled={!wysiwygCompatibility.compatible}
|
||||||
|
htmlToWysiwygDisabledReason={wysiwygCompatibility.reason}
|
||||||
|
onToggleHtmlView={onToggleHtmlView}
|
||||||
|
onFormatHtml={formatHtmlView}
|
||||||
|
fontFamilyOptions={fontFamilyOptions}
|
||||||
|
onSetFontFamily={setFontFamily}
|
||||||
|
onSetFontSize={setFontSize}
|
||||||
|
onSetTextColor={setTextColor}
|
||||||
|
onUnsetTextColor={unsetTextColor}
|
||||||
|
onSetHighlight={setHighlight}
|
||||||
|
onUnsetHighlight={unsetHighlight}
|
||||||
|
linkUrl={(editor.getAttributes("link").href as string | undefined) ?? ""}
|
||||||
|
onSetLink={setLink}
|
||||||
|
onUnsetLink={unsetLink}
|
||||||
|
onInsertTable={insertTable}
|
||||||
|
onAddRow={addRow}
|
||||||
|
onAddColumn={addColumn}
|
||||||
|
onDeleteTable={deleteTable}
|
||||||
|
customContent={props.renderToolbarEnd?.({ editor, command, view })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} disabled={!canImageUpload} />
|
||||||
|
|
||||||
|
{view === "wysiwyg" ? (
|
||||||
|
<EditorContent editor={editor} />
|
||||||
|
) : (
|
||||||
|
<div className="p-2">
|
||||||
|
<textarea
|
||||||
|
ref={htmlTextareaRef}
|
||||||
|
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
|
||||||
|
defaultValue={htmlDraftRef.current}
|
||||||
|
onMouseDown={(e) => e.stopPropagation()}
|
||||||
|
onChange={(e) => {
|
||||||
|
htmlDraftRef.current = e.target.value;
|
||||||
|
setPreviewSource(htmlDraftRef.current);
|
||||||
|
scheduleChange(htmlDraftRef.current);
|
||||||
|
}}
|
||||||
|
onBlur={() => flushChange(htmlDraftRef.current)}
|
||||||
|
placeholder={placeholder}
|
||||||
|
{...htmlTi.bindSelectionHandlers}
|
||||||
|
/>
|
||||||
|
{!wysiwygCompatibility.compatible ? (
|
||||||
|
<p className="mt-2 text-xs text-amber-700" role="status">
|
||||||
|
{wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</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>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
src/components/kri-editor/extensions/div.ts
Normal file
31
src/components/kri-editor/extensions/div.ts
Normal 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];
|
||||||
|
},
|
||||||
|
});
|
||||||
46
src/components/kri-editor/extensions/font-size.ts
Normal file
46
src/components/kri-editor/extensions/font-size.ts
Normal 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();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
93
src/components/kri-editor/extensions/image-map.ts
Normal file
93
src/components/kri-editor/extensions/image-map.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { Node, mergeAttributes } from '@tiptap/core'
|
||||||
|
import TiptapImage from '@tiptap/extension-image'
|
||||||
|
import type { DOMOutputSpec } from '@tiptap/pm/model'
|
||||||
|
|
||||||
|
export type ImageMapAreaAttributes = {
|
||||||
|
shape?: string
|
||||||
|
coords?: string
|
||||||
|
href?: string
|
||||||
|
alt?: string
|
||||||
|
title?: string
|
||||||
|
target?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const readAttribute = (element: Element, name: string): string | undefined =>
|
||||||
|
element.getAttribute(name) ?? undefined
|
||||||
|
|
||||||
|
export const ImageWithMap = TiptapImage.extend({
|
||||||
|
addAttributes() {
|
||||||
|
return {
|
||||||
|
...this.parent?.(),
|
||||||
|
usemap: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('usemap'),
|
||||||
|
renderHTML: (attributes) => attributes.usemap ? { usemap: attributes.usemap } : {},
|
||||||
|
},
|
||||||
|
align: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('align'),
|
||||||
|
renderHTML: (attributes) => attributes.align ? { align: attributes.align } : {},
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('style'),
|
||||||
|
renderHTML: (attributes) => attributes.style ? { style: attributes.style } : {},
|
||||||
|
},
|
||||||
|
loading: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('loading'),
|
||||||
|
renderHTML: (attributes) => attributes.loading ? { loading: attributes.loading } : {},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const ImageMap = Node.create({
|
||||||
|
name: 'imageMap',
|
||||||
|
group: 'block',
|
||||||
|
atom: true,
|
||||||
|
|
||||||
|
addAttributes() {
|
||||||
|
return {
|
||||||
|
name: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('name'),
|
||||||
|
renderHTML: (attributes) => attributes.name ? { name: attributes.name } : {},
|
||||||
|
},
|
||||||
|
id: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('id'),
|
||||||
|
renderHTML: (attributes) => attributes.id ? { id: attributes.id } : {},
|
||||||
|
},
|
||||||
|
areas: {
|
||||||
|
default: [],
|
||||||
|
parseHTML: (element) => Array.from(element.children)
|
||||||
|
.filter((child) => child.tagName.toLowerCase() === 'area')
|
||||||
|
.map((area): ImageMapAreaAttributes => ({
|
||||||
|
shape: readAttribute(area, 'shape'),
|
||||||
|
coords: readAttribute(area, 'coords'),
|
||||||
|
href: readAttribute(area, 'href'),
|
||||||
|
alt: readAttribute(area, 'alt'),
|
||||||
|
title: readAttribute(area, 'title'),
|
||||||
|
target: readAttribute(area, 'target'),
|
||||||
|
})),
|
||||||
|
renderHTML: () => ({}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
parseHTML() {
|
||||||
|
return [{ tag: 'map' }]
|
||||||
|
},
|
||||||
|
|
||||||
|
renderHTML({ node, HTMLAttributes }) {
|
||||||
|
const mapAttributes = { ...HTMLAttributes }
|
||||||
|
delete mapAttributes.areas
|
||||||
|
const areas = (node.attrs.areas as ImageMapAreaAttributes[]).map((area): DOMOutputSpec => [
|
||||||
|
'area',
|
||||||
|
Object.fromEntries(Object.entries(area).filter(([, value]) => Boolean(value))),
|
||||||
|
])
|
||||||
|
|
||||||
|
return ['map', mergeAttributes(mapAttributes), ...areas] as DOMOutputSpec
|
||||||
|
},
|
||||||
|
})
|
||||||
42
src/components/kri-editor/hooks/useDebouncedChange.ts
Normal file
42
src/components/kri-editor/hooks/useDebouncedChange.ts
Normal 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 };
|
||||||
|
}
|
||||||
61
src/components/kri-editor/hooks/useTextareaInsert.ts
Normal file
61
src/components/kri-editor/hooks/useTextareaInsert.ts
Normal 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,
|
||||||
|
};
|
||||||
|
}
|
||||||
21
src/components/kri-editor/index.ts
Normal file
21
src/components/kri-editor/index.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
export { KriEditor } from './KriEditor'
|
||||||
|
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
|
||||||
|
export { KriEditorKko } from './KriEditorKko'
|
||||||
|
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,
|
||||||
|
KriEditorWysiwygCompatibility,
|
||||||
|
ToolbarState,
|
||||||
|
} from './types'
|
||||||
|
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'
|
||||||
326
src/components/kri-editor/toolbar/Toolbar.tsx
Normal file
326
src/components/kri-editor/toolbar/Toolbar.tsx
Normal file
@@ -0,0 +1,326 @@
|
|||||||
|
'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
|
||||||
|
htmlToWysiwygDisabled?: boolean
|
||||||
|
htmlToWysiwygDisabledReason?: string
|
||||||
|
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,
|
||||||
|
htmlToWysiwygDisabled = false,
|
||||||
|
htmlToWysiwygDisabledReason,
|
||||||
|
onToggleHtmlView,
|
||||||
|
onFormatHtml,
|
||||||
|
fontFamilyOptions,
|
||||||
|
onSetFontFamily,
|
||||||
|
onSetFontSize,
|
||||||
|
onSetTextColor,
|
||||||
|
onUnsetTextColor,
|
||||||
|
onSetHighlight,
|
||||||
|
onUnsetHighlight,
|
||||||
|
linkUrl,
|
||||||
|
onSetLink,
|
||||||
|
onUnsetLink,
|
||||||
|
onInsertTable,
|
||||||
|
onAddRow,
|
||||||
|
onAddColumn,
|
||||||
|
onDeleteTable,
|
||||||
|
customContent,
|
||||||
|
}: ToolbarProps) {
|
||||||
|
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
|
||||||
|
const showFontControls = enabled('fontFamily') || enabled('fontSize')
|
||||||
|
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
|
||||||
|
const showColors = enabled('textColor') || enabled('highlight')
|
||||||
|
const showLists = enabled('bulletList') || enabled('orderedList')
|
||||||
|
const [linkOpen, setLinkOpen] = useState(false)
|
||||||
|
const [linkDraft, setLinkDraft] = useState(linkUrl)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (linkOpen) setLinkDraft(linkUrl)
|
||||||
|
}, [linkOpen, linkUrl])
|
||||||
|
|
||||||
|
const applyLink = () => {
|
||||||
|
const next = linkDraft.trim()
|
||||||
|
if (!next) return
|
||||||
|
onSetLink(next)
|
||||||
|
setLinkOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
|
||||||
|
{enabled('fontFamily') ? (
|
||||||
|
<select
|
||||||
|
className="h-8 w-[150px] rounded-md border bg-background px-2 text-sm"
|
||||||
|
value={state.fontFamily ?? ''}
|
||||||
|
onChange={(event) => onSetFontFamily(event.target.value)}
|
||||||
|
title="글꼴"
|
||||||
|
>
|
||||||
|
{fontFamilyOptions.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>{option.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{enabled('fontSize') ? (
|
||||||
|
<select
|
||||||
|
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
|
||||||
|
value={state.fontSize}
|
||||||
|
onChange={(event) => onSetFontSize(event.target.value)}
|
||||||
|
title="폰트 크기"
|
||||||
|
>
|
||||||
|
{['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px'].map((value) => (
|
||||||
|
<option key={value} value={value}>{value.replace('px', '')}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{showFontControls && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||||
|
|
||||||
|
{enabled('bold') ? (
|
||||||
|
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">
|
||||||
|
<Bold className="size-4" />
|
||||||
|
</ToolbarButton>
|
||||||
|
) : null}
|
||||||
|
{enabled('italic') ? (
|
||||||
|
<ToolbarButton active={state.isItalic} disabled={!editor.can().chain().focus().toggleItalic().run()} onClick={() => editor.chain().focus().toggleItalic().run()} title="기울임">
|
||||||
|
<Italic className="size-4" />
|
||||||
|
</ToolbarButton>
|
||||||
|
) : null}
|
||||||
|
{enabled('underline') ? (
|
||||||
|
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
|
||||||
|
<Underline className="size-4" />
|
||||||
|
</ToolbarButton>
|
||||||
|
) : null}
|
||||||
|
{enabled('strike') ? (
|
||||||
|
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
|
||||||
|
<Strikethrough className="size-4" />
|
||||||
|
</ToolbarButton>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{showTextStyle && showColors ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||||
|
|
||||||
|
{enabled('textColor') ? (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<span>
|
||||||
|
<ToolbarButton title="텍스트 색상" active={Boolean(state.textColor)}>
|
||||||
|
<Palette className="size-4" /><Swatch color={state.textColor} />
|
||||||
|
</ToolbarButton>
|
||||||
|
</span>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-56" align="start">
|
||||||
|
<div className="text-muted-foreground mb-2 text-xs">텍스트 색상</div>
|
||||||
|
<div className="grid grid-cols-5 gap-2">
|
||||||
|
{PRESET_COLORS.map((color) => (
|
||||||
|
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetTextColor(color)} aria-label={`색상 ${color}`} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex items-center gap-2">
|
||||||
|
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetTextColor(event.target.value)} aria-label="사용자 지정 텍스트 색상" />
|
||||||
|
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetTextColor}>색상 제거</button>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{enabled('highlight') ? (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<span>
|
||||||
|
<ToolbarButton title="하이라이트" active={Boolean(state.highlightColor)}>
|
||||||
|
<Highlighter className="size-4" /><Swatch color={state.highlightColor} />
|
||||||
|
</ToolbarButton>
|
||||||
|
</span>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-56" align="start">
|
||||||
|
<div className="text-muted-foreground mb-2 text-xs">하이라이트</div>
|
||||||
|
<div className="grid grid-cols-5 gap-2">
|
||||||
|
{HIGHLIGHT_COLORS.map((color) => (
|
||||||
|
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetHighlight(color)} aria-label={`하이라이트 ${color}`} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex items-center gap-2">
|
||||||
|
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetHighlight(event.target.value)} aria-label="사용자 지정 하이라이트" />
|
||||||
|
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetHighlight}>하이라이트 제거</button>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{showColors && enabled('align') ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||||
|
|
||||||
|
{enabled('align') ? (
|
||||||
|
<>
|
||||||
|
<ToolbarButton active={state.align === 'left'} onClick={() => editor.chain().focus().setTextAlign('left').run()} title="왼쪽 정렬"><AlignLeft className="size-4" /></ToolbarButton>
|
||||||
|
<ToolbarButton active={state.align === 'center'} onClick={() => editor.chain().focus().setTextAlign('center').run()} title="가운데 정렬"><AlignCenter className="size-4" /></ToolbarButton>
|
||||||
|
<ToolbarButton active={state.align === 'right'} onClick={() => editor.chain().focus().setTextAlign('right').run()} title="오른쪽 정렬"><AlignRight className="size-4" /></ToolbarButton>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{enabled('align') && showLists ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||||
|
|
||||||
|
{enabled('bulletList') ? <ToolbarButton active={state.isBulletList} onClick={() => editor.chain().focus().toggleBulletList().run()} title="불릿"><List className="size-4" /></ToolbarButton> : null}
|
||||||
|
{enabled('orderedList') ? <ToolbarButton active={state.isOrderedList} onClick={() => editor.chain().focus().toggleOrderedList().run()} title="번호"><ListOrdered className="size-4" /></ToolbarButton> : null}
|
||||||
|
|
||||||
|
{showLists && (enabled('link') || enabled('image') || enabled('table')) ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||||
|
|
||||||
|
{enabled('link') ? (
|
||||||
|
<Popover open={linkOpen} onOpenChange={setLinkOpen}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<span>
|
||||||
|
<ToolbarButton active={state.isLink} title={state.isLink ? '링크 수정' : '링크 삽입'}>
|
||||||
|
<Link2 className="size-4" />
|
||||||
|
</ToolbarButton>
|
||||||
|
</span>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-80" align="start">
|
||||||
|
<form
|
||||||
|
className="space-y-3"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
applyLink()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label htmlFor="kri-editor-link-url" className="text-sm font-medium">링크 URL</label>
|
||||||
|
<Input
|
||||||
|
id="kri-editor-link-url"
|
||||||
|
value={linkDraft}
|
||||||
|
onChange={(event) => setLinkDraft(event.target.value)}
|
||||||
|
placeholder="https://example.com"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
{state.isLink ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
onUnsetLink()
|
||||||
|
setLinkOpen(false)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
링크 해제
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button type="submit" size="sm" disabled={!linkDraft.trim()}>적용</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
) : null}
|
||||||
|
{enabled('image') ? <ToolbarButton title={canImageUpload ? '이미지 업로드' : 'onImageUpload 미설정'} disabled={!canImageUpload} onClick={onPickImage}><ImageIcon className="size-4" /></ToolbarButton> : null}
|
||||||
|
|
||||||
|
{enabled('table') ? (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild><span><ToolbarButton title="표"><Table2 className="size-4" /></ToolbarButton></span></DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-44">
|
||||||
|
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onInsertTable() }}>표 삽입</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddRow() }} disabled={!state.inTable}>행 추가</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddColumn() }} disabled={!state.inTable}>열 추가</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onDeleteTable() }} disabled={!state.inTable} className="text-destructive">표 삭제</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{showHtmlToggle && enabled('html') ? (
|
||||||
|
<>
|
||||||
|
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||||
|
<ToolbarButton
|
||||||
|
active={isHtmlView}
|
||||||
|
disabled={isHtmlView && htmlToWysiwygDisabled}
|
||||||
|
title={isHtmlView && htmlToWysiwygDisabled ? (htmlToWysiwygDisabledReason ?? 'WYSIWYG로 전환할 수 없습니다.') : (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>
|
||||||
|
)
|
||||||
|
}
|
||||||
35
src/components/kri-editor/toolbar/ToolbarButton.tsx
Normal file
35
src/components/kri-editor/toolbar/ToolbarButton.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
127
src/components/kri-editor/types.ts
Normal file
127
src/components/kri-editor/types.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import type { Extensions } from '@tiptap/core'
|
||||||
|
import type { Editor } from '@tiptap/react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms' | 'kko'
|
||||||
|
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 KriEditorWysiwygCompatibility = {
|
||||||
|
compatible: boolean
|
||||||
|
reason?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type KriEditorFontFamilyOption = {
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type KriEditorSmsImage = {
|
||||||
|
fileName: string
|
||||||
|
src: 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
|
||||||
|
smsPreviewSuffix?: string
|
||||||
|
/** 첨부파일이 있으면 길이·제목과 무관하게 LMS/MMS로 판정한다. */
|
||||||
|
smsHasAttachment?: boolean
|
||||||
|
/** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */
|
||||||
|
smsImages?: KriEditorSmsImage[]
|
||||||
|
/** 알림톡 미리보기의 강조 제목. 없으면 표시하지 않는다. */
|
||||||
|
kkoTitle?: string
|
||||||
|
/** 알림톡 미리보기의 채널명·발신 프로필 이름. 없으면 표시하지 않는다. */
|
||||||
|
kkoSenderName?: string
|
||||||
|
/** 알림톡 말풍선 상단 문구. 기본값 "알림톡 도착" */
|
||||||
|
kkoHeaderLabel?: string
|
||||||
|
toolbar?: KriEditorToolbarConfig | false
|
||||||
|
fontFamilyOptions?: KriEditorFontFamilyOption[]
|
||||||
|
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
|
||||||
|
editorExtensions?: Extensions
|
||||||
|
allowedCustomHtml?: KriEditorAllowedHtml
|
||||||
|
enableImageMap?: boolean
|
||||||
|
htmlSanitizer?: (html: string) => string
|
||||||
|
getWysiwygCompatibility?: (html: string) => KriEditorWysiwygCompatibility
|
||||||
|
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
|
||||||
|
}
|
||||||
9
src/components/kri-editor/utils/editorTypeGuards.ts
Normal file
9
src/components/kri-editor/utils/editorTypeGuards.ts
Normal 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
|
||||||
|
}
|
||||||
9
src/components/kri-editor/utils/emptyParagraph.ts
Normal file
9
src/components/kri-editor/utils/emptyParagraph.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
const EMPTY_PARAGRAPH_PATTERN = /<p((?:\s+[^>]*)?)>\s*<\/p>/gi;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TipTap이 빈 줄을 <p></p>로 직렬화하면 이메일 클라이언트에서 margin collapse로 사라진다.
|
||||||
|
* 눈에 보이지 않는 콘텐츠( )를 채워 실제 발송 HTML에서도 빈 줄이 유지되게 한다.
|
||||||
|
*/
|
||||||
|
export function preserveEmptyParagraphs(html: string): string {
|
||||||
|
return html.replace(EMPTY_PARAGRAPH_PATTERN, (_match, attrs: string) => `<p${attrs}> </p>`);
|
||||||
|
}
|
||||||
29
src/components/kri-editor/utils/fontFamilyOptions.ts
Normal file
29
src/components/kri-editor/utils/fontFamilyOptions.ts
Normal 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" },
|
||||||
|
];
|
||||||
16
src/components/kri-editor/utils/formatHtml.ts
Normal file
16
src/components/kri-editor/utils/formatHtml.ts
Normal 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",
|
||||||
|
});
|
||||||
|
}
|
||||||
85
src/components/kri-editor/utils/imageCompression.ts
Normal file
85
src/components/kri-editor/utils/imageCompression.ts
Normal 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 });
|
||||||
|
}
|
||||||
29
src/components/kri-editor/utils/linkPreview.ts
Normal file
29
src/components/kri-editor/utils/linkPreview.ts
Normal 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}>`;
|
||||||
|
});
|
||||||
|
}
|
||||||
53
src/components/kri-editor/utils/sanitizeHtml.ts
Normal file
53
src/components/kri-editor/utils/sanitizeHtml.ts
Normal 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);
|
||||||
|
}
|
||||||
78
src/components/layout/KriHeader.tsx
Normal file
78
src/components/layout/KriHeader.tsx
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { Menu, X } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { KriNavigationItem } from './types'
|
||||||
|
|
||||||
|
export interface KriHeaderProps {
|
||||||
|
logo?: ReactNode
|
||||||
|
homePath?: string
|
||||||
|
menus?: KriNavigationItem[]
|
||||||
|
activeMenuId?: string
|
||||||
|
menuOpen?: boolean
|
||||||
|
showMenuButton?: boolean
|
||||||
|
onToggleMenu?: () => void
|
||||||
|
onNavigate?: (path: string, item?: KriNavigationItem) => void
|
||||||
|
center?: ReactNode
|
||||||
|
right?: ReactNode
|
||||||
|
sticky?: boolean
|
||||||
|
className?: string
|
||||||
|
innerClassName?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function KriHeader({
|
||||||
|
logo,
|
||||||
|
homePath = '/',
|
||||||
|
menus = [],
|
||||||
|
activeMenuId,
|
||||||
|
menuOpen = false,
|
||||||
|
showMenuButton = true,
|
||||||
|
onToggleMenu,
|
||||||
|
onNavigate,
|
||||||
|
center,
|
||||||
|
right,
|
||||||
|
sticky = true,
|
||||||
|
className,
|
||||||
|
innerClassName,
|
||||||
|
}: KriHeaderProps) {
|
||||||
|
return (
|
||||||
|
<header className={cn('border-b bg-background', sticky && 'sticky top-0 z-40', className)}>
|
||||||
|
<div className={cn('flex h-16 items-center justify-between gap-4 px-4', innerClassName)}>
|
||||||
|
<div className="flex min-w-0 items-center gap-4">
|
||||||
|
{showMenuButton && onToggleMenu ? (
|
||||||
|
<Button type="button" variant="ghost" size="icon" onClick={onToggleMenu} aria-label={menuOpen ? '메뉴 닫기' : '메뉴 열기'}>
|
||||||
|
{menuOpen ? <X className="size-5" /> : <Menu className="size-5" />}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{logo ? (
|
||||||
|
<button type="button" className="flex shrink-0 items-center cursor-pointer" onClick={() => onNavigate?.(homePath)}>
|
||||||
|
{logo}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{menus.length ? (
|
||||||
|
<nav className="hidden items-center gap-1 md:flex">
|
||||||
|
{menus.map((item) => (
|
||||||
|
<Button
|
||||||
|
key={item.id}
|
||||||
|
type="button"
|
||||||
|
variant={activeMenuId === item.id ? 'default' : 'ghost'}
|
||||||
|
disabled={item.disabled || !item.path}
|
||||||
|
onClick={() => item.path && onNavigate?.(item.path, item)}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1 text-center">{center}</div>
|
||||||
|
<div className="flex shrink-0 items-center gap-2">{right}</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
50
src/components/layout/KriMainLayout.tsx
Normal file
50
src/components/layout/KriMainLayout.tsx
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import type { CSSProperties, ReactNode } from 'react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export interface KriMainLayoutProps {
|
||||||
|
children: ReactNode
|
||||||
|
header?: ReactNode
|
||||||
|
sidebar?: ReactNode
|
||||||
|
sidebarOpen?: boolean
|
||||||
|
onSidebarOpenChange?: (open: boolean) => void
|
||||||
|
fullHeight?: boolean
|
||||||
|
className?: string
|
||||||
|
bodyClassName?: string
|
||||||
|
mainClassName?: string
|
||||||
|
mainStyle?: CSSProperties
|
||||||
|
}
|
||||||
|
|
||||||
|
export function KriMainLayout({
|
||||||
|
children,
|
||||||
|
header,
|
||||||
|
sidebar,
|
||||||
|
sidebarOpen = false,
|
||||||
|
onSidebarOpenChange,
|
||||||
|
fullHeight = true,
|
||||||
|
className,
|
||||||
|
bodyClassName,
|
||||||
|
mainClassName,
|
||||||
|
mainStyle,
|
||||||
|
}: KriMainLayoutProps) {
|
||||||
|
return (
|
||||||
|
<div className={cn('flex flex-col bg-muted/30', fullHeight && 'min-h-screen', className)}>
|
||||||
|
{header}
|
||||||
|
<div className={cn('flex min-h-0 flex-1', bodyClassName)}>
|
||||||
|
{sidebar}
|
||||||
|
<main className={cn('min-w-0 flex-1 overflow-y-auto p-4', mainClassName)} style={mainStyle}>
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
{sidebar && sidebarOpen ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="사이드바 닫기"
|
||||||
|
className="fixed inset-0 z-20 bg-black/20 lg:hidden"
|
||||||
|
onClick={() => onSidebarOpenChange?.(false)}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
22
src/components/layout/KriPageTitle.tsx
Normal file
22
src/components/layout/KriPageTitle.tsx
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export interface KriPageTitleProps {
|
||||||
|
title: ReactNode
|
||||||
|
description?: ReactNode
|
||||||
|
actions?: ReactNode
|
||||||
|
className?: string
|
||||||
|
titleClassName?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function KriPageTitle({ title, description, actions, className, titleClassName }: KriPageTitleProps) {
|
||||||
|
return (
|
||||||
|
<div className={cn('flex items-start justify-between gap-4', className)}>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h1 className={cn('text-2xl font-bold tracking-tight', titleClassName)}>{title}</h1>
|
||||||
|
{description ? <div className="text-muted-foreground mt-1 text-sm">{description}</div> : null}
|
||||||
|
</div>
|
||||||
|
{actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
129
src/components/layout/KriSidebar.tsx
Normal file
129
src/components/layout/KriSidebar.tsx
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import { ChevronDown } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { KriNavigationItem } from './types'
|
||||||
|
|
||||||
|
export interface KriSidebarProps {
|
||||||
|
items: KriNavigationItem[]
|
||||||
|
isOpen: boolean
|
||||||
|
pathname?: string
|
||||||
|
header?: React.ReactNode
|
||||||
|
openItemIds?: string[]
|
||||||
|
defaultOpenItemIds?: string[]
|
||||||
|
onOpenItemIdsChange?: (ids: string[]) => void
|
||||||
|
onNavigate?: (path: string, item: KriNavigationItem) => void
|
||||||
|
className?: string
|
||||||
|
contentClassName?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function isActive(item: KriNavigationItem, pathname: string): boolean {
|
||||||
|
if (item.match) return item.match(pathname)
|
||||||
|
if (item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`))) return true
|
||||||
|
return item.children?.some((child) => isActive(child, pathname)) ?? false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function KriSidebar({
|
||||||
|
items,
|
||||||
|
isOpen,
|
||||||
|
pathname = '',
|
||||||
|
header,
|
||||||
|
openItemIds,
|
||||||
|
defaultOpenItemIds = [],
|
||||||
|
onOpenItemIdsChange,
|
||||||
|
onNavigate,
|
||||||
|
className,
|
||||||
|
contentClassName,
|
||||||
|
}: KriSidebarProps) {
|
||||||
|
const [internalOpenIds, setInternalOpenIds] = React.useState(defaultOpenItemIds)
|
||||||
|
const currentOpenIds = openItemIds ?? internalOpenIds
|
||||||
|
|
||||||
|
const setOpenIds = (next: string[]) => {
|
||||||
|
if (openItemIds === undefined) setInternalOpenIds(next)
|
||||||
|
onOpenItemIdsChange?.(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleItem = (id: string) => {
|
||||||
|
setOpenIds(currentOpenIds.includes(id) ? currentOpenIds.filter((value) => value !== id) : [...currentOpenIds, id])
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside
|
||||||
|
className={cn(
|
||||||
|
'fixed top-16 left-0 z-30 h-[calc(100vh-4rem)] overflow-y-auto border-r bg-background transition-all duration-300 lg:static lg:top-0 lg:h-auto lg:translate-x-0',
|
||||||
|
isOpen ? 'w-64 translate-x-0' : 'w-64 -translate-x-full lg:w-0 lg:border-r-0',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className={cn('h-full space-y-4 overflow-y-auto p-4', contentClassName)}>
|
||||||
|
{header}
|
||||||
|
<nav className="space-y-1">
|
||||||
|
{items.map((item) => {
|
||||||
|
const active = isActive(item, pathname)
|
||||||
|
const hasChildren = Boolean(item.children?.length)
|
||||||
|
const opened = currentOpenIds.includes(item.id)
|
||||||
|
const Icon = item.icon
|
||||||
|
|
||||||
|
if (!hasChildren) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
key={item.id}
|
||||||
|
type="button"
|
||||||
|
variant={active ? 'secondary' : 'ghost'}
|
||||||
|
className="w-full justify-start"
|
||||||
|
disabled={item.disabled || !item.path}
|
||||||
|
onClick={() => item.path && onNavigate?.(item.path, item)}
|
||||||
|
>
|
||||||
|
{Icon ? <Icon className="size-4" /> : null}
|
||||||
|
<span>{item.label}</span>
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={item.id} className="space-y-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={active ? 'secondary' : 'ghost'}
|
||||||
|
className="w-full justify-between"
|
||||||
|
disabled={item.disabled}
|
||||||
|
onClick={() => toggleItem(item.id)}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
{Icon ? <Icon className="size-4" /> : null}
|
||||||
|
<span>{item.label}</span>
|
||||||
|
</span>
|
||||||
|
<ChevronDown className={cn('size-4 transition-transform', opened && 'rotate-180')} />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{opened ? (
|
||||||
|
<div className="ml-6 space-y-1">
|
||||||
|
{item.children?.map((child) => {
|
||||||
|
const childActive = isActive(child, pathname)
|
||||||
|
const ChildIcon = child.icon
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
key={child.id}
|
||||||
|
type="button"
|
||||||
|
variant={childActive ? 'secondary' : 'ghost'}
|
||||||
|
className="w-full justify-start"
|
||||||
|
disabled={child.disabled || !child.path}
|
||||||
|
onClick={() => child.path && onNavigate?.(child.path, child)}
|
||||||
|
>
|
||||||
|
{ChildIcon ? <ChildIcon className="size-4" /> : null}
|
||||||
|
<span>{child.label}</span>
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
)
|
||||||
|
}
|
||||||
9
src/components/layout/index.ts
Normal file
9
src/components/layout/index.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export { KriHeader } from './KriHeader'
|
||||||
|
export { KriMainLayout } from './KriMainLayout'
|
||||||
|
export { KriPageTitle } from './KriPageTitle'
|
||||||
|
export { KriSidebar } from './KriSidebar'
|
||||||
|
export type { KriNavigationItem } from './types'
|
||||||
|
export type { KriHeaderProps } from './KriHeader'
|
||||||
|
export type { KriMainLayoutProps } from './KriMainLayout'
|
||||||
|
export type { KriPageTitleProps } from './KriPageTitle'
|
||||||
|
export type { KriSidebarProps } from './KriSidebar'
|
||||||
11
src/components/layout/types.ts
Normal file
11
src/components/layout/types.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import type { ComponentType, ReactNode } from 'react'
|
||||||
|
|
||||||
|
export interface KriNavigationItem {
|
||||||
|
id: string
|
||||||
|
label: ReactNode
|
||||||
|
path?: string
|
||||||
|
icon?: ComponentType<{ className?: string }>
|
||||||
|
children?: KriNavigationItem[]
|
||||||
|
disabled?: boolean
|
||||||
|
match?: (pathname: string) => boolean
|
||||||
|
}
|
||||||
18
src/components/providers/AppProvider.tsx
Normal file
18
src/components/providers/AppProvider.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Provider as JotaiProvider } from "jotai";
|
||||||
|
import { QueryProvider } from "@kri/common/query";
|
||||||
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
|
import { QueryLoadingSync } from "./QueryLoadingSync";
|
||||||
|
|
||||||
|
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<JotaiProvider>
|
||||||
|
<QueryProvider>
|
||||||
|
<QueryLoadingSync />
|
||||||
|
<LoadingOverlayAdapter />
|
||||||
|
{children}
|
||||||
|
</QueryProvider>
|
||||||
|
</JotaiProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
src/components/providers/QueryLoadingSync.tsx
Normal file
10
src/components/providers/QueryLoadingSync.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { QueryLoadingSync as CommonQueryLoadingSync } from "@kri/common/query";
|
||||||
|
import { useSetAtom } from "jotai";
|
||||||
|
import { queryLoadingAtom } from "@/store/jotai/loading";
|
||||||
|
|
||||||
|
export function QueryLoadingSync() {
|
||||||
|
const setQueryLoading = useSetAtom(queryLoadingAtom);
|
||||||
|
return <CommonQueryLoadingSync onLoadingChange={setQueryLoading} />;
|
||||||
|
}
|
||||||
47
src/components/ui/badge.tsx
Normal file
47
src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
import { cn } from "cn"
|
||||||
|
import { Slot } from "radix-ui"
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
|
||||||
|
outline:
|
||||||
|
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
link: "text-primary underline-offset-4 [a&]:hover:underline",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span"> &
|
||||||
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot.Root : "span"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="badge"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(badgeVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
63
src/components/ui/button.tsx
Normal file
63
src/components/ui/button.tsx
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
import { cn } from "cn"
|
||||||
|
import { Slot } from "radix-ui"
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||||
|
outline:
|
||||||
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
|
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||||
|
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||||
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
|
icon: "size-9",
|
||||||
|
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"button"> &
|
||||||
|
VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot.Root : "button"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants }
|
||||||
220
src/components/ui/calendar.tsx
Normal file
220
src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "cn"
|
||||||
|
import {
|
||||||
|
ChevronDownIcon,
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
|
} from "lucide-react"
|
||||||
|
import {
|
||||||
|
DayPicker,
|
||||||
|
getDefaultClassNames,
|
||||||
|
type DayButton,
|
||||||
|
} from "react-day-picker"
|
||||||
|
|
||||||
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function Calendar({
|
||||||
|
className,
|
||||||
|
classNames,
|
||||||
|
showOutsideDays = true,
|
||||||
|
captionLayout = "label",
|
||||||
|
buttonVariant = "ghost",
|
||||||
|
formatters,
|
||||||
|
components,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||||
|
}) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DayPicker
|
||||||
|
showOutsideDays={showOutsideDays}
|
||||||
|
className={cn(
|
||||||
|
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||||
|
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||||
|
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
captionLayout={captionLayout}
|
||||||
|
formatters={{
|
||||||
|
formatMonthDropdown: (date) =>
|
||||||
|
date.toLocaleString("default", { month: "short" }),
|
||||||
|
...formatters,
|
||||||
|
}}
|
||||||
|
classNames={{
|
||||||
|
root: cn("w-fit", defaultClassNames.root),
|
||||||
|
months: cn(
|
||||||
|
"relative flex flex-col gap-4 md:flex-row",
|
||||||
|
defaultClassNames.months
|
||||||
|
),
|
||||||
|
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||||
|
nav: cn(
|
||||||
|
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||||
|
defaultClassNames.nav
|
||||||
|
),
|
||||||
|
button_previous: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
|
defaultClassNames.button_previous
|
||||||
|
),
|
||||||
|
button_next: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
|
defaultClassNames.button_next
|
||||||
|
),
|
||||||
|
month_caption: cn(
|
||||||
|
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
|
||||||
|
defaultClassNames.month_caption
|
||||||
|
),
|
||||||
|
dropdowns: cn(
|
||||||
|
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||||
|
defaultClassNames.dropdowns
|
||||||
|
),
|
||||||
|
dropdown_root: cn(
|
||||||
|
"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50",
|
||||||
|
defaultClassNames.dropdown_root
|
||||||
|
),
|
||||||
|
dropdown: cn(
|
||||||
|
"absolute inset-0 bg-popover opacity-0",
|
||||||
|
defaultClassNames.dropdown
|
||||||
|
),
|
||||||
|
caption_label: cn(
|
||||||
|
"font-medium select-none",
|
||||||
|
captionLayout === "label"
|
||||||
|
? "text-sm"
|
||||||
|
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||||
|
defaultClassNames.caption_label
|
||||||
|
),
|
||||||
|
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
|
||||||
|
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||||
|
weekday: cn(
|
||||||
|
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||||
|
defaultClassNames.weekday
|
||||||
|
),
|
||||||
|
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||||
|
week_number_header: cn(
|
||||||
|
"w-(--cell-size) select-none",
|
||||||
|
defaultClassNames.week_number_header
|
||||||
|
),
|
||||||
|
week_number: cn(
|
||||||
|
"text-[0.8rem] text-muted-foreground select-none",
|
||||||
|
defaultClassNames.week_number
|
||||||
|
),
|
||||||
|
day: cn(
|
||||||
|
"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md",
|
||||||
|
props.showWeekNumber
|
||||||
|
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||||
|
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||||
|
defaultClassNames.day
|
||||||
|
),
|
||||||
|
range_start: cn(
|
||||||
|
"rounded-l-md bg-accent",
|
||||||
|
defaultClassNames.range_start
|
||||||
|
),
|
||||||
|
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||||
|
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||||
|
today: cn(
|
||||||
|
"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none",
|
||||||
|
defaultClassNames.today
|
||||||
|
),
|
||||||
|
outside: cn(
|
||||||
|
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||||
|
defaultClassNames.outside
|
||||||
|
),
|
||||||
|
disabled: cn(
|
||||||
|
"text-muted-foreground opacity-50",
|
||||||
|
defaultClassNames.disabled
|
||||||
|
),
|
||||||
|
hidden: cn("invisible", defaultClassNames.hidden),
|
||||||
|
...classNames,
|
||||||
|
}}
|
||||||
|
components={{
|
||||||
|
Root: ({ className, rootRef, ...props }) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="calendar"
|
||||||
|
ref={rootRef}
|
||||||
|
className={cn(className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Chevron: ({ className, orientation, ...props }) => {
|
||||||
|
if (orientation === "left") {
|
||||||
|
return (
|
||||||
|
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (orientation === "right") {
|
||||||
|
return (
|
||||||
|
<ChevronRightIcon
|
||||||
|
className={cn("size-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
},
|
||||||
|
DayButton: CalendarDayButton,
|
||||||
|
WeekNumber: ({ children, ...props }) => {
|
||||||
|
return (
|
||||||
|
<td {...props}>
|
||||||
|
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
...components,
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CalendarDayButton({
|
||||||
|
className,
|
||||||
|
day,
|
||||||
|
modifiers,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayButton>) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
const ref = React.useRef<HTMLButtonElement>(null)
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (modifiers.focused) ref.current?.focus()
|
||||||
|
}, [modifiers.focused])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
data-day={day.date.toLocaleDateString()}
|
||||||
|
data-selected-single={
|
||||||
|
modifiers.selected &&
|
||||||
|
!modifiers.range_start &&
|
||||||
|
!modifiers.range_end &&
|
||||||
|
!modifiers.range_middle
|
||||||
|
}
|
||||||
|
data-range-start={modifiers.range_start}
|
||||||
|
data-range-end={modifiers.range_end}
|
||||||
|
data-range-middle={modifiers.range_middle}
|
||||||
|
className={cn(
|
||||||
|
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
|
||||||
|
defaultClassNames.day,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Calendar, CalendarDayButton }
|
||||||
91
src/components/ui/card.tsx
Normal file
91
src/components/ui/card.tsx
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "cn"
|
||||||
|
|
||||||
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn("leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-content"
|
||||||
|
className={cn("px-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Card,
|
||||||
|
CardHeader,
|
||||||
|
CardFooter,
|
||||||
|
CardTitle,
|
||||||
|
CardAction,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
}
|
||||||
31
src/components/ui/checkbox.tsx
Normal file
31
src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "cn"
|
||||||
|
import { CheckIcon } from "lucide-react"
|
||||||
|
import { Checkbox as CheckboxPrimitive } from "radix-ui"
|
||||||
|
|
||||||
|
function Checkbox({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<CheckboxPrimitive.Root
|
||||||
|
data-slot="checkbox"
|
||||||
|
className={cn(
|
||||||
|
"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<CheckboxPrimitive.Indicator
|
||||||
|
data-slot="checkbox-indicator"
|
||||||
|
className="grid place-content-center text-current transition-none"
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3.5" />
|
||||||
|
</CheckboxPrimitive.Indicator>
|
||||||
|
</CheckboxPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Checkbox }
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user