260703_01_FST: First Commit

This commit is contained in:
2026-07-03 10:40:45 +09:00
commit b11d47b14e
65 changed files with 11002 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules/
dist/
.idea/
*.iml
.DS_Store

View File

@@ -0,0 +1,12 @@
import type { HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export type BadgeVariant = "default" | "secondary" | "outline" | "destructive";
export interface BadgeProps extends HTMLAttributes<HTMLSpanElement> {
variant?: BadgeVariant;
}
export function Badge({ className, variant = "default", ...props }: BadgeProps) {
return <span data-variant={variant} className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,17 @@
import { forwardRef, type ButtonHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export type ButtonVariant = "default" | "outline" | "ghost" | "secondary" | "destructive" | "link";
export type ButtonSize = "default" | "sm" | "lg" | "icon" | "icon-sm";
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
}
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant = "default", size = "default", ...props }, ref) => (
<button ref={ref} data-variant={variant} data-size={size} className={cn(className)} {...props} />
)
);
Button.displayName = "Button";

View File

@@ -0,0 +1,25 @@
import { forwardRef, type ButtonHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
type CheckedState = boolean | "indeterminate";
export interface CheckboxProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onChange" | "checked"> {
checked?: CheckedState;
onCheckedChange?: (checked: CheckedState) => void;
}
export const Checkbox = forwardRef<HTMLButtonElement, CheckboxProps>(
({ className, checked, onCheckedChange, ...props }, ref) => (
<button
ref={ref}
type="button"
role="checkbox"
aria-checked={checked === "indeterminate" ? "mixed" : checked}
data-state={checked === "indeterminate" ? "indeterminate" : checked ? "checked" : "unchecked"}
onClick={() => onCheckedChange?.(checked !== true)}
className={cn(className)}
{...props}
/>
)
);
Checkbox.displayName = "Checkbox";

View File

@@ -0,0 +1,66 @@
import type { HTMLAttributes, InputHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export interface CommandProps extends HTMLAttributes<HTMLDivElement> {
shouldFilter?: boolean;
}
export function Command({ className, shouldFilter, ...props }: CommandProps) {
return <div data-should-filter={shouldFilter} className={cn(className)} {...props} />;
}
export interface CommandInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "onValueChange"> {
onValueChange?: (value: string) => void;
}
export function CommandInput({ className, onValueChange, onChange, ...props }: CommandInputProps) {
return (
<input
className={cn(className)}
onChange={(e) => {
onValueChange?.(e.target.value);
onChange?.(e);
}}
{...props}
/>
);
}
export function CommandList({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn(className)} {...props} />;
}
export function CommandEmpty({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn(className)} {...props} />;
}
export interface CommandGroupProps extends HTMLAttributes<HTMLDivElement> {
heading?: string;
}
export function CommandGroup({ className, heading, ...props }: CommandGroupProps) {
return <div data-heading={heading} className={cn(className)} {...props} />;
}
export interface CommandItemProps extends Omit<HTMLAttributes<HTMLDivElement>, "onSelect"> {
value?: string;
disabled?: boolean;
onSelect?: (value: string) => void;
}
export function CommandItem({ className, value, disabled, onSelect, ...props }: CommandItemProps) {
return (
<div
role="option"
data-value={value}
aria-disabled={disabled}
onClick={() => !disabled && onSelect?.(value ?? "")}
className={cn(className)}
{...props}
/>
);
}
export function CommandSeparator({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div role="separator" className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,45 @@
import type { HTMLAttributes, ReactNode } from "react";
import { renderAsChild } from "@/lib/as-child";
import { cn } from "@/lib/utils";
export interface DialogProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
children?: ReactNode;
}
export function Dialog({ open, children }: DialogProps) {
return open ? <>{children}</> : null;
}
export function DialogClose({
asChild,
children,
...props
}: HTMLAttributes<HTMLElement> & { asChild?: boolean }) {
return renderAsChild(asChild, children, props);
}
export interface DialogContentProps extends HTMLAttributes<HTMLDivElement> {
showCloseButton?: boolean;
}
export function DialogContent({ className, showCloseButton, ...props }: DialogContentProps) {
return <div role="dialog" data-show-close-button={showCloseButton} className={cn(className)} {...props} />;
}
export function DialogHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn(className)} {...props} />;
}
export function DialogFooter({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn(className)} {...props} />;
}
export function DialogTitle({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) {
return <h2 className={cn(className)} {...props} />;
}
export function DialogDescription({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
return <p className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,42 @@
import type { HTMLAttributes, ReactNode } from "react";
import { renderAsChild } from "@/lib/as-child";
import { cn } from "@/lib/utils";
export interface DropdownMenuProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
children?: ReactNode;
}
export function DropdownMenu({ children }: DropdownMenuProps) {
return <>{children}</>;
}
export function DropdownMenuTrigger({
asChild,
children,
...props
}: HTMLAttributes<HTMLElement> & { asChild?: boolean }) {
return renderAsChild(asChild, children, props);
}
export interface DropdownMenuContentProps extends HTMLAttributes<HTMLDivElement> {
align?: "start" | "center" | "end";
side?: "top" | "right" | "bottom" | "left";
sideOffset?: number;
}
export function DropdownMenuContent({ className, align, side, sideOffset, ...props }: DropdownMenuContentProps) {
return <div data-align={align} data-side={side} className={cn(className)} {...props} />;
}
export function DropdownMenuItem({
className,
...props
}: HTMLAttributes<HTMLDivElement> & { disabled?: boolean }) {
return <div role="menuitem" className={cn(className)} {...props} />;
}
export function DropdownMenuSeparator({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div role="separator" className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,9 @@
import { forwardRef, type InputHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
({ className, type, ...props }, ref) => (
<input ref={ref} type={type} className={cn(className)} {...props} />
)
);
Input.displayName = "Input";

View File

@@ -0,0 +1,7 @@
import { forwardRef, type LabelHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export const Label = forwardRef<HTMLLabelElement, LabelHTMLAttributes<HTMLLabelElement>>(
({ className, ...props }, ref) => <label ref={ref} className={cn(className)} {...props} />
);
Label.displayName = "Label";

View File

@@ -0,0 +1,23 @@
import type { HTMLAttributes, LiHTMLAttributes } from "react";
import { Button, type ButtonProps } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export function Pagination({ className, ...props }: HTMLAttributes<HTMLElement>) {
return <nav role="navigation" aria-label="pagination" className={cn(className)} {...props} />;
}
export function PaginationContent({ className, ...props }: HTMLAttributes<HTMLUListElement>) {
return <ul className={cn(className)} {...props} />;
}
export function PaginationItem({ className, ...props }: LiHTMLAttributes<HTMLLIElement>) {
return <li className={cn(className)} {...props} />;
}
export function PaginationLink({ className, isActive, ...props }: ButtonProps & { isActive?: boolean }) {
return <Button data-active={isActive} className={cn(className)} {...props} />;
}
export function PaginationEllipsis({ className, ...props }: HTMLAttributes<HTMLSpanElement>) {
return <span aria-hidden className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,32 @@
import type { HTMLAttributes, ReactNode } from "react";
import { renderAsChild } from "@/lib/as-child";
import { cn } from "@/lib/utils";
export interface PopoverProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
modal?: boolean;
children?: ReactNode;
}
export function Popover({ children }: PopoverProps) {
return <>{children}</>;
}
export function PopoverTrigger({
asChild,
children,
...props
}: HTMLAttributes<HTMLElement> & { asChild?: boolean }) {
return renderAsChild(asChild, children, props);
}
export interface PopoverContentProps extends HTMLAttributes<HTMLDivElement> {
align?: "start" | "center" | "end";
side?: "top" | "right" | "bottom" | "left";
sideOffset?: number;
}
export function PopoverContent({ className, align, side, sideOffset, ...props }: PopoverContentProps) {
return <div data-align={align} data-side={side} className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,34 @@
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "@/lib/utils";
export interface SelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
disabled?: boolean;
children?: ReactNode;
}
export function Select({ children }: SelectProps) {
return <>{children}</>;
}
export function SelectTrigger({ className, ...props }: HTMLAttributes<HTMLButtonElement>) {
return <button type="button" className={cn(className)} {...props} />;
}
export function SelectValue({ placeholder, ...props }: HTMLAttributes<HTMLSpanElement> & { placeholder?: string }) {
return <span {...props}>{placeholder}</span>;
}
export function SelectContent({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn(className)} {...props} />;
}
export function SelectItem({
className,
value,
...props
}: HTMLAttributes<HTMLDivElement> & { value: string }) {
return <div data-value={value} role="option" className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,10 @@
import type { HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export interface SeparatorProps extends HTMLAttributes<HTMLDivElement> {
orientation?: "horizontal" | "vertical";
}
export function Separator({ className, orientation = "horizontal", ...props }: SeparatorProps) {
return <div role="separator" data-orientation={orientation} className={cn(className)} {...props} />;
}

View File

@@ -0,0 +1,26 @@
import type { HTMLAttributes, TdHTMLAttributes, ThHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export function Table({ className, ...props }: HTMLAttributes<HTMLTableElement>) {
return <table className={cn(className)} {...props} />;
}
export function TableHeader({ className, ...props }: HTMLAttributes<HTMLTableSectionElement>) {
return <thead className={cn(className)} {...props} />;
}
export function TableBody({ className, ...props }: HTMLAttributes<HTMLTableSectionElement>) {
return <tbody className={cn(className)} {...props} />;
}
export function TableRow({ className, ...props }: HTMLAttributes<HTMLTableRowElement>) {
return <tr className={cn(className)} {...props} />;
}
export function TableHead({ className, ...props }: ThHTMLAttributes<HTMLTableCellElement>) {
return <th className={cn(className)} {...props} />;
}
export function TableCell({ className, ...props }: TdHTMLAttributes<HTMLTableCellElement>) {
return <td className={cn(className)} {...props} />;
}

12
.tooling/lib/as-child.tsx Normal file
View File

@@ -0,0 +1,12 @@
import { cloneElement, isValidElement, type HTMLAttributes, type ReactNode } from "react";
export function renderAsChild(
asChild: boolean | undefined,
children: ReactNode,
props: HTMLAttributes<HTMLElement>
) {
if (asChild && isValidElement<HTMLAttributes<HTMLElement>>(children)) {
return cloneElement(children, { ...props, ...children.props });
}
return <span {...props}>{children}</span>;
}

6
.tooling/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

106
README.md Normal file
View File

@@ -0,0 +1,106 @@
# KRI UI Registry
사내 shadcn UI Registry 소스 프로젝트입니다. `dist/r`의 정적 JSON을 IIS 또는 Nginx에 배포합니다.
## 빌드 및 검증
```powershell
npm ci
npm run build
npm run verify
npm run preview
```
로컬 Registry 주소:
```text
http://localhost:4100/r/registry.json
```
## Registry 항목
```text
kri-select
kri-date-range-picker
kri-password
kri-auto-complete
kri-data-table
kri-loading-overlay
kri-editor
kri-layout
kri-dialog
```
전체 설치 예시:
```powershell
npx shadcn@latest add http://localhost:4100/r/kri-password.json
npx shadcn@latest add http://localhost:4100/r/kri-auto-complete.json
npx shadcn@latest add http://localhost:4100/r/kri-data-table.json
npx shadcn@latest add http://localhost:4100/r/kri-loading-overlay.json
npx shadcn@latest add http://localhost:4100/r/kri-editor.json
npx shadcn@latest add http://localhost:4100/r/kri-layout.json
npx shadcn@latest add http://localhost:4100/r/kri-dialog.json
```
## KriDialog Footer 규칙
기본값은 `닫기` 버튼이 있는 Footer입니다.
```tsx
<KriDialog open={open} onOpenChange={setOpen} title="사용자 등록">
{/* Body */}
</KriDialog>
```
기본 Footer를 제거합니다.
```tsx
<KriDialog
open={open}
onOpenChange={setOpen}
title="사용자 등록"
showDefaultFooter={false}
>
{/* Body */}
</KriDialog>
```
사용자 정의 Footer를 전달합니다. `footer`가 지정되면 기본 Footer보다 우선합니다.
```tsx
<KriDialog
open={open}
onOpenChange={setOpen}
title="사용자 등록"
footer={
<>
<Button variant="outline" onClick={() => setOpen(false)}>취소</Button>
<Button onClick={handleSave}>저장</Button>
</>
}
>
{/* Body */}
</KriDialog>
```
`footer={null}`을 전달해도 Footer가 표시되지 않습니다.
## Editor 주요 옵션
```tsx
<KriEditor
mode="both"
value={html}
onChange={setHtml}
onImageUpload={async (file) => upload(file)}
smsMaxBytes={90}
lmsMaxBytes={2000}
toolbar={{ image: true, table: false, html: true }}
/>
```
- 편집 값은 HTML 문자열입니다.
- 이미지 업로드 함수는 URL 문자열 또는 `{ url }`을 반환할 수 있습니다.
- `toolbar={false}`로 툴바 전체를 감출 수 있습니다.
- SMS/LMS 기본 제한은 각각 90/2,000바이트입니다.

6273
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "kri-ui-registry",
"version": "0.2.0",
"private": true,
"description": "KRI internal shadcn UI registry",
"scripts": {
"clean": "rimraf dist",
"build": "npm run clean && shadcn build --output ./dist/r",
"verify": "node ./scripts/verify-registry.mjs",
"preview": "serve ./dist -l 4100"
},
"devDependencies": {
"@tanstack/react-table": "^8.21.3",
"@tiptap/extension-color": "^3.27.1",
"@tiptap/extension-highlight": "^3.27.1",
"@tiptap/extension-image": "^3.27.1",
"@tiptap/extension-link": "^3.27.1",
"@tiptap/extension-placeholder": "^3.27.1",
"@tiptap/extension-table": "^3.27.1",
"@tiptap/extension-table-cell": "^3.27.1",
"@tiptap/extension-table-header": "^3.27.1",
"@tiptap/extension-table-row": "^3.27.1",
"@tiptap/extension-text-align": "^3.27.1",
"@tiptap/extension-text-style": "^3.27.1",
"@tiptap/extension-underline": "^3.27.1",
"@tiptap/react": "^3.27.1",
"@tiptap/starter-kit": "^3.27.1",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"clsx": "^2.1.1",
"dompurify": "^3.4.11",
"lucide-react": "^1.23.0",
"rimraf": "^6.0.0",
"serve": "^14.2.4",
"shadcn": "^4.8.3",
"sonner": "^2.0.7",
"tailwind-merge": "^3.6.0",
"typescript": "^6.0.3"
}
}

8
registry.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "kri",
"homepage": "https://ui-registry.kric.com",
"include": [
"registry/components/registry.json"
]
}

View File

@@ -0,0 +1,207 @@
'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
}
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,
}: KriMultiSelectProps<T>) {
const options = React.useMemo(
() => toOptions(items, getValue, getLabel, withInfo),
[getLabel, getValue, items, withInfo],
)
return (
<div className={cn('flex-none overflow-hidden', 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
singleLine
resetOnDefaultValueChange
deduplicateOptions
disabled={disabled}
/>
</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
}
export function KriSingleSelect<T = unknown>({
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,
}: KriSingleSelectProps<T>) {
const ref = React.useRef<MultiSelectRef>(null)
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 overflow-hidden', 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
singleLine
closeOnSelect
resetOnDefaultValueChange
deduplicateOptions
disabled={disabled}
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
/>
</div>
)
}

View File

@@ -0,0 +1,120 @@
'use client'
import { useRef } from 'react'
import { CalendarDays, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
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
}
export function KriDateRangePicker({
value,
onChange,
placeholder = '조회 기간 선택',
className,
triggerClassName,
contentClassName,
disabled = false,
}: KriDateRangePickerProps) {
const toInputRef = useRef<HTMLInputElement | null>(null)
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
const invalidRange = value.from.length > 0 && value.to.length > 0 && value.from > value.to
const focusAndOpenToDate = () => {
const input = toInputRef.current
if (!input) return
input.focus()
const inputWithPicker = input as HTMLInputElement & { showPicker?: () => void }
inputWithPicker.showPicker?.()
if (!inputWithPicker.showPicker) {
input.click()
}
}
return (
<div className={cn('flex items-center gap-2', className)}>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className={cn('justify-start min-w-[260px] font-normal', triggerClassName)}
>
<CalendarDays className="w-4 h-4" />
<span className="truncate">{displayText}</span>
</Button>
</PopoverTrigger>
<PopoverContent align="start" className={cn('w-[360px] space-y-3', contentClassName)}>
<Label className="font-semibold">조회 기간</Label>
<div className="flex items-center gap-2">
<Input
type="date"
value={value.from}
onChange={(e) => {
const nextFrom = e.target.value
onChange({ ...value, from: nextFrom })
if (nextFrom) {
requestAnimationFrame(() => {
focusAndOpenToDate()
})
}
}}
/>
<span className="text-sm text-muted-foreground">~</span>
<Input
ref={toInputRef}
type="date"
value={value.to}
onChange={(e) => onChange({ ...value, to: e.target.value })}
/>
</div>
{invalidRange && (
<p className="text-xs text-red-600">조회 시작일은 종료일보다 이후일 수 없습니다.</p>
)}
</PopoverContent>
</Popover>
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => onChange({ from: '', to: '' })}
disabled={disabled || !hasValue}
aria-label="조회 기간 초기화"
>
<X className="w-4 h-4" />
</Button>
</div>
)
}
export default KriDateRangePicker

View File

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

View File

@@ -0,0 +1,26 @@
'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)}
>
<div className={cn('size-12 animate-spin rounded-full border-4 border-gray-400 border-t-white', spinnerClassName)} />
<span className="sr-only">{label}</span>
</div>
)
}

View File

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

View File

@@ -0,0 +1,95 @@
'use client'
import type { CSSProperties } from 'react'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { cn } from '@/lib/utils'
export type KriSelectItem = {
value: string
label: string
}
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
}
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,
}: KriSelectProps<T>) {
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
const triggerStyle: CSSProperties | undefined = heightClassName
? { height: HEIGHT_CLASS_VALUE[heightClassName] ?? undefined }
: undefined
return (
<Select
value={value}
onValueChange={(selectedValue) => {
onChange?.(selectedValue)
const selected = items.find((item) => extractValue(item) === selectedValue)
if (selected) {
onChangeOption?.(selected)
}
}}
>
<SelectTrigger
className={cn('w-fit whitespace-nowrap bg-white', triggerTextClassName, heightClassName, className)}
style={triggerStyle}
aria-label={placeholder ?? 'select'}
>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent className={contentClassName}>
{useAll ? (
<SelectItem value="ALL" className={itemClassName}>
전체
</SelectItem>
) : null}
{items.map((item, index) => {
const itemValue = extractValue(item)
const label = extractLabel(item)
return (
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
{label}
</SelectItem>
)
})}
</SelectContent>
</Select>
)
}

View File

@@ -0,0 +1,182 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import type { PaginationState, Row, 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 { Table, 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'
export function DataTable<TData, TValue = unknown>({
columns,
data,
getRowId,
highlightRowIds,
isClient = true,
pageCount: serverPageCount,
totalCount: serverTotalCount,
onPaginationChange: onServerPaginationChange,
onSortingChange: onServerSortingChange,
selectMode = 'none',
onRowClick,
onRowSelectionChange,
defaultPageSize = 10,
pageSizeOptions = [5, 10, 25, 50],
paginationItemsToDisplay = 5,
emptyText = '데이터가 없습니다.',
className,
}: Readonly<DataTableProps<TData, TValue>>) {
const [pagination, setPagination] = 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 }) => (
<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 table = useReactTable({
data,
columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount,
state: { sorting, pagination, rowSelection },
enableRowSelection: selectionEnabled,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
manualPagination: !isClient,
manualSorting: !isClient,
enableSortingRemoval: false,
...(getRowId ? { getRowId } : {}),
})
useEffect(() => {
if (!isClient) onServerPaginationChange?.(pagination)
}, [isClient, onServerPaginationChange, pagination])
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)
return (
<div className={cn('w-full space-y-4', className)}>
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => {
const column = header.column
const 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>
{table.getRowModel().rows.length ? table.getRowModel().rows.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>
)}
</TableBody>
</Table>
</div>
<DataTablePagination
table={table}
isClient={isClient}
totalCount={totalCount}
pageSizeOptions={pageSizeOptions}
paginationItemsToDisplay={paginationItemsToDisplay}
/>
</div>
)
}

View File

@@ -0,0 +1,36 @@
import type { ColumnDef, PaginationState, SortingState } 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
onPaginationChange?: (pagination: 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
}

View File

@@ -0,0 +1,96 @@
'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>) {
const currentPage = table.getState().pagination.pageIndex + 1
const pageCount = table.getPageCount()
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
currentPage,
totalPages: pageCount,
paginationItemsToDisplay,
})
return (
<div className="flex items-center justify-between gap-3 p-2 pt-0 max-sm:flex-col">
<p className="text-muted-foreground flex-1 whitespace-nowrap text-sm" aria-live="polite">
Page <span className="text-foreground">{currentPage}</span> of{' '}
<span className="text-foreground">{pageCount}</span>
{!isClient && totalCount > 0 ? (
<span className="ml-2">(총 <span className="text-foreground">{totalCount}</span>건)</span>
) : null}
</p>
<div className="grow">
<Pagination>
<PaginationContent>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.firstPage()} disabled={!table.getCanPreviousPage()} aria-label="첫 페이지">
<ChevronsLeftIcon aria-hidden="true" />
</Button>
</PaginationItem>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} aria-label="이전 페이지">
<ChevronLeftIcon aria-hidden="true" />
</Button>
</PaginationItem>
{showLeftEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
{pages.map((page) => (
<PaginationItem key={page}>
<Button
size="icon"
variant={page === currentPage ? 'default' : 'ghost'}
onClick={() => table.setPageIndex(page - 1)}
aria-current={page === currentPage ? 'page' : undefined}
>
{page}
</Button>
</PaginationItem>
))}
{showRightEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} aria-label="다음 페이지">
<ChevronRightIcon aria-hidden="true" />
</Button>
</PaginationItem>
<PaginationItem>
<Button size="icon" variant="outline" onClick={() => table.lastPage()} disabled={!table.getCanNextPage()} aria-label="마지막 페이지">
<ChevronsRightIcon aria-hidden="true" />
</Button>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
<div className="flex flex-1 justify-end">
<Select value={String(table.getState().pagination.pageSize)} onValueChange={(value) => table.setPageSize(Number(value))}>
<SelectTrigger className="w-fit whitespace-nowrap" aria-label="페이지당 개수">
<SelectValue placeholder="페이지당 개수" />
</SelectTrigger>
<SelectContent>
{pageSizeOptions.map((size) => <SelectItem key={size} value={String(size)}>{size} / page</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
)
}

View File

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

View File

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

View File

@@ -0,0 +1,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)
let endPage = Math.min(totalPages, startPage + visibleCount - 1)
if (endPage - startPage + 1 < visibleCount) {
startPage = Math.max(1, endPage - visibleCount + 1)
}
return {
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
showLeftEllipsis: startPage > 1,
showRightEllipsis: endPage < totalPages,
}
}, [currentPage, paginationItemsToDisplay, totalPages])
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,158 @@
'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 { 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])
React.useEffect(() => {
if ((value || '') !== latestHtmlRef.current) {
setHtml(value || '')
latestHtmlRef.current = value || ''
}
}, [value])
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 previewHtml = React.useMemo(() => sanitizeHtmlForPreview(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>
{onImageUpload ? (
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
이미지 업로드
</button>
) : null}
</div>
<textarea
ref={textareaRef}
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
value={html}
onChange={(event) => commitHtml(event.target.value)}
onBlur={() => flushChange(latestHtmlRef.current)}
placeholder={placeholder}
rows={rows}
{...textareaInsert.bindSelectionHandlers}
/>
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
</div>
{showPreview ? (
<div className={cn('border-t p-3', previewClassName)}>
<div className="mb-2 text-sm font-semibold">미리보기</div>
<div className="rounded-md border bg-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
) : null}
</div>
)
}

View File

@@ -0,0 +1,117 @@
'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,
smsMaxBytes = 90,
lmsMaxBytes = 2000,
}: SmsEditorProps) {
const [text, setText] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
const latestTextRef = React.useRef(text)
const lastTypeRef = React.useRef<'SMS' | 'LMS' | null>(null)
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
const textareaInsert = useTextareaInsert(textareaRef)
const byteSize = React.useMemo(() => calculateBytes(text), [text])
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
const commitText = React.useCallback((next: string, immediate = false) => {
setText(next)
latestTextRef.current = next
if (immediate) flushChange(next)
else scheduleChange(next)
}, [flushChange, scheduleChange])
React.useEffect(() => {
if ((value || '') !== latestTextRef.current) {
setText(value || '')
latestTextRef.current = value || ''
}
}, [value])
React.useEffect(() => {
if (lastTypeRef.current === messageType) return
lastTypeRef.current = messageType
changeSmsType?.(messageType)
}, [changeSmsType, messageType])
React.useEffect(() => {
onEditorReady?.(textareaRef.current)
}, [onEditorReady])
React.useEffect(() => {
if (!onCommandReady) return
onCommandReady({
focus: () => textareaRef.current?.focus(),
insertText: (insertedText) => {
textareaInsert.insertText(
insertedText,
latestTextRef.current,
(next) => commitText(next),
(next) => commitText(next, true),
)
},
})
return () => onCommandReady(null)
}, [commitText, onCommandReady, textareaInsert])
return (
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
<div className="mb-3 flex items-center justify-between px-2">
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}>
{messageType}
</span>
</div>
<div className="flex flex-1 flex-col overflow-hidden rounded-2xl bg-white shadow-sm">
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
<textarea
ref={textareaRef}
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
value={text}
onChange={(event) => {
const next = event.target.value
if (calculateBytes(next) <= lmsMaxBytes) commitText(next)
}}
onBlur={() => flushChange(latestTextRef.current)}
placeholder={placeholder}
style={{ minHeight: smsTitle ? '320px' : '360px' }}
{...textareaInsert.bindSelectionHandlers}
/>
</div>
{byteSize > maxBytes ? (
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
최대 용량을 {byteSize - maxBytes}byte 초과했습니다.
</p>
) : null}
</div>
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
</div>
</div>
)
}

View File

@@ -0,0 +1,642 @@
"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 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 { KriEditorProps, KriEditorMode, ToolbarState } from "./types";
import { resolveUploadUrl } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { useTextareaInsert } from "./hooks/useTextareaInsert";
type ViewMode = "wysiwyg" | "html";
function resolveMode(mode?: KriEditorMode): KriEditorMode {
return mode ?? "wysiwyg";
}
function getToolbarState(editor: Editor): ToolbarState {
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; color?: string | null };
const hl = editor.getAttributes("highlight") as { color?: 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 {
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: modeProp,
debounceMs = 350,
onImageUpload,
onImageUploadError,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = "image/webp",
allowBase64 = false,
sanitizeHtml: sanitizeHtmlOpt = true,
toolbar = {},
} = props;
const mode = resolveMode(modeProp);
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 [view, setView] = useState<ViewMode>("wysiwyg");
const [wysiwygKey, setWysiwygKey] = useState<number>(0);
const [previewSource, setPreviewSource] = useState(value ?? "");
const viewRef = useRef<ViewMode>("wysiwyg");
useEffect(() => {
viewRef.current = view;
}, [view]);
const htmlDraftRef = useRef<string>(value ?? "");
const canImageUpload = Boolean(onImageUpload);
const selectionRef = useRef<{ from: number; to: number } | null>(null);
const [tb, setTb] = useState<ToolbarState>({
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,
Color,
Highlight.configure({ multicolor: true }),
Div,
Link.configure({
autolink: true,
openOnClick: false,
linkOnPaste: true,
HTMLAttributes: {
class: "cursor-pointer text-blue-600 underline underline-offset-2",
...LINK_HTML_ATTRS,
},
}),
TextAlign.configure({ types: ["paragraph", "divBlock"] }),
Table.configure({ resizable: true }),
TableRow,
TableHeader,
TableCell,
TiptapImage.configure({
inline: true,
allowBase64,
HTMLAttributes: {
class: "max-w-full h-auto",
"data-kri-image": "true",
},
resize: {
enabled: true,
alwaysPreserveAspectRatio: true,
},
}),
Placeholder.configure({ placeholder }),
],
content: value || "<p></p>",
onUpdate: ({ editor }) => {
if (viewRef.current === "html") return;
const nextHtml = editor.getHTML();
setPreviewSource(nextHtml);
scheduleChange(nextHtml);
},
editorProps: {
attributes: {
class: cn(
"min-h-[180px] 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;
},
},
},
},[wysiwygKey]);
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 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") {
htmlDraftRef.current = editor.getHTML();
setView("html");
return;
}
const raw = htmlDraftRef.current;
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(editor.getHTML());
setView("wysiwyg");
}, [editor, flushChange, sanitizeHtmlOpt]);
useEffect(() => {
if (!editor) return;
const sync = () => {
selectionRef.current = { from: editor.state.selection.from, to: editor.state.selection.to };
setTb(getToolbarState(editor));
};
sync();
editor.on("selectionUpdate", sync);
editor.on("transaction", sync);
return () => {
editor.off("selectionUpdate", sync);
editor.off("transaction", sync);
};
}, [editor]);
useEffect(() => {
if (!props.onEditorReady || !editor) return;
if (viewRef.current === "html") {
props.onEditorReady(htmlTextareaRef.current);
} else {
props.onEditorReady(editor);
}
}, [editor, view, props.onEditorReady]);
useEffect(() => {
setPreviewSource(value ?? "");
if (!editor) return;
if (viewRef.current === "html") return;
if (value == null) return;
const current = editor.getHTML();
if (value !== current && value !== optimisticHtmlRef.current) {
// 이미지가 포함된 HTML 업데이트면, 아예 editor를 새로 생성
editor.commands.setContent(value, {
emitUpdate: false,
parseOptions: {preserveWhitespace: "full"},
});
}
}, [value, editor, view]);
useEffect(() => {
if (value.includes("<img")) {
setWysiwygKey((k) => k + 1);
return;
}
}, [value]);
useEffect(() => {
if (!editor) return;
const onBlur = () => {
if (viewRef.current === "html") flushChange(htmlDraftRef.current);
else flushChange(editor.getHTML());
};
editor.on("blur", onBlur);
return () => {
editor.off("blur", onBlur);
};
}, [editor, flushChange]);
useEffect(() => {
if (!props.onCommandReady) return;
// editor가 아직 없으면 null 전달
if (!editor) {
props.onCommandReady(null);
return;
}
props.onCommandReady({
focus: () => {
if (viewRef.current === "html") htmlTextareaRef.current?.focus();
else editor.chain().focus().run();
},
insertText: (placeholder: string) => {
// 1) HTML textarea 모드
if (viewRef.current === "html") {
const current = htmlDraftRef.current ?? "";
htmlTi.insertText(
placeholder,
current,
(next) => {
htmlDraftRef.current = next;
// uncontrolled textarea이므로 DOM value를 직접 갱신
if (htmlTextareaRef.current) htmlTextareaRef.current.value = next;
},
(next) => {
// 삽입은 즉시 커밋(저장 버튼 클릭 직후 반영 누락 방지)
flushChange(next);
}
);
return;
}
// 2) WYSIWYG(tiptap) 모드
restoreSelection();
editor.chain().focus().insertContent(placeholder).run();
flushChange(editor.getHTML());
},
});
return () => props.onCommandReady?.(null);
}, [editor, props.onCommandReady, restoreSelection, flushChange, htmlTi]);
const previewHtml = useMemo(() => {
return sanitizeHtmlOpt ? sanitizeHtml(previewSource) : previewSource;
}, [previewSource, sanitizeHtmlOpt]);
if (!editor) {
return (
<div className={cn("rounded-lg border bg-background", className)}>
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
<div className="p-3 text-sm text-muted-foreground">에디터 로딩 중…</div>
</div>
);
}
return (
<div className={cn("rounded-lg border bg-background", className)}>
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
{toolbar !== false ? (
<div className="border-b">
<Toolbar
editor={editor}
state={tb}
config={toolbar}
className="flex-nowrap"
canImageUpload={canImageUpload}
onPickImage={handlePickImage}
showHtmlToggle={showHtmlToggle}
isHtmlView={view === "html"}
onToggleHtmlView={onToggleHtmlView}
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}
/>
</div>
) : null}
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} disabled={!canImageUpload} />
{view === "wysiwyg" ? (
<EditorContent editor={editor} />
) : (
<div className="p-2">
<textarea
ref={htmlTextareaRef}
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
defaultValue={htmlDraftRef.current}
onMouseDown={(e) => e.stopPropagation()}
onChange={(e) => {
htmlDraftRef.current = e.target.value;
setPreviewSource(htmlDraftRef.current);
scheduleChange(htmlDraftRef.current);
}}
onBlur={() => flushChange(htmlDraftRef.current)}
placeholder={placeholder}
{...htmlTi.bindSelectionHandlers}
/>
</div>
)}
{showPreview && (
<div className={cn("border-t p-3", previewClassName)}>
<div className="mb-2 text-sm font-semibold">미리보기</div>
<div className="rounded-md border bg-muted/30 p-3">
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
</div>
)}
</div>
);
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,13 @@
export { KriEditor } from './KriEditor'
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export type {
KriEditorCommand,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,
KriEditorToolbarFeature,
KriEditorUploadResult,
ToolbarState,
} from './types'

View File

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

View File

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

View File

@@ -0,0 +1,77 @@
import type { Editor } from '@tiptap/react'
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
export type KriEditorUploadResult = string | { url: string }
export type KriEditorToolbarFeature =
| '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 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
smsMaxBytes?: number
lmsMaxBytes?: number
toolbar?: KriEditorToolbarConfig | false
}
export type ToolbarState = {
fontSize: string
textColor: string | null
highlightColor: string | null
isBold: boolean
isItalic: boolean
isUnderline: boolean
isStrike: boolean
align: 'left' | 'center' | 'right'
isBulletList: boolean
isOrderedList: boolean
isLink: boolean
inTable: boolean
}
export function resolveUploadUrl(result: KriEditorUploadResult): string {
return typeof result === 'string' ? result : result.url
}

View File

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

View File

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

View File

@@ -0,0 +1,28 @@
"use client";
import DOMPurify from "dompurify";
const HTML_PROFILE = {
USE_PROFILES: {
html: true,
},
} as const;
export function sanitizeHtml(
input: string,
): string {
if (!input) {
return "";
}
return DOMPurify.sanitize(
input,
HTML_PROFILE,
);
}
export function sanitizeHtmlForPreview(
input: string,
): string {
return sanitizeHtml(input);
}

View 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" 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>
)
}

View File

@@ -0,0 +1,50 @@
'use client'
import type { CSSProperties, ReactNode } from 'react'
import { cn } from '@/lib/utils'
export interface KriMainLayoutProps {
children: ReactNode
header?: ReactNode
sidebar?: ReactNode
sidebarOpen?: boolean
onSidebarOpenChange?: (open: boolean) => void
fullHeight?: boolean
className?: string
bodyClassName?: string
mainClassName?: string
mainStyle?: CSSProperties
}
export function KriMainLayout({
children,
header,
sidebar,
sidebarOpen = false,
onSidebarOpenChange,
fullHeight = true,
className,
bodyClassName,
mainClassName,
mainStyle,
}: KriMainLayoutProps) {
return (
<div className={cn('flex flex-col bg-muted/30', fullHeight && '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>
)
}

View File

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

View File

@@ -0,0 +1,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>
)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,353 @@
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"items": [
{
"name": "kri-select",
"type": "registry:component",
"title": "KRI Select",
"description": "KRI 공통 단일 선택 컴포넌트입니다.",
"registryDependencies": [
"select"
],
"files": [
{
"path": "KriSelect.tsx",
"type": "registry:component",
"target": "@components/common/KriSelect.tsx"
}
]
},
{
"name": "kri-date-range-picker",
"type": "registry:component",
"title": "KRI Date Range Picker",
"description": "시작일과 종료일을 선택하고 초기화할 수 있는 KRI 공통 날짜 범위 컴포넌트입니다.",
"registryDependencies": [
"button",
"input",
"label",
"popover"
],
"dependencies": [
"lucide-react"
],
"files": [
{
"path": "KriDateRangePicker.tsx",
"type": "registry:component",
"target": "@components/common/KriDateRangePicker.tsx"
}
]
},
{
"name": "kri-password",
"type": "registry:component",
"title": "KRI Password",
"description": "8~20자 비밀번호 규칙과 표시 전환 및 강도 안내를 제공하는 컴포넌트입니다.",
"registryDependencies": [
"button",
"input",
"label"
],
"dependencies": [
"lucide-react"
],
"files": [
{
"path": "KriPassword.tsx",
"type": "registry:component",
"target": "@components/common/KriPassword.tsx"
}
]
},
{
"name": "kri-auto-complete",
"type": "registry:component",
"title": "KRI Auto Complete",
"description": "단일·다중 선택, 로컬 필터 및 서버 검색을 지원하는 KRI 공통 자동완성 컴포넌트입니다.",
"registryDependencies": [
"badge",
"button",
"command",
"popover"
],
"dependencies": [
"lucide-react"
],
"files": [
{
"path": "KriAutoComplete.tsx",
"type": "registry:component",
"target": "@components/common/KriAutoComplete.tsx"
},
{
"path": "multi-select/MultiSelect.tsx",
"type": "registry:component",
"target": "@components/common/multi-select/MultiSelect.tsx"
},
{
"path": "multi-select/MultiSelectContent.tsx",
"type": "registry:component",
"target": "@components/common/multi-select/MultiSelectContent.tsx"
},
{
"path": "multi-select/MultiSelectTrigger.tsx",
"type": "registry:component",
"target": "@components/common/multi-select/MultiSelectTrigger.tsx"
},
{
"path": "multi-select/index.ts",
"type": "registry:component",
"target": "@components/common/multi-select/index.ts"
},
{
"path": "multi-select/types.ts",
"type": "registry:component",
"target": "@components/common/multi-select/types.ts"
},
{
"path": "multi-select/use-responsive-settings.ts",
"type": "registry:component",
"target": "@components/common/multi-select/use-responsive-settings.ts"
},
{
"path": "multi-select/utils.ts",
"type": "registry:component",
"target": "@components/common/multi-select/utils.ts"
}
]
},
{
"name": "kri-data-table",
"type": "registry:component",
"title": "KRI Data Table",
"description": "클라이언트·서버 페이지네이션, 정렬, 행 선택을 지원하는 공통 데이터 테이블입니다.",
"registryDependencies": [
"button",
"checkbox",
"pagination",
"select",
"table"
],
"dependencies": [
"@tanstack/react-table",
"lucide-react"
],
"files": [
{
"path": "data-table/DataTable.tsx",
"type": "registry:component",
"target": "@components/data-table/DataTable.tsx"
},
{
"path": "data-table/DataTable.type.ts",
"type": "registry:component",
"target": "@components/data-table/DataTable.type.ts"
},
{
"path": "data-table/DataTablePagination.tsx",
"type": "registry:component",
"target": "@components/data-table/DataTablePagination.tsx"
},
{
"path": "data-table/hooks/usePagination.ts",
"type": "registry:component",
"target": "@components/data-table/hooks/usePagination.ts"
},
{
"path": "data-table/hooks/usePreventClickOnDrag.ts",
"type": "registry:component",
"target": "@components/data-table/hooks/usePreventClickOnDrag.ts"
},
{
"path": "data-table/index.ts",
"type": "registry:component",
"target": "@components/data-table/index.ts"
}
]
},
{
"name": "kri-loading-overlay",
"type": "registry:component",
"title": "KRI Loading Overlay",
"description": "상태 관리 라이브러리에 의존하지 않고 open prop으로 제어하는 로딩 오버레이입니다.",
"files": [
{
"path": "LoadingOverlay.tsx",
"type": "registry:component",
"target": "@components/common/LoadingOverlay.tsx"
}
]
},
{
"name": "kri-editor",
"type": "registry:component",
"title": "KRI Editor",
"description": "WYSIWYG, HTML, SMS 모드와 주입형 이미지 업로드 및 선택형 툴바를 제공하는 편집기입니다.",
"registryDependencies": [
"button",
"dropdown-menu",
"input",
"popover",
"separator"
],
"dependencies": [
"@tiptap/extension-color",
"@tiptap/extension-highlight",
"@tiptap/extension-image",
"@tiptap/extension-link",
"@tiptap/extension-placeholder",
"@tiptap/extension-table",
"@tiptap/extension-table-cell",
"@tiptap/extension-table-header",
"@tiptap/extension-table-row",
"@tiptap/extension-text-align",
"@tiptap/extension-text-style",
"@tiptap/extension-underline",
"@tiptap/react",
"@tiptap/starter-kit",
"dompurify",
"lucide-react",
"sonner"
],
"files": [
{
"path": "kri-editor/KriEditor.tsx",
"type": "registry:component",
"target": "@components/kri-editor/KriEditor.tsx"
},
{
"path": "kri-editor/KriEditorHtmlOnly.tsx",
"type": "registry:component",
"target": "@components/kri-editor/KriEditorHtmlOnly.tsx"
},
{
"path": "kri-editor/KriEditorSms.tsx",
"type": "registry:component",
"target": "@components/kri-editor/KriEditorSms.tsx"
},
{
"path": "kri-editor/KriEditorWysiwyg.tsx",
"type": "registry:component",
"target": "@components/kri-editor/KriEditorWysiwyg.tsx"
},
{
"path": "kri-editor/extensions/div.ts",
"type": "registry:component",
"target": "@components/kri-editor/extensions/div.ts"
},
{
"path": "kri-editor/extensions/font-size.ts",
"type": "registry:component",
"target": "@components/kri-editor/extensions/font-size.ts"
},
{
"path": "kri-editor/hooks/useDebouncedChange.ts",
"type": "registry:component",
"target": "@components/kri-editor/hooks/useDebouncedChange.ts"
},
{
"path": "kri-editor/hooks/useTextareaInsert.ts",
"type": "registry:component",
"target": "@components/kri-editor/hooks/useTextareaInsert.ts"
},
{
"path": "kri-editor/index.ts",
"type": "registry:component",
"target": "@components/kri-editor/index.ts"
},
{
"path": "kri-editor/toolbar/Toolbar.tsx",
"type": "registry:component",
"target": "@components/kri-editor/toolbar/Toolbar.tsx"
},
{
"path": "kri-editor/toolbar/ToolbarButton.tsx",
"type": "registry:component",
"target": "@components/kri-editor/toolbar/ToolbarButton.tsx"
},
{
"path": "kri-editor/types.ts",
"type": "registry:component",
"target": "@components/kri-editor/types.ts"
},
{
"path": "kri-editor/utils/editorTypeGuards.ts",
"type": "registry:component",
"target": "@components/kri-editor/utils/editorTypeGuards.ts"
},
{
"path": "kri-editor/utils/imageCompression.ts",
"type": "registry:component",
"target": "@components/kri-editor/utils/imageCompression.ts"
},
{
"path": "kri-editor/utils/sanitizeHtml.ts",
"type": "registry:component",
"target": "@components/kri-editor/utils/sanitizeHtml.ts"
}
]
},
{
"name": "kri-layout",
"type": "registry:component",
"title": "KRI Layout",
"description": "프로젝트 상태와 라우터에 의존하지 않는 Header, Sidebar, MainLayout, PageTitle 컴포넌트 모음입니다.",
"registryDependencies": [
"button"
],
"dependencies": [
"lucide-react"
],
"files": [
{
"path": "layout/KriHeader.tsx",
"type": "registry:component",
"target": "@components/layout/KriHeader.tsx"
},
{
"path": "layout/KriMainLayout.tsx",
"type": "registry:component",
"target": "@components/layout/KriMainLayout.tsx"
},
{
"path": "layout/KriPageTitle.tsx",
"type": "registry:component",
"target": "@components/layout/KriPageTitle.tsx"
},
{
"path": "layout/KriSidebar.tsx",
"type": "registry:component",
"target": "@components/layout/KriSidebar.tsx"
},
{
"path": "layout/index.ts",
"type": "registry:component",
"target": "@components/layout/index.ts"
},
{
"path": "layout/types.ts",
"type": "registry:component",
"target": "@components/layout/types.ts"
}
]
},
{
"name": "kri-dialog",
"type": "registry:component",
"title": "KRI Dialog",
"description": "빈 Body, 기본 닫기 Footer 및 사용자 정의 Footer를 지원하는 범용 다이얼로그입니다.",
"registryDependencies": [
"button",
"dialog"
],
"files": [
{
"path": "KriDialog.tsx",
"type": "registry:component",
"target": "@components/common/KriDialog.tsx"
}
]
}
]
}

View File

@@ -0,0 +1,56 @@
import { access, readFile } from 'node:fs/promises'
import path from 'node:path'
const outputDir = path.resolve('dist/r')
const sourceRegistryPath = path.resolve('registry/components/registry.json')
const outputRegistryPath = path.join(outputDir, 'registry.json')
await access(outputRegistryPath)
const sourceRegistry = JSON.parse(await readFile(sourceRegistryPath, 'utf8'))
const outputRegistry = JSON.parse(await readFile(outputRegistryPath, 'utf8'))
if (outputRegistry.name !== 'kri') throw new Error(`Unexpected registry name: ${outputRegistry.name}`)
if (!Array.isArray(outputRegistry.items)) throw new Error('registry.items must be an array.')
if (outputRegistry.items.length !== sourceRegistry.items.length) {
throw new Error(`Expected ${sourceRegistry.items.length} items, received ${outputRegistry.items.length}.`)
}
for (const expected of sourceRegistry.items) {
const itemPath = path.join(outputDir, `${expected.name}.json`)
await access(itemPath)
const item = JSON.parse(await readFile(itemPath, 'utf8'))
if (item.name !== expected.name) throw new Error(`Unexpected item name: ${item.name}`)
if (!outputRegistry.items.some((entry) => entry.name === expected.name)) {
throw new Error(`${expected.name} was not found in registry.json.`)
}
for (const dependency of expected.registryDependencies ?? []) {
if (!item.registryDependencies?.includes(dependency)) {
throw new Error(`${expected.name} must depend on registry item ${dependency}.`)
}
}
for (const dependency of expected.dependencies ?? []) {
if (!item.dependencies?.includes(dependency)) {
throw new Error(`${expected.name} must include package ${dependency}.`)
}
}
for (const expectedFile of expected.files ?? []) {
const generatedFile = item.files?.find((file) => file.target === expectedFile.target)
if (!generatedFile?.content) throw new Error(`${expected.name}: ${expectedFile.target} content was not generated.`)
if (generatedFile.content.includes('content-text-')) {
throw new Error(`${expected.name}: project-specific content-text class remains in ${expectedFile.target}.`)
}
if (generatedFile.content.includes('@kri/common/ui')) {
throw new Error(`${expected.name}: @kri/common/ui import remains in ${expectedFile.target}.`)
}
}
console.log(`[OK] item=${item.name} files=${item.files?.length ?? 0}`)
}
console.log(`[OK] registry=${outputRegistry.name}`)
console.log(`[OK] items=${outputRegistry.items.length}`)
console.log(`[OK] output=${outputDir}`)

22
tsconfig.json Normal file
View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2021",
"lib": ["DOM", "DOM.Iterable", "ES2021"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"paths": {
"@/components/common/*": ["./registry/components/*"],
"@/components/ui/*": ["./.tooling/components/ui/*"],
"@/lib/*": ["./.tooling/lib/*"],
"@/*": ["./.tooling/*"]
}
},
"include": ["registry", ".tooling"]
}