261012_01_FST: first commit

This commit is contained in:
2026-10-12 12:37:46 +09:00
commit 964269cd82
137 changed files with 17476 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
"use client";
import Image from "next/image";
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { KriHeader } from "@/components/layout/KriHeader";
import { topMenus } from "@/config/menu.data";
import type { LoginUser } from "@kri/common";
interface AppHeaderProps {
menuOpen: boolean;
showMenuButton: boolean;
activeMenuId?: string;
user?: LoginUser | null;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
}
export function AppHeader({ menuOpen, showMenuButton, activeMenuId, user, onToggleMenu, onNavigate }: AppHeaderProps) {
return (
<KriHeader
logo={<Image src="/logo.png" alt="로고" width={120} height={40} className="h-10 w-auto object-contain" priority />}
menus={topMenus}
activeMenuId={activeMenuId}
menuOpen={menuOpen}
showMenuButton={showMenuButton}
onToggleMenu={onToggleMenu}
onNavigate={onNavigate}
right={
<>
<span className="hidden text-sm text-muted-foreground sm:inline">{user?.userName ?? ""}</span>
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
<LogOut className="size-4" />
<span className="hidden sm:inline">로그아웃</span>
</Button>
</>
}
/>
);
}

View File

@@ -0,0 +1,45 @@
"use client";
import type { Route } from "next";
import { useMemo, useState, type ReactNode } from "react";
import { usePathname, useRouter } from "next/navigation";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import { AppHeader } from "./AppHeader";
import { AppSidebar } from "./AppSidebar";
import { sideMenus, topMenus } from "@/config/menu.data";
import { useAuth } from "@/hooks/useAuth";
export function AppMainLayout({ children }: { children: ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const { auth } = useAuth();
const [menuOpen, setMenuOpen] = useState(true);
const activeMenuId = useMemo(
() => topMenus.find((item) => item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)))?.id,
[pathname],
);
const navigate = (path: string) => router.push(path as Route);
const hasSidebar = sideMenus.length > 0;
return (
<KriMainLayout
sidebarOpen={hasSidebar && menuOpen}
onSidebarOpenChange={setMenuOpen}
header={
<AppHeader
menuOpen={menuOpen}
showMenuButton={hasSidebar}
activeMenuId={activeMenuId}
user={auth.user}
onToggleMenu={() => setMenuOpen((current) => !current)}
onNavigate={navigate}
/>
}
sidebar={hasSidebar ? <AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} onNavigate={navigate} /> : undefined}
>
{children}
</KriMainLayout>
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,59 @@
'use client'
import { User } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { KriEditorProps } from './types'
type KkoEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'kko' }
export function KriEditorKko({
label,
value,
placeholder = '미리볼 내용이 없습니다.',
className,
kkoTitle = '',
kkoSenderName = '',
kkoHeaderLabel = '알림톡 도착',
}: KkoEditorProps) {
const body = value ?? ''
return (
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
<div className="flex h-full flex-col bg-[#d6e4f7] pt-8 pb-4">
{kkoSenderName ? (
<div className="border-b border-black/10 px-4 pb-3 text-center text-sm font-bold text-gray-900">{kkoSenderName}</div>
) : null}
<div className="flex-1 overflow-y-auto px-3 py-3">
{kkoSenderName ? (
<div className="mb-1 flex items-center gap-2">
<span aria-hidden="true" className="flex size-8 shrink-0 items-center justify-center rounded-full bg-gray-300 text-white">
<User className="size-5" />
</span>
<span className="text-xs text-gray-600">{kkoSenderName}</span>
</div>
) : null}
<div className="relative mr-3 ml-10 rounded-xl bg-white shadow-sm">
<span
aria-hidden="true"
className="absolute -top-3 -right-3 flex size-8 items-center justify-center rounded-full bg-gray-800 text-[9px] font-bold text-white"
>
kakao
</span>
<div className="rounded-t-xl bg-[#FEE500] px-4 py-3 text-sm font-bold text-gray-900">{kkoHeaderLabel}</div>
{kkoTitle ? <div className="px-4 pt-3 text-sm font-bold break-words whitespace-pre-wrap text-gray-800">{kkoTitle}</div> : null}
{body.trim() ? (
<div className="px-4 py-3 text-sm leading-relaxed break-words whitespace-pre-wrap text-gray-700">{body}</div>
) : (
<div className="px-4 py-3 text-sm text-gray-400">{placeholder}</div>
)}
</div>
</div>
</div>
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
</div>
</div>
)
}

View File

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

View File

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

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,93 @@
import { Node, mergeAttributes } from '@tiptap/core'
import TiptapImage from '@tiptap/extension-image'
import type { DOMOutputSpec } from '@tiptap/pm/model'
export type ImageMapAreaAttributes = {
shape?: string
coords?: string
href?: string
alt?: string
title?: string
target?: string
}
const readAttribute = (element: Element, name: string): string | undefined =>
element.getAttribute(name) ?? undefined
export const ImageWithMap = TiptapImage.extend({
addAttributes() {
return {
...this.parent?.(),
usemap: {
default: null,
parseHTML: (element) => element.getAttribute('usemap'),
renderHTML: (attributes) => attributes.usemap ? { usemap: attributes.usemap } : {},
},
align: {
default: null,
parseHTML: (element) => element.getAttribute('align'),
renderHTML: (attributes) => attributes.align ? { align: attributes.align } : {},
},
style: {
default: null,
parseHTML: (element) => element.getAttribute('style'),
renderHTML: (attributes) => attributes.style ? { style: attributes.style } : {},
},
loading: {
default: null,
parseHTML: (element) => element.getAttribute('loading'),
renderHTML: (attributes) => attributes.loading ? { loading: attributes.loading } : {},
},
}
},
})
export const ImageMap = Node.create({
name: 'imageMap',
group: 'block',
atom: true,
addAttributes() {
return {
name: {
default: null,
parseHTML: (element) => element.getAttribute('name'),
renderHTML: (attributes) => attributes.name ? { name: attributes.name } : {},
},
id: {
default: null,
parseHTML: (element) => element.getAttribute('id'),
renderHTML: (attributes) => attributes.id ? { id: attributes.id } : {},
},
areas: {
default: [],
parseHTML: (element) => Array.from(element.children)
.filter((child) => child.tagName.toLowerCase() === 'area')
.map((area): ImageMapAreaAttributes => ({
shape: readAttribute(area, 'shape'),
coords: readAttribute(area, 'coords'),
href: readAttribute(area, 'href'),
alt: readAttribute(area, 'alt'),
title: readAttribute(area, 'title'),
target: readAttribute(area, 'target'),
})),
renderHTML: () => ({}),
},
}
},
parseHTML() {
return [{ tag: 'map' }]
},
renderHTML({ node, HTMLAttributes }) {
const mapAttributes = { ...HTMLAttributes }
delete mapAttributes.areas
const areas = (node.attrs.areas as ImageMapAreaAttributes[]).map((area): DOMOutputSpec => [
'area',
Object.fromEntries(Object.entries(area).filter(([, value]) => Boolean(value))),
])
return ['map', mergeAttributes(mapAttributes), ...areas] as DOMOutputSpec
},
})

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,21 @@
export { KriEditor } from './KriEditor'
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
export { KriEditorKko } from './KriEditorKko'
export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
export { DEFAULT_FONT_FAMILY_OPTIONS } from './utils/fontFamilyOptions'
export type {
KriEditorAllowedHtml,
KriEditorCommand,
KriEditorFontFamilyOption,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,
KriEditorToolbarContext,
KriEditorToolbarFeature,
KriEditorUploadResult,
KriEditorWysiwygCompatibility,
ToolbarState,
} from './types'
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'

View File

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

View File

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

View File

@@ -0,0 +1,127 @@
import type { Extensions } from '@tiptap/core'
import type { Editor } from '@tiptap/react'
import type { ReactNode } from 'react'
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms' | 'kko'
export type KriEditorUploadResult = string | { url: string }
export type KriEditorToolbarFeature =
| 'fontFamily'
| 'fontSize'
| 'bold'
| 'italic'
| 'underline'
| 'strike'
| 'textColor'
| 'highlight'
| 'align'
| 'bulletList'
| 'orderedList'
| 'link'
| 'image'
| 'table'
| 'html'
export type KriEditorToolbarConfig = Partial<Record<KriEditorToolbarFeature, boolean>>
export type KriEditorCommand = {
focus: () => void
insertText: (text: string) => void
}
export type KriEditorToolbarContext = {
editor: Editor
command: KriEditorCommand
view: 'wysiwyg' | 'html'
}
export type KriEditorAllowedHtml = {
tags?: string[]
attributes?: string[]
}
export type KriEditorWysiwygCompatibility = {
compatible: boolean
reason?: string
}
export type KriEditorFontFamilyOption = {
label: string
value: string
}
export type KriEditorSmsImage = {
fileName: string
src: string
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
label?: string
value: string
onChange: (html: string) => void
placeholder?: string
className?: string
showPreview?: boolean
previewClassName?: string
mode?: KriEditorMode
/** @deprecated mode를 사용하세요. */
editorMode?: KriEditorMode
onImageUpload?: (file: File) => Promise<KriEditorUploadResult>
maxImageBytes?: number
imageMaxWidth?: number
imageMaxHeight?: number
imageQuality?: number
imageMimeType?: 'image/webp' | 'image/jpeg'
allowBase64?: boolean
sanitizeHtml?: boolean
rows?: number
onImageUploadError?: (error: unknown) => void
debounceMs?: number
smsTitle?: string
changeSmsType?: (type: 'SMS' | 'LMS') => void
isSmsReadOnly?: boolean
smsMaxBytes?: number
lmsMaxBytes?: number
smsPreviewSuffix?: string
/** 첨부파일이 있으면 길이·제목과 무관하게 LMS/MMS로 판정한다. */
smsHasAttachment?: boolean
/** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */
smsImages?: KriEditorSmsImage[]
/** 알림톡 미리보기의 강조 제목. 없으면 표시하지 않는다. */
kkoTitle?: string
/** 알림톡 미리보기의 채널명·발신 프로필 이름. 없으면 표시하지 않는다. */
kkoSenderName?: string
/** 알림톡 말풍선 상단 문구. 기본값 "알림톡 도착" */
kkoHeaderLabel?: string
toolbar?: KriEditorToolbarConfig | false
fontFamilyOptions?: KriEditorFontFamilyOption[]
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
editorExtensions?: Extensions
allowedCustomHtml?: KriEditorAllowedHtml
enableImageMap?: boolean
htmlSanitizer?: (html: string) => string
getWysiwygCompatibility?: (html: string) => KriEditorWysiwygCompatibility
transformPreviewHtml?: (html: string) => string
}
export type ToolbarState = {
fontFamily: string | null
fontSize: string
textColor: string | null
highlightColor: string | null
isBold: boolean
isItalic: boolean
isUnderline: boolean
isStrike: boolean
align: 'left' | 'center' | 'right'
isBulletList: boolean
isOrderedList: boolean
isLink: boolean
inTable: boolean
}
export function resolveUploadUrl(result: KriEditorUploadResult): string {
return typeof result === 'string' ? result : result.url
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,256 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

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

View File

@@ -0,0 +1,23 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { Label as LabelPrimitive } from "radix-ui"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

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

View File

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

View File

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

View File

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

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

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