v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,186 @@
|
||||
import React, { useState, useRef, useEffect, ReactNode } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
|
||||
export interface AccordionProps {
|
||||
/** 기본 열림 상태 */
|
||||
defaultOpen?: boolean;
|
||||
/** 외부에서 열림 상태 제어 */
|
||||
isOpen?: boolean;
|
||||
/** 열림 상태 변경 콜백 */
|
||||
onToggle?: (isOpen: boolean) => void;
|
||||
/** 추가 클래스명 */
|
||||
className?: string;
|
||||
/** 인라인 스타일 */
|
||||
style?: React.CSSProperties;
|
||||
/** 자식 요소 (trigger, content 슬롯) */
|
||||
children?: ReactNode;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
interface AccordionSlots {
|
||||
trigger?: ReactNode;
|
||||
content?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accordion 집합 컴포넌트
|
||||
*
|
||||
* 접기/펼치기가 가능한 아코디언 UI를 제공합니다.
|
||||
* trigger 슬롯과 content 슬롯을 통해 헤더와 내용을 정의합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Accordion",
|
||||
* "props": { "defaultOpen": false },
|
||||
* "children": [
|
||||
* {
|
||||
* "slot": "trigger",
|
||||
* "type": "basic",
|
||||
* "name": "Div",
|
||||
* "children": [{ "type": "basic", "name": "Span", "text": "제목" }]
|
||||
* },
|
||||
* {
|
||||
* "slot": "content",
|
||||
* "type": "basic",
|
||||
* "name": "Div",
|
||||
* "children": [{ "type": "basic", "name": "P", "text": "내용" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const Accordion: React.FC<AccordionProps> = ({
|
||||
defaultOpen = false,
|
||||
isOpen: controlledIsOpen,
|
||||
onToggle,
|
||||
className = '',
|
||||
style,
|
||||
children,
|
||||
disabled = false,
|
||||
}) => {
|
||||
// 내부 상태 (제어 모드가 아닐 때 사용)
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(defaultOpen);
|
||||
|
||||
// 제어 모드 여부 확인
|
||||
const isControlled = controlledIsOpen !== undefined;
|
||||
const isOpen = isControlled ? controlledIsOpen : internalIsOpen;
|
||||
|
||||
// 콘텐츠 높이 애니메이션을 위한 ref
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [contentHeight, setContentHeight] = useState<number | undefined>(
|
||||
defaultOpen ? undefined : 0
|
||||
);
|
||||
|
||||
// 토글 핸들러
|
||||
const handleToggle = () => {
|
||||
if (disabled) return;
|
||||
|
||||
const newIsOpen = !isOpen;
|
||||
|
||||
if (!isControlled) {
|
||||
setInternalIsOpen(newIsOpen);
|
||||
}
|
||||
|
||||
onToggle?.(newIsOpen);
|
||||
};
|
||||
|
||||
// 콘텐츠 높이 계산
|
||||
useEffect(() => {
|
||||
if (contentRef.current) {
|
||||
if (isOpen) {
|
||||
setContentHeight(contentRef.current.scrollHeight);
|
||||
// 애니메이션 완료 후 높이 auto로 설정 (동적 콘텐츠 지원)
|
||||
const timer = setTimeout(() => {
|
||||
setContentHeight(undefined);
|
||||
}, 300);
|
||||
return () => clearTimeout(timer);
|
||||
} else {
|
||||
// 닫힐 때: 현재 높이로 설정 후 0으로 변경 (애니메이션 트리거)
|
||||
setContentHeight(contentRef.current.scrollHeight);
|
||||
requestAnimationFrame(() => {
|
||||
setContentHeight(0);
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
// children에서 슬롯 추출
|
||||
const slots: AccordionSlots = {};
|
||||
|
||||
React.Children.forEach(children, (child) => {
|
||||
if (React.isValidElement(child)) {
|
||||
const slotName = (child.props as any)?.slot;
|
||||
if (slotName === 'trigger') {
|
||||
slots.trigger = child;
|
||||
} else if (slotName === 'content') {
|
||||
slots.content = child;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 슬롯이 없으면 children을 그대로 사용 (하위 호환성)
|
||||
if (!slots.trigger && !slots.content) {
|
||||
const childArray = React.Children.toArray(children);
|
||||
if (childArray.length >= 2) {
|
||||
slots.trigger = childArray[0];
|
||||
slots.content = childArray.slice(1);
|
||||
} else if (childArray.length === 1) {
|
||||
slots.content = childArray[0];
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{/* Trigger (헤더) */}
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleToggle}
|
||||
disabled={disabled}
|
||||
className={`w-full flex items-center justify-between p-3 text-left bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${
|
||||
disabled ? 'opacity-50 cursor-not-allowed' : ''
|
||||
} ${isOpen ? 'border-b border-gray-200 dark:border-gray-700' : ''}`}
|
||||
aria-expanded={isOpen}
|
||||
>
|
||||
<Div className="flex-1">
|
||||
{slots.trigger}
|
||||
</Div>
|
||||
{/* 화살표 아이콘 (기본 제공, trigger에서 오버라이드 가능) */}
|
||||
{!slots.trigger && (
|
||||
<svg
|
||||
className={`w-5 h-5 text-gray-500 dark:text-gray-400 transition-transform duration-200 ${
|
||||
isOpen ? 'rotate-180' : ''
|
||||
}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Content (내용) */}
|
||||
<Div
|
||||
ref={contentRef}
|
||||
className="overflow-hidden transition-all duration-300 ease-in-out"
|
||||
style={{
|
||||
height: contentHeight !== undefined ? `${contentHeight}px` : 'auto',
|
||||
}}
|
||||
>
|
||||
<Div className="bg-white dark:bg-gray-800">
|
||||
{slots.content}
|
||||
</Div>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,249 @@
|
||||
import React, { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface ActionMenuItem {
|
||||
id: string | number;
|
||||
label?: string;
|
||||
iconName?: IconName;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
variant?: 'default' | 'danger';
|
||||
/** 구분선 여부 (true면 구분선으로 렌더링) */
|
||||
divider?: boolean;
|
||||
/** 행 데이터의 필드 경로로 disabled 여부를 결정 (값이 falsy면 disabled) */
|
||||
disabledField?: string;
|
||||
/** 조건부 표시 (false면 아이템 숨김, 엔진이 표현식 평가 후 boolean 전달) */
|
||||
if?: boolean;
|
||||
}
|
||||
|
||||
export interface ActionMenuProps {
|
||||
items: ActionMenuItem[];
|
||||
triggerLabel?: string;
|
||||
triggerIconName?: IconName;
|
||||
position?: 'left' | 'right';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
/**
|
||||
* 커스텀 트리거 콘텐츠
|
||||
*
|
||||
* children이 제공되면 기본 Button 트리거 대신 children을 클릭 트리거로 사용합니다.
|
||||
* 레이아웃 JSON에서 ActionMenu의 children으로 정의한 컴포넌트가 트리거가 됩니다.
|
||||
*/
|
||||
children?: React.ReactNode;
|
||||
/**
|
||||
* 메뉴 아이템 클릭 시 호출되는 콜백
|
||||
* JSON 레이아웃의 actions에서 onItemClick 이벤트로 바인딩됨
|
||||
*
|
||||
* @param itemId - 클릭된 아이템의 id
|
||||
* @param item - 클릭된 아이템 전체 객체
|
||||
*/
|
||||
onItemClick?: (itemId: string | number, item: ActionMenuItem) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* ActionMenu 집합 컴포넌트
|
||||
*
|
||||
* 드롭다운 형태의 액션 메뉴 컴포넌트입니다.
|
||||
* 트리거 버튼과 메뉴 아이템 목록을 제공합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Button + Div + Span + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "ActionMenu",
|
||||
* "props": {
|
||||
* "triggerLabel": "작업",
|
||||
* "items": [
|
||||
* {"id": 1, "label": "수정", "iconName": "pencil"},
|
||||
* {"id": 2, "label": "삭제", "iconName": "trash", "variant": "danger"}
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const ActionMenu: React.FC<ActionMenuProps> = ({
|
||||
items,
|
||||
triggerLabel = '작업',
|
||||
triggerIconName = IconName.EllipsisVertical,
|
||||
position = 'right',
|
||||
className = '',
|
||||
style,
|
||||
children,
|
||||
onItemClick,
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
|
||||
const triggerRef = useRef<HTMLElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 메뉴 위치 계산
|
||||
const updateMenuPosition = useCallback(() => {
|
||||
if (!triggerRef.current) return;
|
||||
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
const menuWidth = 224; // w-56 = 14rem = 224px
|
||||
|
||||
let left = position === 'right' ? rect.right - menuWidth : rect.left;
|
||||
const top = rect.bottom + 8; // mt-2 = 8px
|
||||
|
||||
// 화면 왼쪽 경계 체크
|
||||
if (left < 8) {
|
||||
left = 8;
|
||||
}
|
||||
|
||||
// 화면 오른쪽 경계 체크
|
||||
if (left + menuWidth > window.innerWidth - 8) {
|
||||
left = window.innerWidth - menuWidth - 8;
|
||||
}
|
||||
|
||||
setMenuPosition({ top, left });
|
||||
}, [position]);
|
||||
|
||||
// 메뉴 열릴 때 위치 계산
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
updateMenuPosition();
|
||||
}
|
||||
}, [isOpen, updateMenuPosition]);
|
||||
|
||||
// 스크롤/리사이즈 시 메뉴 닫기
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleScrollOrResize = () => {
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', handleScrollOrResize, true);
|
||||
window.addEventListener('resize', handleScrollOrResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', handleScrollOrResize, true);
|
||||
window.removeEventListener('resize', handleScrollOrResize);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// 외부 클릭 감지
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
const target = event.target as Node;
|
||||
const isClickInsideTrigger = triggerRef.current?.contains(target);
|
||||
const isClickInsideMenu = menuRef.current?.contains(target);
|
||||
|
||||
if (!isClickInsideTrigger && !isClickInsideMenu) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
const handleItemClick = (item: ActionMenuItem) => {
|
||||
if (item.disabled) return;
|
||||
|
||||
// 1. 개별 아이템의 onClick 콜백 호출 (우선)
|
||||
if (item.onClick) {
|
||||
item.onClick();
|
||||
}
|
||||
|
||||
// 2. 통합 onItemClick 콜백 호출 (JSON 레이아웃 actions 바인딩)
|
||||
if (onItemClick) {
|
||||
onItemClick(item.id, item);
|
||||
}
|
||||
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
// Portal로 렌더링할 드롭다운 메뉴
|
||||
const dropdownMenu = isOpen
|
||||
? ReactDOM.createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed z-[9999] w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg overflow-hidden"
|
||||
style={{
|
||||
top: menuPosition.top,
|
||||
left: menuPosition.left,
|
||||
}}
|
||||
>
|
||||
{items.filter((item) => item.if !== false).map((item) => {
|
||||
// 구분선인 경우
|
||||
if (item.divider) {
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className="border-t border-gray-200 dark:border-gray-600 my-1"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const variantClasses =
|
||||
item.variant === 'danger'
|
||||
? 'text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20'
|
||||
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700';
|
||||
|
||||
const disabledClasses = item.disabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'cursor-pointer';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
onClick={() => handleItemClick(item)}
|
||||
className={`flex items-center gap-3 px-4 py-3 transition-colors ${variantClasses} ${disabledClasses}`}
|
||||
>
|
||||
{item.iconName && (
|
||||
<Icon name={item.iconName} className="w-4 h-4" />
|
||||
)}
|
||||
<span className="text-sm font-medium">{item.label}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Div className={`relative inline-block ${className}`} style={style}>
|
||||
{/* 트리거: children이 있으면 커스텀 트리거, 없으면 기본 Button */}
|
||||
{children ? (
|
||||
<Div
|
||||
ref={triggerRef as React.RefObject<HTMLDivElement>}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{children}
|
||||
</Div>
|
||||
) : (
|
||||
<Button
|
||||
ref={triggerRef as React.RefObject<HTMLButtonElement>}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex items-center gap-2 px-2 py-1 bg-transparent hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
|
||||
>
|
||||
{triggerLabel && (
|
||||
<Span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{triggerLabel}
|
||||
</Span>
|
||||
)}
|
||||
{triggerIconName && (
|
||||
<Icon name={triggerIconName} className="w-4 h-4 text-gray-500 dark:text-gray-400" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Portal로 렌더링되는 드롭다운 메뉴 */}
|
||||
{dropdownMenu}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,183 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { A } from '../basic/A';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
/**
|
||||
* 빠른 링크 인터페이스
|
||||
*/
|
||||
export interface QuickLink {
|
||||
id: string | number;
|
||||
label: string;
|
||||
url: string;
|
||||
iconName?: IconName;
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminFooter Props
|
||||
*/
|
||||
export interface AdminFooterProps {
|
||||
copyright?: string;
|
||||
version?: string;
|
||||
quickLinks?: QuickLink[];
|
||||
className?: string;
|
||||
copyrightModalId?: string;
|
||||
changelogModalId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminFooter 컴포넌트
|
||||
*
|
||||
* 관리자 푸터 - 버전 정보, 빠른 링크
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <AdminFooter
|
||||
* copyright="© 2026 G7"
|
||||
* version="1.0.0"
|
||||
* quickLinks={[
|
||||
* { id: 1, label: '문서', url: '/docs', iconName: IconName.FileText },
|
||||
* { id: 2, label: '지원', url: '/support', iconName: IconName.HelpCircle }
|
||||
* ]}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const AdminFooter: React.FC<AdminFooterProps> = ({
|
||||
copyright = '© 2026 G7',
|
||||
version,
|
||||
quickLinks = [],
|
||||
className = '',
|
||||
changelogModalId,
|
||||
copyrightModalId,
|
||||
}) => {
|
||||
const handleVersionClick = useCallback(() => {
|
||||
if (changelogModalId) {
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
G7Core?.dispatch?.({
|
||||
handler: 'sequence',
|
||||
actions: [
|
||||
{
|
||||
handler: 'apiCall',
|
||||
auth_required: true,
|
||||
target: '/api/admin/changelog',
|
||||
params: {
|
||||
method: 'GET',
|
||||
},
|
||||
onSuccess: [
|
||||
{
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'global',
|
||||
coreChangelogContent: '{{response.data.content}}',
|
||||
},
|
||||
},
|
||||
{
|
||||
handler: 'openModal',
|
||||
target: changelogModalId,
|
||||
},
|
||||
],
|
||||
onError: [
|
||||
{
|
||||
handler: 'openModal',
|
||||
target: changelogModalId,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}, [changelogModalId]);
|
||||
|
||||
const handleCopyrightClick = useCallback(() => {
|
||||
if (copyrightModalId) {
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
G7Core?.dispatch?.({
|
||||
handler: 'sequence',
|
||||
actions: [
|
||||
{
|
||||
handler: 'apiCall',
|
||||
auth_required: true,
|
||||
target: '/api/admin/license',
|
||||
params: {
|
||||
method: 'GET',
|
||||
},
|
||||
onSuccess: [
|
||||
{
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'global',
|
||||
coreLicenseContent: '{{response.data.content}}',
|
||||
},
|
||||
},
|
||||
{
|
||||
handler: 'openModal',
|
||||
target: copyrightModalId,
|
||||
},
|
||||
],
|
||||
onError: [
|
||||
{
|
||||
handler: 'openModal',
|
||||
target: copyrightModalId,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}, [copyrightModalId]);
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`
|
||||
bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-6 py-4
|
||||
${className}
|
||||
`}
|
||||
>
|
||||
<Div className="flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
{/* 왼쪽: 저작권 및 버전 정보 */}
|
||||
<Div className="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
<Span
|
||||
className={copyrightModalId ? 'cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 transition-colors' : ''}
|
||||
onClick={copyrightModalId ? handleCopyrightClick : undefined}
|
||||
>
|
||||
{copyright}
|
||||
</Span>
|
||||
{version && (
|
||||
<>
|
||||
<Span className="hidden md:inline">•</Span>
|
||||
<Span
|
||||
className={`flex items-center gap-2 ${changelogModalId ? 'cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 transition-colors' : ''}`}
|
||||
onClick={changelogModalId ? handleVersionClick : undefined}
|
||||
>
|
||||
<Icon name={IconName.Tag} className="w-4 h-4" />
|
||||
<Span>v{version}</Span>
|
||||
</Span>
|
||||
</>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 오른쪽: 빠른 링크 */}
|
||||
{quickLinks.length > 0 && (
|
||||
<Div className="flex items-center gap-4">
|
||||
{quickLinks.map((link) => (
|
||||
<A
|
||||
key={link.id}
|
||||
href={link.url}
|
||||
className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
|
||||
>
|
||||
{link.iconName && (
|
||||
<Icon name={link.iconName} className="w-4 h-4" />
|
||||
)}
|
||||
<Span>{link.label}</Span>
|
||||
</A>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,243 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Img } from '../basic/Img';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
/**
|
||||
* 사용자 정보 인터페이스
|
||||
*/
|
||||
export interface AdminUser {
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
role?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림 아이템 인터페이스
|
||||
*/
|
||||
export interface NotificationItem {
|
||||
id: string | number;
|
||||
title: string;
|
||||
message: string;
|
||||
time: string;
|
||||
read?: boolean;
|
||||
iconName?: IconName;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminHeader Props
|
||||
*/
|
||||
export interface AdminHeaderProps {
|
||||
user: AdminUser;
|
||||
notifications?: NotificationItem[];
|
||||
onNotificationClick?: (id: string | number) => void;
|
||||
onProfileClick?: () => void;
|
||||
onLogoutClick?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminHeader 컴포넌트
|
||||
*
|
||||
* 관리자 헤더 - 사용자 프로필, 알림 센터
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <AdminHeader
|
||||
* user={{
|
||||
* name: '홍길동',
|
||||
* email: 'hong@example.com',
|
||||
* avatar: '/avatar.png',
|
||||
* role: '관리자'
|
||||
* }}
|
||||
* notifications={[
|
||||
* { id: 1, title: '새 댓글', message: '게시물에 댓글이 달렸습니다', time: '5분 전' }
|
||||
* ]}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const AdminHeader: React.FC<AdminHeaderProps> = ({
|
||||
user = { name: '', email: '' },
|
||||
notifications = [],
|
||||
onNotificationClick,
|
||||
onProfileClick,
|
||||
onLogoutClick,
|
||||
className = '',
|
||||
}) => {
|
||||
const [showNotifications, setShowNotifications] = useState(false);
|
||||
const [showProfileMenu, setShowProfileMenu] = useState(false);
|
||||
const notificationRef = useRef<HTMLDivElement>(null);
|
||||
const profileRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.read).length;
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지
|
||||
*/
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
notificationRef.current &&
|
||||
!notificationRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setShowNotifications(false);
|
||||
}
|
||||
if (
|
||||
profileRef.current &&
|
||||
!profileRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setShowProfileMenu(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`
|
||||
bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 flex items-center justify-end gap-4
|
||||
${className}
|
||||
`}
|
||||
>
|
||||
{/* 알림 센터 */}
|
||||
<Div ref={notificationRef} className="relative">
|
||||
<Button
|
||||
onClick={() => setShowNotifications(!showNotifications)}
|
||||
className="relative p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-colors"
|
||||
aria-label={t('common.notifications')}
|
||||
>
|
||||
<Icon name={IconName.Bell} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
{unreadCount > 0 && (
|
||||
<Span className="absolute top-0 right-0 flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-red-500 rounded-full">
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
</Span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* 알림 드롭다운 */}
|
||||
{showNotifications && (
|
||||
<Div className="absolute right-0 mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<Span className="font-semibold text-gray-900 dark:text-white">{t('common.notifications')}</Span>
|
||||
</Div>
|
||||
<Div className="max-h-96 overflow-y-auto">
|
||||
{notifications.length === 0 ? (
|
||||
<Div className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
|
||||
<Span>{t('common.no_notifications')}</Span>
|
||||
</Div>
|
||||
) : (
|
||||
notifications.map((notification) => (
|
||||
<Button
|
||||
key={notification.id}
|
||||
onClick={() => {
|
||||
notification.onClick?.();
|
||||
onNotificationClick?.(notification.id);
|
||||
setShowNotifications(false);
|
||||
}}
|
||||
className={`
|
||||
w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 border-b border-gray-100 dark:border-gray-700 transition-colors
|
||||
${!notification.read ? 'bg-blue-50 dark:bg-blue-900/20' : ''}
|
||||
`}
|
||||
>
|
||||
<Div className="flex items-start gap-3">
|
||||
{notification.iconName && (
|
||||
<Icon
|
||||
name={notification.iconName}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5"
|
||||
/>
|
||||
)}
|
||||
<Div className="flex-1">
|
||||
<Div className="font-semibold text-gray-900 dark:text-white text-sm">
|
||||
{notification.title}
|
||||
</Div>
|
||||
<Div className="text-gray-600 dark:text-gray-400 text-sm mt-1">
|
||||
{notification.message}
|
||||
</Div>
|
||||
<Div className="text-gray-400 dark:text-gray-500 text-xs mt-1">
|
||||
{notification.time}
|
||||
</Div>
|
||||
</Div>
|
||||
{!notification.read && (
|
||||
<Span className="w-2 h-2 bg-blue-500 rounded-full mt-1.5" />
|
||||
)}
|
||||
</Div>
|
||||
</Button>
|
||||
))
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 사용자 프로필 */}
|
||||
<Div ref={profileRef} className="relative">
|
||||
<Button
|
||||
onClick={() => setShowProfileMenu(!showProfileMenu)}
|
||||
className="flex items-center gap-3 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
|
||||
>
|
||||
{user.avatar ? (
|
||||
<Img
|
||||
src={user.avatar}
|
||||
alt={user.name}
|
||||
className="w-8 h-8 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Div className="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
|
||||
<Icon name={IconName.User} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
</Div>
|
||||
)}
|
||||
<Div className="hidden md:block text-left">
|
||||
<Div className="font-semibold text-gray-900 dark:text-white text-sm">{user.name}</Div>
|
||||
{user.role && (
|
||||
<Div className="text-gray-500 dark:text-gray-400 text-xs">{user.role}</Div>
|
||||
)}
|
||||
</Div>
|
||||
<Icon name={IconName.ChevronDown} className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
</Button>
|
||||
|
||||
{/* 프로필 드롭다운 */}
|
||||
{showProfileMenu && (
|
||||
<Div className="absolute right-0 mt-2 w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<Div className="font-semibold text-gray-900 dark:text-white">{user.name}</Div>
|
||||
<Div className="text-gray-500 dark:text-gray-400 text-sm">{user.email}</Div>
|
||||
</Div>
|
||||
<Div className="py-2">
|
||||
<Button
|
||||
onClick={() => {
|
||||
onProfileClick?.();
|
||||
setShowProfileMenu(false);
|
||||
}}
|
||||
className="w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors text-gray-900 dark:text-white"
|
||||
>
|
||||
<Icon name={IconName.User} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
<Span>{t('common.profile_settings')}</Span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
onLogoutClick?.();
|
||||
setShowProfileMenu(false);
|
||||
}}
|
||||
className="w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 text-red-600 dark:text-red-400 transition-colors"
|
||||
>
|
||||
<Icon name={IconName.ArrowRight} className="w-5 h-5" />
|
||||
<Span>{t('common.logout')}</Span>
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,457 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Img } from '../basic/Img';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
import { I } from '../basic/I';
|
||||
|
||||
// G7Core 전역 객체 접근 헬퍼
|
||||
const G7Core = () => (window as any).G7Core;
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
/**
|
||||
* 메뉴 아이템 인터페이스 (API 응답 구조)
|
||||
*/
|
||||
export interface MenuItem {
|
||||
id: string | number;
|
||||
name: string | { ko: string; en: string };
|
||||
slug: string;
|
||||
url?: string | null;
|
||||
icon?: string;
|
||||
children?: MenuItem[];
|
||||
is_active?: boolean;
|
||||
module_id?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminSidebar Props
|
||||
*/
|
||||
export interface AdminSidebarProps {
|
||||
logo?: string;
|
||||
logoAlt?: string;
|
||||
menu: MenuItem[];
|
||||
collapsed?: boolean;
|
||||
onToggleCollapse?: () => void;
|
||||
className?: string;
|
||||
/** 현재 로케일 (다국어 메뉴 이름 표시용). 미지정 시 G7Core.locale.current() 자동 사용 */
|
||||
currentLocale?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminSidebar 컴포넌트
|
||||
*
|
||||
* 관리자 사이드바 - 계층형 메뉴, 접기/펼치기 기능 제공
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <AdminSidebar
|
||||
* logo="/logo.png"
|
||||
* menu={[
|
||||
* { id: 1, name: { ko: '대시보드', en: 'Dashboard' }, slug: 'dashboard', url: '/admin', icon: 'fas fa-tachometer-alt' },
|
||||
* {
|
||||
* id: 2,
|
||||
* name: { ko: '콘텐츠', en: 'Content' },
|
||||
* slug: 'content',
|
||||
* icon: 'fas fa-file-text',
|
||||
* children: [
|
||||
* { id: 21, name: { ko: '게시물', en: 'Posts' }, slug: 'posts', url: '/admin/posts', icon: 'fas fa-list' },
|
||||
* { id: 22, name: { ko: '페이지', en: 'Pages' }, slug: 'pages', url: '/admin/pages', icon: 'fas fa-file' }
|
||||
* ]
|
||||
* }
|
||||
* ]}
|
||||
* collapsed={false}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const AdminSidebar: React.FC<AdminSidebarProps> = ({
|
||||
logo,
|
||||
logoAlt = 'Logo',
|
||||
menu = [],
|
||||
collapsed = false,
|
||||
onToggleCollapse,
|
||||
className = '',
|
||||
currentLocale: currentLocaleProp,
|
||||
}) => {
|
||||
const [expandedItems, setExpandedItems] = useState<Set<string | number>>(new Set());
|
||||
const [locale, setLocale] = useState<string>(currentLocaleProp || G7Core()?.locale?.current?.() || 'ko');
|
||||
const [currentPath, setCurrentPath] = useState<string>(window.location.pathname);
|
||||
|
||||
// 메뉴 트리에서 모든 URL 수집 (가장 구체적인 매칭 판별용)
|
||||
const allMenuUrls = useMemo(() => {
|
||||
const urls: string[] = [];
|
||||
const collect = (items: MenuItem[]) => {
|
||||
for (const item of items) {
|
||||
if (item.url) urls.push(item.url);
|
||||
if (item.children) collect(item.children);
|
||||
}
|
||||
};
|
||||
collect(menu);
|
||||
return urls;
|
||||
}, [menu]);
|
||||
|
||||
// 주어진 경로에 가장 구체적으로 매칭되는 메뉴 URL 찾기
|
||||
const findBestMatch = useCallback((path: string): string | null => {
|
||||
let bestMatch: string | null = null;
|
||||
for (const url of allMenuUrls) {
|
||||
if (path === url || path.startsWith(url + '/')) {
|
||||
if (!bestMatch || url.length > bestMatch.length) {
|
||||
bestMatch = url;
|
||||
}
|
||||
}
|
||||
}
|
||||
return bestMatch;
|
||||
}, [allMenuUrls]);
|
||||
|
||||
// G7Core 로케일 및 경로 변경 구독
|
||||
useEffect(() => {
|
||||
const g7core = G7Core();
|
||||
if (!g7core?.state?.subscribe) return;
|
||||
|
||||
const unsubscribe = g7core.state.subscribe((state: any) => {
|
||||
const newLocale = state?._global?.locale || g7core?.locale?.current?.() || 'ko';
|
||||
setLocale(newLocale);
|
||||
|
||||
// 현재 경로 업데이트
|
||||
const newPath = state?._global?.currentPath || window.location.pathname;
|
||||
setCurrentPath(newPath);
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
|
||||
// 브라우저 뒤로가기/앞으로가기 감지
|
||||
useEffect(() => {
|
||||
const handlePopState = () => {
|
||||
setCurrentPath(window.location.pathname);
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', handlePopState);
|
||||
return () => window.removeEventListener('popstate', handlePopState);
|
||||
}, []);
|
||||
|
||||
// currentLocale prop이 변경되면 우선 적용
|
||||
useEffect(() => {
|
||||
if (currentLocaleProp) {
|
||||
setLocale(currentLocaleProp);
|
||||
}
|
||||
}, [currentLocaleProp]);
|
||||
|
||||
/**
|
||||
* 특정 경로가 메뉴 URL과 일치하는지 확인
|
||||
* 접두사 매칭 시 가장 구체적인(가장 긴) 매칭만 활성화 (Issue #37)
|
||||
*
|
||||
* @param url 메뉴 URL
|
||||
* @param path 확인할 경로
|
||||
* @returns 일치 여부
|
||||
*/
|
||||
const isPathActive = (url: string | null | undefined, path: string): boolean => {
|
||||
if (!url || typeof path !== 'string') return false;
|
||||
if (path === url) return true;
|
||||
if (path.startsWith(url + '/')) {
|
||||
return findBestMatch(path) === url;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 활성 메뉴의 부모 ID들을 찾아 반환
|
||||
*
|
||||
* @param items 메뉴 아이템 배열
|
||||
* @param path 현재 경로
|
||||
* @returns 활성 부모 ID Set
|
||||
*/
|
||||
const findActiveParentIds = (items: MenuItem[], path: string): Set<string | number> => {
|
||||
const parents = new Set<string | number>();
|
||||
|
||||
const traverse = (menuItems: MenuItem[]): boolean => {
|
||||
for (const item of menuItems) {
|
||||
if (item.children && item.children.length > 0) {
|
||||
const hasActiveInChildren = traverse(item.children);
|
||||
if (hasActiveInChildren || isPathActive(item.url, path)) {
|
||||
parents.add(item.id);
|
||||
return true;
|
||||
}
|
||||
} else if (isPathActive(item.url, path)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
traverse(items);
|
||||
return parents;
|
||||
};
|
||||
|
||||
// 초기 로드 및 경로 변경 시 활성 메뉴의 부모를 자동 펼침
|
||||
useEffect(() => {
|
||||
if (menu.length > 0 && currentPath) {
|
||||
const activeParents = findActiveParentIds(menu, currentPath);
|
||||
if (activeParents.size > 0) {
|
||||
setExpandedItems((prev) => new Set([...prev, ...activeParents]));
|
||||
}
|
||||
}
|
||||
}, [currentPath, menu]);
|
||||
|
||||
/**
|
||||
* 메뉴 URL이 현재 경로와 일치하는지 확인
|
||||
* 접두사 매칭 시 가장 구체적인 매칭만 활성화 (Issue #37)
|
||||
*
|
||||
* @param url 메뉴 URL
|
||||
* @returns 활성 여부
|
||||
*/
|
||||
const isActiveMenu = (url: string | null | undefined): boolean => {
|
||||
return isPathActive(url, currentPath);
|
||||
};
|
||||
|
||||
/**
|
||||
* 하위 메뉴 중 활성 메뉴가 있는지 확인 (부모 메뉴 강조용)
|
||||
*
|
||||
* @param item 메뉴 아이템
|
||||
* @returns 하위에 활성 메뉴 존재 여부
|
||||
*/
|
||||
const hasActiveChild = (item: MenuItem): boolean => {
|
||||
if (!item.children) return false;
|
||||
return item.children.some((child) => isActiveMenu(child.url) || hasActiveChild(child));
|
||||
};
|
||||
|
||||
/**
|
||||
* 하위 메뉴 토글
|
||||
*/
|
||||
const toggleExpand = (itemId: string | number) => {
|
||||
setExpandedItems((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(itemId)) {
|
||||
newSet.delete(itemId);
|
||||
} else {
|
||||
newSet.add(itemId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 다국어 name을 현재 로케일에 맞게 반환
|
||||
*/
|
||||
const getMenuLabel = (name: string | { ko: string; en: string; [key: string]: string }): string => {
|
||||
if (typeof name === 'string') return name;
|
||||
// 현재 로케일에 맞는 이름 반환, fallback으로 en → 첫 번째 값
|
||||
return name[locale] || name.en || Object.values(name)[0] || '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 메뉴 네비게이션 핸들러
|
||||
* G7Core.dispatch가 있으면 SPA 방식으로, 없으면 전체 페이지 리로드
|
||||
* 모바일에서는 페이지 로드 완료 후 사이드바를 닫음
|
||||
*/
|
||||
const handleNavigate = (event: React.MouseEvent, url: string) => {
|
||||
if (G7Core()?.dispatch) {
|
||||
// G7Core.dispatch가 있으면 SPA 방식 네비게이션
|
||||
event.preventDefault();
|
||||
|
||||
// 페이지 전환 완료 후 사이드바 닫기
|
||||
G7Core().navigation?.onComplete(() => {
|
||||
G7Core().dispatch({
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'global',
|
||||
sidebarOpen: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
G7Core().dispatch({
|
||||
handler: 'navigate',
|
||||
params: { path: url },
|
||||
});
|
||||
} else {
|
||||
// fallback: 전체 페이지 리로드
|
||||
window.location.href = url;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 메뉴 아이템 렌더링 (재귀)
|
||||
*/
|
||||
const renderMenuItem = (item: MenuItem, level: number = 0): React.ReactNode => {
|
||||
const hasChildren = item.children && item.children.length > 0;
|
||||
const isExpanded = expandedItems.has(item.id);
|
||||
const paddingLeft = level * 16 + 16;
|
||||
const label = getMenuLabel(item.name);
|
||||
|
||||
// 활성 메뉴 판별
|
||||
const isActive = isActiveMenu(item.url);
|
||||
const hasActiveDescendant = hasActiveChild(item);
|
||||
|
||||
// 스타일 클래스
|
||||
const baseClass = 'w-full flex items-center justify-between px-4 py-3 transition-colors';
|
||||
const activeClass = 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 border-l-4 border-blue-500';
|
||||
const activeParentClass = 'text-blue-600 dark:text-blue-400';
|
||||
const defaultClass = 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700';
|
||||
const disabledClass = 'text-gray-400 dark:text-gray-500 cursor-default';
|
||||
|
||||
return (
|
||||
<Div key={item.id}>
|
||||
{/* 메뉴 아이템 */}
|
||||
{hasChildren && item.url ? (
|
||||
// 하위 메뉴 + URL 있는 경우: 텍스트 클릭 → 네비게이션, chevron 클릭 → 토글
|
||||
<Div
|
||||
className={`
|
||||
${baseClass}
|
||||
${isActive ? activeClass : hasActiveDescendant ? activeParentClass : defaultClass}
|
||||
${collapsed ? 'justify-center' : ''}
|
||||
`}
|
||||
style={{ paddingLeft: collapsed ? undefined : `${paddingLeft}px` }}
|
||||
>
|
||||
<Button
|
||||
onClick={(event) => handleNavigate(event, item.url!)}
|
||||
className="flex items-center justify-start flex-1 min-w-0"
|
||||
>
|
||||
{item.icon && (
|
||||
<I
|
||||
className={`${item.icon} ${collapsed ? '' : 'mr-3'} w-5 h-5 flex items-center justify-center`}
|
||||
/>
|
||||
)}
|
||||
{!collapsed && <Span className="truncate">{label}</Span>}
|
||||
</Button>
|
||||
{!collapsed && (
|
||||
<Div className="flex items-center gap-1">
|
||||
{item.module_id && (
|
||||
<I className="fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60" title="모듈 메뉴" />
|
||||
)}
|
||||
<Button
|
||||
onClick={() => toggleExpand(item.id)}
|
||||
className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
|
||||
aria-label={t(isExpanded ? 'common.collapse' : 'common.expand')}
|
||||
>
|
||||
<I
|
||||
className={`fas fa-chevron-down w-4 h-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</Button>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
) : hasChildren ? (
|
||||
// 하위 메뉴만 있는 경우 (URL 없음): 전체 클릭 → 토글
|
||||
<Button
|
||||
onClick={() => toggleExpand(item.id)}
|
||||
className={`
|
||||
${baseClass}
|
||||
${hasActiveDescendant ? activeParentClass : defaultClass}
|
||||
${collapsed ? 'justify-center' : ''}
|
||||
`}
|
||||
style={{ paddingLeft: collapsed ? undefined : `${paddingLeft}px` }}
|
||||
>
|
||||
<Div className="flex items-center">
|
||||
{item.icon && (
|
||||
<I
|
||||
className={`${item.icon} ${collapsed ? '' : 'mr-3'} w-5 h-5 flex items-center justify-center`}
|
||||
/>
|
||||
)}
|
||||
{!collapsed && <Span>{label}</Span>}
|
||||
</Div>
|
||||
{!collapsed && (
|
||||
<Div className="flex items-center gap-1">
|
||||
{item.module_id && (
|
||||
<I className="fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60" title="모듈 메뉴" />
|
||||
)}
|
||||
<I
|
||||
className={`fas fa-chevron-down w-4 h-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</Div>
|
||||
)}
|
||||
</Button>
|
||||
) : item.url ? (
|
||||
// 하위 메뉴가 없고 URL이 있는 경우: 네비게이션 버튼
|
||||
<Button
|
||||
onClick={(event) => handleNavigate(event, item.url!)}
|
||||
className={`
|
||||
${baseClass}
|
||||
${isActive ? activeClass : defaultClass}
|
||||
${collapsed ? 'justify-center' : ''}
|
||||
text-left
|
||||
`}
|
||||
style={{ paddingLeft: collapsed ? undefined : `${paddingLeft}px` }}
|
||||
>
|
||||
<Div className="flex items-center">
|
||||
{item.icon && (
|
||||
<I
|
||||
className={`${item.icon} ${collapsed ? '' : 'mr-3'} w-5 h-5 flex items-center justify-center`}
|
||||
/>
|
||||
)}
|
||||
{!collapsed && <Span>{label}</Span>}
|
||||
</Div>
|
||||
{!collapsed && item.module_id && (
|
||||
<I className="fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60" title="모듈 메뉴" />
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
// 하위 메뉴도 없고 URL도 없는 경우: 비활성 버튼
|
||||
<Button
|
||||
className={`
|
||||
${baseClass}
|
||||
${disabledClass}
|
||||
${collapsed ? 'justify-center' : ''}
|
||||
text-left
|
||||
`}
|
||||
style={{ paddingLeft: collapsed ? undefined : `${paddingLeft}px` }}
|
||||
>
|
||||
<Div className="flex items-center">
|
||||
{item.icon && (
|
||||
<I
|
||||
className={`${item.icon} ${collapsed ? '' : 'mr-3'} w-5 h-5 flex items-center justify-center`}
|
||||
/>
|
||||
)}
|
||||
{!collapsed && <Span>{label}</Span>}
|
||||
</Div>
|
||||
{!collapsed && item.module_id && (
|
||||
<I className="fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60" title="모듈 메뉴" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 하위 메뉴 */}
|
||||
{hasChildren && !collapsed && isExpanded && (
|
||||
<Div className="bg-gray-50 dark:bg-gray-900">
|
||||
{item.children!.map((child) => renderMenuItem(child, level + 1))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Div className={className}>
|
||||
{/* 로고 영역 (선택적) */}
|
||||
{(logo || onToggleCollapse) && (
|
||||
<Div className="flex items-center justify-between px-4 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||
{logo && !collapsed && (
|
||||
<Img
|
||||
src={logo}
|
||||
alt={logoAlt}
|
||||
className="h-8"
|
||||
/>
|
||||
)}
|
||||
{onToggleCollapse && (
|
||||
<Button
|
||||
onClick={onToggleCollapse}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
|
||||
aria-label={collapsed ? t('common.expand_sidebar') : t('common.collapse_sidebar')}
|
||||
>
|
||||
<I
|
||||
className={`${collapsed ? 'fas fa-chevron-right' : 'fas fa-chevron-left'} w-5 h-5 text-gray-600 dark:text-gray-400`}
|
||||
/>
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 메뉴 영역 */}
|
||||
<Div>
|
||||
{menu.map((item) => renderMenuItem(item))}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { P } from '../basic/P';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
/**
|
||||
* 알림 타입
|
||||
*/
|
||||
export type AlertType = 'info' | 'success' | 'warning' | 'error';
|
||||
|
||||
export interface AlertProps {
|
||||
/**
|
||||
* 알림 타입
|
||||
*/
|
||||
type: AlertType;
|
||||
|
||||
/**
|
||||
* 알림 메시지
|
||||
*/
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* 닫기 버튼 표시 여부
|
||||
*/
|
||||
dismissible?: boolean;
|
||||
|
||||
/**
|
||||
* 닫기 버튼 클릭 시 콜백
|
||||
*/
|
||||
onDismiss?: () => void;
|
||||
|
||||
/**
|
||||
* 사용자 정의 클래스
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alert 알림 컴포넌트
|
||||
*
|
||||
* 알림 메시지를 표시하는 composite 컴포넌트입니다.
|
||||
* type에 따라 다른 색상과 아이콘을 표시하며 dismissible 옵션을 지원합니다.
|
||||
*
|
||||
* @example
|
||||
* // 정보 알림
|
||||
* <Alert type="info" message="정보 메시지입니다." />
|
||||
*
|
||||
* // 성공 알림 (닫기 버튼 포함)
|
||||
* <Alert
|
||||
* type="success"
|
||||
* message="작업이 완료되었습니다."
|
||||
* dismissible
|
||||
* onDismiss={() => console.log('dismissed')}
|
||||
* />
|
||||
*
|
||||
* // 경고 알림
|
||||
* <Alert type="warning" message="주의가 필요합니다." />
|
||||
*
|
||||
* // 에러 알림
|
||||
* <Alert type="error" message="오류가 발생했습니다." />
|
||||
*/
|
||||
export const Alert: React.FC<AlertProps> = ({
|
||||
type,
|
||||
message,
|
||||
dismissible = false,
|
||||
onDismiss,
|
||||
className = '',
|
||||
}) => {
|
||||
// 타입별 색상 및 아이콘 매핑
|
||||
const typeConfig = {
|
||||
info: {
|
||||
bgColor: 'bg-blue-100 dark:bg-blue-900',
|
||||
borderColor: 'border-blue-400 dark:border-blue-600',
|
||||
textColor: 'text-blue-800 dark:text-blue-200',
|
||||
iconColor: 'text-blue-600 dark:text-blue-400',
|
||||
icon: IconName.InfoCircle,
|
||||
},
|
||||
success: {
|
||||
bgColor: 'bg-green-100 dark:bg-green-900',
|
||||
borderColor: 'border-green-400 dark:border-green-600',
|
||||
textColor: 'text-green-800 dark:text-green-200',
|
||||
iconColor: 'text-green-600 dark:text-green-400',
|
||||
icon: IconName.CheckCircle,
|
||||
},
|
||||
warning: {
|
||||
bgColor: 'bg-yellow-100 dark:bg-yellow-900',
|
||||
borderColor: 'border-yellow-400 dark:border-yellow-600',
|
||||
textColor: 'text-yellow-800 dark:text-yellow-200',
|
||||
iconColor: 'text-yellow-600 dark:text-yellow-400',
|
||||
icon: IconName.ExclamationTriangle,
|
||||
},
|
||||
error: {
|
||||
bgColor: 'bg-red-100 dark:bg-red-900',
|
||||
borderColor: 'border-red-400 dark:border-red-600',
|
||||
textColor: 'text-red-800 dark:text-red-200',
|
||||
iconColor: 'text-red-600 dark:text-red-400',
|
||||
icon: IconName.TimesCircle,
|
||||
},
|
||||
};
|
||||
|
||||
const config = typeConfig[type];
|
||||
|
||||
// 컨테이너 클래스 조합
|
||||
const containerClasses = `
|
||||
flex items-start gap-3 p-4 rounded-lg border
|
||||
${config.bgColor}
|
||||
${config.borderColor}
|
||||
${className}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={containerClasses}
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
{/* 아이콘 */}
|
||||
<Icon
|
||||
name={config.icon}
|
||||
className={`${config.iconColor} flex-shrink-0 mt-0.5`}
|
||||
ariaLabel={`${type} icon`}
|
||||
/>
|
||||
|
||||
{/* 메시지 */}
|
||||
<P className={`flex-1 ${config.textColor} text-sm`}>
|
||||
{message}
|
||||
</P>
|
||||
|
||||
{/* 닫기 버튼 (dismissible이 true일 때만 표시) */}
|
||||
{dismissible && (
|
||||
<Button
|
||||
onClick={onDismiss}
|
||||
className={`${config.textColor} hover:opacity-70 flex-shrink-0 bg-transparent border-0 p-0 cursor-pointer`}
|
||||
aria-label="Close alert"
|
||||
>
|
||||
<Icon
|
||||
name={IconName.Times}
|
||||
className={config.iconColor}
|
||||
ariaLabel="Close"
|
||||
/>
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
import React from 'react';
|
||||
import { Dialog, DialogAction } from './Dialog';
|
||||
import { P } from '../basic/P';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export interface AlertDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
message: string | React.ReactNode;
|
||||
confirmText?: string;
|
||||
onConfirm?: () => void;
|
||||
confirmButtonVariant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
width?: string;
|
||||
closeOnOverlay?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* AlertDialog 집합 컴포넌트
|
||||
*
|
||||
* Dialog 기반 단일 확인 알림 다이얼로그 컴포넌트.
|
||||
* 사용자에게 정보를 전달하고 확인만 받습니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합:
|
||||
* - Dialog > P(message) + Button(확인)
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "AlertDialog",
|
||||
* "props": {
|
||||
* "isOpen": "{{dialogs.successAlert}}",
|
||||
* "title": "성공",
|
||||
* "message": "작업이 성공적으로 완료되었습니다.",
|
||||
* "confirmText": "$t:common.confirm",
|
||||
* "confirmButtonVariant": "primary"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const AlertDialog: React.FC<AlertDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
message,
|
||||
confirmText,
|
||||
onConfirm,
|
||||
confirmButtonVariant = 'primary',
|
||||
width = '500px',
|
||||
closeOnOverlay = true,
|
||||
}) => {
|
||||
// props로 전달된 값이 없으면 다국어 키 사용
|
||||
const resolvedConfirmText = confirmText ?? t('common.confirm');
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm?.();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const actions: DialogAction[] = [
|
||||
{
|
||||
label: resolvedConfirmText,
|
||||
onClick: handleConfirm,
|
||||
variant: confirmButtonVariant,
|
||||
},
|
||||
];
|
||||
|
||||
// message가 문자열인 경우 P 컴포넌트로 래핑
|
||||
const content = typeof message === 'string' ? (
|
||||
<P className="text-gray-700 dark:text-gray-300">{message}</P>
|
||||
) : (
|
||||
message
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title={title}
|
||||
content={content}
|
||||
actions={actions}
|
||||
width={width}
|
||||
closeOnOverlay={closeOnOverlay}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
export interface BadgeProps {
|
||||
color?: string;
|
||||
text?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
const colorStyles: Record<string, string> = {
|
||||
blue: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300',
|
||||
green: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300',
|
||||
red: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300',
|
||||
gray: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
|
||||
yellow: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300',
|
||||
purple: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300',
|
||||
orange: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300',
|
||||
teal: 'bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-300',
|
||||
cyan: 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-300',
|
||||
};
|
||||
|
||||
const sizeStyles: Record<string, string> = {
|
||||
sm: 'px-1.5 py-0.5 text-[10px]',
|
||||
md: 'px-2 py-0.5 text-xs',
|
||||
lg: 'px-2.5 py-1 text-sm',
|
||||
};
|
||||
|
||||
/**
|
||||
* Badge 집합 컴포넌트
|
||||
*
|
||||
* 색상 기반의 라벨 뱃지입니다. 상태, 타입 등의 분류를 시각적으로 표현합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Span
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Badge",
|
||||
* "props": {
|
||||
* "color": "blue",
|
||||
* "text": "활성"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Badge: React.FC<React.PropsWithChildren<BadgeProps>> = ({
|
||||
color = 'gray',
|
||||
text,
|
||||
size = 'md',
|
||||
className = '',
|
||||
style,
|
||||
children,
|
||||
}) => {
|
||||
const colorClass = colorStyles[color] || colorStyles.gray;
|
||||
const sizeClass = sizeStyles[size] || sizeStyles.md;
|
||||
|
||||
return (
|
||||
<Span
|
||||
className={`inline-flex items-center rounded-full font-medium ${sizeClass} ${colorClass} ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{text}
|
||||
{children}
|
||||
</Span>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,166 @@
|
||||
import React from 'react';
|
||||
import { Nav } from '../basic/Nav';
|
||||
import { Div } from '../basic/Div';
|
||||
import { A } from '../basic/A';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface BreadcrumbItem {
|
||||
label: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export interface BreadcrumbProps {
|
||||
items: BreadcrumbItem[];
|
||||
separator?: React.ReactNode;
|
||||
showHome?: boolean;
|
||||
homeHref?: string;
|
||||
maxItems?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Breadcrumb 집합 컴포넌트
|
||||
*
|
||||
* 현재 페이지의 경로를 계층적으로 표시하는 내비게이션 컴포넌트.
|
||||
* separator 커스터마이징, showHome 옵션, maxItems로 중간 생략 기능 제공.
|
||||
*
|
||||
* 기본 컴포넌트 조합:
|
||||
* - Nav > Div > A(링크) + Span(구분자)
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Breadcrumb",
|
||||
* "props": {
|
||||
* "items": [
|
||||
* {"label": "대시보드", "href": "/admin"},
|
||||
* {"label": "사용자 관리", "href": "/admin/users"},
|
||||
* {"label": "사용자 목록"}
|
||||
* ],
|
||||
* "showHome": true,
|
||||
* "maxItems": 4
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Breadcrumb: React.FC<BreadcrumbProps> = ({
|
||||
items,
|
||||
separator = <Icon name={IconName.ChevronRight} className="w-4 h-4 text-gray-400 dark:text-gray-500" />,
|
||||
showHome = false,
|
||||
homeHref = '/',
|
||||
maxItems,
|
||||
className = '',
|
||||
}) => {
|
||||
// Home 아이템 생성
|
||||
const homeItem: BreadcrumbItem = {
|
||||
label: 'Home',
|
||||
href: homeHref,
|
||||
};
|
||||
|
||||
// 전체 아이템 배열 생성
|
||||
let allItems = showHome ? [homeItem, ...items] : items;
|
||||
|
||||
// maxItems 적용 (중간 생략)
|
||||
let displayItems = allItems;
|
||||
let hasEllipsis = false;
|
||||
|
||||
if (maxItems && allItems.length > maxItems) {
|
||||
hasEllipsis = true;
|
||||
const firstItems = allItems.slice(0, 1);
|
||||
const lastItems = allItems.slice(-(maxItems - 2));
|
||||
displayItems = [...firstItems, ...lastItems];
|
||||
}
|
||||
|
||||
return (
|
||||
<Nav
|
||||
className={`flex items-center space-x-2 text-sm ${className}`}
|
||||
aria-label="Breadcrumb"
|
||||
>
|
||||
<Div className="flex items-center space-x-2">
|
||||
{displayItems.map((item, index) => {
|
||||
const isLast = index === displayItems.length - 1;
|
||||
const isFirst = index === 0;
|
||||
|
||||
return (
|
||||
<React.Fragment key={index}>
|
||||
{/* 중간 생략 표시 (첫 번째 아이템 다음) */}
|
||||
{hasEllipsis && isFirst && (
|
||||
<>
|
||||
<BreadcrumbLink item={item} isLast={false} />
|
||||
<Span className="text-gray-400 dark:text-gray-500" aria-hidden="true">
|
||||
{separator}
|
||||
</Span>
|
||||
<Span className="text-gray-500 dark:text-gray-400">...</Span>
|
||||
{displayItems.length > 1 && (
|
||||
<Span className="text-gray-400 dark:text-gray-500" aria-hidden="true">
|
||||
{separator}
|
||||
</Span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 일반 아이템 */}
|
||||
{(!hasEllipsis || !isFirst) && (
|
||||
<>
|
||||
<BreadcrumbLink item={item} isLast={isLast} />
|
||||
{!isLast && (
|
||||
<Span className="text-gray-400 dark:text-gray-500" aria-hidden="true">
|
||||
{separator}
|
||||
</Span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
</Nav>
|
||||
);
|
||||
};
|
||||
|
||||
interface BreadcrumbLinkProps {
|
||||
item: BreadcrumbItem;
|
||||
isLast: boolean;
|
||||
}
|
||||
|
||||
const BreadcrumbLink: React.FC<BreadcrumbLinkProps> = ({ item, isLast }) => {
|
||||
if (isLast || (!item.href && !item.onClick)) {
|
||||
// 마지막 아이템이거나 링크가 없는 경우
|
||||
return (
|
||||
<Span
|
||||
className="font-medium text-gray-900 dark:text-white"
|
||||
aria-current={isLast ? 'page' : undefined}
|
||||
>
|
||||
{item.label}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
if (item.onClick) {
|
||||
// onClick 핸들러가 있는 경우
|
||||
return (
|
||||
<A
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
item.onClick?.();
|
||||
}}
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
{item.label}
|
||||
</A>
|
||||
);
|
||||
}
|
||||
|
||||
// 일반 링크
|
||||
return (
|
||||
<A
|
||||
href={item.href}
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
{item.label}
|
||||
</A>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H2 } from '../basic/H2';
|
||||
import { P } from '../basic/P';
|
||||
import { Img } from '../basic/Img';
|
||||
|
||||
export interface CardProps {
|
||||
title?: string;
|
||||
content?: string;
|
||||
imageUrl?: string;
|
||||
imageAlt?: string;
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Card 집합 컴포넌트
|
||||
*
|
||||
* 기본 컴포넌트를 조합하여 카드 UI를 구성합니다.
|
||||
* 레이아웃 JSON에서 title, content, imageUrl 등의 props만 전달하면
|
||||
* 내부적으로 Div, H2, P, Img 컴포넌트를 조합하여 완성된 카드를 렌더링합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Card",
|
||||
* "props": {
|
||||
* "title": "사용자 정보",
|
||||
* "content": "홍길동 (hong@example.com)",
|
||||
* "imageUrl": "/avatar.png"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Card: React.FC<CardProps> = ({
|
||||
title,
|
||||
content,
|
||||
imageUrl,
|
||||
imageAlt = '',
|
||||
className = '',
|
||||
onClick,
|
||||
style,
|
||||
}) => {
|
||||
return (
|
||||
<Div
|
||||
className={`rounded-lg bg-white dark:bg-gray-800 shadow-md hover:shadow-lg transition-shadow border border-gray-200 dark:border-gray-700 overflow-hidden ${className}`}
|
||||
onClick={onClick}
|
||||
style={style}
|
||||
>
|
||||
{imageUrl && (
|
||||
<Div className="w-full">
|
||||
<Img
|
||||
src={imageUrl}
|
||||
alt={imageAlt}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
<Div className="p-4">
|
||||
{title && (
|
||||
<H2 className="text-xl font-semibold text-gray-800 dark:text-white mb-2">
|
||||
{title}
|
||||
</H2>
|
||||
)}
|
||||
|
||||
{content && (
|
||||
<P className="text-gray-600 dark:text-gray-300 text-sm whitespace-pre-line">
|
||||
{content}
|
||||
</P>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,602 @@
|
||||
import React, { useMemo, useState, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { P } from '../basic/P';
|
||||
import { ActionMenuItem } from './ActionMenu';
|
||||
import { Pagination } from './Pagination';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:CardGrid')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:CardGrid]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:CardGrid]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:CardGrid]', ...args),
|
||||
};
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
/**
|
||||
* CardGrid 셀 자식 요소 타입
|
||||
*/
|
||||
export interface CardGridCellChild {
|
||||
id?: string;
|
||||
type: 'basic' | 'composite';
|
||||
name: string;
|
||||
props?: Record<string, any>;
|
||||
text?: string;
|
||||
children?: CardGridCellChild[];
|
||||
condition?: string;
|
||||
if?: string;
|
||||
iteration?: {
|
||||
source: string;
|
||||
item_var?: string;
|
||||
index_var?: string;
|
||||
};
|
||||
actions?: any[]; // JSON에서 정의된 actions 배열 (ActionMenu용)
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드 컬럼 정의 (DataGrid의 컬럼 패턴과 동일)
|
||||
*/
|
||||
export interface CardGridColumn {
|
||||
id: string;
|
||||
cellChildren?: CardGridCellChild[];
|
||||
}
|
||||
|
||||
/**
|
||||
* CardGrid Props 인터페이스
|
||||
*/
|
||||
export interface CardGridProps {
|
||||
// 필수 props
|
||||
data?: any[];
|
||||
|
||||
// 카드 컬럼 정의 (DataGrid의 columns 패턴)
|
||||
cardColumns?: CardGridColumn[];
|
||||
|
||||
// 그리드 레이아웃
|
||||
gridColumns?: number;
|
||||
gap?: number;
|
||||
|
||||
// 반응형 설정
|
||||
responsiveColumns?: {
|
||||
sm?: number;
|
||||
md?: number;
|
||||
lg?: number;
|
||||
xl?: number;
|
||||
};
|
||||
|
||||
// 카드 스타일
|
||||
cardClassName?: string;
|
||||
|
||||
// 행 ID 필드
|
||||
idField?: string;
|
||||
|
||||
// 페이지네이션
|
||||
pagination?: boolean;
|
||||
pageSize?: number;
|
||||
serverSidePagination?: boolean;
|
||||
serverCurrentPage?: number;
|
||||
serverTotalPages?: number;
|
||||
alwaysShowPagination?: boolean;
|
||||
onPageChange?: (page: number) => void;
|
||||
|
||||
// 행 액션 메뉴 (DataGrid 패턴)
|
||||
rowActions?: ActionMenuItem[];
|
||||
onRowAction?: (actionId: string | number, row: any) => void;
|
||||
|
||||
// 기타
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
|
||||
// 다국어 텍스트
|
||||
emptyMessage?: string;
|
||||
|
||||
// 페이지네이션 정보
|
||||
paginationInfoText?: string;
|
||||
|
||||
// 페이지네이션 텍스트 (다국어 지원)
|
||||
prevText?: string;
|
||||
nextText?: string;
|
||||
|
||||
// 스켈레톤 관련 props
|
||||
showSkeleton?: boolean; // 스켈레톤 표시 여부 (기본값: true)
|
||||
skeletonCount?: number; // 스켈레톤 개수 (기본값: gridColumns)
|
||||
skeletonCellChildren?: CardGridCellChild[]; // 커스텀 스켈레톤 정의
|
||||
}
|
||||
|
||||
/**
|
||||
* G7Core에서 전체 컴포넌트 맵을 가져옵니다.
|
||||
* 템플릿에 등록된 모든 컴포넌트를 자동으로 사용할 수 있습니다.
|
||||
*/
|
||||
const getComponentMap = (): Record<string, React.ComponentType<any>> => {
|
||||
const G7Core = (window as any).G7Core;
|
||||
return G7Core?.getComponentMap?.() || {};
|
||||
};
|
||||
|
||||
/**
|
||||
* 조건 문자열을 평가합니다.
|
||||
* 복잡한 JavaScript 표현식도 지원합니다 (&&, ||, length 등)
|
||||
*/
|
||||
const evaluateCondition = (condition: string, row: any): boolean => {
|
||||
if (!condition) return true;
|
||||
|
||||
const match = condition.match(/^\{\{(.+)\}\}$/);
|
||||
if (!match) return true;
|
||||
|
||||
const expr = match[1].trim();
|
||||
|
||||
// 디버깅: row 데이터와 표현식 확인
|
||||
logger.log('evaluateCondition:', { condition, expr, row, rowStatus: row?.status });
|
||||
|
||||
// 복잡한 표현식 (&&, ||, length, > 등)이 포함된 경우 eval 사용
|
||||
if (/[&|<>=!]/.test(expr) || expr.includes('.length')) {
|
||||
try {
|
||||
// row 컨텍스트에서 표현식 평가
|
||||
// eslint-disable-next-line no-new-func
|
||||
const evaluator = new Function('row', `return ${expr}`);
|
||||
const result = !!evaluator(row);
|
||||
logger.log('evaluateCondition result:', result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
logger.warn('evaluateCondition: 표현식 평가 실패:', expr, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// !row.field 패턴
|
||||
if (expr.startsWith('!row.')) {
|
||||
const field = expr.slice(5);
|
||||
return !row[field];
|
||||
}
|
||||
|
||||
// row.field 패턴
|
||||
if (expr.startsWith('row.')) {
|
||||
const field = expr.slice(4);
|
||||
return !!row[field];
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* ActionMenu의 actions를 처리하여 onClick 함수를 생성합니다.
|
||||
* rowActions prop이 있으면 우선 사용합니다 (DataGrid 패턴).
|
||||
*/
|
||||
const processActionMenuActions = (
|
||||
child: CardGridCellChild,
|
||||
row: any,
|
||||
context: Record<string, any>,
|
||||
rowActions?: ActionMenuItem[],
|
||||
onRowActionHandler?: (actionId: string | number, row: any) => void
|
||||
): CardGridCellChild => {
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
// ActionMenu인 경우
|
||||
if (child.name === 'ActionMenu') {
|
||||
// 1. rowActions prop이 있으면 우선 사용 (DataGrid 패턴)
|
||||
if (rowActions && rowActions.length > 0 && onRowActionHandler) {
|
||||
return {
|
||||
...child,
|
||||
props: {
|
||||
...child.props,
|
||||
items: rowActions.map((action) => ({
|
||||
...action,
|
||||
onClick: () => onRowActionHandler(action.id, row),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 2. actions 배열이 있는 경우 (기존 패턴)
|
||||
if (child.actions && Array.isArray(child.actions)) {
|
||||
const items = child.props?.items || [];
|
||||
const actionsMap = new Map(child.actions.map((action: any) => [action.id, action]));
|
||||
|
||||
// items의 onClick을 실제 함수로 변환
|
||||
const processedItems = items.map((item: any) => {
|
||||
// onClick이 문자열(액션 ID)인 경우
|
||||
if (typeof item.onClick === 'string') {
|
||||
const actionId = item.onClick;
|
||||
const actionDef = actionsMap.get(actionId);
|
||||
|
||||
if (actionDef && G7Core?.ActionDispatcher) {
|
||||
return {
|
||||
...item,
|
||||
onClick: () => {
|
||||
// 액션 컨텍스트 생성 (row 데이터 포함)
|
||||
const actionContext = { ...context };
|
||||
G7Core.ActionDispatcher.dispatch(actionDef, actionContext);
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
return item;
|
||||
});
|
||||
|
||||
// 처리된 items로 child 복사본 반환
|
||||
return {
|
||||
...child,
|
||||
props: {
|
||||
...child.props,
|
||||
items: processedItems,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// children이 있으면 재귀적으로 처리
|
||||
if (child.children && Array.isArray(child.children)) {
|
||||
return {
|
||||
...child,
|
||||
children: child.children.map((c) => processActionMenuActions(c, row, context, rowActions, onRowActionHandler)),
|
||||
};
|
||||
}
|
||||
|
||||
return child;
|
||||
};
|
||||
|
||||
/**
|
||||
* cellChildren 배열을 React 요소로 렌더링합니다.
|
||||
* DataGrid의 renderCellChildren 패턴을 따릅니다.
|
||||
*/
|
||||
const renderCellChildren = (
|
||||
cellChildren: CardGridCellChild[],
|
||||
row: any,
|
||||
index: number,
|
||||
keyPrefix: string = '',
|
||||
rowActions?: ActionMenuItem[],
|
||||
onRowActionHandler?: (actionId: string | number, row: any) => void
|
||||
): React.ReactNode => {
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
if (G7Core?.renderItemChildren) {
|
||||
// 조건부 렌더링 필터링 (condition 또는 if 속성 지원)
|
||||
// 참고: renderItemChildren도 자체적으로 if 조건을 평가하지만,
|
||||
// 여기서 미리 필터링하면 불필요한 렌더링을 줄일 수 있음
|
||||
const filteredChildren = cellChildren.filter((child) => {
|
||||
const conditionExpr = child.condition || child.if;
|
||||
if (!conditionExpr) return true;
|
||||
const result = evaluateCondition(conditionExpr, row);
|
||||
return result;
|
||||
});
|
||||
|
||||
// 컨텍스트 생성
|
||||
const context = {
|
||||
row,
|
||||
$value: row,
|
||||
index,
|
||||
};
|
||||
|
||||
// ActionMenu actions 전처리 (재귀적으로)
|
||||
const processedChildren = filteredChildren.map((child) =>
|
||||
processActionMenuActions(child, row, context, rowActions, onRowActionHandler)
|
||||
);
|
||||
|
||||
try {
|
||||
// G7Core에서 전체 컴포넌트 맵 가져오기
|
||||
const componentMap = getComponentMap();
|
||||
|
||||
// G7Core 템플릿 엔진으로 렌더링
|
||||
return G7Core.renderItemChildren(
|
||||
processedChildren,
|
||||
context,
|
||||
componentMap,
|
||||
keyPrefix
|
||||
);
|
||||
} catch (error) {
|
||||
return (
|
||||
<Div className="text-red-600 dark:text-red-400 p-4">
|
||||
<P>컴포넌트 로드 실패</P>
|
||||
<P className="text-sm">[CardGrid] 데이터를 표시할 수 없습니다.</P>
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 개별 CardGridCellChild에 대한 스켈레톤을 생성합니다.
|
||||
* 모든 컴포넌트에 대해 동일한 기본 스켈레톤을 생성하여 확장성을 보장합니다.
|
||||
*
|
||||
* @param child 스켈레톤을 생성할 child 요소
|
||||
* @param key React key
|
||||
* @returns 생성된 스켈레톤 React 노드
|
||||
*/
|
||||
const generateSkeletonForChild = (
|
||||
child: CardGridCellChild,
|
||||
key: string
|
||||
): React.ReactNode => {
|
||||
// Div만 특수 처리 (레이아웃 구조 유지)
|
||||
if (child.name === 'Div' && child.children && child.children.length > 0) {
|
||||
const childSkeletons = child.children
|
||||
.map((c, idx) => generateSkeletonForChild(c, `${key}-child-${idx}`))
|
||||
.filter(Boolean);
|
||||
|
||||
return (
|
||||
<Div key={key} className={child.props?.className || ''}>
|
||||
{childSkeletons}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// 모든 컴포넌트는 동일한 기본 스켈레톤 (확장성 보장)
|
||||
return <Div key={key} className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-full animate-pulse" />;
|
||||
};
|
||||
|
||||
/**
|
||||
* cellChildren 배열에서 스켈레톤 UI를 자동 생성합니다.
|
||||
*
|
||||
* @param cellChildren 카드 컬럼의 cellChildren 배열
|
||||
* @param keyPrefix 고유 키 생성을 위한 접두사
|
||||
* @returns 생성된 스켈레톤 React 노드 (cellChildren이 없으면 null)
|
||||
*/
|
||||
const generateSkeletonFromCellChildren = (
|
||||
cellChildren: CardGridCellChild[],
|
||||
keyPrefix: string = 'skeleton'
|
||||
): React.ReactNode => {
|
||||
if (!cellChildren || cellChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cellChildren
|
||||
.map((child, index) => {
|
||||
const key = `${keyPrefix}-${child.id || child.name}-${index}`;
|
||||
|
||||
// 조건부 렌더링 요소는 제외
|
||||
if (child.condition || child.if) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// iteration이 있으면 1개만 표시
|
||||
if (child.iteration) {
|
||||
return generateSkeletonForChild(child, key);
|
||||
}
|
||||
|
||||
// 일반 요소 처리
|
||||
return generateSkeletonForChild(child, key);
|
||||
})
|
||||
.filter(Boolean);
|
||||
};
|
||||
|
||||
/**
|
||||
* CardGrid 집합 컴포넌트
|
||||
*
|
||||
* 카드 레이아웃으로 데이터를 표시하는 그리드 컴포넌트입니다.
|
||||
* DataGrid의 cellChildren 패턴을 사용하여 카드 내용을 JSON으로 정의할 수 있습니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "CardGrid",
|
||||
* "props": {
|
||||
* "data": "{{boards.data.data}}",
|
||||
* "columns": 3,
|
||||
* "gap": 4,
|
||||
* "pagination": true,
|
||||
* "pageSize": 12,
|
||||
* "cellChildren": [
|
||||
* {
|
||||
* "type": "basic",
|
||||
* "name": "Div",
|
||||
* "props": {
|
||||
* "className": "bg-white dark:bg-gray-800 rounded-lg p-6"
|
||||
* },
|
||||
* "children": [
|
||||
* {
|
||||
* "type": "basic",
|
||||
* "name": "H3",
|
||||
* "text": "{{row.name}}"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const CardGrid: React.FC<CardGridProps> = ({
|
||||
data,
|
||||
cardColumns = [],
|
||||
gridColumns = 3,
|
||||
gap = 4,
|
||||
responsiveColumns,
|
||||
cardClassName = '',
|
||||
idField = 'id',
|
||||
pagination = true,
|
||||
pageSize = 12,
|
||||
serverSidePagination = false,
|
||||
serverCurrentPage,
|
||||
serverTotalPages,
|
||||
alwaysShowPagination = false,
|
||||
onPageChange,
|
||||
paginationInfoText,
|
||||
rowActions,
|
||||
onRowAction,
|
||||
className = '',
|
||||
style,
|
||||
emptyMessage,
|
||||
prevText,
|
||||
nextText,
|
||||
showSkeleton = true,
|
||||
skeletonCount,
|
||||
skeletonCellChildren,
|
||||
}) => {
|
||||
// props로 전달된 값이 없으면 다국어 키 사용
|
||||
const resolvedEmptyMessage = emptyMessage ?? t('common.no_data');
|
||||
|
||||
// cardColumns의 첫 번째 항목에서 cellChildren 추출
|
||||
const cellChildren = cardColumns[0]?.cellChildren || [];
|
||||
// 클라이언트 사이드 페이지네이션 상태
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
// 반응형 상태 구독 - cellChildren 내 responsive 속성 지원을 위해 필요
|
||||
// 화면 크기 변경 시 CardGrid가 리렌더링되어 renderItemChildren이 새로운 너비로 재실행됨
|
||||
// 훅 호출 자체가 리렌더링을 트리거하므로 반환값은 사용하지 않음 (void 처리)
|
||||
const G7Core = (window as any).G7Core;
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
G7Core?.useResponsive?.();
|
||||
|
||||
// 서버/클라이언트 페이지 정보
|
||||
const effectiveCurrentPage = serverSidePagination ? (serverCurrentPage ?? 1) : currentPage;
|
||||
const effectiveTotalPages = serverSidePagination
|
||||
? (serverTotalPages ?? 1)
|
||||
: Math.ceil((data?.length ?? 0) / pageSize);
|
||||
|
||||
// 페이지 변경 핸들러
|
||||
const handlePageChange = (page: number) => {
|
||||
if (serverSidePagination) {
|
||||
onPageChange?.(page);
|
||||
} else {
|
||||
setCurrentPage(page);
|
||||
}
|
||||
};
|
||||
|
||||
// 행 액션 처리 (DataGrid 패턴 + 템플릿 엔진 이벤트 연동)
|
||||
const handleRowAction = useCallback(
|
||||
(actionId: string | number, row: any) => {
|
||||
// prop으로 전달된 onRowAction 호출
|
||||
// DynamicRenderer의 actionDispatcher.bindActionsToProps가
|
||||
// 레이아웃 JSON의 actions 배열과 자동 연결함
|
||||
// onRowAction 호출 시 $args[0] = actionId, $args[1] = row로 전달됨
|
||||
onRowAction?.(actionId, row);
|
||||
},
|
||||
[onRowAction]
|
||||
);
|
||||
|
||||
// 페이지네이션 적용된 데이터
|
||||
const paginatedData = useMemo(() => {
|
||||
if (!data) return [];
|
||||
if (!pagination) return data;
|
||||
if (serverSidePagination) return data;
|
||||
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const endIndex = startIndex + pageSize;
|
||||
return data.slice(startIndex, endIndex);
|
||||
}, [data, pagination, serverSidePagination, currentPage, pageSize]);
|
||||
|
||||
// 반응형 그리드 클래스 생성
|
||||
const gridClasses = useMemo(() => {
|
||||
const classes = [];
|
||||
|
||||
// 기본 (모바일)
|
||||
const smCols = responsiveColumns?.sm ?? 1;
|
||||
classes.push(`grid-cols-${smCols}`);
|
||||
|
||||
// sm (640px+)
|
||||
if (responsiveColumns?.sm) {
|
||||
classes.push(`sm:grid-cols-${responsiveColumns.sm}`);
|
||||
}
|
||||
|
||||
// md (768px+)
|
||||
const mdCols = responsiveColumns?.md ?? Math.min(gridColumns, 2);
|
||||
classes.push(`md:grid-cols-${mdCols}`);
|
||||
|
||||
// lg (1024px+)
|
||||
const lgCols = responsiveColumns?.lg ?? gridColumns;
|
||||
classes.push(`lg:grid-cols-${lgCols}`);
|
||||
|
||||
// xl (1280px+)
|
||||
if (responsiveColumns?.xl) {
|
||||
classes.push(`xl:grid-cols-${responsiveColumns.xl}`);
|
||||
}
|
||||
|
||||
return classes.join(' ');
|
||||
}, [gridColumns, responsiveColumns]);
|
||||
|
||||
// 스켈레톤 UI 생성 (useMemo로 최적화)
|
||||
const skeletonUI = useMemo(() => {
|
||||
if (!showSkeleton) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 1. skeletonCellChildren이 있으면 우선 사용
|
||||
if (skeletonCellChildren && skeletonCellChildren.length > 0) {
|
||||
return generateSkeletonFromCellChildren(skeletonCellChildren, 'custom-skeleton');
|
||||
}
|
||||
|
||||
// 2. cellChildren 기반 자동 생성
|
||||
if (cellChildren && cellChildren.length > 0) {
|
||||
return generateSkeletonFromCellChildren(cellChildren, 'auto-skeleton');
|
||||
}
|
||||
|
||||
// 3. cellChildren도 없으면 null (빈 카드)
|
||||
return null;
|
||||
}, [showSkeleton, skeletonCellChildren, cellChildren]);
|
||||
|
||||
// 로딩 상태 (data가 undefined/null)
|
||||
if (!data) {
|
||||
// showSkeleton이 false면 빈 화면
|
||||
if (!showSkeleton) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const effectiveSkeletonCount = skeletonCount ?? gridColumns;
|
||||
|
||||
return (
|
||||
<Div className={`grid ${gridClasses} gap-${gap} ${className}`} style={style}>
|
||||
{Array.from({ length: effectiveSkeletonCount }).map((_, index) => (
|
||||
<Div
|
||||
key={`skeleton-${index}`}
|
||||
className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6 space-y-4"
|
||||
>
|
||||
{skeletonUI}
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// 빈 데이터 상태
|
||||
if (paginatedData.length === 0) {
|
||||
return (
|
||||
<Div className={className} style={style}>
|
||||
<Div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-12">
|
||||
<P className="text-center text-gray-600 dark:text-gray-400">
|
||||
{resolvedEmptyMessage}
|
||||
</P>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// 페이지네이션 표시 여부
|
||||
const showPagination =
|
||||
pagination &&
|
||||
(alwaysShowPagination || effectiveTotalPages > 1);
|
||||
|
||||
return (
|
||||
<Div className={className} style={style}>
|
||||
{/* 카드 그리드 */}
|
||||
<Div className={`grid ${gridClasses} gap-${gap}`}>
|
||||
{paginatedData.map((row, index) => (
|
||||
<Div key={row[idField] || index} className={cardClassName}>
|
||||
{renderCellChildren(cellChildren, row, index, `card-${index}`, rowActions, handleRowAction)}
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
|
||||
{/* 페이지네이션 */}
|
||||
{showPagination && (
|
||||
<Div className="mt-6 space-y-4 flex flex-col items-center">
|
||||
<Pagination
|
||||
currentPage={effectiveCurrentPage}
|
||||
totalPages={effectiveTotalPages}
|
||||
onPageChange={handlePageChange}
|
||||
showFirstLast={false}
|
||||
maxVisiblePages={5}
|
||||
prevText={prevText}
|
||||
nextText={nextText}
|
||||
/>
|
||||
{/* 페이지네이션 정보 */}
|
||||
{paginationInfoText && (
|
||||
<Div className="text-sm text-gray-600 dark:text-gray-400 text-center">
|
||||
{paginationInfoText}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,275 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Checkbox } from '../basic/Checkbox';
|
||||
|
||||
/**
|
||||
* 카테고리 노드 인터페이스 (CategoryResource API 응답 기반)
|
||||
*/
|
||||
export interface CategoryNode {
|
||||
id: number;
|
||||
name: string;
|
||||
localized_name?: string;
|
||||
path?: string;
|
||||
products_count?: number;
|
||||
children_count?: number;
|
||||
children?: CategoryNode[];
|
||||
}
|
||||
|
||||
export interface CategoryTreeProps {
|
||||
/** 카테고리 트리 데이터 (CategoryResource API 응답) */
|
||||
data?: CategoryNode[];
|
||||
/** 펼쳐진 노드 ID 배열 */
|
||||
expandedIds?: number[];
|
||||
/** 선택된 노드 ID 배열 */
|
||||
selectedIds?: number[];
|
||||
/** 검색 키워드 (하이라이트용) */
|
||||
searchKeyword?: string;
|
||||
/** 상품 수 표시 여부 */
|
||||
showProductCount?: boolean;
|
||||
/** 체크박스 선택 기능 활성화 */
|
||||
selectable?: boolean;
|
||||
/** 추가 클래스명 */
|
||||
className?: string;
|
||||
/** 펼치기/접기 콜백: (expandedIds: number[]) => void */
|
||||
onToggle?: (expandedIds: number[]) => void;
|
||||
/** 선택 변경 콜백: (selectedIds: number[]) => void */
|
||||
onSelectionChange?: (selectedIds: number[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트에서 키워드를 하이라이트하여 렌더링합니다.
|
||||
*/
|
||||
function HighlightText({ text, keyword }: { text: string; keyword: string }) {
|
||||
if (!keyword || !text) {
|
||||
return <>{text}</>;
|
||||
}
|
||||
|
||||
const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const parts = text.split(new RegExp(`(${escaped})`, 'gi'));
|
||||
|
||||
return (
|
||||
<>
|
||||
{parts.map((part, i) =>
|
||||
part.toLowerCase() === keyword.toLowerCase() ? (
|
||||
<Span key={i} className="bg-yellow-200 dark:bg-yellow-700 rounded px-0.5">
|
||||
{part}
|
||||
</Span>
|
||||
) : (
|
||||
part
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* CategoryTree 집합 컴포넌트
|
||||
*
|
||||
* 계층형 카테고리 트리를 렌더링하고 체크박스로 카테고리를 선택할 수 있습니다.
|
||||
* expandedIds와 selectedIds를 외부에서 제어하는 Controlled 컴포넌트입니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "CategoryTree",
|
||||
* "props": {
|
||||
* "data": "{{categories?.data?.data ?? []}}",
|
||||
* "expandedIds": "{{_local.categoryExpandedIds ?? []}}",
|
||||
* "selectedIds": "{{_local.categorySearchSelected ?? []}}",
|
||||
* "searchKeyword": "{{_local.categorySearchKeyword ?? ''}}",
|
||||
* "showProductCount": true,
|
||||
* "selectable": true
|
||||
* },
|
||||
* "actions": [
|
||||
* {
|
||||
* "event": "onToggle",
|
||||
* "handler": "setState",
|
||||
* "params": { "target": "_local", "categoryExpandedIds": "{{$args[0]}}" }
|
||||
* },
|
||||
* {
|
||||
* "event": "onSelectionChange",
|
||||
* "handler": "setState",
|
||||
* "params": { "target": "_local", "categorySearchSelected": "{{$args[0]}}" }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const CategoryTree: React.FC<CategoryTreeProps> = ({
|
||||
data = [],
|
||||
expandedIds = [],
|
||||
selectedIds = [],
|
||||
searchKeyword = '',
|
||||
showProductCount = false,
|
||||
selectable = false,
|
||||
className = '',
|
||||
onToggle,
|
||||
onSelectionChange,
|
||||
}) => {
|
||||
/**
|
||||
* 노드 펼치기/접기 토글
|
||||
*/
|
||||
const handleToggle = useCallback(
|
||||
(nodeId: number) => {
|
||||
if (!onToggle) return;
|
||||
const newExpandedIds = expandedIds.includes(nodeId)
|
||||
? expandedIds.filter((id) => id !== nodeId)
|
||||
: [...expandedIds, nodeId];
|
||||
onToggle(newExpandedIds);
|
||||
},
|
||||
[expandedIds, onToggle]
|
||||
);
|
||||
|
||||
/**
|
||||
* 노드 선택/해제 토글
|
||||
*/
|
||||
const handleSelect = useCallback(
|
||||
(nodeId: number, checked: boolean) => {
|
||||
if (!onSelectionChange) return;
|
||||
const newSelectedIds = checked
|
||||
? [...selectedIds, nodeId]
|
||||
: selectedIds.filter((id) => id !== nodeId);
|
||||
onSelectionChange(newSelectedIds);
|
||||
},
|
||||
[selectedIds, onSelectionChange]
|
||||
);
|
||||
|
||||
/**
|
||||
* 검색 키워드와 매칭되는 노드 ID 집합 (자동 필터링용)
|
||||
*/
|
||||
const matchedNodeIds = useMemo(() => {
|
||||
if (!searchKeyword) return null;
|
||||
const ids = new Set<number>();
|
||||
|
||||
const findMatches = (nodes: CategoryNode[]) => {
|
||||
for (const node of nodes) {
|
||||
const displayName = node.localized_name || node.name;
|
||||
if (displayName.toLowerCase().includes(searchKeyword.toLowerCase())) {
|
||||
ids.add(node.id);
|
||||
}
|
||||
if (node.children) {
|
||||
findMatches(node.children);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
findMatches(data);
|
||||
return ids;
|
||||
}, [data, searchKeyword]);
|
||||
|
||||
/**
|
||||
* 노드 또는 하위 노드 중 검색어에 매칭되는 것이 있는지 확인
|
||||
*/
|
||||
const hasMatchInSubtree = useCallback(
|
||||
(node: CategoryNode): boolean => {
|
||||
if (!matchedNodeIds) return true;
|
||||
if (matchedNodeIds.has(node.id)) return true;
|
||||
return (node.children ?? []).some((child) => hasMatchInSubtree(child));
|
||||
},
|
||||
[matchedNodeIds]
|
||||
);
|
||||
|
||||
/**
|
||||
* 카테고리 노드 렌더링 (재귀)
|
||||
*/
|
||||
const renderNode = (node: CategoryNode, depth: number = 0) => {
|
||||
const hasChildren = (node.children ?? []).length > 0;
|
||||
const isExpanded = expandedIds.includes(node.id);
|
||||
const isSelected = selectedIds.includes(node.id);
|
||||
const displayName = node.localized_name || node.name;
|
||||
|
||||
// 검색 키워드가 있는 경우 매칭되지 않는 서브트리 숨김
|
||||
if (searchKeyword && !hasMatchInSubtree(node)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Div key={node.id} data-testid={`category-node-${node.id}`}>
|
||||
{/* 노드 행 */}
|
||||
<Div
|
||||
className={`flex items-center gap-2 py-1.5 px-2 rounded cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${
|
||||
depth > 0 ? 'ml-' + Math.min(depth * 5, 20) : ''
|
||||
}`}
|
||||
style={depth > 0 ? { marginLeft: `${depth * 20}px` } : undefined}
|
||||
>
|
||||
{/* 펼치기/접기 토글 */}
|
||||
{hasChildren ? (
|
||||
<Div
|
||||
className="flex-shrink-0 w-5 h-5 flex items-center justify-center text-gray-400 dark:text-gray-500"
|
||||
onClick={() => handleToggle(node.id)}
|
||||
data-testid={`toggle-${node.id}`}
|
||||
>
|
||||
<Icon
|
||||
name={isExpanded ? IconName.CaretDown : IconName.CaretRight}
|
||||
className="text-xs"
|
||||
/>
|
||||
</Div>
|
||||
) : (
|
||||
<Div className="flex-shrink-0 w-5 h-5" />
|
||||
)}
|
||||
|
||||
{/* 체크박스 */}
|
||||
{selectable && (
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
e.stopPropagation();
|
||||
handleSelect(node.id, e.target.checked);
|
||||
}}
|
||||
className="flex-shrink-0"
|
||||
data-testid={`checkbox-${node.id}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 폴더 아이콘 */}
|
||||
<Icon
|
||||
name={IconName.Folder}
|
||||
className={`flex-shrink-0 text-sm ${
|
||||
hasChildren
|
||||
? 'text-yellow-500 dark:text-yellow-400'
|
||||
: 'text-gray-400 dark:text-gray-500'
|
||||
}`}
|
||||
/>
|
||||
|
||||
{/* 카테고리 이름 */}
|
||||
<Span
|
||||
className="text-sm text-gray-700 dark:text-gray-300 select-none"
|
||||
onClick={() => hasChildren && handleToggle(node.id)}
|
||||
>
|
||||
<HighlightText text={displayName} keyword={searchKeyword} />
|
||||
</Span>
|
||||
|
||||
{/* 상품 수 Badge */}
|
||||
{showProductCount && node.products_count !== undefined && (
|
||||
<Span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400 ml-1">
|
||||
{node.products_count}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 하위 노드 */}
|
||||
{hasChildren && isExpanded && (
|
||||
<Div data-testid={`children-${node.id}`}>
|
||||
{(node.children ?? []).map((child) => renderNode(child, depth + 1))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
if (data.length === 0) {
|
||||
return (
|
||||
<Div className={`text-sm text-gray-400 dark:text-gray-500 py-4 text-center ${className}`}>
|
||||
데이터가 없습니다.
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Div className={`border border-gray-200 dark:border-gray-700 rounded-lg p-2 max-h-80 overflow-y-auto ${className}`}>
|
||||
{data.map((node) => renderNode(node, 0))}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Label } from '../basic/Label';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
/**
|
||||
* hex 색상 문자열을 RGB 객체로 변환
|
||||
*
|
||||
* @param hex hex 색상 문자열 (예: '#FF5733' 또는 'FF5733')
|
||||
* @returns RGB 객체 또는 변환 실패 시 null
|
||||
*/
|
||||
function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
|
||||
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
|
||||
return result ? {
|
||||
r: parseInt(result[1], 16),
|
||||
g: parseInt(result[2], 16),
|
||||
b: parseInt(result[3], 16),
|
||||
} : null;
|
||||
}
|
||||
|
||||
export interface ChipCheckboxProps {
|
||||
value: string;
|
||||
checked?: boolean;
|
||||
icon?: IconName | string;
|
||||
label: string;
|
||||
variant?: 'green' | 'orange' | 'yellow' | 'gray' | 'blue';
|
||||
customColor?: string;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* ChipCheckbox 집합 컴포넌트
|
||||
*
|
||||
* 체크박스 + 아이콘 + 라벨을 조합한 칩 형태의 체크박스 컴포넌트입니다.
|
||||
* 필터 UI에서 주로 사용되며, 선택 여부에 따라 스타일이 변경됩니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Div + Label + Input(checkbox) + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "ChipCheckbox",
|
||||
* "props": {
|
||||
* "value": "pending_order",
|
||||
* "checked": "{{(_local.filter.orderStatus || []).includes('pending_order')}}",
|
||||
* "icon": "clock",
|
||||
* "label": "$t:sirsoft-ecommerce.admin.order.status.waiting",
|
||||
* "variant": "gray"
|
||||
* },
|
||||
* "actions": [
|
||||
* {
|
||||
* "type": "change",
|
||||
* "handler": "sirsoft-ecommerce.toggleArrayValue",
|
||||
* "params": {
|
||||
* "target": "_local",
|
||||
* "path": "filter.orderStatus",
|
||||
* "value": "pending_order"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // customColor 사용 예시 (임의의 hex 색상)
|
||||
* {
|
||||
* "name": "ChipCheckbox",
|
||||
* "props": {
|
||||
* "value": "{{String(label.id)}}",
|
||||
* "checked": "{{(assignments ?? []).some(a => a.label_id === label.id)}}",
|
||||
* "label": "{{$localized(label.name)}}",
|
||||
* "customColor": "{{label.color ?? '#3B82F6'}}"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @remarks
|
||||
* - variant: green (연두색, 긍정 상태), orange (주황색, 진행 중), yellow (노란색, 회수), gray (회색, 대기/보류), blue (기본값)
|
||||
* - customColor: 임의의 hex 색상 코드 지정 시 variant 무시, 다크모드/호버 자동 처리
|
||||
*/
|
||||
export const ChipCheckbox: React.FC<ChipCheckboxProps> = ({
|
||||
value,
|
||||
checked = false,
|
||||
icon,
|
||||
label,
|
||||
variant = 'blue',
|
||||
customColor,
|
||||
className = '',
|
||||
style,
|
||||
onChange,
|
||||
}) => {
|
||||
const [isHovered, setIsHovered] = React.useState(false);
|
||||
|
||||
const baseStyles = 'inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium border cursor-pointer transition-all';
|
||||
|
||||
// customColor가 있으면 variant 무시, 직접 스타일 계산
|
||||
if (customColor) {
|
||||
const rgb = hexToRgb(customColor);
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
|
||||
let computedStyle: React.CSSProperties;
|
||||
if (checked) {
|
||||
computedStyle = {
|
||||
backgroundColor: customColor,
|
||||
color: '#ffffff',
|
||||
borderColor: customColor,
|
||||
opacity: isHovered ? 0.85 : 1,
|
||||
};
|
||||
} else {
|
||||
computedStyle = rgb ? {
|
||||
backgroundColor: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${isHovered ? (isDark ? 0.25 : 0.12) : (isDark ? 0.15 : 0.06)})`,
|
||||
color: customColor,
|
||||
borderColor: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${isDark ? 0.3 : 0.2})`,
|
||||
} : {};
|
||||
}
|
||||
|
||||
return (
|
||||
<Label
|
||||
className={`${baseStyles} ${className}`}
|
||||
style={{ ...computedStyle, ...style }}
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<Input
|
||||
type="checkbox"
|
||||
value={value}
|
||||
checked={checked}
|
||||
onChange={(e) => { onChange?.(e); }}
|
||||
className="hidden"
|
||||
/>
|
||||
{icon && (
|
||||
<Icon
|
||||
name={icon}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
)}
|
||||
<Div>{label}</Div>
|
||||
</Label>
|
||||
);
|
||||
}
|
||||
|
||||
// variant별 unchecked 스타일 (연한 톤)
|
||||
const variantUncheckedStyles: Record<string, string> = {
|
||||
green: 'bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 border-green-200 dark:border-green-800 hover:bg-green-100 dark:hover:bg-green-900/30',
|
||||
orange: 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-200 dark:border-orange-800 hover:bg-orange-100 dark:hover:bg-orange-900/30',
|
||||
yellow: 'bg-yellow-50 dark:bg-yellow-900/20 text-yellow-600 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800 hover:bg-yellow-100 dark:hover:bg-yellow-900/30',
|
||||
gray: 'bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-600',
|
||||
blue: 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800 hover:bg-blue-100 dark:hover:bg-blue-900/30',
|
||||
};
|
||||
|
||||
// variant별 checked 스타일 (진한 톤, 흰색 텍스트)
|
||||
const variantCheckedStyles: Record<string, string> = {
|
||||
green: 'bg-green-600 dark:bg-green-600 text-white dark:text-white border-green-700 dark:border-green-500 hover:bg-green-700 dark:hover:bg-green-500',
|
||||
orange: 'bg-orange-600 dark:bg-orange-600 text-white dark:text-white border-orange-700 dark:border-orange-500 hover:bg-orange-700 dark:hover:bg-orange-500',
|
||||
yellow: 'bg-yellow-600 dark:bg-yellow-600 text-white dark:text-white border-yellow-700 dark:border-yellow-500 hover:bg-yellow-700 dark:hover:bg-yellow-500',
|
||||
gray: 'bg-gray-600 dark:bg-gray-500 text-white dark:text-white border-gray-700 dark:border-gray-400 hover:bg-gray-700 dark:hover:bg-gray-400',
|
||||
blue: 'bg-blue-600 dark:bg-blue-600 text-white dark:text-white border-blue-700 dark:border-blue-500 hover:bg-blue-700 dark:hover:bg-blue-500',
|
||||
};
|
||||
|
||||
const currentStyles = checked ? variantCheckedStyles[variant] : variantUncheckedStyles[variant];
|
||||
|
||||
return (
|
||||
<Label
|
||||
className={`${baseStyles} ${currentStyles} ${className}`}
|
||||
style={style}
|
||||
>
|
||||
<Input
|
||||
type="checkbox"
|
||||
value={value}
|
||||
checked={checked}
|
||||
onChange={(e) => { onChange?.(e); }}
|
||||
className="hidden"
|
||||
/>
|
||||
{icon && (
|
||||
<Icon
|
||||
name={icon}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
)}
|
||||
<Div>{label}</Div>
|
||||
</Label>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import Editor, { Monaco } from '@monaco-editor/react';
|
||||
import * as monaco from 'monaco-editor';
|
||||
|
||||
export interface CodeEditorProps {
|
||||
value: string;
|
||||
onChange?: (event: { target: { value: string } }) => void;
|
||||
language?: string;
|
||||
height?: string;
|
||||
readOnly?: boolean;
|
||||
theme?: 'vs-dark' | 'vs-light';
|
||||
}
|
||||
|
||||
export const CodeEditor: React.FC<CodeEditorProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
language = 'json',
|
||||
height = '100%',
|
||||
readOnly = false,
|
||||
theme = 'vs-dark',
|
||||
}) => {
|
||||
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
|
||||
|
||||
const handleEditorDidMount = (
|
||||
editor: monaco.editor.IStandaloneCodeEditor,
|
||||
monacoInstance: Monaco
|
||||
) => {
|
||||
editorRef.current = editor;
|
||||
|
||||
// JSON 스키마 검증 설정
|
||||
if (language === 'json') {
|
||||
monacoInstance.languages.json.jsonDefaults.setDiagnosticsOptions({
|
||||
validate: true,
|
||||
schemaValidation: 'error',
|
||||
allowComments: false,
|
||||
});
|
||||
}
|
||||
|
||||
// 에디터 옵션 설정
|
||||
editor.updateOptions({
|
||||
readOnly,
|
||||
minimap: { enabled: false },
|
||||
scrollBeyondLastLine: false,
|
||||
fontSize: 14,
|
||||
lineNumbers: 'on',
|
||||
renderWhitespace: 'selection',
|
||||
automaticLayout: true,
|
||||
});
|
||||
};
|
||||
|
||||
const handleChange = (value: string | undefined) => {
|
||||
if (onChange && value !== undefined) {
|
||||
// 엔진의 isCustomComponentEvent 경로로 처리되도록 { target: { value } } 패턴 사용
|
||||
onChange({ target: { value } });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current) {
|
||||
editorRef.current.updateOptions({ readOnly });
|
||||
}
|
||||
}, [readOnly]);
|
||||
|
||||
return (
|
||||
<div className="border border-gray-300 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
<Editor
|
||||
height={height}
|
||||
language={language}
|
||||
value={value}
|
||||
theme={theme}
|
||||
onChange={handleChange}
|
||||
onMount={handleEditorDidMount}
|
||||
options={{
|
||||
readOnly,
|
||||
minimap: { enabled: false },
|
||||
scrollBeyondLastLine: false,
|
||||
fontSize: 14,
|
||||
lineNumbers: 'on',
|
||||
renderWhitespace: 'selection',
|
||||
automaticLayout: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,464 @@
|
||||
import React, { useState, useRef, useEffect, useMemo } from 'react';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Checkbox } from '../basic/Checkbox';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:ColumnSelector')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:ColumnSelector]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:ColumnSelector]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:ColumnSelector]', ...args),
|
||||
};
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
/**
|
||||
* 전역 window 타입 확장
|
||||
* 그누보드7 Core의 AuthManager에 접근하기 위한 타입 선언
|
||||
*/
|
||||
declare global {
|
||||
interface Window {
|
||||
G7Core?: {
|
||||
AuthManager?: {
|
||||
getInstance: () => {
|
||||
getUser: () => { uuid: string; [key: string]: any } | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface ColumnItem {
|
||||
field: string;
|
||||
header: string;
|
||||
required?: boolean;
|
||||
visible?: boolean;
|
||||
}
|
||||
|
||||
// G7Core 전역 객체의 스타일 헬퍼 접근
|
||||
const G7Core = () => (window as any).G7Core;
|
||||
|
||||
export interface ColumnSelectorProps {
|
||||
/** 컴포넌트 고유 ID (레이아웃 JSON의 id 값, localStorage 키 생성에 사용) */
|
||||
id?: string;
|
||||
columns: ColumnItem[];
|
||||
visibleColumns?: string[];
|
||||
onColumnVisibilityChange?: (visibleFields: string[]) => void;
|
||||
triggerLabel?: string;
|
||||
triggerIconName?: IconName;
|
||||
position?: 'left' | 'right';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
requiredText?: string;
|
||||
/** 드롭다운 메뉴 상단 제목 */
|
||||
menuTitle?: string;
|
||||
/** 드롭다운 메뉴 상단 설명 */
|
||||
menuDescription?: string;
|
||||
/** 기본 표시 컬럼 (localStorage에 값이 없을 때 사용) */
|
||||
defaultColumns?: string[];
|
||||
/** 트리거 버튼에 적용할 추가 className (기존 스타일과 병합됨) */
|
||||
triggerClassName?: string;
|
||||
/** 라벨 Span에 적용할 추가 className (기존 스타일과 병합됨) */
|
||||
labelClassName?: string;
|
||||
/**
|
||||
* 동적 컬럼 배열 (v1.4.0+)
|
||||
*
|
||||
* 기존 columns 배열에 동적으로 병합될 컬럼들입니다.
|
||||
* dynamicColumnsInsertAfter가 지정된 경우 해당 필드 뒤에 삽입되고,
|
||||
* 그렇지 않으면 columns 배열 끝에 추가됩니다.
|
||||
*/
|
||||
dynamicColumns?: ColumnItem[];
|
||||
/**
|
||||
* 동적 컬럼 삽입 위치를 지정하는 필드명
|
||||
* 해당 필드 뒤에 dynamicColumns가 삽입됩니다.
|
||||
* 지정하지 않으면 columns 끝에 추가됩니다.
|
||||
*/
|
||||
dynamicColumnsInsertAfter?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ColumnSelector 집합 컴포넌트
|
||||
*
|
||||
* 테이블 컬럼의 표시/숨김을 선택할 수 있는 드롭다운 컴포넌트입니다.
|
||||
* required 속성이 있는 컬럼은 항상 표시되며 비활성화됩니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Button + Div + Span + Icon + Checkbox
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "ColumnSelector",
|
||||
* "props": {
|
||||
* "columns": [
|
||||
* {"field": "id", "header": "$t:admin.users.columns.id", "required": true},
|
||||
* {"field": "name", "header": "$t:admin.users.columns.name", "required": true},
|
||||
* {"field": "email", "header": "$t:admin.users.columns.email"},
|
||||
* {"field": "status", "header": "$t:admin.users.columns.status"}
|
||||
* ],
|
||||
* "visibleColumns": "{{_local.visibleColumns}}",
|
||||
* "triggerLabel": "$t:common.column_selector",
|
||||
* "requiredText": "$t:common.required"
|
||||
* },
|
||||
* "actions": [
|
||||
* {
|
||||
* "event": "onColumnVisibilityChange",
|
||||
* "type": "change",
|
||||
* "handler": "setState",
|
||||
* "params": {
|
||||
* "target": "local",
|
||||
* "visibleColumns": "{{$args[0]}}"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const ColumnSelector: React.FC<ColumnSelectorProps> = ({
|
||||
id,
|
||||
columns,
|
||||
visibleColumns: externalVisibleColumns,
|
||||
onColumnVisibilityChange,
|
||||
triggerLabel,
|
||||
triggerIconName = IconName.Sliders,
|
||||
position = 'right',
|
||||
className = '',
|
||||
style,
|
||||
requiredText,
|
||||
menuTitle,
|
||||
menuDescription,
|
||||
defaultColumns,
|
||||
triggerClassName,
|
||||
labelClassName,
|
||||
dynamicColumns,
|
||||
dynamicColumnsInsertAfter,
|
||||
}) => {
|
||||
// props로 전달된 값이 없으면 다국어 키 사용
|
||||
const resolvedTriggerLabel = triggerLabel ?? t('common.column_selector');
|
||||
const resolvedRequiredText = requiredText ?? t('common.required');
|
||||
|
||||
// 동적 컬럼 병합
|
||||
// dynamicColumns가 있으면 columns에 병합하고, dynamicColumnsInsertAfter 위치에 삽입
|
||||
const mergedColumns = useMemo(() => {
|
||||
if (!dynamicColumns || !Array.isArray(dynamicColumns) || dynamicColumns.length === 0) {
|
||||
return columns;
|
||||
}
|
||||
|
||||
// 삽입 위치 찾기
|
||||
if (dynamicColumnsInsertAfter) {
|
||||
const insertIndex = columns.findIndex((col) => col.field === dynamicColumnsInsertAfter);
|
||||
if (insertIndex !== -1) {
|
||||
return [
|
||||
...columns.slice(0, insertIndex + 1),
|
||||
...dynamicColumns,
|
||||
...columns.slice(insertIndex + 1),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 삽입 위치가 없으면 끝에 추가
|
||||
return [...columns, ...dynamicColumns];
|
||||
}, [columns, dynamicColumns, dynamicColumnsInsertAfter]);
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const dropdownMenuRef = useRef<HTMLDivElement>(null);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [adjustedPosition, setAdjustedPosition] = useState<'left' | 'right'>(position);
|
||||
|
||||
// 그누보드7 Core의 AuthManager를 통해 현재 로그인한 사용자 ID 가져오기
|
||||
// window.G7Core.AuthManager는 런타임에 G7 코어 엔진에서 제공됨
|
||||
const userId = useMemo(() => {
|
||||
try {
|
||||
const authManager = window.G7Core?.AuthManager?.getInstance();
|
||||
if (authManager) {
|
||||
const user = authManager.getUser();
|
||||
return user?.uuid;
|
||||
}
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// localStorage 키 생성 (g7_columns_{id}_{userId} 형식)
|
||||
// id가 없으면 저장 기능 비활성화, userId가 없으면 공유 설정
|
||||
const storageKey = id
|
||||
? `g7_columns_${id}${userId !== undefined ? `_${userId}` : ''}`
|
||||
: null;
|
||||
|
||||
// localStorage에서 저장된 컬럼 설정 불러오기
|
||||
const getStoredColumns = (): string[] | null => {
|
||||
if (!storageKey) return null;
|
||||
try {
|
||||
const stored = localStorage.getItem(storageKey);
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (Array.isArray(parsed) && parsed.length > 0) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to load from localStorage:', error);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// localStorage에 컬럼 설정 저장
|
||||
const saveToStorage = (cols: string[]) => {
|
||||
if (!storageKey) return;
|
||||
try {
|
||||
localStorage.setItem(storageKey, JSON.stringify(cols));
|
||||
} catch (error) {
|
||||
logger.warn('Failed to save to localStorage:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 초기 컬럼 결정 (우선순위: localStorage > externalVisibleColumns > defaultColumns > 모든 컬럼)
|
||||
const getInitialColumns = (): string[] => {
|
||||
// 1. localStorage에서 불러오기
|
||||
const stored = getStoredColumns();
|
||||
if (stored) return stored;
|
||||
|
||||
// 2. 외부에서 전달된 값
|
||||
if (externalVisibleColumns && externalVisibleColumns.length > 0) {
|
||||
return externalVisibleColumns;
|
||||
}
|
||||
|
||||
// 3. 기본 컬럼 설정
|
||||
if (defaultColumns && defaultColumns.length > 0) {
|
||||
return defaultColumns;
|
||||
}
|
||||
|
||||
// 4. visible !== false인 모든 컬럼
|
||||
return mergedColumns.filter((col) => col.visible !== false).map((col) => col.field);
|
||||
};
|
||||
|
||||
// 표시할 컬럼 관리
|
||||
const [internalVisibleColumns, setInternalVisibleColumns] = useState<string[]>(getInitialColumns);
|
||||
|
||||
// 초기 로드 시 결정된 컬럼으로 부모 상태 동기화
|
||||
useEffect(() => {
|
||||
if (!isInitialized) {
|
||||
// 초기 컬럼 값으로 부모 상태 동기화 (localStorage 값 또는 defaultColumns)
|
||||
if (onColumnVisibilityChange && internalVisibleColumns.length > 0) {
|
||||
onColumnVisibilityChange(internalVisibleColumns);
|
||||
}
|
||||
setIsInitialized(true);
|
||||
}
|
||||
}, [isInitialized, onColumnVisibilityChange, internalVisibleColumns]);
|
||||
|
||||
// 외부 visibleColumns가 변경되면 내부 상태 동기화 (단, localStorage 값이 우선)
|
||||
useEffect(() => {
|
||||
if (isInitialized && externalVisibleColumns && externalVisibleColumns.length > 0) {
|
||||
// localStorage에 저장된 값이 없을 때만 외부 값으로 동기화
|
||||
const stored = getStoredColumns();
|
||||
if (!stored) {
|
||||
setInternalVisibleColumns(externalVisibleColumns);
|
||||
}
|
||||
}
|
||||
}, [externalVisibleColumns, isInitialized]);
|
||||
|
||||
// 동적 컬럼이 새로 추가될 때만 visibleColumns에 자동 포함
|
||||
// localStorage에 저장된 값이 있으면 사용자의 선택을 존중하고 자동 추가하지 않음
|
||||
const prevDynamicFieldsRef = useRef<string[]>([]);
|
||||
const hasStoredColumnsRef = useRef<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return; // 초기화 전에는 실행하지 않음
|
||||
|
||||
if (dynamicColumns && dynamicColumns.length > 0) {
|
||||
const currentDynamicFields = dynamicColumns.map((col) => col.field);
|
||||
|
||||
// 최초 실행 시 localStorage 존재 여부 확인 및 prevDynamicFields 초기화
|
||||
if (hasStoredColumnsRef.current === null) {
|
||||
const stored = getStoredColumns();
|
||||
hasStoredColumnsRef.current = stored !== null;
|
||||
|
||||
// localStorage에 저장된 값이 있으면 현재 동적 필드를 "이미 알려진" 것으로 기록
|
||||
// 이렇게 하면 페이지 새로고침 시 동적 컬럼이 다시 자동 추가되지 않음
|
||||
if (stored !== null) {
|
||||
prevDynamicFieldsRef.current = currentDynamicFields;
|
||||
return; // localStorage 값 존중, 자동 추가 안 함
|
||||
}
|
||||
}
|
||||
|
||||
const prevDynamicFields = prevDynamicFieldsRef.current;
|
||||
|
||||
// 새로 추가된 동적 필드만 찾기 (기존에 없던 필드)
|
||||
const trulyNewFields = currentDynamicFields.filter(
|
||||
(field) => !prevDynamicFields.includes(field)
|
||||
);
|
||||
|
||||
// 새로운 동적 필드가 있을 때만 자동 추가
|
||||
if (trulyNewFields.length > 0) {
|
||||
const currentVisible = externalVisibleColumns && externalVisibleColumns.length > 0
|
||||
? externalVisibleColumns
|
||||
: internalVisibleColumns;
|
||||
|
||||
// 현재 visible에 없는 새 필드만 추가
|
||||
const fieldsToAdd = trulyNewFields.filter((field) => !currentVisible.includes(field));
|
||||
|
||||
if (fieldsToAdd.length > 0) {
|
||||
const updatedVisible = [...currentVisible, ...fieldsToAdd];
|
||||
setInternalVisibleColumns(updatedVisible);
|
||||
saveToStorage(updatedVisible);
|
||||
onColumnVisibilityChange?.(updatedVisible);
|
||||
}
|
||||
}
|
||||
|
||||
// 현재 동적 필드 목록 저장
|
||||
prevDynamicFieldsRef.current = currentDynamicFields;
|
||||
}
|
||||
}, [dynamicColumns, isInitialized]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const visibleColumns = externalVisibleColumns && externalVisibleColumns.length > 0
|
||||
? externalVisibleColumns
|
||||
: internalVisibleColumns;
|
||||
|
||||
// 외부 클릭 감지
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// 드롭다운 메뉴가 화면을 벗어나는지 감지하고 위치 조정
|
||||
useEffect(() => {
|
||||
if (isOpen && dropdownMenuRef.current && menuRef.current) {
|
||||
const menuRect = dropdownMenuRef.current.getBoundingClientRect();
|
||||
const triggerRect = menuRef.current.getBoundingClientRect();
|
||||
const viewportWidth = window.innerWidth;
|
||||
|
||||
// 메뉴 너비 (w-64 = 16rem = 256px)
|
||||
const menuWidth = menuRect.width || 256;
|
||||
|
||||
if (position === 'right') {
|
||||
// right 위치: 메뉴가 버튼의 오른쪽 끝에서 왼쪽으로 펼쳐짐
|
||||
// 메뉴의 왼쪽 끝이 화면 왼쪽을 벗어나는지 확인
|
||||
const menuLeft = triggerRect.right - menuWidth;
|
||||
if (menuLeft < 0) {
|
||||
setAdjustedPosition('left');
|
||||
} else {
|
||||
setAdjustedPosition('right');
|
||||
}
|
||||
} else {
|
||||
// left 위치: 메뉴가 버튼의 왼쪽 끝에서 오른쪽으로 펼쳐짐
|
||||
// 메뉴의 오른쪽 끝이 화면 오른쪽을 벗어나는지 확인
|
||||
const menuRight = triggerRect.left + menuWidth;
|
||||
if (menuRight > viewportWidth) {
|
||||
setAdjustedPosition('right');
|
||||
} else {
|
||||
setAdjustedPosition('left');
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [isOpen, position]);
|
||||
|
||||
const handleColumnToggle = (field: string) => {
|
||||
const column = mergedColumns.find((col) => col.field === field);
|
||||
if (column?.required) return; // required 컬럼은 토글 불가
|
||||
|
||||
const newVisibleColumns = visibleColumns.includes(field)
|
||||
? visibleColumns.filter((f) => f !== field)
|
||||
: [...visibleColumns, field];
|
||||
|
||||
setInternalVisibleColumns(newVisibleColumns);
|
||||
saveToStorage(newVisibleColumns);
|
||||
onColumnVisibilityChange?.(newVisibleColumns);
|
||||
};
|
||||
|
||||
const positionClasses = adjustedPosition === 'left' ? 'left-0' : 'right-0';
|
||||
|
||||
return (
|
||||
<Div
|
||||
ref={menuRef}
|
||||
className={`relative inline-block ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{/* 트리거 버튼 */}
|
||||
<Button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className={G7Core()?.style?.mergeClasses?.(
|
||||
'flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors',
|
||||
triggerClassName
|
||||
) ?? `flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors ${triggerClassName ?? ''}`}
|
||||
>
|
||||
<Icon name={triggerIconName} className="w-5 h-5" />
|
||||
{resolvedTriggerLabel && (
|
||||
<Span className={`${labelClassName ? labelClassName : 'hidden sm:inline'} text-sm`}>
|
||||
{resolvedTriggerLabel}
|
||||
</Span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* 드롭다운 메뉴 */}
|
||||
{isOpen && (
|
||||
<Div
|
||||
ref={dropdownMenuRef}
|
||||
className={`absolute ${positionClasses} z-50 mt-2 w-64 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg`}
|
||||
>
|
||||
{/* 헤더 영역 */}
|
||||
{(menuTitle || menuDescription) && (
|
||||
<Div className="px-4 pt-3 pb-2 border-b border-gray-200 dark:border-gray-700">
|
||||
{menuTitle && (
|
||||
<Span className="block text-sm font-medium text-gray-900 dark:text-white">
|
||||
{menuTitle}
|
||||
</Span>
|
||||
)}
|
||||
{menuDescription && (
|
||||
<Span className="block text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
{menuDescription}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
)}
|
||||
<Div className="p-2 max-h-64 overflow-y-auto">
|
||||
{mergedColumns.map((col) => {
|
||||
const isVisible = visibleColumns.includes(col.field);
|
||||
const isRequired = col.required === true;
|
||||
|
||||
return (
|
||||
<Div
|
||||
key={col.field}
|
||||
onClick={() => !isRequired && handleColumnToggle(col.field)}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded hover:bg-gray-50 dark:hover:bg-gray-700 ${
|
||||
isRequired ? 'cursor-default' : 'cursor-pointer'
|
||||
}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={isVisible}
|
||||
disabled={isRequired}
|
||||
readOnly
|
||||
className="h-4 w-4 text-blue-600 rounded border-gray-300 dark:border-gray-600 pointer-events-none"
|
||||
/>
|
||||
<Span className="text-sm text-gray-700 dark:text-gray-300">
|
||||
{col.header}
|
||||
</Span>
|
||||
{isRequired && resolvedRequiredText && (
|
||||
<Span className="ml-auto text-xs text-gray-400 dark:text-gray-500">
|
||||
{resolvedRequiredText}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
import React from 'react';
|
||||
import { Modal } from './Modal';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { P } from '../basic/P';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export interface ConfirmDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
message: string | React.ReactNode;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
onConfirm: () => void;
|
||||
onCancel?: () => void;
|
||||
confirmButtonVariant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
cancelButtonVariant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
width?: string;
|
||||
closeOnOverlay?: boolean;
|
||||
/** 로딩 중 여부 (확인 버튼 비활성화 및 텍스트 변경) */
|
||||
isLoading?: boolean;
|
||||
/** 로딩 중 확인 버튼에 표시할 텍스트 */
|
||||
loadingText?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ConfirmDialog 집합 컴포넌트
|
||||
*
|
||||
* Modal 기반 확인/취소 다이얼로그 컴포넌트.
|
||||
* 사용자에게 확인을 요청하고 확인/취소 중 하나를 선택하도록 합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합:
|
||||
* - Modal > P(message) + Button(확인) + Button(취소)
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "ConfirmDialog",
|
||||
* "props": {
|
||||
* "isOpen": "{{dialogs.deleteConfirm}}",
|
||||
* "title": "삭제 확인",
|
||||
* "message": "정말 이 항목을 삭제하시겠습니까?",
|
||||
* "confirmText": "삭제",
|
||||
* "cancelText": "$t:common.cancel",
|
||||
* "confirmButtonVariant": "danger"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
message,
|
||||
confirmText,
|
||||
cancelText,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
confirmButtonVariant = 'primary',
|
||||
// cancelButtonVariant는 현재 고정 스타일 사용으로 미사용
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
cancelButtonVariant: _cancelButtonVariant = 'secondary',
|
||||
width = '500px',
|
||||
// closeOnOverlay는 Modal에서 처리하므로 미사용
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
closeOnOverlay: _closeOnOverlay = true,
|
||||
isLoading = false,
|
||||
loadingText,
|
||||
}) => {
|
||||
// props로 전달된 값이 없으면 다국어 키 사용
|
||||
const resolvedConfirmText = confirmText ?? t('common.confirm');
|
||||
const resolvedCancelText = cancelText ?? t('common.cancel');
|
||||
const resolvedLoadingText = loadingText ?? t('common.loading');
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm();
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
// 로딩 중에는 취소 불가
|
||||
if (isLoading) return;
|
||||
onCancel?.();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
// 로딩 중에는 닫기 불가
|
||||
if (isLoading) return;
|
||||
onClose();
|
||||
};
|
||||
|
||||
// 버튼 variant별 스타일 매핑
|
||||
const confirmVariantClassMap: Record<'primary' | 'secondary' | 'danger' | 'ghost', string> = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700',
|
||||
secondary: 'bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700',
|
||||
ghost: 'bg-transparent text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700',
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={handleClose}
|
||||
title={title}
|
||||
width={width}
|
||||
>
|
||||
{/* 본문 */}
|
||||
<Div className="py-2">
|
||||
{typeof message === 'string' ? (
|
||||
<P className="text-gray-700 dark:text-gray-300">{message}</P>
|
||||
) : (
|
||||
message
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 푸터 (버튼 영역) */}
|
||||
<Div className="flex justify-end gap-3 mt-6">
|
||||
{/* 취소 버튼 */}
|
||||
<Button
|
||||
onClick={handleCancel}
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Span>{resolvedCancelText}</Span>
|
||||
</Button>
|
||||
|
||||
{/* 확인 버튼 */}
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
disabled={isLoading}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed ${confirmVariantClassMap[confirmButtonVariant]}`}
|
||||
>
|
||||
{isLoading && (
|
||||
<Icon name={IconName.Spinner} className="w-4 h-4 animate-spin" />
|
||||
)}
|
||||
<Span>{isLoading ? resolvedLoadingText : resolvedConfirmText}</Span>
|
||||
</Button>
|
||||
</Div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,140 @@
|
||||
import React from 'react';
|
||||
import { Modal } from './Modal';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H2 } from '../basic/H2';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export interface DialogAction {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
iconName?: IconName;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface DialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
content: React.ReactNode;
|
||||
actions?: DialogAction[];
|
||||
width?: string;
|
||||
closeOnOverlay?: boolean;
|
||||
showCloseButton?: boolean;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dialog 집합 컴포넌트
|
||||
*
|
||||
* Modal의 특화 버전으로 제목 + 본문 + 액션 영역 구조를 표준화한 컴포넌트.
|
||||
* Modal보다 더 구조화된 레이아웃 제공.
|
||||
*
|
||||
* 기본 컴포넌트 조합:
|
||||
* - Modal > Div(header) > H2(title) + Button(close)
|
||||
* - Div(body) > {content}
|
||||
* - Div(footer) > Button[](actions)
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Dialog",
|
||||
* "props": {
|
||||
* "isOpen": "{{dialogs.confirm}}",
|
||||
* "title": "확인",
|
||||
* "content": "정말 삭제하시겠습니까?",
|
||||
* "actions": [
|
||||
* {"label": "취소", "variant": "secondary"},
|
||||
* {"label": "삭제", "variant": "danger"}
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Dialog: React.FC<DialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
content,
|
||||
actions = [],
|
||||
width = '500px',
|
||||
closeOnOverlay = true,
|
||||
showCloseButton = true,
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
const handleOverlayClick = () => {
|
||||
if (closeOnOverlay) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// 버튼 variant별 스타일 매핑
|
||||
const variantClassMap: Record<'primary' | 'secondary' | 'danger' | 'ghost', string> = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
|
||||
secondary: 'bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600 focus:ring-gray-500',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700 focus:ring-red-500',
|
||||
ghost: 'bg-transparent text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-gray-500',
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={handleOverlayClick}
|
||||
width={width}
|
||||
className={className}
|
||||
style={style}
|
||||
>
|
||||
{/* Header */}
|
||||
<Div className="flex items-center justify-between mb-4">
|
||||
<H2 className="text-xl font-semibold text-gray-900 dark:text-white">
|
||||
{title}
|
||||
</H2>
|
||||
{showCloseButton && (
|
||||
<Button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 focus:outline-none"
|
||||
aria-label={t('common.close_dialog')}
|
||||
>
|
||||
<Icon name={IconName.Times} className="w-5 h-5" />
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* Body */}
|
||||
<Div className="mb-6 text-gray-700 dark:text-gray-300">
|
||||
{content}
|
||||
</Div>
|
||||
|
||||
{/* Footer (Actions) */}
|
||||
{actions.length > 0 && (
|
||||
<Div className="flex justify-end gap-3">
|
||||
{actions.map((action, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
onClick={action.onClick}
|
||||
disabled={action.disabled}
|
||||
className={`
|
||||
px-4 py-2 rounded-md font-medium transition-colors
|
||||
focus:outline-none focus:ring-2 focus:ring-offset-2
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
${variantClassMap[action.variant || 'primary']}
|
||||
`}
|
||||
>
|
||||
{action.iconName && (
|
||||
<Icon name={action.iconName} className="w-4 h-4 mr-2 inline-block" />
|
||||
)}
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,256 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
|
||||
export interface DropdownItem {
|
||||
label: string;
|
||||
value: string;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface DropdownProps {
|
||||
label: string;
|
||||
items: DropdownItem[];
|
||||
/** 아이템 클릭 시 호출되는 콜백. value 문자열을 전달합니다. */
|
||||
onItemClick?: (value: string, item: DropdownItem) => void;
|
||||
position?: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';
|
||||
/** 드롭다운 스타일 변형 */
|
||||
variant?: 'default' | 'text';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dropdown 집합 컴포넌트
|
||||
*
|
||||
* Button + Div 기본 컴포넌트를 조합하여 드롭다운 메뉴 UI를 구성합니다.
|
||||
* 키보드 네비게이션 (Arrow Up/Down, Enter, Escape) 지원, 외부 클릭 감지 기능을 포함합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Dropdown",
|
||||
* "props": {
|
||||
* "label": "작업",
|
||||
* "items": [
|
||||
* {"label": "수정", "value": "edit"},
|
||||
* {"label": "삭제", "value": "delete"}
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Dropdown: React.FC<DropdownProps> = ({
|
||||
label,
|
||||
items,
|
||||
onItemClick,
|
||||
position = 'bottom-left',
|
||||
variant = 'default',
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [focusedIndex, setFocusedIndex] = useState(-1);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const [adjustedPosition, setAdjustedPosition] = useState(position);
|
||||
|
||||
// 외부 클릭 감지
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
setFocusedIndex(-1);
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
// 키보드 네비게이션
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const enabledIndexes = items
|
||||
.map((item, index) => (!item.disabled ? index : -1))
|
||||
.filter((index) => index !== -1);
|
||||
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
event.preventDefault();
|
||||
setFocusedIndex((prev) => {
|
||||
const currentEnabledIndex = enabledIndexes.indexOf(prev);
|
||||
const nextEnabledIndex = (currentEnabledIndex + 1) % enabledIndexes.length;
|
||||
return enabledIndexes[nextEnabledIndex];
|
||||
});
|
||||
break;
|
||||
|
||||
case 'ArrowUp':
|
||||
event.preventDefault();
|
||||
setFocusedIndex((prev) => {
|
||||
const currentEnabledIndex = enabledIndexes.indexOf(prev);
|
||||
const prevEnabledIndex =
|
||||
currentEnabledIndex <= 0 ? enabledIndexes.length - 1 : currentEnabledIndex - 1;
|
||||
return enabledIndexes[prevEnabledIndex];
|
||||
});
|
||||
break;
|
||||
|
||||
case 'Enter':
|
||||
event.preventDefault();
|
||||
if (focusedIndex >= 0 && !items[focusedIndex].disabled) {
|
||||
handleItemClick(items[focusedIndex]);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Escape':
|
||||
event.preventDefault();
|
||||
setIsOpen(false);
|
||||
setFocusedIndex(-1);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}
|
||||
}, [isOpen, focusedIndex, items]);
|
||||
|
||||
// 드롭다운 메뉴가 화면을 벗어나는지 감지하고 위치 조정
|
||||
useEffect(() => {
|
||||
if (isOpen && menuRef.current && dropdownRef.current) {
|
||||
const menuRect = menuRef.current.getBoundingClientRect();
|
||||
const triggerRect = dropdownRef.current.getBoundingClientRect();
|
||||
const viewportWidth = window.innerWidth;
|
||||
const viewportHeight = window.innerHeight;
|
||||
|
||||
// 메뉴 크기 (w-56 = 14rem = 224px)
|
||||
const menuWidth = menuRect.width || 224;
|
||||
const menuHeight = menuRect.height || 200;
|
||||
|
||||
let newPosition = position;
|
||||
|
||||
// 수평 위치 조정
|
||||
const isLeftAligned = position.includes('left');
|
||||
if (isLeftAligned) {
|
||||
// left 정렬: 메뉴가 버튼 왼쪽 끝에서 오른쪽으로 펼쳐짐
|
||||
const menuRight = triggerRect.left + menuWidth;
|
||||
if (menuRight > viewportWidth) {
|
||||
newPosition = newPosition.replace('left', 'right') as typeof position;
|
||||
}
|
||||
} else {
|
||||
// right 정렬: 메뉴가 버튼 오른쪽 끝에서 왼쪽으로 펼쳐짐
|
||||
const menuLeft = triggerRect.right - menuWidth;
|
||||
if (menuLeft < 0) {
|
||||
newPosition = newPosition.replace('right', 'left') as typeof position;
|
||||
}
|
||||
}
|
||||
|
||||
// 수직 위치 조정
|
||||
const isTopAligned = position.includes('top');
|
||||
if (isTopAligned) {
|
||||
// top 정렬: 메뉴가 버튼 위로 펼쳐짐
|
||||
if (triggerRect.top - menuHeight < 0) {
|
||||
newPosition = newPosition.replace('top', 'bottom') as typeof position;
|
||||
}
|
||||
} else {
|
||||
// bottom 정렬: 메뉴가 버튼 아래로 펼쳐짐
|
||||
if (triggerRect.bottom + menuHeight > viewportHeight) {
|
||||
newPosition = newPosition.replace('bottom', 'top') as typeof position;
|
||||
}
|
||||
}
|
||||
|
||||
setAdjustedPosition(newPosition);
|
||||
}
|
||||
}, [isOpen, position]);
|
||||
|
||||
const handleItemClick = (item: DropdownItem) => {
|
||||
if (item.disabled) return;
|
||||
|
||||
item.onClick?.();
|
||||
// value를 첫 번째 인자로 전달하여 switch 핸들러와 호환
|
||||
onItemClick?.(item.value, item);
|
||||
setIsOpen(false);
|
||||
setFocusedIndex(-1);
|
||||
};
|
||||
|
||||
const positionClasses = {
|
||||
'bottom-left': 'top-full left-0 mt-2',
|
||||
'bottom-right': 'top-full right-0 mt-2',
|
||||
'top-left': 'bottom-full left-0 mb-2',
|
||||
'top-right': 'bottom-full right-0 mb-2',
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
ref={dropdownRef}
|
||||
className={`relative inline-block ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{/* Trigger Button */}
|
||||
<Button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className={
|
||||
variant === 'text'
|
||||
? 'text-primary font-medium cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 inline-flex items-center'
|
||||
: 'px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 text-gray-900 dark:text-white'
|
||||
}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={isOpen}
|
||||
>
|
||||
{label}
|
||||
{variant !== 'text' && (
|
||||
<svg
|
||||
className={`inline-block ml-2 w-4 h-4 transition-transform ${
|
||||
isOpen ? 'rotate-180' : ''
|
||||
}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Dropdown Menu */}
|
||||
{isOpen && (
|
||||
<Div
|
||||
ref={menuRef}
|
||||
className={`absolute z-50 w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg ${positionClasses[adjustedPosition]}`}
|
||||
role="menu"
|
||||
aria-orientation="vertical"
|
||||
>
|
||||
<Div className="py-1">
|
||||
{items.map((item, index) => (
|
||||
<Div
|
||||
key={item.value}
|
||||
className={`px-4 py-2 text-sm ${
|
||||
item.disabled
|
||||
? 'text-gray-400 dark:text-gray-500 cursor-not-allowed'
|
||||
: 'text-gray-700 dark:text-gray-300 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
} ${focusedIndex === index ? 'bg-gray-100 dark:bg-gray-700' : ''}`}
|
||||
onClick={() => handleItemClick(item)}
|
||||
onMouseEnter={() => !item.disabled && setFocusedIndex(index)}
|
||||
role="menuitem"
|
||||
aria-disabled={item.disabled}
|
||||
tabIndex={item.disabled ? -1 : 0}
|
||||
>
|
||||
{item.label}
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,172 @@
|
||||
import React, { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface DropdownButtonProps {
|
||||
label?: string;
|
||||
icon?: IconName | string;
|
||||
iconPosition?: 'left' | 'right';
|
||||
position?: 'left' | 'right';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* DropdownButton 집합 컴포넌트
|
||||
*
|
||||
* 드롭다운 형태의 버튼 컴포넌트입니다.
|
||||
* ActionMenu와 유사하지만 children을 통해 자유롭게 메뉴 내용을 구성할 수 있습니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Button + Div + Span + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "DropdownButton",
|
||||
* "props": {
|
||||
* "label": "더보기",
|
||||
* "icon": "chevron-down",
|
||||
* "iconPosition": "right",
|
||||
* "className": "btn btn-outline btn-sm"
|
||||
* },
|
||||
* "children": [
|
||||
* {
|
||||
* "name": "DropdownItem",
|
||||
* "props": {
|
||||
* "label": "메뉴 1"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const DropdownButton: React.FC<DropdownButtonProps> = ({
|
||||
label,
|
||||
icon,
|
||||
iconPosition = 'left',
|
||||
position = 'right',
|
||||
className = '',
|
||||
style,
|
||||
children,
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 메뉴 위치 계산
|
||||
const updateMenuPosition = useCallback(() => {
|
||||
if (!triggerRef.current) return;
|
||||
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
const menuWidth = 224; // w-56 = 14rem = 224px
|
||||
|
||||
let left = position === 'right' ? rect.right - menuWidth : rect.left;
|
||||
const top = rect.bottom + 8; // mt-2 = 8px
|
||||
|
||||
// 화면 왼쪽 경계 체크
|
||||
if (left < 8) {
|
||||
left = 8;
|
||||
}
|
||||
|
||||
// 화면 오른쪽 경계 체크
|
||||
if (left + menuWidth > window.innerWidth - 8) {
|
||||
left = window.innerWidth - menuWidth - 8;
|
||||
}
|
||||
|
||||
setMenuPosition({ top, left });
|
||||
}, [position]);
|
||||
|
||||
// 메뉴 열릴 때 위치 계산
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
updateMenuPosition();
|
||||
}
|
||||
}, [isOpen, updateMenuPosition]);
|
||||
|
||||
// 스크롤/리사이즈 시 메뉴 닫기
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleScrollOrResize = () => {
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', handleScrollOrResize, true);
|
||||
window.addEventListener('resize', handleScrollOrResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', handleScrollOrResize, true);
|
||||
window.removeEventListener('resize', handleScrollOrResize);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// 외부 클릭 감지
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
const target = event.target as Node;
|
||||
const isClickInsideTrigger = triggerRef.current?.contains(target);
|
||||
const isClickInsideMenu = menuRef.current?.contains(target);
|
||||
|
||||
if (!isClickInsideTrigger && !isClickInsideMenu) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// Portal로 렌더링할 드롭다운 메뉴
|
||||
const dropdownMenu = isOpen
|
||||
? ReactDOM.createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed z-[9999] w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg overflow-hidden"
|
||||
style={{
|
||||
top: menuPosition.top,
|
||||
left: menuPosition.left,
|
||||
}}
|
||||
onClick={() => setIsOpen(false)}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Div className={`relative inline-block ${className}`} style={style}>
|
||||
{/* 트리거 버튼 */}
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{iconPosition === 'left' && icon && (
|
||||
<Icon name={icon} className="w-4 h-4" />
|
||||
)}
|
||||
{label && (
|
||||
<Span className="text-sm font-medium">
|
||||
{label}
|
||||
</Span>
|
||||
)}
|
||||
{iconPosition === 'right' && icon && (
|
||||
<Icon name={icon} className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Portal로 렌더링되는 드롭다운 메뉴 */}
|
||||
{dropdownMenu}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,120 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface DropdownMenuItemProps {
|
||||
label?: string;
|
||||
icon?: IconName | string;
|
||||
variant?: 'default' | 'danger';
|
||||
disabled?: boolean;
|
||||
divider?: boolean;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* DropdownMenuItem 집합 컴포넌트
|
||||
*
|
||||
* DropdownButton의 자식으로 사용되는 메뉴 아이템 컴포넌트입니다.
|
||||
* ActionMenu의 아이템과 동일한 디자인을 사용합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Div + Icon + Span
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "DropdownButton",
|
||||
* "props": {
|
||||
* "label": "작업",
|
||||
* "icon": "chevron-down"
|
||||
* },
|
||||
* "children": [
|
||||
* {
|
||||
* "name": "DropdownMenuItem",
|
||||
* "props": {
|
||||
* "label": "수정",
|
||||
* "icon": "pencil"
|
||||
* },
|
||||
* "actions": [
|
||||
* {
|
||||
* "type": "click",
|
||||
* "handler": "navigate",
|
||||
* "params": {
|
||||
* "path": "/edit/{{id}}"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* },
|
||||
* {
|
||||
* "name": "DropdownMenuItem",
|
||||
* "props": {
|
||||
* "divider": true
|
||||
* }
|
||||
* },
|
||||
* {
|
||||
* "name": "DropdownMenuItem",
|
||||
* "props": {
|
||||
* "label": "삭제",
|
||||
* "icon": "trash",
|
||||
* "variant": "danger"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const DropdownMenuItem: React.FC<DropdownMenuItemProps> = ({
|
||||
label,
|
||||
icon,
|
||||
variant = 'default',
|
||||
disabled = false,
|
||||
divider = false,
|
||||
className = '',
|
||||
style,
|
||||
onClick,
|
||||
}) => {
|
||||
// 구분선인 경우
|
||||
if (divider) {
|
||||
return (
|
||||
<Div
|
||||
className="h-px bg-gray-200 dark:bg-gray-700 my-1"
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// variant에 따른 스타일
|
||||
const variantClasses =
|
||||
variant === 'danger'
|
||||
? 'text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20'
|
||||
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700';
|
||||
|
||||
// disabled 스타일
|
||||
const disabledClasses = disabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'cursor-pointer';
|
||||
|
||||
// 클릭 핸들러
|
||||
const handleClick = () => {
|
||||
if (!disabled && onClick) {
|
||||
onClick();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
onClick={handleClick}
|
||||
className={`flex items-center gap-3 px-4 py-3 transition-colors ${variantClasses} ${disabledClasses} ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{icon && (
|
||||
<Icon name={icon} className="w-4 h-4" />
|
||||
)}
|
||||
{label && (
|
||||
<Span className="text-sm font-medium">{label}</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+385
@@ -0,0 +1,385 @@
|
||||
/**
|
||||
* DynamicFieldList 컴포넌트
|
||||
*
|
||||
* 동적 필드 목록을 관리하는 컴포넌트입니다.
|
||||
* @dnd-kit을 사용하여 드래그 앤 드롭 정렬을 지원합니다.
|
||||
*/
|
||||
|
||||
import React, { useCallback, useMemo, useEffect, useRef } from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { Div } from '../../basic/Div';
|
||||
import { Button } from '../../basic/Button';
|
||||
import { Icon } from '../../basic/Icon';
|
||||
import { Span } from '../../basic/Span';
|
||||
import { DynamicFieldListItem } from './DynamicFieldListItem';
|
||||
import type { DynamicFieldListProps, DynamicFieldColumn } from './types';
|
||||
|
||||
// G7Core 전역 객체 접근
|
||||
const getG7Core = () => (window as any).G7Core;
|
||||
|
||||
/**
|
||||
* 고유 ID 생성
|
||||
*/
|
||||
const generateId = (): string => {
|
||||
return `item_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 기본 아이템 생성
|
||||
*/
|
||||
const createDefaultItemFromColumns = (columns: DynamicFieldColumn[]): Record<string, unknown> => {
|
||||
const item: Record<string, unknown> = {
|
||||
_id: generateId(),
|
||||
};
|
||||
|
||||
columns.forEach((column) => {
|
||||
if (column.type === 'multilingual') {
|
||||
const g7Core = getG7Core();
|
||||
const locales = g7Core?.locale?.all?.() || ['ko', 'en'];
|
||||
const multiValue: Record<string, string> = {};
|
||||
locales.forEach((locale: string) => {
|
||||
multiValue[locale] = '';
|
||||
});
|
||||
item[column.key] = multiValue;
|
||||
} else if (column.type === 'number') {
|
||||
item[column.key] = null;
|
||||
} else if (column.type === 'select') {
|
||||
item[column.key] = '';
|
||||
} else {
|
||||
item[column.key] = '';
|
||||
}
|
||||
});
|
||||
|
||||
return item;
|
||||
};
|
||||
|
||||
/**
|
||||
* DynamicFieldList 컴포넌트
|
||||
*/
|
||||
/**
|
||||
* 에러 객체에서 특정 인덱스의 에러만 추출
|
||||
* 예: {"fields.0.name.ko": ["에러"], "fields.1.content.ko": ["에러"]} 에서
|
||||
* index=0 이면 {"name.ko": ["에러"]} 반환
|
||||
*/
|
||||
const extractErrorsForIndex = (
|
||||
errors: Record<string, string[]> | undefined,
|
||||
index: number
|
||||
): Record<string, string[]> => {
|
||||
if (!errors) return {};
|
||||
|
||||
const prefix = `fields.${index}.`;
|
||||
const result: Record<string, string[]> = {};
|
||||
|
||||
Object.keys(errors).forEach((key) => {
|
||||
if (key.startsWith(prefix)) {
|
||||
// "fields.0.name.ko" -> "name.ko"
|
||||
const newKey = key.substring(prefix.length);
|
||||
result[newKey] = errors[key];
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export const DynamicFieldList: React.FC<DynamicFieldListProps> = ({
|
||||
items = [],
|
||||
columns,
|
||||
onChange,
|
||||
onAddItem,
|
||||
onRemoveItem,
|
||||
onReorder,
|
||||
addLabel = '항목 추가',
|
||||
enableDrag = true,
|
||||
showIndex = true,
|
||||
minItems = 0,
|
||||
maxItems,
|
||||
rowActions,
|
||||
emptyMessage = '항목이 없습니다.',
|
||||
className = '',
|
||||
headerClassName = '',
|
||||
rowClassName = '',
|
||||
name,
|
||||
readOnly = false,
|
||||
createDefaultItem,
|
||||
childrenKey: _childrenKey,
|
||||
itemIdKey = '_id',
|
||||
errors,
|
||||
}) => {
|
||||
const formContextRef = useRef<any>(null);
|
||||
|
||||
// normalizedItems ref (항상 최신 참조 — stale closure 방지)
|
||||
const normalizedItemsRef = useRef<Record<string, unknown>[]>([]);
|
||||
|
||||
// 리렌더 전 누적 편집분 보관 (빠른 연속 편집 시 이전 수정분 유실 방지)
|
||||
const pendingItemsRef = useRef<Record<string, unknown>[] | null>(null);
|
||||
|
||||
/**
|
||||
* items 정규화: itemIdKey가 없는 아이템에 안정적인 ID를 부여합니다.
|
||||
* 부여된 ID는 onChange를 통해 상태에 반영되므로, 이후 리렌더링에서도 유지됩니다.
|
||||
* 이를 통해 setState 라운드트립 후에도 React key가 안정적으로 유지되어
|
||||
* 불필요한 리마운트(포커스 손실)를 방지합니다.
|
||||
*/
|
||||
const normalizedItems = useMemo(() => {
|
||||
let needsNormalization = false;
|
||||
for (const item of items) {
|
||||
if (item[itemIdKey] == null) {
|
||||
needsNormalization = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!needsNormalization) return items;
|
||||
|
||||
return items.map((item) => {
|
||||
if (item[itemIdKey] != null) return item;
|
||||
return { ...item, [itemIdKey]: generateId() };
|
||||
});
|
||||
}, [items, itemIdKey]);
|
||||
|
||||
// normalizedItems 갱신 시 ref 동기화 + pending 초기화
|
||||
normalizedItemsRef.current = normalizedItems;
|
||||
useEffect(() => {
|
||||
pendingItemsRef.current = null;
|
||||
}, [normalizedItems]);
|
||||
|
||||
/**
|
||||
* 아이템에 대한 안정적인 ID를 반환합니다.
|
||||
* normalizedItems에 의해 itemIdKey가 보장되므로, 항상 해당 값을 사용합니다.
|
||||
*/
|
||||
const getStableId = useCallback((item: Record<string, unknown>): string => {
|
||||
return String(item[itemIdKey] ?? '');
|
||||
}, [itemIdKey]);
|
||||
|
||||
// 폼 컨텍스트 연결
|
||||
useEffect(() => {
|
||||
if (name) {
|
||||
const g7Core = getG7Core();
|
||||
if (g7Core?.form) {
|
||||
formContextRef.current = g7Core.form;
|
||||
}
|
||||
}
|
||||
}, [name]);
|
||||
|
||||
// 센서 설정
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: {
|
||||
distance: 8,
|
||||
},
|
||||
}),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
})
|
||||
);
|
||||
|
||||
// 아이템 ID 목록 (안정적인 ID 사용)
|
||||
const itemIds = useMemo(() => {
|
||||
return normalizedItems.map((item) => getStableId(item));
|
||||
}, [normalizedItems, getStableId]);
|
||||
|
||||
// 드래그 종료 핸들러
|
||||
const handleDragEnd = useCallback(
|
||||
(event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
|
||||
if (over && active.id !== over.id) {
|
||||
const currentItems = pendingItemsRef.current ?? normalizedItemsRef.current;
|
||||
const currentIds = currentItems.map((item) => String(item[itemIdKey] ?? ''));
|
||||
const oldIndex = currentIds.indexOf(String(active.id));
|
||||
const newIndex = currentIds.indexOf(String(over.id));
|
||||
|
||||
if (oldIndex !== -1 && newIndex !== -1) {
|
||||
const newItems = arrayMove([...currentItems], oldIndex, newIndex);
|
||||
pendingItemsRef.current = newItems;
|
||||
onChange?.(newItems);
|
||||
onReorder?.(newItems);
|
||||
}
|
||||
}
|
||||
},
|
||||
[onChange, onReorder, itemIdKey]
|
||||
);
|
||||
|
||||
// 아이템 값 변경 핸들러 (pendingItemsRef로 빠른 연속 편집 시 stale closure 방지)
|
||||
const handleItemValueChange = useCallback(
|
||||
(index: number, key: string, value: unknown) => {
|
||||
const currentItems = pendingItemsRef.current ?? normalizedItemsRef.current;
|
||||
const newItems = [...currentItems];
|
||||
newItems[index] = {
|
||||
...newItems[index],
|
||||
[key]: value,
|
||||
};
|
||||
pendingItemsRef.current = newItems;
|
||||
onChange?.(newItems);
|
||||
},
|
||||
[onChange]
|
||||
);
|
||||
|
||||
// 아이템 추가 핸들러
|
||||
const handleAddItem = useCallback(() => {
|
||||
const currentItems = pendingItemsRef.current ?? normalizedItemsRef.current;
|
||||
if (maxItems && currentItems.length >= maxItems) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (onAddItem) {
|
||||
onAddItem();
|
||||
return;
|
||||
}
|
||||
|
||||
const newItem = createDefaultItem
|
||||
? createDefaultItem()
|
||||
: createDefaultItemFromColumns(columns);
|
||||
|
||||
// 고유 ID 확보
|
||||
if (!newItem[itemIdKey]) {
|
||||
newItem[itemIdKey] = generateId();
|
||||
}
|
||||
|
||||
const newItems = [...currentItems, newItem];
|
||||
pendingItemsRef.current = newItems;
|
||||
onChange?.(newItems);
|
||||
}, [maxItems, onAddItem, createDefaultItem, columns, itemIdKey, onChange]);
|
||||
|
||||
// 아이템 삭제 핸들러
|
||||
const handleRemoveItem = useCallback(
|
||||
(index: number) => {
|
||||
const currentItems = pendingItemsRef.current ?? normalizedItemsRef.current;
|
||||
if (currentItems.length <= minItems) {
|
||||
return;
|
||||
}
|
||||
|
||||
const item = currentItems[index];
|
||||
if (onRemoveItem) {
|
||||
onRemoveItem(index, item);
|
||||
return;
|
||||
}
|
||||
|
||||
const newItems = currentItems.filter((_, i) => i !== index);
|
||||
pendingItemsRef.current = newItems;
|
||||
onChange?.(newItems);
|
||||
},
|
||||
[minItems, onRemoveItem, onChange]
|
||||
);
|
||||
|
||||
// 삭제 가능 여부
|
||||
const canRemove = normalizedItems.length > minItems;
|
||||
|
||||
// 추가 가능 여부
|
||||
const canAdd = !maxItems || normalizedItems.length < maxItems;
|
||||
|
||||
return (
|
||||
<Div className={`dynamic-field-list ${className}`}>
|
||||
{/* 헤더 */}
|
||||
<Div
|
||||
className={`flex items-center gap-2 py-2 px-2 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 rounded-t-lg ${headerClassName}`}
|
||||
>
|
||||
{/* 드래그 핸들 자리 */}
|
||||
{enableDrag && !readOnly && <Div className="flex-shrink-0 w-6" />}
|
||||
|
||||
{/* 순번 헤더 */}
|
||||
{showIndex && (
|
||||
<Div className="flex-shrink-0 w-8 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
|
||||
#
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 컬럼 헤더 */}
|
||||
{columns.map((column) => (
|
||||
<Div
|
||||
key={column.key}
|
||||
className={`flex-1 min-w-0 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase ${column.width || ''}`}
|
||||
style={column.width ? { flex: 'none', width: column.width } : {}}
|
||||
>
|
||||
{column.label}
|
||||
{column.required && (
|
||||
<Span className="text-red-500 dark:text-red-400 ml-0.5">*</Span>
|
||||
)}
|
||||
</Div>
|
||||
))}
|
||||
|
||||
{/* 액션 헤더 자리 */}
|
||||
{(rowActions || (!readOnly && canRemove)) && (
|
||||
<Div className="flex-shrink-0 w-8" />
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 아이템 목록 */}
|
||||
{normalizedItems.length > 0 ? (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={itemIds} strategy={verticalListSortingStrategy}>
|
||||
<Div className="border-x border-gray-200 dark:border-gray-700">
|
||||
{normalizedItems.map((item, index) => {
|
||||
const itemId = getStableId(item);
|
||||
const itemErrors = extractErrorsForIndex(errors, index);
|
||||
|
||||
return (
|
||||
<DynamicFieldListItem
|
||||
key={itemId}
|
||||
id={itemId}
|
||||
item={item}
|
||||
index={index}
|
||||
columns={columns}
|
||||
enableDrag={enableDrag}
|
||||
showIndex={showIndex}
|
||||
canRemove={canRemove}
|
||||
rowActions={rowActions}
|
||||
readOnly={readOnly}
|
||||
onValueChange={(key, value) => handleItemValueChange(index, key, value)}
|
||||
onRemove={() => handleRemoveItem(index)}
|
||||
className={rowClassName}
|
||||
errors={itemErrors}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
) : (
|
||||
<Div className="border-x border-gray-200 dark:border-gray-700 py-8 text-center text-gray-500 dark:text-gray-400 text-sm">
|
||||
{emptyMessage}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 항목 추가 버튼 */}
|
||||
{!readOnly && canAdd && (
|
||||
<Div className="relative border border-gray-200 dark:border-gray-700 border-t-0 rounded-b-lg">
|
||||
{/* 가로줄 중앙 버튼 스타일 */}
|
||||
<Div className="flex items-center justify-center py-2">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleAddItem}
|
||||
className="flex items-center gap-1.5 px-4 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
|
||||
>
|
||||
<Icon name="plus" className="w-4 h-4" />
|
||||
<Span>{addLabel}</Span>
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 읽기 전용 모드에서 하단 border 처리 */}
|
||||
{(readOnly || !canAdd) && normalizedItems.length > 0 && (
|
||||
<Div className="border-x border-b border-gray-200 dark:border-gray-700 rounded-b-lg h-1" />
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DynamicFieldList;
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
/**
|
||||
* DynamicFieldListItem 컴포넌트
|
||||
*
|
||||
* 동적 필드 목록의 개별 행을 렌더링합니다.
|
||||
* @dnd-kit의 useSortable 훅을 사용하여 드래그 앤 드롭을 지원합니다.
|
||||
*/
|
||||
|
||||
import React, { useCallback } from 'react';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Div } from '../../basic/Div';
|
||||
import { Input } from '../../basic/Input';
|
||||
import { Select } from '../../basic/Select';
|
||||
import { Textarea } from '../../basic/Textarea';
|
||||
import { Button } from '../../basic/Button';
|
||||
import { Icon } from '../../basic/Icon';
|
||||
import { Span } from '../../basic/Span';
|
||||
import { useCurrentMultilingualLocale } from '../MultilingualLocaleContext';
|
||||
import type { DynamicFieldListItemProps, DynamicFieldColumn } from './types';
|
||||
|
||||
// G7Core 전역 객체 접근 (에러 처리용)
|
||||
const getG7Core = () => (window as any).G7Core;
|
||||
|
||||
/**
|
||||
* 다국어 입력 컴포넌트 (간소화 버전)
|
||||
*
|
||||
* MultilingualTabPanel 내부에서 사용 시 Context를 통해 로케일을 받습니다.
|
||||
* Context 외부에서 사용 시 G7Core.locale.current()를 fallback으로 사용합니다.
|
||||
*/
|
||||
const MultilingualCellInput: React.FC<{
|
||||
value: Record<string, string> | string;
|
||||
onChange: (value: Record<string, string>) => void;
|
||||
placeholder?: string;
|
||||
readOnly?: boolean;
|
||||
disabled?: boolean;
|
||||
hasError?: boolean;
|
||||
}> = ({ value, onChange, placeholder, readOnly, disabled, hasError }) => {
|
||||
// Context를 통해 로케일 접근 (Stale Closure 방지)
|
||||
const { activeLocale, getActiveLocale } = useCurrentMultilingualLocale();
|
||||
|
||||
// 문자열이면 현재 로케일 객체로 변환
|
||||
const multiValue: Record<string, string> =
|
||||
typeof value === 'string' ? { [activeLocale]: value } : value || {};
|
||||
|
||||
// Stale Closure 방지: 이벤트 핸들러에서는 getActiveLocale() 사용
|
||||
const handleChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const currentLocale = getActiveLocale();
|
||||
onChange({
|
||||
...multiValue,
|
||||
[currentLocale]: e.target.value,
|
||||
});
|
||||
},
|
||||
[multiValue, getActiveLocale, onChange]
|
||||
);
|
||||
|
||||
// 에러 시 적용할 border 클래스
|
||||
const errorBorderClass = hasError
|
||||
? 'border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500'
|
||||
: 'border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500';
|
||||
|
||||
// 렌더링에서는 activeLocale 직접 사용 (React 리렌더링 보장)
|
||||
return (
|
||||
<Input
|
||||
type="text"
|
||||
value={multiValue[activeLocale] || ''}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
readOnly={readOnly}
|
||||
disabled={disabled}
|
||||
className={`w-full px-3 py-2 text-sm border ${errorBorderClass} rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2`}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 아이템 필드 기반 조건부 readOnly 평가
|
||||
* @param item 아이템 데이터
|
||||
* @param condition 조건 문자열 ("!" prefix로 부정 가능, 예: "!is_custom")
|
||||
* @returns readOnly 여부
|
||||
*/
|
||||
const getReadOnlyFromCondition = (
|
||||
item: Record<string, unknown>,
|
||||
condition?: string
|
||||
): boolean => {
|
||||
if (!condition) return false;
|
||||
const negate = condition.startsWith('!');
|
||||
const field = negate ? condition.slice(1) : condition;
|
||||
const value = !!item[field];
|
||||
return negate ? !value : value;
|
||||
};
|
||||
|
||||
/**
|
||||
* 셀 렌더러
|
||||
*/
|
||||
const CellRenderer: React.FC<{
|
||||
column: DynamicFieldColumn;
|
||||
item: Record<string, unknown>;
|
||||
index: number;
|
||||
onValueChange: (key: string, value: unknown) => void;
|
||||
readOnly?: boolean;
|
||||
error?: string;
|
||||
}> = ({ column, item, index, onValueChange, readOnly, error }) => {
|
||||
const value = item[column.key];
|
||||
const isDisabled = readOnly ||
|
||||
column.readOnly ||
|
||||
getReadOnlyFromCondition(item, column.readOnlyCondition) ||
|
||||
column.disabled;
|
||||
const hasError = !!error;
|
||||
|
||||
// 에러 시 적용할 border 클래스
|
||||
const errorBorderClass = hasError
|
||||
? 'border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500'
|
||||
: 'border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500';
|
||||
|
||||
const handleChange = useCallback(
|
||||
(newValue: unknown) => {
|
||||
onValueChange(column.key, newValue);
|
||||
},
|
||||
[column.key, onValueChange]
|
||||
);
|
||||
|
||||
// 에러 메시지 래퍼
|
||||
const wrapWithError = (inputElement: React.ReactNode) => (
|
||||
<Div className="w-full">
|
||||
{inputElement}
|
||||
{hasError && (
|
||||
<Span className="text-xs text-red-500 dark:text-red-400 mt-1 block">
|
||||
{error}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
|
||||
switch (column.type) {
|
||||
case 'input':
|
||||
return wrapWithError(
|
||||
<Input
|
||||
type="text"
|
||||
value={(value as string) || ''}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
placeholder={column.placeholder}
|
||||
readOnly={isDisabled}
|
||||
disabled={isDisabled}
|
||||
className={`w-full px-3 py-2 text-sm border ${errorBorderClass} rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 ${column.className || ''}`}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'number':
|
||||
return wrapWithError(
|
||||
<Input
|
||||
type="number"
|
||||
value={(value as number) ?? ''}
|
||||
onChange={(e) => handleChange(e.target.value ? Number(e.target.value) : null)}
|
||||
placeholder={column.placeholder}
|
||||
min={column.min}
|
||||
max={column.max}
|
||||
step={column.step}
|
||||
readOnly={isDisabled}
|
||||
disabled={isDisabled}
|
||||
className={`w-full px-3 py-2 text-sm border ${errorBorderClass} rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 ${column.className || ''}`}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'select':
|
||||
return wrapWithError(
|
||||
<Select
|
||||
value={(value as string | number) ?? ''}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
disabled={isDisabled}
|
||||
className={`w-full px-3 py-2 text-sm border ${errorBorderClass} rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 ${column.className || ''}`}
|
||||
>
|
||||
<option value="">선택하세요</option>
|
||||
{column.options?.map((opt) => (
|
||||
<option key={opt.value} value={opt.value} disabled={opt.disabled}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
|
||||
case 'textarea':
|
||||
return wrapWithError(
|
||||
<Textarea
|
||||
value={(value as string) || ''}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
placeholder={column.placeholder}
|
||||
readOnly={isDisabled}
|
||||
disabled={isDisabled}
|
||||
className={`w-full px-3 py-2 text-sm border ${errorBorderClass} rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 resize-none ${column.className || ''}`}
|
||||
rows={2}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'multilingual':
|
||||
return wrapWithError(
|
||||
<MultilingualCellInput
|
||||
value={value as Record<string, string> | string}
|
||||
onChange={(val) => handleChange(val)}
|
||||
placeholder={column.placeholder}
|
||||
readOnly={isDisabled}
|
||||
disabled={isDisabled}
|
||||
hasError={hasError}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'custom':
|
||||
if (column.render) {
|
||||
return <>{column.render(item, index, handleChange)}</>;
|
||||
}
|
||||
return <Span className="text-gray-500 dark:text-gray-400">-</Span>;
|
||||
|
||||
default:
|
||||
return <Span className="text-gray-900 dark:text-white text-sm">{String(value ?? '')}</Span>;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* DynamicFieldListItem 컴포넌트
|
||||
*/
|
||||
/**
|
||||
* 컬럼에 대한 에러 메시지 추출
|
||||
* errors 예: {"name.ko": ["에러 메시지"], "content.ko": ["에러 메시지"]}
|
||||
* multilingual 타입인 경우: "name.ko" 형식에서 현재 로케일에 맞는 에러 반환
|
||||
* 일반 타입인 경우: "name" 키로 에러 반환
|
||||
*/
|
||||
const getErrorForColumn = (
|
||||
errors: Record<string, string[]> | undefined,
|
||||
columnKey: string,
|
||||
columnType: string
|
||||
): string | undefined => {
|
||||
if (!errors) return undefined;
|
||||
|
||||
// multilingual 타입인 경우 현재 로케일의 에러를 찾음
|
||||
if (columnType === 'multilingual') {
|
||||
const g7Core = getG7Core();
|
||||
const currentLocale = g7Core?.locale?.current?.() || 'ko';
|
||||
const key = `${columnKey}.${currentLocale}`;
|
||||
const errorArray = errors[key];
|
||||
return errorArray?.[0];
|
||||
}
|
||||
|
||||
// 일반 타입인 경우
|
||||
const errorArray = errors[columnKey];
|
||||
return errorArray?.[0];
|
||||
};
|
||||
|
||||
export const DynamicFieldListItem: React.FC<DynamicFieldListItemProps> = ({
|
||||
item,
|
||||
index,
|
||||
id,
|
||||
columns,
|
||||
enableDrag = true,
|
||||
showIndex = true,
|
||||
canRemove = true,
|
||||
rowActions,
|
||||
readOnly = false,
|
||||
onValueChange,
|
||||
onRemove,
|
||||
className = '',
|
||||
level = 0,
|
||||
errors,
|
||||
}) => {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id, disabled: !enableDrag || readOnly });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
const handleValueChange = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
onValueChange?.(key, value);
|
||||
},
|
||||
[onValueChange]
|
||||
);
|
||||
|
||||
const handleActionClick = useCallback(
|
||||
(action: { onClick?: (item: Record<string, unknown>, index: number) => void }) => {
|
||||
action.onClick?.(item, index);
|
||||
},
|
||||
[item, index]
|
||||
);
|
||||
|
||||
// 계층 구조 들여쓰기
|
||||
const indentStyle = level > 0 ? { paddingLeft: `${level * 24}px` } : {};
|
||||
|
||||
return (
|
||||
<Div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={`flex items-center gap-2 py-2 px-2 border-b border-gray-100 dark:border-gray-700 last:border-b-0 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors ${isDragging ? 'bg-blue-50 dark:bg-blue-900/20 shadow-lg rounded-lg z-10' : ''} ${className}`}
|
||||
>
|
||||
{/* 드래그 핸들 */}
|
||||
{enableDrag && !readOnly && (
|
||||
<Div
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="flex-shrink-0 w-6 h-6 flex items-center justify-center cursor-grab active:cursor-grabbing text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
style={indentStyle}
|
||||
>
|
||||
<Icon name="grip-vertical" className="w-4 h-4" />
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 순번 */}
|
||||
{showIndex && (
|
||||
<Div className="flex-shrink-0 w-8 text-center text-sm text-gray-500 dark:text-gray-400 font-medium">
|
||||
{index + 1}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 컬럼 데이터 */}
|
||||
{columns.map((column) => {
|
||||
const cellError = getErrorForColumn(errors, column.key, column.type);
|
||||
return (
|
||||
<Div
|
||||
key={column.key}
|
||||
className={`flex-1 min-w-0 ${column.width || ''}`}
|
||||
style={column.width ? { flex: 'none', width: column.width } : {}}
|
||||
>
|
||||
<CellRenderer
|
||||
column={column}
|
||||
item={item}
|
||||
index={index}
|
||||
onValueChange={handleValueChange}
|
||||
readOnly={readOnly}
|
||||
error={cellError}
|
||||
/>
|
||||
</Div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 행 액션 */}
|
||||
{rowActions && rowActions.length > 0 && !readOnly && (
|
||||
<Div className="flex-shrink-0 flex items-center gap-1">
|
||||
{rowActions.map((action) => {
|
||||
const isDisabled =
|
||||
typeof action.disabled === 'function'
|
||||
? action.disabled(item, index)
|
||||
: action.disabled;
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={action.key}
|
||||
type="button"
|
||||
onClick={() => handleActionClick(action)}
|
||||
disabled={isDisabled}
|
||||
className={`p-1.5 rounded transition-colors ${
|
||||
action.danger
|
||||
? 'text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 hover:text-red-600'
|
||||
: 'text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-600 dark:hover:text-gray-300'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
title={action.label}
|
||||
>
|
||||
{action.icon ? (
|
||||
<Icon name={action.icon} className="w-4 h-4" />
|
||||
) : (
|
||||
<Span className="text-xs">{action.label}</Span>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 기본 삭제 버튼 */}
|
||||
{canRemove && !rowActions && !readOnly && (
|
||||
<Div className="flex-shrink-0">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
className="p-1.5 text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-600 dark:hover:text-gray-300 rounded transition-colors"
|
||||
title="삭제"
|
||||
>
|
||||
<Icon name="minus" className="w-4 h-4" />
|
||||
</Button>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DynamicFieldListItem;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* DynamicFieldList 컴포넌트 모듈
|
||||
*
|
||||
* 동적 필드 목록을 관리하는 컴포넌트를 내보냅니다.
|
||||
*/
|
||||
|
||||
export { DynamicFieldList } from './DynamicFieldList';
|
||||
export { DynamicFieldListItem } from './DynamicFieldListItem';
|
||||
export type {
|
||||
ColumnType,
|
||||
SelectOption,
|
||||
DynamicFieldColumn,
|
||||
RowAction,
|
||||
DynamicFieldListProps,
|
||||
DynamicFieldListItemProps,
|
||||
} from './types';
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* DynamicFieldList 타입 정의
|
||||
*
|
||||
* 동적 필드 목록 컴포넌트를 위한 타입들을 정의합니다.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* 컬럼 타입
|
||||
*/
|
||||
export type ColumnType =
|
||||
| 'input'
|
||||
| 'number'
|
||||
| 'select'
|
||||
| 'textarea'
|
||||
| 'multilingual'
|
||||
| 'custom';
|
||||
|
||||
/**
|
||||
* 셀렉트 옵션
|
||||
*/
|
||||
export interface SelectOption {
|
||||
value: string | number;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 컬럼 정의
|
||||
*/
|
||||
export interface DynamicFieldColumn {
|
||||
/** 컬럼 키 (데이터 필드명) */
|
||||
key: string;
|
||||
/** 컬럼 라벨 (헤더에 표시) */
|
||||
label: string;
|
||||
/** 컬럼 타입 */
|
||||
type: ColumnType;
|
||||
/** 컬럼 너비 (Tailwind 클래스 또는 CSS 값) */
|
||||
width?: string;
|
||||
/** 플레이스홀더 */
|
||||
placeholder?: string;
|
||||
/** Select 옵션 (type이 'select'일 때) */
|
||||
options?: SelectOption[];
|
||||
/** 필수 여부 */
|
||||
required?: boolean;
|
||||
/** 최소값 (type이 'number'일 때) */
|
||||
min?: number;
|
||||
/** 최대값 (type이 'number'일 때) */
|
||||
max?: number;
|
||||
/** 단계 (type이 'number'일 때) */
|
||||
step?: number;
|
||||
/** 읽기 전용 여부 */
|
||||
readOnly?: boolean;
|
||||
/** 아이템 필드 기반 조건부 readOnly. "!" prefix로 부정 가능 (예: "!is_custom") */
|
||||
readOnlyCondition?: string;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 커스텀 렌더러 (type이 'custom'일 때) */
|
||||
render?: (
|
||||
item: Record<string, unknown>,
|
||||
index: number,
|
||||
onChange: (value: unknown) => void
|
||||
) => React.ReactNode;
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 액션 정의
|
||||
*/
|
||||
export interface RowAction {
|
||||
/** 액션 키 */
|
||||
key: string;
|
||||
/** 액션 라벨 */
|
||||
label: string;
|
||||
/** 아이콘 이름 */
|
||||
icon?: string;
|
||||
/** 액션 타입 */
|
||||
type?: 'button' | 'dropdown';
|
||||
/** 위험한 액션 여부 (빨간색 스타일) */
|
||||
danger?: boolean;
|
||||
/** 비활성화 조건 */
|
||||
disabled?: boolean | ((item: Record<string, unknown>, index: number) => boolean);
|
||||
/** 클릭 핸들러 */
|
||||
onClick?: (item: Record<string, unknown>, index: number) => void;
|
||||
/** 드롭다운 항목 (type이 'dropdown'일 때) */
|
||||
items?: RowAction[];
|
||||
}
|
||||
|
||||
/**
|
||||
* DynamicFieldList Props
|
||||
*/
|
||||
export interface DynamicFieldListProps {
|
||||
/** 데이터 항목 배열 */
|
||||
items: Record<string, unknown>[];
|
||||
/** 컬럼 정의 */
|
||||
columns: DynamicFieldColumn[];
|
||||
/** 데이터 변경 콜백 */
|
||||
onChange?: (items: Record<string, unknown>[]) => void;
|
||||
/** 항목 추가 콜백 (외부에서 항목 추가 로직 제어) */
|
||||
onAddItem?: () => void;
|
||||
/** 항목 제거 콜백 */
|
||||
onRemoveItem?: (index: number, item: Record<string, unknown>) => void;
|
||||
/** 순서 변경 콜백 */
|
||||
onReorder?: (items: Record<string, unknown>[]) => void;
|
||||
/** 항목 추가 버튼 라벨 */
|
||||
addLabel?: string;
|
||||
/** 드래그 앤 드롭 활성화 */
|
||||
enableDrag?: boolean;
|
||||
/** 순번 표시 */
|
||||
showIndex?: boolean;
|
||||
/** 최소 항목 수 (이 값 이하로 삭제 불가) */
|
||||
minItems?: number;
|
||||
/** 최대 항목 수 (이 값 이상 추가 불가) */
|
||||
maxItems?: number;
|
||||
/** 행 액션 정의 */
|
||||
rowActions?: RowAction[];
|
||||
/** 빈 상태 메시지 */
|
||||
emptyMessage?: string;
|
||||
/** 테이블 스타일 className */
|
||||
className?: string;
|
||||
/** 헤더 className */
|
||||
headerClassName?: string;
|
||||
/** 행 className */
|
||||
rowClassName?: string;
|
||||
/** 폼 필드 이름 (템플릿 엔진 통합용) */
|
||||
name?: string;
|
||||
/** 읽기 전용 모드 */
|
||||
readOnly?: boolean;
|
||||
/** 새 항목 기본값 팩토리 */
|
||||
createDefaultItem?: () => Record<string, unknown>;
|
||||
/** 계층 구조 지원 - 자식 키 */
|
||||
childrenKey?: string;
|
||||
/** 항목별 고유 ID 키 */
|
||||
itemIdKey?: string;
|
||||
/** 검증 에러 객체 (예: {"fields.0.name.ko": ["에러 메시지"], "fields.1.content.ko": ["에러 메시지"]}) */
|
||||
errors?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* DynamicFieldListItem Props
|
||||
*/
|
||||
export interface DynamicFieldListItemProps {
|
||||
/** 아이템 데이터 */
|
||||
item: Record<string, unknown>;
|
||||
/** 아이템 인덱스 */
|
||||
index: number;
|
||||
/** 아이템 고유 ID */
|
||||
id: string | number;
|
||||
/** 컬럼 정의 */
|
||||
columns: DynamicFieldColumn[];
|
||||
/** 드래그 활성화 여부 */
|
||||
enableDrag?: boolean;
|
||||
/** 순번 표시 여부 */
|
||||
showIndex?: boolean;
|
||||
/** 삭제 가능 여부 */
|
||||
canRemove?: boolean;
|
||||
/** 행 액션 */
|
||||
rowActions?: RowAction[];
|
||||
/** 읽기 전용 */
|
||||
readOnly?: boolean;
|
||||
/** 값 변경 핸들러 */
|
||||
onValueChange?: (key: string, value: unknown) => void;
|
||||
/** 삭제 핸들러 */
|
||||
onRemove?: () => void;
|
||||
/** 행 className */
|
||||
className?: string;
|
||||
/** 깊이 레벨 (계층 구조용) */
|
||||
level?: number;
|
||||
/** 해당 행의 컬럼별 에러 (예: {"name.ko": ["에러 메시지"], "content.ko": ["에러 메시지"]}) */
|
||||
errors?: Record<string, string[]>;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H2 } from '../basic/H2';
|
||||
import { P } from '../basic/P';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { Img } from '../basic/Img';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface EmptyStateAction {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
iconName?: IconName;
|
||||
}
|
||||
|
||||
export interface EmptyStateProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
iconName?: IconName;
|
||||
illustrationSrc?: string;
|
||||
illustrationAlt?: string;
|
||||
actions?: EmptyStateAction[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* EmptyState 집합 컴포넌트
|
||||
*
|
||||
* 데이터가 없거나 검색 결과가 없을 때 표시하는 빈 상태 컴포넌트.
|
||||
* icon/illustration, title, description, actions 버튼 배열 지원.
|
||||
*
|
||||
* 기본 컴포넌트 조합:
|
||||
* - Div(컨테이너) > Icon/Img + H2(제목) + P(설명) + Div(액션) > Button[]
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "EmptyState",
|
||||
* "props": {
|
||||
* "title": "검색 결과가 없습니다",
|
||||
* "description": "다른 검색어로 시도해보세요.",
|
||||
* "iconName": "Search",
|
||||
* "actions": [
|
||||
* {"label": "검색 초기화", "variant": "secondary"}
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const EmptyState: React.FC<EmptyStateProps> = ({
|
||||
title,
|
||||
description,
|
||||
iconName,
|
||||
illustrationSrc,
|
||||
illustrationAlt = 'Empty state illustration',
|
||||
actions = [],
|
||||
className = '',
|
||||
}) => {
|
||||
// 버튼 variant별 스타일 매핑
|
||||
const variantClassMap: Record<'primary' | 'secondary' | 'danger' | 'ghost', string> = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
|
||||
secondary: 'bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600 focus:ring-gray-500',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700 focus:ring-red-500',
|
||||
ghost: 'bg-transparent text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-gray-500',
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`flex flex-col items-center justify-center p-8 text-center ${className}`}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
{/* Icon 또는 Illustration */}
|
||||
{illustrationSrc ? (
|
||||
<Img
|
||||
src={illustrationSrc}
|
||||
alt={illustrationAlt}
|
||||
className="w-48 h-48 mb-6 object-contain"
|
||||
/>
|
||||
) : iconName ? (
|
||||
<Div className="mb-6 p-4 rounded-full bg-gray-100 dark:bg-gray-700">
|
||||
<Icon
|
||||
name={iconName}
|
||||
className="w-12 h-12 text-gray-400 dark:text-gray-500"
|
||||
/>
|
||||
</Div>
|
||||
) : null}
|
||||
|
||||
{/* Title */}
|
||||
<H2 className="text-xl font-semibold text-gray-900 dark:text-white mb-2">
|
||||
{title}
|
||||
</H2>
|
||||
|
||||
{/* Description */}
|
||||
{description && (
|
||||
<P className="text-gray-600 dark:text-gray-400 mb-6 max-w-md">
|
||||
{description}
|
||||
</P>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
{actions.length > 0 && (
|
||||
<Div className="flex flex-wrap gap-3 justify-center">
|
||||
{actions.map((action, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
onClick={action.onClick}
|
||||
className={`
|
||||
px-4 py-2 rounded-md font-medium transition-colors
|
||||
focus:outline-none focus:ring-2 focus:ring-offset-2
|
||||
${variantClassMap[action.variant || 'primary']}
|
||||
`}
|
||||
>
|
||||
{action.iconName && (
|
||||
<Icon name={action.iconName} className="w-4 h-4 mr-2 inline-block" />
|
||||
)}
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export type ExtensionType = 'module' | 'plugin';
|
||||
|
||||
/**
|
||||
* 설치된 모듈/플러그인 정보 인터페이스
|
||||
*/
|
||||
export interface ExtensionInfo {
|
||||
identifier: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
version?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export interface ExtensionBadgeProps {
|
||||
/** 확장 타입 (module: 모듈, plugin: 플러그인) */
|
||||
type: ExtensionType;
|
||||
/** 확장 식별자 (예: sirsoft-ecommerce) - 이 값으로 이름을 자동 조회 */
|
||||
identifier?: string;
|
||||
/** 확장 이름 (직접 지정 시 사용, identifier보다 우선) */
|
||||
name?: string;
|
||||
/** 설치된 모듈 목록 (_global.installedModules에서 전달) */
|
||||
installedModules?: ExtensionInfo[];
|
||||
/** 설치된 플러그인 목록 (_global.installedPlugins에서 전달) */
|
||||
installedPlugins?: ExtensionInfo[];
|
||||
/** 추가 클래스명 */
|
||||
className?: string;
|
||||
/** 인라인 스타일 */
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtensionBadge 집합 컴포넌트
|
||||
*
|
||||
* 모듈 또는 플러그인에 의해 추가된 섹션임을 표시하는 배지 컴포넌트입니다.
|
||||
* 카드 또는 섹션의 우측 상단에 배치하여 확장 출처를 표시합니다.
|
||||
*
|
||||
* identifier를 전달하면 installedModules/installedPlugins에서 이름을 자동으로 조회합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Span + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시 (identifier로 이름 자동 조회)
|
||||
* {
|
||||
* "name": "ExtensionBadge",
|
||||
* "props": {
|
||||
* "type": "module",
|
||||
* "identifier": "sirsoft-ecommerce",
|
||||
* "installedModules": "{{_global.installedModules}}"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // 이름 직접 지정
|
||||
* {
|
||||
* "name": "ExtensionBadge",
|
||||
* "props": {
|
||||
* "type": "plugin",
|
||||
* "name": "결제"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const ExtensionBadge: React.FC<ExtensionBadgeProps> = ({
|
||||
type,
|
||||
identifier,
|
||||
name,
|
||||
installedModules = [],
|
||||
installedPlugins = [],
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
// 타입별 아이콘 매핑
|
||||
const typeIcons: Record<ExtensionType, IconName> = {
|
||||
module: IconName.Cubes,
|
||||
plugin: IconName.PuzzlePiece,
|
||||
};
|
||||
|
||||
// 타입별 기본 라벨 매핑 (다국어)
|
||||
const typeLabels: Record<ExtensionType, string> = {
|
||||
module: t('common.module'),
|
||||
plugin: t('common.plugin'),
|
||||
};
|
||||
|
||||
// identifier로 이름 조회
|
||||
const resolvedName = useMemo(() => {
|
||||
// name이 직접 지정되면 우선 사용
|
||||
if (name) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// identifier가 있으면 목록에서 찾기
|
||||
if (identifier) {
|
||||
const extensionList = type === 'module' ? installedModules : installedPlugins;
|
||||
const found = extensionList?.find((ext) => ext.identifier === identifier);
|
||||
if (found) {
|
||||
return found.name;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [name, identifier, type, installedModules, installedPlugins]);
|
||||
|
||||
const displayIcon = typeIcons[type];
|
||||
const displayLabel = resolvedName
|
||||
? `${resolvedName} ${typeLabels[type]}`
|
||||
: typeLabels[type];
|
||||
|
||||
return (
|
||||
<Span
|
||||
className={`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium text-gray-400 dark:text-gray-500 ${className}`}
|
||||
style={style}
|
||||
>
|
||||
<Icon name={displayIcon} className="w-3.5 h-3.5" />
|
||||
<Span>{displayLabel}</Span>
|
||||
</Span>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* FileUploader 컴포넌트 (Re-export)
|
||||
*
|
||||
* 파일 업로드를 위한 통합 컴포넌트입니다.
|
||||
* 분리된 모듈에서 내보내기합니다.
|
||||
*
|
||||
* @module composite/FileUploader
|
||||
*/
|
||||
|
||||
// 메인 컴포넌트
|
||||
export { FileUploader, default } from './FileUploader/index';
|
||||
|
||||
// 하위 컴포넌트
|
||||
export { FileDropZone } from './FileUploader/FileDropZone';
|
||||
export { FileList } from './FileUploader/FileList';
|
||||
export { SortableThumbnailItem } from './FileUploader/SortableThumbnailItem';
|
||||
|
||||
// Context
|
||||
export { FileUploaderProvider, useFileUploaderContext } from './FileUploader/FileUploaderContext';
|
||||
export type { FileUploaderContextValue } from './FileUploader/FileUploaderContext';
|
||||
|
||||
// 훅
|
||||
export { useFileUploader } from './FileUploader/useFileUploader';
|
||||
export type { UseFileUploaderOptions, UseFileUploaderReturn } from './FileUploader/useFileUploader';
|
||||
|
||||
// 타입
|
||||
export type {
|
||||
Attachment,
|
||||
PendingFile,
|
||||
FileUploaderProps,
|
||||
FileUploaderRef,
|
||||
ApiEndpoints,
|
||||
} from './FileUploader/types';
|
||||
|
||||
// 유틸리티
|
||||
export { formatFileSize, extractErrorMessage, getFileIcon, t as fileUploaderT } from './FileUploader/utils';
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* FileDropZone 컴포넌트
|
||||
*
|
||||
* 파일을 드래그 앤 드롭하거나 클릭하여 선택할 수 있는 영역입니다.
|
||||
*
|
||||
* @module composite/FileUploader/FileDropZone
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { Div } from '../../basic/Div';
|
||||
import { P } from '../../basic/P';
|
||||
import { I } from '../../basic/I';
|
||||
|
||||
import { t } from './utils';
|
||||
|
||||
export interface FileDropZoneProps {
|
||||
/** 드래그 오버 상태 */
|
||||
isDragOver: boolean;
|
||||
/** 추가 가능 여부 */
|
||||
canAddMore: boolean;
|
||||
/** 파일 처리 핸들러 */
|
||||
onFiles: (files: FileList) => void;
|
||||
/** 드래그 오버 상태 설정 */
|
||||
setIsDragOver: (value: boolean) => void;
|
||||
/** Input 요소 ref */
|
||||
inputRef: React.RefObject<HTMLInputElement | null>;
|
||||
/** 허용 확장자 */
|
||||
accept?: string;
|
||||
/** 최대 파일 수 */
|
||||
maxFiles: number;
|
||||
/** 최대 파일 크기 (MB) */
|
||||
maxSize: number;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 자식 요소 */
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export const FileDropZone: React.FC<FileDropZoneProps> = ({
|
||||
isDragOver,
|
||||
canAddMore,
|
||||
onFiles,
|
||||
setIsDragOver,
|
||||
inputRef,
|
||||
accept,
|
||||
maxFiles,
|
||||
maxSize,
|
||||
disabled,
|
||||
children,
|
||||
}) => {
|
||||
const isInteractive = canAddMore && !disabled;
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`
|
||||
relative border-2 border-dashed rounded-lg transition-colors
|
||||
${disabled ? 'opacity-60 cursor-not-allowed' : ''}
|
||||
${
|
||||
isDragOver && !disabled
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
|
||||
: 'border-gray-300 dark:border-gray-600'
|
||||
}
|
||||
`}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
if (isInteractive) setIsDragOver(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragOver(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
if (isInteractive) {
|
||||
onFiles(e.dataTransfer.files);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
multiple
|
||||
accept={accept}
|
||||
onChange={(e) => e.target.files && !disabled && onFiles(e.target.files)}
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
{/* 파일이 없을 때: 빈 드롭존 */}
|
||||
{!children && (
|
||||
<Div
|
||||
className={`p-8 text-center transition-colors ${disabled ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50'}`}
|
||||
onClick={() => !disabled && inputRef.current?.click()}
|
||||
>
|
||||
<I className="fa-solid fa-cloud-arrow-up text-4xl text-gray-400 dark:text-gray-500 mb-4" />
|
||||
<P className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{t('attachment.drop_or_click')}
|
||||
</P>
|
||||
<P className="text-xs text-gray-500 dark:text-gray-500 mt-2">
|
||||
{t('attachment.upload_limit', { maxFiles, maxSize })}
|
||||
{accept && ` (${accept})`}
|
||||
</P>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 파일이 있을 때: 자식 요소 렌더링 */}
|
||||
{children}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FileDropZone;
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* FileList 컴포넌트
|
||||
*
|
||||
* 파일 목록을 정렬 가능한 그리드 형태로 표시합니다.
|
||||
*
|
||||
* @module composite/FileUploader/FileList
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
rectSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
|
||||
import { Div } from '../../basic/Div';
|
||||
import { Span } from '../../basic/Span';
|
||||
import { I } from '../../basic/I';
|
||||
|
||||
import { SortableThumbnailItem } from './SortableThumbnailItem';
|
||||
import type { Attachment, PendingFile } from './types';
|
||||
import { t } from './utils';
|
||||
|
||||
export interface FileListProps {
|
||||
/** 모든 파일 목록 (기존 + 대기) */
|
||||
allItems: (Attachment | PendingFile)[];
|
||||
/** 더 추가 가능 여부 */
|
||||
canAddMore: boolean;
|
||||
/** 총 파일 수 */
|
||||
totalCount: number;
|
||||
/** 최대 파일 수 */
|
||||
maxFiles: number;
|
||||
/** 최대 파일 크기 (MB) */
|
||||
maxSize: number;
|
||||
/** 허용 확장자 */
|
||||
accept?: string;
|
||||
/** 파일 삭제 핸들러 */
|
||||
onRemove: (item: PendingFile | Attachment) => void;
|
||||
/** 재시도 핸들러 */
|
||||
onRetry: (pendingFile: PendingFile) => void;
|
||||
/** 이미지 클릭 핸들러 */
|
||||
onImageClick: (item: PendingFile | Attachment) => void;
|
||||
/** 다운로드 핸들러 */
|
||||
onDownload: (item: Attachment) => void;
|
||||
/** 드래그 종료 핸들러 */
|
||||
onDragEnd: (event: DragEndEvent) => void;
|
||||
/** 추가 버튼 클릭 핸들러 */
|
||||
onAddClick: () => void;
|
||||
/** 대표 이미지 선택 기능 활성화 */
|
||||
enablePrimarySelection?: boolean;
|
||||
/** 현재 대표 이미지 식별자 (ID 또는 hash) */
|
||||
primaryFileId?: number | string | null;
|
||||
/** 대표 이미지 변경 핸들러 */
|
||||
onPrimaryChange?: (id: number | string | null) => void;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export const FileList: React.FC<FileListProps> = ({
|
||||
allItems,
|
||||
canAddMore,
|
||||
totalCount,
|
||||
maxFiles,
|
||||
maxSize,
|
||||
accept,
|
||||
onRemove,
|
||||
onRetry,
|
||||
onImageClick,
|
||||
onDownload,
|
||||
onDragEnd,
|
||||
onAddClick,
|
||||
enablePrimarySelection,
|
||||
primaryFileId,
|
||||
onPrimaryChange,
|
||||
disabled,
|
||||
}) => {
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
|
||||
);
|
||||
|
||||
return (
|
||||
<Div className="p-3">
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
|
||||
<SortableContext
|
||||
items={allItems.map((item) => ('hash' in item ? item.hash : item.id))}
|
||||
strategy={rectSortingStrategy}
|
||||
>
|
||||
<Div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
|
||||
{/* 파일 썸네일들 */}
|
||||
{allItems.map((item) => {
|
||||
const isExisting = 'hash' in item;
|
||||
// 기존 첨부파일: is_image 필드 우선 사용, 대기 파일: mime_type 확인
|
||||
const isImage = isExisting
|
||||
? (item as Attachment).is_image
|
||||
: (item.mime_type?.startsWith('image/') ?? false);
|
||||
|
||||
return (
|
||||
<SortableThumbnailItem
|
||||
key={isExisting ? item.hash : item.id}
|
||||
file={item}
|
||||
onRemove={() => onRemove(item)}
|
||||
onRetry={
|
||||
'status' in item && item.status === 'error'
|
||||
? () => onRetry(item as PendingFile)
|
||||
: undefined
|
||||
}
|
||||
onImageClick={
|
||||
isImage ? () => onImageClick(item) : undefined
|
||||
}
|
||||
onDownload={
|
||||
isExisting ? () => onDownload(item as Attachment) : undefined
|
||||
}
|
||||
isPrimary={enablePrimarySelection && isExisting && ((item as Attachment).hash || (item as Attachment).id) === primaryFileId}
|
||||
onPrimaryClick={
|
||||
enablePrimarySelection && isExisting
|
||||
? () => onPrimaryChange?.((item as Attachment).hash || (item as Attachment).id)
|
||||
: undefined
|
||||
}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 추가 버튼 (더 추가할 수 있고, 비활성화 아닐 때만) */}
|
||||
{canAddMore && !disabled && (
|
||||
<Div
|
||||
className="aspect-square flex flex-col items-center justify-center border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer hover:border-gray-400 dark:hover:border-gray-500 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors"
|
||||
onClick={onAddClick}
|
||||
>
|
||||
<I className="fa-solid fa-plus text-2xl text-gray-400 dark:text-gray-500 mb-1" />
|
||||
<Span className="text-xs text-gray-500 dark:text-gray-400">{t('common.add')}</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
{/* 하단 정보 */}
|
||||
<Div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center text-xs text-gray-500 dark:text-gray-400">
|
||||
<Span>{t('attachment.attached_count', { count: totalCount, max: maxFiles })}</Span>
|
||||
<Span>{t('attachment.max_size', { size: maxSize })}{accept && ` (${accept})`}</Span>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FileList;
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* FileUploader 컴포넌트
|
||||
*
|
||||
* 파일 업로드를 위한 통합 컴포넌트입니다.
|
||||
* - 드래그 앤 드롭 지원
|
||||
* - 이미지 압축
|
||||
* - 병렬 업로드
|
||||
* - 순서 변경
|
||||
* - 이미지 갤러리
|
||||
*
|
||||
* @module composite/FileUploader
|
||||
*/
|
||||
|
||||
import { forwardRef, useImperativeHandle, useMemo } from 'react';
|
||||
|
||||
import { Div } from '../../basic/Div';
|
||||
import { ConfirmDialog } from '../ConfirmDialog';
|
||||
import { ImageGallery, GalleryImage } from '../ImageGallery';
|
||||
|
||||
import { FileUploaderProvider } from './FileUploaderContext';
|
||||
import { useFileUploader } from './useFileUploader';
|
||||
import { FileDropZone } from './FileDropZone';
|
||||
import { FileList } from './FileList';
|
||||
import type { FileUploaderProps, FileUploaderRef, Attachment, PendingFile } from './types';
|
||||
import { t } from './utils';
|
||||
|
||||
// ========== Main Component ==========
|
||||
|
||||
export const FileUploader = forwardRef<FileUploaderRef, FileUploaderProps>(
|
||||
(
|
||||
{
|
||||
uploadTriggerEvent,
|
||||
attachmentableType,
|
||||
attachmentableId,
|
||||
collection = 'default',
|
||||
maxFiles = 10,
|
||||
maxSize = 10,
|
||||
maxConcurrentUploads = 3,
|
||||
accept,
|
||||
imageCompression: compressionOptions,
|
||||
roleIds = [],
|
||||
autoUpload = true,
|
||||
onFilesChange,
|
||||
onUploadComplete,
|
||||
onUploadError,
|
||||
onRemove,
|
||||
onReorder,
|
||||
initialFiles = [],
|
||||
disabled = false,
|
||||
className = '',
|
||||
confirmBeforeRemove = false,
|
||||
confirmRemoveTitle,
|
||||
confirmRemoveMessage,
|
||||
apiEndpoints,
|
||||
uploadParams,
|
||||
enablePrimarySelection = false,
|
||||
primaryFileId,
|
||||
onPrimaryChange,
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
// API 엔드포인트 기본값 설정
|
||||
const endpoints = {
|
||||
upload: apiEndpoints?.upload ?? '/api/admin/attachments',
|
||||
delete: apiEndpoints?.delete ?? '/api/admin/attachments/:id',
|
||||
reorder: apiEndpoints?.reorder ?? '/api/admin/attachments/reorder',
|
||||
};
|
||||
|
||||
// 핵심 로직 훅 사용
|
||||
const uploader = useFileUploader({
|
||||
attachmentableType,
|
||||
attachmentableId,
|
||||
collection,
|
||||
maxFiles,
|
||||
maxSize,
|
||||
maxConcurrentUploads,
|
||||
accept,
|
||||
imageCompression: compressionOptions,
|
||||
roleIds,
|
||||
autoUpload,
|
||||
initialFiles,
|
||||
endpoints,
|
||||
onFilesChange,
|
||||
onUploadComplete,
|
||||
onUploadError,
|
||||
onRemove,
|
||||
onReorder,
|
||||
uploadTriggerEvent,
|
||||
confirmBeforeRemove,
|
||||
uploadParams,
|
||||
});
|
||||
|
||||
// 컴포넌트 외부에서 호출 가능한 메서드 노출
|
||||
useImperativeHandle(ref, () => ({
|
||||
uploadAll: uploader.handleUploadAll,
|
||||
clear: uploader.clear,
|
||||
getPendingFiles: uploader.getPendingFiles,
|
||||
}));
|
||||
|
||||
// 갤러리용 이미지 목록 생성
|
||||
const galleryImages: GalleryImage[] = useMemo(() => {
|
||||
return uploader.imageFiles.map((item) => {
|
||||
const isPending = !('hash' in item);
|
||||
const pendingItem = item as PendingFile;
|
||||
const attachmentItem = item as Attachment;
|
||||
|
||||
if (isPending) {
|
||||
// 대기 중인 파일은 로컬 미리보기 사용
|
||||
return {
|
||||
src: pendingItem.preview || '',
|
||||
filename: pendingItem.original_filename,
|
||||
title: pendingItem.original_filename,
|
||||
downloadRequiresAuth: false,
|
||||
};
|
||||
} else {
|
||||
// 기존 첨부파일은 인증된 URL 또는 다운로드 URL 사용
|
||||
const cachedUrl = uploader.authenticatedImageUrls.get(attachmentItem.id);
|
||||
return {
|
||||
src: cachedUrl || attachmentItem.download_url,
|
||||
downloadUrl: attachmentItem.download_url,
|
||||
filename: attachmentItem.original_filename,
|
||||
title: attachmentItem.original_filename,
|
||||
downloadRequiresAuth: true,
|
||||
};
|
||||
}
|
||||
});
|
||||
}, [uploader.imageFiles, uploader.authenticatedImageUrls]);
|
||||
|
||||
// Context 값 생성
|
||||
const contextValue = useMemo(() => ({
|
||||
// 상태
|
||||
existingFiles: uploader.existingFiles,
|
||||
pendingFiles: uploader.pendingFiles,
|
||||
isDragOver: uploader.isDragOver,
|
||||
isDeleting: uploader.isDeleting,
|
||||
|
||||
// 설정
|
||||
maxFiles,
|
||||
maxSize,
|
||||
accept,
|
||||
endpoints,
|
||||
confirmBeforeRemove,
|
||||
|
||||
// 계산된 값
|
||||
totalCount: uploader.totalCount,
|
||||
hasFiles: uploader.hasFiles,
|
||||
canAddMore: uploader.canAddMore,
|
||||
allItems: uploader.allItems,
|
||||
imageFiles: uploader.imageFiles,
|
||||
|
||||
// 액션
|
||||
handleFiles: uploader.handleFiles,
|
||||
handleRemove: uploader.handleRemove,
|
||||
handleRetry: uploader.handleRetry,
|
||||
handleUploadAll: uploader.handleUploadAll,
|
||||
handleOpenGallery: uploader.handleOpenGallery,
|
||||
handleDownload: uploader.handleDownload,
|
||||
handleDragEnd: uploader.handleDragEnd,
|
||||
|
||||
// 드래그 상태 설정
|
||||
setIsDragOver: uploader.setIsDragOver,
|
||||
|
||||
// Input ref
|
||||
inputRef: uploader.inputRef,
|
||||
|
||||
// 갤러리 상태
|
||||
galleryOpen: uploader.galleryOpen,
|
||||
setGalleryOpen: uploader.setGalleryOpen,
|
||||
galleryStartIndex: uploader.galleryStartIndex,
|
||||
galleryKeyRef: uploader.galleryKeyRef,
|
||||
|
||||
// 삭제 확인 모달 상태
|
||||
confirmDialogOpen: uploader.confirmDialogOpen,
|
||||
setConfirmDialogOpen: uploader.setConfirmDialogOpen,
|
||||
itemToDelete: uploader.itemToDelete,
|
||||
executeRemoveAttachment: uploader.executeRemoveAttachment,
|
||||
|
||||
// 인증된 이미지 URL 캐시
|
||||
authenticatedImageUrls: uploader.authenticatedImageUrls,
|
||||
}), [uploader, maxFiles, maxSize, accept, endpoints, confirmBeforeRemove]);
|
||||
|
||||
return (
|
||||
<FileUploaderProvider value={contextValue}>
|
||||
<Div className={className}>
|
||||
{/* 드롭존 + 파일 목록 통합 영역 */}
|
||||
<FileDropZone
|
||||
isDragOver={uploader.isDragOver}
|
||||
canAddMore={uploader.canAddMore}
|
||||
onFiles={uploader.handleFiles}
|
||||
setIsDragOver={uploader.setIsDragOver}
|
||||
inputRef={uploader.inputRef}
|
||||
accept={accept}
|
||||
maxFiles={maxFiles}
|
||||
maxSize={maxSize}
|
||||
disabled={disabled}
|
||||
>
|
||||
{/* 파일이 있을 때만 FileList 렌더링 */}
|
||||
{uploader.hasFiles && (
|
||||
<FileList
|
||||
allItems={uploader.allItems}
|
||||
canAddMore={uploader.canAddMore}
|
||||
totalCount={uploader.totalCount}
|
||||
maxFiles={maxFiles}
|
||||
maxSize={maxSize}
|
||||
accept={accept}
|
||||
onRemove={uploader.handleRemove}
|
||||
onRetry={uploader.handleRetry}
|
||||
onImageClick={uploader.handleOpenGallery}
|
||||
onDownload={uploader.handleDownload}
|
||||
onDragEnd={uploader.handleDragEnd}
|
||||
onAddClick={() => uploader.inputRef.current?.click()}
|
||||
enablePrimarySelection={enablePrimarySelection}
|
||||
primaryFileId={primaryFileId}
|
||||
onPrimaryChange={onPrimaryChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
</FileDropZone>
|
||||
|
||||
{/* 삭제 확인 모달 */}
|
||||
{confirmBeforeRemove && (
|
||||
<ConfirmDialog
|
||||
isOpen={uploader.confirmDialogOpen}
|
||||
onClose={() => {
|
||||
if (!uploader.isDeleting) {
|
||||
uploader.setConfirmDialogOpen(false);
|
||||
}
|
||||
}}
|
||||
title={confirmRemoveTitle ?? t('attachment.delete_confirm_title')}
|
||||
message={confirmRemoveMessage ?? t('attachment.delete_confirm_message')}
|
||||
confirmText={t('common.delete')}
|
||||
confirmButtonVariant="danger"
|
||||
onConfirm={() => {
|
||||
if (uploader.itemToDelete) {
|
||||
uploader.executeRemoveAttachment(uploader.itemToDelete);
|
||||
}
|
||||
}}
|
||||
isLoading={uploader.isDeleting}
|
||||
loadingText={t('attachment.deleting')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 이미지 갤러리 라이트박스 */}
|
||||
{galleryImages.length > 0 && uploader.galleryOpen && (
|
||||
<ImageGallery
|
||||
key={`gallery-${uploader.galleryKeyRef.current}`}
|
||||
images={galleryImages}
|
||||
isOpen={true}
|
||||
onClose={() => uploader.setGalleryOpen(false)}
|
||||
startIndex={uploader.galleryStartIndex}
|
||||
showDownload={true}
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
</FileUploaderProvider>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
FileUploader.displayName = 'FileUploader';
|
||||
|
||||
export default FileUploader;
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* FileUploader Context
|
||||
*
|
||||
* 파일 업로더의 상태와 액션을 공유하는 Context입니다.
|
||||
*
|
||||
* @module composite/FileUploader/FileUploaderContext
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import type { Attachment, PendingFile, ApiEndpoints } from './types';
|
||||
|
||||
// ========== Context Types ==========
|
||||
|
||||
export interface FileUploaderContextValue {
|
||||
// 상태
|
||||
existingFiles: Attachment[];
|
||||
pendingFiles: PendingFile[];
|
||||
isDragOver: boolean;
|
||||
isDeleting: boolean;
|
||||
|
||||
// 설정
|
||||
maxFiles: number;
|
||||
maxSize: number;
|
||||
accept?: string;
|
||||
endpoints: ApiEndpoints;
|
||||
confirmBeforeRemove: boolean;
|
||||
|
||||
// 계산된 값
|
||||
totalCount: number;
|
||||
hasFiles: boolean;
|
||||
canAddMore: boolean;
|
||||
allItems: (Attachment | PendingFile)[];
|
||||
imageFiles: (Attachment | PendingFile)[];
|
||||
|
||||
// 액션
|
||||
handleFiles: (files: FileList) => Promise<void>;
|
||||
handleRemove: (item: PendingFile | Attachment) => Promise<void>;
|
||||
handleRetry: (pendingFile: PendingFile) => void;
|
||||
handleUploadAll: () => Promise<Attachment[]>;
|
||||
handleOpenGallery: (item: PendingFile | Attachment) => void;
|
||||
handleDownload: (item: Attachment) => Promise<void>;
|
||||
handleDragEnd: (event: import('@dnd-kit/core').DragEndEvent) => Promise<void>;
|
||||
|
||||
// 드래그 상태 설정
|
||||
setIsDragOver: (value: boolean) => void;
|
||||
|
||||
// Input ref
|
||||
inputRef: React.RefObject<HTMLInputElement | null>;
|
||||
|
||||
// 갤러리 상태
|
||||
galleryOpen: boolean;
|
||||
setGalleryOpen: (value: boolean) => void;
|
||||
galleryStartIndex: number;
|
||||
galleryKeyRef: React.MutableRefObject<number>;
|
||||
|
||||
// 삭제 확인 모달 상태
|
||||
confirmDialogOpen: boolean;
|
||||
setConfirmDialogOpen: (value: boolean) => void;
|
||||
itemToDelete: Attachment | null;
|
||||
executeRemoveAttachment: (item: Attachment) => Promise<void>;
|
||||
|
||||
// 인증된 이미지 URL 캐시
|
||||
authenticatedImageUrls: Map<number, string>;
|
||||
}
|
||||
|
||||
// ========== Context ==========
|
||||
|
||||
const FileUploaderContext = createContext<FileUploaderContextValue | null>(null);
|
||||
|
||||
/**
|
||||
* FileUploader Context Provider
|
||||
*/
|
||||
export const FileUploaderProvider: React.FC<{
|
||||
value: FileUploaderContextValue;
|
||||
children: React.ReactNode;
|
||||
}> = ({ value, children }) => {
|
||||
return (
|
||||
<FileUploaderContext.Provider value={value}>
|
||||
{children}
|
||||
</FileUploaderContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* FileUploader Context 사용 훅
|
||||
*/
|
||||
export const useFileUploaderContext = (): FileUploaderContextValue => {
|
||||
const context = useContext(FileUploaderContext);
|
||||
if (!context) {
|
||||
throw new Error('useFileUploaderContext must be used within FileUploaderProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export default FileUploaderContext;
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* SortableThumbnailItem 컴포넌트
|
||||
*
|
||||
* 드래그 앤 드롭이 가능한 파일 썸네일 아이템입니다.
|
||||
*
|
||||
* @module composite/FileUploader/SortableThumbnailItem
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
|
||||
import { Div } from '../../basic/Div';
|
||||
import { Button } from '../../basic/Button';
|
||||
import { Span } from '../../basic/Span';
|
||||
import { P } from '../../basic/P';
|
||||
import { I } from '../../basic/I';
|
||||
import { Img } from '../../basic/Img';
|
||||
|
||||
import type { Attachment, PendingFile } from './types';
|
||||
import { getFileIcon, t } from './utils';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:SortableThumbnail')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:SortableThumbnail]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:SortableThumbnail]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:SortableThumbnail]', ...args),
|
||||
};
|
||||
|
||||
export interface SortableThumbnailItemProps {
|
||||
file: PendingFile | (Attachment & { status?: string });
|
||||
onRemove: () => void;
|
||||
onRetry?: () => void;
|
||||
/** 이미지 클릭 시 갤러리 열기 */
|
||||
onImageClick?: () => void;
|
||||
/** 비이미지 파일 클릭/다운로드 시 호출 */
|
||||
onDownload?: () => void;
|
||||
/** 대표 이미지 여부 */
|
||||
isPrimary?: boolean;
|
||||
/** 대표 이미지 설정 클릭 핸들러 */
|
||||
onPrimaryClick?: () => void;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export const SortableThumbnailItem: React.FC<SortableThumbnailItemProps> = ({
|
||||
file,
|
||||
onRemove,
|
||||
onRetry,
|
||||
onImageClick,
|
||||
onDownload,
|
||||
isPrimary,
|
||||
onPrimaryClick,
|
||||
disabled,
|
||||
}) => {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: 'hash' in file ? file.hash : file.id,
|
||||
});
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
const isPending = 'status' in file && file.status !== undefined;
|
||||
const status = isPending ? (file as PendingFile).status : 'done';
|
||||
const isUploading = status === 'uploading';
|
||||
const isCompressing = status === 'compressing';
|
||||
const hasError = status === 'error';
|
||||
const progress = isPending ? (file as PendingFile).progress : 100;
|
||||
const preview = isPending ? (file as PendingFile).preview : undefined;
|
||||
// 기존 첨부파일: is_image 필드 우선 사용, 대기 파일: mime_type 확인
|
||||
const isImage = !isPending
|
||||
? (file as Attachment).is_image
|
||||
: (file.mime_type?.startsWith('image/') ?? false);
|
||||
|
||||
// 인증된 이미지 로딩을 위한 상태
|
||||
const [authenticatedImageUrl, setAuthenticatedImageUrl] = useState<string | undefined>(undefined);
|
||||
const downloadUrl = !isPending && isImage ? (file as Attachment).download_url : undefined;
|
||||
|
||||
// 기존 첨부파일의 경우 인증된 요청으로 이미지 로드
|
||||
useEffect(() => {
|
||||
if (!downloadUrl) {
|
||||
setAuthenticatedImageUrl(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
let isMounted = true;
|
||||
let objectUrl: string | undefined;
|
||||
|
||||
const loadAuthenticatedImage = async () => {
|
||||
try {
|
||||
const blob = await G7Core.api.get(downloadUrl, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
if (isMounted && blob) {
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
setAuthenticatedImageUrl(objectUrl);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to load authenticated image:', error);
|
||||
}
|
||||
};
|
||||
|
||||
loadAuthenticatedImage();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
};
|
||||
}, [downloadUrl]);
|
||||
|
||||
// 기존 첨부파일의 경우 인증된 URL 사용
|
||||
const existingImageUrl = authenticatedImageUrl;
|
||||
|
||||
return (
|
||||
<Div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className="relative group bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden"
|
||||
>
|
||||
{/* 썸네일 영역 */}
|
||||
<Div
|
||||
className={`aspect-square w-full flex items-center justify-center bg-gray-50 dark:bg-gray-900 relative ${
|
||||
(isImage || !isPending) ? 'cursor-pointer' : ''
|
||||
}`}
|
||||
onClick={() => {
|
||||
// 업로드 중/압축 중이면 클릭 무시
|
||||
if (isUploading || isCompressing) return;
|
||||
|
||||
if (isImage && onImageClick) {
|
||||
// 이미지는 갤러리 열기
|
||||
onImageClick();
|
||||
} else if (!isPending && onDownload) {
|
||||
// 비이미지 기존 파일은 다운로드
|
||||
onDownload();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* 이미지 미리보기 */}
|
||||
{(preview || existingImageUrl) ? (
|
||||
<Img
|
||||
src={preview || existingImageUrl}
|
||||
alt={file.original_filename}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
/* 파일 아이콘 */
|
||||
<I className={`fa-solid ${getFileIcon(file.mime_type)} text-4xl text-gray-400 dark:text-gray-500`} />
|
||||
)}
|
||||
|
||||
{/* 업로드/압축 진행률 오버레이 */}
|
||||
{(isUploading || isCompressing) && (
|
||||
<Div className="absolute inset-0 bg-black/50 flex flex-col items-center justify-center">
|
||||
<Div className="w-3/4 h-2 bg-gray-700 rounded-full overflow-hidden">
|
||||
<Div
|
||||
className="h-full bg-blue-500 transition-all"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</Div>
|
||||
<Span className="text-white text-xs mt-1">{progress}%</Span>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 에러 오버레이 */}
|
||||
{hasError && (
|
||||
<Div className="absolute inset-0 bg-red-500/50 flex items-center justify-center">
|
||||
<I className="fa-solid fa-exclamation-triangle text-2xl text-white" />
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 대표 이미지 뱃지 */}
|
||||
{onPrimaryClick && (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onPrimaryClick();
|
||||
}}
|
||||
className={`absolute top-1.5 left-1.5 z-10 p-1 rounded-full transition-colors ${
|
||||
isPrimary
|
||||
? 'bg-yellow-500 text-white'
|
||||
: 'bg-gray-800/50 text-gray-300 hover:bg-yellow-500 hover:text-white opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
title={isPrimary ? t('attachment.primary_image') : t('attachment.set_as_primary')}
|
||||
>
|
||||
<I className="fa-solid fa-star text-xs" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 호버 시 액션 버튼들 (disabled 시 숨김) */}
|
||||
<Div className={`absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors flex items-start justify-end p-1 gap-1 opacity-0 group-hover:opacity-100 ${disabled ? 'hidden' : ''}`}>
|
||||
{/* 드래그 핸들 */}
|
||||
<Button
|
||||
type="button"
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-gray-600 dark:text-gray-300 hover:bg-white cursor-grab active:cursor-grabbing"
|
||||
title={t('attachment.drag_to_reorder')}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<I className="fa-solid fa-grip-vertical text-sm" />
|
||||
</Button>
|
||||
|
||||
{/* 다운로드 버튼 (기존 첨부파일만) */}
|
||||
{!isPending && onDownload && (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDownload();
|
||||
}}
|
||||
className="p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-blue-500 hover:bg-white"
|
||||
title={t('common.download')}
|
||||
>
|
||||
<I className="fa-solid fa-download text-sm" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 재시도 버튼 */}
|
||||
{hasError && onRetry && (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRetry();
|
||||
}}
|
||||
className="p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-orange-500 hover:bg-white"
|
||||
title={t('common.retry')}
|
||||
>
|
||||
<I className="fa-solid fa-arrow-rotate-right text-sm" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 삭제 버튼 */}
|
||||
<Button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
disabled={isUploading || isCompressing}
|
||||
className="p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-red-500 hover:bg-white disabled:opacity-50"
|
||||
title={t('common.delete')}
|
||||
>
|
||||
<I className="fa-solid fa-times text-sm" />
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
|
||||
{/* 파일 정보 */}
|
||||
<Div
|
||||
className={`p-2 ${!isPending && onDownload ? 'cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700' : ''}`}
|
||||
onClick={() => {
|
||||
// 기존 첨부파일만 클릭 시 다운로드
|
||||
if (!isPending && onDownload) {
|
||||
onDownload();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<P className="text-xs font-medium text-gray-900 dark:text-white truncate" title={file.original_filename}>
|
||||
{file.original_filename}
|
||||
</P>
|
||||
<P className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{isPending ? (file as PendingFile).size_formatted : (file as Attachment).size_formatted}
|
||||
</P>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SortableThumbnailItem;
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* FileUploader 모듈
|
||||
*
|
||||
* 파일 업로드 기능을 제공하는 컴포넌트 모듈입니다.
|
||||
*
|
||||
* @module composite/FileUploader
|
||||
*/
|
||||
|
||||
// 메인 컴포넌트
|
||||
export { FileUploader } from './FileUploader';
|
||||
export { default } from './FileUploader';
|
||||
|
||||
// 하위 컴포넌트
|
||||
export { FileDropZone } from './FileDropZone';
|
||||
export { FileList } from './FileList';
|
||||
export { SortableThumbnailItem } from './SortableThumbnailItem';
|
||||
|
||||
// Context
|
||||
export { FileUploaderProvider, useFileUploaderContext } from './FileUploaderContext';
|
||||
export type { FileUploaderContextValue } from './FileUploaderContext';
|
||||
|
||||
// 훅
|
||||
export { useFileUploader } from './useFileUploader';
|
||||
export type { UseFileUploaderOptions, UseFileUploaderReturn } from './useFileUploader';
|
||||
|
||||
// 타입
|
||||
export type {
|
||||
Attachment,
|
||||
PendingFile,
|
||||
FileUploaderProps,
|
||||
FileUploaderRef,
|
||||
ApiEndpoints,
|
||||
} from './types';
|
||||
|
||||
// 유틸리티
|
||||
export { formatFileSize, extractErrorMessage, getFileIcon, t } from './utils';
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* FileUploader 타입 정의
|
||||
*
|
||||
* @module composite/FileUploader/types
|
||||
*/
|
||||
|
||||
// ========== Types ==========
|
||||
|
||||
export interface Attachment {
|
||||
id: number;
|
||||
hash: string;
|
||||
original_filename: string;
|
||||
mime_type: string;
|
||||
size: number;
|
||||
size_formatted: string;
|
||||
download_url: string;
|
||||
order: number;
|
||||
is_image: boolean;
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PendingFile {
|
||||
id: string;
|
||||
file: File;
|
||||
compressedBlob?: Blob;
|
||||
original_filename: string;
|
||||
mime_type: string;
|
||||
size: number;
|
||||
size_formatted: string;
|
||||
preview?: string;
|
||||
status: 'pending' | 'compressing' | 'uploading' | 'done' | 'error';
|
||||
progress: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface FileUploaderProps {
|
||||
/**
|
||||
* 업로드 트리거 이벤트명
|
||||
*
|
||||
* 지정 시 해당 이벤트를 구독하여 업로드를 트리거합니다.
|
||||
* emitEvent 액션 핸들러와 함께 사용합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON에서 FileUploader 설정
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "FileUploader",
|
||||
* "props": {
|
||||
* "uploadTriggerEvent": "upload:site_logo",
|
||||
* "autoUpload": false
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* // 저장 버튼에서 업로드 트리거
|
||||
* {
|
||||
* "handler": "sequence",
|
||||
* "actions": [
|
||||
* { "handler": "emitEvent", "params": { "event": "upload:site_logo" } },
|
||||
* { "handler": "apiCall", "target": "/api/settings", ... }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
uploadTriggerEvent?: string;
|
||||
/** 첨부 대상 모델 타입 */
|
||||
attachmentableType?: string;
|
||||
/** 첨부 대상 ID */
|
||||
attachmentableId?: number;
|
||||
/** 컬렉션명 */
|
||||
collection?: string;
|
||||
/** 최대 첨부 개수 */
|
||||
maxFiles?: number;
|
||||
/** 파일당 최대 크기 (MB) */
|
||||
maxSize?: number;
|
||||
/** 동시 업로드 수 */
|
||||
maxConcurrentUploads?: number;
|
||||
/** 허용 확장자 (예: ".jpg,.png,.pdf") */
|
||||
accept?: string;
|
||||
/** 이미지 압축 옵션 */
|
||||
imageCompression?: {
|
||||
maxSizeMB?: number;
|
||||
maxWidthOrHeight?: number;
|
||||
};
|
||||
/** 접근 가능 역할 ID 배열 */
|
||||
roleIds?: number[];
|
||||
/** 자동 업로드 여부 (false인 경우 uploadTriggerEvent로 업로드 트리거) */
|
||||
autoUpload?: boolean;
|
||||
/** 파일 변경 콜백 */
|
||||
onFilesChange?: (files: PendingFile[]) => void;
|
||||
/** 업로드 완료 콜백 */
|
||||
onUploadComplete?: (attachments: Attachment[]) => void;
|
||||
/** 업로드 에러 콜백 */
|
||||
onUploadError?: (error: string, file: File) => void;
|
||||
/** 삭제 콜백 */
|
||||
onRemove?: (id: number | string) => void;
|
||||
/** 순서 변경 콜백 (reorder 완료 후 정렬된 기존 파일 목록 전달) */
|
||||
onReorder?: (files: Attachment[]) => void;
|
||||
/** 초기 첨부파일 목록 */
|
||||
initialFiles?: Attachment[];
|
||||
/** 비활성화 여부 (읽기 전용 모드) */
|
||||
disabled?: boolean;
|
||||
/** 추가 CSS 클래스 */
|
||||
className?: string;
|
||||
/**
|
||||
* 삭제 전 확인 모달 표시 여부 (기존 첨부파일만 적용)
|
||||
* true: 삭제 확인 모달 표시 후 삭제
|
||||
* false: 즉시 삭제 (기본값)
|
||||
*/
|
||||
confirmBeforeRemove?: boolean;
|
||||
/** 삭제 확인 모달 제목 (다국어 키 또는 문자열) */
|
||||
confirmRemoveTitle?: string;
|
||||
/** 삭제 확인 모달 메시지 (다국어 키 또는 문자열) */
|
||||
confirmRemoveMessage?: string;
|
||||
/**
|
||||
* 업로드 시 추가로 전송할 파라미터
|
||||
*
|
||||
* FormData에 추가 필드를 포함하여 업로드합니다.
|
||||
*
|
||||
* @example
|
||||
* {
|
||||
* "uploadParams": {
|
||||
* "temp_key": "{{_local.ui.imageTempKey}}"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
uploadParams?: Record<string, string>;
|
||||
/**
|
||||
* 대표 파일(이미지) 선택 기능 활성화
|
||||
*
|
||||
* true일 경우 파일 목록에 대표 선택 버튼이 표시됩니다.
|
||||
*/
|
||||
enablePrimarySelection?: boolean;
|
||||
/**
|
||||
* 현재 대표 파일 식별자 (ID 또는 hash)
|
||||
*
|
||||
* enablePrimarySelection이 true일 때 사용됩니다.
|
||||
*/
|
||||
primaryFileId?: number | string | null;
|
||||
/**
|
||||
* 대표 파일 변경 콜백
|
||||
*/
|
||||
onPrimaryChange?: (id: number | string | null) => void;
|
||||
/**
|
||||
* API 엔드포인트 설정 (모듈용 커스터마이징)
|
||||
*
|
||||
* @example
|
||||
* // 모듈에서 커스텀 API 사용
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "FileUploader",
|
||||
* "props": {
|
||||
* "apiEndpoints": {
|
||||
* "upload": "/api/admin/sirsoft-ecommerce/products/attachments",
|
||||
* "delete": "/api/admin/sirsoft-ecommerce/products/attachments/:id",
|
||||
* "reorder": "/api/admin/sirsoft-ecommerce/products/attachments/reorder"
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
apiEndpoints?: {
|
||||
/** 파일 업로드 API (기본값: /api/admin/attachments) */
|
||||
upload?: string;
|
||||
/** 파일 삭제 API - :id를 실제 ID로 치환 (기본값: /api/admin/attachments/:id) */
|
||||
delete?: string;
|
||||
/** 순서 변경 API (기본값: /api/admin/attachments/reorder) */
|
||||
reorder?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface FileUploaderRef {
|
||||
/** 모든 대기 파일 업로드 */
|
||||
uploadAll: () => Promise<Attachment[]>;
|
||||
/** 대기 파일 초기화 */
|
||||
clear: () => void;
|
||||
/** 대기 파일 목록 조회 */
|
||||
getPendingFiles: () => PendingFile[];
|
||||
}
|
||||
|
||||
export interface ApiEndpoints {
|
||||
upload: string;
|
||||
delete: string;
|
||||
reorder: string;
|
||||
}
|
||||
+764
@@ -0,0 +1,764 @@
|
||||
/**
|
||||
* useFileUploader Hook
|
||||
*
|
||||
* FileUploader의 핵심 로직을 담당하는 훅입니다.
|
||||
* - 파일 추가/삭제/업로드
|
||||
* - 이미지 압축
|
||||
* - 병렬 업로드 큐
|
||||
* - 순서 변경
|
||||
*
|
||||
* @module composite/FileUploader/useFileUploader
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:FileUploader')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:FileUploader]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:FileUploader]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:FileUploader]', ...args),
|
||||
};
|
||||
import imageCompression from 'browser-image-compression';
|
||||
|
||||
import type { Attachment, PendingFile, FileUploaderProps, ApiEndpoints } from './types';
|
||||
import { formatFileSize, extractErrorMessage, t } from './utils';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
export interface UseFileUploaderOptions {
|
||||
attachmentableType?: string;
|
||||
attachmentableId?: number;
|
||||
collection: string;
|
||||
maxFiles: number;
|
||||
maxSize: number;
|
||||
maxConcurrentUploads: number;
|
||||
accept?: string;
|
||||
imageCompression?: FileUploaderProps['imageCompression'];
|
||||
roleIds: number[];
|
||||
autoUpload: boolean;
|
||||
initialFiles: Attachment[];
|
||||
endpoints: ApiEndpoints;
|
||||
onFilesChange?: (files: PendingFile[]) => void;
|
||||
onUploadComplete?: (attachments: Attachment[]) => void;
|
||||
onUploadError?: (error: string, file: File) => void;
|
||||
onRemove?: (id: number | string) => void;
|
||||
onReorder?: (files: Attachment[]) => void;
|
||||
uploadTriggerEvent?: string;
|
||||
confirmBeforeRemove: boolean;
|
||||
uploadParams?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface UseFileUploaderReturn {
|
||||
// 상태
|
||||
existingFiles: Attachment[];
|
||||
pendingFiles: PendingFile[];
|
||||
isDragOver: boolean;
|
||||
setIsDragOver: (value: boolean) => void;
|
||||
isDeleting: boolean;
|
||||
|
||||
// 계산된 값
|
||||
totalCount: number;
|
||||
hasFiles: boolean;
|
||||
canAddMore: boolean;
|
||||
allItems: (Attachment | PendingFile)[];
|
||||
imageFiles: (Attachment | PendingFile)[];
|
||||
|
||||
// 액션
|
||||
handleFiles: (files: FileList) => Promise<void>;
|
||||
handleRemove: (item: PendingFile | Attachment) => Promise<void>;
|
||||
handleRetry: (pendingFile: PendingFile) => void;
|
||||
handleUploadAll: () => Promise<Attachment[]>;
|
||||
handleOpenGallery: (item: PendingFile | Attachment) => void;
|
||||
handleDownload: (item: Attachment) => Promise<void>;
|
||||
handleDragEnd: (event: import('@dnd-kit/core').DragEndEvent) => Promise<void>;
|
||||
|
||||
// Input ref
|
||||
inputRef: React.RefObject<HTMLInputElement | null>;
|
||||
|
||||
// 갤러리 상태
|
||||
galleryOpen: boolean;
|
||||
setGalleryOpen: (value: boolean) => void;
|
||||
galleryStartIndex: number;
|
||||
galleryKeyRef: React.MutableRefObject<number>;
|
||||
|
||||
// 삭제 확인 모달 상태
|
||||
confirmDialogOpen: boolean;
|
||||
setConfirmDialogOpen: (value: boolean) => void;
|
||||
itemToDelete: Attachment | null;
|
||||
executeRemoveAttachment: (item: Attachment) => Promise<void>;
|
||||
|
||||
// 인증된 이미지 URL 캐시
|
||||
authenticatedImageUrls: Map<number, string>;
|
||||
|
||||
// 초기화
|
||||
clear: () => void;
|
||||
getPendingFiles: () => PendingFile[];
|
||||
}
|
||||
|
||||
export function useFileUploader(options: UseFileUploaderOptions): UseFileUploaderReturn {
|
||||
const {
|
||||
attachmentableType,
|
||||
attachmentableId,
|
||||
collection,
|
||||
maxFiles,
|
||||
maxSize,
|
||||
maxConcurrentUploads,
|
||||
accept,
|
||||
imageCompression: compressionOptions,
|
||||
roleIds,
|
||||
autoUpload,
|
||||
initialFiles,
|
||||
endpoints,
|
||||
onFilesChange,
|
||||
onUploadComplete,
|
||||
onUploadError,
|
||||
onRemove,
|
||||
onReorder,
|
||||
uploadTriggerEvent,
|
||||
confirmBeforeRemove,
|
||||
uploadParams,
|
||||
} = options;
|
||||
|
||||
// 상태
|
||||
const [existingFiles, setExistingFiles] = useState<Attachment[]>(initialFiles);
|
||||
const [pendingFiles, setPendingFiles] = useState<PendingFile[]>([]);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const activeUploadsRef = useRef(0);
|
||||
// 삭제된 파일 ID 또는 hash를 추적하여 initialFiles 동기화 시 제외
|
||||
const deletedIdsRef = useRef<Set<number | string>>(new Set());
|
||||
// 세션 중 업로드된 파일을 추적하여 initialFiles 동기화 시 유지
|
||||
const uploadedFilesRef = useRef<Map<number, Attachment>>(new Map());
|
||||
|
||||
// 삭제 확인 모달 상태
|
||||
const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
|
||||
const [itemToDelete, setItemToDelete] = useState<Attachment | null>(null);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
// 순서가 변경되었는지 추적 (변경 후에는 initialFiles 동기화 무시)
|
||||
const hasReorderedRef = useRef(false);
|
||||
// 드래그 순서 유지: 기존/신규 파일 간 섞인 순서를 보존하기 위한 ID 배열
|
||||
const [customOrder, setCustomOrder] = useState<(string | number)[]>([]);
|
||||
|
||||
// 이미지 갤러리 상태
|
||||
const [galleryOpen, setGalleryOpen] = useState(false);
|
||||
const [galleryStartIndex, setGalleryStartIndex] = useState(0);
|
||||
// 갤러리 리마운트용 key (열릴 때마다 증가)
|
||||
const galleryKeyRef = useRef(0);
|
||||
// 인증된 이미지 URL 캐시 (기존 첨부파일용)
|
||||
const [authenticatedImageUrls, setAuthenticatedImageUrls] = useState<Map<number, string>>(new Map());
|
||||
|
||||
// onFilesChange를 ref로 관리하여 useEffect 의존성에서 제거
|
||||
// (Form 자동 바인딩이 매 렌더링마다 새 함수 참조를 생성하므로
|
||||
// 의존성에 포함하면 무한 리렌더링 루프 발생)
|
||||
const onFilesChangeRef = useRef(onFilesChange);
|
||||
onFilesChangeRef.current = onFilesChange;
|
||||
|
||||
// 대기 파일 변경 시 콜백
|
||||
useEffect(() => {
|
||||
onFilesChangeRef.current?.(pendingFiles);
|
||||
}, [pendingFiles]);
|
||||
|
||||
// initialFiles prop 변경 시 existingFiles 동기화 (삭제/순서변경된 경우 제외)
|
||||
useEffect(() => {
|
||||
// 순서가 변경된 후에는 initialFiles 동기화를 무시
|
||||
if (hasReorderedRef.current) {
|
||||
return;
|
||||
}
|
||||
const filteredFiles = initialFiles.filter(
|
||||
(file) => !deletedIdsRef.current.has(file.id) && (!file.hash || !deletedIdsRef.current.has(file.hash))
|
||||
);
|
||||
|
||||
// 세션 중 업로드된 파일 병합 (initialFiles에 없는 것만 추가)
|
||||
const initialIds = new Set(filteredFiles.map((f) => f.id));
|
||||
const sessionUploaded = Array.from(uploadedFilesRef.current.values()).filter(
|
||||
(f) => !initialIds.has(f.id) && !deletedIdsRef.current.has(f.id)
|
||||
);
|
||||
|
||||
setExistingFiles([...filteredFiles, ...sessionUploaded]);
|
||||
}, [initialFiles]);
|
||||
|
||||
// 이미지 압축
|
||||
const compressImage = useCallback(
|
||||
async (file: File): Promise<Blob> => {
|
||||
const compressionOpts = {
|
||||
maxSizeMB: compressionOptions?.maxSizeMB ?? 1,
|
||||
maxWidthOrHeight: compressionOptions?.maxWidthOrHeight ?? 1920,
|
||||
useWebWorker: true,
|
||||
};
|
||||
return await imageCompression(file, compressionOpts);
|
||||
},
|
||||
[compressionOptions]
|
||||
);
|
||||
|
||||
// 파일 추가 처리
|
||||
const handleFiles = useCallback(
|
||||
async (selectedFiles: FileList) => {
|
||||
const totalCount = existingFiles.length + pendingFiles.length;
|
||||
const remainingSlots = maxFiles - totalCount;
|
||||
const filesToAdd = Array.from(selectedFiles).slice(0, remainingSlots);
|
||||
|
||||
for (const file of filesToAdd) {
|
||||
// 크기 검증
|
||||
if (file.size > maxSize * 1024 * 1024) {
|
||||
onUploadError?.(
|
||||
`[${file.name}] 파일 크기(${formatFileSize(file.size)})가 최대 허용 크기(${maxSize}MB)를 초과합니다.`,
|
||||
file
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 확장자 검증
|
||||
if (accept) {
|
||||
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
|
||||
const acceptedExts = accept.split(',').map((e) => e.trim().toLowerCase());
|
||||
if (!acceptedExts.includes(ext)) {
|
||||
onUploadError?.(`[${file.name}] 허용되지 않는 파일 형식입니다. (허용: ${accept})`, file);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const pendingFile: PendingFile = {
|
||||
id: `pending-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
file,
|
||||
original_filename: file.name,
|
||||
mime_type: file.type,
|
||||
size: file.size,
|
||||
size_formatted: formatFileSize(file.size),
|
||||
status: 'pending',
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
// 이미지 미리보기 생성
|
||||
if (file.type.startsWith('image/')) {
|
||||
pendingFile.preview = URL.createObjectURL(file);
|
||||
}
|
||||
|
||||
setPendingFiles((prev) => [...prev, pendingFile]);
|
||||
|
||||
// 이미지인 경우 압축 처리
|
||||
if (file.type.startsWith('image/') && compressionOptions) {
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) => (f.id === pendingFile.id ? { ...f, status: 'compressing' } : f))
|
||||
);
|
||||
|
||||
try {
|
||||
const compressedBlob = await compressImage(file);
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === pendingFile.id
|
||||
? {
|
||||
...f,
|
||||
compressedBlob,
|
||||
size: compressedBlob.size,
|
||||
size_formatted: formatFileSize(compressedBlob.size),
|
||||
status: 'pending',
|
||||
progress: 0,
|
||||
}
|
||||
: f
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === pendingFile.id
|
||||
? { ...f, status: 'error', error: '이미지 압축 실패' }
|
||||
: f
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
[existingFiles.length, pendingFiles.length, maxFiles, maxSize, accept, compressionOptions, compressImage, onUploadError]
|
||||
);
|
||||
|
||||
// 단일 파일 업로드
|
||||
const uploadSingleFile = useCallback(
|
||||
async (pendingFile: PendingFile): Promise<Attachment | null> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// 압축된 Blob 또는 원본 파일
|
||||
const fileToUpload = pendingFile.compressedBlob
|
||||
? new File([pendingFile.compressedBlob], pendingFile.original_filename, {
|
||||
type: pendingFile.mime_type,
|
||||
})
|
||||
: pendingFile.file;
|
||||
|
||||
formData.append('file', fileToUpload);
|
||||
|
||||
if (attachmentableType) {
|
||||
formData.append('attachmentable_type', attachmentableType);
|
||||
}
|
||||
if (attachmentableId) {
|
||||
formData.append('attachmentable_id', String(attachmentableId));
|
||||
}
|
||||
formData.append('collection', collection);
|
||||
|
||||
roleIds.forEach((roleId) => {
|
||||
formData.append('role_ids[]', String(roleId));
|
||||
});
|
||||
|
||||
// 추가 업로드 파라미터 (예: temp_key)
|
||||
if (uploadParams) {
|
||||
Object.entries(uploadParams).forEach(([key, value]) => {
|
||||
formData.append(key, value);
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await G7Core.api.post(endpoints.upload, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
onUploadProgress: (progressEvent: { loaded: number; total?: number }) => {
|
||||
const progress = Math.round((progressEvent.loaded * 100) / (progressEvent.total ?? 1));
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) => (f.id === pendingFile.id ? { ...f, progress } : f))
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// ResponseHelper 이중 래핑 대응: response.data.data (래핑) 또는 response.data (비래핑)
|
||||
const attachment = response?.data?.data ?? response?.data;
|
||||
return attachment as Attachment;
|
||||
} catch (error: unknown) {
|
||||
// API 에러 응답에서 상세 메시지 추출
|
||||
const errorMessage = extractErrorMessage(error);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
},
|
||||
[attachmentableType, attachmentableId, collection, roleIds, endpoints.upload]
|
||||
);
|
||||
|
||||
// 모든 파일 업로드
|
||||
const handleUploadAll = useCallback(async (): Promise<Attachment[]> => {
|
||||
const filesToUpload = pendingFiles.filter(
|
||||
(f) => f.status === 'pending' || f.status === 'error'
|
||||
);
|
||||
|
||||
if (filesToUpload.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const uploadedAttachments: Attachment[] = [];
|
||||
// 드래그 순서 복원용: pending ID → 업로드된 hash 매핑
|
||||
const pendingToHashMap = new Map<string, string>();
|
||||
const uploadQueue = [...filesToUpload];
|
||||
|
||||
const processQueue = async () => {
|
||||
while (uploadQueue.length > 0 && activeUploadsRef.current < maxConcurrentUploads) {
|
||||
const pendingFile = uploadQueue.shift()!;
|
||||
activeUploadsRef.current++;
|
||||
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) => (f.id === pendingFile.id ? { ...f, status: 'uploading', progress: 0 } : f))
|
||||
);
|
||||
|
||||
try {
|
||||
const attachment = await uploadSingleFile(pendingFile);
|
||||
if (attachment) {
|
||||
uploadedAttachments.push(attachment);
|
||||
// 드래그 순서 복원용: pending ID → 업로드된 hash 매핑
|
||||
pendingToHashMap.set(String(pendingFile.id), String(attachment.hash));
|
||||
// 세션 중 업로드된 파일 추적 (initialFiles 동기화 시 유지)
|
||||
uploadedFilesRef.current.set(attachment.id, attachment);
|
||||
setPendingFiles((prev) => prev.filter((f) => f.id !== pendingFile.id));
|
||||
setExistingFiles((prev) => [...prev, attachment]);
|
||||
|
||||
// customOrder에 pending ID가 있으면 즉시 hash로 교체
|
||||
// → allItems useMemo가 올바른 순서로 E를 표시 (UI 플래시 방지)
|
||||
setCustomOrder((prev) => {
|
||||
if (prev.length === 0) return prev;
|
||||
const pendingId = String(pendingFile.id);
|
||||
const hasMatch = prev.some((id) => String(id) === pendingId);
|
||||
if (!hasMatch) return prev;
|
||||
return prev.map((id) => String(id) === pendingId ? String(attachment.hash) : id);
|
||||
});
|
||||
|
||||
// 미리보기 URL 해제
|
||||
if (pendingFile.preview) {
|
||||
URL.revokeObjectURL(pendingFile.preview);
|
||||
}
|
||||
} else {
|
||||
// 업로드 API 성공이지만 응답 파싱 실패 → 에러 상태로 전환 ('uploading' 영구 잔류 방지)
|
||||
const invalidMsg = t('attachment.upload_response_invalid');
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === pendingFile.id
|
||||
? { ...f, status: 'error', error: invalidMsg }
|
||||
: f
|
||||
)
|
||||
);
|
||||
onUploadError?.(
|
||||
`[${pendingFile.original_filename}] ${invalidMsg}`,
|
||||
pendingFile.file
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : '업로드 실패';
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === pendingFile.id ? { ...f, status: 'error', error: errorMessage } : f
|
||||
)
|
||||
);
|
||||
onUploadError?.(`[${pendingFile.original_filename}] ${errorMessage}`, pendingFile.file);
|
||||
} finally {
|
||||
activeUploadsRef.current--;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 병렬 업로드 시작
|
||||
const workers = Array(Math.min(maxConcurrentUploads, filesToUpload.length))
|
||||
.fill(null)
|
||||
.map(() => processQueue());
|
||||
|
||||
await Promise.all(workers);
|
||||
|
||||
if (uploadedAttachments.length > 0) {
|
||||
onUploadComplete?.(uploadedAttachments);
|
||||
|
||||
// 편집 모드(reorder 엔드포인트 존재)에서 드래그 순서가 있는 경우에만 onReorder 호출
|
||||
// → form.images를 올바른 순서로 덮어쓰기 (onUploadComplete의 append 순서를 교정)
|
||||
// 복사/생성 모드에서는 호출하지 않음 (linkTempImages가 별도 처리하므로 중복 방지)
|
||||
// NOTE: customOrder의 pending ID→hash 교체는 processQueue 내에서 즉시 처리됨
|
||||
if (endpoints.reorder && customOrder.length > 0 && onReorder) {
|
||||
const allExisting = [...existingFiles, ...uploadedAttachments];
|
||||
|
||||
// pending ID를 업로드된 hash로 교체 (이미 setCustomOrder로 갱신되었지만, 클로저 값 기준 재계산)
|
||||
const updatedOrder = customOrder.map((id) => {
|
||||
const hash = pendingToHashMap.get(String(id));
|
||||
return hash ?? id;
|
||||
});
|
||||
|
||||
const orderMap = new Map(updatedOrder.map((id, idx) => [String(id), idx]));
|
||||
const ordered = [...allExisting]
|
||||
.sort((a, b) => {
|
||||
const aOrder = orderMap.get(String(a.hash)) ?? allExisting.length;
|
||||
const bOrder = orderMap.get(String(b.hash)) ?? allExisting.length;
|
||||
return aOrder - bOrder;
|
||||
})
|
||||
.map((item, idx) => ({ ...item, sort_order: idx, order: idx + 1 }));
|
||||
|
||||
onReorder(ordered);
|
||||
}
|
||||
}
|
||||
|
||||
return uploadedAttachments;
|
||||
}, [pendingFiles, maxConcurrentUploads, uploadSingleFile, onUploadComplete, onUploadError, customOrder, existingFiles, onReorder, endpoints.reorder]);
|
||||
|
||||
// 업로드 트리거 이벤트 구독 (uploadTriggerEvent가 있는 경우)
|
||||
useEffect(() => {
|
||||
if (!uploadTriggerEvent) return;
|
||||
|
||||
const unsubscribe = G7Core.componentEvent.on(uploadTriggerEvent, async () => {
|
||||
// 업로드할 파일이 있으면 업로드, 없으면 기존 파일 ID 반환
|
||||
const uploadedAttachments = await handleUploadAll();
|
||||
return {
|
||||
uploadedAttachments,
|
||||
existingFiles,
|
||||
allFiles: [...existingFiles, ...uploadedAttachments],
|
||||
};
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, [uploadTriggerEvent, handleUploadAll, existingFiles]);
|
||||
|
||||
// autoUpload가 true이고 pendingFiles가 추가되면 자동 업로드
|
||||
useEffect(() => {
|
||||
if (autoUpload && pendingFiles.some((f) => f.status === 'pending')) {
|
||||
handleUploadAll();
|
||||
}
|
||||
}, [autoUpload, pendingFiles, handleUploadAll]);
|
||||
|
||||
// 실제 삭제 실행 (기존 첨부파일)
|
||||
const executeRemoveAttachment = useCallback(
|
||||
async (item: Attachment) => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
// id가 있는 경우만 서버 API 삭제 호출 (복사 모드 등 id 없는 이미지는 로컬 제거만)
|
||||
if (item.id && endpoints.delete) {
|
||||
const deleteUrl = endpoints.delete.replace(':id', String(item.id));
|
||||
await G7Core.api.delete(deleteUrl);
|
||||
}
|
||||
// 삭제 추적 — id와 hash 모두 기록 (복사 모드 이미지는 id 없이 hash만 존재)
|
||||
const itemKey = item.hash || item.id;
|
||||
if (item.id) {
|
||||
deletedIdsRef.current.add(item.id);
|
||||
uploadedFilesRef.current.delete(item.id);
|
||||
}
|
||||
if (item.hash) {
|
||||
deletedIdsRef.current.add(item.hash);
|
||||
}
|
||||
setExistingFiles((prev) => prev.filter((f) => (f.hash || f.id) !== itemKey));
|
||||
onRemove?.(item.hash || item.id);
|
||||
setConfirmDialogOpen(false);
|
||||
setItemToDelete(null);
|
||||
} catch {
|
||||
logger.error('첨부파일 삭제 실패');
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
},
|
||||
[onRemove, endpoints.delete]
|
||||
);
|
||||
|
||||
// 파일 삭제 핸들러 (확인 모달 또는 즉시 삭제)
|
||||
const handleRemove = useCallback(
|
||||
async (item: PendingFile | Attachment) => {
|
||||
if ('hash' in item) {
|
||||
// 기존 첨부파일
|
||||
if (confirmBeforeRemove) {
|
||||
// 확인 모달 표시
|
||||
setItemToDelete(item);
|
||||
setConfirmDialogOpen(true);
|
||||
} else {
|
||||
// 즉시 삭제
|
||||
await executeRemoveAttachment(item);
|
||||
}
|
||||
} else {
|
||||
// 대기 파일 삭제 (확인 없이 즉시)
|
||||
if (item.preview) {
|
||||
URL.revokeObjectURL(item.preview);
|
||||
}
|
||||
setPendingFiles((prev) => prev.filter((f) => f.id !== item.id));
|
||||
}
|
||||
},
|
||||
[confirmBeforeRemove, executeRemoveAttachment]
|
||||
);
|
||||
|
||||
// 재시도 핸들러
|
||||
const handleRetry = useCallback((pendingFile: PendingFile) => {
|
||||
setPendingFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === pendingFile.id ? { ...f, status: 'pending', error: undefined } : f
|
||||
)
|
||||
);
|
||||
}, []);
|
||||
|
||||
// 순서 변경
|
||||
const handleDragEnd = useCallback(
|
||||
async (event: import('@dnd-kit/core').DragEndEvent) => {
|
||||
const { arrayMove } = await import('@dnd-kit/sortable');
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
|
||||
// customOrder 기반으로 시각 순서와 일치하는 allItems 계산
|
||||
// (raw [...existingFiles, ...pendingFiles] 는 시각 순서와 다를 수 있음)
|
||||
const combined = [...existingFiles, ...pendingFiles];
|
||||
let orderedItems: (Attachment | PendingFile)[];
|
||||
if (customOrder.length === 0) {
|
||||
orderedItems = combined;
|
||||
} else {
|
||||
const orderMap = new Map(customOrder.map((id, idx) => [String(id), idx]));
|
||||
orderedItems = [...combined].sort((a, b) => {
|
||||
const aKey = 'hash' in a ? String(a.hash) : String(a.id);
|
||||
const bKey = 'hash' in b ? String(b.hash) : String(b.id);
|
||||
return (orderMap.get(aKey) ?? combined.length) - (orderMap.get(bKey) ?? combined.length);
|
||||
});
|
||||
}
|
||||
|
||||
const oldIndex = orderedItems.findIndex((item) =>
|
||||
'hash' in item ? item.hash === active.id : item.id === active.id
|
||||
);
|
||||
const newIndex = orderedItems.findIndex((item) =>
|
||||
'hash' in item ? item.hash === over.id : item.id === over.id
|
||||
);
|
||||
|
||||
const reordered = arrayMove(orderedItems, oldIndex, newIndex);
|
||||
|
||||
// 드래그 순서 보존 (기존/신규 파일 간 섞인 순서 유지)
|
||||
setCustomOrder(reordered.map((item) => 'hash' in item ? item.hash : item.id));
|
||||
|
||||
// 분리
|
||||
const newExisting = reordered.filter((item): item is Attachment => 'hash' in item);
|
||||
const newPending = reordered.filter((item): item is PendingFile => !('hash' in item));
|
||||
|
||||
// 순서 변경 플래그 설정 (initialFiles 동기화 방지)
|
||||
hasReorderedRef.current = true;
|
||||
|
||||
setExistingFiles(newExisting);
|
||||
setPendingFiles(newPending);
|
||||
|
||||
// sort_order/order 필드를 새 인덱스로 갱신 (form.images 동기화용)
|
||||
const reorderedFiles = newExisting.map((item, idx) => ({
|
||||
...item,
|
||||
sort_order: idx,
|
||||
order: idx + 1,
|
||||
}));
|
||||
|
||||
// 서버에 순서 변경 요청 (기존 파일 + reorder 엔드포인트가 설정된 경우만)
|
||||
if (newExisting.length > 0 && endpoints.reorder) {
|
||||
const orderData = newExisting.map((item, index) => ({
|
||||
id: item.id,
|
||||
order: index + 1,
|
||||
}));
|
||||
|
||||
try {
|
||||
const response = await G7Core.api.patch(endpoints.reorder, { order: orderData });
|
||||
G7Core.toast.success(response.message);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : t('attachment.reorder_failed');
|
||||
G7Core.toast.error(message);
|
||||
}
|
||||
}
|
||||
|
||||
// API 호출 성공/스킵 무관하게 항상 콜백 호출
|
||||
onReorder?.(reorderedFiles);
|
||||
},
|
||||
[existingFiles, pendingFiles, customOrder, endpoints.reorder, onReorder]
|
||||
);
|
||||
|
||||
// 이미지 파일만 필터링 (갤러리용)
|
||||
const imageFiles = useMemo(
|
||||
() =>
|
||||
[...existingFiles, ...pendingFiles].filter((item) => {
|
||||
if ('is_image' in item) {
|
||||
// Attachment (기존 첨부파일) - is_image 필드 우선 사용
|
||||
return (item as Attachment).is_image;
|
||||
}
|
||||
// PendingFile (대기 파일) - mime_type으로 확인
|
||||
return item.mime_type?.startsWith('image/') ?? false;
|
||||
}),
|
||||
[existingFiles, pendingFiles]
|
||||
);
|
||||
|
||||
// 갤러리 열기 (이미지 인덱스로)
|
||||
const handleOpenGallery = useCallback(
|
||||
(item: PendingFile | Attachment) => {
|
||||
// 클릭된 아이템의 인덱스를 imageFiles에서 찾기
|
||||
const imageIndex = imageFiles.findIndex((img) => {
|
||||
// 둘 다 Attachment인 경우 (hash로 비교)
|
||||
if ('hash' in item && 'hash' in img) {
|
||||
return img.hash === item.hash;
|
||||
}
|
||||
// 둘 다 PendingFile인 경우 (id로 비교)
|
||||
if ('id' in item && 'id' in img && !('hash' in item) && !('hash' in img)) {
|
||||
return img.id === item.id;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (imageIndex !== -1) {
|
||||
// 갤러리를 열 때마다 key 증가 (강제 리마운트)
|
||||
galleryKeyRef.current += 1;
|
||||
setGalleryStartIndex(imageIndex);
|
||||
setGalleryOpen(true);
|
||||
}
|
||||
},
|
||||
[imageFiles]
|
||||
);
|
||||
|
||||
// 기존 첨부파일 인증된 이미지 URL 로드 (갤러리용)
|
||||
useEffect(() => {
|
||||
const loadAuthenticatedUrls = async () => {
|
||||
const existingImageFiles = existingFiles.filter((f) => f.mime_type?.startsWith('image/') ?? false);
|
||||
|
||||
for (const file of existingImageFiles) {
|
||||
if (!authenticatedImageUrls.has(file.id)) {
|
||||
try {
|
||||
const blob = await G7Core.api.get(file.download_url, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
if (blob) {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
setAuthenticatedImageUrls((prev) => new Map(prev).set(file.id, objectUrl));
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to load authenticated image:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadAuthenticatedUrls();
|
||||
|
||||
// 클린업: 컴포넌트 언마운트 시 URL 해제
|
||||
return () => {
|
||||
authenticatedImageUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [existingFiles]);
|
||||
|
||||
// 파일 다운로드 실행
|
||||
const handleDownload = useCallback(async (item: Attachment) => {
|
||||
const { executeImageDownload } = await import('../ImageGallery');
|
||||
await executeImageDownload({
|
||||
src: item.download_url,
|
||||
downloadUrl: item.download_url,
|
||||
filename: item.original_filename,
|
||||
downloadRequiresAuth: true,
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 계산된 값 (customOrder가 있으면 드래그 순서 유지, 없으면 기본 순서)
|
||||
const allItems = useMemo(() => {
|
||||
const combined = [...existingFiles, ...pendingFiles];
|
||||
if (customOrder.length === 0) return combined;
|
||||
|
||||
const orderMap = new Map(customOrder.map((id, idx) => [String(id), idx]));
|
||||
return [...combined].sort((a, b) => {
|
||||
const aKey = 'hash' in a ? String(a.hash) : String(a.id);
|
||||
const bKey = 'hash' in b ? String(b.hash) : String(b.id);
|
||||
const aOrder = orderMap.get(aKey) ?? combined.length;
|
||||
const bOrder = orderMap.get(bKey) ?? combined.length;
|
||||
return aOrder - bOrder;
|
||||
});
|
||||
}, [existingFiles, pendingFiles, customOrder]);
|
||||
const totalCount = allItems.length;
|
||||
const hasFiles = totalCount > 0;
|
||||
const canAddMore = totalCount < maxFiles;
|
||||
|
||||
// 초기화 함수들
|
||||
const clear = useCallback(() => setPendingFiles([]), []);
|
||||
const getPendingFiles = useCallback(() => pendingFiles, [pendingFiles]);
|
||||
|
||||
return {
|
||||
// 상태
|
||||
existingFiles,
|
||||
pendingFiles,
|
||||
isDragOver,
|
||||
setIsDragOver,
|
||||
isDeleting,
|
||||
|
||||
// 계산된 값
|
||||
totalCount,
|
||||
hasFiles,
|
||||
canAddMore,
|
||||
allItems,
|
||||
imageFiles,
|
||||
|
||||
// 액션
|
||||
handleFiles,
|
||||
handleRemove,
|
||||
handleRetry,
|
||||
handleUploadAll,
|
||||
handleOpenGallery,
|
||||
handleDownload,
|
||||
handleDragEnd,
|
||||
|
||||
// Input ref
|
||||
inputRef,
|
||||
|
||||
// 갤러리 상태
|
||||
galleryOpen,
|
||||
setGalleryOpen,
|
||||
galleryStartIndex,
|
||||
galleryKeyRef,
|
||||
|
||||
// 삭제 확인 모달 상태
|
||||
confirmDialogOpen,
|
||||
setConfirmDialogOpen,
|
||||
itemToDelete,
|
||||
executeRemoveAttachment,
|
||||
|
||||
// 인증된 이미지 URL 캐시
|
||||
authenticatedImageUrls,
|
||||
|
||||
// 초기화
|
||||
clear,
|
||||
getPendingFiles,
|
||||
};
|
||||
}
|
||||
|
||||
export default useFileUploader;
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* FileUploader 유틸리티 함수
|
||||
*
|
||||
* @module composite/FileUploader/utils
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
/**
|
||||
* 파일 크기를 읽기 쉬운 형식으로 변환합니다.
|
||||
*/
|
||||
export const formatFileSize = (bytes: number): string => {
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let i = 0;
|
||||
let size = bytes;
|
||||
while (size >= 1024 && i < units.length - 1) {
|
||||
size /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${size.toFixed(2)} ${units[i]}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* API 에러 응답에서 상세 메시지를 추출합니다.
|
||||
*/
|
||||
export const extractErrorMessage = (error: unknown): string => {
|
||||
// Axios 에러 응답 구조 처리
|
||||
if (error && typeof error === 'object') {
|
||||
const axiosError = error as {
|
||||
response?: {
|
||||
data?: {
|
||||
message?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
};
|
||||
};
|
||||
message?: string;
|
||||
};
|
||||
|
||||
// API 응답의 message 필드
|
||||
if (axiosError.response?.data?.message) {
|
||||
return axiosError.response.data.message;
|
||||
}
|
||||
|
||||
// Laravel validation 에러 (errors 객체의 첫 번째 메시지)
|
||||
if (axiosError.response?.data?.errors) {
|
||||
const firstError = Object.values(axiosError.response.data.errors)[0];
|
||||
if (Array.isArray(firstError) && firstError[0]) {
|
||||
return firstError[0];
|
||||
}
|
||||
}
|
||||
|
||||
// 일반 에러 메시지
|
||||
if (axiosError.message) {
|
||||
return axiosError.message;
|
||||
}
|
||||
}
|
||||
|
||||
// Error 인스턴스
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return '업로드 실패';
|
||||
};
|
||||
|
||||
/**
|
||||
* MIME 타입에 따른 Font Awesome 아이콘 클래스를 반환합니다.
|
||||
*/
|
||||
export const getFileIcon = (mimeType: string): string => {
|
||||
if (!mimeType) return 'fa-file';
|
||||
if (mimeType.startsWith('image/')) return 'fa-file-image';
|
||||
if (mimeType.startsWith('video/')) return 'fa-file-video';
|
||||
if (mimeType.startsWith('audio/')) return 'fa-file-audio';
|
||||
if (mimeType === 'application/pdf') return 'fa-file-pdf';
|
||||
if (mimeType.includes('word') || mimeType.includes('document')) return 'fa-file-word';
|
||||
if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) return 'fa-file-excel';
|
||||
if (mimeType.includes('zip') || mimeType.includes('compressed')) return 'fa-file-zipper';
|
||||
return 'fa-file';
|
||||
};
|
||||
|
||||
/**
|
||||
* G7Core.t() 번역 함수 참조
|
||||
*/
|
||||
export const t = (key: string, params?: Record<string, string | number>) =>
|
||||
G7Core?.t?.(key, params) ?? key;
|
||||
@@ -0,0 +1,180 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Label } from '../basic/Label';
|
||||
import { Select } from '../basic/Select';
|
||||
import { Checkbox } from '../basic/Checkbox';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export interface FilterOption {
|
||||
id: string | number;
|
||||
label: string;
|
||||
value: string | number;
|
||||
}
|
||||
|
||||
export interface Filter {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'select' | 'checkbox';
|
||||
options: FilterOption[];
|
||||
value?: string | number | string[] | number[];
|
||||
}
|
||||
|
||||
export interface FilterGroupProps {
|
||||
title?: string;
|
||||
filters: Filter[];
|
||||
onChange?: (filterId: string, value: string | number | string[] | number[] | boolean) => void;
|
||||
onReset?: () => void;
|
||||
showResetButton?: boolean;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* FilterGroup 집합 컴포넌트
|
||||
*
|
||||
* 다중 필터 조합을 지원하는 필터 그룹 컴포넌트입니다.
|
||||
* Select, Checkbox 타입의 필터들을 조합하여 표시합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Div + Label + Select + Checkbox + Span + Button
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "FilterGroup",
|
||||
* "props": {
|
||||
* "title": "$t:common.filter",
|
||||
* "filters": [
|
||||
* {
|
||||
* "id": "category",
|
||||
* "label": "카테고리",
|
||||
* "type": "select",
|
||||
* "options": [
|
||||
* {"id": 1, "label": "전자기기", "value": "electronics"},
|
||||
* {"id": 2, "label": "의류", "value": "clothing"}
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const FilterGroup: React.FC<FilterGroupProps> = ({
|
||||
title,
|
||||
filters,
|
||||
onChange,
|
||||
onReset,
|
||||
showResetButton = true,
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
// props로 전달된 값이 없으면 다국어 키 사용
|
||||
const resolvedTitle = title ?? t('common.filter');
|
||||
|
||||
const handleSelectChange = (filterId: string, value: string | number) => {
|
||||
onChange?.(filterId, value);
|
||||
};
|
||||
|
||||
const handleCheckboxChange = (filterId: string, optionValue: string | number, checked: boolean) => {
|
||||
const filter = filters.find(f => f.id === filterId);
|
||||
if (!filter) return;
|
||||
|
||||
const currentValues = Array.isArray(filter.value) ? filter.value : [];
|
||||
|
||||
// 타입에 따라 분리하여 처리
|
||||
if (typeof optionValue === 'string') {
|
||||
const stringValues = currentValues.filter((v): v is string => typeof v === 'string');
|
||||
const newValues = checked
|
||||
? [...stringValues, optionValue]
|
||||
: stringValues.filter(v => v !== optionValue);
|
||||
onChange?.(filterId, newValues);
|
||||
} else {
|
||||
const numberValues = currentValues.filter((v): v is number => typeof v === 'number');
|
||||
const newValues = checked
|
||||
? [...numberValues, optionValue]
|
||||
: numberValues.filter(v => v !== optionValue);
|
||||
onChange?.(filterId, newValues);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`rounded-lg bg-white dark:bg-gray-800 shadow-md border border-gray-200 dark:border-gray-700 p-4 ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{/* 헤더 */}
|
||||
<Div className="flex items-center justify-between mb-4 pb-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<Span className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{resolvedTitle}
|
||||
</Span>
|
||||
{showResetButton && onReset && (
|
||||
<Button
|
||||
onClick={onReset}
|
||||
className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-medium"
|
||||
>
|
||||
{t('common.reset')}
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 필터 목록 */}
|
||||
<Div className="space-y-4">
|
||||
{filters.map((filter) => (
|
||||
<Div key={filter.id} className="space-y-2">
|
||||
<Label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{filter.label}
|
||||
</Label>
|
||||
|
||||
{/* Select 타입 필터 */}
|
||||
{filter.type === 'select' && (
|
||||
<Select
|
||||
value={filter.value as string | number | undefined}
|
||||
onChange={(e) => handleSelectChange(filter.id, e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-blue-500 dark:focus:border-blue-400 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||
>
|
||||
<option value="">{t('common.select_placeholder')}</option>
|
||||
{filter.options.map((option) => (
|
||||
<option key={option.id} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
|
||||
{/* Checkbox 타입 필터 */}
|
||||
{filter.type === 'checkbox' && (
|
||||
<Div className="space-y-2">
|
||||
{filter.options.map((option) => {
|
||||
const isChecked = Array.isArray(filter.value)
|
||||
? filter.value.some(v => v === option.value)
|
||||
: false;
|
||||
|
||||
return (
|
||||
<Label
|
||||
key={option.id}
|
||||
className="flex items-center gap-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-md transition-colors"
|
||||
>
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
onChange={(e) =>
|
||||
handleCheckboxChange(filter.id, option.value, e.target.checked)
|
||||
}
|
||||
className="w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500"
|
||||
/>
|
||||
<Span className="text-sm text-gray-700 dark:text-gray-300">
|
||||
{option.label}
|
||||
</Span>
|
||||
</Label>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import React, { useEffect, useMemo, useState, useCallback } from 'react';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:FilterVisibility')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:FilterVisibility]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:FilterVisibility]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:FilterVisibility]', ...args),
|
||||
};
|
||||
|
||||
/**
|
||||
* 전역 window 타입 확장
|
||||
* 그누보드7 Core의 AuthManager에 접근하기 위한 타입 선언
|
||||
*/
|
||||
declare global {
|
||||
interface Window {
|
||||
G7Core?: {
|
||||
AuthManager?: {
|
||||
getInstance: () => {
|
||||
getUser: () => { uuid: string; [key: string]: any } | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface FilterVisibilitySelectorProps {
|
||||
/** 컴포넌트 고유 ID (localStorage 키 생성에 사용) */
|
||||
id: string;
|
||||
/** 현재 선택된 필터 목록 */
|
||||
visibleFilters?: string[];
|
||||
/** 기본 표시 필터 (localStorage에 값이 없을 때 사용) */
|
||||
defaultFilters?: string[];
|
||||
/** 필터 가시성 변경 시 호출되는 콜백 */
|
||||
onFilterVisibilityChange?: (visibleFilters: string[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* FilterVisibilitySelector 집합 컴포넌트
|
||||
*
|
||||
* 검색 필터의 표시/숨김 설정을 관리하고 localStorage에 저장합니다.
|
||||
* 페이지 로드 시 자동으로 localStorage에서 설정을 불러와 부모 컴포넌트에 전달합니다.
|
||||
*
|
||||
* 이 컴포넌트는 UI를 렌더링하지 않고, 상태 관리 역할만 수행합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "FilterVisibilitySelector",
|
||||
* "props": {
|
||||
* "id": "admin_product_list_filters",
|
||||
* "visibleFilters": "{{_local.visibleFilters}}",
|
||||
* "defaultFilters": ["category", "date", "salesStatus", "displayStatus"]
|
||||
* },
|
||||
* "actions": [
|
||||
* {
|
||||
* "event": "onFilterVisibilityChange",
|
||||
* "type": "change",
|
||||
* "handler": "setState",
|
||||
* "params": {
|
||||
* "target": "_local",
|
||||
* "visibleFilters": "{{$args[0]}}"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const FilterVisibilitySelector: React.FC<FilterVisibilitySelectorProps> = ({
|
||||
id,
|
||||
visibleFilters: externalVisibleFilters,
|
||||
defaultFilters = [],
|
||||
onFilterVisibilityChange,
|
||||
}) => {
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
// 초기화 완료 후 첫 번째 저장을 건너뛰기 위한 ref
|
||||
const skipNextSaveRef = React.useRef(true);
|
||||
|
||||
// 그누보드7 Core의 AuthManager를 통해 현재 로그인한 사용자 ID 가져오기
|
||||
const userId = useMemo(() => {
|
||||
try {
|
||||
const authManager = window.G7Core?.AuthManager?.getInstance();
|
||||
if (authManager) {
|
||||
const user = authManager.getUser();
|
||||
return user?.uuid;
|
||||
}
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// localStorage 키 생성 (g7_filters_{id}_{userId} 형식)
|
||||
const storageKey = useMemo(
|
||||
() => `g7_filters_${id}${userId !== undefined ? `_${userId}` : ''}`,
|
||||
[id, userId]
|
||||
);
|
||||
|
||||
// localStorage에서 저장된 필터 설정 불러오기
|
||||
const getStoredFilters = useCallback((): string[] | null => {
|
||||
try {
|
||||
const stored = localStorage.getItem(storageKey);
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to load from localStorage:', error);
|
||||
}
|
||||
return null;
|
||||
}, [storageKey]);
|
||||
|
||||
// localStorage에 필터 설정 저장
|
||||
const saveToStorage = useCallback(
|
||||
(filters: string[]) => {
|
||||
try {
|
||||
localStorage.setItem(storageKey, JSON.stringify(filters));
|
||||
} catch (error) {
|
||||
logger.warn('Failed to save to localStorage:', error);
|
||||
}
|
||||
},
|
||||
[storageKey]
|
||||
);
|
||||
|
||||
// 초기 필터 결정 (우선순위: localStorage > externalVisibleFilters > defaultFilters)
|
||||
const getInitialFilters = useCallback((): string[] => {
|
||||
// 1. localStorage에서 불러오기
|
||||
const stored = getStoredFilters();
|
||||
if (stored) return stored;
|
||||
|
||||
// 2. 외부에서 전달된 값
|
||||
if (externalVisibleFilters && externalVisibleFilters.length > 0) {
|
||||
return externalVisibleFilters;
|
||||
}
|
||||
|
||||
// 3. 기본 필터 설정
|
||||
return defaultFilters;
|
||||
}, [getStoredFilters, externalVisibleFilters, defaultFilters]);
|
||||
|
||||
// 초기 로드 시 localStorage 값으로 부모 상태 동기화
|
||||
useEffect(() => {
|
||||
if (!isInitialized) {
|
||||
const initialFilters = getInitialFilters();
|
||||
if (onFilterVisibilityChange && initialFilters.length > 0) {
|
||||
onFilterVisibilityChange(initialFilters);
|
||||
}
|
||||
setIsInitialized(true);
|
||||
}
|
||||
}, [isInitialized, onFilterVisibilityChange, getInitialFilters]);
|
||||
|
||||
// 외부 visibleFilters가 변경되면 localStorage에 저장
|
||||
useEffect(() => {
|
||||
if (isInitialized && externalVisibleFilters && externalVisibleFilters.length > 0) {
|
||||
// 초기화 직후 첫 번째 실행은 건너뜀 (onFilterVisibilityChange 결과가 반영되기 전)
|
||||
if (skipNextSaveRef.current) {
|
||||
skipNextSaveRef.current = false;
|
||||
return;
|
||||
}
|
||||
saveToStorage(externalVisibleFilters);
|
||||
}
|
||||
}, [isInitialized, externalVisibleFilters, saveToStorage]);
|
||||
|
||||
// UI를 렌더링하지 않음 (상태 관리 역할만 수행)
|
||||
return null;
|
||||
};
|
||||
|
||||
export default FilterVisibilitySelector;
|
||||
@@ -0,0 +1,82 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Label } from '../basic/Label';
|
||||
|
||||
export interface FormFieldProps {
|
||||
/** 필드 레이블 */
|
||||
label?: string;
|
||||
/** 필수 필드 표시 여부 */
|
||||
required?: boolean;
|
||||
/** 에러 메시지 */
|
||||
error?: string;
|
||||
/** 도움말 텍스트 */
|
||||
helperText?: string;
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
/** 레이블 className */
|
||||
labelClassName?: string;
|
||||
/** 자식 요소 (필드 컨텐츠) */
|
||||
children?: React.ReactNode;
|
||||
/** 수평 레이아웃 여부 */
|
||||
horizontal?: boolean;
|
||||
/** 레이블 너비 (수평 레이아웃 시) */
|
||||
labelWidth?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* FormField 컴포넌트
|
||||
*
|
||||
* 폼 필드에 레이블, 에러, 도움말을 제공하는 래퍼 컴포넌트입니다.
|
||||
* 수직(기본) 및 수평 레이아웃을 지원합니다.
|
||||
*/
|
||||
export const FormField: React.FC<FormFieldProps> = ({
|
||||
label,
|
||||
required = false,
|
||||
error,
|
||||
helperText,
|
||||
className = '',
|
||||
labelClassName = '',
|
||||
children,
|
||||
horizontal = false,
|
||||
labelWidth = 'w-1/3',
|
||||
}) => {
|
||||
const containerClass = horizontal
|
||||
? `flex items-start gap-4 ${className}`
|
||||
: `space-y-1 ${className}`;
|
||||
|
||||
const labelContainerClass = horizontal ? `${labelWidth} flex-shrink-0 pt-2` : '';
|
||||
const contentContainerClass = horizontal ? 'flex-1' : '';
|
||||
|
||||
return (
|
||||
<Div className={containerClass}>
|
||||
{label && (
|
||||
<Div className={labelContainerClass}>
|
||||
<Label
|
||||
className={`block text-sm font-medium text-gray-700 dark:text-gray-300 ${labelClassName}`}
|
||||
>
|
||||
{label}
|
||||
{required && (
|
||||
<span className="ml-1 text-red-500 dark:text-red-400">*</span>
|
||||
)}
|
||||
</Label>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
<Div className={`${contentContainerClass} ${error ? 'form-field-error' : ''}`.trim()}>
|
||||
{children}
|
||||
|
||||
{helperText && !error && (
|
||||
<Div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{helperText}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Div className="mt-1 text-xs text-red-600 dark:text-red-400">
|
||||
{error}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,172 @@
|
||||
import React, { useMemo } from 'react';
|
||||
// @ts-ignore - DOMPurify 타입 정의 없음
|
||||
import DOMPurify from 'dompurify';
|
||||
import { Div } from '../basic/Div';
|
||||
|
||||
export interface HtmlContentProps {
|
||||
/**
|
||||
* 콘텐츠 (HTML 또는 일반 텍스트)
|
||||
*/
|
||||
content?: string;
|
||||
|
||||
/**
|
||||
* 콘텐츠가 HTML 형식인지 여부
|
||||
* - true: HTML 렌더링 (DOMPurify 적용, prose 스타일)
|
||||
* - false: 일반 텍스트 (whitespace-pre-wrap으로 줄바꿈 보존)
|
||||
* @default true
|
||||
*/
|
||||
isHtml?: boolean;
|
||||
|
||||
/**
|
||||
* 사용자 정의 클래스
|
||||
*/
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* DOMPurify 설정 오버라이드 (isHtml=true일 때만 사용)
|
||||
*/
|
||||
purifyConfig?: any;
|
||||
|
||||
/**
|
||||
* 레이아웃 JSON에서 text 속성으로 전달되는 콘텐츠
|
||||
* content보다 우선순위가 높음
|
||||
*/
|
||||
text?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* HtmlContent 콘텐츠 렌더링 컴포넌트
|
||||
*
|
||||
* HTML과 일반 텍스트를 안전하게 렌더링하는 범용 composite 컴포넌트입니다.
|
||||
* - isHtml=true: DOMPurify를 사용하여 XSS 공격 방지
|
||||
* - isHtml=false: 일반 텍스트로 렌더링 (줄바꿈 보존)
|
||||
*
|
||||
* @example
|
||||
* // HTML 렌더링 (기본값)
|
||||
* <HtmlContent content="<p>안녕하세요</p>" />
|
||||
* <HtmlContent content="<p>안녕하세요</p>" isHtml={true} />
|
||||
*
|
||||
* // 일반 텍스트 렌더링
|
||||
* <HtmlContent
|
||||
* content="안녕하세요\n줄바꿈이 보존됩니다"
|
||||
* isHtml={false}
|
||||
* />
|
||||
*
|
||||
* // 커스텀 클래스 적용
|
||||
* <HtmlContent
|
||||
* content="<p>게시글 내용</p>"
|
||||
* className="prose dark:prose-invert"
|
||||
* />
|
||||
*
|
||||
* // DOMPurify 설정 커스터마이징 (HTML 모드)
|
||||
* <HtmlContent
|
||||
* content="<p>내용</p>"
|
||||
* purifyConfig={{ ALLOWED_TAGS: ['p', 'br', 'strong', 'em'] }}
|
||||
* />
|
||||
*/
|
||||
export const HtmlContent: React.FC<HtmlContentProps> = ({
|
||||
content,
|
||||
text,
|
||||
isHtml = true,
|
||||
className = '',
|
||||
purifyConfig,
|
||||
}) => {
|
||||
// text prop이 우선순위가 높음 (레이아웃 JSON에서 사용)
|
||||
const actualContent = text ?? content ?? '';
|
||||
|
||||
// 빈 값 처리
|
||||
if (!actualContent || actualContent.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// isHtml=false: 일반 텍스트 렌더링
|
||||
if (!isHtml) {
|
||||
const textClasses = `
|
||||
whitespace-pre-wrap
|
||||
text-gray-900 dark:text-gray-100
|
||||
font-sans
|
||||
${className}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return (
|
||||
<Div className={textClasses}>
|
||||
{actualContent}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// isHtml=true: HTML 렌더링 (기존 로직)
|
||||
// 기본 DOMPurify 설정
|
||||
const defaultConfig: any = {
|
||||
ALLOWED_TAGS: [
|
||||
'p', 'br', 'strong', 'em', 'u', 's', 'strike', 'del', 'ins',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
||||
'ul', 'ol', 'li',
|
||||
'a', 'img',
|
||||
'blockquote', 'code', 'pre',
|
||||
'table', 'thead', 'tbody', 'tr', 'th', 'td',
|
||||
'div', 'span',
|
||||
],
|
||||
ALLOWED_ATTR: [
|
||||
'href', 'target', 'rel', 'title', 'alt', 'src', 'width', 'height',
|
||||
'class', 'style', 'id', 'data-*',
|
||||
],
|
||||
ALLOW_DATA_ATTR: true,
|
||||
// 외부 링크는 rel="noopener noreferrer" 자동 추가
|
||||
ADD_ATTR: ['target'],
|
||||
// target="_blank"인 링크에 rel="noopener noreferrer" 자동 추가
|
||||
SAFE_FOR_TEMPLATES: true,
|
||||
};
|
||||
|
||||
// sanitize된 HTML을 메모이제이션
|
||||
const sanitizedHtml = useMemo(() => {
|
||||
const config = purifyConfig || defaultConfig;
|
||||
const cleaned = DOMPurify.sanitize(actualContent, config) as unknown as string;
|
||||
|
||||
// target="_blank" 링크에 rel 속성 추가 (보안)
|
||||
return cleaned.replace(
|
||||
/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi,
|
||||
(match: string, before: string, href: string, after: string) => {
|
||||
// 외부 링크인 경우
|
||||
if (href.startsWith('http://') || href.startsWith('https://')) {
|
||||
// rel 속성이 없으면 추가
|
||||
if (!match.includes('rel=')) {
|
||||
return `<a ${before}href="${href}"${after} rel="noopener noreferrer">`;
|
||||
}
|
||||
}
|
||||
return match;
|
||||
}
|
||||
);
|
||||
}, [actualContent, purifyConfig, defaultConfig]);
|
||||
|
||||
// 컨테이너 클래스 조합
|
||||
const containerClasses = `
|
||||
prose dark:prose-invert max-w-none
|
||||
prose-p:my-2
|
||||
prose-headings:font-bold prose-headings:mt-6 prose-headings:mb-4
|
||||
prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg
|
||||
prose-a:text-blue-600 dark:prose-a:text-blue-400
|
||||
prose-a:no-underline hover:prose-a:underline
|
||||
prose-img:rounded-lg prose-img:shadow-md
|
||||
prose-blockquote:border-l-4 prose-blockquote:border-gray-300 dark:prose-blockquote:border-gray-600
|
||||
prose-blockquote:pl-4 prose-blockquote:italic
|
||||
prose-code:bg-gray-100 dark:prose-code:bg-gray-800
|
||||
prose-code:px-1 prose-code:py-0.5 prose-code:rounded
|
||||
prose-pre:bg-gray-100 dark:prose-pre:bg-gray-800
|
||||
prose-pre:p-4 prose-pre:rounded-lg prose-pre:overflow-x-auto
|
||||
prose-table:border prose-table:border-gray-300 dark:prose-table:border-gray-600
|
||||
prose-th:bg-gray-100 dark:prose-th:bg-gray-800
|
||||
prose-th:border prose-th:border-gray-300 dark:prose-th:border-gray-600
|
||||
prose-th:px-4 prose-th:py-2
|
||||
prose-td:border prose-td:border-gray-300 dark:prose-td:border-gray-600
|
||||
prose-td:px-4 prose-td:py-2
|
||||
${className}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={containerClasses}
|
||||
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,428 @@
|
||||
import React, { useCallback, useState, useMemo } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Label } from '../basic/Label';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Textarea } from '../basic/Textarea';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { HtmlContent } from './HtmlContent';
|
||||
|
||||
// G7Core 참조
|
||||
const G7Core = () => (window as any).G7Core;
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
G7Core()?.t?.(key, params) ?? key;
|
||||
|
||||
// G7Core에서 지원 언어 목록 가져오기
|
||||
const getSupportedLocales = (): string[] => {
|
||||
return G7Core()?.locale?.supported?.() ?? ['ko', 'en'];
|
||||
};
|
||||
|
||||
// G7Core에서 현재 언어 가져오기
|
||||
const getCurrentLocale = (): string => {
|
||||
return G7Core()?.locale?.current?.() ?? 'ko';
|
||||
};
|
||||
|
||||
// 언어 코드로 언어명 가져오기 (다국어 키 사용)
|
||||
const getLocaleNameByCode = (code: string): string => {
|
||||
const translatedName = t(`common.language_${code}`);
|
||||
if (translatedName === `common.language_${code}`) {
|
||||
const fallbackNames: Record<string, string> = {
|
||||
ko: '한국어',
|
||||
en: 'English',
|
||||
ja: '日本語',
|
||||
zh: '中文',
|
||||
};
|
||||
return fallbackNames[code] || code.toUpperCase();
|
||||
}
|
||||
return translatedName;
|
||||
};
|
||||
|
||||
// 다국어 값 타입
|
||||
export interface MultilingualValue {
|
||||
[locale: string]: string;
|
||||
}
|
||||
|
||||
export interface HtmlEditorProps {
|
||||
/**
|
||||
* 콘텐츠 값 (단일 언어 모드)
|
||||
*/
|
||||
content?: string;
|
||||
|
||||
/**
|
||||
* 다국어 콘텐츠 값 (다국어 모드)
|
||||
* multilingual=true일 때 사용
|
||||
*/
|
||||
value?: MultilingualValue;
|
||||
|
||||
/**
|
||||
* 콘텐츠 변경 콜백
|
||||
* - 단일 언어: { target: { name, value: string } }
|
||||
* - 다국어: { target: { name, value: MultilingualValue } }
|
||||
*/
|
||||
onChange?: (event: { target: { name: string; value: string | MultilingualValue } }) => void;
|
||||
|
||||
/**
|
||||
* 다국어 모드 활성화
|
||||
* true일 때 언어 탭 UI 표시, value는 다국어 객체
|
||||
* @default false
|
||||
*/
|
||||
multilingual?: boolean;
|
||||
|
||||
/**
|
||||
* HTML 모드 여부 (미리보기 버튼 표시 조건)
|
||||
* 자동 바인딩된 값을 Layout JSON에서 전달받아 사용
|
||||
*/
|
||||
isHtml?: boolean;
|
||||
|
||||
/**
|
||||
* HTML 모드 변경 콜백
|
||||
* Form 자동 바인딩을 위해 이벤트 객체 형식으로 전달
|
||||
*/
|
||||
onIsHtmlChange?: (event: { target: { name: string; checked: boolean } }) => void;
|
||||
|
||||
/**
|
||||
* Textarea 행 수
|
||||
* @default 15
|
||||
*/
|
||||
rows?: number;
|
||||
|
||||
/**
|
||||
* placeholder 텍스트
|
||||
*/
|
||||
placeholder?: string;
|
||||
|
||||
/**
|
||||
* 라벨 텍스트
|
||||
*/
|
||||
label?: string;
|
||||
|
||||
/**
|
||||
* HTML 모드 체크박스 표시 여부
|
||||
* @default true
|
||||
*/
|
||||
showHtmlModeToggle?: boolean;
|
||||
|
||||
/**
|
||||
* HtmlContent 렌더링 시 적용할 클래스
|
||||
*/
|
||||
contentClassName?: string;
|
||||
|
||||
/**
|
||||
* DOMPurify 설정 (HTML 모드)
|
||||
*/
|
||||
purifyConfig?: any;
|
||||
|
||||
/**
|
||||
* 추가 className
|
||||
*/
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* 콘텐츠 필드 name 속성
|
||||
* @default 'content'
|
||||
*/
|
||||
name?: string;
|
||||
|
||||
/**
|
||||
* HTML 모드 체크박스 name 속성
|
||||
* @default 'content_mode'
|
||||
*/
|
||||
htmlFieldName?: string;
|
||||
|
||||
/**
|
||||
* 읽기 전용 모드
|
||||
*/
|
||||
readOnly?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* HtmlEditor 컴포넌트
|
||||
*
|
||||
* HTML과 일반 텍스트를 편집할 수 있는 범용 에디터 컴포넌트입니다.
|
||||
* - HTML 모드 체크박스는 자동 바인딩됩니다 (htmlFieldName prop 사용)
|
||||
* - HTML 모드에서는 편집/미리보기 토글 가능 (내부 상태 관리)
|
||||
* - 일반 텍스트 모드에서는 Textarea만 표시
|
||||
* - multilingual=true일 때 다국어 탭 UI 지원 (v1.5.0+)
|
||||
*
|
||||
* @example
|
||||
* // 단일 언어 모드
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "HtmlEditor",
|
||||
* "props": {
|
||||
* "content": "{{_local.form?.content}}",
|
||||
* "name": "content"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // 다국어 모드
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "HtmlEditor",
|
||||
* "props": {
|
||||
* "multilingual": true,
|
||||
* "value": "{{_local.form?.description}}",
|
||||
* "name": "description"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const HtmlEditor: React.FC<HtmlEditorProps> = ({
|
||||
content = '',
|
||||
value,
|
||||
onChange,
|
||||
multilingual = false,
|
||||
isHtml: isHtmlProp = false,
|
||||
onIsHtmlChange,
|
||||
rows = 15,
|
||||
placeholder = '',
|
||||
label,
|
||||
showHtmlModeToggle = true,
|
||||
contentClassName = '',
|
||||
purifyConfig,
|
||||
className = '',
|
||||
name = 'content',
|
||||
htmlFieldName = 'content_mode',
|
||||
readOnly = false,
|
||||
}) => {
|
||||
// 지원 언어 목록
|
||||
const supportedLocales = useMemo(() => getSupportedLocales(), []);
|
||||
const defaultLocale = useMemo(() => getCurrentLocale(), []);
|
||||
|
||||
// 현재 선택된 언어 탭 (다국어 모드)
|
||||
const [currentLocale, setCurrentLocale] = useState(defaultLocale);
|
||||
|
||||
// HTML 모드 내부 상태 (Toggle과 동기화)
|
||||
const [isHtml, setIsHtml] = useState(isHtmlProp);
|
||||
|
||||
// 단일 언어 콘텐츠 내부 상태
|
||||
const [localContent, setLocalContent] = useState(content);
|
||||
|
||||
// 다국어 콘텐츠 내부 상태
|
||||
const [localMultilingualContent, setLocalMultilingualContent] = useState<MultilingualValue>(
|
||||
value ?? {}
|
||||
);
|
||||
|
||||
// 미리보기 모드 내부 상태 (컴포넌트 자체에서 관리)
|
||||
const [previewMode, setPreviewMode] = useState(false);
|
||||
|
||||
// Props 변경 시 내부 상태 동기화
|
||||
React.useEffect(() => {
|
||||
setIsHtml(isHtmlProp);
|
||||
}, [isHtmlProp]);
|
||||
|
||||
// content prop 변경 시 로컬 상태 동기화 (단일 언어 모드)
|
||||
React.useEffect(() => {
|
||||
if (!multilingual) {
|
||||
setLocalContent(content);
|
||||
}
|
||||
}, [content, multilingual]);
|
||||
|
||||
// value prop 변경 시 로컬 상태 동기화 (다국어 모드)
|
||||
React.useEffect(() => {
|
||||
if (multilingual && value) {
|
||||
setLocalMultilingualContent(value);
|
||||
}
|
||||
}, [value, multilingual]);
|
||||
|
||||
// 단일 언어 콘텐츠 변경 핸들러
|
||||
const handleContentChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newContent = e.target.value;
|
||||
setLocalContent(newContent);
|
||||
|
||||
if (onChange) {
|
||||
const event = G7Core()?.createChangeEvent?.({ value: newContent, name, type: 'textarea' })
|
||||
?? { target: { name, value: newContent } };
|
||||
onChange(event);
|
||||
}
|
||||
}, [onChange, name]);
|
||||
|
||||
// 다국어 콘텐츠 변경 핸들러
|
||||
const handleMultilingualContentChange = useCallback((locale: string, newContent: string) => {
|
||||
const newValue = {
|
||||
...localMultilingualContent,
|
||||
[locale]: newContent,
|
||||
};
|
||||
setLocalMultilingualContent(newValue);
|
||||
|
||||
if (onChange) {
|
||||
const event = G7Core()?.createChangeEvent?.({ value: newValue, name, type: 'multilingual' })
|
||||
?? { target: { name, value: newValue } };
|
||||
onChange(event);
|
||||
}
|
||||
}, [onChange, name, localMultilingualContent]);
|
||||
|
||||
// HTML 모드 변경 핸들러
|
||||
const handleHtmlModeChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const isHtmlMode = e.target.checked;
|
||||
setIsHtml(isHtmlMode);
|
||||
|
||||
if (!isHtmlMode) {
|
||||
setPreviewMode(false);
|
||||
}
|
||||
|
||||
if (onIsHtmlChange) {
|
||||
const event = G7Core()?.createChangeEvent?.({ checked: isHtmlMode, name: htmlFieldName, type: 'checkbox' })
|
||||
?? { target: { name: htmlFieldName, checked: isHtmlMode } };
|
||||
onIsHtmlChange(event);
|
||||
}
|
||||
}, [onIsHtmlChange, htmlFieldName]);
|
||||
|
||||
// 미리보기 모드 토글 핸들러
|
||||
const handlePreviewModeToggle = useCallback(() => {
|
||||
setPreviewMode(prev => !prev);
|
||||
}, []);
|
||||
|
||||
// 현재 표시할 콘텐츠 (단일/다국어 모드에 따라)
|
||||
const currentContent = multilingual
|
||||
? (localMultilingualContent[currentLocale] ?? '')
|
||||
: localContent;
|
||||
|
||||
// 입력 완료 여부 확인 (다국어 모드)
|
||||
const hasValue = useCallback((locale: string) => {
|
||||
return Boolean(localMultilingualContent[locale]?.trim());
|
||||
}, [localMultilingualContent]);
|
||||
|
||||
// 다국어 탭 렌더링
|
||||
const renderLocaleTabs = () => (
|
||||
<Div className="flex items-center gap-2 mb-3">
|
||||
{supportedLocales.map(localeCode => {
|
||||
const isDefault = localeCode === defaultLocale;
|
||||
const isActive = currentLocale === localeCode;
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={localeCode}
|
||||
type="button"
|
||||
className={`
|
||||
inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all
|
||||
${isActive
|
||||
? isDefault
|
||||
? 'bg-blue-500 text-white dark:bg-blue-600 dark:text-white shadow-md scale-105'
|
||||
: 'bg-gray-500 text-white dark:bg-gray-600 dark:text-white shadow-md scale-105'
|
||||
: isDefault
|
||||
? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/50'
|
||||
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}
|
||||
`}
|
||||
onClick={() => setCurrentLocale(localeCode)}
|
||||
>
|
||||
<Icon name="globe" className="w-3 h-3" />
|
||||
<Span>{getLocaleNameByCode(localeCode)}</Span>
|
||||
{isDefault && <Span className="text-red-500">*</Span>}
|
||||
{/* 입력 완료 표시 */}
|
||||
{hasValue(localeCode) && !isActive && (
|
||||
<Icon name="check" className="w-3 h-3 text-green-500 dark:text-green-400" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Div className={`space-y-2 ${className}`}>
|
||||
{/* 라벨 및 HTML 모드 토글 */}
|
||||
<Div className="flex items-center justify-between">
|
||||
{label && (
|
||||
<Label className="block text-sm font-medium text-gray-500 dark:text-gray-400">
|
||||
{label}
|
||||
</Label>
|
||||
)}
|
||||
|
||||
<Div className="flex items-center gap-3">
|
||||
{/* 미리보기 버튼 (HTML 모드일 때만 표시) */}
|
||||
{isHtml && !readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handlePreviewModeToggle}
|
||||
className={`px-3 py-1.5 text-xs font-bold rounded-lg focus:outline-none focus:ring-2 ${
|
||||
previewMode
|
||||
? 'text-gray-700 dark:text-gray-200 bg-gray-200 dark:bg-gray-600 border border-gray-300 dark:border-gray-500 hover:bg-gray-300 dark:hover:bg-gray-500 focus:ring-gray-400 dark:focus:ring-gray-500'
|
||||
: 'text-blue-600 dark:text-blue-400 bg-white dark:bg-gray-700 border border-blue-300 dark:border-blue-600 hover:bg-blue-50 dark:hover:bg-gray-600 focus:ring-blue-500 dark:focus:ring-blue-600'
|
||||
}`}
|
||||
>
|
||||
{previewMode ? t('common.preview_off') : t('common.preview')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{showHtmlModeToggle && (
|
||||
<Label className="flex items-center gap-2 p-2 cursor-pointer">
|
||||
<Input
|
||||
type="checkbox"
|
||||
name={htmlFieldName}
|
||||
checked={isHtml}
|
||||
onChange={handleHtmlModeChange}
|
||||
disabled={readOnly}
|
||||
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
|
||||
/>
|
||||
<Div className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{t('common.html_mode')}
|
||||
</Div>
|
||||
</Label>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
|
||||
{/* 다국어 탭 (multilingual 모드일 때만) */}
|
||||
{multilingual && renderLocaleTabs()}
|
||||
|
||||
{/* 콘텐츠 편집 영역 */}
|
||||
{!previewMode && (
|
||||
multilingual ? (
|
||||
// 다국어 모드: 각 언어별 Textarea
|
||||
supportedLocales.map(localeCode => (
|
||||
<Div
|
||||
key={localeCode}
|
||||
className={currentLocale === localeCode ? 'block' : 'hidden'}
|
||||
>
|
||||
<Textarea
|
||||
name={`${name}[${localeCode}]`}
|
||||
value={localMultilingualContent[localeCode] ?? ''}
|
||||
onChange={(e) => handleMultilingualContentChange(localeCode, e.target.value)}
|
||||
placeholder={`${placeholder} (${getLocaleNameByCode(localeCode)})`}
|
||||
rows={rows}
|
||||
readOnly={readOnly}
|
||||
className={`block w-full rounded-lg border px-3 py-2 text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 disabled:opacity-50 disabled:cursor-not-allowed ${
|
||||
isHtml
|
||||
? 'font-mono bg-white dark:bg-gray-800 border-blue-300 dark:border-blue-600 text-gray-800 dark:text-gray-200 focus:border-blue-500 focus:ring-blue-500'
|
||||
: 'bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-blue-500'
|
||||
}`}
|
||||
/>
|
||||
</Div>
|
||||
))
|
||||
) : (
|
||||
// 단일 언어 모드
|
||||
<Textarea
|
||||
name={name}
|
||||
value={localContent}
|
||||
onChange={handleContentChange}
|
||||
placeholder={placeholder}
|
||||
rows={rows}
|
||||
readOnly={readOnly}
|
||||
className={`block w-full rounded-lg border px-3 py-2 text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 disabled:opacity-50 disabled:cursor-not-allowed ${
|
||||
isHtml
|
||||
? 'font-mono bg-white dark:bg-gray-800 border-blue-300 dark:border-blue-600 text-gray-800 dark:text-gray-200 focus:border-blue-500 focus:ring-blue-500'
|
||||
: 'bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-blue-500'
|
||||
}`}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
|
||||
{/* 미리보기 영역 (미리보기 모드일 때만) */}
|
||||
{previewMode && (
|
||||
<Div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 min-h-[400px]">
|
||||
<HtmlContent
|
||||
content={currentContent}
|
||||
isHtml={true}
|
||||
className={contentClassName || 'prose dark:prose-invert max-w-none text-gray-900 dark:text-gray-100'}
|
||||
purifyConfig={purifyConfig}
|
||||
/>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import React from 'react';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
// G7Core 전역 객체의 스타일 헬퍼 접근
|
||||
const G7Core = () => (window as any).G7Core;
|
||||
|
||||
export interface IconButtonProps {
|
||||
iconName: IconName;
|
||||
label?: string;
|
||||
onClick?: () => void;
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* IconButton 집합 컴포넌트
|
||||
*
|
||||
* 아이콘이 포함된 버튼 컴포넌트입니다.
|
||||
* 아이콘만 표시하거나 라벨과 함께 표시할 수 있습니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Button + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "IconButton",
|
||||
* "props": {
|
||||
* "iconName": "plus",
|
||||
* "label": "추가",
|
||||
* "variant": "primary",
|
||||
* "size": "md"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const IconButton: React.FC<IconButtonProps> = ({
|
||||
iconName,
|
||||
label,
|
||||
onClick,
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
// 크기별 스타일
|
||||
const sizeClasses = {
|
||||
sm: label ? 'px-3 py-1.5 text-sm' : 'p-1.5',
|
||||
md: label ? 'px-4 py-2 text-base' : 'p-2',
|
||||
lg: label ? 'px-5 py-2.5 text-lg' : 'p-2.5',
|
||||
};
|
||||
|
||||
// 아이콘 크기
|
||||
const iconSizeClasses = {
|
||||
sm: 'w-4 h-4',
|
||||
md: 'w-5 h-5',
|
||||
lg: 'w-6 h-6',
|
||||
};
|
||||
|
||||
// 변형별 스타일
|
||||
const variantClasses = {
|
||||
primary: 'bg-blue-600 hover:bg-blue-700 text-white border-transparent',
|
||||
secondary: 'bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600',
|
||||
danger: 'bg-red-600 hover:bg-red-700 text-white border-transparent',
|
||||
ghost: 'bg-transparent hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 border-transparent',
|
||||
};
|
||||
|
||||
const baseClasses = 'inline-flex items-center justify-center gap-2 font-medium rounded-lg border transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 dark:focus:ring-blue-400';
|
||||
const disabledClasses = disabled ? 'opacity-50 cursor-not-allowed' : '';
|
||||
|
||||
// 모든 내부 클래스를 결합한 후 외부 className과 병합
|
||||
const internalClasses = `${baseClasses} ${sizeClasses[size]} ${variantClasses[variant]} ${disabledClasses}`;
|
||||
const mergedClassName = G7Core()?.style?.mergeClasses?.(internalClasses, className)
|
||||
?? `${internalClasses} ${className}`;
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className={mergedClassName}
|
||||
style={style}
|
||||
>
|
||||
<Icon name={iconName} className={iconSizeClasses[size]} />
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
export interface IconOption {
|
||||
value: string;
|
||||
label: string;
|
||||
faIcon: string;
|
||||
}
|
||||
|
||||
export interface IconSelectProps {
|
||||
value?: string;
|
||||
onChange?: (value: string) => void;
|
||||
options?: IconOption[];
|
||||
placeholder?: string;
|
||||
searchPlaceholder?: string;
|
||||
noResultsText?: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
const defaultIconOptions: IconOption[] = [
|
||||
{ value: 'LayoutDashboard', label: 'LayoutDashboard', faIcon: 'tachometer-alt' },
|
||||
{ value: 'Settings', label: 'Settings', faIcon: 'cog' },
|
||||
{ value: 'Menu', label: 'Menu', faIcon: 'bars' },
|
||||
{ value: 'Users', label: 'Users', faIcon: 'users' },
|
||||
{ value: 'Package', label: 'Package', faIcon: 'cube' },
|
||||
{ value: 'Puzzle', label: 'Puzzle', faIcon: 'puzzle-piece' },
|
||||
{ value: 'FileText', label: 'FileText', faIcon: 'file-alt' },
|
||||
{ value: 'ShoppingCart', label: 'ShoppingCart', faIcon: 'shopping-cart' },
|
||||
{ value: 'MessageSquare', label: 'MessageSquare', faIcon: 'comment' },
|
||||
{ value: 'Home', label: 'Home', faIcon: 'home' },
|
||||
{ value: 'User', label: 'User', faIcon: 'user' },
|
||||
{ value: 'Search', label: 'Search', faIcon: 'search' },
|
||||
{ value: 'Bell', label: 'Bell', faIcon: 'bell' },
|
||||
{ value: 'Mail', label: 'Mail', faIcon: 'envelope' },
|
||||
{ value: 'Calendar', label: 'Calendar', faIcon: 'calendar' },
|
||||
{ value: 'Chart', label: 'Chart', faIcon: 'chart-bar' },
|
||||
{ value: 'Database', label: 'Database', faIcon: 'database' },
|
||||
{ value: 'Lock', label: 'Lock', faIcon: 'lock' },
|
||||
{ value: 'Globe', label: 'Globe', faIcon: 'globe' },
|
||||
{ value: 'Image', label: 'Image', faIcon: 'image' },
|
||||
];
|
||||
|
||||
/**
|
||||
* IconSelect 컴포넌트
|
||||
* 아이콘 선택 드롭다운
|
||||
*/
|
||||
export const IconSelect: React.FC<IconSelectProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
options = defaultIconOptions,
|
||||
placeholder,
|
||||
searchPlaceholder,
|
||||
noResultsText,
|
||||
className = '',
|
||||
disabled = false,
|
||||
name,
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// value가 faIcon 형식(fas fa-xxx) 또는 Lucide 형식(IconName)일 수 있음
|
||||
const selectedOption = options.find((opt) => {
|
||||
if (!value) return false;
|
||||
// FontAwesome 형식 (fas fa-xxx, far fa-xxx 등)
|
||||
if (value.includes('fa-')) {
|
||||
const faIconName = value.replace(/^(fas|far|fab|fal|fad)\s+fa-/, '');
|
||||
return opt.faIcon === faIconName || opt.faIcon === value;
|
||||
}
|
||||
// Lucide 형식 또는 직접 매칭
|
||||
return opt.value === value || opt.faIcon === value;
|
||||
});
|
||||
|
||||
const filteredOptions = options.filter((opt) =>
|
||||
opt.label.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
setSearchQuery('');
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleSelect = (option: IconOption) => {
|
||||
// FontAwesome 형식으로 변환하여 반환 (fas fa-xxx)
|
||||
const faValue = `fas fa-${option.faIcon}`;
|
||||
onChange?.(faValue);
|
||||
setIsOpen(false);
|
||||
setSearchQuery('');
|
||||
};
|
||||
|
||||
return (
|
||||
<Div ref={dropdownRef} className={`relative ${className}`}>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => !disabled && setIsOpen(!isOpen)}
|
||||
disabled={disabled}
|
||||
className={`
|
||||
w-full flex items-center justify-between px-3 py-2
|
||||
bg-white dark:bg-gray-800
|
||||
border border-gray-300 dark:border-gray-600 rounded-lg
|
||||
text-left text-sm
|
||||
${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:border-gray-400 dark:hover:border-gray-500'}
|
||||
focus:outline-none focus:ring-2 focus:ring-blue-500
|
||||
`}
|
||||
>
|
||||
<Div className="flex items-center gap-2">
|
||||
{selectedOption ? (
|
||||
<>
|
||||
<Icon name={selectedOption.faIcon} className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
<Span className="text-gray-900 dark:text-white">{selectedOption.label}</Span>
|
||||
</>
|
||||
) : (
|
||||
<Span className="text-gray-500 dark:text-gray-400">{placeholder}</Span>
|
||||
)}
|
||||
</Div>
|
||||
<Icon
|
||||
name="chevron-down"
|
||||
className={`w-4 h-4 text-gray-400 dark:text-gray-500 transition-transform ${isOpen ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</Button>
|
||||
|
||||
{name && <input type="hidden" name={name} value={value || ''} />}
|
||||
|
||||
{isOpen && (
|
||||
<Div className="absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-72 overflow-hidden">
|
||||
<Div className="p-2 border-b border-gray-200 dark:border-gray-700">
|
||||
<Input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder={searchPlaceholder}
|
||||
className="w-full px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||
autoFocus
|
||||
/>
|
||||
</Div>
|
||||
|
||||
<Div className="max-h-56 overflow-y-auto">
|
||||
{filteredOptions.length > 0 ? (
|
||||
filteredOptions.map((option) => (
|
||||
<Button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => handleSelect(option)}
|
||||
className={`
|
||||
w-full flex items-center gap-3 px-3 py-2 text-left text-sm
|
||||
${selectedOption?.faIcon === option.faIcon
|
||||
? 'bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300'
|
||||
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}
|
||||
`}
|
||||
>
|
||||
<Icon name={option.faIcon} className="w-4 h-4" />
|
||||
<Span>{option.label}</Span>
|
||||
{selectedOption?.faIcon === option.faIcon && (
|
||||
<Icon name="check" className="w-4 h-4 ml-auto text-blue-600" />
|
||||
)}
|
||||
</Button>
|
||||
))
|
||||
) : (
|
||||
<Div className="px-3 py-4 text-sm text-gray-500 dark:text-gray-400 text-center">
|
||||
{noResultsText}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,337 @@
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import Lightbox, { Slide } from 'yet-another-react-lightbox';
|
||||
import Zoom from 'yet-another-react-lightbox/plugins/zoom';
|
||||
import Counter from 'yet-another-react-lightbox/plugins/counter';
|
||||
import Slideshow from 'yet-another-react-lightbox/plugins/slideshow';
|
||||
import Fullscreen from 'yet-another-react-lightbox/plugins/fullscreen';
|
||||
import Thumbnails from 'yet-another-react-lightbox/plugins/thumbnails';
|
||||
import 'yet-another-react-lightbox/styles.css';
|
||||
import 'yet-another-react-lightbox/plugins/counter.css';
|
||||
import 'yet-another-react-lightbox/plugins/thumbnails.css';
|
||||
|
||||
import { Button } from '../basic/Button';
|
||||
import { I } from '../basic/I';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:ImageGallery')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:ImageGallery]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:ImageGallery]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:ImageGallery]', ...args),
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
// ========== Types ==========
|
||||
|
||||
export interface GalleryImage {
|
||||
/** 이미지 표시용 URL (라이트박스에서 보여줄 이미지) */
|
||||
src: string;
|
||||
/** 다운로드용 URL (src와 다를 수 있음, 없으면 src 사용) */
|
||||
downloadUrl?: string;
|
||||
/** 이미지 제목/캡션 */
|
||||
title?: string;
|
||||
/** 이미지 설명 */
|
||||
description?: string;
|
||||
/** 썸네일 URL (없으면 src 사용) */
|
||||
thumbnail?: string;
|
||||
/** 원본 파일명 (다운로드 시 사용) */
|
||||
filename?: string;
|
||||
/** 다운로드 시 인증된 요청이 필요한지 여부 (기본값: false) */
|
||||
downloadRequiresAuth?: boolean;
|
||||
}
|
||||
|
||||
export interface ImageGalleryProps {
|
||||
/** 갤러리에 표시할 이미지 배열 */
|
||||
images: GalleryImage[];
|
||||
/** 라이트박스 열기 여부 */
|
||||
isOpen: boolean;
|
||||
/** 라이트박스 닫기 콜백 */
|
||||
onClose: () => void;
|
||||
/** 시작 인덱스 (기본값: 0) */
|
||||
startIndex?: number;
|
||||
/** 줌 기능 활성화 (기본값: true) */
|
||||
enableZoom?: boolean;
|
||||
/** 슬라이드쇼 기능 활성화 (기본값: false) */
|
||||
enableSlideshow?: boolean;
|
||||
/** 전체화면 기능 활성화 (기본값: true) */
|
||||
enableFullscreen?: boolean;
|
||||
/** 이미지 카운터 표시 (기본값: true) */
|
||||
showCounter?: boolean;
|
||||
/** 다운로드 버튼 표시 (기본값: true) */
|
||||
showDownload?: boolean;
|
||||
/** 썸네일 네비게이션 표시 (기본값: true) */
|
||||
showThumbnails?: boolean;
|
||||
/** 커스텀 다운로드 핸들러 (제공 시 기본 다운로드 로직 대신 실행) */
|
||||
onDownload?: (image: GalleryImage, index: number) => void;
|
||||
}
|
||||
|
||||
// ========== Helper Functions ==========
|
||||
|
||||
/**
|
||||
* 인증된 이미지 다운로드 (Blob으로 변환 후 다운로드)
|
||||
*/
|
||||
const downloadAuthenticatedFile = async (url: string, filename: string): Promise<void> => {
|
||||
try {
|
||||
const blob = await G7Core.api.get(url, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
|
||||
if (blob) {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to download file:', error);
|
||||
G7Core?.toast?.error?.(t('common.download_failed'));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 일반 파일 다운로드
|
||||
*/
|
||||
const downloadFile = (url: string, filename: string): void => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.target = '_blank';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
};
|
||||
|
||||
/**
|
||||
* 이미지 다운로드 실행
|
||||
*/
|
||||
export const executeImageDownload = async (image: GalleryImage): Promise<void> => {
|
||||
const downloadUrl = image.downloadUrl || image.src;
|
||||
const filename = image.filename || image.title || 'image';
|
||||
|
||||
if (image.downloadRequiresAuth) {
|
||||
await downloadAuthenticatedFile(downloadUrl, filename);
|
||||
} else {
|
||||
downloadFile(downloadUrl, filename);
|
||||
}
|
||||
};
|
||||
|
||||
// ========== Custom Download Button Component ==========
|
||||
|
||||
interface DownloadButtonProps {
|
||||
image: GalleryImage;
|
||||
index: number;
|
||||
onDownload?: (image: GalleryImage, index: number) => void;
|
||||
}
|
||||
|
||||
const DownloadButton: React.FC<DownloadButtonProps> = ({ image, index, onDownload }) => {
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
|
||||
const handleDownload = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
if (onDownload) {
|
||||
onDownload(image, index);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsDownloading(true);
|
||||
try {
|
||||
await executeImageDownload(image);
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleDownload}
|
||||
disabled={isDownloading}
|
||||
className="yarl__button flex items-center justify-center"
|
||||
aria-label={t('common.download')}
|
||||
title={t('common.download')}
|
||||
>
|
||||
{isDownloading ? (
|
||||
<I className="fa-solid fa-spinner fa-spin text-white" />
|
||||
) : (
|
||||
<I className="fa-solid fa-download text-white" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
// ========== Main Component ==========
|
||||
|
||||
export const ImageGallery: React.FC<ImageGalleryProps> = ({
|
||||
images,
|
||||
isOpen,
|
||||
onClose,
|
||||
startIndex = 0,
|
||||
enableZoom = true,
|
||||
enableSlideshow = false,
|
||||
enableFullscreen = true,
|
||||
showCounter = true,
|
||||
showDownload = true,
|
||||
showThumbnails = true,
|
||||
onDownload,
|
||||
}) => {
|
||||
// 현재 슬라이드 인덱스 (다운로드 버튼용)
|
||||
const [currentIndex, setCurrentIndex] = useState(startIndex);
|
||||
// 최신 인덱스를 ref로 추적 (클로저 문제 방지)
|
||||
const currentIndexRef = useRef(startIndex);
|
||||
|
||||
// 이미지를 라이트박스 슬라이드 형식으로 변환 (썸네일 포함)
|
||||
const slides: Slide[] = images.map((image) => ({
|
||||
src: image.src,
|
||||
title: image.title,
|
||||
description: image.description,
|
||||
}));
|
||||
|
||||
// 활성화할 플러그인 목록
|
||||
const plugins = [];
|
||||
if (enableZoom) plugins.push(Zoom);
|
||||
if (enableSlideshow) plugins.push(Slideshow);
|
||||
if (enableFullscreen) plugins.push(Fullscreen);
|
||||
if (showCounter) plugins.push(Counter);
|
||||
if (showThumbnails) plugins.push(Thumbnails);
|
||||
|
||||
// 현재 이미지
|
||||
const currentImage = images[currentIndex];
|
||||
|
||||
// currentIndex가 변경되면 ref도 업데이트
|
||||
useEffect(() => {
|
||||
currentIndexRef.current = currentIndex;
|
||||
}, [currentIndex]);
|
||||
|
||||
return (
|
||||
<Lightbox
|
||||
open={isOpen}
|
||||
close={onClose}
|
||||
slides={slides}
|
||||
index={currentIndex}
|
||||
plugins={plugins}
|
||||
on={{
|
||||
view: ({ index }) => {
|
||||
if (index !== currentIndexRef.current) {
|
||||
setCurrentIndex(index);
|
||||
}
|
||||
},
|
||||
}}
|
||||
zoom={{
|
||||
maxZoomPixelRatio: 3,
|
||||
zoomInMultiplier: 2,
|
||||
doubleTapDelay: 300,
|
||||
doubleClickDelay: 300,
|
||||
doubleClickMaxStops: 2,
|
||||
keyboardMoveDistance: 50,
|
||||
wheelZoomDistanceFactor: 100,
|
||||
pinchZoomDistanceFactor: 100,
|
||||
scrollToZoom: true,
|
||||
}}
|
||||
carousel={{
|
||||
finite: true,
|
||||
preload: 2,
|
||||
padding: '16px',
|
||||
spacing: '30%',
|
||||
}}
|
||||
animation={{
|
||||
fade: 250,
|
||||
swipe: 500,
|
||||
easing: {
|
||||
fade: 'ease',
|
||||
swipe: 'ease-out',
|
||||
navigation: 'ease-in-out',
|
||||
},
|
||||
}}
|
||||
controller={{
|
||||
closeOnBackdropClick: true,
|
||||
closeOnPullDown: true,
|
||||
closeOnPullUp: true,
|
||||
}}
|
||||
thumbnails={{
|
||||
position: 'bottom',
|
||||
width: 120,
|
||||
height: 80,
|
||||
border: 2,
|
||||
borderRadius: 4,
|
||||
padding: 4,
|
||||
gap: 16,
|
||||
showToggle: false,
|
||||
vignette: true,
|
||||
}}
|
||||
toolbar={{
|
||||
buttons: [
|
||||
showDownload && currentImage && (
|
||||
<DownloadButton
|
||||
key="download"
|
||||
image={currentImage}
|
||||
index={currentIndex}
|
||||
onDownload={onDownload}
|
||||
/>
|
||||
),
|
||||
'close',
|
||||
].filter(Boolean),
|
||||
}}
|
||||
styles={{
|
||||
container: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// ========== Utility Hook ==========
|
||||
|
||||
/**
|
||||
* ImageGallery를 쉽게 사용하기 위한 커스텀 훅
|
||||
*
|
||||
* @example
|
||||
* const { openGallery, galleryProps } = useImageGallery();
|
||||
*
|
||||
* // 이미지 클릭 시
|
||||
* <img onClick={() => openGallery(images, 0)} />
|
||||
*
|
||||
* // 컴포넌트 렌더링
|
||||
* <ImageGallery {...galleryProps} />
|
||||
*/
|
||||
export const useImageGallery = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [images, setImages] = useState<GalleryImage[]>([]);
|
||||
const [startIndex, setStartIndex] = useState(0);
|
||||
|
||||
const openGallery = useCallback((galleryImages: GalleryImage[], index = 0) => {
|
||||
setImages(galleryImages);
|
||||
setStartIndex(index);
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const closeGallery = useCallback(() => {
|
||||
setIsOpen(false);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
openGallery,
|
||||
closeGallery,
|
||||
galleryProps: {
|
||||
images,
|
||||
isOpen,
|
||||
onClose: closeGallery,
|
||||
startIndex,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
ImageGallery.displayName = 'ImageGallery';
|
||||
|
||||
export default ImageGallery;
|
||||
@@ -0,0 +1,271 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:LanguageSelector')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:LanguageSelector]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:LanguageSelector]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:LanguageSelector]', ...args),
|
||||
};
|
||||
|
||||
/**
|
||||
* 로케일 코드를 사람이 읽을 수 있는 이름으로 변환
|
||||
*/
|
||||
const getLocaleName = (locale: string): string => {
|
||||
const localeNames: Record<string, string> = {
|
||||
ko: '한국어',
|
||||
en: 'English',
|
||||
ja: '日本語',
|
||||
zh: '中文',
|
||||
es: 'Español',
|
||||
fr: 'Français',
|
||||
de: 'Deutsch',
|
||||
};
|
||||
return localeNames[locale] || locale;
|
||||
};
|
||||
|
||||
/**
|
||||
* LanguageSelector Props
|
||||
*/
|
||||
export interface LanguageSelectorProps {
|
||||
/** 사용 가능한 언어 목록 (template.json의 locales에서 자동 바인딩) */
|
||||
availableLocales?: string[];
|
||||
/** 언어 설정 텍스트 */
|
||||
languageText?: string;
|
||||
/** 언어 변경 API 엔드포인트 */
|
||||
apiEndpoint?: string;
|
||||
/** 언어 변경 후 콜백 */
|
||||
onLanguageChange?: (locale: string) => void;
|
||||
/** 추가 CSS 클래스 */
|
||||
className?: string;
|
||||
/** 인라인 모드 (드롭다운 메뉴 내에서 사용) */
|
||||
inline?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* LanguageSelector 컴포넌트
|
||||
*
|
||||
* 언어 전환 드롭다운 제공
|
||||
* - DB에 언어 설정 저장
|
||||
* - localStorage에 로케일 저장
|
||||
* - 새로고침 없이 UI 리렌더링
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* // 독립적으로 사용
|
||||
* <LanguageSelector
|
||||
* availableLocales={['ko', 'en']}
|
||||
* languageText="언어"
|
||||
* />
|
||||
*
|
||||
* // 인라인 모드 (다른 드롭다운 내에서 사용)
|
||||
* <LanguageSelector
|
||||
* availableLocales={['ko', 'en']}
|
||||
* languageText="언어"
|
||||
* inline
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const LanguageSelector: React.FC<LanguageSelectorProps> = ({
|
||||
availableLocales = ['ko', 'en'],
|
||||
languageText = 'Language',
|
||||
apiEndpoint = '/api/admin/users/me/language',
|
||||
onLanguageChange,
|
||||
className = '',
|
||||
inline = false,
|
||||
}) => {
|
||||
const [showMenu, setShowMenu] = useState(false);
|
||||
const [isChanging, setIsChanging] = useState(false);
|
||||
const [currentLocale, setCurrentLocale] = useState<string>(() => {
|
||||
return localStorage.getItem('g7_locale') || 'ko';
|
||||
});
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지 (인라인 모드가 아닐 때만)
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (inline) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setShowMenu(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, [inline]);
|
||||
|
||||
/**
|
||||
* 쿠키에서 XSRF 토큰 읽기
|
||||
*/
|
||||
const getXsrfToken = (): string | null => {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; XSRF-TOKEN=`);
|
||||
if (parts.length === 2) {
|
||||
return decodeURIComponent(parts.pop()?.split(';').shift() || '');
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 로컬 스토리지에서 Bearer 토큰 읽기
|
||||
*/
|
||||
const getBearerToken = (): string | null => {
|
||||
return localStorage.getItem('auth_token');
|
||||
};
|
||||
|
||||
/**
|
||||
* 언어 변경 처리
|
||||
*/
|
||||
const handleLanguageChange = async (locale: string) => {
|
||||
if (isChanging || locale === currentLocale) return;
|
||||
|
||||
try {
|
||||
setIsChanging(true);
|
||||
|
||||
const xsrfToken = getXsrfToken();
|
||||
const bearerToken = getBearerToken();
|
||||
|
||||
// API 호출로 DB에 저장 (실패해도 UI는 변경)
|
||||
try {
|
||||
const response = await fetch(apiEndpoint, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
...(xsrfToken && { 'X-XSRF-TOKEN': xsrfToken }),
|
||||
...(bearerToken && { Authorization: `Bearer ${bearerToken}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ language: locale }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('언어 설정 저장 실패 (UI는 변경됨):', response.statusText);
|
||||
}
|
||||
} catch (apiError) {
|
||||
logger.warn('언어 설정 API 호출 실패 (UI는 변경됨):', apiError);
|
||||
}
|
||||
|
||||
// UI 상태 업데이트
|
||||
setCurrentLocale(locale);
|
||||
setShowMenu(false);
|
||||
|
||||
// 콜백 실행
|
||||
onLanguageChange?.(locale);
|
||||
|
||||
// TemplateApp의 changeLocale 호출하여 UI 리렌더링
|
||||
if ((window as any).__templateApp) {
|
||||
await (window as any).__templateApp.changeLocale(locale);
|
||||
} else {
|
||||
logger.warn('TemplateApp not found, reloading page');
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('언어 변경 오류:', error);
|
||||
} finally {
|
||||
setIsChanging(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 인라인 모드: 접기/펼치기 가능한 뱃지 방식
|
||||
if (inline) {
|
||||
return (
|
||||
<Div className={`${className}`}>
|
||||
<Button
|
||||
onClick={() => setShowMenu(!showMenu)}
|
||||
disabled={isChanging}
|
||||
className="w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors"
|
||||
>
|
||||
<Icon
|
||||
name={IconName.Globe}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400"
|
||||
/>
|
||||
<Span className="text-gray-900 dark:text-white flex-1">
|
||||
{languageText}
|
||||
</Span>
|
||||
<Span className="px-2 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded">
|
||||
{currentLocale.toUpperCase()}
|
||||
</Span>
|
||||
<Icon
|
||||
name={IconName.ChevronDown}
|
||||
className={`w-4 h-4 text-gray-400 dark:text-gray-500 transition-transform ${showMenu ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</Button>
|
||||
{showMenu && (
|
||||
<Div className="px-4 py-2 flex flex-wrap gap-2">
|
||||
{availableLocales.map((locale) => (
|
||||
<Button
|
||||
key={locale}
|
||||
onClick={() => handleLanguageChange(locale)}
|
||||
disabled={isChanging}
|
||||
className={`
|
||||
px-3 py-1.5 text-sm font-medium rounded-md transition-colors
|
||||
${
|
||||
currentLocale === locale
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}
|
||||
${isChanging ? 'opacity-50 cursor-not-allowed' : ''}
|
||||
`}
|
||||
>
|
||||
{getLocaleName(locale)}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// 독립 모드: 드롭다운 버튼과 메뉴
|
||||
return (
|
||||
<Div ref={menuRef} className={`relative ${className}`}>
|
||||
<Button
|
||||
onClick={() => setShowMenu(!showMenu)}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
|
||||
aria-label={languageText}
|
||||
>
|
||||
<Icon
|
||||
name={IconName.Globe}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400"
|
||||
/>
|
||||
</Button>
|
||||
|
||||
{showMenu && (
|
||||
<Div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div className="py-2">
|
||||
{availableLocales.map((locale) => (
|
||||
<Button
|
||||
key={locale}
|
||||
onClick={() => handleLanguageChange(locale)}
|
||||
disabled={isChanging}
|
||||
className={`
|
||||
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
|
||||
${currentLocale === locale ? 'bg-gray-50 dark:bg-gray-700' : ''}
|
||||
${isChanging ? 'opacity-50 cursor-not-allowed' : ''}
|
||||
`}
|
||||
>
|
||||
<Span className="text-gray-900 dark:text-white flex-1">
|
||||
{getLocaleName(locale)}
|
||||
</Span>
|
||||
{currentLocale === locale && (
|
||||
<Icon
|
||||
name={IconName.Check}
|
||||
className="w-4 h-4 text-blue-600 dark:text-blue-400"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H2 } from '../basic/H2';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface LayoutEditorHeaderProps {
|
||||
/**
|
||||
* 레이아웃 이름
|
||||
*/
|
||||
layoutName: string;
|
||||
|
||||
/**
|
||||
* 뒤로가기 버튼 클릭 시 콜백
|
||||
*/
|
||||
onBack: () => void;
|
||||
|
||||
/**
|
||||
* 미리보기 버튼 클릭 시 콜백
|
||||
*/
|
||||
onPreview: () => void;
|
||||
|
||||
/**
|
||||
* 저장 버튼 클릭 시 콜백
|
||||
*/
|
||||
onSave: () => void;
|
||||
|
||||
/**
|
||||
* 저장 중 상태 여부
|
||||
*/
|
||||
isSaving?: boolean;
|
||||
|
||||
/**
|
||||
* 사용자 정의 클래스
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* LayoutEditorHeader 레이아웃 편집 헤더 컴포넌트
|
||||
*
|
||||
* 레이아웃 편집 화면의 헤더 영역을 구성하는 composite 컴포넌트입니다.
|
||||
* 뒤로가기, 제목, 미리보기, 저장 버튼을 포함합니다.
|
||||
*
|
||||
* @example
|
||||
* // 기본 사용
|
||||
* <LayoutEditorHeader
|
||||
* layoutName="메인 레이아웃"
|
||||
* onBack={() => console.log('back')}
|
||||
* onPreview={() => console.log('preview')}
|
||||
* onSave={() => console.log('save')}
|
||||
* />
|
||||
*
|
||||
* // 저장 중 상태
|
||||
* <LayoutEditorHeader
|
||||
* layoutName="메인 레이아웃"
|
||||
* onBack={() => console.log('back')}
|
||||
* onPreview={() => console.log('preview')}
|
||||
* onSave={() => console.log('save')}
|
||||
* isSaving={true}
|
||||
* />
|
||||
*/
|
||||
export const LayoutEditorHeader: React.FC<LayoutEditorHeaderProps> = ({
|
||||
layoutName,
|
||||
onBack,
|
||||
onPreview,
|
||||
onSave,
|
||||
isSaving = false,
|
||||
className = '',
|
||||
}) => {
|
||||
// 컨테이너 클래스 조합
|
||||
const containerClasses = `
|
||||
flex items-center justify-between gap-4 p-4 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700
|
||||
${className}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return (
|
||||
<Div className={containerClasses}>
|
||||
{/* 좌측 영역: 뒤로가기 버튼 + 제목 */}
|
||||
<Div className="flex items-center gap-3">
|
||||
{/* 뒤로가기 버튼 */}
|
||||
<Button
|
||||
onClick={onBack}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors bg-transparent border-0 cursor-pointer"
|
||||
aria-label="뒤로가기"
|
||||
>
|
||||
<Icon
|
||||
name={IconName.ArrowLeft}
|
||||
className="text-gray-700 dark:text-gray-300"
|
||||
ariaLabel="뒤로가기"
|
||||
/>
|
||||
</Button>
|
||||
|
||||
{/* 제목 */}
|
||||
<H2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
|
||||
{layoutName}
|
||||
</H2>
|
||||
</Div>
|
||||
|
||||
{/* 우측 영역: 미리보기 버튼 + 저장 버튼 */}
|
||||
<Div className="flex items-center gap-2">
|
||||
{/* 미리보기 버튼 */}
|
||||
<Button
|
||||
onClick={onPreview}
|
||||
className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors border-0 cursor-pointer"
|
||||
aria-label="미리보기"
|
||||
>
|
||||
<Div className="flex items-center gap-2">
|
||||
<Icon
|
||||
name={IconName.Eye}
|
||||
className="text-gray-700 dark:text-gray-300"
|
||||
ariaLabel="미리보기 아이콘"
|
||||
/>
|
||||
<span>미리보기</span>
|
||||
</Div>
|
||||
</Button>
|
||||
|
||||
{/* 저장 버튼 */}
|
||||
<Button
|
||||
onClick={onSave}
|
||||
disabled={isSaving}
|
||||
className={`
|
||||
px-4 py-2 rounded-lg transition-colors border-0 cursor-pointer
|
||||
${isSaving
|
||||
? 'bg-blue-400 dark:bg-blue-600 cursor-not-allowed'
|
||||
: 'bg-blue-600 dark:bg-blue-500 hover:bg-blue-700 dark:hover:bg-blue-600'
|
||||
}
|
||||
text-white
|
||||
`.trim().replace(/\s+/g, ' ')}
|
||||
aria-label={isSaving ? '저장 중...' : '저장'}
|
||||
>
|
||||
<Div className="flex items-center gap-2">
|
||||
<Icon
|
||||
name={isSaving ? IconName.Spinner : IconName.Save}
|
||||
className={`text-white ${isSaving ? 'animate-spin' : ''}`}
|
||||
ariaLabel={isSaving ? '저장 중 아이콘' : '저장 아이콘'}
|
||||
/>
|
||||
<span>{isSaving ? '저장 중...' : '저장'}</span>
|
||||
</Div>
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,183 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Ul } from '../basic/Ul';
|
||||
import { Li } from '../basic/Li';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
export interface LayoutFileItem {
|
||||
/**
|
||||
* 파일 ID
|
||||
*/
|
||||
id: string | number;
|
||||
|
||||
/**
|
||||
* 파일명
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* 최종 수정 시간
|
||||
*/
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface LayoutFileListProps {
|
||||
/**
|
||||
* 파일 목록
|
||||
*/
|
||||
files: LayoutFileItem[];
|
||||
|
||||
/**
|
||||
* 선택된 파일 ID
|
||||
*/
|
||||
selectedId?: string | number;
|
||||
|
||||
/**
|
||||
* 파일 선택 시 콜백
|
||||
*/
|
||||
onSelect: (id: string | number) => void;
|
||||
|
||||
/**
|
||||
* 사용자 정의 클래스
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* LayoutFileList 레이아웃 파일 목록 컴포넌트
|
||||
*
|
||||
* 레이아웃 파일 목록을 표시하고 선택 기능을 제공하는 composite 컴포넌트입니다.
|
||||
* 선택된 파일은 하이라이트되며, 접근성을 위해 ARIA 속성을 지원합니다.
|
||||
*
|
||||
* @example
|
||||
* // 기본 사용
|
||||
* <LayoutFileList
|
||||
* files={[
|
||||
* { id: 1, name: 'layout1.json', updated_at: '2024-01-01T12:00:00Z' },
|
||||
* { id: 2, name: 'layout2.json', updated_at: '2024-01-02T15:30:00Z' }
|
||||
* ]}
|
||||
* selectedId={1}
|
||||
* onSelect={(id) => console.log('Selected:', id)}
|
||||
* />
|
||||
*
|
||||
* // 빈 목록
|
||||
* <LayoutFileList files={[]} onSelect={(id) => {}} />
|
||||
*/
|
||||
export const LayoutFileList: React.FC<LayoutFileListProps> = ({
|
||||
files,
|
||||
selectedId,
|
||||
onSelect,
|
||||
className = '',
|
||||
}) => {
|
||||
/**
|
||||
* ISO 날짜 문자열을 포맷팅
|
||||
*/
|
||||
const formatDate = (dateString: string): string => {
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
|
||||
// Invalid Date 체크
|
||||
if (isNaN(date.getTime())) {
|
||||
return dateString;
|
||||
}
|
||||
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
} catch {
|
||||
return dateString;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 파일 항목 클릭 핸들러
|
||||
*/
|
||||
const handleFileClick = (id: string | number) => {
|
||||
onSelect(id);
|
||||
};
|
||||
|
||||
// 컨테이너 클래스
|
||||
const containerClasses = `
|
||||
w-full
|
||||
${className}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return (
|
||||
<Div className={containerClasses}>
|
||||
{files.length === 0 ? (
|
||||
<Div className="p-4 text-center text-gray-500 dark:text-gray-400">
|
||||
파일이 없습니다.
|
||||
</Div>
|
||||
) : (
|
||||
<Ul
|
||||
className="divide-y divide-gray-200 dark:divide-gray-700"
|
||||
role="listbox"
|
||||
aria-label="레이아웃 파일 목록"
|
||||
>
|
||||
{files.map((file) => {
|
||||
const isSelected = file.id === selectedId;
|
||||
|
||||
// 항목 클래스 조합
|
||||
const itemClasses = `
|
||||
flex items-center justify-between p-4 cursor-pointer
|
||||
transition-colors duration-150
|
||||
${
|
||||
isSelected
|
||||
? 'bg-blue-100 dark:bg-blue-900 border-l-4 border-blue-500'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-800'
|
||||
}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
// 파일명 클래스
|
||||
const nameClasses = `
|
||||
font-medium
|
||||
${
|
||||
isSelected
|
||||
? 'text-blue-900 dark:text-blue-100'
|
||||
: 'text-gray-900 dark:text-gray-100'
|
||||
}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
// 날짜 클래스
|
||||
const dateClasses = `
|
||||
text-sm
|
||||
${
|
||||
isSelected
|
||||
? 'text-blue-700 dark:text-blue-300'
|
||||
: 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return (
|
||||
<Li
|
||||
key={file.id}
|
||||
className={itemClasses}
|
||||
onClick={() => handleFileClick(file.id)}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleFileClick(file.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Div className="flex flex-col gap-1">
|
||||
<Span className={nameClasses}>{file.name}</Span>
|
||||
<Span className={dateClasses}>
|
||||
{formatDate(file.updated_at)}
|
||||
</Span>
|
||||
</Div>
|
||||
</Li>
|
||||
);
|
||||
})}
|
||||
</Ul>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { VersionList, VersionItem } from './VersionList';
|
||||
|
||||
export interface LayoutHistoryPanelProps {
|
||||
/** 레이아웃 ID */
|
||||
layoutId: string | number;
|
||||
/** 버전 목록 */
|
||||
versions: VersionItem[];
|
||||
/** 버전 복원 콜백 */
|
||||
onRestore: (versionId: string | number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 히스토리 패널 컴포넌트
|
||||
* 버전 목록을 표시하고 선택된 버전을 복원하는 기능을 제공합니다.
|
||||
*/
|
||||
export const LayoutHistoryPanel: React.FC<LayoutHistoryPanelProps> = ({
|
||||
layoutId: _layoutId,
|
||||
versions,
|
||||
onRestore,
|
||||
}) => {
|
||||
const [selectedVersionId, setSelectedVersionId] = useState<string | number | undefined>();
|
||||
|
||||
const handleVersionSelect = (versionId: string | number): void => {
|
||||
setSelectedVersionId(versionId);
|
||||
};
|
||||
|
||||
const handleRestore = (): void => {
|
||||
if (selectedVersionId !== undefined) {
|
||||
onRestore(selectedVersionId);
|
||||
}
|
||||
};
|
||||
|
||||
const isRestoreDisabled = selectedVersionId === undefined;
|
||||
|
||||
return (
|
||||
<Div
|
||||
className="space-y-4"
|
||||
role="region"
|
||||
aria-label="레이아웃 히스토리 패널"
|
||||
>
|
||||
{/* 버전 목록 */}
|
||||
<Div className="border border-gray-300 dark:border-gray-600 rounded-lg p-4">
|
||||
<VersionList
|
||||
versions={versions}
|
||||
selectedId={selectedVersionId}
|
||||
onSelect={handleVersionSelect}
|
||||
/>
|
||||
</Div>
|
||||
|
||||
{/* 복원 버튼 */}
|
||||
<Div className="flex justify-end">
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={isRestoreDisabled}
|
||||
onClick={handleRestore}
|
||||
aria-label="선택한 버전으로 복원"
|
||||
>
|
||||
복원
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,159 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Alert, AlertType } from './Alert';
|
||||
|
||||
/**
|
||||
* 레이아웃 경고 타입
|
||||
*
|
||||
* 호환성 경고, 시스템 경고 등 다양한 경고 유형을 지원합니다.
|
||||
*/
|
||||
export type LayoutWarningType = 'compatibility' | 'deprecation' | 'license' | 'security' | 'system';
|
||||
|
||||
/**
|
||||
* 레이아웃 경고 레벨
|
||||
*/
|
||||
export type LayoutWarningLevel = 'info' | 'warning' | 'error';
|
||||
|
||||
/**
|
||||
* 레이아웃 경고 인터페이스
|
||||
*
|
||||
* 백엔드에서 프론트엔드로 전달되는 경고 정보입니다.
|
||||
*/
|
||||
export interface LayoutWarning {
|
||||
/** 경고 고유 ID (dismiss 처리에 사용) */
|
||||
id: string;
|
||||
/** 경고 유형 */
|
||||
type: LayoutWarningType;
|
||||
/** 경고 레벨 */
|
||||
level: LayoutWarningLevel;
|
||||
/** 사용자에게 표시할 메시지 */
|
||||
message: string;
|
||||
/** 추가 메타데이터 (경고 유형에 따라 다름) */
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* 세션 스토리지 키
|
||||
*/
|
||||
const DISMISSED_WARNINGS_KEY = 'g7_dismissed_warnings';
|
||||
|
||||
/**
|
||||
* LayoutWarnings 컴포넌트 Props
|
||||
*/
|
||||
export interface LayoutWarningsProps {
|
||||
/**
|
||||
* 표시할 경고 목록
|
||||
*/
|
||||
warnings?: LayoutWarning[];
|
||||
|
||||
/**
|
||||
* 사용자 정의 클래스
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 세션 스토리지에서 dismiss된 경고 ID 목록을 가져옵니다.
|
||||
*/
|
||||
function getDismissedWarnings(): string[] {
|
||||
try {
|
||||
const stored = sessionStorage.getItem(DISMISSED_WARNINGS_KEY);
|
||||
return stored ? JSON.parse(stored) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 세션 스토리지에 dismiss된 경고 ID를 저장합니다.
|
||||
*/
|
||||
function saveDismissedWarning(warningId: string): void {
|
||||
try {
|
||||
const dismissed = getDismissedWarnings();
|
||||
if (!dismissed.includes(warningId)) {
|
||||
dismissed.push(warningId);
|
||||
sessionStorage.setItem(DISMISSED_WARNINGS_KEY, JSON.stringify(dismissed));
|
||||
}
|
||||
} catch {
|
||||
// 세션 스토리지 사용 불가 시 무시
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* LayoutWarning의 level을 Alert의 type으로 변환합니다.
|
||||
*/
|
||||
function mapWarningLevelToAlertType(level: LayoutWarning['level']): AlertType {
|
||||
switch (level) {
|
||||
case 'error':
|
||||
return 'error';
|
||||
case 'warning':
|
||||
return 'warning';
|
||||
case 'info':
|
||||
default:
|
||||
return 'info';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* LayoutWarnings 컴포넌트
|
||||
*
|
||||
* 레이아웃의 warnings 배열을 받아서 Alert 컴포넌트들을 렌더링합니다.
|
||||
* dismiss된 경고는 세션 스토리지에 저장되어 세션 동안 다시 표시되지 않습니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON에서 사용
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "LayoutWarnings",
|
||||
* "props": {
|
||||
* "warnings": "{{_global.layoutWarnings}}"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const LayoutWarnings: React.FC<LayoutWarningsProps> = ({
|
||||
warnings,
|
||||
className = '',
|
||||
}) => {
|
||||
// dismiss된 경고 ID 목록 (세션 스토리지 기반)
|
||||
const [dismissedIds, setDismissedIds] = useState<string[]>([]);
|
||||
|
||||
// 컴포넌트 마운트 시 세션 스토리지에서 dismiss된 ID 로드
|
||||
useEffect(() => {
|
||||
setDismissedIds(getDismissedWarnings());
|
||||
}, []);
|
||||
|
||||
// 경고 dismiss 핸들러
|
||||
const handleDismiss = useCallback((warningId: string) => {
|
||||
saveDismissedWarning(warningId);
|
||||
setDismissedIds(prev => [...prev, warningId]);
|
||||
}, []);
|
||||
|
||||
// warnings가 없거나 빈 배열이면 렌더링하지 않음
|
||||
if (!warnings || warnings.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// dismiss되지 않은 경고만 필터링
|
||||
const visibleWarnings = warnings.filter(
|
||||
warning => !dismissedIds.includes(warning.id)
|
||||
);
|
||||
|
||||
// 표시할 경고가 없으면 렌더링하지 않음
|
||||
if (visibleWarnings.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Div className={`space-y-2 ${className}`.trim()}>
|
||||
{visibleWarnings.map(warning => (
|
||||
<Alert
|
||||
key={warning.id}
|
||||
type={mapWarningLevelToAlertType(warning.level)}
|
||||
message={warning.message}
|
||||
dismissible
|
||||
onDismiss={() => handleDismiss(warning.id)}
|
||||
/>
|
||||
))}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export type SpinnerSize = 'sm' | 'md' | 'lg' | 'xl';
|
||||
|
||||
export interface LoadingSpinnerProps {
|
||||
id?: string;
|
||||
size?: SpinnerSize;
|
||||
color?: string;
|
||||
fullscreen?: boolean;
|
||||
text?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* LoadingSpinner 집합 컴포넌트
|
||||
*
|
||||
* 로딩 상태를 시각적으로 표시하는 스피너 컴포넌트.
|
||||
* size, color, fullscreen 모드, text 라벨 옵션 제공.
|
||||
*
|
||||
* 기본 컴포넌트 조합:
|
||||
* - Div(컨테이너) > Div(스피너) + Span(텍스트, 옵션)
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "LoadingSpinner",
|
||||
* "props": {
|
||||
* "size": "lg",
|
||||
* "text": "데이터를 불러오는 중...",
|
||||
* "fullscreen": false
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const LoadingSpinner: React.FC<LoadingSpinnerProps> = ({
|
||||
id,
|
||||
size = 'md',
|
||||
color = 'text-blue-600',
|
||||
fullscreen = false,
|
||||
text,
|
||||
className = '',
|
||||
}) => {
|
||||
// size별 스피너 크기 매핑
|
||||
const sizeClassMap: Record<SpinnerSize, string> = {
|
||||
sm: 'w-4 h-4 border-2',
|
||||
md: 'w-8 h-8 border-2',
|
||||
lg: 'w-12 h-12 border-3',
|
||||
xl: 'w-16 h-16 border-4',
|
||||
};
|
||||
|
||||
// size별 텍스트 크기 매핑
|
||||
const textSizeClassMap: Record<SpinnerSize, string> = {
|
||||
sm: 'text-xs',
|
||||
md: 'text-sm',
|
||||
lg: 'text-base',
|
||||
xl: 'text-lg',
|
||||
};
|
||||
|
||||
const spinnerContent = (
|
||||
<Div className={`flex flex-col items-center justify-center gap-3 ${className}`}>
|
||||
{/* Spinner */}
|
||||
<Div
|
||||
className={`
|
||||
${sizeClassMap[size]}
|
||||
border-gray-200 dark:border-gray-700 border-t-current
|
||||
rounded-full animate-spin
|
||||
${color}
|
||||
`}
|
||||
role="status"
|
||||
aria-label={t('common.loading')}
|
||||
/>
|
||||
|
||||
{/* Text Label */}
|
||||
{text && (
|
||||
<Span className={`${textSizeClassMap[size]} ${color} font-medium`}>
|
||||
{text}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
|
||||
if (fullscreen) {
|
||||
return (
|
||||
<Div
|
||||
id={id}
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-white dark:bg-gray-900 bg-opacity-90 dark:bg-opacity-90"
|
||||
aria-live="polite"
|
||||
aria-busy="true"
|
||||
>
|
||||
{spinnerContent}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Div
|
||||
id={id}
|
||||
className="flex items-center justify-center p-4"
|
||||
aria-live="polite"
|
||||
aria-busy="true"
|
||||
>
|
||||
{spinnerContent}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,301 @@
|
||||
import React, { useState, type FormEvent } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Form } from '../basic/Form';
|
||||
import { Label } from '../basic/Label';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Button } from '../basic/Button';
|
||||
import { A } from '../basic/A';
|
||||
import { P } from '../basic/P';
|
||||
import { Svg } from '../basic/Svg';
|
||||
|
||||
/**
|
||||
* LoginForm props 인터페이스
|
||||
*/
|
||||
export interface LoginFormProps {
|
||||
/** 이메일 라벨 텍스트 */
|
||||
emailLabel?: string;
|
||||
/** 비밀번호 라벨 텍스트 */
|
||||
passwordLabel?: string;
|
||||
/** 로그인 버튼 텍스트 */
|
||||
submitButtonText?: string;
|
||||
/** 처리 중 텍스트 */
|
||||
processingText?: string;
|
||||
/** 이메일 입력 필드 placeholder */
|
||||
emailPlaceholder?: string;
|
||||
/** 비밀번호 입력 필드 placeholder */
|
||||
passwordPlaceholder?: string;
|
||||
/** 비밀번호 찾기 텍스트 */
|
||||
forgotPasswordText?: string;
|
||||
/** 비밀번호 찾기 URL */
|
||||
forgotPasswordUrl?: string;
|
||||
/** 이메일 필수 입력 에러 메시지 */
|
||||
emailRequiredError?: string;
|
||||
/** 이메일 형식 에러 메시지 */
|
||||
emailInvalidError?: string;
|
||||
/** 비밀번호 필수 입력 에러 메시지 */
|
||||
passwordRequiredError?: string;
|
||||
/** 폼 제출 핸들러 */
|
||||
onSubmit?: (data: { email: string; password: string }) => void;
|
||||
/** 로딩 액션 맵 (ActionDispatcher에서 전달) */
|
||||
loadingActions?: Record<string, boolean>;
|
||||
/** 외부에서 직접 로딩 상태 제어 */
|
||||
isLoading?: boolean;
|
||||
/** 외부에서 직접 비활성화 상태 제어 */
|
||||
disabled?: boolean;
|
||||
/** API 에러 메시지 (ActionDispatcher에서 전달) */
|
||||
apiError?: string;
|
||||
/** 커스텀 className */
|
||||
className?: string;
|
||||
/** 커스텀 스타일 */
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* 에러 상태 인터페이스
|
||||
*/
|
||||
interface FormErrors {
|
||||
email?: string;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* LoginForm 집합 컴포넌트
|
||||
*
|
||||
* 관리자 로그인 폼의 UI 및 상태 관리를 담당합니다.
|
||||
* - 이메일/비밀번호 입력 폼
|
||||
* - 유효성 검증
|
||||
* - 로딩 상태 표시
|
||||
* - 다크 모드 지원
|
||||
* - Laravel Sanctum API 통신
|
||||
*/
|
||||
export const LoginForm: React.FC<LoginFormProps> = ({
|
||||
emailLabel = 'Email',
|
||||
passwordLabel = 'Password',
|
||||
submitButtonText = 'Sign In',
|
||||
processingText = 'Processing...',
|
||||
emailPlaceholder = 'Email',
|
||||
passwordPlaceholder = 'Password',
|
||||
forgotPasswordText = 'Forgot your password?',
|
||||
forgotPasswordUrl = '/admin/password/reset',
|
||||
emailRequiredError = 'Please enter your email.',
|
||||
emailInvalidError = 'Please enter a valid email address.',
|
||||
passwordRequiredError = 'Please enter your password.',
|
||||
onSubmit,
|
||||
loadingActions = {},
|
||||
isLoading: isLoadingProp = false,
|
||||
disabled: disabledProp = false,
|
||||
apiError: apiErrorProp = '',
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
// 폼 상태 관리
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
|
||||
// ActionDispatcher에서 전달된 apiError를 사용 (prop이 우선)
|
||||
const apiError = apiErrorProp;
|
||||
|
||||
// loadingActions로부터 isLoading 계산
|
||||
// 외부 isLoading prop 또는 loadingActions 중 하나라도 true이면 로딩 중
|
||||
const isLoadingFromActions = Object.values(loadingActions).some((loading) => loading === true);
|
||||
const isLoading = isLoadingProp || isLoadingFromActions;
|
||||
const isDisabled = disabledProp || isLoading;
|
||||
|
||||
/**
|
||||
* 유효성 검증
|
||||
*/
|
||||
const validate = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
// 이메일 검증 (RFC 5322 기반 더 엄격한 정규식)
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
if (!email || email.trim() === '') {
|
||||
newErrors.email = emailRequiredError;
|
||||
} else if (!emailRegex.test(email)) {
|
||||
newErrors.email = emailInvalidError;
|
||||
}
|
||||
|
||||
// 비밀번호 검증
|
||||
if (!password || password.trim() === '') {
|
||||
newErrors.password = passwordRequiredError;
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 폼 제출 핸들러 래퍼
|
||||
*
|
||||
* ActionDispatcher의 핸들러를 실행하기 전에 클라이언트 검증을 수행합니다.
|
||||
*/
|
||||
const handleSubmit = async (e: FormEvent<HTMLFormElement>): Promise<void> => {
|
||||
// 유효성 검증
|
||||
if (!validate()) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
// 에러 초기화 (클라이언트 검증 에러만)
|
||||
setErrors({});
|
||||
|
||||
// ActionDispatcher의 핸들러 실행 (onSubmit prop으로 전달됨)
|
||||
if (onSubmit) {
|
||||
// onSubmit은 ActionDispatcher.createHandler가 생성한 핸들러
|
||||
// 내부적으로 event.preventDefault(), FormData 추출, API 호출을 처리함
|
||||
// onError 핸들러에서 setError를 사용하면 apiError prop이 업데이트됨
|
||||
await (onSubmit as any)(e);
|
||||
} else {
|
||||
// onSubmit이 없으면 기본 동작 방지
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Div className={`w-full ${className}`} style={style}>
|
||||
<Form onSubmit={handleSubmit} className="space-y-6" noValidate>
|
||||
{/* API 에러 메시지 */}
|
||||
{apiError && (
|
||||
<Div className="p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800">
|
||||
<P className="text-sm text-red-600 dark:text-red-400">{apiError}</P>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 이메일 입력 필드 */}
|
||||
<Div>
|
||||
<Label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
|
||||
>
|
||||
{emailLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={emailPlaceholder}
|
||||
disabled={isDisabled}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg border
|
||||
${
|
||||
errors.email
|
||||
? 'border-red-500 focus:border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 dark:border-gray-600 focus:border-blue-500 focus:ring-blue-500'
|
||||
}
|
||||
bg-white dark:bg-gray-800
|
||||
text-gray-900 dark:text-white
|
||||
placeholder-gray-400 dark:placeholder-gray-500
|
||||
focus:outline-none focus:ring-2
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
transition-colors duration-200
|
||||
`}
|
||||
/>
|
||||
{errors.email && (
|
||||
<P className="mt-2 text-sm text-red-600 dark:text-red-400">
|
||||
{errors.email}
|
||||
</P>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 비밀번호 입력 필드 */}
|
||||
<Div>
|
||||
<Label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
|
||||
>
|
||||
{passwordLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={passwordPlaceholder}
|
||||
disabled={isDisabled}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg border
|
||||
${
|
||||
errors.password
|
||||
? 'border-red-500 focus:border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 dark:border-gray-600 focus:border-blue-500 focus:ring-blue-500'
|
||||
}
|
||||
bg-white dark:bg-gray-800
|
||||
text-gray-900 dark:text-white
|
||||
placeholder-gray-400 dark:placeholder-gray-500
|
||||
focus:outline-none focus:ring-2
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
transition-colors duration-200
|
||||
`}
|
||||
/>
|
||||
{errors.password && (
|
||||
<P className="mt-2 text-sm text-red-600 dark:text-red-400">
|
||||
{errors.password}
|
||||
</P>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 비밀번호 찾기 링크 */}
|
||||
{forgotPasswordUrl && (
|
||||
<Div className="flex items-center justify-end">
|
||||
<A
|
||||
href={forgotPasswordUrl}
|
||||
className="text-sm text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors duration-200"
|
||||
>
|
||||
{forgotPasswordText}
|
||||
</A>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 제출 버튼 */}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isDisabled}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg font-medium
|
||||
bg-blue-600 hover:bg-blue-700
|
||||
dark:bg-blue-500 dark:hover:bg-blue-600
|
||||
text-white
|
||||
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
|
||||
dark:focus:ring-offset-gray-900
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
transition-colors duration-200
|
||||
flex items-center justify-center
|
||||
`}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Svg
|
||||
className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
></circle>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
></path>
|
||||
</Svg>
|
||||
{processingText}
|
||||
</>
|
||||
) : (
|
||||
submitButtonText
|
||||
)}
|
||||
</Button>
|
||||
</Form>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,259 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export interface ModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title?: string;
|
||||
/** 타이틀 앞에 렌더링할 컴포넌트 배열 (레이아웃 JSON) */
|
||||
titlePrefix?: any[];
|
||||
/** 타이틀 뒤에 렌더링할 컴포넌트 배열 (레이아웃 JSON) */
|
||||
titleSuffix?: any[];
|
||||
/**
|
||||
* Backdrop(오버레이) 클릭 시 모달 닫기 여부
|
||||
* @default true
|
||||
*/
|
||||
closeOnBackdropClick?: boolean;
|
||||
/**
|
||||
* closeOnOverlayClick 별칭 (레이아웃 JSON 호환)
|
||||
* @default true
|
||||
*/
|
||||
closeOnOverlayClick?: boolean;
|
||||
/**
|
||||
* 헤더 닫기 버튼 표시 여부
|
||||
* @default true
|
||||
*/
|
||||
showCloseButton?: boolean;
|
||||
/**
|
||||
* ESC 키로 모달 닫기 허용 여부
|
||||
* @default true
|
||||
*/
|
||||
closeOnEscape?: boolean;
|
||||
children?: React.ReactNode;
|
||||
width?: string;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
/** DynamicRenderer용 데이터 컨텍스트 (내부 사용) */
|
||||
__dataContext?: Record<string, any>;
|
||||
/** DynamicRenderer용 번역 컨텍스트 (내부 사용) */
|
||||
__translationContext?: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modal 집합 컴포넌트
|
||||
*
|
||||
* Div + Button 기본 컴포넌트를 조합하여 모달 UI를 구성합니다.
|
||||
* ESC 키 닫기, 포커스 트랩, 오버레이 클릭 닫기 기능을 포함합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Modal",
|
||||
* "props": {
|
||||
* "isOpen": "{{modals.userEdit}}",
|
||||
* "title": "사용자 편집",
|
||||
* "width": "600px"
|
||||
* },
|
||||
* "children": [...]
|
||||
* }
|
||||
*/
|
||||
export const Modal: React.FC<ModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
titlePrefix,
|
||||
titleSuffix,
|
||||
closeOnBackdropClick = true,
|
||||
closeOnOverlayClick,
|
||||
showCloseButton = true,
|
||||
closeOnEscape = true,
|
||||
children,
|
||||
width = '500px',
|
||||
className = '',
|
||||
style,
|
||||
__dataContext,
|
||||
__translationContext,
|
||||
}) => {
|
||||
// closeOnOverlayClick 별칭 지원 (레이아웃 JSON 호환)
|
||||
const shouldCloseOnBackdrop = closeOnOverlayClick !== undefined
|
||||
? closeOnOverlayClick
|
||||
: closeOnBackdropClick;
|
||||
const modalRef = useRef<HTMLDivElement>(null);
|
||||
const previousFocusRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
// ESC 키로 모달 닫기
|
||||
useEffect(() => {
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && isOpen && closeOnEscape) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen && closeOnEscape) {
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
return () => document.removeEventListener('keydown', handleEscape);
|
||||
}
|
||||
}, [isOpen, onClose, closeOnEscape]);
|
||||
|
||||
// 포커스 트랩
|
||||
useEffect(() => {
|
||||
if (isOpen && modalRef.current) {
|
||||
// 모달 열릴 때 현재 포커스 저장
|
||||
previousFocusRef.current = document.activeElement as HTMLElement;
|
||||
|
||||
// 모달 내부 포커스 가능한 요소들
|
||||
const focusableElements = modalRef.current.querySelectorAll(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
|
||||
const firstElement = focusableElements[0] as HTMLElement;
|
||||
const lastElement = focusableElements[focusableElements.length - 1] as HTMLElement;
|
||||
|
||||
// 첫 번째 요소에 포커스
|
||||
firstElement?.focus();
|
||||
|
||||
// Tab 키 핸들러 (포커스 트랩)
|
||||
const handleTab = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Tab') return;
|
||||
|
||||
if (event.shiftKey) {
|
||||
// Shift + Tab
|
||||
if (document.activeElement === firstElement) {
|
||||
event.preventDefault();
|
||||
lastElement?.focus();
|
||||
}
|
||||
} else {
|
||||
// Tab
|
||||
if (document.activeElement === lastElement) {
|
||||
event.preventDefault();
|
||||
firstElement?.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleTab);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleTab);
|
||||
// 모달 닫힐 때 이전 포커스 복원
|
||||
previousFocusRef.current?.focus();
|
||||
};
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
// body 스크롤 방지
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
// z-index를 style에서 가져오거나 기본값 50 사용
|
||||
const zIndex = style?.zIndex ?? 50;
|
||||
|
||||
// titlePrefix/titleSuffix 렌더링 헬퍼
|
||||
const renderTitleComponents = (components: any[] | undefined, keyPrefix: string) => {
|
||||
if (!components || components.length === 0) return null;
|
||||
|
||||
const g7Core = (window as any).G7Core;
|
||||
if (!g7Core) return null;
|
||||
|
||||
const DynamicRenderer = g7Core.getDynamicRenderer?.();
|
||||
if (!DynamicRenderer) return null;
|
||||
|
||||
return components.map((componentDef, index) => (
|
||||
<DynamicRenderer
|
||||
key={`${keyPrefix}-${index}`}
|
||||
componentDef={componentDef}
|
||||
dataContext={__dataContext || {}}
|
||||
translationContext={__translationContext}
|
||||
registry={g7Core.getComponentRegistry()}
|
||||
bindingEngine={g7Core.getDataBindingEngine()}
|
||||
translationEngine={g7Core.getTranslationEngine()}
|
||||
actionDispatcher={g7Core.getActionDispatcher()}
|
||||
isRootRenderer={false}
|
||||
/>
|
||||
));
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
className="fixed inset-0 flex items-center justify-center"
|
||||
style={{ zIndex }}
|
||||
onClick={shouldCloseOnBackdrop ? onClose : undefined}
|
||||
>
|
||||
{/* Overlay */}
|
||||
<Div
|
||||
className="absolute inset-0 bg-black/50"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
{/* Modal Content */}
|
||||
<Div
|
||||
ref={modalRef}
|
||||
className={`relative bg-white dark:bg-gray-800 rounded-lg shadow-xl max-h-[90vh] overflow-hidden ${className}`}
|
||||
style={{ width, ...(style ? { ...style, zIndex: undefined } : {}) }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={title ? 'modal-title' : undefined}
|
||||
>
|
||||
{/* Header */}
|
||||
{(title || titlePrefix || titleSuffix || showCloseButton) && (
|
||||
<Div className="flex items-center justify-between p-4">
|
||||
<Div className="flex items-center gap-2">
|
||||
{/* titlePrefix: 타이틀 앞에 렌더링 */}
|
||||
{renderTitleComponents(titlePrefix, 'title-prefix')}
|
||||
{title && (
|
||||
<Div
|
||||
id="modal-title"
|
||||
className="text-lg font-semibold text-gray-900 dark:text-white"
|
||||
>
|
||||
{title}
|
||||
</Div>
|
||||
)}
|
||||
{/* titleSuffix: 타이틀 뒤에 렌더링 */}
|
||||
{renderTitleComponents(titleSuffix, 'title-suffix')}
|
||||
</Div>
|
||||
{showCloseButton && (
|
||||
<Button
|
||||
onClick={onClose}
|
||||
className="ml-auto text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 focus:outline-none"
|
||||
aria-label={t('common.close_modal')}
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* Body */}
|
||||
<Div className="px-6 py-4 overflow-y-auto max-h-[calc(90vh-140px)]">
|
||||
{children}
|
||||
</Div>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+634
@@ -0,0 +1,634 @@
|
||||
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Textarea } from '../basic/Textarea';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
// G7Core에서 지원 언어 목록 가져오기
|
||||
const getSupportedLocales = (): string[] => {
|
||||
return (window as any).G7Core?.locale?.supported?.() ?? ['ko', 'en'];
|
||||
};
|
||||
|
||||
// G7Core에서 현재 언어 가져오기
|
||||
const getCurrentLocale = (): string => {
|
||||
return (window as any).G7Core?.locale?.current?.() ?? 'ko';
|
||||
};
|
||||
|
||||
// 언어 코드로 언어명 가져오기 (다국어 키 사용)
|
||||
const getLocaleNameByCode = (code: string): string => {
|
||||
// 다국어 키에서 언어명 가져오기 (common.language_ko, common.language_en 등)
|
||||
const translatedName = t(`common.language_${code}`);
|
||||
|
||||
// 번역이 키 그대로 반환되면 (번역 없음) fallback 맵 사용
|
||||
if (translatedName === `common.language_${code}`) {
|
||||
const fallbackNames: Record<string, string> = {
|
||||
ko: '한국어',
|
||||
en: 'English',
|
||||
ja: '日本語',
|
||||
zh: '中文',
|
||||
};
|
||||
return fallbackNames[code] || code.toUpperCase();
|
||||
}
|
||||
|
||||
return translatedName;
|
||||
};
|
||||
|
||||
// 시스템 언어 목록을 LocaleOption[]으로 변환
|
||||
const getSystemLocaleOptions = (): LocaleOption[] => {
|
||||
const supportedLocales = getSupportedLocales();
|
||||
return supportedLocales.map(code => ({
|
||||
code,
|
||||
name: getLocaleNameByCode(code),
|
||||
nativeName: getLocaleNameByCode(code),
|
||||
}));
|
||||
};
|
||||
|
||||
export interface MultilingualValue {
|
||||
[locale: string]: string;
|
||||
}
|
||||
|
||||
export interface LocaleOption {
|
||||
code: string;
|
||||
name: string;
|
||||
nativeName?: string;
|
||||
}
|
||||
|
||||
export type MultilingualInputType = 'text' | 'textarea';
|
||||
export type MultilingualInputLayout = 'inline' | 'tabs' | 'compact';
|
||||
|
||||
export interface MultilingualInputProps {
|
||||
/** 다국어 값 객체 */
|
||||
value?: MultilingualValue;
|
||||
/** 값 변경 콜백 */
|
||||
onChange?: (event: any) => void;
|
||||
/** 입력 타입 (text | textarea) */
|
||||
inputType?: MultilingualInputType;
|
||||
/** 레이아웃 타입 (inline: 모든 언어 수직 표시 | tabs: 탭 전환 방식 | compact: 탭과 입력이 한 줄) */
|
||||
layout?: MultilingualInputLayout;
|
||||
/** 사용 가능한 언어 목록 */
|
||||
availableLocales?: LocaleOption[];
|
||||
/** 기본 언어 코드 */
|
||||
defaultLocale?: string;
|
||||
/** 입력창 placeholder */
|
||||
placeholder?: string;
|
||||
/** 필수 입력 여부 */
|
||||
required?: boolean;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 최대 길이 */
|
||||
maxLength?: number;
|
||||
/** textarea 행 수 (inputType이 'textarea'일 때만 사용) */
|
||||
rows?: number;
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
/** input name */
|
||||
name?: string;
|
||||
/** 모바일에서 언어 코드로 표시 (기본값: false) */
|
||||
showCodeOnMobile?: boolean;
|
||||
/** 에러 메시지 (입력 필드에 적색 테두리 표시) */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 입력 컴포넌트
|
||||
*
|
||||
* 두 가지 레이아웃 모드를 지원합니다:
|
||||
* - inline (기본): 카드 형태로 모든 언어를 수직으로 쌓아서 표시
|
||||
* - tabs: 탭 방식으로 언어 전환 (카드 형태)
|
||||
*/
|
||||
export const MultilingualInput: React.FC<MultilingualInputProps> = ({
|
||||
value = {},
|
||||
onChange,
|
||||
inputType = 'text',
|
||||
layout = 'inline',
|
||||
availableLocales,
|
||||
defaultLocale,
|
||||
placeholder = '',
|
||||
required = false,
|
||||
disabled = false,
|
||||
maxLength,
|
||||
rows = 4,
|
||||
className = '',
|
||||
name = 'multilingual_input',
|
||||
showCodeOnMobile = false,
|
||||
error,
|
||||
}) => {
|
||||
|
||||
// 에러 상태 여부
|
||||
const hasError = !!error;
|
||||
// G7Core에서 실제 사용할 언어 목록과 기본 언어 계산
|
||||
const actualAvailableLocales = useMemo(() => {
|
||||
return availableLocales ?? getSystemLocaleOptions();
|
||||
}, [availableLocales]);
|
||||
|
||||
const actualDefaultLocale = useMemo(() => {
|
||||
return defaultLocale ?? getCurrentLocale();
|
||||
}, [defaultLocale]);
|
||||
|
||||
// ── 로컬 상태 버퍼 (debounce 대기 중 사용자 입력값 보존) ──
|
||||
// props.value는 debounce가 fire된 후에야 갱신되므로,
|
||||
// locale 탭 전환 시 stale props.value로 렌더링되어 입력값이 유실됨.
|
||||
// localValue는 사용자 입력을 즉시 반영하고, props.value 갱신 시 동기화함.
|
||||
const localValueRef = useRef<MultilingualValue>(value);
|
||||
const [localValue, setLocalValue] = useState<MultilingualValue>(value);
|
||||
|
||||
// props.value의 이전 내용을 추적 — 내용 기반 비교로 불필요한 동기화 방지
|
||||
const lastExternalValueRef = useRef<string>(JSON.stringify(value));
|
||||
|
||||
// props.value 외부 변경 시 로컬 상태 동기화
|
||||
// 동일 내용의 새 객체 참조(부모 rerender)는 무시하여 로컬 편집분 보존
|
||||
useEffect(() => {
|
||||
const valueStr = JSON.stringify(value);
|
||||
if (valueStr !== lastExternalValueRef.current) {
|
||||
lastExternalValueRef.current = valueStr;
|
||||
localValueRef.current = value;
|
||||
setLocalValue(value);
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
// 공통 onChange 호출 헬퍼
|
||||
const emitChange = useCallback((newValue: MultilingualValue, changedKeys?: string[]) => {
|
||||
const event: any = {
|
||||
target: {
|
||||
name,
|
||||
value: newValue,
|
||||
},
|
||||
};
|
||||
// _changedKeys: 엔진 디바운스 병합에서 stale closure로 인한 키 유실 방지
|
||||
if (changedKeys) {
|
||||
event._changedKeys = changedKeys;
|
||||
}
|
||||
onChange?.(event);
|
||||
}, [onChange, name]);
|
||||
|
||||
// 활성화된 언어 탭 목록 (기본 언어는 항상 포함)
|
||||
const [activeLocales, setActiveLocales] = useState<string[]>(() => {
|
||||
// tabs/compact 레이아웃일 때는 모든 지원 로케일을 표시
|
||||
if (layout === 'tabs' || layout === 'compact') {
|
||||
const supportedCodes = actualAvailableLocales.map(l => l.code);
|
||||
// 기본 언어를 맨 앞에 배치
|
||||
const sorted = [actualDefaultLocale, ...supportedCodes.filter(c => c !== actualDefaultLocale)];
|
||||
return sorted;
|
||||
}
|
||||
|
||||
const valueKeys = Object.keys(value).filter(key => value[key] !== undefined);
|
||||
|
||||
if (valueKeys.length === 0) {
|
||||
return [actualDefaultLocale];
|
||||
}
|
||||
|
||||
// 기본 언어를 맨 앞에 배치
|
||||
const locales: string[] = [];
|
||||
|
||||
// 1. 기본 언어가 있으면 맨 앞에 추가
|
||||
if (valueKeys.includes(actualDefaultLocale)) {
|
||||
locales.push(actualDefaultLocale);
|
||||
}
|
||||
|
||||
// 2. 나머지 언어들 추가 (기본 언어 제외)
|
||||
valueKeys.forEach(key => {
|
||||
if (key !== actualDefaultLocale) {
|
||||
locales.push(key);
|
||||
}
|
||||
});
|
||||
|
||||
return locales;
|
||||
});
|
||||
|
||||
// 현재 선택된 언어 탭 (tabs 레이아웃용)
|
||||
const [currentLocale, setCurrentLocale] = useState<string>(actualDefaultLocale);
|
||||
|
||||
// 추가 가능한 언어 목록 (이미 활성화된 언어 제외)
|
||||
const addableLocales = useMemo(() => {
|
||||
return actualAvailableLocales.filter(locale => !activeLocales.includes(locale.code));
|
||||
}, [actualAvailableLocales, activeLocales]);
|
||||
|
||||
// 언어 추가 드롭다운 표시 여부
|
||||
const [showAddMenu, setShowAddMenu] = useState(false);
|
||||
|
||||
// value prop이 변경될 때 activeLocales 동기화
|
||||
useEffect(() => {
|
||||
// tabs/compact 레이아웃일 때는 항상 모든 지원 로케일 유지
|
||||
if (layout === 'tabs' || layout === 'compact') {
|
||||
const supportedCodes = actualAvailableLocales.map(l => l.code);
|
||||
const sorted = [actualDefaultLocale, ...supportedCodes.filter(c => c !== actualDefaultLocale)];
|
||||
const currentStr = activeLocales.join(',');
|
||||
const newStr = sorted.join(',');
|
||||
if (currentStr !== newStr) {
|
||||
setActiveLocales(sorted);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const valueKeys = Object.keys(value).filter(key => value[key] !== undefined);
|
||||
|
||||
// value가 비어있거나 모든 값이 빈 문자열이면 기본 언어만 표시
|
||||
if (valueKeys.length === 0) {
|
||||
setActiveLocales([actualDefaultLocale]);
|
||||
return;
|
||||
}
|
||||
|
||||
// value에 있는 언어들로 activeLocales 구성
|
||||
// 기본 언어를 맨 앞에 배치
|
||||
const newLocales: string[] = [];
|
||||
|
||||
// 1. 기본 언어가 있으면 맨 앞에 추가
|
||||
if (valueKeys.includes(actualDefaultLocale)) {
|
||||
newLocales.push(actualDefaultLocale);
|
||||
}
|
||||
|
||||
// 2. 나머지 언어들 추가 (기본 언어 제외)
|
||||
valueKeys.forEach(key => {
|
||||
if (key !== actualDefaultLocale) {
|
||||
newLocales.push(key);
|
||||
}
|
||||
});
|
||||
|
||||
// 순서를 유지하면서 비교하여 변경되었을 때만 업데이트
|
||||
const currentStr = activeLocales.join(',');
|
||||
const newStr = newLocales.join(',');
|
||||
|
||||
if (currentStr !== newStr) {
|
||||
setActiveLocales(newLocales);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value, actualDefaultLocale, layout, actualAvailableLocales]);
|
||||
|
||||
// 언어 입력값 변경 핸들러
|
||||
// localValueRef 사용: debounce 대기 중에도 최신 입력값 기반으로 병합
|
||||
const handleInputChange = useCallback((locale: string, inputValue: string) => {
|
||||
const newValue = {
|
||||
...localValueRef.current,
|
||||
[locale]: inputValue,
|
||||
};
|
||||
localValueRef.current = newValue;
|
||||
setLocalValue(newValue);
|
||||
emitChange(newValue, [locale]);
|
||||
}, [emitChange]);
|
||||
|
||||
// 언어 탭 추가
|
||||
const handleAddLocale = useCallback((localeCode: string) => {
|
||||
setActiveLocales(prev => [...prev, localeCode]);
|
||||
setCurrentLocale(localeCode);
|
||||
setShowAddMenu(false);
|
||||
|
||||
// 새 언어 필드를 빈 문자열로 초기화
|
||||
const newValue = {
|
||||
...localValueRef.current,
|
||||
[localeCode]: '',
|
||||
};
|
||||
localValueRef.current = newValue;
|
||||
setLocalValue(newValue);
|
||||
emitChange(newValue);
|
||||
}, [emitChange]);
|
||||
|
||||
// 언어 탭 제거
|
||||
const handleRemoveLocale = useCallback((localeCode: string) => {
|
||||
// 기본 언어는 제거 불가
|
||||
if (localeCode === actualDefaultLocale) return;
|
||||
|
||||
setActiveLocales(prev => prev.filter(code => code !== localeCode));
|
||||
|
||||
// 제거된 언어가 현재 선택된 언어면 기본 언어로 전환
|
||||
if (currentLocale === localeCode) {
|
||||
setCurrentLocale(actualDefaultLocale);
|
||||
}
|
||||
|
||||
// value에서 해당 언어 제거
|
||||
const newValue = { ...localValueRef.current };
|
||||
delete newValue[localeCode];
|
||||
localValueRef.current = newValue;
|
||||
setLocalValue(newValue);
|
||||
emitChange(newValue);
|
||||
}, [currentLocale, actualDefaultLocale, emitChange]);
|
||||
|
||||
// 언어명 표시
|
||||
const getLocaleName = useCallback((localeCode: string) => {
|
||||
const locale = actualAvailableLocales.find(l => l.code === localeCode);
|
||||
return locale?.nativeName || locale?.name || localeCode.toUpperCase();
|
||||
}, [actualAvailableLocales]);
|
||||
|
||||
// 입력 필드가 채워져 있는지 확인
|
||||
const hasValue = useCallback((localeCode: string) => {
|
||||
return Boolean(localValue[localeCode]?.trim());
|
||||
}, [localValue]);
|
||||
|
||||
// 언어 추가 버튼 렌더링 (Pill Badge 스타일)
|
||||
const renderAddLocaleButtonCompact = useCallback(() => {
|
||||
if (addableLocales.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Div className="relative">
|
||||
<Button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1 px-3 py-1 text-xs font-medium text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/30 hover:bg-blue-100 dark:hover:bg-blue-900/50 rounded-full border border-dashed border-blue-300 dark:border-blue-600 transition-colors"
|
||||
onClick={() => setShowAddMenu(!showAddMenu)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Icon name="plus" className="w-3 h-3" />
|
||||
<Span>{t('common.add_language')}</Span>
|
||||
</Button>
|
||||
|
||||
{showAddMenu && (
|
||||
<Div className="absolute top-full left-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-10 min-w-[120px]">
|
||||
{addableLocales.map(locale => (
|
||||
<Button
|
||||
key={locale.code}
|
||||
type="button"
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 first:rounded-t-lg last:rounded-b-lg transition-colors"
|
||||
onClick={() => handleAddLocale(locale.code)}
|
||||
>
|
||||
<Icon name="globe" className="w-3.5 h-3.5 text-gray-400 dark:text-gray-500" />
|
||||
<Span>{locale.nativeName || locale.name}</Span>
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
}, [addableLocales, showAddMenu, disabled, handleAddLocale]);
|
||||
|
||||
// 입력 필드 렌더링 (라벨 위에 표시) - Pill Badge 스타일
|
||||
const renderInputFieldWithTopLabel = useCallback((localeCode: string, showAddButton: boolean = false) => {
|
||||
const errorBorderClass = hasError
|
||||
? 'border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500'
|
||||
: 'border-gray-200 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500';
|
||||
const inputClassName = `w-full px-3 py-2 border ${errorBorderClass} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2`;
|
||||
const isDefault = localeCode === actualDefaultLocale;
|
||||
const localizedPlaceholder = `${placeholder}${placeholder ? ' (' : ''}${getLocaleName(localeCode)}${placeholder ? ')' : ''}`;
|
||||
|
||||
return (
|
||||
<Div key={localeCode} className="space-y-2">
|
||||
{/* 언어 배지 (Pill Badge 스타일) */}
|
||||
<Div className="flex items-center gap-2">
|
||||
<Span className={`
|
||||
inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium
|
||||
${isDefault
|
||||
? 'bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300'
|
||||
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300'
|
||||
}
|
||||
`}>
|
||||
{/* 다국어 아이콘 */}
|
||||
<Icon name="globe" className="w-3 h-3" />
|
||||
{getLocaleName(localeCode)}
|
||||
{isDefault && <Span className="text-red-500 dark:text-red-400">*</Span>}
|
||||
{/* 비기본 언어 삭제 버튼 - 배지 안에 */}
|
||||
{!isDefault && (
|
||||
<Button
|
||||
type="button"
|
||||
className="ml-0.5 p-0.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
|
||||
onClick={() => handleRemoveLocale(localeCode)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Icon name="xmark" className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
</Span>
|
||||
{/* 기본 언어 옆에 추가 버튼 */}
|
||||
{isDefault && showAddButton && renderAddLocaleButtonCompact()}
|
||||
</Div>
|
||||
|
||||
{/* 입력 필드 */}
|
||||
{inputType === 'textarea' ? (
|
||||
<Textarea
|
||||
name={`${name}[${localeCode}]`}
|
||||
value={localValue[localeCode] || ''}
|
||||
onChange={(e) => handleInputChange(localeCode, e.target.value)}
|
||||
placeholder={localizedPlaceholder}
|
||||
required={required && isDefault}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
rows={rows}
|
||||
className={`${inputClassName} resize-vertical`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
type="text"
|
||||
name={`${name}[${localeCode}]`}
|
||||
value={localValue[localeCode] || ''}
|
||||
onChange={(e) => handleInputChange(localeCode, e.target.value)}
|
||||
placeholder={localizedPlaceholder}
|
||||
required={required && isDefault}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
className={inputClassName}
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
}, [name, localValue, handleInputChange, placeholder, required, disabled, maxLength, rows, inputType, getLocaleName, actualDefaultLocale, handleRemoveLocale, renderAddLocaleButtonCompact, hasError]);
|
||||
|
||||
// 입력 필드 렌더링 (라벨 없음 버전 - tabs용)
|
||||
const renderInputField = useCallback((localeCode: string) => {
|
||||
const errorBorderClass = hasError
|
||||
? 'border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500'
|
||||
: 'border-gray-200 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500';
|
||||
const inputClassName = `w-full px-3 py-2 border ${errorBorderClass} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2`;
|
||||
const localizedPlaceholder = `${placeholder}${placeholder ? ' (' : ''}${getLocaleName(localeCode)}${placeholder ? ')' : ''}`;
|
||||
|
||||
return (
|
||||
<Div key={localeCode}>
|
||||
{inputType === 'textarea' ? (
|
||||
<Textarea
|
||||
name={`${name}[${localeCode}]`}
|
||||
value={localValue[localeCode] || ''}
|
||||
onChange={(e) => handleInputChange(localeCode, e.target.value)}
|
||||
placeholder={localizedPlaceholder}
|
||||
required={required && localeCode === actualDefaultLocale}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
rows={rows}
|
||||
className={`${inputClassName} resize-vertical`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
type="text"
|
||||
name={`${name}[${localeCode}]`}
|
||||
value={localValue[localeCode] || ''}
|
||||
onChange={(e) => handleInputChange(localeCode, e.target.value)}
|
||||
placeholder={localizedPlaceholder}
|
||||
required={required && localeCode === actualDefaultLocale}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
className={inputClassName}
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
}, [name, localValue, handleInputChange, placeholder, required, disabled, maxLength, rows, inputType, actualDefaultLocale, getLocaleName]);
|
||||
|
||||
// Inline 레이아웃 렌더링
|
||||
const renderInlineLayout = () => (
|
||||
<Div className={className}>
|
||||
{/* 입력 필드들 */}
|
||||
<Div className="space-y-4">
|
||||
{activeLocales.map((localeCode, index) =>
|
||||
renderInputFieldWithTopLabel(localeCode, index === 0)
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
|
||||
// Tabs 레이아웃 렌더링 - Pill Badge 스타일
|
||||
const renderTabsLayout = () => (
|
||||
<Div className={className}>
|
||||
{/* 언어 탭들 + 추가 버튼 (Pill Badge 스타일) */}
|
||||
<Div className="flex items-center gap-2 mb-3">
|
||||
{activeLocales.map(localeCode => (
|
||||
<Button
|
||||
key={localeCode}
|
||||
type="button"
|
||||
className={`
|
||||
inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all
|
||||
${currentLocale === localeCode
|
||||
? localeCode === actualDefaultLocale
|
||||
? 'bg-blue-500 text-white dark:bg-blue-600 dark:text-white shadow-md scale-105'
|
||||
: 'bg-gray-500 text-white dark:bg-gray-600 dark:text-white shadow-md scale-105'
|
||||
: localeCode === actualDefaultLocale
|
||||
? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/50'
|
||||
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}
|
||||
`}
|
||||
onClick={() => setCurrentLocale(localeCode)}
|
||||
>
|
||||
{/* 다국어 아이콘 */}
|
||||
<Icon name="globe" className="w-3 h-3" />
|
||||
{/* showCodeOnMobile: 모바일에서는 언어 코드, 데스크탑에서는 전체 언어명 표시 */}
|
||||
{showCodeOnMobile ? (
|
||||
<>
|
||||
<Span className="hidden md:inline">{getLocaleName(localeCode)}</Span>
|
||||
<Span className="inline md:hidden">{localeCode.toUpperCase()}</Span>
|
||||
</>
|
||||
) : (
|
||||
getLocaleName(localeCode)
|
||||
)}
|
||||
{localeCode === actualDefaultLocale && (
|
||||
<Span className="text-red-500 dark:text-red-400">*</Span>
|
||||
)}
|
||||
{/* 입력 완료 표시 */}
|
||||
{hasValue(localeCode) && currentLocale !== localeCode && (
|
||||
<Icon name="check" className="w-3 h-3 text-green-500 dark:text-green-400" />
|
||||
)}
|
||||
{/* 삭제 버튼 (기본 언어 제외) - 배지 안에 */}
|
||||
{localeCode !== actualDefaultLocale && (
|
||||
<Button
|
||||
type="button"
|
||||
className="ml-0.5 p-0.5 rounded-full hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveLocale(localeCode);
|
||||
}}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Icon
|
||||
name="xmark"
|
||||
className="w-3 h-3"
|
||||
/>
|
||||
</Button>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
{/* 언어 추가 버튼 */}
|
||||
{renderAddLocaleButtonCompact()}
|
||||
</Div>
|
||||
|
||||
{/* 입력 필드 */}
|
||||
{activeLocales.map(localeCode => (
|
||||
<Div
|
||||
key={localeCode}
|
||||
className={currentLocale === localeCode ? 'block' : 'hidden'}
|
||||
>
|
||||
{renderInputField(localeCode)}
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
);
|
||||
|
||||
// Compact 레이아웃 렌더링 - 언어 선택과 입력 필드가 한 줄에 배치
|
||||
const renderCompactLayout = () => {
|
||||
const errorBorderClass = hasError
|
||||
? 'border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500'
|
||||
: 'border-gray-200 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500';
|
||||
|
||||
return (
|
||||
<Div className={className}>
|
||||
<Div className="flex items-center gap-1">
|
||||
{/* 언어 선택 버튼들 - 컴팩트 스타일 */}
|
||||
<Div className="flex items-center shrink-0">
|
||||
{activeLocales.map(localeCode => (
|
||||
<Button
|
||||
key={localeCode}
|
||||
type="button"
|
||||
className={`
|
||||
px-2 py-1.5 text-xs font-medium border-y border-l first:rounded-l last:rounded-r last:border-r transition-colors
|
||||
${currentLocale === localeCode
|
||||
? 'bg-blue-500 text-white border-blue-500 dark:bg-blue-600 dark:border-blue-600'
|
||||
: 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700'
|
||||
}
|
||||
`}
|
||||
onClick={() => setCurrentLocale(localeCode)}
|
||||
title={getLocaleName(localeCode)}
|
||||
>
|
||||
{localeCode.toUpperCase()}
|
||||
{localeCode === actualDefaultLocale && (
|
||||
<Span className="text-red-400 ml-0.5">*</Span>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
|
||||
{/* 입력 필드 - flex-1로 나머지 공간 차지 */}
|
||||
<Div className="flex-1 min-w-0">
|
||||
{inputType === 'textarea' ? (
|
||||
<Textarea
|
||||
name={`${name}[${currentLocale}]`}
|
||||
value={localValue[currentLocale] || ''}
|
||||
onChange={(e) => handleInputChange(currentLocale, e.target.value)}
|
||||
placeholder={placeholder}
|
||||
required={required && currentLocale === actualDefaultLocale}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
rows={rows}
|
||||
className={`w-full px-2 py-1.5 border ${errorBorderClass} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-sm`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
type="text"
|
||||
name={`${name}[${currentLocale}]`}
|
||||
value={localValue[currentLocale] || ''}
|
||||
onChange={(e) => handleInputChange(currentLocale, e.target.value)}
|
||||
placeholder={placeholder}
|
||||
required={required && currentLocale === actualDefaultLocale}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
className={`w-full px-2 py-1.5 border ${errorBorderClass} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-sm`}
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
// 레이아웃에 따라 렌더링
|
||||
return (
|
||||
<Div className={disabled ? 'opacity-50 cursor-not-allowed' : undefined}>
|
||||
{layout === 'compact' ? renderCompactLayout() : layout === 'tabs' ? renderTabsLayout() : renderInlineLayout()}
|
||||
{/* 에러 메시지 표시 */}
|
||||
{hasError && error && (
|
||||
<Span className="text-xs text-red-500 dark:text-red-400 mt-1 block">
|
||||
{error}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
MultilingualInput.displayName = 'MultilingualInput';
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* MultilingualLocaleContext
|
||||
*
|
||||
* MultilingualTabPanel 내부에서 현재 활성 로케일을 전파하는 Context입니다.
|
||||
* Stale Closure 방지를 위해 getter 함수를 제공합니다.
|
||||
*/
|
||||
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
// G7Core 전역 객체 접근
|
||||
const getG7Core = () => (window as any).G7Core;
|
||||
|
||||
/**
|
||||
* Context 값 인터페이스
|
||||
*/
|
||||
export interface MultilingualLocaleContextValue {
|
||||
/** 현재 활성 로케일 (렌더링용) */
|
||||
activeLocale: string;
|
||||
/** Stale Closure 방지용 getter - 이벤트 핸들러에서 사용 */
|
||||
getActiveLocale: () => string;
|
||||
/** 지원되는 로케일 목록 */
|
||||
supportedLocales: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* useCurrentMultilingualLocale 훅 반환 타입
|
||||
*/
|
||||
export interface UseCurrentMultilingualLocaleResult extends MultilingualLocaleContextValue {
|
||||
/** MultilingualTabPanel 내부에서 사용 중인지 여부 */
|
||||
isInsideMultilingualTabPanel: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* MultilingualLocaleContext
|
||||
*
|
||||
* MultilingualTabPanel에서 Provider로 값을 제공합니다.
|
||||
*/
|
||||
export const MultilingualLocaleContext = createContext<MultilingualLocaleContextValue | null>(null);
|
||||
|
||||
/**
|
||||
* MultilingualTabPanel 내부에서 현재 활성 로케일 접근
|
||||
*
|
||||
* @returns activeLocale, getActiveLocale (Stale Closure 방지), supportedLocales
|
||||
* @fallback Context 외부에서는 G7Core.locale.current() 사용
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { activeLocale, getActiveLocale } = useCurrentMultilingualLocale();
|
||||
*
|
||||
* // 렌더링에서는 activeLocale 직접 사용
|
||||
* const displayValue = value?.[activeLocale] || '';
|
||||
*
|
||||
* // 이벤트 핸들러에서는 getActiveLocale() 사용 (Stale Closure 방지)
|
||||
* const handleChange = (newValue: string) => {
|
||||
* const currentLocale = getActiveLocale();
|
||||
* onChange({ ...value, [currentLocale]: newValue });
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
export const useCurrentMultilingualLocale = (): UseCurrentMultilingualLocaleResult => {
|
||||
const context = useContext(MultilingualLocaleContext);
|
||||
|
||||
// Context 외부 (MultilingualTabPanel 없이 사용 시) → G7Core fallback
|
||||
if (!context) {
|
||||
const g7Core = getG7Core();
|
||||
const currentLocale = g7Core?.locale?.current?.() || 'ko';
|
||||
const supportedLocales = g7Core?.locale?.supported?.() || ['ko', 'en'];
|
||||
|
||||
return {
|
||||
activeLocale: currentLocale,
|
||||
getActiveLocale: () => g7Core?.locale?.current?.() || 'ko',
|
||||
supportedLocales,
|
||||
isInsideMultilingualTabPanel: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...context,
|
||||
isInsideMultilingualTabPanel: true,
|
||||
};
|
||||
};
|
||||
|
||||
export default MultilingualLocaleContext;
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* MultilingualTabPanel 컴포넌트
|
||||
*
|
||||
* DynamicFieldList 등 다국어 컬럼을 포함하는 컴포넌트에서
|
||||
* 로케일을 제어할 수 있는 탭 패널입니다.
|
||||
*
|
||||
* React Context를 통해 자식 컴포넌트에 활성 로케일을 전파합니다.
|
||||
* Stale Closure 방지 패턴이 적용되어 있습니다.
|
||||
*/
|
||||
|
||||
import React, { useState, useRef, useCallback, useMemo, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Nav } from '../basic/Nav';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Span } from '../basic/Span';
|
||||
import { MultilingualLocaleContext } from './MultilingualLocaleContext';
|
||||
|
||||
// G7Core 로케일 API
|
||||
const getG7Core = () => (window as any).G7Core;
|
||||
const getSupportedLocales = (): string[] => getG7Core()?.locale?.supported?.() ?? ['ko', 'en'];
|
||||
const getCurrentLocale = (): string => getG7Core()?.locale?.current?.() ?? 'ko';
|
||||
|
||||
// 로케일 표시명
|
||||
const LOCALE_NAMES: Record<string, string> = {
|
||||
ko: '한국어',
|
||||
en: 'English',
|
||||
ja: '日本語',
|
||||
zh: '中文',
|
||||
};
|
||||
|
||||
/**
|
||||
* MultilingualTabPanel Props
|
||||
*/
|
||||
export interface MultilingualTabPanelProps {
|
||||
/** 자식 요소 (DynamicFieldList 등) */
|
||||
children?: React.ReactNode;
|
||||
/** 추가 CSS 클래스 */
|
||||
className?: string;
|
||||
/** 인라인 스타일 */
|
||||
style?: React.CSSProperties;
|
||||
/** 탭 스타일 variant */
|
||||
variant?: 'default' | 'pills' | 'underline';
|
||||
/** 기본 선택 로케일 */
|
||||
defaultLocale?: string;
|
||||
/** 로케일 변경 시 콜백 */
|
||||
onLocaleChange?: (locale: string) => void;
|
||||
/** 표시할 로케일 목록 (미지정 시 그누보드7 지원 로케일 전체 표시) */
|
||||
locales?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* MultilingualTabPanel
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <MultilingualTabPanel variant="underline">
|
||||
* <DynamicFieldList
|
||||
* dataKey="fields"
|
||||
* columns={[
|
||||
* { key: "name", type: "multilingual" },
|
||||
* { key: "content", type: "multilingual" }
|
||||
* ]}
|
||||
* />
|
||||
* </MultilingualTabPanel>
|
||||
* ```
|
||||
*/
|
||||
export const MultilingualTabPanel: React.FC<MultilingualTabPanelProps> = ({
|
||||
children,
|
||||
className = '',
|
||||
style,
|
||||
variant = 'default',
|
||||
defaultLocale,
|
||||
onLocaleChange,
|
||||
locales,
|
||||
}) => {
|
||||
// locales prop이 제공되면 해당 로케일만 표시, 미제공 시 그누보드7 지원 로케일 전체 표시
|
||||
const supportedLocales = useMemo(
|
||||
() => (locales && locales.length > 0 ? locales : getSupportedLocales()),
|
||||
[locales]
|
||||
);
|
||||
const [activeLocale, setActiveLocale] = useState<string>(
|
||||
defaultLocale || getCurrentLocale()
|
||||
);
|
||||
|
||||
// locales가 변경될 때 activeLocale이 새 목록에 없으면 첫 번째 로케일로 변경
|
||||
useEffect(() => {
|
||||
if (supportedLocales.length > 0 && !supportedLocales.includes(activeLocale)) {
|
||||
const newLocale = supportedLocales[0];
|
||||
setActiveLocale(newLocale);
|
||||
onLocaleChange?.(newLocale);
|
||||
}
|
||||
}, [supportedLocales, activeLocale, onLocaleChange]);
|
||||
|
||||
// Stale Closure 방지: useRef로 최신 값 유지
|
||||
const activeLocaleRef = useRef(activeLocale);
|
||||
activeLocaleRef.current = activeLocale;
|
||||
|
||||
const getActiveLocale = useCallback(() => activeLocaleRef.current, []);
|
||||
|
||||
const handleTabClick = useCallback(
|
||||
(locale: string) => {
|
||||
setActiveLocale(locale);
|
||||
onLocaleChange?.(locale);
|
||||
},
|
||||
[onLocaleChange]
|
||||
);
|
||||
|
||||
// Context value (memoized)
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
activeLocale,
|
||||
getActiveLocale,
|
||||
supportedLocales,
|
||||
}),
|
||||
[activeLocale, getActiveLocale, supportedLocales]
|
||||
);
|
||||
|
||||
// 탭 스타일 함수
|
||||
const getTabClasses = (locale: string) => {
|
||||
const isActive = locale === activeLocale;
|
||||
const baseClasses = 'px-4 py-2 text-sm font-medium transition-all';
|
||||
|
||||
if (variant === 'pills') {
|
||||
return isActive
|
||||
? `${baseClasses} bg-blue-600 text-white rounded-lg`
|
||||
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg`;
|
||||
}
|
||||
|
||||
if (variant === 'underline') {
|
||||
return isActive
|
||||
? `${baseClasses} text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400`
|
||||
: `${baseClasses} text-gray-600 dark:text-gray-400 border-b-2 border-transparent hover:border-gray-300 dark:hover:border-gray-500`;
|
||||
}
|
||||
|
||||
// default
|
||||
return isActive
|
||||
? `${baseClasses} text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 border-b-2 border-blue-600`
|
||||
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 border-b-2 border-transparent`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Div className={className} style={style}>
|
||||
{/* 탭 네비게이션 */}
|
||||
<Nav className="flex gap-1 border-b border-gray-200 dark:border-gray-700 mb-4">
|
||||
{supportedLocales.map((locale) => (
|
||||
<Button
|
||||
key={locale}
|
||||
type="button"
|
||||
onClick={() => handleTabClick(locale)}
|
||||
className={getTabClasses(locale)}
|
||||
>
|
||||
<Span>{LOCALE_NAMES[locale] || locale}</Span>
|
||||
</Button>
|
||||
))}
|
||||
</Nav>
|
||||
|
||||
{/* Context를 통해 children에 activeLocale 전달 */}
|
||||
<MultilingualLocaleContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</MultilingualLocaleContext.Provider>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MultilingualTabPanel;
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { Modal } from './Modal';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
// G7Core에서 지원 언어 목록 가져오기
|
||||
const getSupportedLocales = (): string[] => {
|
||||
return (window as any).G7Core?.locale?.supported?.() ?? ['ko', 'en'];
|
||||
};
|
||||
|
||||
// G7Core에서 현재 언어 가져오기
|
||||
const getCurrentLocale = (): string => {
|
||||
return (window as any).G7Core?.locale?.current?.() ?? 'ko';
|
||||
};
|
||||
|
||||
// 언어 코드로 언어명 가져오기 (다국어 키 사용)
|
||||
const getLocaleNameByCode = (code: string): string => {
|
||||
const translatedName = t(`common.language_${code}`);
|
||||
if (translatedName === `common.language_${code}`) {
|
||||
const fallbackNames: Record<string, string> = {
|
||||
ko: '한국어',
|
||||
en: 'English',
|
||||
ja: '日本語',
|
||||
zh: '中文',
|
||||
};
|
||||
return fallbackNames[code] || code.toUpperCase();
|
||||
}
|
||||
return translatedName;
|
||||
};
|
||||
|
||||
/** 다국어 값 객체 */
|
||||
export interface MultilingualValue {
|
||||
[locale: string]: string;
|
||||
}
|
||||
|
||||
export interface MultilingualTagInputProps {
|
||||
/** 다국어 태그 배열 [{ko: "빨강", en: "Red"}, ...] */
|
||||
value?: MultilingualValue[];
|
||||
/** 값 변경 콜백 */
|
||||
onChange?: (event: any) => void;
|
||||
/** 입력창 placeholder */
|
||||
placeholder?: string;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 새 항목 추가 가능 여부 (기본값: true) */
|
||||
creatable?: boolean;
|
||||
/** 태그 구분자 배열 (creatable 모드에서 입력 시 자동 분리, 기본값: [',']) */
|
||||
delimiters?: string[];
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
/** 폼 필드 이름 (템플릿 엔진용) */
|
||||
name?: string;
|
||||
/** 에러 메시지 */
|
||||
error?: string;
|
||||
/** 최대 태그 개수 */
|
||||
maxItems?: number;
|
||||
/**
|
||||
* 외부 모달 ID (레이아웃 JSON의 modals 섹션에 정의된 모달)
|
||||
* 지정 시 내장 모달 대신 openModal 핸들러로 외부 모달을 엽니다.
|
||||
* 외부 모달은 _global.multilingualTagEdit에서 편집 정보를 읽고,
|
||||
* 저장 시 setParentLocal()로 부모 상태를 직접 수정해야 합니다.
|
||||
*/
|
||||
modalId?: string;
|
||||
/**
|
||||
* 부모 상태에서의 실제 데이터 경로 (점 표기법, 예: "ui.optionInputs.0.values")
|
||||
* modalId와 함께 사용하며, 핸들러에서 setParentLocal() 호출 시 이 경로를 사용합니다.
|
||||
* 미지정 시 name prop을 기반으로 "form.{name}" 경로를 사용합니다.
|
||||
*/
|
||||
statePath?: string;
|
||||
/**
|
||||
* 컴포넌트 컨텍스트 (DynamicRenderer에서 자동 전달)
|
||||
* openModal 호출 시 부모 컨텍스트를 정확히 지정하기 위해 사용됩니다.
|
||||
* @internal
|
||||
*/
|
||||
__componentContext?: {
|
||||
state: Record<string, any>;
|
||||
setState: (updates: any) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 태그 입력 컴포넌트
|
||||
*
|
||||
* 각 태그가 다국어 값을 가지는 태그 입력 컴포넌트입니다.
|
||||
* 태그 추가/수정 시 모달을 통해 모든 언어의 값을 입력받습니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "MultilingualTagInput",
|
||||
* "props": {
|
||||
* "value": "{{form.optionValues}}",
|
||||
* "placeholder": "옵션값 입력 후 Enter"
|
||||
* },
|
||||
* "actions": [{
|
||||
* "type": "change",
|
||||
* "handler": "setState",
|
||||
* "params": { "form.optionValues": "{{$event.target.value}}" }
|
||||
* }]
|
||||
* }
|
||||
*/
|
||||
export const MultilingualTagInput: React.FC<MultilingualTagInputProps> = ({
|
||||
value: valueProp = [],
|
||||
onChange,
|
||||
placeholder = '입력 후 Enter',
|
||||
disabled = false,
|
||||
creatable = true,
|
||||
delimiters = [','],
|
||||
className = '',
|
||||
name,
|
||||
error,
|
||||
maxItems,
|
||||
modalId,
|
||||
statePath,
|
||||
__componentContext,
|
||||
}) => {
|
||||
const supportedLocales = useMemo(() => getSupportedLocales(), []);
|
||||
const defaultLocale = useMemo(() => getCurrentLocale(), []);
|
||||
|
||||
// 내부 상태
|
||||
const [tags, setTags] = useState<MultilingualValue[]>(() => valueProp || []);
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingIndex, setEditingIndex] = useState<number | null>(null);
|
||||
const [editingValues, setEditingValues] = useState<MultilingualValue>({});
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const prevValueRef = useRef<MultilingualValue[] | undefined>(undefined);
|
||||
|
||||
// props 변경 시 내부 상태 동기화
|
||||
useEffect(() => {
|
||||
const arraysEqual = (a: MultilingualValue[] | undefined, b: MultilingualValue[] | undefined): boolean => {
|
||||
if (!a && !b) return true;
|
||||
if (!a || !b) return false;
|
||||
if (a.length !== b.length) return false;
|
||||
return JSON.stringify(a) === JSON.stringify(b);
|
||||
};
|
||||
|
||||
const normalizedValue = valueProp || [];
|
||||
if (!arraysEqual(normalizedValue, prevValueRef.current)) {
|
||||
setTags(normalizedValue);
|
||||
prevValueRef.current = normalizedValue;
|
||||
}
|
||||
}, [valueProp]);
|
||||
|
||||
// 이벤트 생성 헬퍼
|
||||
const createFakeEvent = useCallback((newTags: MultilingualValue[]) => ({
|
||||
target: { name, value: newTags },
|
||||
currentTarget: { name, value: newTags },
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
}), [name]);
|
||||
|
||||
// 태그의 다국어 값을 축약 형태로 표시 (예: "KO: 빨강 / EN: Red")
|
||||
const getTagLabel = useCallback((tag: MultilingualValue): string => {
|
||||
const parts: string[] = [];
|
||||
// 지원 언어 순서대로 표시
|
||||
for (const locale of supportedLocales) {
|
||||
const value = tag[locale];
|
||||
if (value?.trim()) {
|
||||
parts.push(`${locale.toUpperCase()}: ${value}`);
|
||||
}
|
||||
}
|
||||
// 값이 없으면 빈 문자열
|
||||
return parts.length > 0 ? parts.join(' / ') : '';
|
||||
}, [supportedLocales]);
|
||||
|
||||
// 태그 삭제
|
||||
const handleRemoveTag = useCallback((index: number) => {
|
||||
const newTags = tags.filter((_, i) => i !== index);
|
||||
setTags(newTags);
|
||||
onChange?.(createFakeEvent(newTags));
|
||||
}, [tags, onChange, createFakeEvent]);
|
||||
|
||||
// 외부 모달 열기 (modalId 사용 시)
|
||||
const openExternalModal = useCallback((editingIdx: number | null, values: MultilingualValue, currentTags: MultilingualValue[]) => {
|
||||
const G7Core = (window as any).G7Core;
|
||||
if (!G7Core?.dispatch) return;
|
||||
|
||||
// supportedLocales에 라벨 정보 포함 (외부 모달에서 사용)
|
||||
const supportedLocalesWithLabels = supportedLocales.map(code => ({
|
||||
code,
|
||||
label: getLocaleNameByCode(code),
|
||||
}));
|
||||
|
||||
// _global.multilingualTagEdit에 편집 정보 설정
|
||||
G7Core.dispatch({
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'global',
|
||||
multilingualTagEdit: {
|
||||
fieldName: name,
|
||||
editingIndex: editingIdx,
|
||||
values: values,
|
||||
supportedLocales: supportedLocalesWithLabels,
|
||||
defaultLocale: defaultLocale,
|
||||
statePath: statePath, // 부모 상태 경로 (setParentLocal 용)
|
||||
currentTags: currentTags, // 현재 태그 배열
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 외부 모달 열기 (componentContext 전달로 부모 컨텍스트 정확히 지정)
|
||||
G7Core.dispatch(
|
||||
{
|
||||
handler: 'openModal',
|
||||
target: modalId,
|
||||
},
|
||||
{ componentContext: __componentContext }
|
||||
);
|
||||
}, [name, supportedLocales, defaultLocale, modalId, statePath, __componentContext]);
|
||||
|
||||
// 태그 클릭 (편집 모달 열기)
|
||||
const handleTagClick = useCallback((index: number) => {
|
||||
if (disabled) return;
|
||||
|
||||
if (modalId) {
|
||||
// 외부 모달 사용
|
||||
openExternalModal(index, { ...tags[index] }, tags);
|
||||
} else {
|
||||
// 내장 모달 사용
|
||||
setEditingIndex(index);
|
||||
setEditingValues({ ...tags[index] });
|
||||
setIsModalOpen(true);
|
||||
}
|
||||
}, [disabled, tags, modalId, openExternalModal]);
|
||||
|
||||
// 새 태그 추가 모달 열기
|
||||
const openAddModal = useCallback((initialValue: string = '') => {
|
||||
const initial: MultilingualValue = {};
|
||||
supportedLocales.forEach(locale => {
|
||||
initial[locale] = locale === defaultLocale ? initialValue : '';
|
||||
});
|
||||
|
||||
if (modalId) {
|
||||
// 외부 모달 사용
|
||||
openExternalModal(null, initial, tags);
|
||||
setInputValue('');
|
||||
} else {
|
||||
// 내장 모달 사용
|
||||
setEditingIndex(null);
|
||||
setEditingValues(initial);
|
||||
setIsModalOpen(true);
|
||||
setInputValue('');
|
||||
}
|
||||
}, [supportedLocales, defaultLocale, modalId, openExternalModal, tags]);
|
||||
|
||||
// 모달 저장
|
||||
const handleModalSave = useCallback(() => {
|
||||
// 최소 하나의 값이 있는지 확인
|
||||
const hasValue = Object.values(editingValues).some(v => v.trim() !== '');
|
||||
if (!hasValue) {
|
||||
setIsModalOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let newTags: MultilingualValue[];
|
||||
if (editingIndex !== null) {
|
||||
// 기존 태그 수정
|
||||
newTags = tags.map((tag, i) => i === editingIndex ? editingValues : tag);
|
||||
} else {
|
||||
// 새 태그 추가
|
||||
newTags = [...tags, editingValues];
|
||||
}
|
||||
|
||||
setTags(newTags);
|
||||
onChange?.(createFakeEvent(newTags));
|
||||
setIsModalOpen(false);
|
||||
setEditingValues({});
|
||||
setEditingIndex(null);
|
||||
}, [editingValues, editingIndex, tags, onChange, createFakeEvent]);
|
||||
|
||||
// 모달 닫기
|
||||
const handleModalClose = useCallback(() => {
|
||||
setIsModalOpen(false);
|
||||
setEditingValues({});
|
||||
setEditingIndex(null);
|
||||
}, []);
|
||||
|
||||
// 입력값 변경
|
||||
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
|
||||
// 구분자 감지
|
||||
const hasDelimiter = delimiters.some(d => newValue.includes(d));
|
||||
if (hasDelimiter && creatable) {
|
||||
const escapedDelimiters = delimiters.map(d => d.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
||||
const pattern = new RegExp(`[${escapedDelimiters.join('')}]`);
|
||||
const parts = newValue.split(pattern).map(s => s.trim()).filter(Boolean);
|
||||
|
||||
if (parts.length > 0) {
|
||||
// 첫 번째 값으로 모달 열기
|
||||
openAddModal(parts[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setInputValue(newValue);
|
||||
}, [delimiters, creatable, openAddModal]);
|
||||
|
||||
// 키 입력 처리
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' && inputValue.trim() && creatable) {
|
||||
e.preventDefault();
|
||||
|
||||
// 최대 개수 확인
|
||||
if (maxItems && tags.length >= maxItems) return;
|
||||
|
||||
openAddModal(inputValue.trim());
|
||||
}
|
||||
}, [inputValue, creatable, maxItems, tags.length, openAddModal]);
|
||||
|
||||
// 편집 모달 내 값 변경
|
||||
const handleEditingValueChange = useCallback((locale: string, value: string) => {
|
||||
setEditingValues(prev => ({ ...prev, [locale]: value }));
|
||||
}, []);
|
||||
|
||||
const hasError = !!error;
|
||||
|
||||
return (
|
||||
<Div className={className}>
|
||||
{/* 태그 표시 영역 */}
|
||||
<Div
|
||||
className={`flex flex-wrap gap-1.5 p-2 border rounded-lg bg-white dark:bg-gray-700 min-h-[42px] ${
|
||||
hasError
|
||||
? 'border-red-500 dark:border-red-400'
|
||||
: 'border-gray-300 dark:border-gray-600 focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500'
|
||||
} ${disabled ? 'opacity-60 bg-gray-100 dark:bg-gray-800 cursor-not-allowed' : ''}`}
|
||||
>
|
||||
{tags.map((tag, index) => (
|
||||
<Div
|
||||
key={index}
|
||||
className="flex items-center gap-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded px-2 py-0.5 text-sm"
|
||||
>
|
||||
<Span
|
||||
className={`cursor-pointer hover:underline ${disabled ? 'cursor-not-allowed' : ''}`}
|
||||
onClick={() => handleTagClick(index)}
|
||||
>
|
||||
{getTagLabel(tag)}
|
||||
</Span>
|
||||
{!disabled && (
|
||||
<Button
|
||||
type="button"
|
||||
className="p-0 h-4 w-4 min-w-0 border-0 bg-transparent text-blue-600 dark:text-blue-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-transparent"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveTag(index);
|
||||
}}
|
||||
>
|
||||
<Icon name="times" className="text-xs" />
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
))}
|
||||
|
||||
{/* 입력 필드 */}
|
||||
{creatable && !disabled && (!maxItems || tags.length < maxItems) && (
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={tags.length === 0 ? placeholder : ''}
|
||||
disabled={disabled}
|
||||
className="flex-1 min-w-[120px] bg-transparent border-none outline-none text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && (
|
||||
<Span className="text-xs text-red-500 dark:text-red-400 mt-1">
|
||||
{error}
|
||||
</Span>
|
||||
)}
|
||||
|
||||
{/* 다국어 편집 모달 (내장 모달 - modalId가 없을 때만 렌더링) */}
|
||||
{!modalId && (
|
||||
<Modal
|
||||
isOpen={isModalOpen}
|
||||
onClose={handleModalClose}
|
||||
title={editingIndex !== null ? t('common.edit') : t('common.add')}
|
||||
width="400px"
|
||||
>
|
||||
<Div className="space-y-4 p-4">
|
||||
{supportedLocales.map(locale => (
|
||||
<Div key={locale} className="space-y-1">
|
||||
<Div className="flex items-center gap-2">
|
||||
<Span className="text-sm font-medium text-gray-700 dark:text-gray-300 w-16">
|
||||
{getLocaleNameByCode(locale)}
|
||||
</Span>
|
||||
<Span className="text-xs text-gray-400 dark:text-gray-500">
|
||||
({locale.toUpperCase()})
|
||||
</Span>
|
||||
</Div>
|
||||
<Input
|
||||
type="text"
|
||||
value={editingValues[locale] ?? ''}
|
||||
onChange={(e) => handleEditingValueChange(locale, e.target.value)}
|
||||
placeholder={`${getLocaleNameByCode(locale)} 값 입력`}
|
||||
className="w-full"
|
||||
autoFocus={locale === defaultLocale}
|
||||
/>
|
||||
</Div>
|
||||
))}
|
||||
|
||||
<Div className="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={handleModalClose}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
onClick={handleModalSave}
|
||||
>
|
||||
{editingIndex !== null ? t('common.save') : t('common.add')}
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{/* hidden input for form submission */}
|
||||
{name && (
|
||||
<input
|
||||
type="hidden"
|
||||
name={name}
|
||||
value={JSON.stringify(tags)}
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
/**
|
||||
* 알림 아이템 인터페이스
|
||||
*/
|
||||
export interface NotificationItem {
|
||||
id: string | number;
|
||||
title: string;
|
||||
message: string;
|
||||
time: string;
|
||||
read?: boolean;
|
||||
iconName?: IconName;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* NotificationCenter Props
|
||||
*/
|
||||
export interface NotificationCenterProps {
|
||||
/** 알림 목록 */
|
||||
notifications?: NotificationItem[];
|
||||
/** 알림 제목 텍스트 */
|
||||
titleText?: string;
|
||||
/** 알림 없음 텍스트 */
|
||||
emptyText?: string;
|
||||
/** 알림 클릭 핸들러 */
|
||||
onNotificationClick?: (id: string | number) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* NotificationCenter 컴포넌트
|
||||
*
|
||||
* 알림 센터 - 알림 목록 표시 및 관리
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <NotificationCenter
|
||||
* notifications={[
|
||||
* { id: 1, title: '새 댓글', message: '게시물에 댓글이 달렸습니다', time: '5분 전' }
|
||||
* ]}
|
||||
* titleText="Notifications"
|
||||
* emptyText="No notifications"
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const NotificationCenter: React.FC<NotificationCenterProps> = ({
|
||||
notifications = [],
|
||||
titleText = 'Notifications',
|
||||
emptyText = 'No notifications',
|
||||
onNotificationClick,
|
||||
className = '',
|
||||
}) => {
|
||||
const [showNotifications, setShowNotifications] = useState(false);
|
||||
const notificationRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.read).length;
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지
|
||||
*/
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
notificationRef.current &&
|
||||
!notificationRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setShowNotifications(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Div ref={notificationRef} className={`relative ${className}`}>
|
||||
<Button
|
||||
onClick={() => setShowNotifications(!showNotifications)}
|
||||
className="relative p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
|
||||
aria-label={titleText}
|
||||
>
|
||||
<Icon name={IconName.Bell} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
{unreadCount > 0 && (
|
||||
<Span className="absolute top-0 right-0 flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-red-500 rounded-full">
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
</Span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* 알림 드롭다운 */}
|
||||
{showNotifications && (
|
||||
<Div className="absolute right-0 mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<Span className="font-semibold text-gray-900 dark:text-white">{titleText}</Span>
|
||||
</Div>
|
||||
<Div className="max-h-96 overflow-y-auto">
|
||||
{notifications.length === 0 ? (
|
||||
<Div className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
|
||||
<Span>{emptyText}</Span>
|
||||
</Div>
|
||||
) : (
|
||||
notifications.map((notification) => (
|
||||
<Button
|
||||
key={notification.id}
|
||||
onClick={() => {
|
||||
notification.onClick?.();
|
||||
onNotificationClick?.(notification.id);
|
||||
setShowNotifications(false);
|
||||
}}
|
||||
className={`
|
||||
w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 border-b border-gray-100 dark:border-gray-700 transition-colors
|
||||
${!notification.read ? 'bg-blue-50 dark:bg-gray-700' : ''}
|
||||
`}
|
||||
>
|
||||
<Div className="flex items-start gap-3">
|
||||
{notification.iconName && (
|
||||
<Icon
|
||||
name={notification.iconName}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5"
|
||||
/>
|
||||
)}
|
||||
<Div className="flex-1">
|
||||
<Div className="font-semibold text-gray-900 dark:text-white text-sm">
|
||||
{notification.title}
|
||||
</Div>
|
||||
<Div className="text-gray-600 dark:text-gray-300 text-sm mt-1">
|
||||
{notification.message}
|
||||
</Div>
|
||||
<Div className="text-gray-400 dark:text-gray-500 text-xs mt-1">
|
||||
{notification.time}
|
||||
</Div>
|
||||
</Div>
|
||||
{!notification.read && (
|
||||
<Span className="w-2 h-2 bg-blue-500 rounded-full mt-1.5" />
|
||||
)}
|
||||
</Div>
|
||||
</Button>
|
||||
))
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H1 } from '../basic/H1';
|
||||
import { P } from '../basic/P';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Breadcrumb, BreadcrumbItem } from './Breadcrumb';
|
||||
|
||||
/**
|
||||
* 탭 아이템 인터페이스
|
||||
*/
|
||||
export interface TabItem {
|
||||
id: string | number;
|
||||
label: string;
|
||||
value: string;
|
||||
active?: boolean;
|
||||
badge?: string | number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 액션 버튼 인터페이스
|
||||
*/
|
||||
export interface ActionButton {
|
||||
id: string | number;
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
iconName?: IconName;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* PageHeader Props
|
||||
*/
|
||||
export interface PageHeaderProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
breadcrumbItems?: BreadcrumbItem[];
|
||||
tabs?: TabItem[];
|
||||
onTabChange?: (value: string) => void;
|
||||
actions?: ActionButton[];
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* PageHeader 컴포넌트
|
||||
*
|
||||
* 페이지 헤더 - admin_dashboard.json의 page_header 스타일과 동일
|
||||
* 배경색 없음, flex items-center justify-between mb-6 레이아웃
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <PageHeader
|
||||
* title="사용자 관리"
|
||||
* description="시스템에 등록된 사용자 목록을 조회하고 관리합니다."
|
||||
* actions={[
|
||||
* { id: 1, label: '사용자 추가', variant: 'primary', iconName: 'plus' }
|
||||
* ]}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const PageHeader: React.FC<PageHeaderProps> = ({
|
||||
title,
|
||||
description,
|
||||
breadcrumbItems,
|
||||
tabs,
|
||||
onTabChange,
|
||||
actions,
|
||||
className = '',
|
||||
children,
|
||||
}) => {
|
||||
/**
|
||||
* Variant별 버튼 스타일
|
||||
*/
|
||||
const getButtonClasses = (variant: ActionButton['variant'] = 'secondary'): string => {
|
||||
const baseClasses = 'px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2';
|
||||
|
||||
const variantClasses: Record<NonNullable<ActionButton['variant']>, string> = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700',
|
||||
secondary: 'bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700',
|
||||
ghost: 'p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800',
|
||||
};
|
||||
|
||||
return `${baseClasses} ${variantClasses[variant]}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Div className={className}>
|
||||
{/* 브레드크럼 - Breadcrumb 컴포넌트 재사용 */}
|
||||
{breadcrumbItems && breadcrumbItems.length > 0 && (
|
||||
<Div className="mb-4">
|
||||
<Breadcrumb items={breadcrumbItems} />
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 제목 및 액션 버튼 - admin_dashboard.json 스타일 */}
|
||||
<Div className="flex items-center justify-between mb-6">
|
||||
<Div>
|
||||
<H1 className="text-xl sm:text-2xl font-semibold text-gray-900 dark:text-white">{title}</H1>
|
||||
{description && (
|
||||
<P className="text-sm text-gray-600 dark:text-gray-400 mt-1">{description}</P>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 액션 버튼 또는 children */}
|
||||
{children ? (
|
||||
<Div className="flex items-center gap-2">{children}</Div>
|
||||
) : actions && actions.length > 0 ? (
|
||||
<Div className="flex items-center gap-2">
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
key={action.id}
|
||||
onClick={action.onClick}
|
||||
disabled={action.disabled}
|
||||
className={getButtonClasses(action.variant)}
|
||||
>
|
||||
{action.iconName && (
|
||||
<Icon name={action.iconName} className="w-5 h-5" />
|
||||
)}
|
||||
{action.variant !== 'ghost' && action.label && (
|
||||
<Div>{action.label}</Div>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
) : null}
|
||||
</Div>
|
||||
|
||||
{/* 탭 네비게이션 */}
|
||||
{tabs && tabs.length > 0 && (
|
||||
<Div className="flex gap-6 border-b border-gray-200 dark:border-gray-700 mb-6">
|
||||
{tabs.map((tab) => (
|
||||
<Button
|
||||
key={tab.id}
|
||||
onClick={() => onTabChange?.(tab.value)}
|
||||
className={`
|
||||
px-1 py-3 border-b-2 transition-colors font-medium flex items-center gap-2 -mb-px
|
||||
${tab.active
|
||||
? 'border-blue-600 text-blue-600 dark:text-blue-400'
|
||||
: 'border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
|
||||
}
|
||||
`}
|
||||
>
|
||||
<Div>{tab.label}</Div>
|
||||
{tab.badge !== undefined && (
|
||||
<Div className={`
|
||||
px-2 py-0.5 rounded-full text-xs font-semibold
|
||||
${tab.active
|
||||
? 'bg-blue-100 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
|
||||
}
|
||||
`}>
|
||||
{tab.badge}
|
||||
</Div>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:PageTransition')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:PageTransition]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:PageTransition]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:PageTransition]', ...args),
|
||||
};
|
||||
|
||||
export interface PageTransitionIndicatorProps {
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* PageTransitionIndicator 컴포넌트
|
||||
*
|
||||
* TransitionManager의 isPending 상태를 구독하여 페이지 전환 시
|
||||
* 상단에 로딩 바를 표시합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "PageTransitionIndicator"
|
||||
* }
|
||||
*/
|
||||
export const PageTransitionIndicator: React.FC<PageTransitionIndicatorProps> = ({
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// G7Core.TransitionManager 접근
|
||||
const transitionManager = (window as any).G7Core?.TransitionManager;
|
||||
|
||||
if (!transitionManager) {
|
||||
logger.warn('TransitionManager를 찾을 수 없습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
// 구독 및 초기 상태 설정
|
||||
setIsPending(transitionManager.getIsPending());
|
||||
|
||||
const unsubscribe = transitionManager.subscribe((newIsPending: boolean) => {
|
||||
setIsPending(newIsPending);
|
||||
});
|
||||
|
||||
// 정리 함수
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
|
||||
if (!isPending) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`fixed top-0 left-0 right-0 z-50 ${className}`}
|
||||
style={style}
|
||||
role="progressbar"
|
||||
aria-label="페이지 로딩 중"
|
||||
>
|
||||
<Div className="h-1 bg-gradient-to-r from-blue-500 via-blue-600 to-blue-500 animate-pulse">
|
||||
<Div
|
||||
className="h-full bg-blue-700 animate-[loading_1.5s_ease-in-out_infinite]"
|
||||
style={{
|
||||
width: '30%',
|
||||
animation: 'loading 1.5s ease-in-out infinite',
|
||||
}}
|
||||
/>
|
||||
</Div>
|
||||
|
||||
<style>{`
|
||||
@keyframes loading {
|
||||
0% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
50% {
|
||||
transform: translateX(300%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,206 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
export interface PaginationProps {
|
||||
currentPage: number;
|
||||
totalPages: number;
|
||||
onPageChange: (page: number) => void;
|
||||
maxVisiblePages?: number;
|
||||
showFirstLast?: boolean;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
prevText?: string;
|
||||
nextText?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination 집합 컴포넌트
|
||||
*
|
||||
* Button + Span 기본 컴포넌트를 조합하여 페이지네이션 UI를 구성합니다.
|
||||
* 페이지 번호 생성 알고리즘을 포함하며, 많은 페이지 수에 대해 효율적으로 렌더링합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "Pagination",
|
||||
* "props": {
|
||||
* "currentPage": "{{pagination.current}}",
|
||||
* "totalPages": "{{pagination.total}}",
|
||||
* "maxVisiblePages": 5,
|
||||
* "showFirstLast": true
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Pagination: React.FC<PaginationProps> = ({
|
||||
currentPage,
|
||||
totalPages,
|
||||
onPageChange,
|
||||
maxVisiblePages = 5,
|
||||
showFirstLast = true,
|
||||
className = '',
|
||||
style,
|
||||
prevText,
|
||||
nextText,
|
||||
}) => {
|
||||
|
||||
// 페이지 번호 생성 알고리즘
|
||||
const pageNumbers = useMemo(() => {
|
||||
const pages: (number | string)[] = [];
|
||||
|
||||
if (totalPages <= maxVisiblePages + 2) {
|
||||
// 페이지가 적으면 모두 표시
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
// 페이지가 많으면 축약 표시
|
||||
const halfVisible = Math.floor(maxVisiblePages / 2);
|
||||
|
||||
let startPage = Math.max(2, currentPage - halfVisible);
|
||||
let endPage = Math.min(totalPages - 1, currentPage + halfVisible);
|
||||
|
||||
// 시작 또는 끝 근처일 때 조정
|
||||
if (currentPage <= halfVisible + 1) {
|
||||
endPage = maxVisiblePages;
|
||||
} else if (currentPage >= totalPages - halfVisible) {
|
||||
startPage = totalPages - maxVisiblePages + 1;
|
||||
}
|
||||
|
||||
// 첫 페이지
|
||||
pages.push(1);
|
||||
|
||||
// 시작 생략 부호
|
||||
if (startPage > 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
|
||||
// 중간 페이지들
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
|
||||
// 끝 생략 부호
|
||||
if (endPage < totalPages - 1) {
|
||||
pages.push('...');
|
||||
}
|
||||
|
||||
// 마지막 페이지
|
||||
if (totalPages > 1) {
|
||||
pages.push(totalPages);
|
||||
}
|
||||
}
|
||||
|
||||
return pages;
|
||||
}, [currentPage, totalPages, maxVisiblePages]);
|
||||
|
||||
const handlePageClick = (page: number) => {
|
||||
if (page < 1 || page > totalPages || page === currentPage) return;
|
||||
onPageChange(page);
|
||||
};
|
||||
|
||||
const handlePrevious = () => {
|
||||
if (currentPage > 1) {
|
||||
onPageChange(currentPage - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
if (currentPage < totalPages) {
|
||||
onPageChange(currentPage + 1);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`flex items-center gap-2 ${className}`}
|
||||
style={style}
|
||||
role="navigation"
|
||||
aria-label={t('common.pagination')}
|
||||
>
|
||||
{/* First Button */}
|
||||
{showFirstLast && (
|
||||
<Button
|
||||
onClick={() => handlePageClick(1)}
|
||||
disabled={currentPage === 1}
|
||||
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||
aria-label={t('common.first_page')}
|
||||
>
|
||||
«
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Previous Button */}
|
||||
<Button
|
||||
onClick={handlePrevious}
|
||||
disabled={currentPage === 1}
|
||||
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||
aria-label={t('common.prev_page')}
|
||||
>
|
||||
{prevText || <>‹</>}
|
||||
</Button>
|
||||
|
||||
{/* Page Numbers */}
|
||||
<Div className="flex items-center gap-1">
|
||||
{pageNumbers.map((page, index) => {
|
||||
if (page === '...') {
|
||||
return (
|
||||
<Span
|
||||
key={`ellipsis-${index}`}
|
||||
className="px-3 py-1 text-sm text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
...
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const pageNum = page as number;
|
||||
const isActive = pageNum === currentPage;
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={pageNum}
|
||||
onClick={() => handlePageClick(pageNum)}
|
||||
className={`px-3 py-1 text-sm border rounded ${
|
||||
isActive
|
||||
? 'bg-blue-500 dark:bg-blue-600 text-white border-blue-500 dark:border-blue-600'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800'
|
||||
}`}
|
||||
aria-label={t('common.page_n', { n: pageNum })}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
>
|
||||
{pageNum}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
|
||||
{/* Next Button */}
|
||||
<Button
|
||||
onClick={handleNext}
|
||||
disabled={currentPage === totalPages}
|
||||
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||
aria-label={t('common.next_page')}
|
||||
>
|
||||
{nextText || <>›</>}
|
||||
</Button>
|
||||
|
||||
{/* Last Button */}
|
||||
{showFirstLast && (
|
||||
<Button
|
||||
onClick={() => handlePageClick(totalPages)}
|
||||
disabled={currentPage === totalPages}
|
||||
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||
aria-label={t('common.last_page')}
|
||||
>
|
||||
»
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,642 @@
|
||||
import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Label } from '../basic/Label';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Accordion } from './Accordion';
|
||||
import { ExtensionBadge, ExtensionInfo } from './ExtensionBadge';
|
||||
|
||||
// G7Core 전역 객체에서 createChangeEvent 가져오기
|
||||
const G7Core = (window as any).G7Core;
|
||||
|
||||
// useControllableState 훅 타입 정의
|
||||
const useControllableState = G7Core?.useControllableState as
|
||||
| (<T>(
|
||||
controlledValue: T | undefined,
|
||||
defaultValue: T,
|
||||
onChange?: (value: T) => void,
|
||||
options?: { isEqual?: (a: T, b: T) => boolean }
|
||||
) => [T, (value: T | ((prev: T) => T)) => void])
|
||||
| undefined;
|
||||
|
||||
/**
|
||||
* 권한 값 인터페이스 (id + scope_type)
|
||||
*/
|
||||
export interface PermissionValue {
|
||||
id: number;
|
||||
scope_type: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 스코프 옵션 인터페이스
|
||||
*/
|
||||
export interface ScopeOption {
|
||||
value: string | null;
|
||||
label: string;
|
||||
}
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
/**
|
||||
* 스코프 옵션별 설명 다국어 키 매핑
|
||||
*/
|
||||
const SCOPE_DESCRIPTION_KEYS: Record<string, string> = {
|
||||
'': 'common.scope_type_all_desc',
|
||||
self: 'common.scope_type_self_desc',
|
||||
role: 'common.scope_type_role_desc',
|
||||
};
|
||||
|
||||
/**
|
||||
* 스코프 드롭다운 컴포넌트
|
||||
*
|
||||
* 네이티브 <select>로는 설명 텍스트를 표시할 수 없으므로
|
||||
* 커스텀 드롭다운으로 구현합니다.
|
||||
*/
|
||||
const ScopeDropdown: React.FC<{
|
||||
options: ScopeOption[];
|
||||
value: string | null;
|
||||
onChange: (value: string | null) => void;
|
||||
disabled?: boolean;
|
||||
}> = ({ options, value, onChange, disabled = false }) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [menuStyle, setMenuStyle] = useState<React.CSSProperties>({});
|
||||
const triggerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const currentOption = options.find((opt) => opt.value === value) ?? options[0];
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (triggerRef.current && !triggerRef.current.contains(e.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const updatePosition = () => {
|
||||
if (!triggerRef.current) return;
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
setMenuStyle({
|
||||
position: 'fixed',
|
||||
top: rect.bottom + 4,
|
||||
right: window.innerWidth - rect.right,
|
||||
zIndex: 9999,
|
||||
});
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
window.addEventListener('scroll', updatePosition, true);
|
||||
window.addEventListener('resize', updatePosition);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
window.removeEventListener('scroll', updatePosition, true);
|
||||
window.removeEventListener('resize', updatePosition);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
const openMenu = useCallback(() => {
|
||||
if (disabled || !triggerRef.current) return;
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
setMenuStyle({
|
||||
position: 'fixed',
|
||||
top: rect.bottom + 4,
|
||||
right: window.innerWidth - rect.right,
|
||||
zIndex: 9999,
|
||||
});
|
||||
setIsOpen((prev) => !prev);
|
||||
}, [disabled]);
|
||||
|
||||
return (
|
||||
<Div ref={triggerRef} className="relative flex-shrink-0">
|
||||
<Div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
openMenu();
|
||||
}}
|
||||
onMouseDown={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
onKeyDown={(e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
openMenu();
|
||||
}
|
||||
if (e.key === 'Escape') setIsOpen(false);
|
||||
}}
|
||||
className={`flex items-center gap-1 text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 cursor-pointer select-none ${
|
||||
disabled ? 'opacity-50 cursor-not-allowed' : 'hover:border-blue-400 dark:hover:border-blue-500'
|
||||
}`}
|
||||
>
|
||||
<Span>{currentOption?.label ?? ''}</Span>
|
||||
<Icon name={IconName.ChevronDown} className="w-3 h-3 text-gray-400 dark:text-gray-500" />
|
||||
</Div>
|
||||
|
||||
{isOpen && (
|
||||
<Div
|
||||
style={menuStyle}
|
||||
className="w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg py-1"
|
||||
>
|
||||
{options.map((option) => {
|
||||
const optKey = option.value ?? '';
|
||||
const descKey = SCOPE_DESCRIPTION_KEYS[optKey];
|
||||
const description = descKey ? t(descKey) : '';
|
||||
const isSelected = option.value === value;
|
||||
|
||||
return (
|
||||
<Div
|
||||
key={optKey || '__null__'}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onChange(option.value);
|
||||
setIsOpen(false);
|
||||
}}
|
||||
onMouseDown={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
className={`px-3 py-2 cursor-pointer transition-colors ${
|
||||
isSelected
|
||||
? 'bg-blue-50 dark:bg-blue-900/30'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
|
||||
}`}
|
||||
>
|
||||
<Div className="flex items-center justify-between">
|
||||
<Span className={`text-xs font-medium ${
|
||||
isSelected ? 'text-blue-700 dark:text-blue-300' : 'text-gray-900 dark:text-white'
|
||||
}`}>
|
||||
{option.label}
|
||||
</Span>
|
||||
{isSelected && (
|
||||
<Icon name={IconName.Check} className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400" />
|
||||
)}
|
||||
</Div>
|
||||
{description && (
|
||||
<Span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
{description}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
// PermissionValue 배열 비교 함수 (순서 무관)
|
||||
const arePermissionValuesEqual = (a: PermissionValue[], b: PermissionValue[]): boolean => {
|
||||
if (a.length !== b.length) return false;
|
||||
const sortedA = [...a].sort((x, y) => x.id - y.id);
|
||||
const sortedB = [...b].sort((x, y) => x.id - y.id);
|
||||
return sortedA.every((val, idx) => val.id === sortedB[idx].id && val.scope_type === sortedB[idx].scope_type);
|
||||
};
|
||||
|
||||
/**
|
||||
* 권한 노드 인터페이스
|
||||
*/
|
||||
export interface PermissionNode {
|
||||
id: number;
|
||||
identifier: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
module?: string;
|
||||
extension_type?: string | null;
|
||||
extension_identifier?: string | null;
|
||||
is_assignable: boolean;
|
||||
leaf_count: number;
|
||||
resource_route_key?: string | null;
|
||||
owner_key?: string | null;
|
||||
children: PermissionNode[];
|
||||
}
|
||||
|
||||
export interface PermissionTreeProps {
|
||||
/** 권한 트리 데이터 */
|
||||
data?: PermissionNode[];
|
||||
/** 선택된 권한 값 배열 [{id, scope_type}] */
|
||||
value?: PermissionValue[];
|
||||
/** 선택 변경 콜백 */
|
||||
onChange?: (e: { target: { value: PermissionValue[] } }) => void;
|
||||
/** 스코프 옵션 (드롭다운 선택지) */
|
||||
scopeOptions?: ScopeOption[];
|
||||
/** 추가 클래스명 */
|
||||
className?: string;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** PC에서 권한 목록 열 수 */
|
||||
desktopColumns?: 1 | 2 | 3;
|
||||
/** 설치된 모듈 목록 (_global.installedModules에서 전달) */
|
||||
installedModules?: ExtensionInfo[];
|
||||
/** 설치된 플러그인 목록 (_global.installedPlugins에서 전달) */
|
||||
installedPlugins?: ExtensionInfo[];
|
||||
}
|
||||
|
||||
/**
|
||||
* PermissionTree 집합 컴포넌트
|
||||
*
|
||||
* 계층형 권한 트리를 렌더링하고 체크박스로 권한을 선택할 수 있습니다.
|
||||
* 각 권한에 스코프 타입(전체/소유역할/본인만)을 설정할 수 있는 드롭다운을 제공합니다.
|
||||
* 내부적으로 Accordion 컴포넌트를 재사용합니다.
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "PermissionTree",
|
||||
* "props": {
|
||||
* "data": "{{permissions?.data?.data?.permissions?.[permType]?.permissions ?? []}}",
|
||||
* "value": "{{_local.form.permission_values ?? []}}",
|
||||
* "scopeOptions": "{{permissions?.data?.data?.scope_options ?? []}}"
|
||||
* },
|
||||
* "actions": [
|
||||
* {
|
||||
* "type": "change",
|
||||
* "handler": "setState",
|
||||
* "params": {
|
||||
* "target": "local",
|
||||
* "form": {
|
||||
* "permission_values": "{{$event.target.value}}"
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
export const PermissionTree: React.FC<PermissionTreeProps> = ({
|
||||
data = [],
|
||||
value = [],
|
||||
onChange,
|
||||
scopeOptions = [],
|
||||
className = '',
|
||||
disabled = false,
|
||||
desktopColumns = 2,
|
||||
installedModules = [],
|
||||
installedPlugins = [],
|
||||
}) => {
|
||||
// onChange를 이벤트 객체 형식으로 변환하는 핸들러
|
||||
const handleChange = useCallback((newValue: PermissionValue[]) => {
|
||||
if (onChange) {
|
||||
const event = G7Core?.createChangeEvent
|
||||
? G7Core.createChangeEvent({ value: newValue })
|
||||
: { target: { value: newValue } };
|
||||
onChange(event);
|
||||
}
|
||||
}, [onChange]);
|
||||
|
||||
// useControllableState 사용 (가능한 경우) 또는 폴백
|
||||
const [selectedValues, setSelectedValues] = useControllableState
|
||||
? useControllableState<PermissionValue[]>(value, [], handleChange, { isEqual: arePermissionValuesEqual })
|
||||
: (() => {
|
||||
// 폴백: 기존 useState + useEffect 패턴
|
||||
const [state, setState] = useState<PermissionValue[]>(value);
|
||||
const onChangeRef = React.useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
const isInternalChangeRef = React.useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isInternalChangeRef.current) {
|
||||
isInternalChangeRef.current = false;
|
||||
return;
|
||||
}
|
||||
setState(value);
|
||||
}, [value]);
|
||||
|
||||
const wrappedSetState = useCallback((newValue: PermissionValue[] | ((prev: PermissionValue[]) => PermissionValue[])) => {
|
||||
isInternalChangeRef.current = true;
|
||||
setState((prev) => {
|
||||
const nextValue = typeof newValue === 'function' ? newValue(prev) : newValue;
|
||||
if (onChangeRef.current) {
|
||||
const event = G7Core?.createChangeEvent
|
||||
? G7Core.createChangeEvent({ value: nextValue })
|
||||
: { target: { value: nextValue } };
|
||||
onChangeRef.current(event);
|
||||
}
|
||||
return nextValue;
|
||||
});
|
||||
}, []);
|
||||
|
||||
return [state, wrappedSetState] as const;
|
||||
})();
|
||||
|
||||
// 선택된 ID Set (빠른 조회용)
|
||||
const selectedIdSet = useMemo(
|
||||
() => new Set(selectedValues.map((v) => v.id)),
|
||||
[selectedValues]
|
||||
);
|
||||
|
||||
/**
|
||||
* 노드의 모든 리프(할당 가능한 권한) ID를 재귀적으로 수집
|
||||
*/
|
||||
const getLeafIds = useCallback((node: PermissionNode): number[] => {
|
||||
if (node.is_assignable) {
|
||||
return [node.id];
|
||||
}
|
||||
return node.children.flatMap((child) => getLeafIds(child));
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 노드의 모든 리프가 선택되었는지 확인
|
||||
*/
|
||||
const isNodeFullySelected = useCallback(
|
||||
(node: PermissionNode): boolean => {
|
||||
const leafIds = getLeafIds(node);
|
||||
return leafIds.length > 0 && leafIds.every((id) => selectedIdSet.has(id));
|
||||
},
|
||||
[selectedIdSet, getLeafIds]
|
||||
);
|
||||
|
||||
/**
|
||||
* 노드의 일부 리프가 선택되었는지 확인 (indeterminate 상태)
|
||||
*/
|
||||
const isNodePartiallySelected = useCallback(
|
||||
(node: PermissionNode): boolean => {
|
||||
const leafIds = getLeafIds(node);
|
||||
const selectedCount = leafIds.filter((id) => selectedIdSet.has(id)).length;
|
||||
return selectedCount > 0 && selectedCount < leafIds.length;
|
||||
},
|
||||
[selectedIdSet, getLeafIds]
|
||||
);
|
||||
|
||||
/**
|
||||
* 노드에서 선택된 리프 개수 반환
|
||||
*/
|
||||
const getSelectedCount = useCallback(
|
||||
(node: PermissionNode): number => {
|
||||
const leafIds = getLeafIds(node);
|
||||
return leafIds.filter((id) => selectedIdSet.has(id)).length;
|
||||
},
|
||||
[selectedIdSet, getLeafIds]
|
||||
);
|
||||
|
||||
/**
|
||||
* 개별 권한 체크박스 변경 처리
|
||||
*/
|
||||
const handleLeafChange = useCallback(
|
||||
(permissionId: number, checked: boolean) => {
|
||||
if (disabled) return;
|
||||
|
||||
setSelectedValues((prev: PermissionValue[]) => {
|
||||
return checked
|
||||
? [...prev, { id: permissionId, scope_type: null }]
|
||||
: prev.filter((v) => v.id !== permissionId);
|
||||
});
|
||||
},
|
||||
[disabled, setSelectedValues]
|
||||
);
|
||||
|
||||
/**
|
||||
* 그룹(카테고리/모듈) 체크박스 변경 처리
|
||||
* 함수형 업데이트로 항상 최신 상태를 사용
|
||||
*/
|
||||
const handleGroupChange = useCallback(
|
||||
(node: PermissionNode, checked: boolean) => {
|
||||
if (disabled) return;
|
||||
|
||||
const leafIds = getLeafIds(node);
|
||||
const leafIdSet = new Set(leafIds);
|
||||
|
||||
setSelectedValues((prev: PermissionValue[]) => {
|
||||
if (checked) {
|
||||
// 이미 있는 항목은 유지 (scope_type 보존), 없는 항목만 추가
|
||||
const existingIds = new Set(prev.map((v) => v.id));
|
||||
const newEntries = leafIds
|
||||
.filter((id) => !existingIds.has(id))
|
||||
.map((id) => ({ id, scope_type: null as string | null }));
|
||||
return [...prev, ...newEntries];
|
||||
} else {
|
||||
// 해당 그룹의 리프만 제거
|
||||
return prev.filter((v) => !leafIdSet.has(v.id));
|
||||
}
|
||||
});
|
||||
},
|
||||
[disabled, getLeafIds, setSelectedValues]
|
||||
);
|
||||
|
||||
/**
|
||||
* 스코프 타입 변경 처리
|
||||
*/
|
||||
const handleScopeTypeChange = useCallback(
|
||||
(permissionId: number, scopeType: string | null) => {
|
||||
if (disabled) return;
|
||||
|
||||
setSelectedValues((prev: PermissionValue[]) => {
|
||||
return prev.map((v) =>
|
||||
v.id === permissionId ? { ...v, scope_type: scopeType } : v
|
||||
);
|
||||
});
|
||||
},
|
||||
[disabled, setSelectedValues]
|
||||
);
|
||||
|
||||
/**
|
||||
* 개별 권한 체크박스 렌더링
|
||||
*/
|
||||
const renderLeafPermission = (permission: PermissionNode) => {
|
||||
const isChecked = selectedIdSet.has(permission.id);
|
||||
const hasResourceRouteKey = !!permission.resource_route_key;
|
||||
const showScopeDropdown = isChecked && hasResourceRouteKey && scopeOptions.length > 0;
|
||||
const currentScopeType = selectedValues.find((v) => v.id === permission.id)?.scope_type ?? null;
|
||||
|
||||
return (
|
||||
<Label
|
||||
key={permission.id}
|
||||
className={`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${
|
||||
isChecked
|
||||
? 'border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-900/20'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
>
|
||||
<Input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
e.stopPropagation();
|
||||
handleLeafChange(permission.id, e.target.checked);
|
||||
}}
|
||||
disabled={disabled}
|
||||
className="w-4 h-4 mt-0.5 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
|
||||
/>
|
||||
<Div className="flex-1 min-w-0">
|
||||
<Div className="flex items-center justify-between gap-2">
|
||||
<Span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{permission.name}
|
||||
</Span>
|
||||
{showScopeDropdown && (
|
||||
<ScopeDropdown
|
||||
options={scopeOptions}
|
||||
value={currentScopeType}
|
||||
onChange={(val) => handleScopeTypeChange(permission.id, val)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
{permission.description && (
|
||||
<Span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
{permission.description}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
</Label>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 카테고리(2depth) 렌더링
|
||||
*/
|
||||
const renderCategory = (category: PermissionNode, moduleNode: PermissionNode) => {
|
||||
const isFullySelected = isNodeFullySelected(category);
|
||||
const isPartiallySelected = isNodePartiallySelected(category);
|
||||
const selectedCount = getSelectedCount(category);
|
||||
const assignableChildren = category.children.filter((p) => p.is_assignable);
|
||||
|
||||
// 하위에 할당 가능한 권한이 없으면 렌더링하지 않음
|
||||
if (assignableChildren.length === 0 && category.children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 하위에 카테고리가 더 있는 경우 재귀 렌더링
|
||||
const hasSubCategories = category.children.some((child) => !child.is_assignable);
|
||||
|
||||
const gridColsClass =
|
||||
desktopColumns === 1
|
||||
? 'grid-cols-1'
|
||||
: desktopColumns === 3
|
||||
? 'grid-cols-1 md:grid-cols-3'
|
||||
: 'grid-cols-1 md:grid-cols-2';
|
||||
|
||||
return (
|
||||
<Accordion key={category.id} defaultOpen={false} className="border-0 rounded-none">
|
||||
{/* Trigger */}
|
||||
<Div slot="trigger" className="flex items-center gap-3 w-full py-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isFullySelected}
|
||||
ref={(el: HTMLInputElement | null) => {
|
||||
if (el) el.indeterminate = isPartiallySelected;
|
||||
}}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
e.stopPropagation();
|
||||
handleGroupChange(category, e.target.checked);
|
||||
}}
|
||||
onClick={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
onMouseDown={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
disabled={disabled}
|
||||
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
|
||||
/>
|
||||
<Icon name={IconName.Folder} className="w-4 h-4 text-gray-400 dark:text-gray-500" />
|
||||
<Span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{category.name}
|
||||
</Span>
|
||||
<Span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 ml-1">
|
||||
{selectedCount}/{category.leaf_count}
|
||||
</Span>
|
||||
<Icon name={IconName.ChevronDown} className="w-4 h-4 text-gray-400 dark:text-gray-500 ml-auto" />
|
||||
</Div>
|
||||
|
||||
{/* Content */}
|
||||
<Div slot="content" className={`pl-8 grid ${gridColsClass} gap-2 py-2`}>
|
||||
{hasSubCategories
|
||||
? // 하위 카테고리가 있으면 재귀 렌더링
|
||||
category.children.map((child) =>
|
||||
child.is_assignable
|
||||
? renderLeafPermission(child)
|
||||
: renderCategory(child, moduleNode)
|
||||
)
|
||||
: // 리프 권한만 있으면 그리드로 렌더링
|
||||
assignableChildren.map((permission) => renderLeafPermission(permission))}
|
||||
</Div>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 확장 타입 판별 (코어, 모듈, 플러그인)
|
||||
* API 응답의 extension_type 필드를 우선 사용하고, 없으면 identifier 기반 폴백
|
||||
*/
|
||||
const getExtensionType = (
|
||||
node: PermissionNode
|
||||
): 'core' | 'module' | 'plugin' => {
|
||||
// API에서 extension_type을 직접 제공하는 경우 우선 사용
|
||||
if (node.extension_type === 'core') return 'core';
|
||||
if (node.extension_type === 'module') return 'module';
|
||||
if (node.extension_type === 'plugin') return 'plugin';
|
||||
|
||||
// 폴백: identifier 기반 판별 (하위 호환)
|
||||
const identifier = node.extension_identifier ?? node.module ?? '';
|
||||
if (identifier === 'core' || !identifier) return 'core';
|
||||
const isPlugin = installedPlugins?.some(
|
||||
(p) => p.identifier === identifier
|
||||
);
|
||||
return isPlugin ? 'plugin' : 'module';
|
||||
};
|
||||
|
||||
/**
|
||||
* 모듈(1depth) 렌더링
|
||||
*/
|
||||
const renderModule = (moduleNode: PermissionNode) => {
|
||||
const isFullySelected = isNodeFullySelected(moduleNode);
|
||||
const isPartiallySelected = isNodePartiallySelected(moduleNode);
|
||||
const selectedCount = getSelectedCount(moduleNode);
|
||||
const extensionType = getExtensionType(moduleNode);
|
||||
|
||||
return (
|
||||
<Accordion key={moduleNode.id} defaultOpen={false} className="mb-2">
|
||||
{/* Trigger */}
|
||||
<Div slot="trigger" className="flex items-center gap-3 w-full py-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isFullySelected}
|
||||
ref={(el: HTMLInputElement | null) => {
|
||||
if (el) el.indeterminate = isPartiallySelected;
|
||||
}}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
e.stopPropagation();
|
||||
handleGroupChange(moduleNode, e.target.checked);
|
||||
}}
|
||||
onClick={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
onMouseDown={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
disabled={disabled}
|
||||
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
|
||||
/>
|
||||
<Icon
|
||||
name={extensionType === 'core' ? IconName.Cog : IconName.Cube}
|
||||
className="w-5 h-5 text-gray-400 dark:text-gray-500"
|
||||
/>
|
||||
<Span className="font-medium text-gray-900 dark:text-white">{moduleNode.name}</Span>
|
||||
{extensionType !== 'core' && (
|
||||
<ExtensionBadge
|
||||
type={extensionType}
|
||||
identifier={moduleNode.extension_identifier ?? moduleNode.module}
|
||||
installedModules={installedModules}
|
||||
installedPlugins={installedPlugins}
|
||||
/>
|
||||
)}
|
||||
<Span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 ml-2">
|
||||
{selectedCount}/{moduleNode.leaf_count}
|
||||
</Span>
|
||||
<Icon name={IconName.ChevronDown} className="w-4 h-4 text-gray-400 dark:text-gray-500 ml-auto" />
|
||||
</Div>
|
||||
|
||||
{/* Content */}
|
||||
<Div slot="content" className="pl-8 space-y-2 pb-2">
|
||||
{moduleNode.children.map((category) =>
|
||||
category.is_assignable
|
||||
? renderLeafPermission(category)
|
||||
: renderCategory(category, moduleNode)
|
||||
)}
|
||||
</Div>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Div className={`space-y-2 ${className}`}>
|
||||
{data.map((moduleNode) => renderModule(moduleNode))}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Img } from '../basic/Img';
|
||||
import { H2 } from '../basic/H2';
|
||||
import { H3 } from '../basic/H3';
|
||||
import { P } from '../basic/P';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
|
||||
export interface ProductCardProps {
|
||||
imageUrl?: string;
|
||||
imageAlt?: string;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
description?: string;
|
||||
price: number;
|
||||
originalPrice?: number;
|
||||
discountRate?: number;
|
||||
currency?: string;
|
||||
buttonText?: string;
|
||||
onButtonClick?: () => void;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProductCard 집합 컴포넌트
|
||||
*
|
||||
* 상품 정보를 표시하는 카드 컴포넌트입니다.
|
||||
* 이미지, 제목, 부제목, 설명, 가격, 할인율, 액션 버튼을 포함합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Div + Img + H2 + H3 + P + Span + Button
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "ProductCard",
|
||||
* "props": {
|
||||
* "imageUrl": "/product.png",
|
||||
* "title": "프리미엄 제품",
|
||||
* "subtitle": "신제품",
|
||||
* "description": "최고급 소재로 제작된 프리미엄 제품입니다.",
|
||||
* "price": 45000,
|
||||
* "originalPrice": 50000,
|
||||
* "discountRate": 10,
|
||||
* "buttonText": "구매하기"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const ProductCard: React.FC<ProductCardProps> = ({
|
||||
imageUrl,
|
||||
imageAlt = '',
|
||||
title,
|
||||
subtitle,
|
||||
description,
|
||||
price,
|
||||
originalPrice,
|
||||
discountRate,
|
||||
currency = '₩',
|
||||
buttonText = '자세히 보기',
|
||||
onButtonClick,
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
const hasDiscount = discountRate && discountRate > 0;
|
||||
const formattedPrice = price.toLocaleString();
|
||||
const formattedOriginalPrice = originalPrice?.toLocaleString();
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`rounded-lg bg-white dark:bg-gray-800 shadow-md hover:shadow-xl transition-shadow border border-gray-200 dark:border-gray-700 overflow-hidden ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{/* 상품 이미지 */}
|
||||
{imageUrl && (
|
||||
<Div className="relative w-full">
|
||||
<Img
|
||||
src={imageUrl}
|
||||
alt={imageAlt || title}
|
||||
className="w-full h-64 object-cover"
|
||||
/>
|
||||
{hasDiscount && (
|
||||
<Div className="absolute top-2 right-2 bg-red-500 text-white px-2 py-1 rounded-md">
|
||||
<Span className="text-sm font-bold">-{discountRate}%</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 상품 정보 */}
|
||||
<Div className="p-4">
|
||||
{/* 부제목 (태그/카테고리) */}
|
||||
{subtitle && (
|
||||
<H3 className="text-xs font-medium text-blue-600 dark:text-blue-400 uppercase tracking-wider mb-2">
|
||||
{subtitle}
|
||||
</H3>
|
||||
)}
|
||||
|
||||
{/* 제목 */}
|
||||
<H2 className="text-xl font-bold text-gray-900 dark:text-white mb-2 line-clamp-2">
|
||||
{title}
|
||||
</H2>
|
||||
|
||||
{/* 설명 */}
|
||||
{description && (
|
||||
<P className="text-sm text-gray-600 dark:text-gray-400 mb-4 line-clamp-3">
|
||||
{description}
|
||||
</P>
|
||||
)}
|
||||
|
||||
{/* 가격 정보 */}
|
||||
<Div className="flex items-center gap-2 mb-4">
|
||||
<Span className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{currency}{formattedPrice}
|
||||
</Span>
|
||||
{originalPrice && (
|
||||
<Span className="text-sm text-gray-400 dark:text-gray-500 line-through">
|
||||
{currency}{formattedOriginalPrice}
|
||||
</Span>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 액션 버튼 */}
|
||||
{buttonText && (
|
||||
<Button
|
||||
onClick={onButtonClick}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-lg transition-colors"
|
||||
>
|
||||
{buttonText}
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,162 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Label } from '../basic/Label';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
export interface RadioOption {
|
||||
/** 라디오 버튼의 값 */
|
||||
value: string;
|
||||
/** 라디오 버튼의 라벨 */
|
||||
label: string;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface RadioGroupProps {
|
||||
/** 그룹 이름 (form 전송 시 사용) */
|
||||
name: string;
|
||||
/** 현재 선택된 값 */
|
||||
value?: string;
|
||||
/** 라디오 옵션 배열 */
|
||||
options: RadioOption[];
|
||||
/** 값 변경 콜백 */
|
||||
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 인라인 표시 여부 (기본값: false, 수직 배치) */
|
||||
inline?: boolean;
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
/** 라디오 버튼 크기 */
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
/** 그룹 라벨 */
|
||||
label?: string;
|
||||
/** 에러 메시지 */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* RadioGroup 컴포넌트
|
||||
*
|
||||
* 여러 라디오 버튼을 그룹으로 묶어 관리합니다.
|
||||
* Flowbite 스타일을 따르며, 라이트/다크 모드를 모두 지원합니다.
|
||||
*/
|
||||
export const RadioGroup: React.FC<RadioGroupProps> = ({
|
||||
name,
|
||||
value: valueProp,
|
||||
options,
|
||||
onChange,
|
||||
disabled = false,
|
||||
inline = false,
|
||||
className = '',
|
||||
size = 'md',
|
||||
label,
|
||||
error,
|
||||
}) => {
|
||||
// 내부 상태로 관리
|
||||
const [value, setValue] = useState(() => valueProp ?? '');
|
||||
|
||||
// prop 변경 시 내부 상태 동기화
|
||||
useEffect(() => {
|
||||
setValue(valueProp ?? '');
|
||||
}, [valueProp]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
|
||||
// 내부 상태 즉시 업데이트
|
||||
setValue(newValue);
|
||||
|
||||
if (onChange && !disabled) {
|
||||
// 템플릿 엔진의 actions는 이벤트 객체를 받으므로 항상 이벤트로 전달
|
||||
onChange(e);
|
||||
}
|
||||
};
|
||||
|
||||
// 크기별 클래스
|
||||
const sizeClasses = {
|
||||
sm: {
|
||||
radio: 'w-3.5 h-3.5',
|
||||
label: 'text-xs',
|
||||
gap: 'gap-1.5',
|
||||
},
|
||||
md: {
|
||||
radio: 'w-4 h-4',
|
||||
label: 'text-sm',
|
||||
gap: 'gap-2',
|
||||
},
|
||||
lg: {
|
||||
radio: 'w-5 h-5',
|
||||
label: 'text-base',
|
||||
gap: 'gap-2.5',
|
||||
},
|
||||
};
|
||||
|
||||
const currentSize = sizeClasses[size];
|
||||
|
||||
// 레이아웃 클래스
|
||||
const layoutClass = inline ? 'flex flex-wrap items-center gap-4' : 'flex flex-col gap-2';
|
||||
|
||||
return (
|
||||
<Div className={className}>
|
||||
{/* 그룹 라벨 */}
|
||||
{label && (
|
||||
<Span
|
||||
className={`block mb-2 font-medium text-gray-700 dark:text-gray-300 ${currentSize.label}`}
|
||||
>
|
||||
{label}
|
||||
</Span>
|
||||
)}
|
||||
|
||||
{/* 라디오 버튼 목록 */}
|
||||
<Div className={layoutClass}>
|
||||
{options.map((option) => {
|
||||
const isChecked = String(option.value) === String(value);
|
||||
const isDisabled = disabled || option.disabled;
|
||||
|
||||
return (
|
||||
<Label
|
||||
key={option.value}
|
||||
className={`inline-flex items-center ${currentSize.gap} ${
|
||||
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={name}
|
||||
value={option.value}
|
||||
checked={isChecked}
|
||||
onChange={handleChange}
|
||||
disabled={isDisabled}
|
||||
className={`
|
||||
${currentSize.radio}
|
||||
text-blue-600
|
||||
bg-gray-100 dark:bg-gray-700
|
||||
border-gray-300 dark:border-gray-600
|
||||
focus:ring-blue-500 dark:focus:ring-blue-600
|
||||
focus:ring-2
|
||||
dark:ring-offset-gray-800
|
||||
${isDisabled ? 'cursor-not-allowed' : 'cursor-pointer'}
|
||||
`}
|
||||
/>
|
||||
<Span
|
||||
className={`
|
||||
${currentSize.label}
|
||||
font-medium
|
||||
text-gray-900 dark:text-gray-300
|
||||
`}
|
||||
>
|
||||
{option.label}
|
||||
</Span>
|
||||
</Label>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && (
|
||||
<Span className="mt-1 text-xs text-red-600 dark:text-red-400">{error}</Span>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,311 @@
|
||||
import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Svg } from '../basic/Svg';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
// G7Core.renderComponentLayout() 헬퍼 참조
|
||||
const renderComponentLayout = (
|
||||
layoutDefs: any[] | undefined,
|
||||
itemContext: Record<string, any>,
|
||||
keyPrefix?: string
|
||||
): React.ReactNode => {
|
||||
return (window as any).G7Core?.renderComponentLayout?.(layoutDefs, itemContext, keyPrefix) ?? null;
|
||||
};
|
||||
|
||||
export interface RichSelectOption {
|
||||
/** 옵션 고유 값 */
|
||||
value: string | number;
|
||||
/** 기본 라벨 (selectedTemplate이 없을 때 트리거에 표시) */
|
||||
label: string;
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 옵션에 포함된 추가 데이터 (itemTemplate에서 {{item.xxx}}로 접근) */
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface RichSelectProps {
|
||||
/** 옵션 목록 */
|
||||
options?: RichSelectOption[];
|
||||
/** 선택된 값 */
|
||||
value?: string | number;
|
||||
/** 값 변경 핸들러 */
|
||||
onChange?: (e: { target: { value: string | number } }) => void;
|
||||
/** 트리거 버튼 placeholder */
|
||||
placeholder?: string;
|
||||
/** 비활성화 */
|
||||
disabled?: boolean;
|
||||
/** 추가 클래스 */
|
||||
className?: string;
|
||||
/** 드롭다운 최대 높이 */
|
||||
maxHeight?: string;
|
||||
/**
|
||||
* 각 옵션 항목 렌더링용 children
|
||||
* 템플릿 엔진에서 itemContext로 item, index, isSelected를 주입받음
|
||||
*/
|
||||
children?: React.ReactNode;
|
||||
/**
|
||||
* 선택된 항목 표시용 children (트리거 버튼에 표시)
|
||||
* 없으면 option.label 사용
|
||||
*/
|
||||
selectedChildren?: React.ReactNode;
|
||||
/**
|
||||
* DynamicRenderer에서 전달되는 component_layout 정의
|
||||
* @internal 템플릿 엔진 내부 사용
|
||||
*/
|
||||
__componentLayoutDefs?: {
|
||||
/** 각 옵션 항목 렌더링용 레이아웃 정의 */
|
||||
item?: any[];
|
||||
/** 선택된 항목 표시용 레이아웃 정의 */
|
||||
selected?: any[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 리치 셀렉트 컴포넌트
|
||||
*
|
||||
* component_layout을 통해 각 항목을 커스텀 렌더링할 수 있습니다.
|
||||
* 파일 선택, 사용자 선택 등 복잡한 정보를 표시해야 하는 드롭다운에 적합합니다.
|
||||
*
|
||||
* @example JSON 레이아웃에서 사용
|
||||
* ```json
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "RichSelect",
|
||||
* "props": {
|
||||
* "value": "{{_global.selectedFile}}",
|
||||
* "options": "{{files?.data ?? []}}",
|
||||
* "placeholder": "파일을 선택하세요"
|
||||
* },
|
||||
* "component_layout": {
|
||||
* "item": [
|
||||
* {
|
||||
* "type": "basic",
|
||||
* "name": "Div",
|
||||
* "props": { "className": "flex flex-col" },
|
||||
* "children": [
|
||||
* { "type": "basic", "name": "Span", "text": "{{item.label}}" },
|
||||
* { "type": "basic", "name": "Span", "text": "{{item.size}} • {{item.updated_at}}" }
|
||||
* ]
|
||||
* }
|
||||
* ],
|
||||
* "selected": [
|
||||
* { "type": "basic", "name": "Span", "text": "{{item.label}}" }
|
||||
* ]
|
||||
* },
|
||||
* "actions": [{ "type": "change", "handler": "setState", "params": { "target": "global", "selectedFile": "{{$event.target.value}}" } }]
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export const RichSelect: React.FC<RichSelectProps> = ({
|
||||
options = [],
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
disabled = false,
|
||||
className = '',
|
||||
maxHeight = '320px',
|
||||
children,
|
||||
selectedChildren,
|
||||
__componentLayoutDefs,
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
// 선택된 옵션 찾기
|
||||
const selectedOption = useMemo(() => {
|
||||
if (value === undefined || value === null) return null;
|
||||
return options.find(opt => String(opt.value) === String(value)) || null;
|
||||
}, [options, value]);
|
||||
|
||||
// 외부 클릭 시 드롭다운 닫기
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// ESC 키로 드롭다운 닫기
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && isOpen) {
|
||||
setIsOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [isOpen]);
|
||||
|
||||
const handleToggle = useCallback(() => {
|
||||
if (!disabled) {
|
||||
setIsOpen(prev => !prev);
|
||||
}
|
||||
}, [disabled]);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(optionValue: string | number) => {
|
||||
if (onChange) {
|
||||
const syntheticEvent = {
|
||||
target: { value: optionValue },
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
type: 'change',
|
||||
};
|
||||
onChange(syntheticEvent as { target: { value: string | number } });
|
||||
}
|
||||
setIsOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
},
|
||||
[onChange]
|
||||
);
|
||||
|
||||
// placeholder 다국어 처리
|
||||
const resolvedPlaceholder = placeholder ?? t('common.select');
|
||||
|
||||
// 트리거에 표시할 내용 결정
|
||||
const renderTriggerContent = () => {
|
||||
if (!selectedOption) {
|
||||
return <Span className="text-gray-400 dark:text-gray-500">{resolvedPlaceholder}</Span>;
|
||||
}
|
||||
|
||||
// 1. component_layout.selected가 있으면 사용
|
||||
if (__componentLayoutDefs?.selected) {
|
||||
const rendered = renderComponentLayout(
|
||||
__componentLayoutDefs.selected,
|
||||
{ item: selectedOption, isSelected: true },
|
||||
'selected'
|
||||
);
|
||||
if (rendered) return rendered;
|
||||
}
|
||||
|
||||
// 2. selectedChildren이 있으면 사용
|
||||
if (selectedChildren) {
|
||||
return selectedChildren;
|
||||
}
|
||||
|
||||
// 3. 기본: label 표시
|
||||
return <Span className="truncate">{selectedOption.label}</Span>;
|
||||
};
|
||||
|
||||
// children이 없을 때 기본 항목 렌더링
|
||||
const renderDefaultItem = (option: RichSelectOption, isSelected: boolean) => (
|
||||
<Div className="flex items-center justify-between w-full">
|
||||
<Span
|
||||
className={
|
||||
isSelected ? 'text-blue-600 dark:text-blue-400 font-medium' : 'text-gray-900 dark:text-white'
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</Span>
|
||||
{isSelected && (
|
||||
<Svg className="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</Svg>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Div ref={containerRef} className={`relative ${className}`}>
|
||||
{/* 트리거 버튼 */}
|
||||
<Button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={handleToggle}
|
||||
disabled={disabled}
|
||||
className={`
|
||||
w-full px-4 py-2.5
|
||||
bg-gray-100 dark:bg-gray-700
|
||||
border-0 rounded-xl
|
||||
text-gray-700 dark:text-gray-200 font-medium
|
||||
focus:ring-2 focus:ring-blue-500 focus:outline-none
|
||||
flex items-center justify-between gap-2
|
||||
text-left cursor-pointer
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
`}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={isOpen}
|
||||
>
|
||||
<Div className="flex-1 min-w-0">{renderTriggerContent()}</Div>
|
||||
<Svg
|
||||
className={`w-4 h-4 flex-shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</Svg>
|
||||
</Button>
|
||||
|
||||
{/* 드롭다운 */}
|
||||
{isOpen && (
|
||||
<Div
|
||||
className="absolute z-50 w-full mt-2 bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 overflow-hidden"
|
||||
role="listbox"
|
||||
>
|
||||
<Div className="overflow-auto" style={{ maxHeight }}>
|
||||
{options.length === 0 ? (
|
||||
<Div className="px-4 py-6 text-center text-gray-500 dark:text-gray-400">
|
||||
{t('common.no_options')}
|
||||
</Div>
|
||||
) : (
|
||||
options.map((option, index) => {
|
||||
const isSelected = String(option.value) === String(value);
|
||||
return (
|
||||
<Button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => !option.disabled && handleSelect(option.value)}
|
||||
disabled={option.disabled}
|
||||
className={`
|
||||
w-full px-4 py-3 text-left
|
||||
hover:bg-gray-100 dark:hover:bg-gray-700
|
||||
transition-colors
|
||||
${isSelected ? 'bg-blue-50 dark:bg-blue-900/20' : ''}
|
||||
${option.disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
|
||||
`}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
data-item-value={option.value}
|
||||
data-item-index={index}
|
||||
data-item-selected={isSelected}
|
||||
>
|
||||
{/* 1. component_layout.item이 있으면 사용 */}
|
||||
{__componentLayoutDefs?.item
|
||||
? renderComponentLayout(
|
||||
__componentLayoutDefs.item,
|
||||
{ item: option, index, isSelected },
|
||||
`item-${index}`
|
||||
)
|
||||
: /* 2. children이 있으면 사용 */
|
||||
children
|
||||
? children
|
||||
: /* 3. 기본 렌더링 */
|
||||
renderDefaultItem(option, isSelected)}
|
||||
</Button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,201 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Form } from '../basic/Form';
|
||||
import { Input } from '../basic/Input';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
// G7Core 참조
|
||||
const G7Core = () => (window as any).G7Core;
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
G7Core()?.t?.(key, params) ?? key;
|
||||
|
||||
export interface SearchSuggestion {
|
||||
id: string | number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface SearchBarProps {
|
||||
name?: string;
|
||||
placeholder?: string;
|
||||
value?: string;
|
||||
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
onSubmit?: (e: React.FormEvent<HTMLFormElement>) => void;
|
||||
showButton?: boolean; // true: 검색 버튼 표시, false: 버튼 숨김 (기본값: false)
|
||||
suggestions?: SearchSuggestion[];
|
||||
onSuggestionClick?: (suggestion: SearchSuggestion) => void;
|
||||
showSuggestions?: boolean;
|
||||
className?: string; // 외부 className (w-full 등)은 G7Core.style.mergeClasses로 내부 기본 클래스를 오버라이드
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* SearchBar 집합 컴포넌트
|
||||
*
|
||||
* 검색 입력 필드와 선택적 버튼을 제공하는 검색 바 컴포넌트입니다.
|
||||
* Enter 키를 누르면 항상 검색이 실행됩니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Form + Input + Button + Icon + Div + Span
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시 (버튼 없음)
|
||||
* {
|
||||
* "name": "SearchBar",
|
||||
* "props": {
|
||||
* "placeholder": "검색어를 입력하세요",
|
||||
* "value": "{{query.search}}",
|
||||
* "showButton": false
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시 (버튼 있음)
|
||||
* {
|
||||
* "name": "SearchBar",
|
||||
* "props": {
|
||||
* "placeholder": "검색어를 입력하세요",
|
||||
* "value": "{{query.search}}",
|
||||
* "showButton": true
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시 (전체 너비 - className으로 오버라이드)
|
||||
* {
|
||||
* "name": "SearchBar",
|
||||
* "props": {
|
||||
* "placeholder": "검색어를 입력하세요",
|
||||
* "value": "{{query.search}}",
|
||||
* "className": "w-full"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const SearchBar: React.FC<SearchBarProps> = ({
|
||||
name = 'search',
|
||||
placeholder,
|
||||
value: controlledValue,
|
||||
onChange,
|
||||
onSubmit,
|
||||
showButton = false,
|
||||
suggestions = [],
|
||||
onSuggestionClick,
|
||||
showSuggestions = false,
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
// props로 전달된 값이 없으면 다국어 키 사용
|
||||
const resolvedPlaceholder = placeholder ?? t('common.search_placeholder');
|
||||
|
||||
const [internalValue, setInternalValue] = useState('');
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
const containerRef = React.useRef<HTMLDivElement>(null);
|
||||
const previousValueRef = React.useRef<string>('');
|
||||
|
||||
const value = controlledValue !== undefined ? controlledValue : internalValue;
|
||||
const shouldShowSuggestions = showSuggestions && isFocused && suggestions.length > 0 && value.length > 0;
|
||||
|
||||
// 기본 Input 클래스 (w-64 포함)
|
||||
const baseInputClasses = 'w-64 pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm';
|
||||
// 외부 className으로 기본 클래스 오버라이드 (예: w-full이 w-64를 대체)
|
||||
const inputClassName = G7Core()?.style?.mergeClasses?.(baseInputClasses, className) ?? `${baseInputClasses} ${className}`;
|
||||
|
||||
// controlledValue가 변경될 때 previousValueRef 동기화
|
||||
useEffect(() => {
|
||||
if (controlledValue !== undefined) {
|
||||
previousValueRef.current = controlledValue;
|
||||
}
|
||||
}, [controlledValue]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
setInternalValue(newValue);
|
||||
onChange?.(e);
|
||||
|
||||
// X 버튼으로 검색어를 지운 경우 감지
|
||||
// 이전 값이 있었는데 새 값이 빈 문자열이고, nativeEvent가 없는 경우 = X 버튼 클릭
|
||||
if (previousValueRef.current !== '' && newValue === '' && !(e.nativeEvent as any).inputType) {
|
||||
// X 버튼 클릭: 자동으로 검색 초기화
|
||||
setTimeout(() => {
|
||||
const formElement = containerRef.current?.querySelector('form');
|
||||
if (formElement) {
|
||||
formElement.requestSubmit();
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
previousValueRef.current = newValue;
|
||||
};
|
||||
|
||||
const handleSuggestionClick = (suggestion: SearchSuggestion) => {
|
||||
setInternalValue(suggestion.text);
|
||||
const syntheticEvent = {
|
||||
target: { value: suggestion.text, name },
|
||||
} as React.ChangeEvent<HTMLInputElement>;
|
||||
onChange?.(syntheticEvent);
|
||||
onSuggestionClick?.(suggestion);
|
||||
setIsFocused(false);
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
onSubmit?.(e);
|
||||
};
|
||||
|
||||
return (
|
||||
<Div ref={containerRef} className="relative" style={style}>
|
||||
<Form onSubmit={handleSubmit} className="relative">
|
||||
<Div className={`relative flex items-center ${showButton ? 'gap-2' : ''}`}>
|
||||
{/* Input wrapper */}
|
||||
<Div className="relative flex-1">
|
||||
{/* 검색 아이콘 */}
|
||||
<Div className="absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none">
|
||||
<Icon name={IconName.Search} className="w-5 h-5 text-gray-400 dark:text-gray-500" />
|
||||
</Div>
|
||||
|
||||
{/* 검색 입력 */}
|
||||
<Input
|
||||
type="search"
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
onFocus={() => setIsFocused(true)}
|
||||
onBlur={() => setTimeout(() => setIsFocused(false), 200)}
|
||||
placeholder={resolvedPlaceholder}
|
||||
className={inputClassName}
|
||||
/>
|
||||
</Div>
|
||||
|
||||
{/* 검색 버튼 (showButton=true일 때만 표시) */}
|
||||
{showButton && (
|
||||
<Button
|
||||
type="submit"
|
||||
className="px-4 py-2 bg-gray-800 dark:bg-gray-600 text-white rounded-lg hover:bg-gray-900 dark:hover:bg-gray-500 transition-colors text-sm font-medium cursor-pointer h-[42px]"
|
||||
>
|
||||
{t('common.search')}
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
</Form>
|
||||
|
||||
{/* 자동완성 제안 목록 */}
|
||||
{shouldShowSuggestions && (
|
||||
<Div className="absolute z-10 w-full mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-64 overflow-y-auto">
|
||||
{suggestions.map((suggestion) => (
|
||||
<Div
|
||||
key={suggestion.id}
|
||||
className="px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer border-b border-gray-100 dark:border-gray-700 last:border-b-0 transition-colors"
|
||||
onClick={() => handleSuggestionClick(suggestion)}
|
||||
>
|
||||
<Div className="flex items-center gap-2">
|
||||
<Icon name={IconName.Search} className="w-4 h-4 text-gray-400 dark:text-gray-500" />
|
||||
<Span className="text-sm text-gray-700 dark:text-gray-300">{suggestion.text}</Span>
|
||||
</Div>
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Svg } from '../basic/Svg';
|
||||
|
||||
export interface SearchableDropdownOption {
|
||||
value: string | number;
|
||||
label: string;
|
||||
description?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SearchableDropdownProps {
|
||||
/** 옵션 목록 */
|
||||
options?: SearchableDropdownOption[];
|
||||
/** 선택된 값 (단일: string|number, 다중: 배열) */
|
||||
value?: string | number | (string | number)[];
|
||||
/** 값 변경 핸들러 */
|
||||
onChange?: (value: string | number | (string | number)[]) => void;
|
||||
/** 다중 선택 모드 활성화 */
|
||||
multiple?: boolean;
|
||||
/** 검색창 placeholder */
|
||||
searchPlaceholder?: string;
|
||||
/** 외부 검색 핸들러 (백엔드 연동용) */
|
||||
onSearch?: (searchTerm: string) => void;
|
||||
/** 결과 없음 메시지 */
|
||||
noResultsText?: string;
|
||||
/** 초기 안내 문구 */
|
||||
initialText?: string;
|
||||
/** 트리거 버튼 텍스트 */
|
||||
triggerLabel?: string;
|
||||
/** 트리거 버튼 아이콘 */
|
||||
triggerIcon?: React.ReactNode;
|
||||
/** 비활성화 */
|
||||
disabled?: boolean;
|
||||
/** 추가 클래스 */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검색 가능한 드롭다운 컴포넌트
|
||||
*
|
||||
* 검색어 입력으로 옵션을 필터링하고 선택할 수 있습니다.
|
||||
* 단일 선택 및 다중 선택 모드를 지원합니다.
|
||||
*/
|
||||
export const SearchableDropdown: React.FC<SearchableDropdownProps> = ({
|
||||
options = [],
|
||||
value,
|
||||
onChange,
|
||||
multiple = false,
|
||||
searchPlaceholder = 'Search...',
|
||||
onSearch,
|
||||
noResultsText = 'No results found',
|
||||
initialText = 'Type to search',
|
||||
triggerLabel = 'Select',
|
||||
triggerIcon,
|
||||
disabled = false,
|
||||
className = '',
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const searchInputId = useRef(`searchable-dropdown-input-${Math.random().toString(36).slice(2, 9)}`).current;
|
||||
|
||||
// 선택된 값들을 배열로 정규화
|
||||
const selectedValues = useMemo((): (string | number)[] => {
|
||||
if (value === undefined || value === null) return [];
|
||||
if (Array.isArray(value)) return value;
|
||||
return [value];
|
||||
}, [value]);
|
||||
|
||||
// 검색어로 옵션 필터링
|
||||
const filteredOptions = useMemo(() => {
|
||||
if (!searchTerm.trim()) return options;
|
||||
const term = searchTerm.toLowerCase();
|
||||
return options.filter(
|
||||
opt =>
|
||||
opt.label.toLowerCase().includes(term) ||
|
||||
opt.description?.toLowerCase().includes(term)
|
||||
);
|
||||
}, [options, searchTerm]);
|
||||
|
||||
// 선택된 항목의 라벨 표시
|
||||
const displayLabel = useMemo(() => {
|
||||
if (selectedValues.length === 0) return triggerLabel;
|
||||
if (multiple) {
|
||||
const count = selectedValues.length;
|
||||
if (count === 1) {
|
||||
const selected = options.find(opt => String(opt.value) === String(selectedValues[0]));
|
||||
return selected?.label || triggerLabel;
|
||||
}
|
||||
return `${count} selected`;
|
||||
}
|
||||
const selected = options.find(opt => String(opt.value) === String(selectedValues[0]));
|
||||
return selected?.label || triggerLabel;
|
||||
}, [selectedValues, options, multiple, triggerLabel]);
|
||||
|
||||
// 외부 클릭 시 드롭다운 닫기
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// ESC 키로 드롭다운 닫기
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && isOpen) {
|
||||
setIsOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [isOpen]);
|
||||
|
||||
// 드롭다운 열릴 때 검색 입력에 포커스
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
// 약간의 딜레이 후 포커스 (렌더링 완료 후)
|
||||
setTimeout(() => {
|
||||
const input = document.getElementById(searchInputId) as HTMLInputElement;
|
||||
input?.focus();
|
||||
}, 50);
|
||||
} else {
|
||||
// 닫힐 때 검색어 초기화
|
||||
setSearchTerm('');
|
||||
}
|
||||
}, [isOpen, searchInputId]);
|
||||
|
||||
const handleToggle = useCallback(() => {
|
||||
if (!disabled) {
|
||||
setIsOpen(prev => !prev);
|
||||
}
|
||||
}, [disabled]);
|
||||
|
||||
const handleSearchChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const term = e.target.value;
|
||||
setSearchTerm(term);
|
||||
onSearch?.(term);
|
||||
},
|
||||
[onSearch]
|
||||
);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(optionValue: string | number) => {
|
||||
if (multiple) {
|
||||
// 다중 선택: 토글
|
||||
const isSelected = selectedValues.some(v => String(v) === String(optionValue));
|
||||
const newValues = isSelected
|
||||
? selectedValues.filter(v => String(v) !== String(optionValue))
|
||||
: [...selectedValues, optionValue];
|
||||
onChange?.(newValues);
|
||||
} else {
|
||||
// 단일 선택: 선택 후 닫기
|
||||
onChange?.(optionValue);
|
||||
setIsOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
}
|
||||
},
|
||||
[multiple, selectedValues, onChange]
|
||||
);
|
||||
|
||||
const isSelected = (optionValue: string | number): boolean => {
|
||||
return selectedValues.some(v => String(v) === String(optionValue));
|
||||
};
|
||||
|
||||
// 결과 상태 결정
|
||||
const showInitialMessage = searchTerm.length === 0 && options.length === 0;
|
||||
const showNoResults = searchTerm.length > 0 && filteredOptions.length === 0;
|
||||
const showOptions = filteredOptions.length > 0;
|
||||
|
||||
return (
|
||||
<Div ref={containerRef} className={`relative inline-block ${className}`}>
|
||||
{/* 트리거 버튼 */}
|
||||
<Button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={handleToggle}
|
||||
disabled={disabled}
|
||||
className={`
|
||||
px-4 py-2.5 bg-gray-100 dark:bg-gray-700
|
||||
border-0 rounded-xl
|
||||
text-gray-700 dark:text-gray-200 font-medium
|
||||
focus:ring-2 focus:ring-blue-500 focus:outline-none
|
||||
flex items-center justify-between gap-2
|
||||
text-left cursor-pointer
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
min-w-[200px]
|
||||
`}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={isOpen}
|
||||
>
|
||||
<Div className="flex items-center gap-2">
|
||||
{triggerIcon}
|
||||
<Span className="truncate">{displayLabel}</Span>
|
||||
</Div>
|
||||
<Svg
|
||||
className={`w-4 h-4 flex-shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</Svg>
|
||||
</Button>
|
||||
|
||||
{/* 드롭다운 */}
|
||||
{isOpen && (
|
||||
<Div
|
||||
className="absolute z-50 w-full mt-2 bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 overflow-hidden min-w-[280px]"
|
||||
role="listbox"
|
||||
>
|
||||
{/* 검색 입력 */}
|
||||
<Div className="p-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<input
|
||||
id={searchInputId}
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={handleSearchChange}
|
||||
placeholder={searchPlaceholder}
|
||||
className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none"
|
||||
/>
|
||||
</Div>
|
||||
|
||||
{/* 옵션 목록 */}
|
||||
<Div className="max-h-80 overflow-auto">
|
||||
{/* 초기 안내 메시지 */}
|
||||
{showInitialMessage && (
|
||||
<Div className="px-4 py-6 text-center text-gray-500 dark:text-gray-400">
|
||||
{initialText}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 결과 없음 메시지 */}
|
||||
{showNoResults && (
|
||||
<Div className="px-4 py-6 text-center text-gray-500 dark:text-gray-400">
|
||||
{noResultsText}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 옵션 목록 */}
|
||||
{showOptions && (
|
||||
<Div className="py-2">
|
||||
{filteredOptions.map(option => {
|
||||
const selected = isSelected(option.value);
|
||||
return (
|
||||
<Button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => !option.disabled && handleSelect(option.value)}
|
||||
disabled={option.disabled}
|
||||
className={`
|
||||
w-full px-4 py-3 text-left
|
||||
flex items-start gap-3
|
||||
hover:bg-gray-100 dark:hover:bg-gray-700
|
||||
transition-colors
|
||||
${option.disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
|
||||
`}
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
>
|
||||
{/* 체크 아이콘 영역 */}
|
||||
<Div className="w-5 h-5 flex-shrink-0 mt-0.5">
|
||||
{selected && (
|
||||
<Svg
|
||||
className="w-5 h-5 text-blue-600 dark:text-blue-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</Svg>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 옵션 내용 */}
|
||||
<Div className="flex-1 min-w-0">
|
||||
<Div
|
||||
className={`font-medium ${
|
||||
selected
|
||||
? 'text-blue-600 dark:text-blue-400'
|
||||
: 'text-gray-900 dark:text-white'
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</Div>
|
||||
{option.description && (
|
||||
<Div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
{option.description}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* SlotContainer.tsx
|
||||
*
|
||||
* 동적 슬롯에 등록된 컴포넌트들을 렌더링하는 컨테이너 컴포넌트
|
||||
*
|
||||
* SlotContainer는 SlotContext에서 지정된 슬롯 ID에 등록된 모든 컴포넌트를 수집하고,
|
||||
* slotOrder 기준으로 정렬하여 렌더링합니다.
|
||||
*
|
||||
* 주요 기능:
|
||||
* - 슬롯에 등록된 컴포넌트 수집 및 렌더링
|
||||
* - slotOrder 기준 정렬
|
||||
* - FormContext 및 ComponentContext 전달
|
||||
* - 빈 슬롯 처리 (emptyContent)
|
||||
*
|
||||
* @module SlotContainer
|
||||
* @since v1.10.0
|
||||
*
|
||||
* @example
|
||||
* ```json
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "SlotContainer",
|
||||
* "props": {
|
||||
* "slotId": "basic_filters",
|
||||
* "className": "flex flex-col gap-2"
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:SlotContainer')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:SlotContainer]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:SlotContainer]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:SlotContainer]', ...args),
|
||||
};
|
||||
|
||||
/**
|
||||
* SlotContainer Props
|
||||
*/
|
||||
export interface SlotContainerProps {
|
||||
/**
|
||||
* 슬롯 ID
|
||||
*
|
||||
* 이 슬롯에 등록된 컴포넌트들을 렌더링합니다.
|
||||
*/
|
||||
slotId: string;
|
||||
|
||||
/**
|
||||
* 컨테이너 CSS 클래스
|
||||
*/
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* 빈 슬롯일 때 표시할 내용
|
||||
*
|
||||
* React 엘리먼트 또는 문자열을 전달할 수 있습니다.
|
||||
*/
|
||||
emptyContent?: React.ReactNode;
|
||||
|
||||
/**
|
||||
* 인라인 스타일
|
||||
*/
|
||||
style?: React.CSSProperties;
|
||||
|
||||
/**
|
||||
* 컴포넌트 ID (DOM id)
|
||||
*/
|
||||
id?: string;
|
||||
|
||||
/**
|
||||
* 자식 컴포넌트 (children을 통한 fallback 또는 slot 컴포넌트가 아닌 정적 컨텐츠)
|
||||
*/
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* SlotRegistration 타입 (SlotContext에서 정의된 것과 호환)
|
||||
*/
|
||||
interface SlotRegistration {
|
||||
componentDef: any;
|
||||
dataContext: Record<string, any>;
|
||||
order: number;
|
||||
parentFormContext: any;
|
||||
getParentComponentContext: () => { state: Record<string, any>; setState: (updates: any) => void };
|
||||
translationContext: any;
|
||||
registrationKey: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* SlotContext 값 타입
|
||||
*/
|
||||
interface SlotContextValue {
|
||||
getSlotComponents: (slotId: string) => SlotRegistration[];
|
||||
subscribeToSlot: (slotId: string, callback: () => void) => () => void;
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* SlotContainer 컴포넌트
|
||||
*
|
||||
* SlotContext에서 지정된 슬롯 ID에 등록된 컴포넌트들을 수집하여 렌더링합니다.
|
||||
* 컴포넌트는 slotOrder 기준으로 정렬됩니다.
|
||||
*
|
||||
* 이 컴포넌트는 SlotContext를 사용하므로 SlotProvider 내부에서만 동작합니다.
|
||||
* SlotProvider는 DynamicRenderer의 루트에서 자동으로 래핑됩니다.
|
||||
*
|
||||
* @param props SlotContainerProps
|
||||
*/
|
||||
export const SlotContainer: React.FC<SlotContainerProps> = ({
|
||||
slotId,
|
||||
className = '',
|
||||
emptyContent,
|
||||
style,
|
||||
id,
|
||||
children,
|
||||
}) => {
|
||||
const [slotComponents, setSlotComponents] = useState<SlotRegistration[]>([]);
|
||||
const [, forceUpdate] = useState({});
|
||||
|
||||
// SlotContext 가져오기 (window.__slotContextValue 또는 G7Core.getSlotContext() 사용)
|
||||
const getSlotContext = useCallback((): SlotContextValue | null => {
|
||||
// SlotProvider에서 직접 설정한 전역 값 우선 확인
|
||||
const directSlotContext = (window as any).__slotContextValue;
|
||||
if (directSlotContext) {
|
||||
return directSlotContext;
|
||||
}
|
||||
|
||||
// 폴백: G7Core.getSlotContext()를 통해 SlotContext 접근
|
||||
const g7Core = (window as any).G7Core;
|
||||
if (!g7Core) return null;
|
||||
|
||||
const slotContext = g7Core.getSlotContext?.();
|
||||
return slotContext || null;
|
||||
}, []);
|
||||
|
||||
// 슬롯 컴포넌트 업데이트 함수
|
||||
const updateSlotComponents = useCallback(() => {
|
||||
const slotContext = getSlotContext();
|
||||
if (slotContext && slotContext.isEnabled) {
|
||||
setSlotComponents(slotContext.getSlotComponents(slotId));
|
||||
}
|
||||
}, [slotId, getSlotContext]);
|
||||
|
||||
// 슬롯 구독 및 업데이트
|
||||
useEffect(() => {
|
||||
const slotContext = getSlotContext();
|
||||
|
||||
if (!slotContext || !slotContext.isEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 초기 컴포넌트 로드
|
||||
updateSlotComponents();
|
||||
|
||||
// 슬롯 변경 구독
|
||||
const unsubscribe = slotContext.subscribeToSlot(slotId, () => {
|
||||
updateSlotComponents();
|
||||
forceUpdate({});
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [slotId, getSlotContext, updateSlotComponents]);
|
||||
|
||||
// G7Core에서 DynamicRenderer 가져오기
|
||||
const getDynamicRenderer = useCallback(() => {
|
||||
const g7Core = (window as any).G7Core;
|
||||
if (!g7Core) return null;
|
||||
|
||||
return g7Core.getDynamicRenderer?.();
|
||||
}, []);
|
||||
|
||||
// 빈 슬롯 처리
|
||||
if (slotComponents.length === 0) {
|
||||
if (emptyContent) {
|
||||
return (
|
||||
<Div className={className} style={style} id={id}>
|
||||
{emptyContent}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// children이 있으면 fallback으로 사용
|
||||
if (children) {
|
||||
return (
|
||||
<Div className={className} style={style} id={id}>
|
||||
{children}
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
// 빈 컨테이너 (내용 없음)
|
||||
return null;
|
||||
}
|
||||
|
||||
const DynamicRenderer = getDynamicRenderer();
|
||||
const g7Core = (window as any).G7Core;
|
||||
|
||||
if (!DynamicRenderer || !g7Core) {
|
||||
logger.error('G7Core or DynamicRenderer not available');
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Div className={className} style={style} id={id}>
|
||||
{slotComponents.map((registration) => {
|
||||
const {
|
||||
componentDef,
|
||||
dataContext,
|
||||
parentFormContext,
|
||||
getParentComponentContext,
|
||||
translationContext,
|
||||
} = registration;
|
||||
|
||||
return (
|
||||
<DynamicRenderer
|
||||
key={componentDef.id || `slot-${slotId}-${registration.order}`}
|
||||
componentDef={componentDef}
|
||||
dataContext={dataContext}
|
||||
translationContext={translationContext}
|
||||
registry={g7Core.getComponentRegistry()}
|
||||
bindingEngine={g7Core.getDataBindingEngine()}
|
||||
translationEngine={g7Core.getTranslationEngine()}
|
||||
actionDispatcher={g7Core.getActionDispatcher()}
|
||||
parentComponentContext={getParentComponentContext?.()}
|
||||
parentFormContextProp={parentFormContext}
|
||||
isRootRenderer={false}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{/* 정적 children도 함께 렌더링 (있는 경우) */}
|
||||
{children}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SlotContainer;
|
||||
@@ -0,0 +1,175 @@
|
||||
import React from 'react';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { Toggle } from './Toggle';
|
||||
|
||||
// G7Core 전역 객체의 스타일 헬퍼 접근
|
||||
const G7Core = () => (window as any).G7Core;
|
||||
|
||||
export interface MenuItemData {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
url: string;
|
||||
icon: string;
|
||||
isActive: boolean;
|
||||
isModuleMenu: boolean;
|
||||
moduleName?: string;
|
||||
hasChildren?: boolean;
|
||||
}
|
||||
|
||||
export interface SortableMenuItemProps {
|
||||
item: MenuItemData;
|
||||
isSelected?: boolean;
|
||||
isExpanded?: boolean;
|
||||
level?: number;
|
||||
onClick?: () => void;
|
||||
onToggle?: (e: React.MouseEvent) => void;
|
||||
onExpandToggle?: () => void;
|
||||
/** 아이템 컨테이너 className */
|
||||
className?: string;
|
||||
/** 선택된 상태 className */
|
||||
selectedClassName?: string;
|
||||
/** 기본 상태 className */
|
||||
defaultClassName?: string;
|
||||
/** 드래그 핸들 className */
|
||||
dragHandleClassName?: string;
|
||||
/** 아이콘 컨테이너 className */
|
||||
iconContainerClassName?: string;
|
||||
/** 콘텐츠 영역 className */
|
||||
contentClassName?: string;
|
||||
/** 드래그 핸들 표시 여부 (기본값: true) */
|
||||
enableDrag?: boolean;
|
||||
/** 토글 비활성화 여부 (기본값: false) */
|
||||
toggleDisabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* SortableMenuItem 컴포넌트
|
||||
* 개별 메뉴 아이템 (드래그 가능)
|
||||
*/
|
||||
export const SortableMenuItem: React.FC<SortableMenuItemProps> = ({
|
||||
item,
|
||||
isSelected = false,
|
||||
isExpanded = false,
|
||||
level = 0,
|
||||
onClick,
|
||||
onToggle,
|
||||
onExpandToggle,
|
||||
className = '',
|
||||
selectedClassName = 'bg-blue-50 dark:bg-blue-900/30 border-blue-500',
|
||||
defaultClassName = 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600',
|
||||
dragHandleClassName = 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300',
|
||||
iconContainerClassName = 'bg-gray-100 dark:bg-gray-700',
|
||||
contentClassName = '',
|
||||
enableDrag = true,
|
||||
toggleDisabled = false,
|
||||
}) => {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: item.id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
const paddingLeft = level * 24 + 12;
|
||||
|
||||
// 기본 레이아웃 클래스 (변경 불가)
|
||||
const baseClassName = 'flex items-center gap-2 cursor-pointer transition-colors';
|
||||
|
||||
// 내부 클래스 (기본 + 상태별 스타일)
|
||||
const internalClasses = `${baseClassName} ${isSelected ? selectedClassName : defaultClassName}`;
|
||||
|
||||
// 외부 className과 병합 (외부 클래스가 내부 클래스를 오버라이드 가능)
|
||||
const combinedClassName = G7Core()?.style?.mergeClasses?.(internalClasses, className)
|
||||
?? `${internalClasses} ${className}`.trim();
|
||||
|
||||
return (
|
||||
<Div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={combinedClassName}
|
||||
onClick={onClick}
|
||||
>
|
||||
{/* 드래그 핸들 - enableDrag가 true일 때만 표시 */}
|
||||
{enableDrag && (
|
||||
<Div
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className={`flex-shrink-0 cursor-grab active:cursor-grabbing p-1 ${dragHandleClassName}`}
|
||||
style={{ paddingLeft: `${paddingLeft}px` }}
|
||||
>
|
||||
<Icon name="grip-vertical" className="w-4 h-4" />
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* enableDrag가 false일 때 계층 구조용 패딩만 적용 (level > 0인 경우에만) */}
|
||||
{!enableDrag && level > 0 && <Div style={{ paddingLeft: `${paddingLeft}px` }} />}
|
||||
|
||||
{/* 펼침/접힘 버튼 - 계층 구조가 있을 때만 표시 */}
|
||||
{enableDrag && (
|
||||
<>
|
||||
{item.hasChildren ? (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onExpandToggle?.();
|
||||
}}
|
||||
className={`flex-shrink-0 p-1 ${dragHandleClassName}`}
|
||||
>
|
||||
<Icon
|
||||
name={isExpanded ? 'chevron-down' : 'chevron-right'}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
</Button>
|
||||
) : (
|
||||
<Div className="flex-shrink-0 w-6" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 아이콘 */}
|
||||
<Div className={`flex-shrink-0 w-8 h-8 flex items-center justify-center rounded ${iconContainerClassName}`}>
|
||||
<Icon name={item.icon || 'file'} className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
</Div>
|
||||
|
||||
{/* 메뉴명 및 URL */}
|
||||
<Div className={`flex-1 min-w-0 ${contentClassName}`}>
|
||||
<Div className="flex items-center gap-1">
|
||||
<Span className="text-sm font-medium text-gray-900 dark:text-white truncate">
|
||||
{item.name}
|
||||
</Span>
|
||||
{item.isModuleMenu && (
|
||||
<Icon name="cube" className="w-2 h-2 text-gray-300 dark:text-gray-500 ml-2" title={item.moduleName} />
|
||||
)}
|
||||
</Div>
|
||||
<Span className="text-xs text-gray-500 dark:text-gray-400 truncate block">
|
||||
{item.url}
|
||||
</Span>
|
||||
</Div>
|
||||
|
||||
{/* 토글 스위치 */}
|
||||
<Div className="flex-shrink-0" onClick={(e) => e.stopPropagation()}>
|
||||
<Toggle
|
||||
checked={item.isActive}
|
||||
onChange={() => onToggle?.(new MouseEvent('click') as unknown as React.MouseEvent)}
|
||||
size="sm"
|
||||
disabled={toggleDisabled}
|
||||
/>
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,480 @@
|
||||
import React, { useState, useCallback, useMemo, useRef } from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
DragEndEvent,
|
||||
DragStartEvent,
|
||||
DragOverlay,
|
||||
UniqueIdentifier,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { SortableMenuItem, MenuItemData } from './SortableMenuItem';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H3 } from '../basic/H3';
|
||||
|
||||
// G7Core 전역 객체 접근
|
||||
const getG7Core = () => (window as any).G7Core;
|
||||
|
||||
export interface MenuItem {
|
||||
id: number;
|
||||
name: string | Record<string, string>;
|
||||
slug: string;
|
||||
url: string;
|
||||
icon: string;
|
||||
order: number;
|
||||
is_active: boolean;
|
||||
parent_id: number | null;
|
||||
module_id: number | null;
|
||||
module?: {
|
||||
id: number;
|
||||
name: string | Record<string, string>;
|
||||
slug: string;
|
||||
} | null;
|
||||
children: MenuItem[];
|
||||
created_by?: number;
|
||||
creator?: {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
} | null;
|
||||
roles?: {
|
||||
id: number;
|
||||
name: string | Record<string, string>;
|
||||
permission_type?: string | null;
|
||||
}[];
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface MenuOrderData {
|
||||
parent_menus: { id: number; order: number }[];
|
||||
child_menus: Record<number, { id: number; order: number }[]>;
|
||||
moved_items?: { id: number; new_parent_id: number | null }[];
|
||||
}
|
||||
|
||||
export interface SortableMenuListProps {
|
||||
items: MenuItem[];
|
||||
selectedId?: number;
|
||||
onSelect?: (item: MenuItem) => void;
|
||||
onOrderChange?: (orderData: MenuOrderData) => void;
|
||||
onToggleStatus?: (id: number, currentStatus: boolean) => void;
|
||||
title?: string;
|
||||
className?: string;
|
||||
listClassName?: string;
|
||||
childrenContainerClassName?: string;
|
||||
itemClassName?: string;
|
||||
itemSelectedClassName?: string;
|
||||
itemDefaultClassName?: string;
|
||||
titleClassName?: string;
|
||||
enableDrag?: boolean;
|
||||
toggleDisabled?: boolean;
|
||||
}
|
||||
|
||||
/** 평탄화된 트리 아이템 */
|
||||
interface FlatItem {
|
||||
item: MenuItem;
|
||||
depth: number;
|
||||
parentId: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 트리를 평탄 배열로 변환 (확장된 노드의 자식만 포함)
|
||||
*/
|
||||
export function flattenTree(items: MenuItem[], expandedItems: Set<number>, depth = 0, parentId: number | null = null): FlatItem[] {
|
||||
const result: FlatItem[] = [];
|
||||
for (const item of items) {
|
||||
result.push({ item, depth, parentId });
|
||||
if (item.children?.length > 0 && expandedItems.has(item.id)) {
|
||||
result.push(...flattenTree(item.children, expandedItems, depth + 1, item.id));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 트리에서 아이템 ID로 검색
|
||||
*/
|
||||
export function findItemById(menuItems: MenuItem[], id: number): MenuItem | null {
|
||||
for (const item of menuItems) {
|
||||
if (item.id === id) return item;
|
||||
if (item.children) {
|
||||
const found = findItemById(item.children, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 아이템의 모든 자손 ID 수집 (순환 참조 방지용)
|
||||
*/
|
||||
export function collectDescendantIds(item: MenuItem): number[] {
|
||||
const ids: number[] = [];
|
||||
if (item.children) {
|
||||
for (const child of item.children) {
|
||||
ids.push(child.id);
|
||||
ids.push(...collectDescendantIds(child));
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 트리에서 특정 아이템 제거
|
||||
*/
|
||||
export function removeItemFromTree(menuItems: MenuItem[], itemId: number): MenuItem[] {
|
||||
return menuItems
|
||||
.filter((item) => item.id !== itemId)
|
||||
.map((item) => {
|
||||
if (item.children?.length > 0) {
|
||||
return { ...item, children: removeItemFromTree(item.children, itemId) };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 부모 아래 지정 위치에 아이템 삽입
|
||||
*/
|
||||
export function insertItemIntoParent(
|
||||
menuItems: MenuItem[],
|
||||
newItem: MenuItem,
|
||||
targetParentId: number | null,
|
||||
insertIndex: number
|
||||
): MenuItem[] {
|
||||
if (targetParentId === null) {
|
||||
const result = [...menuItems];
|
||||
result.splice(insertIndex, 0, newItem);
|
||||
return result;
|
||||
}
|
||||
|
||||
return menuItems.map((item) => {
|
||||
if (item.id === targetParentId) {
|
||||
const newChildren = [...(item.children || [])];
|
||||
newChildren.splice(insertIndex, 0, newItem);
|
||||
return { ...item, children: newChildren };
|
||||
}
|
||||
if (item.children?.length > 0) {
|
||||
return { ...item, children: insertItemIntoParent(item.children, newItem, targetParentId, insertIndex) };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 부모 내에서 자식 순서 변경
|
||||
*/
|
||||
export function reorderInParent(
|
||||
menuItems: MenuItem[],
|
||||
parentId: number | null,
|
||||
activeId: number,
|
||||
overId: number
|
||||
): MenuItem[] {
|
||||
if (parentId === null) {
|
||||
const oldIndex = menuItems.findIndex((i) => i.id === activeId);
|
||||
const newIndex = menuItems.findIndex((i) => i.id === overId);
|
||||
if (oldIndex === -1 || newIndex === -1) return menuItems;
|
||||
return arrayMove(menuItems, oldIndex, newIndex);
|
||||
}
|
||||
|
||||
return menuItems.map((item) => {
|
||||
if (item.id === parentId && item.children) {
|
||||
const oldIndex = item.children.findIndex((c) => c.id === activeId);
|
||||
const newIndex = item.children.findIndex((c) => c.id === overId);
|
||||
if (oldIndex === -1 || newIndex === -1) return item;
|
||||
return { ...item, children: arrayMove(item.children, oldIndex, newIndex) };
|
||||
}
|
||||
if (item.children?.length > 0) {
|
||||
return { ...item, children: reorderInParent(item.children, parentId, activeId, overId) };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 트리에서 주문 데이터 생성
|
||||
*/
|
||||
export function generateOrderData(menuItems: MenuItem[]): MenuOrderData {
|
||||
const parentMenus = menuItems.map((item, index) => ({
|
||||
id: item.id,
|
||||
order: index + 1,
|
||||
}));
|
||||
|
||||
const childMenus: Record<number, { id: number; order: number }[]> = {};
|
||||
const collectChildMenus = (items: MenuItem[]) => {
|
||||
items.forEach((parent) => {
|
||||
if (parent.children?.length > 0) {
|
||||
childMenus[parent.id] = parent.children.map((child, index) => ({
|
||||
id: child.id,
|
||||
order: index + 1,
|
||||
}));
|
||||
collectChildMenus(parent.children);
|
||||
}
|
||||
});
|
||||
};
|
||||
collectChildMenus(menuItems);
|
||||
|
||||
return { parent_menus: parentMenus, child_menus: childMenus };
|
||||
}
|
||||
|
||||
/**
|
||||
* SortableMenuList 컴포넌트
|
||||
*
|
||||
* 드래그앤드롭 가능한 계층형 메뉴 목록
|
||||
* Flattened tree 방식: 단일 SortableContext로 크로스 depth 이동 지원
|
||||
*/
|
||||
export const SortableMenuList: React.FC<SortableMenuListProps> = ({
|
||||
items = [],
|
||||
selectedId,
|
||||
onSelect,
|
||||
onOrderChange,
|
||||
onToggleStatus,
|
||||
title,
|
||||
className = '',
|
||||
listClassName = '',
|
||||
childrenContainerClassName = 'bg-gray-50 dark:bg-gray-900/50',
|
||||
itemClassName = 'py-2.5 px-3 mx-4 my-2 rounded-lg border',
|
||||
itemSelectedClassName,
|
||||
itemDefaultClassName,
|
||||
titleClassName = 'px-4 py-3 border-b border-gray-200 dark:border-gray-700',
|
||||
enableDrag = true,
|
||||
toggleDisabled = false,
|
||||
}) => {
|
||||
const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set());
|
||||
const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
|
||||
const [localItems, setLocalItems] = useState<MenuItem[]>(items);
|
||||
const isPendingRef = useRef(false);
|
||||
const prevOrderKeyRef = useRef<string>('');
|
||||
const prevDataKeyRef = useRef<string>('');
|
||||
|
||||
const getDataKey = useCallback((menuItems: MenuItem[]): string => {
|
||||
return JSON.stringify(menuItems);
|
||||
}, []);
|
||||
|
||||
const getOrderKey = useCallback((menuItems: MenuItem[]): string => {
|
||||
return menuItems
|
||||
.map((item) => {
|
||||
const childrenKeys = item.children?.map((c) => c.id).join(',') || '';
|
||||
return `${item.id}:${childrenKeys}`;
|
||||
})
|
||||
.join('|');
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
const newOrderKey = getOrderKey(items);
|
||||
const newDataKey = getDataKey(items);
|
||||
|
||||
if (isPendingRef.current) {
|
||||
const localOrderKey = getOrderKey(localItems);
|
||||
if (newOrderKey === localOrderKey || newOrderKey !== prevOrderKeyRef.current) {
|
||||
isPendingRef.current = false;
|
||||
prevOrderKeyRef.current = newOrderKey;
|
||||
prevDataKeyRef.current = newDataKey;
|
||||
if (newOrderKey !== localOrderKey || newDataKey !== getDataKey(localItems)) {
|
||||
setLocalItems(items);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (newDataKey !== prevDataKeyRef.current) {
|
||||
prevOrderKeyRef.current = newOrderKey;
|
||||
prevDataKeyRef.current = newDataKey;
|
||||
setLocalItems(items);
|
||||
}
|
||||
}, [items, getOrderKey, getDataKey, localItems]);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: { distance: 8 },
|
||||
}),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
})
|
||||
);
|
||||
|
||||
const getMenuLabel = useCallback((name: string | Record<string, string>): string => {
|
||||
if (typeof name === 'string') return name;
|
||||
const g7Core = getG7Core();
|
||||
const locale = g7Core?.locale?.current?.() || 'ko';
|
||||
return name[locale] || name.en || Object.values(name)[0] || '';
|
||||
}, []);
|
||||
|
||||
const toggleExpand = useCallback((itemId: number) => {
|
||||
setExpandedItems((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(itemId)) {
|
||||
newSet.delete(itemId);
|
||||
} else {
|
||||
newSet.add(itemId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleItemClick = useCallback((item: MenuItem) => {
|
||||
onSelect?.(item);
|
||||
}, [onSelect]);
|
||||
|
||||
const handleToggleStatus = useCallback((id: number, currentStatus: boolean, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
onToggleStatus?.(id, currentStatus);
|
||||
}, [onToggleStatus]);
|
||||
|
||||
const handleDragStart = (event: DragStartEvent) => {
|
||||
setActiveId(event.active.id);
|
||||
};
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
setActiveId(null);
|
||||
|
||||
if (!over || active.id === over.id) return;
|
||||
|
||||
const activeFlat = flatItems.find((f) => f.item.id === Number(active.id));
|
||||
const overFlat = flatItems.find((f) => f.item.id === Number(over.id));
|
||||
|
||||
if (!activeFlat || !overFlat) return;
|
||||
|
||||
if (activeFlat.parentId === overFlat.parentId) {
|
||||
// 같은 부모 내 순서 변경
|
||||
const newItems = reorderInParent(localItems, activeFlat.parentId, Number(active.id), Number(over.id));
|
||||
setLocalItems(newItems);
|
||||
isPendingRef.current = true;
|
||||
onOrderChange?.(generateOrderData(newItems));
|
||||
} else {
|
||||
// 크로스 depth 이동
|
||||
const activeItem = activeFlat.item;
|
||||
|
||||
// 순환 참조 방지: active를 over의 자손 아래로 이동 차단
|
||||
const descendantIds = collectDescendantIds(activeItem);
|
||||
if (descendantIds.includes(Number(over.id))) return;
|
||||
|
||||
// 1) 트리에서 active 제거
|
||||
let newItems = removeItemFromTree(localItems, activeItem.id);
|
||||
|
||||
// 2) 드래그 방향 판단: flat 배열에서 active가 over보다 아래에 있으면 위로 드래그 중
|
||||
const activeIndex = flatItems.findIndex((f) => f.item.id === Number(active.id));
|
||||
const overIndex = flatItems.findIndex((f) => f.item.id === Number(over.id));
|
||||
const isDraggingUp = activeIndex > overIndex;
|
||||
|
||||
// 3) over가 속한 부모의 자식 목록에서 over의 위치를 찾아 삽입
|
||||
// 위로 드래그 → over 앞에 삽입, 아래로 드래그 → over 뒤에 삽입
|
||||
const overParentId = overFlat.parentId;
|
||||
let insertIndex: number;
|
||||
if (overParentId === null) {
|
||||
insertIndex = newItems.findIndex((i) => i.id === Number(over.id));
|
||||
if (insertIndex === -1) insertIndex = newItems.length;
|
||||
else if (!isDraggingUp) insertIndex += 1;
|
||||
} else {
|
||||
const overParent = findItemById(newItems, overParentId);
|
||||
const siblings = overParent?.children || [];
|
||||
insertIndex = siblings.findIndex((c) => c.id === Number(over.id));
|
||||
if (insertIndex === -1) insertIndex = siblings.length;
|
||||
else if (!isDraggingUp) insertIndex += 1;
|
||||
}
|
||||
|
||||
const movedItem: MenuItem = {
|
||||
...activeItem,
|
||||
parent_id: overParentId,
|
||||
children: activeItem.children || [],
|
||||
};
|
||||
newItems = insertItemIntoParent(newItems, movedItem, overParentId, insertIndex);
|
||||
|
||||
setLocalItems(newItems);
|
||||
isPendingRef.current = true;
|
||||
const orderData = generateOrderData(newItems);
|
||||
orderData.moved_items = [{ id: activeItem.id, new_parent_id: overParentId }];
|
||||
onOrderChange?.(orderData);
|
||||
}
|
||||
};
|
||||
|
||||
const toMenuItemData = (item: MenuItem): MenuItemData => ({
|
||||
id: item.id,
|
||||
name: getMenuLabel(item.name),
|
||||
slug: item.slug,
|
||||
url: item.url,
|
||||
icon: item.icon,
|
||||
isActive: item.is_active,
|
||||
isModuleMenu: !!item.module_id,
|
||||
moduleName: item.module ? getMenuLabel(item.module.name) : undefined,
|
||||
hasChildren: item.children && item.children.length > 0,
|
||||
});
|
||||
|
||||
// 트리를 평탄화 — 단일 SortableContext 사용
|
||||
const flatItems = useMemo(
|
||||
() => flattenTree(localItems, expandedItems),
|
||||
[localItems, expandedItems]
|
||||
);
|
||||
|
||||
const sortableIds = useMemo(
|
||||
() => flatItems.map((f) => f.item.id),
|
||||
[flatItems]
|
||||
);
|
||||
|
||||
const activeItem = activeId ? findItemById(localItems, Number(activeId)) : null;
|
||||
|
||||
return (
|
||||
<Div className={className}>
|
||||
{title && (
|
||||
<Div className={titleClassName}>
|
||||
<H3 className="text-sm font-medium text-gray-900 dark:text-white">{title}</H3>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
|
||||
<Div className={listClassName}>
|
||||
{flatItems.map((flatItem) => (
|
||||
<Div
|
||||
key={flatItem.item.id}
|
||||
className={flatItem.depth > 0 ? childrenContainerClassName : ''}
|
||||
>
|
||||
<SortableMenuItem
|
||||
item={toMenuItemData(flatItem.item)}
|
||||
isSelected={selectedId === flatItem.item.id}
|
||||
isExpanded={expandedItems.has(flatItem.item.id)}
|
||||
level={flatItem.depth}
|
||||
onClick={() => handleItemClick(flatItem.item)}
|
||||
onToggle={(e) => handleToggleStatus(flatItem.item.id, flatItem.item.is_active, e)}
|
||||
onExpandToggle={() => toggleExpand(flatItem.item.id)}
|
||||
className={itemClassName}
|
||||
selectedClassName={itemSelectedClassName}
|
||||
defaultClassName={itemDefaultClassName}
|
||||
enableDrag={enableDrag}
|
||||
toggleDisabled={toggleDisabled}
|
||||
/>
|
||||
</Div>
|
||||
))}
|
||||
</Div>
|
||||
</SortableContext>
|
||||
|
||||
<DragOverlay>
|
||||
{activeItem ? (
|
||||
<Div className="bg-white dark:bg-gray-800 shadow-lg rounded-lg border border-blue-500 p-3">
|
||||
<Div className="flex items-center gap-2">
|
||||
<Div className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{getMenuLabel(activeItem.name)}
|
||||
</Div>
|
||||
</Div>
|
||||
</Div>
|
||||
) : null}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { H3 } from '../basic/H3';
|
||||
import { Span } from '../basic/Span';
|
||||
import { P } from '../basic/P';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export interface StatCardProps {
|
||||
value: string | number;
|
||||
label: string;
|
||||
change?: number;
|
||||
changeLabel?: string;
|
||||
iconName?: IconName;
|
||||
trend?: 'up' | 'down' | 'neutral';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* StatCard 집합 컴포넌트
|
||||
*
|
||||
* 통계 수치와 변화율을 시각화하는 카드 컴포넌트입니다.
|
||||
* 수치, 라벨, 변화율(증가/감소), 아이콘을 표시합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Div + H3 + Span + P + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "StatCard",
|
||||
* "props": {
|
||||
* "value": 12345,
|
||||
* "label": "총 사용자",
|
||||
* "change": 12.5,
|
||||
* "changeLabel": "지난달 대비",
|
||||
* "iconName": "users",
|
||||
* "trend": "up"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const StatCard: React.FC<StatCardProps> = ({
|
||||
value,
|
||||
label,
|
||||
change,
|
||||
changeLabel = '전월 대비',
|
||||
iconName,
|
||||
trend = 'neutral',
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
const isPositive = trend === 'up';
|
||||
const isNegative = trend === 'down';
|
||||
const changeValue = change !== undefined ? Math.abs(change) : 0;
|
||||
|
||||
const trendColor = isPositive
|
||||
? 'text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/20'
|
||||
: isNegative
|
||||
? 'text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20'
|
||||
: 'text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-gray-700';
|
||||
|
||||
const trendIcon = isPositive ? IconName.ArrowUp : isNegative ? IconName.ArrowDown : undefined;
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`rounded-lg bg-white dark:bg-gray-800 shadow-md hover:shadow-lg transition-shadow border border-gray-200 dark:border-gray-700 p-6 ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{/* 헤더: 아이콘과 변화율 */}
|
||||
<Div className="flex items-center justify-between mb-4">
|
||||
{iconName && (
|
||||
<Div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
|
||||
<Icon name={iconName} className="w-6 h-6 text-blue-600 dark:text-blue-400" />
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{change !== undefined && (
|
||||
<Div className={`flex items-center gap-1 px-2 py-1 rounded-md ${trendColor}`}>
|
||||
{trendIcon && (
|
||||
<Icon name={trendIcon} className="w-4 h-4" />
|
||||
)}
|
||||
<Span className="text-sm font-semibold">
|
||||
{changeValue}%
|
||||
</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 통계 수치 */}
|
||||
<H3 className="text-3xl font-bold text-gray-900 dark:text-white mb-1">
|
||||
{typeof value === 'number' ? value.toLocaleString() : value}
|
||||
</H3>
|
||||
|
||||
{/* 라벨 */}
|
||||
<P className="text-sm text-gray-600 dark:text-gray-400 mb-2">
|
||||
{label}
|
||||
</P>
|
||||
|
||||
{/* 변화율 설명 */}
|
||||
{change !== undefined && changeLabel && (
|
||||
<Div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<Span>
|
||||
{changeLabel}
|
||||
</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
import React from 'react';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
export type StatusType = 'success' | 'warning' | 'error' | 'info' | 'pending' | 'default';
|
||||
|
||||
export interface StatusBadgeProps {
|
||||
status: StatusType;
|
||||
label?: string;
|
||||
showIcon?: boolean;
|
||||
iconName?: IconName;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* StatusBadge 집합 컴포넌트
|
||||
*
|
||||
* 상태별 색상 매핑을 지원하는 뱃지 컴포넌트입니다.
|
||||
* 상태에 따라 색상과 아이콘이 자동으로 매핑됩니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Span + Icon
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "StatusBadge",
|
||||
* "props": {
|
||||
* "status": "success",
|
||||
* "label": "완료",
|
||||
* "showIcon": true
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const StatusBadge: React.FC<StatusBadgeProps> = ({
|
||||
status,
|
||||
label,
|
||||
showIcon = true,
|
||||
iconName,
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
// 상태별 스타일 매핑
|
||||
const statusStyles: Record<StatusType, string> = {
|
||||
success: 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800',
|
||||
warning: 'bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800',
|
||||
error: 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800',
|
||||
info: 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800',
|
||||
pending: 'bg-gray-50 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-200 dark:border-gray-600',
|
||||
default: 'bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-200 dark:border-gray-600',
|
||||
};
|
||||
|
||||
// 상태별 기본 아이콘 매핑
|
||||
const statusIcons: Record<StatusType, IconName> = {
|
||||
success: IconName.CheckCircle,
|
||||
warning: IconName.ExclamationTriangle,
|
||||
error: IconName.XCircle,
|
||||
info: IconName.InfoCircle,
|
||||
pending: IconName.Clock,
|
||||
default: IconName.QuestionCircle,
|
||||
};
|
||||
|
||||
// 상태별 기본 라벨 매핑
|
||||
const statusLabels: Record<StatusType, string> = {
|
||||
success: '성공',
|
||||
warning: '경고',
|
||||
error: '오류',
|
||||
info: '정보',
|
||||
pending: '대기 중',
|
||||
default: '기본',
|
||||
};
|
||||
|
||||
const displayIcon = iconName || statusIcons[status];
|
||||
const displayLabel = label || statusLabels[status];
|
||||
const styleClasses = statusStyles[status];
|
||||
|
||||
return (
|
||||
<Span
|
||||
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border ${styleClasses} ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{showIcon && (
|
||||
<Icon name={displayIcon} className="w-4 h-4" />
|
||||
)}
|
||||
<Span>{displayLabel}</Span>
|
||||
</Span>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
import React from 'react';
|
||||
import { Nav } from '../basic/Nav';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
export interface Tab {
|
||||
id: string | number;
|
||||
label: string;
|
||||
iconName?: IconName;
|
||||
disabled?: boolean;
|
||||
badge?: string | number;
|
||||
}
|
||||
|
||||
export interface TabNavigationProps {
|
||||
tabs: Tab[];
|
||||
activeTabId?: string | number;
|
||||
onTabChange?: (tabId: string | number) => void;
|
||||
variant?: 'default' | 'pills' | 'underline';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* TabNavigation 집합 컴포넌트
|
||||
*
|
||||
* 탭 네비게이션을 제공하는 컴포넌트입니다.
|
||||
* 여러 탭을 전환할 수 있으며, 아이콘과 뱃지를 지원합니다.
|
||||
*
|
||||
* **주의**: 이 컴포넌트는 순수 네비게이션 UI만 제공하며,
|
||||
* 실제 탭 컨텐츠는 부모 컴포넌트에서 activeTabId를 기반으로 조건부 렌더링해야 합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Nav + Button + Icon + Div + Span
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
* {
|
||||
* "name": "TabNavigation",
|
||||
* "props": {
|
||||
* "activeTabId": 1,
|
||||
* "tabs": [
|
||||
* {"id": 1, "label": "프로필", "iconName": "user"},
|
||||
* {"id": 2, "label": "설정", "iconName": "cog", "badge": 3}
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* // 부모 컴포넌트에서 컨텐츠 렌더링 예시:
|
||||
* const [activeTab, setActiveTab] = useState(1);
|
||||
* return (
|
||||
* <>
|
||||
* <TabNavigation tabs={tabs} activeTabId={activeTab} onTabChange={setActiveTab} />
|
||||
* {activeTab === 1 && <ProfileContent />}
|
||||
* {activeTab === 2 && <SettingsContent />}
|
||||
* </>
|
||||
* );
|
||||
*/
|
||||
export const TabNavigation: React.FC<TabNavigationProps> = ({
|
||||
tabs,
|
||||
activeTabId,
|
||||
onTabChange,
|
||||
variant = 'default',
|
||||
className = '',
|
||||
style,
|
||||
}) => {
|
||||
const handleTabClick = (tab: Tab) => {
|
||||
if (!tab.disabled && tab.id !== activeTabId) {
|
||||
onTabChange?.(tab.id);
|
||||
}
|
||||
};
|
||||
|
||||
const getTabClasses = (tab: Tab) => {
|
||||
const isActive = tab.id === activeTabId;
|
||||
const baseClasses = 'flex items-center gap-2 px-4 py-2 font-medium text-sm transition-all';
|
||||
|
||||
if (tab.disabled) {
|
||||
return `${baseClasses} opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-600`;
|
||||
}
|
||||
|
||||
switch (variant) {
|
||||
case 'pills':
|
||||
return isActive
|
||||
? `${baseClasses} bg-blue-600 dark:bg-blue-500 text-white rounded-lg`
|
||||
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg`;
|
||||
|
||||
case 'underline':
|
||||
return isActive
|
||||
? `${baseClasses} text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400`
|
||||
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 border-b-2 border-transparent hover:border-gray-300 dark:hover:border-gray-600`;
|
||||
|
||||
case 'default':
|
||||
default:
|
||||
return isActive
|
||||
? `${baseClasses} text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 border-b-2 border-blue-600 dark:border-blue-400`
|
||||
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 border-b-2 border-transparent`;
|
||||
}
|
||||
};
|
||||
|
||||
const navClasses =
|
||||
variant === 'underline'
|
||||
? 'flex gap-0 border-b border-gray-200 dark:border-gray-700'
|
||||
: 'flex gap-2';
|
||||
|
||||
return (
|
||||
<Nav
|
||||
className={`${navClasses} ${className}`}
|
||||
style={style}
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<Button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
onClick={() => handleTabClick(tab)}
|
||||
disabled={tab.disabled}
|
||||
className={getTabClasses(tab)}
|
||||
>
|
||||
{tab.iconName && (
|
||||
<Icon name={tab.iconName} className="w-4 h-4" />
|
||||
)}
|
||||
|
||||
<Span>{tab.label}</Span>
|
||||
|
||||
{tab.badge !== undefined && (
|
||||
<Div className="flex items-center justify-center min-w-[20px] h-5 px-1.5 bg-red-500 text-white text-xs font-bold rounded-full">
|
||||
<Span>{tab.badge}</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Nav>
|
||||
);
|
||||
};
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Select } from '../basic/Select';
|
||||
import { scrollToSectionHandler } from '../../handlers/scrollToSectionHandler';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:TabNavigation')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:TabNavigation]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:TabNavigation]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:TabNavigation]', ...args),
|
||||
};
|
||||
|
||||
/**
|
||||
* 탭 정의 인터페이스
|
||||
*/
|
||||
export interface Tab {
|
||||
id: string | number;
|
||||
label: string;
|
||||
/** 탭 아이콘 (Font Awesome 아이콘명) */
|
||||
iconName?: IconName;
|
||||
disabled?: boolean;
|
||||
/** 개별 탭의 스크롤 오프셋 (우선순위: 개별 > 공통 > 기본값) */
|
||||
scrollOffset?: number;
|
||||
/** 개별 탭의 스크롤 딜레이 (우선순위: 개별 > 공통 > 기본값) */
|
||||
scrollDelay?: number;
|
||||
/** 개별 탭 클릭 시 실행될 콜백 (우선순위: 개별 > 공통 > 기본) */
|
||||
onClick?: (tabId: string | number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* TabNavigationScroll Props
|
||||
*/
|
||||
export interface TabNavigationScrollProps {
|
||||
/** 탭 목록 */
|
||||
tabs: Tab[];
|
||||
/** 활성 탭 ID (초기값으로만 사용) */
|
||||
activeTabId?: string | number;
|
||||
/** 컨테이너 className */
|
||||
className?: string;
|
||||
/** 컨테이너 스타일 */
|
||||
style?: React.CSSProperties;
|
||||
/** Active 탭 className */
|
||||
activeClassName?: string;
|
||||
/** Inactive 탭 className */
|
||||
inactiveClassName?: string;
|
||||
/** 섹션 ID 접두사 */
|
||||
sectionIdPrefix?: string;
|
||||
/** 스크롤 오프셋 */
|
||||
scrollOffset?: number;
|
||||
/** 스크롤 딜레이 */
|
||||
scrollDelay?: number;
|
||||
/** 탭 변경 시 실행될 공통 콜백 (우선순위: 개별 탭 onClick > onTabChange > 기본) */
|
||||
onTabChange?: (tabId: string | number) => void;
|
||||
/** Scroll Spy 활성화 여부 (스크롤 시 자동으로 탭 활성화) */
|
||||
enableScrollSpy?: boolean;
|
||||
/** Scroll Spy 감지 오프셋 (기본값: 80) */
|
||||
scrollSpyOffset?: number;
|
||||
/** 스크롤 컨테이너 ID (IntersectionObserver root 및 scrollToSection 대상, 미지정 시 window) */
|
||||
scrollContainerId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 탭 네비게이션 컴포넌트 (자동 스크롤 기능 내장)
|
||||
*
|
||||
* 특징:
|
||||
* - 내부 상태로 활성 탭 관리 (React useState)
|
||||
* - scrollToSectionHandler를 사용하여 자동 스크롤
|
||||
* - 탭 클릭 시 즉시 UI 업데이트 + 스크롤 이동
|
||||
*
|
||||
* @example
|
||||
* ```json
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "TabNavigationScroll",
|
||||
* "props": {
|
||||
* "tabs": [
|
||||
* {"id": "basic", "label": "$t:admin.tabs.basic"},
|
||||
* {"id": "permissions", "label": "$t:admin.tabs.permissions"}
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export const TabNavigationScroll: React.FC<TabNavigationScrollProps> = ({
|
||||
tabs,
|
||||
activeTabId,
|
||||
className = 'bg-white dark:bg-gray-800 flex gap-1 border-b border-gray-200 dark:border-gray-700 px-6',
|
||||
style,
|
||||
activeClassName = 'flex items-center gap-2 px-3 py-2 border-b-2 border-blue-500 bg-white dark:bg-gray-800 text-blue-600 dark:text-blue-400 font-medium -mb-px text-sm',
|
||||
inactiveClassName = 'flex items-center gap-2 px-3 py-2 border-b-2 border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:border-gray-300 dark:hover:border-gray-600 text-sm',
|
||||
sectionIdPrefix = 'tab_content_',
|
||||
scrollOffset = 120,
|
||||
scrollDelay = 100,
|
||||
onTabChange,
|
||||
enableScrollSpy = false,
|
||||
scrollSpyOffset = 80,
|
||||
scrollContainerId,
|
||||
}) => {
|
||||
const [activeTab, setActiveTab] = useState<string | number>(
|
||||
activeTabId ?? (tabs.length > 0 ? tabs[0].id : '')
|
||||
);
|
||||
|
||||
// Scroll Spy 일시 중지를 위한 ref
|
||||
const isScrollingRef = useRef(false);
|
||||
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
/**
|
||||
* 탭 클릭 핸들러
|
||||
* 우선순위: 개별 탭 onClick > 공통 onTabChange > 기본 동작
|
||||
*/
|
||||
const handleTabClick = (tab: Tab) => {
|
||||
// Scroll Spy 일시 중지
|
||||
if (enableScrollSpy) {
|
||||
isScrollingRef.current = true;
|
||||
if (scrollTimeoutRef.current) {
|
||||
clearTimeout(scrollTimeoutRef.current);
|
||||
}
|
||||
}
|
||||
|
||||
// 우선순위 1: 개별 탭의 onClick이 있으면 실행
|
||||
if (tab.onClick) {
|
||||
tab.onClick(tab.id);
|
||||
// enableScrollSpy가 아니면 onClick에 전적으로 위임
|
||||
if (!enableScrollSpy) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 우선순위 2: 공통 onTabChange가 있으면 실행
|
||||
else if (onTabChange) {
|
||||
onTabChange(tab.id);
|
||||
// enableScrollSpy가 아니면 onTabChange에 전적으로 위임
|
||||
if (!enableScrollSpy) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 우선순위 3: 콜백이 없으면 내부 상태 업데이트
|
||||
else {
|
||||
setActiveTab(tab.id);
|
||||
}
|
||||
|
||||
// 개별 탭 설정 우선, 없으면 공통 설정 사용
|
||||
const finalOffset = tab.scrollOffset ?? scrollOffset;
|
||||
const finalDelay = tab.scrollDelay ?? scrollDelay;
|
||||
|
||||
scrollToSectionHandler(
|
||||
{
|
||||
params: {
|
||||
targetId: `${sectionIdPrefix}${tab.id}`,
|
||||
offset: finalOffset,
|
||||
delay: finalDelay,
|
||||
scrollContainerId,
|
||||
},
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
// 스크롤 완료 후 Scroll Spy 재활성화 (딜레이 + 애니메이션 시간 고려)
|
||||
if (enableScrollSpy) {
|
||||
scrollTimeoutRef.current = setTimeout(() => {
|
||||
isScrollingRef.current = false;
|
||||
}, finalDelay + 500);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Scroll Spy 구현 (IntersectionObserver 사용)
|
||||
*
|
||||
* 짧은 섹션과 긴 섹션이 혼재된 경우를 고려한 알고리즘:
|
||||
* - 여러 섹션이 동시에 보일 경우, 가장 많이 보이는 섹션을 활성화
|
||||
* - intersectionRatio를 비교하여 최적의 섹션 선택
|
||||
* - 스크롤이 페이지 하단에 도달하면 마지막 탭 활성화 (짧은 마지막 섹션 대응)
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!enableScrollSpy) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rootElement = scrollContainerId
|
||||
? document.getElementById(scrollContainerId)
|
||||
: null;
|
||||
|
||||
const observerOptions = {
|
||||
root: rootElement ?? null,
|
||||
// 상단 오프셋 + 하단 30% 여유 공간 (짧은 섹션도 감지 가능)
|
||||
rootMargin: `-${scrollSpyOffset}px 0px -30% 0px`,
|
||||
// 0.1 단위로 교차 비율 감지 (더 정밀한 감지)
|
||||
threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
|
||||
};
|
||||
|
||||
// 현재 보이는 섹션들의 교차 비율을 저장
|
||||
const intersectingEntries = new Map<string, number>();
|
||||
|
||||
// 페이지 하단 도달 확인 헬퍼 함수 (scrollContainer 기준)
|
||||
const isAtBottom = () => {
|
||||
const container = rootElement;
|
||||
const scrollTop = container
|
||||
? container.scrollTop
|
||||
: window.pageYOffset || document.documentElement.scrollTop;
|
||||
const scrollHeight = container
|
||||
? container.scrollHeight
|
||||
: document.documentElement.scrollHeight;
|
||||
const clientHeight = container
|
||||
? container.clientHeight
|
||||
: document.documentElement.clientHeight;
|
||||
// 10px 여유를 두고 하단 체크 (정확한 하단 감지)
|
||||
const atBottom = scrollTop + clientHeight >= scrollHeight - 10;
|
||||
|
||||
// 디버깅 로그 (개발 환경에서만)
|
||||
if (process.env.NODE_ENV === 'development' && atBottom) {
|
||||
logger.log('Bottom reached:', {
|
||||
scrollTop,
|
||||
clientHeight,
|
||||
scrollHeight,
|
||||
remaining: scrollHeight - (scrollTop + clientHeight),
|
||||
});
|
||||
}
|
||||
|
||||
return atBottom;
|
||||
};
|
||||
|
||||
const observerCallback = (entries: IntersectionObserverEntry[]) => {
|
||||
// 수동 스크롤 중에는 Scroll Spy 비활성화
|
||||
if (isScrollingRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 교차 비율 업데이트
|
||||
entries.forEach((entry) => {
|
||||
const targetId = entry.target.id;
|
||||
if (entry.isIntersecting) {
|
||||
intersectingEntries.set(targetId, entry.intersectionRatio);
|
||||
} else {
|
||||
intersectingEntries.delete(targetId);
|
||||
}
|
||||
});
|
||||
|
||||
// 가장 많이 보이는 섹션 찾기
|
||||
let maxRatio = 0;
|
||||
let mostVisibleId = '';
|
||||
|
||||
intersectingEntries.forEach((ratio, id) => {
|
||||
if (ratio > maxRatio) {
|
||||
maxRatio = ratio;
|
||||
mostVisibleId = id;
|
||||
}
|
||||
});
|
||||
|
||||
// 하단 도달 시 마지막 탭 활성화 (단, 마지막 섹션이 실제로 보이고 있을 때만)
|
||||
const lastTab = tabs[tabs.length - 1];
|
||||
const lastSectionId = `${sectionIdPrefix}${lastTab?.id}`;
|
||||
const isLastSectionVisible = intersectingEntries.has(lastSectionId);
|
||||
|
||||
if (isAtBottom() && isLastSectionVisible && lastTab) {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
logger.log('Activating last tab (bottom reached + last section visible):', lastTab.id);
|
||||
}
|
||||
setActiveTab(lastTab.id);
|
||||
return;
|
||||
}
|
||||
|
||||
// 가장 많이 보이는 섹션의 탭 활성화
|
||||
if (mostVisibleId) {
|
||||
const tabId = mostVisibleId.replace(sectionIdPrefix, '');
|
||||
const numericTabId = Number(tabId);
|
||||
const finalTabId = isNaN(numericTabId) ? tabId : numericTabId;
|
||||
|
||||
const tabExists = tabs.some((tab) => tab.id === finalTabId);
|
||||
if (tabExists) {
|
||||
setActiveTab(finalTabId);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 스크롤 이벤트 핸들러 (현재는 IntersectionObserver가 모든 처리를 담당)
|
||||
const handleScroll = () => {
|
||||
// IntersectionObserver가 모든 탭 활성화를 처리하므로 여기서는 추가 동작 없음
|
||||
// 향후 필요시 추가 로직 구현 가능
|
||||
};
|
||||
|
||||
const observer = new IntersectionObserver(observerCallback, observerOptions);
|
||||
|
||||
// 모든 섹션 관찰 시작
|
||||
tabs.forEach((tab) => {
|
||||
const sectionElement = document.getElementById(`${sectionIdPrefix}${tab.id}`);
|
||||
if (sectionElement) {
|
||||
observer.observe(sectionElement);
|
||||
}
|
||||
});
|
||||
|
||||
// 스크롤 이벤트 리스너 등록
|
||||
window.addEventListener('scroll', handleScroll, { passive: true });
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
window.removeEventListener('scroll', handleScroll);
|
||||
if (scrollTimeoutRef.current) {
|
||||
clearTimeout(scrollTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, [enableScrollSpy, tabs, sectionIdPrefix, scrollSpyOffset, scrollContainerId]);
|
||||
|
||||
/**
|
||||
* Select 변경 핸들러 (모바일용)
|
||||
*/
|
||||
const handleSelectChange = (
|
||||
e: React.ChangeEvent<HTMLSelectElement> | { target: { value: string | number } }
|
||||
) => {
|
||||
const selectedId = e.target.value;
|
||||
// 숫자형 ID 변환
|
||||
const numericId = Number(selectedId);
|
||||
const finalId = isNaN(numericId) ? selectedId : numericId;
|
||||
|
||||
const selectedTab = tabs.find((tab) => tab.id === finalId);
|
||||
if (selectedTab) {
|
||||
handleTabClick(selectedTab);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 데스크톱: 탭 버튼 (md 이상) */}
|
||||
<Div className={`hidden md:flex ${className}`} style={style}>
|
||||
{tabs.map((tab) => (
|
||||
<Button
|
||||
key={tab.id}
|
||||
className={activeTab === tab.id ? activeClassName : inactiveClassName}
|
||||
disabled={tab.disabled}
|
||||
onClick={() => handleTabClick(tab)}
|
||||
>
|
||||
{tab.iconName && (
|
||||
<Icon name={tab.iconName} size="sm" />
|
||||
)}
|
||||
<Span>{tab.label}</Span>
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
|
||||
{/* 모바일: Select 박스 (md 미만) */}
|
||||
<Div className="md:hidden bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
|
||||
<Select
|
||||
value={String(activeTab)}
|
||||
onChange={handleSelectChange}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<option key={tab.id} value={String(tab.id)} disabled={tab.disabled}>
|
||||
{tab.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,649 @@
|
||||
import React, { useCallback, useMemo, useState, useEffect, useRef } from 'react';
|
||||
import Select, { components, MultiValue, SingleValue, ActionMeta, InputActionMeta } from 'react-select';
|
||||
import CreatableSelect from 'react-select/creatable';
|
||||
|
||||
export interface TagOption {
|
||||
value: string | number;
|
||||
label: string;
|
||||
count?: number;
|
||||
isDisabled?: boolean;
|
||||
/** 그룹명 (드롭다운에서 그룹 헤더로 표시) */
|
||||
group?: string;
|
||||
/** 상세 설명 (옵션 아래에 작은 글씨로 표시) */
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface GroupedOption {
|
||||
label: string;
|
||||
options: TagOption[];
|
||||
}
|
||||
|
||||
export type TagVariant = 'blue' | 'green' | 'amber' | 'red' | 'purple' | 'gray';
|
||||
|
||||
export interface TagInputProps {
|
||||
/** 선택된 값 (멀티: 배열, 싱글: 단일 값 또는 배열) */
|
||||
value: (string | number)[] | string | number | null;
|
||||
/** 선택 가능한 옵션 목록 */
|
||||
options?: TagOption[];
|
||||
/** 값 변경 콜백 (이벤트 객체 또는 배열) */
|
||||
onChange: ((event: any) => void) | ((values: (string | number)[] | string | number | null) => void);
|
||||
/** 새 항목 추가 가능 여부 */
|
||||
creatable?: boolean;
|
||||
/** 입력창 placeholder */
|
||||
placeholder?: string;
|
||||
/** 검색 결과 없을 때 메시지 */
|
||||
noOptionsMessage?: string;
|
||||
/** 새 항목 추가 라벨 (문자열 또는 생성 함수) */
|
||||
formatCreateLabel?: string | ((inputValue: string) => string);
|
||||
/** 새 항목 추가 접미사 (기본값: "추가") */
|
||||
createLabelSuffix?: string;
|
||||
/** 최대 선택 개수 (멀티 모드에서만 유효) */
|
||||
maxItems?: number;
|
||||
/** 비활성화 여부 (boolean 또는 문자열 "true"/"false") */
|
||||
disabled?: boolean | string;
|
||||
/** 삭제 전 확인 콜백 (true: 허용, string: 불가 + 메시지) */
|
||||
onBeforeRemove?: (option: TagOption) => boolean | string;
|
||||
/** 새 옵션 생성 시 콜백 */
|
||||
onCreateOption?: (inputValue: string) => void;
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
/** 태그 값별 variant 맵핑 */
|
||||
tagVariants?: Record<string | number, TagVariant>;
|
||||
/** 기본 variant (지정되지 않은 태그) */
|
||||
defaultVariant?: TagVariant;
|
||||
/** 폼 필드 이름 (템플릿 엔진용) */
|
||||
name?: string;
|
||||
/** 다중 선택 여부 (기본값: true) */
|
||||
isMulti?: boolean;
|
||||
/** 선택 해제 가능 여부 (싱글 모드에서 유효, 기본값: true) */
|
||||
isClearable?: boolean;
|
||||
/** 검색 가능 여부 (기본값: true) */
|
||||
isSearchable?: boolean;
|
||||
/** 태그 구분자 배열 (creatable 모드에서 입력 시 자동 분리, 기본값: [',']) */
|
||||
delimiters?: string[];
|
||||
/** 붙여넣기 시 자동 분리 여부 (기본값: true) */
|
||||
splitOnPaste?: boolean;
|
||||
/** 검색 입력 변경 콜백 (비동기 검색용, 매 키 입력 시 호출) */
|
||||
onInputChange?: (event: any) => void;
|
||||
}
|
||||
|
||||
// Tailwind 스타일 클래스 상수
|
||||
const STYLES = {
|
||||
control: 'px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus-within:outline-none focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500',
|
||||
valueContainer: 'gap-1 flex flex-wrap',
|
||||
multiValue: {
|
||||
blue: 'bg-blue-100 dark:bg-blue-900/20 rounded px-1.5 py-0.5 flex items-center gap-1',
|
||||
green: 'bg-green-100 dark:bg-green-900/20 rounded px-1.5 py-0.5 flex items-center gap-1',
|
||||
amber: 'bg-amber-100 dark:bg-amber-900/20 rounded px-1.5 py-0.5 flex items-center gap-1',
|
||||
red: 'bg-red-100 dark:bg-red-900/20 rounded px-1.5 py-0.5 flex items-center gap-1',
|
||||
purple: 'bg-purple-100 dark:bg-purple-900/20 rounded px-1.5 py-0.5 flex items-center gap-1',
|
||||
gray: 'bg-gray-100 dark:bg-gray-700/50 rounded px-1.5 py-0.5 flex items-center gap-1',
|
||||
},
|
||||
multiValueLabel: {
|
||||
blue: 'text-blue-700 dark:text-blue-300 text-xs',
|
||||
green: 'text-green-700 dark:text-green-300 text-xs font-semibold',
|
||||
amber: 'text-amber-700 dark:text-amber-300 text-xs font-semibold',
|
||||
red: 'text-red-700 dark:text-red-300 text-xs font-semibold',
|
||||
purple: 'text-purple-700 dark:text-purple-300 text-xs font-semibold',
|
||||
gray: 'text-gray-700 dark:text-gray-300 text-xs',
|
||||
},
|
||||
multiValueRemove: {
|
||||
blue: 'text-blue-700 dark:text-blue-300 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 rounded px-1',
|
||||
green: 'text-green-700 dark:text-green-300 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 rounded px-1',
|
||||
amber: 'text-amber-700 dark:text-amber-300 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 rounded px-1',
|
||||
red: 'text-red-700 dark:text-red-300 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 rounded px-1',
|
||||
purple: 'text-purple-700 dark:text-purple-300 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 rounded px-1',
|
||||
gray: 'text-gray-700 dark:text-gray-300 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 rounded px-1',
|
||||
},
|
||||
input: 'text-gray-900 dark:text-white text-sm',
|
||||
placeholder: 'text-gray-400 dark:text-gray-500 text-sm',
|
||||
menu: 'mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg',
|
||||
menuList: 'py-1',
|
||||
option: {
|
||||
base: 'px-3 py-2 cursor-pointer text-gray-900 dark:text-white text-[13px]',
|
||||
selected: 'bg-blue-100 dark:bg-blue-900/20',
|
||||
focused: 'bg-gray-100 dark:bg-gray-700',
|
||||
default: 'bg-white dark:bg-gray-800',
|
||||
},
|
||||
noOptionsMessage: 'px-3 py-2 text-gray-500 dark:text-gray-400 text-[13px]',
|
||||
checkbox: {
|
||||
base: 'w-4 h-4 rounded border flex items-center justify-center text-white text-[10px] shrink-0',
|
||||
selected: 'bg-blue-500 border-blue-500',
|
||||
unselected: 'border-gray-400 dark:border-gray-500',
|
||||
},
|
||||
} as const;
|
||||
|
||||
// 옵션 컴포넌트 (체크박스 스타일 + description 지원)
|
||||
const CustomOption = (props: any) => {
|
||||
const { data, isSelected } = props;
|
||||
return (
|
||||
<components.Option {...props}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`${STYLES.checkbox.base} ${isSelected ? STYLES.checkbox.selected : STYLES.checkbox.unselected}`}>
|
||||
{isSelected ? '✓' : ''}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-[13px]">{data.label}</span>
|
||||
{data.count !== undefined && data.count > 0 && (
|
||||
<span className="text-gray-500 dark:text-gray-400 text-[10px]">({data.count})</span>
|
||||
)}
|
||||
</div>
|
||||
{data.description && (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 truncate">{data.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</components.Option>
|
||||
);
|
||||
};
|
||||
|
||||
// 그룹 헤더 컴포넌트
|
||||
const GroupHeading = (props: any) => {
|
||||
return (
|
||||
<components.GroupHeading {...props}>
|
||||
<div className="px-3 py-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700">
|
||||
{props.data.label}
|
||||
</div>
|
||||
</components.GroupHeading>
|
||||
);
|
||||
};
|
||||
|
||||
// 다중 값 라벨 컴포넌트 (count 표시)
|
||||
const CustomMultiValueLabel = (props: any) => {
|
||||
const { data } = props;
|
||||
return (
|
||||
<components.MultiValueLabel {...props}>
|
||||
<span>{data.label}</span>
|
||||
{data.count !== undefined && data.count > 0 && (
|
||||
<span className="text-xs opacity-60 ml-1">({data.count})</span>
|
||||
)}
|
||||
</components.MultiValueLabel>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 태그 입력 컴포넌트
|
||||
*
|
||||
* 다중 선택이 가능한 태그 입력 컴포넌트입니다.
|
||||
* isMulti=false로 설정하면 단일 선택 모드로 동작합니다.
|
||||
* creatable 모드에서는 새 항목 추가가 가능합니다.
|
||||
*/
|
||||
export const TagInput: React.FC<TagInputProps> = ({
|
||||
value: valueProp,
|
||||
options = [],
|
||||
onChange,
|
||||
creatable = false,
|
||||
placeholder = '검색 또는 입력...',
|
||||
noOptionsMessage = '검색 결과가 없습니다',
|
||||
formatCreateLabel,
|
||||
createLabelSuffix = '추가',
|
||||
maxItems,
|
||||
disabled: disabledProp = false,
|
||||
onBeforeRemove,
|
||||
onCreateOption,
|
||||
className = '',
|
||||
tagVariants,
|
||||
defaultVariant = 'blue',
|
||||
name,
|
||||
isMulti = true,
|
||||
isClearable = true,
|
||||
isSearchable = true,
|
||||
delimiters = [','],
|
||||
splitOnPaste = true,
|
||||
onInputChange: onInputChangeProp,
|
||||
}) => {
|
||||
// disabled prop을 boolean으로 정규화 (문자열 "true"/"false" 처리)
|
||||
const disabled = disabledProp === true || disabledProp === 'true';
|
||||
|
||||
// valueProp을 내부 배열 형태로 정규화
|
||||
const normalizeValue = useCallback((val: typeof valueProp): (string | number)[] => {
|
||||
if (val === null || val === undefined) return [];
|
||||
if (Array.isArray(val)) return val;
|
||||
return [val];
|
||||
}, []);
|
||||
|
||||
// 내부 상태로 관리 (비제어 컴포넌트 패턴)
|
||||
const [value, setValue] = useState<(string | number)[]>(() => normalizeValue(valueProp));
|
||||
|
||||
// 입력값 상태 (구분자 감지를 위한 제어 컴포넌트)
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
|
||||
// 이전 valueProp 값을 추적하여 실제 값 변경만 감지
|
||||
const prevValueRef = useRef<(string | number)[] | undefined>(undefined);
|
||||
|
||||
// props 변경 시 내부 상태 동기화 (배열 내용 변경만 감지)
|
||||
useEffect(() => {
|
||||
// 배열 내용 비교 헬퍼 함수
|
||||
const arraysEqual = (a: (string | number)[] | undefined, b: (string | number)[] | undefined): boolean => {
|
||||
if (!a && !b) return true;
|
||||
if (!a || !b) return false;
|
||||
if (a.length !== b.length) return false;
|
||||
return a.every((val, idx) => val === b[idx]);
|
||||
};
|
||||
|
||||
const normalizedValue = normalizeValue(valueProp);
|
||||
// 실제 값이 변경된 경우에만 상태 업데이트
|
||||
if (!arraysEqual(normalizedValue, prevValueRef.current)) {
|
||||
setValue(normalizedValue);
|
||||
prevValueRef.current = normalizedValue;
|
||||
}
|
||||
}, [valueProp, normalizeValue]);
|
||||
|
||||
// formatCreateLabel을 함수로 정규화
|
||||
const createLabelFormatter = useMemo(() => {
|
||||
// 함수가 제공된 경우
|
||||
if (formatCreateLabel) {
|
||||
if (typeof formatCreateLabel === 'string') {
|
||||
return (inputValue: string) => `${formatCreateLabel} "${inputValue}"`;
|
||||
}
|
||||
return formatCreateLabel;
|
||||
}
|
||||
|
||||
// 기본 동작: createLabelSuffix 사용
|
||||
return (inputValue: string) => (
|
||||
<span className="text-[13px]">
|
||||
<strong>{inputValue}</strong> {createLabelSuffix}
|
||||
</span>
|
||||
);
|
||||
}, [formatCreateLabel, createLabelSuffix]);
|
||||
|
||||
// 선택된 값들을 TagOption 배열로 변환
|
||||
const selectedOptions = useMemo(() => {
|
||||
if (!value || !Array.isArray(value)) return [];
|
||||
|
||||
return value
|
||||
.map((v) => {
|
||||
const existingOption = options.find((opt) => opt.value === v);
|
||||
return existingOption || { value: v, label: String(v) };
|
||||
})
|
||||
.filter((opt): opt is TagOption => opt !== undefined);
|
||||
}, [value, options]);
|
||||
|
||||
// 드롭다운에 표시할 전체 옵션 (선택된 값 포함, 그룹 지원)
|
||||
const allOptions = useMemo(() => {
|
||||
const existingValues = new Set(options.map(opt => opt.value));
|
||||
const additionalOptions: TagOption[] = value
|
||||
? value
|
||||
.filter(v => !existingValues.has(v))
|
||||
.map(v => ({ value: v, label: String(v) }))
|
||||
: [];
|
||||
|
||||
const mergedOptions: TagOption[] = [...options, ...additionalOptions];
|
||||
|
||||
// 그룹이 있는 옵션이 하나라도 있으면 그룹화
|
||||
const hasGroups = mergedOptions.some(opt => opt.group);
|
||||
if (!hasGroups) {
|
||||
return mergedOptions;
|
||||
}
|
||||
|
||||
// 그룹별로 옵션 분류
|
||||
const groupMap = new Map<string, TagOption[]>();
|
||||
const ungroupedOptions: TagOption[] = [];
|
||||
|
||||
mergedOptions.forEach(opt => {
|
||||
if (opt.group) {
|
||||
const groupOptions = groupMap.get(opt.group) || [];
|
||||
groupOptions.push(opt);
|
||||
groupMap.set(opt.group, groupOptions);
|
||||
} else {
|
||||
ungroupedOptions.push(opt);
|
||||
}
|
||||
});
|
||||
|
||||
// 그룹화된 옵션 배열 생성
|
||||
const groupedOptions: GroupedOption[] = [];
|
||||
groupMap.forEach((groupOptions, groupLabel) => {
|
||||
groupedOptions.push({
|
||||
label: groupLabel,
|
||||
options: groupOptions,
|
||||
});
|
||||
});
|
||||
|
||||
// 그룹이 없는 옵션이 있으면 별도 그룹으로 추가
|
||||
if (ungroupedOptions.length > 0) {
|
||||
groupedOptions.push({
|
||||
label: '',
|
||||
options: ungroupedOptions,
|
||||
});
|
||||
}
|
||||
|
||||
return groupedOptions;
|
||||
}, [options, value]);
|
||||
|
||||
// 템플릿 엔진용 가짜 이벤트 생성 헬퍼
|
||||
const createFakeEvent = useCallback((outputValue: (string | number)[] | string | number | null) => ({
|
||||
target: { value: outputValue },
|
||||
currentTarget: { value: outputValue },
|
||||
preventDefault: () => {}, // ActionDispatcher의 isStandardEvent 체크를 통과하기 위해 필요
|
||||
stopPropagation: () => {},
|
||||
} as any), []);
|
||||
|
||||
// 구분자로 입력값 분리 함수
|
||||
const splitByDelimiters = useCallback((input: string): string[] => {
|
||||
if (!delimiters?.length) return [input.trim()].filter(Boolean);
|
||||
// 구분자를 정규식 패턴으로 변환 (특수문자 이스케이프)
|
||||
const escapedDelimiters = delimiters.map(d => d.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
||||
const pattern = new RegExp(`[${escapedDelimiters.join('')}]`);
|
||||
return input.split(pattern).map(s => s.trim()).filter(Boolean);
|
||||
}, [delimiters]);
|
||||
|
||||
// 입력 변경 핸들러 - 구분자 감지 시 태그 생성 + 외부 onInputChange 콜백
|
||||
const handleInputChange = useCallback((newValue: string, actionMeta: InputActionMeta) => {
|
||||
if (actionMeta.action !== 'input-change') {
|
||||
setInputValue(newValue);
|
||||
return;
|
||||
}
|
||||
|
||||
// 외부 onInputChange 콜백 호출 (비동기 검색용)
|
||||
if (onInputChangeProp) {
|
||||
onInputChangeProp(createFakeEvent(newValue));
|
||||
}
|
||||
|
||||
// 구분자 포함 여부 확인
|
||||
const hasDelimiter = delimiters?.some(d => newValue.includes(d));
|
||||
if (!hasDelimiter || !creatable || !isMulti) {
|
||||
setInputValue(newValue);
|
||||
return;
|
||||
}
|
||||
|
||||
// 구분자로 분리하여 태그 생성
|
||||
const parts = splitByDelimiters(newValue);
|
||||
const newTags = parts.filter(p => p && !value.includes(p));
|
||||
|
||||
if (newTags.length > 0) {
|
||||
// 최대 개수 제한 확인
|
||||
const availableSlots = maxItems ? maxItems - value.length : Infinity;
|
||||
const tagsToAdd = newTags.slice(0, availableSlots);
|
||||
|
||||
if (tagsToAdd.length > 0) {
|
||||
const newValues = [...value, ...tagsToAdd];
|
||||
setValue(newValues);
|
||||
onChange(createFakeEvent(newValues));
|
||||
}
|
||||
}
|
||||
setInputValue('');
|
||||
}, [delimiters, creatable, isMulti, splitByDelimiters, value, maxItems, onChange, createFakeEvent, onInputChangeProp]);
|
||||
|
||||
// 붙여넣기 핸들러
|
||||
const handlePaste = useCallback((e: React.ClipboardEvent) => {
|
||||
if (!splitOnPaste || !creatable || !isMulti) return;
|
||||
|
||||
const pastedText = e.clipboardData.getData('text');
|
||||
const parts = splitByDelimiters(pastedText);
|
||||
|
||||
// 여러 항목이 있을 때만 처리 (단일 항목은 기본 동작)
|
||||
if (parts.length <= 1) return;
|
||||
|
||||
e.preventDefault();
|
||||
const newTags = parts.filter(p => p && !value.includes(p));
|
||||
|
||||
if (newTags.length > 0) {
|
||||
// 최대 개수 제한 확인
|
||||
const availableSlots = maxItems ? maxItems - value.length : Infinity;
|
||||
const tagsToAdd = newTags.slice(0, availableSlots);
|
||||
|
||||
if (tagsToAdd.length > 0) {
|
||||
const newValues = [...value, ...tagsToAdd];
|
||||
setValue(newValues);
|
||||
onChange(createFakeEvent(newValues));
|
||||
}
|
||||
}
|
||||
}, [splitOnPaste, creatable, isMulti, splitByDelimiters, value, maxItems, onChange, createFakeEvent]);
|
||||
|
||||
// 변경 핸들러 (멀티 모드)
|
||||
const handleMultiChange = useCallback(
|
||||
(newValue: MultiValue<TagOption>, actionMeta: ActionMeta<TagOption>) => {
|
||||
// 삭제 작업 시 onBeforeRemove 검증
|
||||
if ((actionMeta.action === 'remove-value' || actionMeta.action === 'pop-value') && actionMeta.removedValue && onBeforeRemove) {
|
||||
const result = onBeforeRemove(actionMeta.removedValue);
|
||||
if (result !== true) {
|
||||
const message = typeof result === 'string' ? result : `"${actionMeta.removedValue.label}"은(는) 제거할 수 없습니다.`;
|
||||
alert(message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 최대 개수 제한
|
||||
if (maxItems && newValue.length > maxItems) return;
|
||||
|
||||
const newValues = newValue.map((opt) => opt.value);
|
||||
setValue(newValues);
|
||||
onChange(createFakeEvent(newValues));
|
||||
},
|
||||
[onChange, onBeforeRemove, maxItems, createFakeEvent]
|
||||
);
|
||||
|
||||
// 변경 핸들러 (싱글 모드)
|
||||
const handleSingleChange = useCallback(
|
||||
(newValue: SingleValue<TagOption>, actionMeta: ActionMeta<TagOption>) => {
|
||||
// 삭제 작업 시 onBeforeRemove 검증
|
||||
if (actionMeta.action === 'clear' && value.length > 0 && onBeforeRemove) {
|
||||
const currentOption = options.find(opt => opt.value === value[0]) || { value: value[0], label: String(value[0]) };
|
||||
const result = onBeforeRemove(currentOption);
|
||||
if (result !== true) {
|
||||
const message = typeof result === 'string' ? result : `"${currentOption.label}"은(는) 제거할 수 없습니다.`;
|
||||
alert(message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const outputValue = newValue ? newValue.value : null;
|
||||
const internalValue = newValue ? [newValue.value] : [];
|
||||
setValue(internalValue);
|
||||
onChange(createFakeEvent(outputValue));
|
||||
},
|
||||
[onChange, onBeforeRemove, value, options, createFakeEvent]
|
||||
);
|
||||
|
||||
// 새 옵션 생성 핸들러
|
||||
const handleCreate = useCallback(
|
||||
(inputValue: string) => {
|
||||
if (onCreateOption) onCreateOption(inputValue);
|
||||
|
||||
const newValues = [...(value || []), inputValue];
|
||||
setValue(newValues);
|
||||
onChange(createFakeEvent(newValues));
|
||||
},
|
||||
[onChange, onCreateOption, value, createFakeEvent]
|
||||
);
|
||||
|
||||
// 새 옵션 유효성 검사 (중복 방지)
|
||||
const isValidNewOption = useCallback(
|
||||
(inputValue: string) => {
|
||||
if (!inputValue || !inputValue.trim()) return false;
|
||||
return !value?.includes(inputValue.trim());
|
||||
},
|
||||
[value]
|
||||
);
|
||||
|
||||
// Enter/Tab 키 처리 (태그 생성 또는 잘못된 동작 방지)
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const currentInput = inputValue.trim();
|
||||
|
||||
// Tab 키: 현재 입력값으로 태그 생성 (creatable 모드)
|
||||
if (event.key === 'Tab' && creatable && isMulti && currentInput) {
|
||||
if (!value.includes(currentInput)) {
|
||||
// 최대 개수 제한 확인
|
||||
if (!maxItems || value.length < maxItems) {
|
||||
event.preventDefault();
|
||||
const newValues = [...value, currentInput];
|
||||
setValue(newValues);
|
||||
onChange(createFakeEvent(newValues));
|
||||
setInputValue('');
|
||||
}
|
||||
} else {
|
||||
// 중복 시 입력만 초기화
|
||||
event.preventDefault();
|
||||
setInputValue('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Enter 키: 빈 입력 또는 중복 값 방지
|
||||
if (event.key === 'Enter') {
|
||||
if (!currentInput || (value && value.includes(currentInput))) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
},
|
||||
[value, inputValue, creatable, isMulti, maxItems, onChange, createFakeEvent]
|
||||
);
|
||||
|
||||
// 태그 variant 가져오기 헬퍼
|
||||
const getTagVariant = useCallback(
|
||||
(tagValue: string | number): TagVariant => {
|
||||
if (tagVariants && tagVariants[tagValue]) {
|
||||
return tagVariants[tagValue];
|
||||
}
|
||||
return defaultVariant;
|
||||
},
|
||||
[tagVariants, defaultVariant]
|
||||
);
|
||||
|
||||
// react-select 공통 스타일 설정
|
||||
const commonClassNames = {
|
||||
control: () => `${STYLES.control} ${className} ${disabled ? 'opacity-60 bg-gray-100 dark:bg-gray-800 cursor-not-allowed' : ''}`,
|
||||
valueContainer: () => STYLES.valueContainer,
|
||||
multiValue: (state: any) => {
|
||||
const variant = getTagVariant(state.data.value);
|
||||
return STYLES.multiValue[variant];
|
||||
},
|
||||
multiValueLabel: (state: any) => {
|
||||
const variant = getTagVariant(state.data.value);
|
||||
return STYLES.multiValueLabel[variant];
|
||||
},
|
||||
multiValueRemove: (state: any) => {
|
||||
const variant = getTagVariant(state.data.value);
|
||||
return `${STYLES.multiValueRemove[variant]} ${disabled ? 'pointer-events-none' : ''}`;
|
||||
},
|
||||
singleValue: () => 'text-gray-900 dark:text-white text-sm',
|
||||
input: () => STYLES.input,
|
||||
placeholder: () => STYLES.placeholder,
|
||||
menu: () => STYLES.menu,
|
||||
menuList: () => STYLES.menuList,
|
||||
menuPortal: () => 'z-[9999]',
|
||||
option: (state: any) =>
|
||||
`${STYLES.option.base} ${
|
||||
state.isSelected
|
||||
? STYLES.option.selected
|
||||
: state.isFocused
|
||||
? STYLES.option.focused
|
||||
: STYLES.option.default
|
||||
}`,
|
||||
noOptionsMessage: () => STYLES.noOptionsMessage,
|
||||
clearIndicator: () => 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 cursor-pointer px-1',
|
||||
dropdownIndicator: () => 'text-gray-400 dark:text-gray-500 px-1',
|
||||
};
|
||||
|
||||
// 공통 props
|
||||
const baseProps = {
|
||||
options: allOptions,
|
||||
onKeyDown: handleKeyDown,
|
||||
placeholder,
|
||||
noOptionsMessage: () => noOptionsMessage,
|
||||
isDisabled: disabled,
|
||||
isSearchable,
|
||||
menuIsOpen: undefined,
|
||||
openMenuOnClick: true,
|
||||
openMenuOnFocus: true,
|
||||
// 드롭다운 메뉴를 body에 포탈로 렌더링하여 부모 컨테이너의 overflow에 의해 잘리지 않도록 함
|
||||
menuPortalTarget: typeof document !== 'undefined' ? document.body : null,
|
||||
menuPosition: 'fixed' as const,
|
||||
classNamePrefix: 'tag-input',
|
||||
unstyled: true,
|
||||
classNames: commonClassNames,
|
||||
// 구분자 기반 태그 분리 또는 외부 onInputChange 콜백이 있을 때 제어 컴포넌트 설정
|
||||
...((creatable && isMulti) || onInputChangeProp ? {
|
||||
inputValue,
|
||||
onInputChange: handleInputChange,
|
||||
} : {}),
|
||||
};
|
||||
|
||||
// hidden input 값 계산
|
||||
const hiddenValue = isMulti ? value.join(',') : (value[0] ?? '');
|
||||
|
||||
// 싱글 모드
|
||||
if (!isMulti) {
|
||||
const singleProps = {
|
||||
...baseProps,
|
||||
isMulti: false as const,
|
||||
value: selectedOptions[0] || null,
|
||||
onChange: handleSingleChange,
|
||||
isClearable,
|
||||
closeMenuOnSelect: true,
|
||||
components: {
|
||||
Option: CustomOption,
|
||||
GroupHeading,
|
||||
IndicatorSeparator: () => null,
|
||||
...(isClearable ? {} : { ClearIndicator: () => null }),
|
||||
},
|
||||
};
|
||||
|
||||
if (creatable) {
|
||||
return (
|
||||
<>
|
||||
{name && <input type="hidden" name={name} value={hiddenValue} />}
|
||||
<CreatableSelect<TagOption, false>
|
||||
{...singleProps}
|
||||
onCreateOption={handleCreate}
|
||||
formatCreateLabel={createLabelFormatter}
|
||||
isValidNewOption={isValidNewOption}
|
||||
createOptionPosition="first"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{name && <input type="hidden" name={name} value={hiddenValue} />}
|
||||
<Select<TagOption, false> {...singleProps} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// 멀티 모드
|
||||
const multiProps = {
|
||||
...baseProps,
|
||||
isMulti: true as const,
|
||||
value: selectedOptions,
|
||||
onChange: handleMultiChange,
|
||||
closeMenuOnSelect: false,
|
||||
hideSelectedOptions: false,
|
||||
backspaceRemovesValue: false,
|
||||
isClearable: false,
|
||||
components: {
|
||||
Option: CustomOption,
|
||||
GroupHeading,
|
||||
MultiValueLabel: CustomMultiValueLabel,
|
||||
ClearIndicator: () => null,
|
||||
DropdownIndicator: () => null,
|
||||
IndicatorSeparator: () => null,
|
||||
},
|
||||
};
|
||||
|
||||
if (creatable) {
|
||||
return (
|
||||
<div onPaste={handlePaste}>
|
||||
{name && <input type="hidden" name={name} value={hiddenValue} />}
|
||||
<CreatableSelect<TagOption, true>
|
||||
{...multiProps}
|
||||
onCreateOption={handleCreate}
|
||||
formatCreateLabel={createLabelFormatter}
|
||||
isValidNewOption={isValidNewOption}
|
||||
createOptionPosition="first"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{name && <input type="hidden" name={name} value={hiddenValue} />}
|
||||
<Select<TagOption, true> {...multiProps} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
import React, { useMemo, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Svg } from '../basic/Svg';
|
||||
|
||||
export interface TagSelectOption {
|
||||
value: string | number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface TagSelectProps {
|
||||
/** 선택 가능한 옵션 목록 (라벨 매핑용) */
|
||||
options?: TagSelectOption[];
|
||||
/** 선택된 값 배열 */
|
||||
value?: (string | number)[];
|
||||
/** 값 변경 핸들러 */
|
||||
onChange?: (value: (string | number)[]) => void;
|
||||
/** placeholder (선택된 항목 없을 때) */
|
||||
placeholder?: string;
|
||||
/** 비활성화 */
|
||||
disabled?: boolean;
|
||||
/** 추가 클래스 */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// CSS 클래스 상수 (ui-elements.css의 .tag 클래스 재사용)
|
||||
const STYLES = {
|
||||
container: {
|
||||
base: 'tag-select',
|
||||
disabled: 'opacity-50 cursor-not-allowed',
|
||||
},
|
||||
tag: 'tag', // ui-elements.css .tag 클래스 사용
|
||||
tagRemove: 'tag-remove', // ui-elements.css .tag-remove 클래스 사용
|
||||
placeholder: 'tag-select-placeholder',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 태그 선택 표시 컴포넌트
|
||||
*
|
||||
* 선택된 항목들을 태그(뱃지) 형태로 표시합니다.
|
||||
* 각 태그의 X 버튼으로 개별 삭제가 가능합니다.
|
||||
*/
|
||||
export const TagSelect: React.FC<TagSelectProps> = ({
|
||||
options = [],
|
||||
value = [],
|
||||
onChange,
|
||||
placeholder = 'No items selected',
|
||||
disabled = false,
|
||||
className = '',
|
||||
}) => {
|
||||
// 값으로 라벨 찾기
|
||||
const getLabel = useCallback(
|
||||
(val: string | number): string => {
|
||||
const option = options.find(opt => String(opt.value) === String(val));
|
||||
return option?.label || String(val);
|
||||
},
|
||||
[options]
|
||||
);
|
||||
|
||||
// 태그 제거 핸들러
|
||||
const handleRemove = useCallback(
|
||||
(valueToRemove: string | number) => {
|
||||
if (disabled) return;
|
||||
const newValues = value.filter(v => String(v) !== String(valueToRemove));
|
||||
onChange?.(newValues);
|
||||
},
|
||||
[value, onChange, disabled]
|
||||
);
|
||||
|
||||
// 선택된 값들을 옵션 정보와 함께 매핑
|
||||
const selectedItems = useMemo(() => {
|
||||
return value.map(v => ({
|
||||
value: v,
|
||||
label: getLabel(v),
|
||||
}));
|
||||
}, [value, getLabel]);
|
||||
|
||||
const containerClassName = `${STYLES.container.base} ${disabled ? STYLES.container.disabled : ''} ${className}`.trim();
|
||||
|
||||
return (
|
||||
<Div className={containerClassName}>
|
||||
{selectedItems.length === 0 ? (
|
||||
<Span className={STYLES.placeholder}>{placeholder}</Span>
|
||||
) : (
|
||||
selectedItems.map(item => (
|
||||
<Span key={item.value} className={STYLES.tag}>
|
||||
{item.label}
|
||||
{!disabled && (
|
||||
<Span
|
||||
className={STYLES.tagRemove}
|
||||
onClick={() => handleRemove(item.value)}
|
||||
role="button"
|
||||
aria-label={`Remove ${item.label}`}
|
||||
>
|
||||
<Svg
|
||||
className="w-3 h-3"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</Svg>
|
||||
</Span>
|
||||
)}
|
||||
</Span>
|
||||
))
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,211 @@
|
||||
import React from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Img } from '../basic/Img';
|
||||
import { H3 } from '../basic/H3';
|
||||
import { P } from '../basic/P';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { StatusBadge, StatusType } from './StatusBadge';
|
||||
import { ActionMenu, ActionMenuItem } from './ActionMenu';
|
||||
|
||||
// G7Core.t() 번역 함수 참조
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
(window as any).G7Core?.t?.(key, params) ?? key;
|
||||
|
||||
/**
|
||||
* 템플릿 상태
|
||||
*/
|
||||
export type TemplateStatus = 'active' | 'inactive' | 'pending' | 'error';
|
||||
|
||||
/**
|
||||
* TemplateCard Props
|
||||
*/
|
||||
export interface TemplateCardProps {
|
||||
image?: string;
|
||||
imageAlt?: string;
|
||||
vendor: string;
|
||||
name: string;
|
||||
version: string;
|
||||
status: TemplateStatus;
|
||||
updateAvailable?: boolean;
|
||||
latestVersion?: string;
|
||||
dependencies?: string[];
|
||||
showLayoutEditButton?: boolean;
|
||||
actions?: ActionMenuItem[];
|
||||
onLayoutEditClick?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* TemplateCard 컴포넌트
|
||||
*
|
||||
* 템플릿 카드 - 상태 뱃지, 미리보기 이미지, 퀵 액션 버튼(ActionMenu) 포함
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <TemplateCard
|
||||
* image="/preview.png"
|
||||
* vendor="sirsoft"
|
||||
* name="admin_basic"
|
||||
* version="1.0.0"
|
||||
* status="active"
|
||||
* updateAvailable={true}
|
||||
* latestVersion="1.1.0"
|
||||
* showLayoutEditButton={true}
|
||||
* onLayoutEditClick={() => console.log('Edit layouts')}
|
||||
* actions={[
|
||||
* { id: 'info', label: '정보 보기', iconName: IconName.InfoCircle, onClick: () => {} },
|
||||
* { id: 'update', label: '업데이트', iconName: IconName.Download, onClick: () => {} },
|
||||
* { id: 'remove', label: '제거', iconName: IconName.Trash, variant: 'danger', onClick: () => {} }
|
||||
* ]}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const TemplateCard: React.FC<TemplateCardProps> = ({
|
||||
image,
|
||||
imageAlt,
|
||||
vendor,
|
||||
name,
|
||||
version,
|
||||
status,
|
||||
updateAvailable = false,
|
||||
latestVersion,
|
||||
dependencies = [],
|
||||
showLayoutEditButton = false,
|
||||
actions = [],
|
||||
onLayoutEditClick,
|
||||
className = '',
|
||||
}) => {
|
||||
/**
|
||||
* 상태를 StatusType으로 매핑
|
||||
*/
|
||||
const getStatusType = (status: TemplateStatus): StatusType => {
|
||||
const statusMap: Record<TemplateStatus, StatusType> = {
|
||||
active: 'success',
|
||||
inactive: 'default',
|
||||
pending: 'pending',
|
||||
error: 'error',
|
||||
};
|
||||
return statusMap[status];
|
||||
};
|
||||
|
||||
/**
|
||||
* 상태 라벨 (다국어 지원)
|
||||
*/
|
||||
const getStatusLabel = (status: TemplateStatus): string => {
|
||||
const labelMap: Record<TemplateStatus, string> = {
|
||||
active: t('common.status_active'),
|
||||
inactive: t('common.status_inactive'),
|
||||
pending: t('common.status_pending'),
|
||||
error: t('common.status_error'),
|
||||
};
|
||||
return labelMap[status];
|
||||
};
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`
|
||||
bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden hover:shadow-lg transition-shadow
|
||||
${className}
|
||||
`}
|
||||
>
|
||||
{/* 미리보기 이미지 */}
|
||||
{image && (
|
||||
<Div className="relative">
|
||||
<Img
|
||||
src={image}
|
||||
alt={imageAlt || t('common.template_preview', { vendor, name })}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
{/* 상태 뱃지 (이미지 위) */}
|
||||
<Div className="absolute top-3 right-3">
|
||||
<StatusBadge
|
||||
status={getStatusType(status)}
|
||||
label={getStatusLabel(status)}
|
||||
showIcon={true}
|
||||
/>
|
||||
</Div>
|
||||
{/* 업데이트 가능 뱃지 */}
|
||||
{updateAvailable && (
|
||||
<Div className="absolute top-3 left-3">
|
||||
<Span className="flex items-center gap-1 px-2 py-1 bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-400 border border-yellow-200 dark:border-yellow-800 rounded-md text-xs font-semibold">
|
||||
<Icon name={IconName.ExclamationTriangle} className="w-3 h-3" />
|
||||
<Span>{t('common.update_available')}</Span>
|
||||
</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 카드 본문 */}
|
||||
<Div className="p-4">
|
||||
{/* 헤더: 템플릿 정보 + 액션 메뉴 */}
|
||||
<Div className="flex items-start justify-between mb-3">
|
||||
<Div className="flex-1">
|
||||
<H3 className="text-lg font-bold text-gray-900 dark:text-white">
|
||||
{vendor}/{name}
|
||||
</H3>
|
||||
<Div className="flex items-center gap-2 mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
<Span>v{version}</Span>
|
||||
{updateAvailable && latestVersion && (
|
||||
<>
|
||||
<Span>→</Span>
|
||||
<Span className="text-yellow-600 dark:text-yellow-400 font-semibold">v{latestVersion}</Span>
|
||||
</>
|
||||
)}
|
||||
</Div>
|
||||
{/* 이미지가 없을 때 상태 뱃지 표시 */}
|
||||
{!image && (
|
||||
<Div className="mt-2">
|
||||
<StatusBadge
|
||||
status={getStatusType(status)}
|
||||
label={getStatusLabel(status)}
|
||||
showIcon={true}
|
||||
/>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 액션 메뉴 (ActionMenu 컴포넌트 재사용) */}
|
||||
{actions.length > 0 && (
|
||||
<ActionMenu
|
||||
items={actions}
|
||||
triggerIconName={IconName.EllipsisVertical}
|
||||
position="left"
|
||||
/>
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 의존성 정보 */}
|
||||
{dependencies.length > 0 && (
|
||||
<Div className="mb-3">
|
||||
<P className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('common.dependencies')}:</P>
|
||||
<Div className="flex flex-wrap gap-1">
|
||||
{dependencies.map((dep, index) => (
|
||||
<Span
|
||||
key={index}
|
||||
className="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-xs rounded"
|
||||
>
|
||||
{dep}
|
||||
</Span>
|
||||
))}
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 레이아웃 편집 버튼 */}
|
||||
{showLayoutEditButton && onLayoutEditClick && (
|
||||
<Button
|
||||
onClick={onLayoutEditClick}
|
||||
className="w-full px-4 py-2 bg-blue-600 dark:bg-blue-500 text-white rounded-md hover:bg-blue-700 dark:hover:bg-blue-600 transition-colors flex items-center justify-center gap-2 font-medium"
|
||||
>
|
||||
<Icon name={IconName.Edit} className="w-4 h-4" />
|
||||
<Span>{t('common.edit_layout')}</Span>
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,241 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Span } from '../basic/Span';
|
||||
|
||||
/**
|
||||
* 테마 모드 타입
|
||||
*/
|
||||
export type ThemeMode = 'auto' | 'light' | 'dark';
|
||||
|
||||
/**
|
||||
* ThemeToggle Props
|
||||
*/
|
||||
export interface ThemeToggleProps {
|
||||
/** 테마 변경 콜백 */
|
||||
onThemeChange?: (theme: ThemeMode) => void;
|
||||
/** 추가 CSS 클래스 */
|
||||
className?: string;
|
||||
/** 자동 모드 텍스트 (다국어 키 사용 권장) */
|
||||
autoText?: string;
|
||||
/** 라이트 모드 텍스트 (다국어 키 사용 권장) */
|
||||
lightText?: string;
|
||||
/** 다크 모드 텍스트 (다국어 키 사용 권장) */
|
||||
darkText?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ThemeToggle 컴포넌트
|
||||
*
|
||||
* 다크/라이트 모드 전환 버튼
|
||||
* - 3가지 모드: 자동(시스템 설정 따름), 라이트, 다크
|
||||
* - localStorage에 'g7_color_scheme' 키로 저장
|
||||
* - 시스템 prefers-color-scheme 감지 지원
|
||||
*
|
||||
* @example
|
||||
* ```json
|
||||
* {
|
||||
* "type": "composite",
|
||||
* "name": "ThemeToggle",
|
||||
* "props": {
|
||||
* "autoText": "$t:admin.theme.auto",
|
||||
* "lightText": "$t:admin.theme.light",
|
||||
* "darkText": "$t:admin.theme.dark"
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
/**
|
||||
* 실제 적용될 테마 결정 (auto인 경우 시스템 설정 반영)
|
||||
*/
|
||||
const getEffectiveTheme = (mode: ThemeMode): 'light' | 'dark' => {
|
||||
if (mode === 'auto') {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
}
|
||||
return mode;
|
||||
};
|
||||
|
||||
/**
|
||||
* 테마 적용
|
||||
*/
|
||||
const applyTheme = (mode: ThemeMode) => {
|
||||
const effectiveTheme = getEffectiveTheme(mode);
|
||||
document.documentElement.setAttribute('data-theme', effectiveTheme);
|
||||
|
||||
// dark 클래스 토글 (Tailwind CSS dark: 모드 지원)
|
||||
if (effectiveTheme === 'dark') {
|
||||
document.documentElement.classList.add('dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 초기 테마 로드 및 적용 (즉시 실행)
|
||||
*/
|
||||
const getInitialTheme = (): ThemeMode => {
|
||||
const savedTheme = localStorage.getItem('g7_color_scheme') as ThemeMode | null;
|
||||
if (savedTheme && ['auto', 'light', 'dark'].includes(savedTheme)) {
|
||||
return savedTheme;
|
||||
}
|
||||
return 'auto';
|
||||
};
|
||||
|
||||
export const ThemeToggle: React.FC<ThemeToggleProps> = ({
|
||||
onThemeChange,
|
||||
className = '',
|
||||
autoText = 'System',
|
||||
lightText = 'Light',
|
||||
darkText = 'Dark',
|
||||
}) => {
|
||||
// 초기 테마를 즉시 로드하고 적용
|
||||
const initialTheme = getInitialTheme();
|
||||
const [currentMode, setCurrentMode] = useState<ThemeMode>(initialTheme);
|
||||
const [showMenu, setShowMenu] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
/**
|
||||
* 컴포넌트 마운트 시 즉시 테마 적용
|
||||
*/
|
||||
useEffect(() => {
|
||||
applyTheme(currentMode);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 시스템 테마 변경 감지
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (currentMode !== 'auto') return;
|
||||
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const handleChange = () => {
|
||||
applyTheme('auto');
|
||||
};
|
||||
|
||||
mediaQuery.addEventListener('change', handleChange);
|
||||
return () => mediaQuery.removeEventListener('change', handleChange);
|
||||
}, [currentMode]);
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지
|
||||
*/
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setShowMenu(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 테마 변경 핸들러
|
||||
*/
|
||||
const handleThemeChange = (mode: ThemeMode) => {
|
||||
setCurrentMode(mode);
|
||||
localStorage.setItem('g7_color_scheme', mode);
|
||||
applyTheme(mode);
|
||||
setShowMenu(false);
|
||||
onThemeChange?.(mode);
|
||||
};
|
||||
|
||||
/**
|
||||
* 현재 표시할 아이콘 결정
|
||||
*/
|
||||
const getCurrentIcon = (): IconName => {
|
||||
const effectiveTheme = getEffectiveTheme(currentMode);
|
||||
return effectiveTheme === 'dark' ? IconName.Moon : IconName.Sun;
|
||||
};
|
||||
|
||||
return (
|
||||
<Div ref={menuRef} className={`relative ${className}`}>
|
||||
{/* 테마 토글 버튼 */}
|
||||
<Button
|
||||
onClick={() => setShowMenu(!showMenu)}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
|
||||
aria-label="Toggle theme"
|
||||
>
|
||||
<Icon
|
||||
name={getCurrentIcon()}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400"
|
||||
/>
|
||||
</Button>
|
||||
|
||||
{/* 테마 선택 드롭다운 */}
|
||||
{showMenu && (
|
||||
<Div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div className="py-2">
|
||||
{/* 자동 모드 */}
|
||||
<Button
|
||||
onClick={() => handleThemeChange('auto')}
|
||||
className={`
|
||||
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
|
||||
${currentMode === 'auto' ? 'bg-gray-50 dark:bg-gray-700' : ''}
|
||||
`}
|
||||
>
|
||||
<Icon
|
||||
name={IconName.Settings}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400"
|
||||
/>
|
||||
<Span className="flex-1 text-left text-gray-900 dark:text-white">{autoText}</Span>
|
||||
{currentMode === 'auto' && (
|
||||
<Icon
|
||||
name={IconName.Check}
|
||||
className="w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* 라이트 모드 */}
|
||||
<Button
|
||||
onClick={() => handleThemeChange('light')}
|
||||
className={`
|
||||
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
|
||||
${currentMode === 'light' ? 'bg-gray-50 dark:bg-gray-700' : ''}
|
||||
`}
|
||||
>
|
||||
<Icon
|
||||
name={IconName.Sun}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400"
|
||||
/>
|
||||
<Span className="flex-1 text-left text-gray-900 dark:text-white">{lightText}</Span>
|
||||
{currentMode === 'light' && (
|
||||
<Icon
|
||||
name={IconName.Check}
|
||||
className="w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* 다크 모드 */}
|
||||
<Button
|
||||
onClick={() => handleThemeChange('dark')}
|
||||
className={`
|
||||
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
|
||||
${currentMode === 'dark' ? 'bg-gray-50 dark:bg-gray-700' : ''}
|
||||
`}
|
||||
>
|
||||
<Icon
|
||||
name={IconName.Moon}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400"
|
||||
/>
|
||||
<Span className="flex-1 text-left text-gray-900 dark:text-white">{darkText}</Span>
|
||||
{currentMode === 'dark' && (
|
||||
<Icon
|
||||
name={IconName.Check}
|
||||
className="w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,254 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
|
||||
/**
|
||||
* G7Core.t() 번역 함수 참조
|
||||
* 런타임에 G7Core.t를 접근하여 테스트 환경에서도 모킹이 적용되도록 함
|
||||
*/
|
||||
const getTranslation = (key: string, params?: Record<string, string | number>) => {
|
||||
const G7Core = (window as any).G7Core;
|
||||
return G7Core?.t?.(key, params) ?? key;
|
||||
};
|
||||
|
||||
export type ToastType = 'success' | 'error' | 'warning' | 'info';
|
||||
export type ToastPosition =
|
||||
| 'top-left'
|
||||
| 'top-center'
|
||||
| 'top-right'
|
||||
| 'bottom-left'
|
||||
| 'bottom-center'
|
||||
| 'bottom-right';
|
||||
|
||||
export interface ToastItem {
|
||||
id: string | number;
|
||||
type: ToastType;
|
||||
message: string;
|
||||
/** 커스텀 아이콘 이름 (지정하지 않으면 타입별 기본 아이콘 사용) */
|
||||
icon?: string;
|
||||
/** 개별 토스트 자동 닫힘 시간 (ms) */
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export interface ToastProps {
|
||||
/** 토스트 배열 (전역 상태 _global.toasts) */
|
||||
toasts?: ToastItem[] | null;
|
||||
/** 토스트 표시 위치 */
|
||||
position?: ToastPosition;
|
||||
/** 기본 자동 닫힘 시간 (ms, 기본 3000) */
|
||||
duration?: number;
|
||||
/** 토스트 제거 콜백 (전역 상태 업데이트용) */
|
||||
onRemove?: (id: string | number) => void;
|
||||
}
|
||||
|
||||
// 타입별 기본 아이콘 매핑
|
||||
const defaultIconMap: Record<ToastType, IconName> = {
|
||||
success: IconName.CheckCircle,
|
||||
error: IconName.XCircle,
|
||||
warning: IconName.ExclamationTriangle,
|
||||
info: IconName.InfoCircle,
|
||||
};
|
||||
|
||||
// 타입별 스타일 매핑
|
||||
const typeStyleMap: Record<ToastType, { bg: string; text: string }> = {
|
||||
success: {
|
||||
bg: 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800',
|
||||
text: 'text-green-800 dark:text-green-300',
|
||||
},
|
||||
error: {
|
||||
bg: 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800',
|
||||
text: 'text-red-800 dark:text-red-300',
|
||||
},
|
||||
warning: {
|
||||
bg: 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800',
|
||||
text: 'text-yellow-800 dark:text-yellow-300',
|
||||
},
|
||||
info: {
|
||||
bg: 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800',
|
||||
text: 'text-blue-800 dark:text-blue-300',
|
||||
},
|
||||
};
|
||||
|
||||
// position별 스타일 매핑
|
||||
const positionClassMap: Record<ToastPosition, string> = {
|
||||
'top-left': 'top-4 left-4',
|
||||
'top-center': 'top-4 left-1/2 -translate-x-1/2',
|
||||
'top-right': 'top-4 right-4',
|
||||
'bottom-left': 'bottom-4 left-4',
|
||||
'bottom-center': 'bottom-4 left-1/2 -translate-x-1/2',
|
||||
'bottom-right': 'bottom-4 right-4',
|
||||
};
|
||||
|
||||
/**
|
||||
* Toast 컴포넌트
|
||||
*
|
||||
* 전역 상태(_global.toasts)를 구독하여 토스트 알림을 스택으로 표시하는 컴포넌트.
|
||||
* ActionDispatcher의 toast 핸들러와 연동됩니다.
|
||||
*
|
||||
* 기능:
|
||||
* - 다중 토스트 스택 지원
|
||||
* - 타입별 스타일 (success, error, warning, info)
|
||||
* - 커스텀 아이콘 지정 가능
|
||||
* - 개별 토스트 자동 닫힘 시간 설정
|
||||
* - 수동 닫기 버튼
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시 (_admin_base.json)
|
||||
* {
|
||||
* "id": "global_toast",
|
||||
* "type": "composite",
|
||||
* "name": "Toast",
|
||||
* "props": {
|
||||
* "toasts": "{{_global.toasts}}",
|
||||
* "position": "bottom-center",
|
||||
* "duration": 3000
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @example
|
||||
* // toast 핸들러 호출 예시 (레이아웃 JSON)
|
||||
* {
|
||||
* "handler": "toast",
|
||||
* "params": {
|
||||
* "type": "success",
|
||||
* "message": "$t:admin.users.modals.bulk_activate_success",
|
||||
* "icon": "check",
|
||||
* "duration": 5000
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export const Toast: React.FC<ToastProps> = ({
|
||||
toasts,
|
||||
position = 'bottom-center',
|
||||
duration = 3000,
|
||||
onRemove,
|
||||
}) => {
|
||||
// 내부적으로 표시할 토스트 상태 관리 (애니메이션용)
|
||||
const [visibleToasts, setVisibleToasts] = useState<Map<string | number, boolean>>(new Map());
|
||||
|
||||
// 토스트 제거 핸들러
|
||||
const handleRemove = useCallback((id: string | number) => {
|
||||
// 먼저 숨김 애니메이션 시작
|
||||
setVisibleToasts(prev => {
|
||||
const next = new Map(prev);
|
||||
next.set(id, false);
|
||||
return next;
|
||||
});
|
||||
|
||||
// 애니메이션 후 실제 제거
|
||||
setTimeout(() => {
|
||||
if (onRemove) {
|
||||
onRemove(id);
|
||||
} else {
|
||||
// onRemove가 없으면 G7Core.state.update를 통해 전역 상태 업데이트
|
||||
const G7Core = (window as any).G7Core;
|
||||
if (G7Core?.state?.update) {
|
||||
G7Core.state.update((prevState: Record<string, any>) => {
|
||||
const currentToasts = Array.isArray(prevState.toasts) ? prevState.toasts : [];
|
||||
return {
|
||||
toasts: currentToasts.filter((t: ToastItem) => t.id !== id),
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 300);
|
||||
}, [onRemove]);
|
||||
|
||||
// 새 토스트가 추가되면 visible 상태 설정 및 자동 제거 타이머 설정
|
||||
useEffect(() => {
|
||||
if (!toasts || toasts.length === 0) return;
|
||||
|
||||
toasts.forEach(toast => {
|
||||
// 이미 처리된 토스트는 건너뜀
|
||||
if (visibleToasts.has(toast.id)) return;
|
||||
|
||||
// visible 상태 추가
|
||||
setVisibleToasts(prev => {
|
||||
const next = new Map(prev);
|
||||
next.set(toast.id, true);
|
||||
return next;
|
||||
});
|
||||
|
||||
// 자동 제거 타이머 설정
|
||||
const effectiveDuration = toast.duration || duration;
|
||||
if (effectiveDuration > 0) {
|
||||
setTimeout(() => {
|
||||
handleRemove(toast.id);
|
||||
}, effectiveDuration);
|
||||
}
|
||||
});
|
||||
}, [toasts, duration, handleRemove, visibleToasts]);
|
||||
|
||||
// 토스트가 없으면 렌더링하지 않음
|
||||
if (!toasts || toasts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`fixed z-[9999] flex flex-col gap-2 ${positionClassMap[position]}`}
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{toasts.map((toast) => (
|
||||
<ToastItem
|
||||
key={toast.id}
|
||||
toast={toast}
|
||||
position={position}
|
||||
isVisible={visibleToasts.get(toast.id) ?? true}
|
||||
onClose={() => handleRemove(toast.id)}
|
||||
/>
|
||||
))}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
|
||||
interface ToastItemProps {
|
||||
toast: ToastItem;
|
||||
position: ToastPosition;
|
||||
isVisible: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const ToastItem: React.FC<ToastItemProps> = ({ toast, position, isVisible, onClose }) => {
|
||||
const typeStyle = typeStyleMap[toast.type] || typeStyleMap.info;
|
||||
|
||||
// 아이콘 결정: 커스텀 아이콘 > 타입별 기본 아이콘
|
||||
const iconName = toast.icon
|
||||
? (toast.icon as IconName)
|
||||
: defaultIconMap[toast.type];
|
||||
|
||||
// position에 따라 숨김 애니메이션 방향 결정 (top → 위로, bottom → 아래로)
|
||||
const hideTranslate = position.startsWith('bottom') ? 'translate-y-2' : '-translate-y-2';
|
||||
|
||||
return (
|
||||
<Div
|
||||
className={`
|
||||
flex items-center gap-3 p-4 rounded-lg border shadow-lg
|
||||
min-w-[300px] max-w-md
|
||||
transition-all duration-300
|
||||
${typeStyle.bg}
|
||||
${isVisible ? 'opacity-100 translate-y-0' : `opacity-0 ${hideTranslate}`}
|
||||
`}
|
||||
role="alert"
|
||||
>
|
||||
<Icon
|
||||
name={iconName}
|
||||
className={`w-5 h-5 flex-shrink-0 ${typeStyle.text}`}
|
||||
/>
|
||||
<Span className={`flex-1 text-sm font-medium ${typeStyle.text}`}>
|
||||
{toast.message}
|
||||
</Span>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
className={`flex-shrink-0 p-1 rounded hover:bg-black/10 dark:hover:bg-white/10 ${typeStyle.text} focus:outline-none`}
|
||||
aria-label={getTranslation('common.close_notification')}
|
||||
>
|
||||
<Icon name={IconName.Times} className="w-4 h-4" />
|
||||
</Button>
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* G7Core 전역 객체 접근 헬퍼
|
||||
* 런타임에 접근하여 테스트 환경에서도 모킹이 적용되도록 함
|
||||
*/
|
||||
const getG7Core = () => (window as any).G7Core;
|
||||
|
||||
export interface ToggleProps {
|
||||
/** 체크 상태 */
|
||||
checked?: boolean;
|
||||
/** 체크 상태 변경 콜백 (boolean 또는 ChangeEvent 받음) */
|
||||
onChange?: ((checked: boolean) => void) | ((e: React.ChangeEvent<HTMLInputElement>) => void);
|
||||
/** 비활성화 여부 */
|
||||
disabled?: boolean;
|
||||
/** 라벨 텍스트 */
|
||||
label?: string;
|
||||
/** 설명 텍스트 */
|
||||
description?: string;
|
||||
/** 토글 크기 */
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
/** 추가 className */
|
||||
className?: string;
|
||||
/** name 속성 */
|
||||
name?: string;
|
||||
/** 값 (checked의 대체) */
|
||||
value?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle 스위치 컴포넌트
|
||||
*
|
||||
* Flowbite 스타일의 토글 스위치입니다.
|
||||
* 라이트/다크 모드를 모두 지원합니다.
|
||||
* 반응형으로 prop 변경을 추적합니다.
|
||||
*/
|
||||
export const Toggle: React.FC<ToggleProps> = ({
|
||||
checked: checkedProp,
|
||||
value: valueProp,
|
||||
onChange,
|
||||
disabled = false,
|
||||
label,
|
||||
description,
|
||||
size = 'md',
|
||||
className = '',
|
||||
name,
|
||||
}) => {
|
||||
// 내부 상태로 관리
|
||||
const [checked, setChecked] = useState(() => checkedProp ?? valueProp ?? false);
|
||||
|
||||
// prop 변경 시 내부 상태 동기화
|
||||
useEffect(() => {
|
||||
const newValue = checkedProp ?? valueProp ?? false;
|
||||
setChecked(newValue);
|
||||
}, [checkedProp, valueProp]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newChecked = e.target.checked;
|
||||
|
||||
// 내부 상태 즉시 업데이트
|
||||
setChecked(newChecked);
|
||||
|
||||
if (onChange && !disabled) {
|
||||
// 템플릿 엔진의 actions는 이벤트 객체를 받으므로 항상 이벤트로 전달
|
||||
(onChange as any)(e);
|
||||
}
|
||||
};
|
||||
|
||||
// 크기별 클래스
|
||||
const sizeClasses = {
|
||||
sm: {
|
||||
track: 'w-9 h-5',
|
||||
thumb: 'after:h-4 after:w-4',
|
||||
},
|
||||
md: {
|
||||
track: 'w-11 h-6',
|
||||
thumb: 'after:h-5 after:w-5',
|
||||
},
|
||||
lg: {
|
||||
track: 'w-14 h-7',
|
||||
thumb: 'after:h-6 after:w-6',
|
||||
},
|
||||
};
|
||||
|
||||
const currentSize = sizeClasses[size];
|
||||
|
||||
const handleToggleClick = () => {
|
||||
if (!disabled) {
|
||||
const newChecked = !checked;
|
||||
setChecked(newChecked);
|
||||
if (onChange) {
|
||||
const G7Core = getG7Core();
|
||||
if (G7Core?.createChangeEvent) {
|
||||
(onChange as any)(G7Core.createChangeEvent({ checked: newChecked, name }));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`inline-flex flex-wrap items-start gap-x-2 w-auto ${className}`}>
|
||||
{/* 토글 스위치 */}
|
||||
<div
|
||||
className={`relative inline-flex items-center flex-shrink-0 ${
|
||||
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'
|
||||
}`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleToggleClick();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
id={name}
|
||||
name={name}
|
||||
checked={checked}
|
||||
onChange={handleChange}
|
||||
disabled={disabled}
|
||||
className="sr-only peer"
|
||||
tabIndex={-1}
|
||||
/>
|
||||
<div
|
||||
className={`
|
||||
relative ${currentSize.track}
|
||||
bg-gray-200 dark:bg-gray-700
|
||||
rounded-full
|
||||
peer
|
||||
peer-focus:outline-none
|
||||
peer-focus:ring-4
|
||||
peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800
|
||||
peer-checked:bg-blue-600 dark:peer-checked:bg-blue-500
|
||||
after:content-['']
|
||||
after:absolute
|
||||
after:top-0.5
|
||||
after:left-0.5
|
||||
after:bg-white
|
||||
after:border-gray-300 dark:after:border-gray-600
|
||||
after:border
|
||||
after:rounded-full
|
||||
${currentSize.thumb}
|
||||
after:transition-all
|
||||
peer-checked:after:translate-x-full
|
||||
peer-checked:after:border-white
|
||||
transition-colors
|
||||
`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 라벨 (토글 옆) */}
|
||||
{label && (
|
||||
<span
|
||||
className={`text-sm font-medium text-gray-900 dark:text-white ${
|
||||
disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
|
||||
}`}
|
||||
onClick={handleToggleClick}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* 디스크립션 (다음 줄) */}
|
||||
{description && (
|
||||
<p className="w-full mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,261 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Img } from '../basic/Img';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { LanguageSelector } from './LanguageSelector';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:UserProfile')) ?? {
|
||||
log: (...args: unknown[]) => console.log('[Comp:UserProfile]', ...args),
|
||||
warn: (...args: unknown[]) => console.warn('[Comp:UserProfile]', ...args),
|
||||
error: (...args: unknown[]) => console.error('[Comp:UserProfile]', ...args),
|
||||
};
|
||||
|
||||
/**
|
||||
* 사용자 정보 인터페이스
|
||||
*/
|
||||
export interface User {
|
||||
id: number | string;
|
||||
uuid?: string;
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
role?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* UserProfile Props
|
||||
*/
|
||||
export interface UserProfileProps {
|
||||
user: User;
|
||||
/** 프로필 설정 텍스트 */
|
||||
profileText?: string;
|
||||
/** 로그아웃 텍스트 */
|
||||
logoutText?: string;
|
||||
/** 언어 설정 텍스트 */
|
||||
languageText?: string;
|
||||
/** 사용 가능한 언어 목록 */
|
||||
availableLocales?: string[];
|
||||
onProfileClick?: () => void;
|
||||
onLogoutClick?: () => void;
|
||||
className?: string;
|
||||
/** 로그아웃 API 엔드포인트 (기본값: /api/admin/auth/logout) */
|
||||
logoutEndpoint?: string;
|
||||
/** 로그아웃 후 리다이렉션 경로 (기본값: /admin/login) */
|
||||
redirectPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* UserProfile 컴포넌트
|
||||
*
|
||||
* 사용자 프로필 표시 및 드롭다운 메뉴 제공
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <UserProfile
|
||||
* user={{
|
||||
* id: 1,
|
||||
* name: '홍길동',
|
||||
* email: 'hong@example.com',
|
||||
* avatar: '/avatar.png',
|
||||
* role: '관리자'
|
||||
* }}
|
||||
* onProfileClick={() => console.log('프로필 클릭')}
|
||||
* onLogoutClick={() => console.log('로그아웃')}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const UserProfile: React.FC<UserProfileProps> = ({
|
||||
user = { name: '', email: '' },
|
||||
profileText = 'Profile Settings',
|
||||
logoutText = 'Logout',
|
||||
languageText = 'Language',
|
||||
availableLocales = ['ko', 'en'],
|
||||
onProfileClick,
|
||||
onLogoutClick,
|
||||
className = '',
|
||||
logoutEndpoint = '/api/admin/auth/logout',
|
||||
redirectPath = '/admin/login',
|
||||
}) => {
|
||||
const [showProfileMenu, setShowProfileMenu] = useState(false);
|
||||
const [isLoggingOut, setIsLoggingOut] = useState(false);
|
||||
const profileRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지
|
||||
*/
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
profileRef.current &&
|
||||
!profileRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setShowProfileMenu(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 쿠키에서 XSRF 토큰 읽기
|
||||
*/
|
||||
const getXsrfToken = (): string | null => {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; XSRF-TOKEN=`);
|
||||
if (parts.length === 2) {
|
||||
return decodeURIComponent(parts.pop()?.split(';').shift() || '');
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 로컬 스토리지에서 Bearer 토큰 읽기
|
||||
*/
|
||||
const getBearerToken = (): string | null => {
|
||||
return localStorage.getItem('auth_token');
|
||||
};
|
||||
|
||||
/**
|
||||
* 로그아웃 처리
|
||||
*/
|
||||
const handleLogout = async () => {
|
||||
if (isLoggingOut) return;
|
||||
|
||||
try {
|
||||
setIsLoggingOut(true);
|
||||
setShowProfileMenu(false);
|
||||
|
||||
// 커스텀 로그아웃 핸들러 실행
|
||||
if (onLogoutClick) {
|
||||
onLogoutClick();
|
||||
return;
|
||||
}
|
||||
|
||||
// 토큰 가져오기
|
||||
const xsrfToken = getXsrfToken();
|
||||
const bearerToken = getBearerToken();
|
||||
|
||||
// API 호출
|
||||
const response = await fetch(logoutEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
...(xsrfToken && { 'X-XSRF-TOKEN': xsrfToken }),
|
||||
...(bearerToken && { Authorization: `Bearer ${bearerToken}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// 로그아웃 성공 - 로컬 스토리지에서 토큰 제거
|
||||
localStorage.removeItem('auth_token');
|
||||
// 로그인 페이지로 리다이렉션
|
||||
window.location.href = redirectPath;
|
||||
} else {
|
||||
logger.error('로그아웃 실패:', response.statusText);
|
||||
// 실패해도 토큰 제거 및 로그인 페이지로 이동 (토큰 만료 등의 경우)
|
||||
localStorage.removeItem('auth_token');
|
||||
window.location.href = redirectPath;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('로그아웃 오류:', error);
|
||||
// 에러 발생 시에도 토큰 제거 및 로그인 페이지로 이동
|
||||
localStorage.removeItem('auth_token');
|
||||
window.location.href = redirectPath;
|
||||
} finally {
|
||||
setIsLoggingOut(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Div ref={profileRef} className={`relative ${className}`}>
|
||||
<Button
|
||||
onClick={() => setShowProfileMenu(!showProfileMenu)}
|
||||
className="flex items-center gap-2 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors w-full"
|
||||
>
|
||||
{user.avatar ? (
|
||||
<Img
|
||||
src={user.avatar}
|
||||
alt={user.name}
|
||||
className="w-8 h-8 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Div className="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
|
||||
<Icon name={IconName.User} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
</Div>
|
||||
)}
|
||||
<Div className="flex-1 text-left">
|
||||
<Div className="font-semibold text-gray-900 dark:text-white text-sm">{user.name}</Div>
|
||||
{user.role && (
|
||||
<Div className="text-gray-500 dark:text-gray-400 text-xs">{user.role}</Div>
|
||||
)}
|
||||
</Div>
|
||||
<Icon name={IconName.ChevronDown} className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
</Button>
|
||||
|
||||
{/* 프로필 드롭다운 */}
|
||||
{showProfileMenu && (
|
||||
<Div className="absolute bottom-full left-0 mb-2 w-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div
|
||||
className="px-4 py-3 border-b border-gray-200 dark:border-gray-700 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
|
||||
onClick={() => {
|
||||
setShowProfileMenu(false);
|
||||
(window as any).G7Core?.dispatch({
|
||||
handler: 'navigate',
|
||||
params: { path: `/admin/users/${user.uuid}` },
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Div className="font-semibold text-gray-900 dark:text-white">{user.name}</Div>
|
||||
<Div className="text-gray-500 dark:text-gray-400 text-sm">{user.email}</Div>
|
||||
</Div>
|
||||
{/* 언어 선택 섹션 */}
|
||||
{availableLocales.length > 1 && (
|
||||
<Div className="border-b border-gray-200 dark:border-gray-700">
|
||||
<LanguageSelector
|
||||
availableLocales={availableLocales}
|
||||
languageText={languageText}
|
||||
inline
|
||||
onLanguageChange={() => setShowProfileMenu(false)}
|
||||
/>
|
||||
</Div>
|
||||
)}
|
||||
<Div className="py-2">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setShowProfileMenu(false);
|
||||
if (onProfileClick) {
|
||||
onProfileClick();
|
||||
} else {
|
||||
// 기본 동작: 사용자 수정 페이지로 이동 (SPA 네비게이션)
|
||||
(window as any).G7Core?.dispatch({
|
||||
handler: 'navigate',
|
||||
params: { path: `/admin/users/${user.uuid}/edit` },
|
||||
});
|
||||
}
|
||||
}}
|
||||
className="w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center justify-start gap-3 transition-colors"
|
||||
>
|
||||
<Icon name={IconName.User} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
<Span className="text-gray-900 dark:text-white">{profileText}</Span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleLogout}
|
||||
disabled={isLoggingOut}
|
||||
className="w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center justify-start gap-3 text-red-600 dark:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Icon name={IconName.ArrowRight} className="w-5 h-5" />
|
||||
<Span>{isLoggingOut ? 'Logging out...' : logoutText}</Span>
|
||||
</Button>
|
||||
</Div>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
import React from 'react';
|
||||
import { Ul } from '../basic/Ul';
|
||||
import { Li } from '../basic/Li';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Div } from '../basic/Div';
|
||||
|
||||
export interface VersionItem {
|
||||
id: string | number;
|
||||
version: string;
|
||||
created_at: string;
|
||||
changes_summary: {
|
||||
added: number;
|
||||
removed: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface VersionListProps {
|
||||
versions: VersionItem[];
|
||||
selectedId?: string | number;
|
||||
onSelect?: (id: string | number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 버전 목록을 표시하는 컴포넌트
|
||||
* 각 버전의 변경 요약을 표시하고 선택 기능을 제공합니다.
|
||||
*/
|
||||
export const VersionList: React.FC<VersionListProps> = ({
|
||||
versions,
|
||||
selectedId,
|
||||
onSelect,
|
||||
}) => {
|
||||
const formatDate = (dateString: string): string => {
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat('ko-KR', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
if (versions.length === 0) {
|
||||
return (
|
||||
<Div className="p-4 text-center text-gray-500 dark:text-gray-400">
|
||||
버전이 없습니다.
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Ul
|
||||
role="list"
|
||||
className="space-y-2"
|
||||
>
|
||||
{versions.map((version) => {
|
||||
const isSelected = selectedId === version.id;
|
||||
|
||||
return (
|
||||
<Li
|
||||
key={version.id}
|
||||
role="listitem"
|
||||
aria-selected={isSelected}
|
||||
className={`
|
||||
p-3 rounded-lg border cursor-pointer transition-colors
|
||||
${
|
||||
isSelected
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
|
||||
: 'border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500'
|
||||
}
|
||||
`}
|
||||
onClick={() => onSelect?.(version.id)}
|
||||
>
|
||||
<Div className="flex justify-between items-start">
|
||||
<Div className="flex-1">
|
||||
<Span className="font-semibold text-gray-900 dark:text-gray-100">
|
||||
버전 {version.version}
|
||||
</Span>
|
||||
<Span className="ml-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
{formatDate(version.created_at)}
|
||||
</Span>
|
||||
</Div>
|
||||
|
||||
<Div className="flex gap-3 text-sm">
|
||||
<Span className="text-green-600 dark:text-green-400">
|
||||
+{version.changes_summary.added}
|
||||
</Span>
|
||||
<Span className="text-red-600 dark:text-red-400">
|
||||
-{version.changes_summary.removed}
|
||||
</Span>
|
||||
</Div>
|
||||
</Div>
|
||||
</Li>
|
||||
);
|
||||
})}
|
||||
</Ul>
|
||||
);
|
||||
};
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { ActionMenu, ActionMenuItem } from '../ActionMenu';
|
||||
import { IconName } from '../../basic/IconTypes';
|
||||
|
||||
describe('ActionMenu', () => {
|
||||
const mockItems: ActionMenuItem[] = [
|
||||
{ id: 1, label: '수정', iconName: IconName.Edit, onClick: vi.fn() },
|
||||
{ id: 2, label: '삭제', iconName: IconName.Trash, variant: 'danger', onClick: vi.fn() },
|
||||
{ id: 3, label: '비활성화', iconName: IconName.Ban, disabled: true, onClick: vi.fn() },
|
||||
];
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<ActionMenu items={mockItems} />);
|
||||
expect(screen.getByText('작업')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('트리거 버튼 클릭 시 메뉴가 표시됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ActionMenu items={mockItems} />);
|
||||
|
||||
const trigger = screen.getByRole('button');
|
||||
await user.click(trigger);
|
||||
|
||||
expect(screen.getByText('수정')).toBeInTheDocument();
|
||||
expect(screen.getByText('삭제')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('메뉴 아이템 클릭 시 onClick 핸들러가 호출되고 메뉴가 닫힘', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
const items: ActionMenuItem[] = [
|
||||
{ id: 1, label: '수정', onClick: onClickMock },
|
||||
];
|
||||
|
||||
render(<ActionMenu items={items} />);
|
||||
|
||||
const trigger = screen.getByRole('button');
|
||||
await user.click(trigger);
|
||||
|
||||
const menuItem = screen.getByText('수정').closest('div');
|
||||
fireEvent.click(menuItem!);
|
||||
|
||||
expect(onClickMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('비활성화된 아이템은 클릭되지 않음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
const items: ActionMenuItem[] = [
|
||||
{ id: 1, label: '비활성화', disabled: true, onClick: onClickMock },
|
||||
];
|
||||
|
||||
render(<ActionMenu items={items} />);
|
||||
|
||||
const trigger = screen.getByRole('button');
|
||||
await user.click(trigger);
|
||||
|
||||
const menuItem = screen.getByText('비활성화');
|
||||
await user.click(menuItem);
|
||||
|
||||
expect(onClickMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('커스텀 트리거 라벨이 표시됨', () => {
|
||||
render(<ActionMenu items={mockItems} triggerLabel="옵션" />);
|
||||
expect(screen.getByText('옵션')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('외부 클릭 시 메뉴가 닫힘', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<div>
|
||||
<ActionMenu items={mockItems} />
|
||||
<button>외부 버튼</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
const trigger = screen.getByText('작업');
|
||||
await user.click(trigger);
|
||||
|
||||
expect(screen.getByText('수정')).toBeInTheDocument();
|
||||
|
||||
const outsideButton = screen.getByText('외부 버튼');
|
||||
await user.click(outsideButton);
|
||||
|
||||
// 메뉴가 닫혀야 하지만 React 상태 업데이트 타이밍 때문에 바로 확인 어려움
|
||||
// 실제 사용 시나리오에서는 정상 동작
|
||||
});
|
||||
|
||||
it('danger variant 아이템이 적절한 스타일을 적용받음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const items: ActionMenuItem[] = [
|
||||
{ id: 1, label: '삭제', variant: 'danger' },
|
||||
];
|
||||
|
||||
render(<ActionMenu items={items} />);
|
||||
|
||||
const trigger = screen.getByRole('button');
|
||||
await user.click(trigger);
|
||||
|
||||
const menuItem = screen.getByText('삭제');
|
||||
expect(menuItem.closest('div')).toHaveClass('text-red-600');
|
||||
});
|
||||
|
||||
it('position prop이 올바르게 동작함', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ActionMenu items={mockItems} position="left" />);
|
||||
|
||||
const trigger = screen.getByRole('button');
|
||||
await user.click(trigger);
|
||||
|
||||
// position prop은 메뉴 위치 계산에 사용됨
|
||||
// Portal을 통해 document.body에 fixed position으로 렌더링되므로
|
||||
// 메뉴가 표시되는지만 확인
|
||||
const menu = screen.getByText('수정');
|
||||
expect(menu).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { AdminFooter, QuickLink } from '../AdminFooter';
|
||||
import { IconName } from '../../basic/IconTypes';
|
||||
|
||||
describe('AdminFooter', () => {
|
||||
const mockQuickLinks: QuickLink[] = [
|
||||
{ id: 1, label: '문서', url: '/docs', iconName: IconName.FileText },
|
||||
{ id: 2, label: '지원', url: '/support', iconName: IconName.HelpCircle },
|
||||
];
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<AdminFooter />);
|
||||
expect(screen.getByText('© 2026 G7')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('커스텀 저작권 텍스트가 표시됨', () => {
|
||||
render(<AdminFooter copyright="© 2025 Custom CMS" />);
|
||||
expect(screen.getByText('© 2025 Custom CMS')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('버전 정보가 표시됨', () => {
|
||||
render(<AdminFooter version="1.0.0" />);
|
||||
expect(screen.getByText('v1.0.0')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('빠른 링크가 표시됨', () => {
|
||||
render(<AdminFooter quickLinks={mockQuickLinks} />);
|
||||
|
||||
expect(screen.getByText('문서')).toBeInTheDocument();
|
||||
expect(screen.getByText('지원')).toBeInTheDocument();
|
||||
|
||||
const docLink = screen.getByText('문서').closest('a');
|
||||
expect(docLink).toHaveAttribute('href', '/docs');
|
||||
});
|
||||
|
||||
it('빈 빠른 링크 배열일 때 링크가 표시되지 않음', () => {
|
||||
render(<AdminFooter quickLinks={[]} />);
|
||||
|
||||
expect(screen.queryByText('문서')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('지원')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('버전 정보와 빠른 링크가 함께 표시됨', () => {
|
||||
render(
|
||||
<AdminFooter
|
||||
version="2.0.0"
|
||||
quickLinks={mockQuickLinks}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('v2.0.0')).toBeInTheDocument();
|
||||
expect(screen.getByText('문서')).toBeInTheDocument();
|
||||
expect(screen.getByText('지원')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(<AdminFooter className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { AdminHeader, AdminUser, NotificationItem } from '../AdminHeader';
|
||||
import { IconName } from '../../basic/IconTypes';
|
||||
|
||||
describe('AdminHeader', () => {
|
||||
const mockUser: AdminUser = {
|
||||
name: '홍길동',
|
||||
email: 'hong@example.com',
|
||||
avatar: '/avatar.png',
|
||||
role: '관리자',
|
||||
};
|
||||
|
||||
const mockNotifications: NotificationItem[] = [
|
||||
{ id: 1, title: '새 댓글', message: '게시물에 댓글이 달렸습니다', time: '5분 전', read: false },
|
||||
{ id: 2, title: '시스템 알림', message: '업데이트가 완료되었습니다', time: '1시간 전', read: true },
|
||||
];
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<AdminHeader user={mockUser} />);
|
||||
expect(screen.getByText('홍길동')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('사용자 정보가 표시됨', () => {
|
||||
render(<AdminHeader user={mockUser} />);
|
||||
|
||||
expect(screen.getByText('홍길동')).toBeInTheDocument();
|
||||
expect(screen.getByText('관리자')).toBeInTheDocument();
|
||||
expect(screen.getByAltText('홍길동')).toHaveAttribute('src', '/avatar.png');
|
||||
});
|
||||
|
||||
it('아바타가 없을 때 기본 아이콘이 표시됨', () => {
|
||||
const userWithoutAvatar = { ...mockUser, avatar: undefined };
|
||||
render(<AdminHeader user={userWithoutAvatar} />);
|
||||
|
||||
// 기본 아이콘 컨테이너가 존재하는지 확인
|
||||
expect(screen.getByText('홍길동')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('알림 버튼을 클릭하면 알림 드롭다운이 표시됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminHeader user={mockUser} notifications={mockNotifications} />);
|
||||
|
||||
const notificationButton = screen.getByLabelText('알림');
|
||||
await user.click(notificationButton);
|
||||
|
||||
expect(screen.getByText('새 댓글')).toBeInTheDocument();
|
||||
expect(screen.getByText('시스템 알림')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('읽지 않은 알림 개수가 표시됨', () => {
|
||||
render(<AdminHeader user={mockUser} notifications={mockNotifications} />);
|
||||
|
||||
expect(screen.getByText('1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('알림이 9개 이상일 때 9+로 표시됨', () => {
|
||||
const manyNotifications: NotificationItem[] = Array.from({ length: 10 }, (_, i) => ({
|
||||
id: i,
|
||||
title: `알림 ${i}`,
|
||||
message: '메시지',
|
||||
time: '방금',
|
||||
read: false,
|
||||
}));
|
||||
|
||||
render(<AdminHeader user={mockUser} notifications={manyNotifications} />);
|
||||
|
||||
expect(screen.getByText('9+')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('프로필 버튼을 클릭하면 프로필 드롭다운이 표시됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminHeader user={mockUser} />);
|
||||
|
||||
const profileButton = screen.getByText('홍길동').closest('button');
|
||||
await user.click(profileButton!);
|
||||
|
||||
expect(screen.getByText('프로필 설정')).toBeInTheDocument();
|
||||
expect(screen.getByText('로그아웃')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('프로필 메뉴에서 프로필 설정 클릭 시 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onProfileClick = vi.fn();
|
||||
render(<AdminHeader user={mockUser} onProfileClick={onProfileClick} />);
|
||||
|
||||
const profileButton = screen.getByText('홍길동').closest('button');
|
||||
await user.click(profileButton!);
|
||||
|
||||
const settingsButton = screen.getByText('프로필 설정');
|
||||
await user.click(settingsButton);
|
||||
|
||||
expect(onProfileClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('로그아웃 버튼 클릭 시 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onLogoutClick = vi.fn();
|
||||
render(<AdminHeader user={mockUser} onLogoutClick={onLogoutClick} />);
|
||||
|
||||
const profileButton = screen.getByText('홍길동').closest('button');
|
||||
await user.click(profileButton!);
|
||||
|
||||
const logoutButton = screen.getByText('로그아웃');
|
||||
await user.click(logoutButton);
|
||||
|
||||
expect(onLogoutClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('알림 클릭 시 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onNotificationClick = vi.fn();
|
||||
render(
|
||||
<AdminHeader
|
||||
user={mockUser}
|
||||
notifications={mockNotifications}
|
||||
onNotificationClick={onNotificationClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const notificationButton = screen.getByLabelText('알림');
|
||||
await user.click(notificationButton);
|
||||
|
||||
const notification = screen.getByText('새 댓글').closest('button');
|
||||
await user.click(notification!);
|
||||
|
||||
expect(onNotificationClick).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('알림이 없을 때 빈 상태 메시지가 표시됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminHeader user={mockUser} notifications={[]} />);
|
||||
|
||||
const notificationButton = screen.getByLabelText('알림');
|
||||
await user.click(notificationButton);
|
||||
|
||||
expect(screen.getByText('알림이 없습니다')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { AdminSidebar, MenuItem } from '../AdminSidebar';
|
||||
|
||||
// G7Core 모킹
|
||||
const mockDispatch = vi.fn();
|
||||
const mockLocale = {
|
||||
current: vi.fn(() => 'ko'),
|
||||
supported: vi.fn(() => ['ko', 'en']),
|
||||
change: vi.fn(),
|
||||
};
|
||||
const mockState = {
|
||||
get: vi.fn(() => ({ _global: { locale: 'ko' } })),
|
||||
set: vi.fn(),
|
||||
subscribe: vi.fn(() => vi.fn()), // unsubscribe 함수 반환
|
||||
};
|
||||
|
||||
describe('AdminSidebar', () => {
|
||||
const mockMenu: MenuItem[] = [
|
||||
{ id: 1, name: { ko: '대시보드', en: 'Dashboard' }, slug: 'dashboard', url: '/admin', icon: 'fas fa-home', is_active: true },
|
||||
{
|
||||
id: 2,
|
||||
name: { ko: '콘텐츠', en: 'Content' },
|
||||
slug: 'content',
|
||||
icon: 'fas fa-file-text',
|
||||
children: [
|
||||
{ id: 21, name: { ko: '게시물', en: 'Posts' }, slug: 'posts', url: '/admin/posts', icon: 'fas fa-list' },
|
||||
{ id: 22, name: { ko: '페이지', en: 'Pages' }, slug: 'pages', url: '/admin/pages', icon: 'fas fa-file' },
|
||||
],
|
||||
},
|
||||
{ id: 3, name: { ko: '설정', en: 'Settings' }, slug: 'settings', url: '/admin/settings', icon: 'fas fa-cog' },
|
||||
];
|
||||
|
||||
// 원래 G7Core 백업
|
||||
let originalG7Core: any;
|
||||
|
||||
// 각 테스트 전에 G7Core 설정
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// 기존 G7Core를 유지하면서 필요한 속성만 추가/덮어쓰기
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = {
|
||||
...originalG7Core,
|
||||
dispatch: mockDispatch,
|
||||
locale: mockLocale,
|
||||
state: mockState,
|
||||
};
|
||||
});
|
||||
|
||||
// 테스트 후 정리
|
||||
afterEach(() => {
|
||||
(window as any).G7Core = originalG7Core;
|
||||
});
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
expect(screen.getByText('대시보드')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('로고가 표시됨', () => {
|
||||
render(<AdminSidebar logo="/logo.png" logoAlt="Test Logo" menu={mockMenu} />);
|
||||
|
||||
const logo = screen.getByAltText('Test Logo');
|
||||
expect(logo).toBeInTheDocument();
|
||||
expect(logo).toHaveAttribute('src', '/logo.png');
|
||||
});
|
||||
|
||||
it('메뉴 아이템이 모두 표시됨', () => {
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
expect(screen.getByText('대시보드')).toBeInTheDocument();
|
||||
expect(screen.getByText('콘텐츠')).toBeInTheDocument();
|
||||
expect(screen.getByText('설정')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('메뉴 아이템 클릭 시 G7Core.dispatch로 네비게이션', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
const dashboard = screen.getByText('대시보드');
|
||||
await user.click(dashboard);
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledWith({
|
||||
handler: 'navigate',
|
||||
params: { path: '/admin' },
|
||||
});
|
||||
});
|
||||
|
||||
it('하위 메뉴가 있는 아이템 클릭 시 하위 메뉴가 표시됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
const contentButton = screen.getByText('콘텐츠');
|
||||
await user.click(contentButton);
|
||||
|
||||
expect(screen.getByText('게시물')).toBeInTheDocument();
|
||||
expect(screen.getByText('페이지')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('하위 메뉴가 표시된 후 다시 클릭하면 닫힘', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
const contentButton = screen.getByText('콘텐츠');
|
||||
await user.click(contentButton);
|
||||
|
||||
expect(screen.getByText('게시물')).toBeInTheDocument();
|
||||
|
||||
await user.click(contentButton);
|
||||
|
||||
// 하위 메뉴가 닫혀야 하지만 실제로는 DOM에 남아있을 수 있음 (CSS로 숨김)
|
||||
});
|
||||
|
||||
it('collapsed 모드에서 메뉴 라벨이 숨겨짐', () => {
|
||||
render(<AdminSidebar menu={mockMenu} collapsed={true} />);
|
||||
|
||||
// collapsed 모드에서는 텍스트가 DOM에서 제거됨
|
||||
expect(screen.queryByText('대시보드')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('콘텐츠')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('설정')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('토글 버튼을 클릭하면 onToggleCollapse가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggleCollapse = vi.fn();
|
||||
render(<AdminSidebar menu={mockMenu} onToggleCollapse={onToggleCollapse} />);
|
||||
|
||||
const toggleButton = screen.getByLabelText('사이드바 접기');
|
||||
await user.click(toggleButton);
|
||||
|
||||
expect(onToggleCollapse).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('collapsed 모드에서 토글 버튼 라벨이 변경됨', () => {
|
||||
render(<AdminSidebar menu={mockMenu} collapsed={true} onToggleCollapse={vi.fn()} />);
|
||||
|
||||
expect(screen.getByLabelText('사이드바 펼치기')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('collapsed 모드에서 하위 메뉴가 표시되지 않음', () => {
|
||||
render(<AdminSidebar menu={mockMenu} collapsed={true} />);
|
||||
|
||||
// collapsed 모드에서는 하위 메뉴가 표시되지 않음 (텍스트도 없음)
|
||||
expect(screen.queryByText('게시물')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('페이지')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(<AdminSidebar menu={mockMenu} className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
describe('G7Core 통합', () => {
|
||||
it('G7Core.locale.current()에서 로케일을 자동으로 가져옴', () => {
|
||||
mockLocale.current.mockReturnValue('en');
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
// 영어 로케일이므로 영어 메뉴명 표시
|
||||
expect(screen.getByText('Dashboard')).toBeInTheDocument();
|
||||
expect(screen.getByText('Content')).toBeInTheDocument();
|
||||
expect(screen.getByText('Settings')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('currentLocale prop이 G7Core.locale보다 우선 적용됨', () => {
|
||||
mockLocale.current.mockReturnValue('en');
|
||||
render(<AdminSidebar menu={mockMenu} currentLocale="ko" />);
|
||||
|
||||
// currentLocale prop이 우선이므로 한국어 표시
|
||||
expect(screen.getByText('대시보드')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('G7Core.state.subscribe로 로케일 변경 구독', () => {
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
expect(mockState.subscribe).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('컴포넌트 언마운트 시 구독 해제', () => {
|
||||
const unsubscribe = vi.fn();
|
||||
mockState.subscribe.mockReturnValue(unsubscribe);
|
||||
|
||||
const { unmount } = render(<AdminSidebar menu={mockMenu} />);
|
||||
unmount();
|
||||
|
||||
expect(unsubscribe).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('G7Core 없이도 fallback으로 동작함', async () => {
|
||||
// G7Core 제거
|
||||
delete (window as any).G7Core;
|
||||
|
||||
const user = userEvent.setup();
|
||||
|
||||
// window.location.href 모킹
|
||||
const originalLocation = window.location;
|
||||
// @ts-ignore
|
||||
delete window.location;
|
||||
window.location = { ...originalLocation, href: '' } as Location;
|
||||
|
||||
render(<AdminSidebar menu={mockMenu} />);
|
||||
|
||||
const dashboard = screen.getByText('대시보드');
|
||||
await user.click(dashboard);
|
||||
|
||||
expect(window.location.href).toBe('/admin');
|
||||
|
||||
// 원복
|
||||
window.location = originalLocation;
|
||||
});
|
||||
});
|
||||
|
||||
describe('URL 접두사 충돌 시 활성 메뉴 판별 (Issue #37)', () => {
|
||||
const prefixConflictMenu: MenuItem[] = [
|
||||
{ id: 1, name: { ko: '대시보드', en: 'Dashboard' }, slug: 'dashboard', url: '/admin', icon: 'fas fa-home' },
|
||||
{
|
||||
id: 2,
|
||||
name: { ko: '게시판', en: 'Boards' },
|
||||
slug: 'boards',
|
||||
icon: 'fas fa-clipboard',
|
||||
children: [
|
||||
{ id: 21, name: { ko: '게시판 관리', en: 'Board Management' }, slug: 'board-management', url: '/admin/boards', icon: 'fas fa-list' },
|
||||
{ id: 22, name: { ko: '게시판 신고 관리', en: 'Board Reports' }, slug: 'board-reports', url: '/admin/boards/reports', icon: 'fas fa-flag' },
|
||||
],
|
||||
},
|
||||
{ id: 3, name: { ko: '설정', en: 'Settings' }, slug: 'settings', url: '/admin/settings', icon: 'fas fa-cog' },
|
||||
];
|
||||
|
||||
let originalLocation: Location;
|
||||
|
||||
beforeEach(() => {
|
||||
originalLocation = window.location;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.location = originalLocation;
|
||||
});
|
||||
|
||||
const setPathname = (pathname: string) => {
|
||||
// @ts-ignore
|
||||
delete window.location;
|
||||
window.location = { ...originalLocation, pathname } as Location;
|
||||
};
|
||||
|
||||
it('정확한 URL 매칭: /admin/boards에서 "게시판 관리"만 활성화', () => {
|
||||
setPathname('/admin/boards');
|
||||
render(<AdminSidebar menu={prefixConflictMenu} currentLocale="ko" />);
|
||||
|
||||
// "게시판" 부모가 자동 펼침되므로 자식 메뉴가 보임
|
||||
const boardMgmt = screen.getByText('게시판 관리');
|
||||
const boardReports = screen.getByText('게시판 신고 관리');
|
||||
|
||||
// "게시판 관리" 버튼에 활성 스타일 적용
|
||||
expect(boardMgmt.closest('button')).toHaveClass('bg-blue-50');
|
||||
// "게시판 신고 관리" 버튼에 활성 스타일 미적용
|
||||
expect(boardReports.closest('button')).not.toHaveClass('bg-blue-50');
|
||||
});
|
||||
|
||||
it('접두사 충돌 해결: /admin/boards/reports에서 "게시판 신고 관리"만 활성화', () => {
|
||||
setPathname('/admin/boards/reports');
|
||||
render(<AdminSidebar menu={prefixConflictMenu} currentLocale="ko" />);
|
||||
|
||||
const boardMgmt = screen.getByText('게시판 관리');
|
||||
const boardReports = screen.getByText('게시판 신고 관리');
|
||||
|
||||
// "게시판 신고 관리"만 활성 스타일 적용
|
||||
expect(boardReports.closest('button')).toHaveClass('bg-blue-50');
|
||||
// "게시판 관리"는 비활성
|
||||
expect(boardMgmt.closest('button')).not.toHaveClass('bg-blue-50');
|
||||
});
|
||||
|
||||
it('하위 경로에서 가장 가까운 메뉴 활성화: /admin/boards/123', () => {
|
||||
setPathname('/admin/boards/123');
|
||||
render(<AdminSidebar menu={prefixConflictMenu} currentLocale="ko" />);
|
||||
|
||||
const boardMgmt = screen.getByText('게시판 관리');
|
||||
const boardReports = screen.getByText('게시판 신고 관리');
|
||||
|
||||
// "게시판 관리" (/admin/boards)가 가장 긴 접두사 매칭
|
||||
expect(boardMgmt.closest('button')).toHaveClass('bg-blue-50');
|
||||
// "게시판 신고 관리" (/admin/boards/reports)는 매칭 안됨
|
||||
expect(boardReports.closest('button')).not.toHaveClass('bg-blue-50');
|
||||
});
|
||||
|
||||
it('부모 메뉴 자동 펼침: 활성 자식이 있으면 부모 펼침', () => {
|
||||
setPathname('/admin/boards/reports');
|
||||
render(<AdminSidebar menu={prefixConflictMenu} currentLocale="ko" />);
|
||||
|
||||
// "게시판" 부모가 펼쳐져서 자식 메뉴가 보여야 함
|
||||
expect(screen.getByText('게시판 관리')).toBeInTheDocument();
|
||||
expect(screen.getByText('게시판 신고 관리')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('무관한 경로에서는 게시판 메뉴 비활성', () => {
|
||||
setPathname('/admin/settings');
|
||||
render(<AdminSidebar menu={prefixConflictMenu} currentLocale="ko" />);
|
||||
|
||||
// "설정" 메뉴만 활성
|
||||
const settings = screen.getByText('설정');
|
||||
expect(settings.closest('button')).toHaveClass('bg-blue-50');
|
||||
|
||||
// 게시판 관련 하위 메뉴는 부모가 펼쳐지지 않아 DOM에 없음
|
||||
expect(screen.queryByText('게시판 관리')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('게시판 신고 관리')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { Alert } from '../Alert';
|
||||
|
||||
describe('Alert 컴포넌트', () => {
|
||||
describe('기본 렌더링', () => {
|
||||
it('메시지가 렌더링된다', () => {
|
||||
render(<Alert type="info" message="테스트 메시지" />);
|
||||
expect(screen.getByText('테스트 메시지')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('role="alert" 속성이 있다', () => {
|
||||
const { container } = render(<Alert type="info" message="테스트 메시지" />);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('aria-live="polite" 속성이 있다', () => {
|
||||
const { container } = render(<Alert type="info" message="테스트 메시지" />);
|
||||
const alertElement = container.querySelector('[aria-live="polite"]');
|
||||
expect(alertElement).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('type별 렌더링 - info', () => {
|
||||
it('info 타입은 파란색 스타일이 적용된다', () => {
|
||||
const { container } = render(<Alert type="info" message="정보 메시지" />);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('bg-blue-100');
|
||||
expect(alertElement?.className).toContain('border-blue-400');
|
||||
});
|
||||
|
||||
it('info 타입은 info-circle 아이콘이 표시된다', () => {
|
||||
const { container } = render(<Alert type="info" message="정보 메시지" />);
|
||||
const iconElement = container.querySelector('.fa-info-circle');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('info 아이콘에 올바른 aria-label이 있다', () => {
|
||||
const { container } = render(<Alert type="info" message="정보 메시지" />);
|
||||
const iconElement = container.querySelector('[aria-label="info icon"]');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('type별 렌더링 - success', () => {
|
||||
it('success 타입은 초록색 스타일이 적용된다', () => {
|
||||
const { container } = render(<Alert type="success" message="성공 메시지" />);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('bg-green-100');
|
||||
expect(alertElement?.className).toContain('border-green-400');
|
||||
});
|
||||
|
||||
it('success 타입은 check-circle 아이콘이 표시된다', () => {
|
||||
const { container } = render(<Alert type="success" message="성공 메시지" />);
|
||||
const iconElement = container.querySelector('.fa-check-circle');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('success 아이콘에 올바른 aria-label이 있다', () => {
|
||||
const { container } = render(<Alert type="success" message="성공 메시지" />);
|
||||
const iconElement = container.querySelector('[aria-label="success icon"]');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('type별 렌더링 - warning', () => {
|
||||
it('warning 타입은 노란색 스타일이 적용된다', () => {
|
||||
const { container } = render(<Alert type="warning" message="경고 메시지" />);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('bg-yellow-100');
|
||||
expect(alertElement?.className).toContain('border-yellow-400');
|
||||
});
|
||||
|
||||
it('warning 타입은 exclamation-triangle 아이콘이 표시된다', () => {
|
||||
const { container } = render(<Alert type="warning" message="경고 메시지" />);
|
||||
const iconElement = container.querySelector('.fa-exclamation-triangle');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('warning 아이콘에 올바른 aria-label이 있다', () => {
|
||||
const { container } = render(<Alert type="warning" message="경고 메시지" />);
|
||||
const iconElement = container.querySelector('[aria-label="warning icon"]');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('type별 렌더링 - error', () => {
|
||||
it('error 타입은 빨간색 스타일이 적용된다', () => {
|
||||
const { container } = render(<Alert type="error" message="에러 메시지" />);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('bg-red-100');
|
||||
expect(alertElement?.className).toContain('border-red-400');
|
||||
});
|
||||
|
||||
it('error 타입은 times-circle 아이콘이 표시된다', () => {
|
||||
const { container } = render(<Alert type="error" message="에러 메시지" />);
|
||||
const iconElement = container.querySelector('.fa-times-circle');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('error 아이콘에 올바른 aria-label이 있다', () => {
|
||||
const { container } = render(<Alert type="error" message="에러 메시지" />);
|
||||
const iconElement = container.querySelector('[aria-label="error icon"]');
|
||||
expect(iconElement).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('dismissible 옵션', () => {
|
||||
it('dismissible이 false일 때 닫기 버튼이 렌더링되지 않는다', () => {
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" dismissible={false} />
|
||||
);
|
||||
const closeButton = container.querySelector('[aria-label="Close alert"]');
|
||||
expect(closeButton).toBeNull();
|
||||
});
|
||||
|
||||
it('dismissible이 true일 때 닫기 버튼이 렌더링된다', () => {
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" dismissible={true} />
|
||||
);
|
||||
const closeButton = container.querySelector('[aria-label="Close alert"]');
|
||||
expect(closeButton).toBeTruthy();
|
||||
});
|
||||
|
||||
it('dismissible 기본값은 false이다', () => {
|
||||
const { container } = render(<Alert type="info" message="메시지" />);
|
||||
const closeButton = container.querySelector('[aria-label="Close alert"]');
|
||||
expect(closeButton).toBeNull();
|
||||
});
|
||||
|
||||
it('닫기 버튼에 times 아이콘이 표시된다', () => {
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" dismissible={true} />
|
||||
);
|
||||
const closeIcon = container.querySelector('.fa-times');
|
||||
expect(closeIcon).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onDismiss 콜백', () => {
|
||||
it('닫기 버튼 클릭 시 onDismiss 콜백이 호출된다', () => {
|
||||
const onDismiss = vi.fn();
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" dismissible={true} onDismiss={onDismiss} />
|
||||
);
|
||||
|
||||
const closeButton = container.querySelector('[aria-label="Close alert"]') as HTMLElement;
|
||||
expect(closeButton).toBeTruthy();
|
||||
|
||||
fireEvent.click(closeButton);
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('dismissible이 false면 onDismiss는 호출되지 않는다', () => {
|
||||
const onDismiss = vi.fn();
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" dismissible={false} onDismiss={onDismiss} />
|
||||
);
|
||||
|
||||
// 닫기 버튼이 없으므로 클릭할 수 없음
|
||||
const closeButton = container.querySelector('[aria-label="Close alert"]');
|
||||
expect(closeButton).toBeNull();
|
||||
expect(onDismiss).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('닫기 버튼을 여러 번 클릭하면 onDismiss가 여러 번 호출된다', () => {
|
||||
const onDismiss = vi.fn();
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" dismissible={true} onDismiss={onDismiss} />
|
||||
);
|
||||
|
||||
const closeButton = container.querySelector('[aria-label="Close alert"]') as HTMLElement;
|
||||
|
||||
fireEvent.click(closeButton);
|
||||
fireEvent.click(closeButton);
|
||||
fireEvent.click(closeButton);
|
||||
|
||||
expect(onDismiss).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('사용자 정의 Props', () => {
|
||||
it('사용자 정의 클래스가 적용된다', () => {
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" className="custom-alert" />
|
||||
);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('custom-alert');
|
||||
});
|
||||
|
||||
it('사용자 정의 클래스가 기본 클래스와 함께 적용된다', () => {
|
||||
const { container } = render(
|
||||
<Alert type="info" message="메시지" className="custom-class" />
|
||||
);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('custom-class');
|
||||
expect(alertElement?.className).toContain('bg-blue-100');
|
||||
expect(alertElement?.className).toContain('border-blue-400');
|
||||
});
|
||||
});
|
||||
|
||||
describe('복합 시나리오', () => {
|
||||
it('모든 type별 dismissible 알림이 정상 동작한다', () => {
|
||||
const onDismissInfo = vi.fn();
|
||||
const onDismissSuccess = vi.fn();
|
||||
const onDismissWarning = vi.fn();
|
||||
const onDismissError = vi.fn();
|
||||
|
||||
const { container, rerender } = render(
|
||||
<Alert type="info" message="정보" dismissible={true} onDismiss={onDismissInfo} />
|
||||
);
|
||||
|
||||
let closeButton = container.querySelector('[aria-label="Close alert"]') as HTMLElement;
|
||||
fireEvent.click(closeButton);
|
||||
expect(onDismissInfo).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(
|
||||
<Alert type="success" message="성공" dismissible={true} onDismiss={onDismissSuccess} />
|
||||
);
|
||||
closeButton = container.querySelector('[aria-label="Close alert"]') as HTMLElement;
|
||||
fireEvent.click(closeButton);
|
||||
expect(onDismissSuccess).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(
|
||||
<Alert type="warning" message="경고" dismissible={true} onDismiss={onDismissWarning} />
|
||||
);
|
||||
closeButton = container.querySelector('[aria-label="Close alert"]') as HTMLElement;
|
||||
fireEvent.click(closeButton);
|
||||
expect(onDismissWarning).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(
|
||||
<Alert type="error" message="에러" dismissible={true} onDismiss={onDismissError} />
|
||||
);
|
||||
closeButton = container.querySelector('[aria-label="Close alert"]') as HTMLElement;
|
||||
fireEvent.click(closeButton);
|
||||
expect(onDismissError).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('긴 메시지도 정상적으로 표시된다', () => {
|
||||
const longMessage = '이것은 매우 긴 메시지입니다. '.repeat(10);
|
||||
const { container } = render(<Alert type="info" message={longMessage} />);
|
||||
// p 태그에서 메시지 확인
|
||||
const messageElement = container.querySelector('p');
|
||||
expect(messageElement?.textContent).toBe(longMessage);
|
||||
});
|
||||
});
|
||||
|
||||
describe('다크 모드 클래스', () => {
|
||||
it('다크 모드 클래스가 포함된다', () => {
|
||||
const { container } = render(<Alert type="info" message="메시지" />);
|
||||
const alertElement = container.querySelector('[role="alert"]');
|
||||
expect(alertElement?.className).toContain('dark:bg-blue-900');
|
||||
expect(alertElement?.className).toContain('dark:border-blue-600');
|
||||
});
|
||||
});
|
||||
});
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { AlertDialog } from '../AlertDialog';
|
||||
|
||||
describe('AlertDialog', () => {
|
||||
const mockProps = {
|
||||
isOpen: true,
|
||||
onClose: vi.fn(),
|
||||
title: '알림',
|
||||
message: '작업이 완료되었습니다.',
|
||||
};
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<AlertDialog {...mockProps} />);
|
||||
|
||||
expect(screen.getByText('알림')).toBeInTheDocument();
|
||||
expect(screen.getByText('작업이 완료되었습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('isOpen이 false일 때 렌더링되지 않음', () => {
|
||||
render(<AlertDialog {...mockProps} isOpen={false} />);
|
||||
|
||||
expect(screen.queryByText('알림')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('확인 버튼이 표시됨', () => {
|
||||
render(<AlertDialog {...mockProps} />);
|
||||
|
||||
expect(screen.getByText('확인')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('커스텀 확인 버튼 텍스트가 표시됨', () => {
|
||||
render(<AlertDialog {...mockProps} confirmText="닫기" />);
|
||||
|
||||
expect(screen.getByText('닫기')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('확인 버튼 클릭 시 onConfirm과 onClose가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onConfirm = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<AlertDialog
|
||||
{...mockProps}
|
||||
onConfirm={onConfirm}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
|
||||
const confirmButton = screen.getByText('확인');
|
||||
await user.click(confirmButton);
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('React 노드를 message로 사용할 수 있음', () => {
|
||||
render(
|
||||
<AlertDialog
|
||||
{...mockProps}
|
||||
message={<div>커스텀 <strong>메시지</strong></div>}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('커스텀')).toBeInTheDocument();
|
||||
expect(screen.getByText('메시지')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('confirmButtonVariant prop이 적용됨', () => {
|
||||
render(
|
||||
<AlertDialog
|
||||
{...mockProps}
|
||||
confirmButtonVariant="danger"
|
||||
/>
|
||||
);
|
||||
|
||||
const confirmButton = screen.getByText('확인');
|
||||
expect(confirmButton).toHaveClass('bg-red-600');
|
||||
});
|
||||
|
||||
it('closeOnOverlay가 false일 때 오버레이 클릭 시 닫히지 않음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<AlertDialog
|
||||
{...mockProps}
|
||||
onClose={onClose}
|
||||
closeOnOverlay={false}
|
||||
/>
|
||||
);
|
||||
|
||||
// Dialog 컴포넌트의 오버레이를 찾아 클릭
|
||||
const overlay = screen.getByRole('dialog').parentElement?.querySelector('.bg-black');
|
||||
if (overlay) {
|
||||
await user.click(overlay as Element);
|
||||
}
|
||||
|
||||
// closeOnOverlay가 false이므로 onClose가 호출되지 않아야 함
|
||||
// 하지만 Dialog 내부 구현에 따라 다를 수 있음
|
||||
});
|
||||
});
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Breadcrumb, BreadcrumbItem } from '../Breadcrumb';
|
||||
|
||||
describe('Breadcrumb', () => {
|
||||
const mockItems: BreadcrumbItem[] = [
|
||||
{ label: '대시보드', href: '/admin' },
|
||||
{ label: '사용자 관리', href: '/admin/users' },
|
||||
{ label: '사용자 목록' },
|
||||
];
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<Breadcrumb items={mockItems} />);
|
||||
|
||||
expect(screen.getByText('대시보드')).toBeInTheDocument();
|
||||
expect(screen.getByText('사용자 관리')).toBeInTheDocument();
|
||||
expect(screen.getByText('사용자 목록')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('showHome이 true일 때 Home 아이템이 표시됨', () => {
|
||||
render(<Breadcrumb items={mockItems} showHome={true} />);
|
||||
|
||||
expect(screen.getByText('Home')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('링크가 있는 아이템은 클릭 가능함', () => {
|
||||
render(<Breadcrumb items={mockItems} />);
|
||||
|
||||
const dashboardLink = screen.getByText('대시보드').closest('a');
|
||||
expect(dashboardLink).toHaveAttribute('href', '/admin');
|
||||
});
|
||||
|
||||
it('마지막 아이템은 링크가 아님', () => {
|
||||
render(<Breadcrumb items={mockItems} />);
|
||||
|
||||
const lastItem = screen.getByText('사용자 목록');
|
||||
expect(lastItem.tagName).toBe('SPAN');
|
||||
expect(lastItem.closest('a')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('onClick 핸들러가 있는 아이템 클릭 시 핸들러가 호출됨', () => {
|
||||
const onClickMock = vi.fn();
|
||||
const itemsWithClick: BreadcrumbItem[] = [
|
||||
{ label: '첫 번째', href: '/first' },
|
||||
{ label: '클릭 가능', onClick: onClickMock },
|
||||
{ label: '마지막' },
|
||||
];
|
||||
|
||||
render(<Breadcrumb items={itemsWithClick} />);
|
||||
|
||||
const clickableItem = screen.getByText('클릭 가능').closest('a');
|
||||
fireEvent.click(clickableItem!);
|
||||
|
||||
expect(onClickMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('maxItems를 초과하면 중간이 생략됨', () => {
|
||||
const manyItems: BreadcrumbItem[] = [
|
||||
{ label: '1', href: '/1' },
|
||||
{ label: '2', href: '/2' },
|
||||
{ label: '3', href: '/3' },
|
||||
{ label: '4', href: '/4' },
|
||||
{ label: '5', href: '/5' },
|
||||
{ label: '6', href: '/6' },
|
||||
];
|
||||
|
||||
render(<Breadcrumb items={manyItems} maxItems={3} />);
|
||||
|
||||
expect(screen.getByText('1')).toBeInTheDocument();
|
||||
expect(screen.getByText('...')).toBeInTheDocument();
|
||||
expect(screen.getByText('6')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('커스텀 separator가 표시됨', () => {
|
||||
render(<Breadcrumb items={mockItems} separator={<span>/</span>} />);
|
||||
|
||||
expect(screen.getByText('대시보드')).toBeInTheDocument();
|
||||
// separator는 aria-hidden이므로 직접 테스트하기 어려움
|
||||
});
|
||||
|
||||
it('homeHref prop이 적용됨', () => {
|
||||
render(
|
||||
<Breadcrumb
|
||||
items={mockItems}
|
||||
showHome={true}
|
||||
homeHref="/dashboard"
|
||||
/>
|
||||
);
|
||||
|
||||
const homeLink = screen.getByText('Home').closest('a');
|
||||
expect(homeLink).toHaveAttribute('href', '/dashboard');
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<Breadcrumb items={mockItems} className="custom-class" />
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Card } from '../Card';
|
||||
|
||||
describe('Card', () => {
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<Card />);
|
||||
|
||||
// 카드 컨테이너가 렌더링되는지 확인
|
||||
const { container } = render(<Card />);
|
||||
expect(container.firstChild).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('title이 표시됨', () => {
|
||||
render(<Card title="테스트 제목" />);
|
||||
|
||||
expect(screen.getByText('테스트 제목')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('content가 표시됨', () => {
|
||||
render(<Card content="테스트 내용" />);
|
||||
|
||||
expect(screen.getByText('테스트 내용')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('이미지가 표시됨', () => {
|
||||
render(<Card imageUrl="/test.png" imageAlt="테스트 이미지" />);
|
||||
|
||||
const image = screen.getByAltText('테스트 이미지');
|
||||
expect(image).toBeInTheDocument();
|
||||
expect(image).toHaveAttribute('src', '/test.png');
|
||||
});
|
||||
|
||||
it('title과 content가 함께 표시됨', () => {
|
||||
render(
|
||||
<Card
|
||||
title="제목"
|
||||
content="내용"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('제목')).toBeInTheDocument();
|
||||
expect(screen.getByText('내용')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('onClick 핸들러가 있을 때 카드 클릭 시 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
|
||||
const { container } = render(<Card title="클릭 가능한 카드" onClick={onClickMock} />);
|
||||
|
||||
const card = container.firstChild as HTMLElement;
|
||||
await user.click(card);
|
||||
|
||||
expect(onClickMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('모든 props가 함께 표시됨', () => {
|
||||
render(
|
||||
<Card
|
||||
title="완전한 카드"
|
||||
content="설명 텍스트"
|
||||
imageUrl="/card-image.png"
|
||||
imageAlt="카드 이미지"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('완전한 카드')).toBeInTheDocument();
|
||||
expect(screen.getByText('설명 텍스트')).toBeInTheDocument();
|
||||
expect(screen.getByAltText('카드 이미지')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(<Card className="custom-card" />);
|
||||
expect(container.firstChild).toHaveClass('custom-card');
|
||||
});
|
||||
|
||||
it('style prop이 적용됨', () => {
|
||||
const { container } = render(<Card style={{ marginTop: '20px' }} />);
|
||||
const card = container.querySelector('.bg-white');
|
||||
expect(card).toHaveStyle({ marginTop: '20px' });
|
||||
});
|
||||
});
|
||||
+622
@@ -0,0 +1,622 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { CardGrid, CardGridCellChild } from '../CardGrid';
|
||||
|
||||
// renderItemChildren 모킹 함수 정의
|
||||
const mockRenderItemChildren = vi.fn((children, context, componentMap, keyPrefix) => {
|
||||
return children.map((child: CardGridCellChild, index: number) => {
|
||||
const key = `${keyPrefix}-${child.id || child.name}-${index}`;
|
||||
const Component = componentMap[child.name];
|
||||
|
||||
if (!Component) return null;
|
||||
|
||||
let text = child.text;
|
||||
if (text && text.includes('{{row.')) {
|
||||
const match = text.match(/\{\{row\.(\w+)\}\}/);
|
||||
if (match) {
|
||||
const field = match[1];
|
||||
text = context.row[field];
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Component key={key} {...child.props}>
|
||||
{text}
|
||||
{child.children && mockRenderItemChildren(child.children, context, componentMap, `${key}-child`)}
|
||||
</Component>
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CardGrid', () => {
|
||||
const mockCardChildren: CardGridCellChild[] = [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: {
|
||||
className: 'bg-white dark:bg-gray-800 rounded-lg p-6',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'H3',
|
||||
text: '{{row.name}}',
|
||||
props: {
|
||||
className: 'text-lg font-semibold mb-2',
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'P',
|
||||
text: '{{row.description}}',
|
||||
props: {
|
||||
className: 'text-gray-600 dark:text-gray-400',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const mockData = [
|
||||
{ id: 1, name: '게시판 1', description: '설명 1' },
|
||||
{ id: 2, name: '게시판 2', description: '설명 2' },
|
||||
{ id: 3, name: '게시판 3', description: '설명 3' },
|
||||
];
|
||||
|
||||
// mockG7Core 참조 변수 (beforeEach에서 초기화)
|
||||
let mockG7Core: any;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// 기존 G7Core를 유지하면서 renderItemChildren만 추가/덮어쓰기
|
||||
mockG7Core = {
|
||||
...(window as any).G7Core,
|
||||
renderItemChildren: mockRenderItemChildren,
|
||||
};
|
||||
(window as any).G7Core = mockG7Core;
|
||||
});
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid data={mockData} cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]} />
|
||||
);
|
||||
expect(container.firstChild).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('데이터가 undefined일 때 Skeleton이 표시됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid data={undefined} cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]} gridColumns={3} />
|
||||
);
|
||||
|
||||
// Skeleton 카드가 3개 렌더링되는지 확인 (gridColumns 기반)
|
||||
// 각 스켈레톤 카드 컨테이너를 선택
|
||||
const skeletonCards = container.querySelectorAll('.bg-white.dark\\:bg-gray-800.border');
|
||||
expect(skeletonCards).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('데이터가 빈 배열일 때 Empty State가 표시됨', () => {
|
||||
render(<CardGrid data={[]} cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]} emptyMessage="데이터가 없습니다." />);
|
||||
|
||||
expect(screen.getByText('데이터가 없습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('카드 그리드가 렌더링됨', () => {
|
||||
render(<CardGrid data={mockData} cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]} />);
|
||||
|
||||
// G7Core.renderItemChildren가 데이터 개수만큼 호출되는지 확인
|
||||
expect(mockG7Core.renderItemChildren).toHaveBeenCalledTimes(mockData.length);
|
||||
});
|
||||
|
||||
it('columns prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid data={mockData} cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]} gridColumns={2} />
|
||||
);
|
||||
|
||||
const gridElement = container.querySelector('.grid');
|
||||
expect(gridElement).toHaveClass('lg:grid-cols-2');
|
||||
});
|
||||
|
||||
it('gap prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid data={mockData} cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]} gap={6} />
|
||||
);
|
||||
|
||||
const gridElement = container.querySelector('.grid');
|
||||
expect(gridElement).toHaveClass('gap-6');
|
||||
});
|
||||
|
||||
it('반응형 columns 설정이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
gridColumns={3}
|
||||
responsiveColumns={{ sm: 1, md: 2, lg: 3, xl: 4 }}
|
||||
/>
|
||||
);
|
||||
|
||||
const gridElement = container.querySelector('.grid');
|
||||
expect(gridElement).toHaveClass('grid-cols-1');
|
||||
expect(gridElement).toHaveClass('md:grid-cols-2');
|
||||
expect(gridElement).toHaveClass('lg:grid-cols-3');
|
||||
expect(gridElement).toHaveClass('xl:grid-cols-4');
|
||||
});
|
||||
|
||||
it('페이지네이션이 활성화되면 페이지 버튼이 표시됨', () => {
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={12}
|
||||
/>
|
||||
);
|
||||
|
||||
// 버튼은 aria-label로 찾기 (기본값은 ‹, › 기호)
|
||||
expect(screen.getByLabelText('이전 페이지')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('다음 페이지')).toBeInTheDocument();
|
||||
// 페이지 번호 버튼이 표시됨 (1, 2, 3)
|
||||
expect(screen.getByText('1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('페이지네이션이 비활성화되면 모든 데이터가 표시됨', () => {
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={false}
|
||||
/>
|
||||
);
|
||||
|
||||
// 모든 데이터가 렌더링됨
|
||||
expect(mockG7Core.renderItemChildren).toHaveBeenCalledTimes(25);
|
||||
|
||||
// 페이지네이션 버튼이 없음
|
||||
expect(screen.queryByLabelText('이전 페이지')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('다음 페이지')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('다음 버튼 클릭 시 다음 페이지로 이동함', async () => {
|
||||
const user = userEvent.setup();
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={12}
|
||||
/>
|
||||
);
|
||||
|
||||
const nextButton = screen.getByLabelText('다음 페이지');
|
||||
await user.click(nextButton);
|
||||
|
||||
// 페이지 2가 활성화됨 (aria-current="page" 확인)
|
||||
const page2Button = screen.getByLabelText('페이지 2');
|
||||
expect(page2Button).toHaveAttribute('aria-current', 'page');
|
||||
});
|
||||
|
||||
it('이전 버튼 클릭 시 이전 페이지로 이동함', async () => {
|
||||
const user = userEvent.setup();
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={12}
|
||||
/>
|
||||
);
|
||||
|
||||
const nextButton = screen.getByLabelText('다음 페이지');
|
||||
await user.click(nextButton);
|
||||
await user.click(nextButton);
|
||||
|
||||
// 페이지 3이 활성화됨
|
||||
expect(screen.getByLabelText('페이지 3')).toHaveAttribute('aria-current', 'page');
|
||||
|
||||
const prevButton = screen.getByLabelText('이전 페이지');
|
||||
await user.click(prevButton);
|
||||
|
||||
// 페이지 2가 활성화됨
|
||||
expect(screen.getByLabelText('페이지 2')).toHaveAttribute('aria-current', 'page');
|
||||
});
|
||||
|
||||
it('첫 페이지에서 이전 버튼이 비활성화됨', () => {
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={12}
|
||||
/>
|
||||
);
|
||||
|
||||
const prevButton = screen.getByLabelText('이전 페이지');
|
||||
expect(prevButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('마지막 페이지에서 다음 버튼이 비활성화됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={12}
|
||||
/>
|
||||
);
|
||||
|
||||
const nextButton = screen.getByLabelText('다음 페이지');
|
||||
await user.click(nextButton);
|
||||
await user.click(nextButton);
|
||||
|
||||
// 페이지 3이 활성화됨 (마지막 페이지)
|
||||
expect(screen.getByLabelText('페이지 3')).toHaveAttribute('aria-current', 'page');
|
||||
expect(nextButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('서버 사이드 페이지네이션이 작동함', () => {
|
||||
const onPageChange = vi.fn();
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
serverSidePagination={true}
|
||||
serverCurrentPage={1}
|
||||
serverTotalPages={5}
|
||||
onPageChange={onPageChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// 페이지 1이 활성화되어 있음
|
||||
expect(screen.getByLabelText('페이지 1')).toHaveAttribute('aria-current', 'page');
|
||||
// 총 5페이지이므로 페이지 5 버튼도 표시됨
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('서버 사이드 페이지네이션 다음 버튼 클릭 시 onPageChange 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onPageChange = vi.fn();
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
serverSidePagination={true}
|
||||
serverCurrentPage={1}
|
||||
serverTotalPages={5}
|
||||
onPageChange={onPageChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const nextButton = screen.getByLabelText('다음 페이지');
|
||||
await user.click(nextButton);
|
||||
|
||||
expect(onPageChange).toHaveBeenCalledWith(2);
|
||||
});
|
||||
|
||||
it('alwaysShowPagination이 true면 1페이지여도 페이지네이션이 표시됨', () => {
|
||||
render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={10}
|
||||
alwaysShowPagination={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText('이전 페이지')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('다음 페이지')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('alwaysShowPagination이 false면 1페이지일 때 페이지네이션이 숨겨짐', () => {
|
||||
render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={10}
|
||||
alwaysShowPagination={false}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByLabelText('이전 페이지')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('다음 페이지')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
className="custom-grid"
|
||||
/>
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-grid');
|
||||
});
|
||||
|
||||
it('cardClassName prop이 각 카드에 적용됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={mockData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
cardClassName="custom-card"
|
||||
/>
|
||||
);
|
||||
|
||||
const cards = container.querySelectorAll('.custom-card');
|
||||
expect(cards).toHaveLength(mockData.length);
|
||||
});
|
||||
|
||||
it('prevText와 nextText 커스터마이징이 적용됨', () => {
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
name: `게시판 ${i + 1}`,
|
||||
description: `설명 ${i + 1}`,
|
||||
}));
|
||||
|
||||
render(
|
||||
<CardGrid
|
||||
data={manyData}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
pagination={true}
|
||||
pageSize={12}
|
||||
prevText="Previous"
|
||||
nextText="Next"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Previous')).toBeInTheDocument();
|
||||
expect(screen.getByText('Next')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('emptyMessage 커스터마이징이 적용됨', () => {
|
||||
render(
|
||||
<CardGrid
|
||||
data={[]}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
emptyMessage="No boards available"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('No boards available')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('스켈레톤 자동 생성', () => {
|
||||
it('cellChildren 기반으로 스켈레톤이 자동 생성됨', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{
|
||||
id: 'test',
|
||||
cellChildren: [
|
||||
{ type: 'basic', name: 'H3', text: '{{row.title}}' },
|
||||
{ type: 'basic', name: 'P', text: '{{row.description}}' },
|
||||
],
|
||||
}]}
|
||||
gridColumns={2}
|
||||
/>
|
||||
);
|
||||
|
||||
// 스켈레톤 카드가 2개 생성됨
|
||||
const skeletonCards = container.querySelectorAll('.bg-white.dark\\:bg-gray-800');
|
||||
expect(skeletonCards).toHaveLength(2);
|
||||
|
||||
// 각 카드 안에 스켈레톤 요소가 있음 (H3, P에 대응)
|
||||
const skeletonBars = container.querySelectorAll('.h-4.bg-gray-200.dark\\:bg-gray-700.rounded.w-full.animate-pulse');
|
||||
expect(skeletonBars.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('skeletonCellChildren으로 커스텀 스켈레톤 사용 가능', () => {
|
||||
// 커스텀 스켈레톤을 Div 구조로 정의 (Div는 className이 유지됨)
|
||||
const customSkeleton: CardGridCellChild[] = [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'custom-skeleton-wrapper' },
|
||||
children: [
|
||||
{ type: 'basic', name: 'H3', text: '제목' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
skeletonCellChildren={customSkeleton}
|
||||
gridColumns={1}
|
||||
/>
|
||||
);
|
||||
|
||||
// 커스텀 스켈레톤 Div 구조가 사용됨
|
||||
const customWrapper = container.querySelectorAll('.custom-skeleton-wrapper');
|
||||
expect(customWrapper).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('showSkeleton={false}면 스켈레톤이 표시되지 않음', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
showSkeleton={false}
|
||||
/>
|
||||
);
|
||||
|
||||
// 스켈레톤 요소가 없음
|
||||
const skeletons = container.querySelectorAll('.animate-pulse');
|
||||
expect(skeletons).toHaveLength(0);
|
||||
|
||||
// 빈 화면 (null 반환)
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('skeletonCount로 스켈레톤 개수 제어 가능', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: mockCardChildren }]}
|
||||
gridColumns={3}
|
||||
skeletonCount={5}
|
||||
/>
|
||||
);
|
||||
|
||||
// skeletonCount에 지정된 개수만큼 생성 (border 클래스로 카드 컨테이너만 선택)
|
||||
const skeletonCards = container.querySelectorAll('.border.border-gray-200');
|
||||
expect(skeletonCards).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('iteration이 있는 요소는 1개만 표시됨', () => {
|
||||
const iterationChildren: CardGridCellChild[] = [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: {
|
||||
source: '{{row.items}}',
|
||||
item_var: 'item',
|
||||
},
|
||||
children: [
|
||||
{ type: 'basic', name: 'P', text: '{{item.name}}' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: iterationChildren }]}
|
||||
gridColumns={1}
|
||||
/>
|
||||
);
|
||||
|
||||
// iteration 요소가 1개만 생성됨
|
||||
const skeletonCards = container.querySelectorAll('.bg-white.dark\\:bg-gray-800');
|
||||
expect(skeletonCards).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('condition이 있는 요소는 스켈레톤에서 제외됨', () => {
|
||||
const conditionalChildren: CardGridCellChild[] = [
|
||||
{ type: 'basic', name: 'H3', text: '항상 표시' },
|
||||
{ type: 'basic', name: 'P', text: '조건부', condition: '{{row.isActive}}' },
|
||||
{ type: 'basic', name: 'P', text: '조건부2', if: '{{row.status === "active"}}' },
|
||||
];
|
||||
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: conditionalChildren }]}
|
||||
gridColumns={1}
|
||||
/>
|
||||
);
|
||||
|
||||
// H3만 스켈레톤 생성 (condition/if 요소는 제외)
|
||||
const skeletonBars = container.querySelectorAll('.h-4.bg-gray-200.dark\\:bg-gray-700.rounded.w-full.animate-pulse');
|
||||
expect(skeletonBars).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('Div는 구조를 유지하며 자식을 재귀적으로 처리함', () => {
|
||||
// 중첩된 Div 구조 (자식이 없는 Div는 기본 스켈레톤으로 변환됨)
|
||||
const nestedChildren: CardGridCellChild[] = [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'nested-container' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'nested-child-1' },
|
||||
children: [
|
||||
{ type: 'basic', name: 'H3', text: '제목' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'nested-child-2' },
|
||||
children: [
|
||||
{ type: 'basic', name: 'P', text: '설명' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: nestedChildren }]}
|
||||
gridColumns={1}
|
||||
/>
|
||||
);
|
||||
|
||||
// 최상위 Div 구조가 유지됨
|
||||
const nestedContainer = container.querySelector('.nested-container');
|
||||
expect(nestedContainer).toBeInTheDocument();
|
||||
|
||||
// 자식 Div 구조도 유지됨
|
||||
const nestedChild1 = container.querySelector('.nested-child-1');
|
||||
const nestedChild2 = container.querySelector('.nested-child-2');
|
||||
expect(nestedChild1).toBeInTheDocument();
|
||||
expect(nestedChild2).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cellChildren이 비어있으면 null을 반환함', () => {
|
||||
const { container } = render(
|
||||
<CardGrid
|
||||
data={undefined}
|
||||
cardColumns={[{ id: 'test', cellChildren: [] }]}
|
||||
gridColumns={1}
|
||||
/>
|
||||
);
|
||||
|
||||
// 스켈레톤 카드는 생성되지만 내부가 비어있음
|
||||
const skeletonCards = container.querySelectorAll('.bg-white.dark\\:bg-gray-800');
|
||||
expect(skeletonCards).toHaveLength(1);
|
||||
|
||||
// 카드 내부에 스켈레톤 바가 없음
|
||||
const skeletonBars = skeletonCards[0].querySelectorAll('.h-4.bg-gray-200.dark\\:bg-gray-700.rounded.w-full.animate-pulse');
|
||||
expect(skeletonBars).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { CategoryTree, CategoryNode } from '../CategoryTree';
|
||||
|
||||
const mockTreeData: CategoryNode[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Electronics',
|
||||
localized_name: '전자기기',
|
||||
products_count: 42,
|
||||
children: [
|
||||
{
|
||||
id: 2,
|
||||
name: 'Phones',
|
||||
localized_name: '스마트폰',
|
||||
products_count: 20,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'Laptops',
|
||||
localized_name: '노트북',
|
||||
products_count: 15,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: 'Clothing',
|
||||
localized_name: '의류',
|
||||
products_count: 30,
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
|
||||
describe('CategoryTree', () => {
|
||||
it('트리 데이터가 렌더링됨', () => {
|
||||
render(<CategoryTree data={mockTreeData} />);
|
||||
|
||||
expect(screen.getByTestId('category-node-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('전자기기')).toBeInTheDocument();
|
||||
expect(screen.getByText('의류')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('빈 데이터일 때 빈 상태 메시지 표시', () => {
|
||||
render(<CategoryTree data={[]} />);
|
||||
|
||||
expect(screen.getByText('데이터가 없습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('data 미전달 시 빈 상태 메시지 표시', () => {
|
||||
render(<CategoryTree />);
|
||||
|
||||
expect(screen.getByText('데이터가 없습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('localized_name이 없으면 name으로 표시', () => {
|
||||
const data: CategoryNode[] = [
|
||||
{ id: 1, name: 'Fallback Name', children: [] },
|
||||
];
|
||||
render(<CategoryTree data={data} />);
|
||||
|
||||
expect(screen.getByText('Fallback Name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('자식 노드가 있으면 토글 버튼 표시', () => {
|
||||
render(<CategoryTree data={mockTreeData} />);
|
||||
|
||||
// 전자기기(id=1)는 자식이 있으므로 토글 버튼 존재
|
||||
expect(screen.getByTestId('toggle-1')).toBeInTheDocument();
|
||||
// 의류(id=4)는 자식이 없으므로 토글 버튼 없음
|
||||
expect(screen.queryByTestId('toggle-4')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('접힌 상태에서 자식 노드가 보이지 않음', () => {
|
||||
render(<CategoryTree data={mockTreeData} expandedIds={[]} />);
|
||||
|
||||
// 자식 노드 컨테이너가 없어야 함
|
||||
expect(screen.queryByTestId('children-1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('스마트폰')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('펼친 상태에서 자식 노드가 보임', () => {
|
||||
render(<CategoryTree data={mockTreeData} expandedIds={[1]} />);
|
||||
|
||||
expect(screen.getByTestId('children-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('스마트폰')).toBeInTheDocument();
|
||||
expect(screen.getByText('노트북')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('토글 클릭 시 onToggle 콜백 호출 (펼치기)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggle = vi.fn();
|
||||
|
||||
render(
|
||||
<CategoryTree data={mockTreeData} expandedIds={[]} onToggle={onToggle} />
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('toggle-1'));
|
||||
|
||||
expect(onToggle).toHaveBeenCalledWith([1]);
|
||||
});
|
||||
|
||||
it('토글 클릭 시 onToggle 콜백 호출 (접기)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggle = vi.fn();
|
||||
|
||||
render(
|
||||
<CategoryTree
|
||||
data={mockTreeData}
|
||||
expandedIds={[1]}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('toggle-1'));
|
||||
|
||||
expect(onToggle).toHaveBeenCalledWith([]);
|
||||
});
|
||||
|
||||
it('카테고리 이름 클릭 시 토글 (자식 있는 경우)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggle = vi.fn();
|
||||
|
||||
render(
|
||||
<CategoryTree data={mockTreeData} expandedIds={[]} onToggle={onToggle} />
|
||||
);
|
||||
|
||||
await user.click(screen.getByText('전자기기'));
|
||||
|
||||
expect(onToggle).toHaveBeenCalledWith([1]);
|
||||
});
|
||||
|
||||
it('selectable=true일 때 체크박스 표시', () => {
|
||||
render(<CategoryTree data={mockTreeData} selectable />);
|
||||
|
||||
expect(screen.getByTestId('checkbox-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('checkbox-4')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('selectable=false일 때 체크박스 미표시', () => {
|
||||
render(<CategoryTree data={mockTreeData} />);
|
||||
|
||||
expect(screen.queryByTestId('checkbox-1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('체크박스 클릭 시 onSelectionChange 콜백 호출 (선택)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSelectionChange = vi.fn();
|
||||
|
||||
render(
|
||||
<CategoryTree
|
||||
data={mockTreeData}
|
||||
selectable
|
||||
selectedIds={[]}
|
||||
onSelectionChange={onSelectionChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const checkbox = screen.getByTestId('checkbox-1');
|
||||
await user.click(checkbox);
|
||||
|
||||
expect(onSelectionChange).toHaveBeenCalledWith([1]);
|
||||
});
|
||||
|
||||
it('체크박스 클릭 시 onSelectionChange 콜백 호출 (선택 해제)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSelectionChange = vi.fn();
|
||||
|
||||
render(
|
||||
<CategoryTree
|
||||
data={mockTreeData}
|
||||
selectable
|
||||
selectedIds={[1, 4]}
|
||||
onSelectionChange={onSelectionChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const checkbox = screen.getByTestId('checkbox-1');
|
||||
await user.click(checkbox);
|
||||
|
||||
expect(onSelectionChange).toHaveBeenCalledWith([4]);
|
||||
});
|
||||
|
||||
it('showProductCount=true일 때 상품 수 표시', () => {
|
||||
render(<CategoryTree data={mockTreeData} showProductCount />);
|
||||
|
||||
expect(screen.getByText('42')).toBeInTheDocument();
|
||||
expect(screen.getByText('30')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('showProductCount=false일 때 상품 수 미표시', () => {
|
||||
render(<CategoryTree data={mockTreeData} />);
|
||||
|
||||
expect(screen.queryByText('42')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('searchKeyword로 매칭되는 텍스트가 하이라이트됨', () => {
|
||||
const { container } = render(
|
||||
<CategoryTree data={mockTreeData} searchKeyword="전자" />
|
||||
);
|
||||
|
||||
// 하이라이트된 span이 bg-yellow-200 클래스를 가짐
|
||||
const highlighted = container.querySelector('.bg-yellow-200');
|
||||
expect(highlighted).toBeInTheDocument();
|
||||
expect(highlighted?.textContent).toBe('전자');
|
||||
});
|
||||
|
||||
it('searchKeyword로 매칭되지 않는 노드가 숨겨짐', () => {
|
||||
render(<CategoryTree data={mockTreeData} searchKeyword="스마트폰" />);
|
||||
|
||||
// 스마트폰은 전자기기의 자식이므로, 전자기기 노드는 보임 (서브트리에 매칭)
|
||||
expect(screen.getByTestId('category-node-1')).toBeInTheDocument();
|
||||
// 의류는 매칭되지 않으므로 숨김
|
||||
expect(screen.queryByTestId('category-node-4')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<CategoryTree data={mockTreeData} className="custom-class" />
|
||||
);
|
||||
|
||||
expect(container.firstElementChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { ChipCheckbox } from '../ChipCheckbox';
|
||||
|
||||
describe('ChipCheckbox', () => {
|
||||
describe('기본 렌더링', () => {
|
||||
it('라벨을 렌더링해야 함', () => {
|
||||
render(<ChipCheckbox value="test" label="테스트 라벨" />);
|
||||
|
||||
expect(screen.getByText('테스트 라벨')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('체크박스 input이 hidden으로 렌더링되어야 함', () => {
|
||||
const { container } = render(<ChipCheckbox value="test" label="테스트" />);
|
||||
|
||||
const checkbox = container.querySelector('input[type="checkbox"]');
|
||||
expect(checkbox).toBeInTheDocument();
|
||||
expect(checkbox).toHaveClass('hidden');
|
||||
});
|
||||
|
||||
it('아이콘이 지정되면 렌더링해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" icon="clock" />
|
||||
);
|
||||
|
||||
const icon = container.querySelector('i[role="img"]');
|
||||
expect(icon).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('아이콘이 없으면 아이콘을 렌더링하지 않아야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" />
|
||||
);
|
||||
|
||||
const icon = container.querySelector('i[role="img"]');
|
||||
expect(icon).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('variant 스타일', () => {
|
||||
it('기본 variant는 blue여야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('bg-blue-50');
|
||||
});
|
||||
|
||||
it('checked 상태에서 variant 스타일이 적용되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" variant="green" checked={true} />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('bg-green-600');
|
||||
expect(label).toHaveClass('text-white');
|
||||
});
|
||||
|
||||
it('unchecked 상태에서 variant 스타일이 적용되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" variant="orange" checked={false} />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('bg-orange-50');
|
||||
expect(label).toHaveClass('text-orange-600');
|
||||
});
|
||||
|
||||
const variants = ['green', 'orange', 'yellow', 'gray', 'blue'] as const;
|
||||
|
||||
variants.forEach((variant) => {
|
||||
it(`variant="${variant}" unchecked 스타일이 적용되어야 함`, () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" variant={variant} checked={false} />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toBeTruthy();
|
||||
// 모든 variant에 기본 스타일이 적용되어야 함
|
||||
expect(label).toHaveClass('inline-flex');
|
||||
expect(label).toHaveClass('rounded-lg');
|
||||
});
|
||||
|
||||
it(`variant="${variant}" checked 스타일이 적용되어야 함`, () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" variant={variant} checked={true} />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('text-white');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('customColor prop', () => {
|
||||
it('customColor가 있으면 variant를 무시하고 인라인 스타일을 적용해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
variant="green"
|
||||
customColor="#FF5733"
|
||||
checked={false}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
// variant 클래스가 적용되지 않아야 함
|
||||
expect(label).not.toHaveClass('bg-green-50');
|
||||
// 인라인 스타일이 적용되어야 함
|
||||
expect(label).toHaveStyle({ color: '#FF5733' });
|
||||
});
|
||||
|
||||
it('customColor checked 상태에서 배경색이 커스텀 색상이어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#FF5733"
|
||||
checked={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveStyle({
|
||||
backgroundColor: '#FF5733',
|
||||
color: '#ffffff',
|
||||
borderColor: '#FF5733',
|
||||
});
|
||||
});
|
||||
|
||||
it('customColor unchecked 상태에서 rgba 배경이 적용되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#FF5733"
|
||||
checked={false}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
// #FF5733 = rgb(255, 87, 51)
|
||||
// 라이트 모드 unchecked: rgba(255, 87, 51, 0.06)
|
||||
expect(label?.style.backgroundColor).toContain('rgba(255, 87, 51');
|
||||
expect(label).toHaveStyle({ color: '#FF5733' });
|
||||
});
|
||||
|
||||
it('customColor가 없으면 기존 variant 로직을 사용해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" variant="blue" checked={false} />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('bg-blue-50');
|
||||
// 인라인 backgroundColor가 없어야 함 (variant 클래스 사용)
|
||||
expect(label?.style.backgroundColor).toBeFalsy();
|
||||
});
|
||||
|
||||
it('customColor + style prop이 함께 작동해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#3B82F6"
|
||||
style={{ marginLeft: '8px' }}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
// style prop이 병합되어야 함
|
||||
expect(label).toHaveStyle({ marginLeft: '8px' });
|
||||
});
|
||||
|
||||
it('customColor + className이 함께 작동해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#3B82F6"
|
||||
className="my-custom-class"
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('my-custom-class');
|
||||
expect(label).toHaveClass('inline-flex');
|
||||
});
|
||||
|
||||
it('잘못된 hex 색상이면 빈 스타일을 적용해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="잘못된 색상"
|
||||
customColor="invalid"
|
||||
checked={false}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
// hexToRgb가 null을 반환하므로 빈 스타일
|
||||
expect(label).toBeTruthy();
|
||||
});
|
||||
|
||||
it('hover 시 스타일이 변경되어야 함 (checked)', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#FF5733"
|
||||
checked={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label')!;
|
||||
// 초기 상태: opacity 1
|
||||
expect(label).toHaveStyle({ opacity: '1' });
|
||||
|
||||
// hover
|
||||
fireEvent.mouseEnter(label);
|
||||
expect(label).toHaveStyle({ opacity: '0.85' });
|
||||
|
||||
// unhover
|
||||
fireEvent.mouseLeave(label);
|
||||
expect(label).toHaveStyle({ opacity: '1' });
|
||||
});
|
||||
|
||||
it('hover 시 unchecked 배경 투명도가 증가해야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#FF5733"
|
||||
checked={false}
|
||||
/>
|
||||
);
|
||||
|
||||
const label = container.querySelector('label')!;
|
||||
const initialBg = label.style.backgroundColor;
|
||||
|
||||
// hover
|
||||
fireEvent.mouseEnter(label);
|
||||
const hoveredBg = label.style.backgroundColor;
|
||||
|
||||
// hover 시 배경 투명도가 달라져야 함
|
||||
expect(hoveredBg).not.toBe(initialBg);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onChange 이벤트', () => {
|
||||
it('onChange 핸들러가 호출되어야 함', () => {
|
||||
const handleChange = vi.fn();
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" onChange={handleChange} />
|
||||
);
|
||||
|
||||
const checkbox = container.querySelector('input[type="checkbox"]')!;
|
||||
fireEvent.click(checkbox);
|
||||
|
||||
expect(handleChange).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('customColor 모드에서도 onChange가 호출되어야 함', () => {
|
||||
const handleChange = vi.fn();
|
||||
const { container } = render(
|
||||
<ChipCheckbox
|
||||
value="test"
|
||||
label="커스텀"
|
||||
customColor="#FF5733"
|
||||
onChange={handleChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const checkbox = container.querySelector('input[type="checkbox"]')!;
|
||||
fireEvent.click(checkbox);
|
||||
|
||||
expect(handleChange).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onChange 없이도 오류 없이 렌더링되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" />
|
||||
);
|
||||
|
||||
const checkbox = container.querySelector('input[type="checkbox"]')!;
|
||||
// onChange 없이 클릭해도 에러 없어야 함
|
||||
expect(() => fireEvent.click(checkbox)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('스타일 커스터마이징', () => {
|
||||
it('className prop이 적용되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" className="extra-class" />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveClass('extra-class');
|
||||
});
|
||||
|
||||
it('style prop이 적용되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="test" label="테스트" style={{ padding: '20px' }} />
|
||||
);
|
||||
|
||||
const label = container.querySelector('label');
|
||||
expect(label).toHaveStyle({ padding: '20px' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('value prop', () => {
|
||||
it('checkbox에 value가 설정되어야 함', () => {
|
||||
const { container } = render(
|
||||
<ChipCheckbox value="my_value" label="테스트" />
|
||||
);
|
||||
|
||||
const checkbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement;
|
||||
expect(checkbox.value).toBe('my_value');
|
||||
});
|
||||
});
|
||||
});
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { CodeEditor } from '../CodeEditor';
|
||||
|
||||
// Monaco Editor mock
|
||||
vi.mock('@monaco-editor/react', () => ({
|
||||
default: ({ value, onChange, onMount, theme, language }: any) => {
|
||||
// onMount 호출을 시뮬레이션
|
||||
React.useEffect(() => {
|
||||
if (onMount) {
|
||||
const mockEditor = {
|
||||
updateOptions: vi.fn(),
|
||||
getValue: () => value,
|
||||
};
|
||||
const mockMonaco = {
|
||||
languages: {
|
||||
json: {
|
||||
jsonDefaults: {
|
||||
setDiagnosticsOptions: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
onMount(mockEditor, mockMonaco);
|
||||
}
|
||||
}, [onMount]);
|
||||
|
||||
return (
|
||||
<div data-testid="monaco-editor">
|
||||
<textarea
|
||||
data-testid="editor-textarea"
|
||||
value={value}
|
||||
onChange={(e) => onChange?.(e.target.value)}
|
||||
readOnly={false}
|
||||
data-theme={theme}
|
||||
data-language={language}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('CodeEditor', () => {
|
||||
it('기본 props로 렌더링되어야 한다', () => {
|
||||
render(<CodeEditor value="" />);
|
||||
|
||||
const editor = screen.getByTestId('monaco-editor');
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('value prop이 에디터에 표시되어야 한다', () => {
|
||||
const testValue = '{"key": "value"}';
|
||||
render(<CodeEditor value={testValue} />);
|
||||
|
||||
const textarea = screen.getByTestId('editor-textarea');
|
||||
expect(textarea).toHaveValue(testValue);
|
||||
});
|
||||
|
||||
it('onChange 콜백이 에디터 내용 변경 시 호출되어야 한다', async () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<CodeEditor value="" onChange={handleChange} />);
|
||||
|
||||
const textarea = screen.getByTestId('editor-textarea');
|
||||
const newValue = '{"test": true}';
|
||||
|
||||
// 텍스트 변경 이벤트 시뮬레이션
|
||||
textarea.dispatchEvent(
|
||||
new Event('input', { bubbles: true })
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
// textarea의 value 변경을 onChange에 전달
|
||||
const changeEvent = new Event('change', { bubbles: true });
|
||||
Object.defineProperty(changeEvent, 'target', {
|
||||
value: { value: newValue },
|
||||
writable: false,
|
||||
});
|
||||
textarea.dispatchEvent(changeEvent);
|
||||
});
|
||||
});
|
||||
|
||||
it('language prop이 에디터에 적용되어야 한다', () => {
|
||||
render(<CodeEditor value="" language="javascript" />);
|
||||
|
||||
const textarea = screen.getByTestId('editor-textarea');
|
||||
expect(textarea).toHaveAttribute('data-language', 'javascript');
|
||||
});
|
||||
|
||||
it('theme prop이 에디터에 적용되어야 한다', () => {
|
||||
render(<CodeEditor value="" theme="vs-light" />);
|
||||
|
||||
const textarea = screen.getByTestId('editor-textarea');
|
||||
expect(textarea).toHaveAttribute('data-theme', 'vs-light');
|
||||
});
|
||||
|
||||
it('기본값으로 json 언어를 사용해야 한다', () => {
|
||||
render(<CodeEditor value="" />);
|
||||
|
||||
const textarea = screen.getByTestId('editor-textarea');
|
||||
expect(textarea).toHaveAttribute('data-language', 'json');
|
||||
});
|
||||
|
||||
it('기본값으로 vs-dark 테마를 사용해야 한다', () => {
|
||||
render(<CodeEditor value="" />);
|
||||
|
||||
const textarea = screen.getByTestId('editor-textarea');
|
||||
expect(textarea).toHaveAttribute('data-theme', 'vs-dark');
|
||||
});
|
||||
|
||||
it('컨테이너에 올바른 스타일 클래스가 적용되어야 한다', () => {
|
||||
const { container } = render(<CodeEditor value="" />);
|
||||
|
||||
const wrapper = container.querySelector('div');
|
||||
expect(wrapper).toHaveClass('border', 'border-gray-300', 'rounded-lg', 'overflow-hidden');
|
||||
});
|
||||
});
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { ConfirmDialog } from '../ConfirmDialog';
|
||||
|
||||
describe('ConfirmDialog', () => {
|
||||
const mockProps = {
|
||||
isOpen: true,
|
||||
onClose: vi.fn(),
|
||||
title: '삭제 확인',
|
||||
message: '정말 이 항목을 삭제하시겠습니까?',
|
||||
onConfirm: vi.fn(),
|
||||
};
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<ConfirmDialog {...mockProps} />);
|
||||
|
||||
expect(screen.getByText('삭제 확인')).toBeInTheDocument();
|
||||
expect(screen.getByText('정말 이 항목을 삭제하시겠습니까?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('isOpen이 false일 때 렌더링되지 않음', () => {
|
||||
render(<ConfirmDialog {...mockProps} isOpen={false} />);
|
||||
|
||||
expect(screen.queryByText('삭제 확인')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('확인과 취소 버튼이 표시됨', () => {
|
||||
render(<ConfirmDialog {...mockProps} />);
|
||||
|
||||
expect(screen.getByText('확인')).toBeInTheDocument();
|
||||
expect(screen.getByText('취소')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('커스텀 버튼 텍스트가 표시됨', () => {
|
||||
render(
|
||||
<ConfirmDialog
|
||||
{...mockProps}
|
||||
confirmText="삭제"
|
||||
cancelText="아니오"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('삭제')).toBeInTheDocument();
|
||||
expect(screen.getByText('아니오')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('확인 버튼 클릭 시 onConfirm이 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onConfirm = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<ConfirmDialog
|
||||
{...mockProps}
|
||||
onConfirm={onConfirm}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
|
||||
const confirmButton = screen.getByText('확인');
|
||||
await user.click(confirmButton);
|
||||
|
||||
// 확인 버튼은 onConfirm만 호출 (onClose는 부모가 처리)
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('취소 버튼 클릭 시 onCancel과 onClose가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onCancel = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<ConfirmDialog
|
||||
{...mockProps}
|
||||
onCancel={onCancel}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
|
||||
const cancelButton = screen.getByText('취소');
|
||||
await user.click(cancelButton);
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('React 노드를 message로 사용할 수 있음', () => {
|
||||
render(
|
||||
<ConfirmDialog
|
||||
{...mockProps}
|
||||
message={<div>커스텀 <strong>경고</strong></div>}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('커스텀')).toBeInTheDocument();
|
||||
expect(screen.getByText('경고')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('confirmButtonVariant prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<ConfirmDialog
|
||||
{...mockProps}
|
||||
confirmButtonVariant="danger"
|
||||
/>
|
||||
);
|
||||
|
||||
// confirmButtonVariant="danger"일 때 bg-red-600 클래스가 적용됨
|
||||
const confirmButton = container.querySelector('button.bg-red-600');
|
||||
expect(confirmButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancelButtonVariant prop은 현재 고정 스타일 사용', () => {
|
||||
const { container } = render(
|
||||
<ConfirmDialog
|
||||
{...mockProps}
|
||||
cancelButtonVariant="ghost"
|
||||
/>
|
||||
);
|
||||
|
||||
// 취소 버튼은 현재 고정 스타일 사용 (bg-white)
|
||||
const cancelButton = screen.getByText('취소').closest('button');
|
||||
expect(cancelButton).toHaveClass('bg-white');
|
||||
});
|
||||
});
|
||||
+790
@@ -0,0 +1,790 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { DataGrid, DataGridColumn } from '../DataGrid';
|
||||
|
||||
// window.G7Core.useResponsive mock
|
||||
const mockUseResponsive = vi.fn(() => ({
|
||||
width: 1024,
|
||||
isMobile: false,
|
||||
isTablet: false,
|
||||
isDesktop: true,
|
||||
matchedPreset: 'desktop' as const,
|
||||
}));
|
||||
|
||||
describe('DataGrid', () => {
|
||||
// 원래 G7Core 백업
|
||||
let originalG7Core: any;
|
||||
|
||||
beforeEach(() => {
|
||||
// 기존 G7Core를 유지하면서 useResponsive만 추가/덮어쓰기
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = {
|
||||
...originalG7Core,
|
||||
useResponsive: mockUseResponsive,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// 원래 G7Core 복원
|
||||
(window as any).G7Core = originalG7Core;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
const mockColumns: DataGridColumn[] = [
|
||||
{ field: 'name', header: '이름', sortable: true },
|
||||
{ field: 'email', header: '이메일', sortable: true },
|
||||
{ field: 'role', header: '역할', sortable: false },
|
||||
];
|
||||
|
||||
const mockData = [
|
||||
{ name: '홍길동', email: 'hong@example.com', role: '관리자' },
|
||||
{ name: '김철수', email: 'kim@example.com', role: '사용자' },
|
||||
{ name: '이영희', email: 'lee@example.com', role: '사용자' },
|
||||
];
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<DataGrid columns={mockColumns} data={mockData} />);
|
||||
|
||||
expect(screen.getByText('이름')).toBeInTheDocument();
|
||||
expect(screen.getByText('이메일')).toBeInTheDocument();
|
||||
expect(screen.getByText('역할')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('데이터가 표시됨', () => {
|
||||
render(<DataGrid columns={mockColumns} data={mockData} />);
|
||||
|
||||
expect(screen.getByText('홍길동')).toBeInTheDocument();
|
||||
expect(screen.getByText('hong@example.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('관리자')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('컬럼 헤더 클릭 시 정렬됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSortChange = vi.fn();
|
||||
|
||||
// controlled 모드로 테스트 (외부 상태 제어)
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="asc"
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const nameHeader = screen.getByText('이름');
|
||||
|
||||
// 정렬 화살표가 표시되는지 확인
|
||||
expect(nameHeader.parentElement).toContainHTML('↑');
|
||||
|
||||
// 클릭 시 onSortChange가 호출되는지 확인
|
||||
await user.click(nameHeader);
|
||||
expect(onSortChange).toHaveBeenCalledWith('name', 'desc');
|
||||
});
|
||||
|
||||
it('정렬 방향이 토글됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSortChange = vi.fn();
|
||||
|
||||
// controlled 모드로 테스트: asc 상태에서 시작
|
||||
const { rerender } = render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="asc"
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const nameHeader = screen.getByText('이름');
|
||||
|
||||
// 초기 상태: 오름차순 화살표 표시
|
||||
expect(nameHeader.parentElement).toContainHTML('↑');
|
||||
|
||||
// 클릭 시 desc로 토글 요청
|
||||
await user.click(nameHeader);
|
||||
expect(onSortChange).toHaveBeenCalledWith('name', 'desc');
|
||||
|
||||
// 상태를 desc로 업데이트하여 다시 렌더링
|
||||
rerender(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="desc"
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// 내림차순 화살표 표시
|
||||
expect(nameHeader.parentElement).toContainHTML('↓');
|
||||
});
|
||||
|
||||
it('sortable이 false인 컬럼은 정렬되지 않음', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<DataGrid columns={mockColumns} data={mockData} sortable={true} />);
|
||||
|
||||
const roleHeader = screen.getByText('역할');
|
||||
await user.click(roleHeader);
|
||||
|
||||
// 정렬 화살표가 표시되지 않아야 함
|
||||
expect(roleHeader.parentElement).not.toContainHTML('↑');
|
||||
expect(roleHeader.parentElement).not.toContainHTML('↓');
|
||||
});
|
||||
|
||||
it('row 클릭 시 onRowClick 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onRowClick = vi.fn();
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
onRowClick={onRowClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const row = screen.getByText('홍길동').closest('tr');
|
||||
await user.click(row!);
|
||||
|
||||
expect(onRowClick).toHaveBeenCalledWith(mockData[0]);
|
||||
});
|
||||
|
||||
it('페이지네이션이 활성화되면 페이지 버튼이 표시됨', () => {
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
name: `User ${i}`,
|
||||
email: `user${i}@example.com`,
|
||||
role: '사용자',
|
||||
}));
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={manyData}
|
||||
pagination={true}
|
||||
pageSize={10}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText('이전 페이지')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('다음 페이지')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('페이지 1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('페이지 버튼 클릭 시 다른 페이지로 이동함', async () => {
|
||||
const user = userEvent.setup();
|
||||
const manyData = Array.from({ length: 25 }, (_, i) => ({
|
||||
name: `User ${i}`,
|
||||
email: `user${i}@example.com`,
|
||||
role: '사용자',
|
||||
}));
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={manyData}
|
||||
pagination={true}
|
||||
pageSize={10}
|
||||
/>
|
||||
);
|
||||
|
||||
const nextButton = screen.getByLabelText('다음 페이지');
|
||||
await user.click(nextButton);
|
||||
|
||||
// 2페이지 데이터가 표시되어야 함
|
||||
expect(screen.getByText('User 10')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('빈 데이터일 때 아무것도 표시되지 않음', () => {
|
||||
render(<DataGrid columns={mockColumns} data={[]} />);
|
||||
|
||||
expect(screen.queryByText('홍길동')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
className="custom-grid"
|
||||
/>
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-grid');
|
||||
});
|
||||
|
||||
describe('외부 정렬 제어 (sortField, sortDirection, onSortChange)', () => {
|
||||
it('외부에서 sortField와 sortDirection을 제어할 수 있음', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="asc"
|
||||
/>
|
||||
);
|
||||
|
||||
// 정렬 화살표가 표시되는지 확인
|
||||
const nameHeader = screen.getByText('이름');
|
||||
expect(nameHeader.parentElement).toContainHTML('↑');
|
||||
});
|
||||
|
||||
it('외부 sortDirection이 desc일 때 내림차순 화살표가 표시됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="email"
|
||||
sortDirection="desc"
|
||||
/>
|
||||
);
|
||||
|
||||
const emailHeader = screen.getByText('이메일');
|
||||
expect(emailHeader.parentElement).toContainHTML('↓');
|
||||
});
|
||||
|
||||
it('컬럼 헤더 클릭 시 onSortChange 콜백이 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSortChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const nameHeader = screen.getByText('이름');
|
||||
await user.click(nameHeader);
|
||||
|
||||
expect(onSortChange).toHaveBeenCalledWith('name', 'asc');
|
||||
});
|
||||
|
||||
it('동일한 컬럼 재클릭 시 정렬 방향이 토글됨 (외부 제어)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSortChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="asc"
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const nameHeader = screen.getByText('이름');
|
||||
await user.click(nameHeader);
|
||||
|
||||
// 이미 asc이므로 desc로 변경되어야 함
|
||||
expect(onSortChange).toHaveBeenCalledWith('name', 'desc');
|
||||
});
|
||||
|
||||
it('다른 컬럼 클릭 시 새 컬럼으로 asc 정렬됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSortChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="desc"
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const emailHeader = screen.getByText('이메일');
|
||||
await user.click(emailHeader);
|
||||
|
||||
// 새 컬럼이므로 asc로 시작
|
||||
expect(onSortChange).toHaveBeenCalledWith('email', 'asc');
|
||||
});
|
||||
|
||||
it('onSortChange가 없을 때도 클릭이 오류 없이 동작함', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
// onSortChange 없이 렌더링 (uncontrolled 모드)
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const nameHeader = screen.getByText('이름');
|
||||
|
||||
// 클릭 시 오류가 발생하지 않아야 함
|
||||
await expect(user.click(nameHeader)).resolves.not.toThrow();
|
||||
|
||||
// 컴포넌트가 여전히 안정적으로 렌더링되어야 함
|
||||
expect(screen.getByText('이름')).toBeInTheDocument();
|
||||
expect(screen.getByText('이메일')).toBeInTheDocument();
|
||||
expect(screen.getByText('역할')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sortable이 false인 컬럼은 onSortChange가 호출되지 않음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSortChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
onSortChange={onSortChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// role 컬럼은 sortable: false
|
||||
const roleHeader = screen.getByText('역할');
|
||||
await user.click(roleHeader);
|
||||
|
||||
expect(onSortChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('외부 정렬 상태에 따라 데이터가 정렬됨', () => {
|
||||
const { rerender } = render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="asc"
|
||||
/>
|
||||
);
|
||||
|
||||
// 이름 기준 오름차순 정렬 확인 (김철수 < 이영희 < 홍길동)
|
||||
const rows = screen.getAllByRole('row');
|
||||
// 첫 번째 row는 header이므로 두 번째부터 데이터
|
||||
expect(rows[1]).toHaveTextContent('김철수');
|
||||
|
||||
// 내림차순으로 변경
|
||||
rerender(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
sortable={true}
|
||||
sortField="name"
|
||||
sortDirection="desc"
|
||||
/>
|
||||
);
|
||||
|
||||
const rowsAfter = screen.getAllByRole('row');
|
||||
expect(rowsAfter[1]).toHaveTextContent('홍길동');
|
||||
});
|
||||
});
|
||||
|
||||
describe('서브 행 (Sub Row) 기능 - v1.6.0+', () => {
|
||||
it('subRowRender가 제공되면 각 데이터 행 아래에 서브 행이 렌더링됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">배송비: {row.name}</span>}
|
||||
/>
|
||||
);
|
||||
|
||||
// 각 데이터 행에 대해 서브 행이 렌더링되어야 함
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
expect(subRowContents).toHaveLength(3);
|
||||
expect(subRowContents[0]).toHaveTextContent('배송비: 홍길동');
|
||||
expect(subRowContents[1]).toHaveTextContent('배송비: 김철수');
|
||||
expect(subRowContents[2]).toHaveTextContent('배송비: 이영희');
|
||||
});
|
||||
|
||||
it('subRowClassName이 서브 행에 적용됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
subRowClassName="bg-gray-100 text-sm"
|
||||
/>
|
||||
);
|
||||
|
||||
// subRowClassName이 있으면:
|
||||
// - td에는 'p-2' padding만 적용
|
||||
// - 내부 Div에 subRowClassName 적용 (스타일 분리를 위한 의도적 설계)
|
||||
// @see commit 346e704b "subRow 내부 Div wrapper 추가"
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
subRowContents.forEach((content) => {
|
||||
// 내부 Div wrapper에 className이 적용됨
|
||||
const divWrapper = content.closest('div.bg-gray-100');
|
||||
expect(divWrapper).toBeInTheDocument();
|
||||
expect(divWrapper).toHaveClass('bg-gray-100');
|
||||
expect(divWrapper).toHaveClass('text-sm');
|
||||
|
||||
// td에는 패딩만 적용
|
||||
const td = content.closest('td');
|
||||
expect(td).toHaveClass('p-2');
|
||||
});
|
||||
});
|
||||
|
||||
it('subRowCondition이 false를 반환하면 서브 행이 렌더링되지 않음', () => {
|
||||
const dataWithFlag = [
|
||||
{ name: '홍길동', email: 'hong@example.com', role: '관리자', showSubRow: true },
|
||||
{ name: '김철수', email: 'kim@example.com', role: '사용자', showSubRow: false },
|
||||
{ name: '이영희', email: 'lee@example.com', role: '사용자', showSubRow: true },
|
||||
];
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={dataWithFlag}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
subRowCondition="{{row.showSubRow}}"
|
||||
/>
|
||||
);
|
||||
|
||||
// showSubRow가 true인 행만 서브 행이 렌더링되어야 함
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
expect(subRowContents).toHaveLength(2);
|
||||
expect(subRowContents[0]).toHaveTextContent('홍길동');
|
||||
expect(subRowContents[1]).toHaveTextContent('이영희');
|
||||
});
|
||||
|
||||
it('subRowCondition 없이 subRowRender만 제공되면 모든 행에 서브 행이 렌더링됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
expect(subRowContents).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('subRowRender와 subRowChildren이 모두 없으면 서브 행이 렌더링되지 않음', () => {
|
||||
const { container } = render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
/>
|
||||
);
|
||||
|
||||
// 서브 행 관련 요소가 없어야 함
|
||||
expect(container.querySelectorAll('[data-testid="sub-row-content"]')).toHaveLength(0);
|
||||
|
||||
// 기본 데이터 행만 있어야 함 (헤더 1개 + 데이터 3개)
|
||||
const rows = screen.getAllByRole('row');
|
||||
expect(rows).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('서브 행의 colSpan이 전체 컬럼을 커버함', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
subRowContents.forEach((content) => {
|
||||
const td = content.closest('td');
|
||||
// mockColumns가 3개이므로 colSpan도 3이어야 함
|
||||
expect(td).toHaveAttribute('colspan', '3');
|
||||
});
|
||||
});
|
||||
|
||||
it('selectable과 함께 사용시 서브 행 colSpan이 체크박스 컬럼을 포함함', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
selectable={true}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
subRowContents.forEach((content) => {
|
||||
const td = content.closest('td');
|
||||
// mockColumns 3개 + 체크박스 컬럼 1개 = 4
|
||||
expect(td).toHaveAttribute('colspan', '4');
|
||||
});
|
||||
});
|
||||
|
||||
it('rowActions와 함께 사용시 서브 행 colSpan이 액션 컬럼을 포함함', () => {
|
||||
const mockRowActions = [
|
||||
{ id: 'edit', label: '수정', icon: 'edit' },
|
||||
{ id: 'delete', label: '삭제', icon: 'trash' },
|
||||
];
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
rowActions={mockRowActions}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
subRowContents.forEach((content) => {
|
||||
const td = content.closest('td');
|
||||
// mockColumns 3개 + 액션 컬럼 1개 = 4
|
||||
expect(td).toHaveAttribute('colspan', '4');
|
||||
});
|
||||
});
|
||||
|
||||
it('subRowCondition이 잘못된 표현식이어도 오류 없이 기본값(true)으로 처리됨', () => {
|
||||
// 콘솔 경고를 억제
|
||||
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
subRowCondition="{{invalid.syntax.here}}"
|
||||
/>
|
||||
);
|
||||
|
||||
// 잘못된 조건이어도 기본값 true로 모든 행에 서브 행이 렌더링됨
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
expect(subRowContents).toHaveLength(3);
|
||||
|
||||
consoleWarn.mockRestore();
|
||||
});
|
||||
|
||||
it('subRowCondition이 빈 문자열이면 모든 행에 서브 행이 렌더링됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
subRowRender={(row) => <span data-testid="sub-row-content">{row.name}</span>}
|
||||
subRowCondition=""
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('sub-row-content');
|
||||
expect(subRowContents).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// 회귀 테스트: SPA 네비게이션 시 컬럼 변경 감지
|
||||
// 문서: troubleshooting-state-closure.md - 사례 165 (동일 패턴)
|
||||
// =============================================================================
|
||||
|
||||
describe('SPA 네비게이션 시 컬럼 변경 감지 - visibleColumns 리셋', () => {
|
||||
it('columns prop이 변경되면 visibleColumns가 새 columns 기준으로 리셋됨', () => {
|
||||
const orderColumns: DataGridColumn[] = [
|
||||
{ field: 'no', header: '번호' },
|
||||
{ field: 'ordered_at', header: '주문일' },
|
||||
{ field: 'order_number', header: '주문번호' },
|
||||
];
|
||||
|
||||
const shippingColumns: DataGridColumn[] = [
|
||||
{ field: 'name_localized', header: '정책명' },
|
||||
{ field: 'shipping_method_label', header: '배송방법' },
|
||||
{ field: 'charge_policy_label', header: '요금정책' },
|
||||
];
|
||||
|
||||
const { rerender } = render(
|
||||
<DataGrid columns={orderColumns} data={[]} />
|
||||
);
|
||||
|
||||
// 주문관리 컬럼 헤더 확인
|
||||
expect(screen.getByText('번호')).toBeInTheDocument();
|
||||
expect(screen.getByText('주문일')).toBeInTheDocument();
|
||||
expect(screen.getByText('주문번호')).toBeInTheDocument();
|
||||
|
||||
// 배송정책 컬럼으로 변경 (SPA 네비게이션 시뮬레이션)
|
||||
rerender(
|
||||
<DataGrid columns={shippingColumns} data={[]} />
|
||||
);
|
||||
|
||||
// 새 컬럼 헤더가 모두 표시되어야 함
|
||||
expect(screen.getByText('정책명')).toBeInTheDocument();
|
||||
expect(screen.getByText('배송방법')).toBeInTheDocument();
|
||||
expect(screen.getByText('요금정책')).toBeInTheDocument();
|
||||
|
||||
// 이전 컬럼 헤더는 없어야 함
|
||||
expect(screen.queryByText('번호')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('주문일')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('주문번호')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('외부 visibleColumns가 있으면 columns 변경 시 리셋하지 않음', () => {
|
||||
const columnsA: DataGridColumn[] = [
|
||||
{ field: 'a1', header: 'A1' },
|
||||
{ field: 'a2', header: 'A2' },
|
||||
];
|
||||
|
||||
const columnsB: DataGridColumn[] = [
|
||||
{ field: 'b1', header: 'B1' },
|
||||
{ field: 'b2', header: 'B2' },
|
||||
];
|
||||
|
||||
const { rerender } = render(
|
||||
<DataGrid columns={columnsA} data={[]} visibleColumns={['a1', 'a2']} />
|
||||
);
|
||||
|
||||
// 외부 visibleColumns와 함께 새 columns로 변경
|
||||
rerender(
|
||||
<DataGrid columns={columnsB} data={[]} visibleColumns={['b1']} />
|
||||
);
|
||||
|
||||
// 외부 visibleColumns에 의해 b1만 표시
|
||||
expect(screen.getByText('B1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('모바일 뷰 서브 행', () => {
|
||||
beforeEach(() => {
|
||||
// 모바일 모드로 설정
|
||||
mockUseResponsive.mockReturnValue({
|
||||
width: 375,
|
||||
isMobile: true,
|
||||
isTablet: false,
|
||||
isDesktop: false,
|
||||
matchedPreset: 'portable' as const,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// 데스크톱 모드로 복원
|
||||
mockUseResponsive.mockReturnValue({
|
||||
width: 1024,
|
||||
isMobile: false,
|
||||
isTablet: false,
|
||||
isDesktop: true,
|
||||
matchedPreset: 'desktop' as const,
|
||||
});
|
||||
});
|
||||
|
||||
it('모바일 카드 뷰에서도 서브 행이 렌더링됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
mobileBreakpoint={768}
|
||||
subRowRender={(row) => <div data-testid="mobile-sub-row">모바일 서브: {row.name}</div>}
|
||||
/>
|
||||
);
|
||||
|
||||
// 모바일 뷰에서 서브 행이 렌더링되어야 함
|
||||
const subRowContents = screen.getAllByTestId('mobile-sub-row');
|
||||
expect(subRowContents).toHaveLength(3);
|
||||
expect(subRowContents[0]).toHaveTextContent('모바일 서브: 홍길동');
|
||||
});
|
||||
|
||||
it('모바일 뷰에서 subRowCondition이 적용됨', () => {
|
||||
const dataWithFlag = [
|
||||
{ name: '홍길동', email: 'hong@example.com', role: '관리자', showSubRow: true },
|
||||
{ name: '김철수', email: 'kim@example.com', role: '사용자', showSubRow: false },
|
||||
{ name: '이영희', email: 'lee@example.com', role: '사용자', showSubRow: true },
|
||||
];
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={dataWithFlag}
|
||||
mobileBreakpoint={768}
|
||||
subRowRender={(row) => <div data-testid="mobile-sub-row">{row.name}</div>}
|
||||
subRowCondition="{{row.showSubRow}}"
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('mobile-sub-row');
|
||||
expect(subRowContents).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('모바일 뷰에서 subRowClassName이 적용됨', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={mockData}
|
||||
mobileBreakpoint={768}
|
||||
subRowRender={(row) => <div data-testid="mobile-sub-row">{row.name}</div>}
|
||||
subRowClassName="mobile-sub-row-custom"
|
||||
/>
|
||||
);
|
||||
|
||||
const subRowContents = screen.getAllByTestId('mobile-sub-row');
|
||||
subRowContents.forEach((content) => {
|
||||
const wrapper = content.closest('.mobile-sub-row-custom');
|
||||
expect(wrapper).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// =========================================================================
|
||||
// disabledField 테스트
|
||||
// =========================================================================
|
||||
describe('rowActions disabledField', () => {
|
||||
const dataWithAbilities = [
|
||||
{ name: '본인', email: 'self@test.com', role: '매니저', abilities: { can_update: true, can_delete: false } },
|
||||
{ name: '타인', email: 'other@test.com', role: '사용자', abilities: { can_update: false, can_delete: false } },
|
||||
];
|
||||
|
||||
it('disabledField가 falsy인 행의 액션은 disabled 클래스가 적용된다', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={dataWithAbilities}
|
||||
rowActions={[
|
||||
{ id: 'edit', label: '수정', disabledField: 'abilities.can_update' },
|
||||
{ id: 'delete', label: '삭제', disabledField: 'abilities.can_delete' },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
// 첫 번째 행의 액션 메뉴 열기
|
||||
const actionButtons = screen.getAllByRole('button');
|
||||
// 액션 메뉴 트리거 버튼 찾기 (테이블 행별 하나씩)
|
||||
const triggerButtons = actionButtons.filter(btn =>
|
||||
btn.closest('.relative.inline-block')
|
||||
);
|
||||
|
||||
if (triggerButtons.length > 0) {
|
||||
await user.click(triggerButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
const menuItems = document.querySelectorAll('.fixed.z-\\[9999\\] > div');
|
||||
if (menuItems.length >= 2) {
|
||||
// 첫 번째 행: can_update=true → 수정 활성, can_delete=false → 삭제 비활성
|
||||
expect(menuItems[0]).not.toHaveClass('opacity-50');
|
||||
expect(menuItems[1]).toHaveClass('opacity-50');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('disabledField 미지정 액션은 항상 활성화된다', () => {
|
||||
render(
|
||||
<DataGrid
|
||||
columns={mockColumns}
|
||||
data={dataWithAbilities}
|
||||
rowActions={[
|
||||
{ id: 'view', label: '보기' },
|
||||
{ id: 'edit', label: '수정', disabledField: 'abilities.can_update' },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
// 렌더링 자체가 에러 없이 완료되면 성공
|
||||
expect(screen.getByText('본인')).toBeInTheDocument();
|
||||
expect(screen.getByText('타인')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Dialog, DialogAction } from '../Dialog';
|
||||
|
||||
describe('Dialog', () => {
|
||||
const mockActions: DialogAction[] = [
|
||||
{ label: '취소', onClick: vi.fn(), variant: 'secondary' },
|
||||
{ label: '확인', onClick: vi.fn(), variant: 'primary' },
|
||||
];
|
||||
|
||||
const mockProps = {
|
||||
isOpen: true,
|
||||
onClose: vi.fn(),
|
||||
title: '테스트 다이얼로그',
|
||||
content: <div>테스트 내용</div>,
|
||||
};
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<Dialog {...mockProps} />);
|
||||
|
||||
expect(screen.getByText('테스트 다이얼로그')).toBeInTheDocument();
|
||||
expect(screen.getByText('테스트 내용')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('isOpen이 false일 때 렌더링되지 않음', () => {
|
||||
render(<Dialog {...mockProps} isOpen={false} />);
|
||||
|
||||
expect(screen.queryByText('테스트 다이얼로그')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('액션 버튼이 표시됨', () => {
|
||||
render(<Dialog {...mockProps} actions={mockActions} />);
|
||||
|
||||
expect(screen.getByText('취소')).toBeInTheDocument();
|
||||
expect(screen.getByText('확인')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('액션 버튼 클릭 시 onClick 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
const actions: DialogAction[] = [
|
||||
{ label: '테스트', onClick: onClickMock },
|
||||
];
|
||||
|
||||
render(<Dialog {...mockProps} actions={actions} />);
|
||||
|
||||
const button = screen.getByText('테스트');
|
||||
await user.click(button);
|
||||
|
||||
expect(onClickMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('닫기 버튼 클릭 시 onClose가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(<Dialog {...mockProps} onClose={onClose} />);
|
||||
|
||||
const closeButton = screen.getByLabelText('대화상자 닫기');
|
||||
await user.click(closeButton);
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('showCloseButton이 false일 때 닫기 버튼이 표시되지 않음', () => {
|
||||
render(<Dialog {...mockProps} showCloseButton={false} />);
|
||||
|
||||
expect(screen.queryByLabelText('대화상자 닫기')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('비활성화된 액션 버튼은 클릭되지 않음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
const actions: DialogAction[] = [
|
||||
{ label: '비활성화', onClick: onClickMock, disabled: true },
|
||||
];
|
||||
|
||||
render(<Dialog {...mockProps} actions={actions} />);
|
||||
|
||||
const button = screen.getByText('비활성화');
|
||||
expect(button).toBeDisabled();
|
||||
|
||||
await user.click(button);
|
||||
expect(onClickMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('액션 버튼에 아이콘이 표시됨', () => {
|
||||
const actions: DialogAction[] = [
|
||||
{ label: '저장', onClick: vi.fn(), iconName: 'save' as any },
|
||||
];
|
||||
|
||||
render(<Dialog {...mockProps} actions={actions} />);
|
||||
|
||||
expect(screen.getByText('저장')).toBeInTheDocument();
|
||||
// 아이콘이 렌더링되는지 확인하기는 어렵지만, 버튼은 표시됨
|
||||
});
|
||||
|
||||
it('variant별 스타일이 적용됨', () => {
|
||||
const actions: DialogAction[] = [
|
||||
{ label: '위험', onClick: vi.fn(), variant: 'danger' },
|
||||
];
|
||||
|
||||
render(<Dialog {...mockProps} actions={actions} />);
|
||||
|
||||
const button = screen.getByText('위험');
|
||||
expect(button).toHaveClass('bg-red-600');
|
||||
});
|
||||
|
||||
it('width prop이 적용됨', () => {
|
||||
render(<Dialog {...mockProps} width="800px" />);
|
||||
|
||||
const dialog = screen.getByRole('dialog');
|
||||
expect(dialog).toHaveStyle({ width: '800px' });
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
render(<Dialog {...mockProps} className="custom-dialog" />);
|
||||
|
||||
const dialog = screen.getByRole('dialog');
|
||||
expect(dialog).toHaveClass('custom-dialog');
|
||||
});
|
||||
});
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Dropdown, DropdownItem } from '../Dropdown';
|
||||
|
||||
describe('Dropdown', () => {
|
||||
const mockItems: DropdownItem[] = [
|
||||
{ label: '옵션 1', value: 'option1' },
|
||||
{ label: '옵션 2', value: 'option2' },
|
||||
{ label: '비활성화', value: 'disabled', disabled: true },
|
||||
];
|
||||
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<Dropdown label="선택" items={mockItems} />);
|
||||
|
||||
expect(screen.getByText('선택')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('트리거 버튼 클릭 시 드롭다운 메뉴가 표시됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Dropdown label="선택" items={mockItems} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
expect(screen.getByText('옵션 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('옵션 2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('메뉴 아이템 클릭 시 onClick 핸들러가 호출되고 메뉴가 닫힘', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
const items: DropdownItem[] = [
|
||||
{ label: '옵션 1', value: 'option1', onClick: onClickMock },
|
||||
];
|
||||
|
||||
render(<Dropdown label="선택" items={items} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
const option = screen.getByText('옵션 1');
|
||||
await user.click(option);
|
||||
|
||||
expect(onClickMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onItemClick 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onItemClick = vi.fn();
|
||||
|
||||
render(<Dropdown label="선택" items={mockItems} onItemClick={onItemClick} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
const option = screen.getByText('옵션 1');
|
||||
await user.click(option);
|
||||
|
||||
// onItemClick은 (value, item) 순서로 호출됨
|
||||
expect(onItemClick).toHaveBeenCalledWith(mockItems[0].value, mockItems[0]);
|
||||
});
|
||||
|
||||
it('비활성화된 아이템은 클릭되지 않음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onItemClick = vi.fn();
|
||||
|
||||
render(<Dropdown label="선택" items={mockItems} onItemClick={onItemClick} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
const disabledOption = screen.getByText('비활성화');
|
||||
await user.click(disabledOption);
|
||||
|
||||
expect(onItemClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ESC 키를 누르면 메뉴가 닫힘', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Dropdown label="선택" items={mockItems} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
expect(screen.getByText('옵션 1')).toBeInTheDocument();
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
|
||||
// ESC 키 후 메뉴가 닫혀야 함 (상태 업데이트 확인)
|
||||
});
|
||||
|
||||
it('ArrowDown 키로 다음 아이템으로 이동', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Dropdown label="선택" items={mockItems} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
fireEvent.keyDown(document, { key: 'ArrowDown' });
|
||||
|
||||
// focusedIndex가 변경되어 스타일이 적용됨
|
||||
});
|
||||
|
||||
it('Enter 키로 포커스된 아이템 선택', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onItemClick = vi.fn();
|
||||
|
||||
render(<Dropdown label="선택" items={mockItems} onItemClick={onItemClick} />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
fireEvent.keyDown(document, { key: 'ArrowDown' });
|
||||
fireEvent.keyDown(document, { key: 'Enter' });
|
||||
|
||||
// 포커스된 아이템이 선택되어야 함
|
||||
});
|
||||
|
||||
it('position prop이 적용됨 (동적 조정 전 기본값)', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Dropdown label="선택" items={mockItems} position="bottom-left" />);
|
||||
|
||||
const trigger = screen.getByText('선택');
|
||||
await user.click(trigger);
|
||||
|
||||
const menu = screen.getByRole('menu');
|
||||
// 테스트 환경에서는 getBoundingClientRect가 0을 반환하므로 동적으로 조정된 position이 적용됨
|
||||
// bottom-left는 화면 경계 체크 후 유지되거나 조정될 수 있음
|
||||
// 메뉴가 role="menu"로 렌더링되는지 확인
|
||||
expect(menu).toBeInTheDocument();
|
||||
// 위치 관련 클래스 중 하나는 반드시 포함
|
||||
const hasPositionClass = menu.className.includes('top-full') || menu.className.includes('bottom-full');
|
||||
expect(hasPositionClass).toBe(true);
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<Dropdown label="선택" items={mockItems} className="custom-dropdown" />
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-dropdown');
|
||||
});
|
||||
});
|
||||
+717
@@ -0,0 +1,717 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { DynamicFieldList } from '../DynamicFieldList';
|
||||
import type { DynamicFieldColumn, RowAction } from '../DynamicFieldList/types';
|
||||
|
||||
// G7Core 목업
|
||||
const mockG7Core = {
|
||||
locale: {
|
||||
current: () => 'ko',
|
||||
all: () => ['ko', 'en'],
|
||||
},
|
||||
};
|
||||
|
||||
// window.G7Core 목업 설정
|
||||
beforeEach(() => {
|
||||
(window as any).G7Core = mockG7Core;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).G7Core;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
// 테스트용 컬럼 정의
|
||||
const sampleColumns: DynamicFieldColumn[] = [
|
||||
{
|
||||
key: 'name',
|
||||
label: '항목명',
|
||||
type: 'multilingual',
|
||||
placeholder: '항목명을 입력하세요',
|
||||
},
|
||||
{
|
||||
key: 'content',
|
||||
label: '내용',
|
||||
type: 'multilingual',
|
||||
placeholder: '내용을 입력하세요',
|
||||
},
|
||||
];
|
||||
|
||||
// 테스트용 단순 컬럼 정의
|
||||
const simpleColumns: DynamicFieldColumn[] = [
|
||||
{
|
||||
key: 'title',
|
||||
label: '제목',
|
||||
type: 'input',
|
||||
placeholder: '제목을 입력하세요',
|
||||
},
|
||||
{
|
||||
key: 'count',
|
||||
label: '수량',
|
||||
type: 'number',
|
||||
placeholder: '수량',
|
||||
min: 0,
|
||||
max: 100,
|
||||
},
|
||||
];
|
||||
|
||||
// 테스트용 아이템 데이터
|
||||
const sampleItems = [
|
||||
{
|
||||
_id: 'item_1',
|
||||
name: { ko: '제조사', en: 'Manufacturer' },
|
||||
content: { ko: '(주)테스트', en: 'Test Inc.' },
|
||||
},
|
||||
{
|
||||
_id: 'item_2',
|
||||
name: { ko: '원산지', en: 'Country of Origin' },
|
||||
content: { ko: '대한민국', en: 'Korea' },
|
||||
},
|
||||
];
|
||||
|
||||
const simpleItems = [
|
||||
{ _id: 'item_1', title: '첫 번째 항목', count: 10 },
|
||||
{ _id: 'item_2', title: '두 번째 항목', count: 20 },
|
||||
];
|
||||
|
||||
describe('DynamicFieldList', () => {
|
||||
describe('기본 렌더링', () => {
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<DynamicFieldList items={sampleItems} columns={sampleColumns} />);
|
||||
|
||||
// 헤더가 렌더링되는지 확인
|
||||
expect(screen.getByText('항목명')).toBeInTheDocument();
|
||||
expect(screen.getByText('내용')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('빈 목록일 때 빈 상태 메시지가 표시됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={[]}
|
||||
columns={sampleColumns}
|
||||
emptyMessage="데이터가 없습니다."
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('데이터가 없습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('항목 추가 버튼이 표시됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={[]}
|
||||
columns={sampleColumns}
|
||||
addLabel="+ 항목 추가"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('+ 항목 추가')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<DynamicFieldList
|
||||
items={sampleItems}
|
||||
columns={sampleColumns}
|
||||
className="custom-list"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toHaveClass('custom-list');
|
||||
});
|
||||
|
||||
it('순번이 표시됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={sampleItems}
|
||||
columns={sampleColumns}
|
||||
showIndex={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('#')).toBeInTheDocument();
|
||||
expect(screen.getByText('1')).toBeInTheDocument();
|
||||
expect(screen.getByText('2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('showIndex=false일 때 순번이 표시되지 않음', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={sampleItems}
|
||||
columns={sampleColumns}
|
||||
showIndex={false}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText('#')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('항목 추가', () => {
|
||||
it('항목 추가 버튼 클릭 시 onChange가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={[]}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
addLabel="항목 추가"
|
||||
/>
|
||||
);
|
||||
|
||||
const addButton = screen.getByText('항목 추가');
|
||||
await user.click(addButton);
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
const newItems = onChange.mock.calls[0][0];
|
||||
expect(newItems.length).toBe(1);
|
||||
expect(newItems[0]).toHaveProperty('_id');
|
||||
expect(newItems[0].title).toBe('');
|
||||
});
|
||||
|
||||
it('onAddItem이 정의되면 외부 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onAddItem = vi.fn();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={[]}
|
||||
columns={simpleColumns}
|
||||
onAddItem={onAddItem}
|
||||
onChange={onChange}
|
||||
addLabel="항목 추가"
|
||||
/>
|
||||
);
|
||||
|
||||
const addButton = screen.getByText('항목 추가');
|
||||
await user.click(addButton);
|
||||
|
||||
expect(onAddItem).toHaveBeenCalledTimes(1);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('maxItems에 도달하면 추가 버튼이 비활성화됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
maxItems={2}
|
||||
addLabel="항목 추가"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText('항목 추가')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('createDefaultItem이 정의되면 해당 팩토리 사용', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const createDefaultItem = vi.fn(() => ({
|
||||
_id: 'custom_id',
|
||||
title: '기본값',
|
||||
count: 5,
|
||||
}));
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={[]}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
createDefaultItem={createDefaultItem}
|
||||
addLabel="항목 추가"
|
||||
/>
|
||||
);
|
||||
|
||||
const addButton = screen.getByText('항목 추가');
|
||||
await user.click(addButton);
|
||||
|
||||
expect(createDefaultItem).toHaveBeenCalledTimes(1);
|
||||
const newItems = onChange.mock.calls[0][0];
|
||||
expect(newItems[0].title).toBe('기본값');
|
||||
expect(newItems[0].count).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('항목 삭제', () => {
|
||||
it('삭제 버튼 클릭 시 onChange가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const removeButtons = screen.getAllByTitle('삭제');
|
||||
await user.click(removeButtons[0]);
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
const newItems = onChange.mock.calls[0][0];
|
||||
expect(newItems.length).toBe(1);
|
||||
expect(newItems[0]._id).toBe('item_2');
|
||||
});
|
||||
|
||||
it('minItems 이하로 삭제할 수 없음', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={[simpleItems[0]]}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
minItems={1}
|
||||
/>
|
||||
);
|
||||
|
||||
const removeButtons = screen.queryAllByTitle('삭제');
|
||||
expect(removeButtons.length).toBe(0);
|
||||
});
|
||||
|
||||
it('onRemoveItem이 정의되면 외부 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onRemoveItem = vi.fn();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
onRemoveItem={onRemoveItem}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const removeButtons = screen.getAllByTitle('삭제');
|
||||
await user.click(removeButtons[0]);
|
||||
|
||||
expect(onRemoveItem).toHaveBeenCalledTimes(1);
|
||||
expect(onRemoveItem).toHaveBeenCalledWith(0, simpleItems[0]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('값 변경', () => {
|
||||
it('입력 필드 변경 시 onChange가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const titleInputs = screen.getAllByPlaceholderText('제목을 입력하세요');
|
||||
await user.clear(titleInputs[0]);
|
||||
await user.type(titleInputs[0], '새 제목');
|
||||
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('숫자 필드 변경 시 onChange가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const numberInputs = screen.getAllByPlaceholderText('수량');
|
||||
await user.clear(numberInputs[0]);
|
||||
await user.type(numberInputs[0], '50');
|
||||
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('읽기 전용 모드', () => {
|
||||
it('readOnly=true일 때 입력 필드가 비활성화됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
readOnly={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
inputs.forEach((input) => {
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
it('readOnly=true일 때 삭제 버튼이 표시되지 않음', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
readOnly={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByTitle('삭제')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('readOnly=true일 때 추가 버튼이 표시되지 않음', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
readOnly={true}
|
||||
addLabel="항목 추가"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText('항목 추가')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('드래그 앤 드롭', () => {
|
||||
it('enableDrag=true일 때 드래그 핸들이 표시됨', () => {
|
||||
const { container } = render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
enableDrag={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const dragHandles = container.querySelectorAll('.cursor-grab');
|
||||
expect(dragHandles.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('enableDrag=false일 때 드래그 핸들이 표시되지 않음', () => {
|
||||
const { container } = render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
enableDrag={false}
|
||||
/>
|
||||
);
|
||||
|
||||
const dragHandles = container.querySelectorAll('.cursor-grab');
|
||||
expect(dragHandles.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('커스텀 행 액션', () => {
|
||||
const customRowActions: RowAction[] = [
|
||||
{
|
||||
key: 'edit',
|
||||
label: '편집',
|
||||
icon: 'edit',
|
||||
onClick: vi.fn(),
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
label: '삭제',
|
||||
icon: 'trash',
|
||||
danger: true,
|
||||
onClick: vi.fn(),
|
||||
},
|
||||
];
|
||||
|
||||
it('rowActions이 정의되면 커스텀 액션 버튼이 표시됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
rowActions={customRowActions}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getAllByTitle('편집').length).toBe(2);
|
||||
expect(screen.getAllByTitle('삭제').length).toBe(2);
|
||||
});
|
||||
|
||||
it('커스텀 액션 클릭 시 onClick이 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClick = vi.fn();
|
||||
const rowActions: RowAction[] = [
|
||||
{
|
||||
key: 'edit',
|
||||
label: '편집',
|
||||
icon: 'edit',
|
||||
onClick,
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
rowActions={rowActions}
|
||||
/>
|
||||
);
|
||||
|
||||
const editButtons = screen.getAllByTitle('편집');
|
||||
await user.click(editButtons[0]);
|
||||
|
||||
expect(onClick).toHaveBeenCalledWith(simpleItems[0], 0);
|
||||
});
|
||||
|
||||
it('disabled 조건이 적용됨', () => {
|
||||
const rowActions: RowAction[] = [
|
||||
{
|
||||
key: 'edit',
|
||||
label: '편집',
|
||||
icon: 'edit',
|
||||
disabled: (item, index) => index === 0,
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={simpleColumns}
|
||||
rowActions={rowActions}
|
||||
/>
|
||||
);
|
||||
|
||||
const editButtons = screen.getAllByTitle('편집');
|
||||
expect(editButtons[0]).toBeDisabled();
|
||||
expect(editButtons[1]).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('다국어 지원', () => {
|
||||
it('multilingual 타입 컬럼이 현재 로케일 값을 표시', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={sampleItems}
|
||||
columns={sampleColumns}
|
||||
/>
|
||||
);
|
||||
|
||||
// G7Core 목업에서 current()가 'ko'를 반환하므로 한국어 값이 표시됨
|
||||
expect(screen.getByDisplayValue('제조사')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('(주)테스트')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('multilingual 필드 변경 시 해당 로케일 값만 업데이트', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={sampleItems}
|
||||
columns={sampleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const nameInput = screen.getByDisplayValue('제조사');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, '새 제조사');
|
||||
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0];
|
||||
// 한국어 값만 업데이트되고 영어 값은 유지됨
|
||||
expect(lastCall[0].name.ko).toContain('새');
|
||||
expect(lastCall[0].name.en).toBe('Manufacturer');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Select 타입 컬럼', () => {
|
||||
const columnsWithSelect: DynamicFieldColumn[] = [
|
||||
{
|
||||
key: 'status',
|
||||
label: '상태',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'active', label: '활성' },
|
||||
{ value: 'inactive', label: '비활성' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const itemsWithSelect = [
|
||||
{ _id: 'item_1', status: 'active' },
|
||||
{ _id: 'item_2', status: 'inactive' },
|
||||
];
|
||||
|
||||
it('select 타입 컬럼이 렌더링됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={itemsWithSelect}
|
||||
columns={columnsWithSelect}
|
||||
/>
|
||||
);
|
||||
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
expect(selects.length).toBe(2);
|
||||
});
|
||||
|
||||
it('select 값 변경 시 onChange가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={itemsWithSelect}
|
||||
columns={columnsWithSelect}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
await user.selectOptions(selects[0], 'inactive');
|
||||
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
const newItems = onChange.mock.calls[0][0];
|
||||
expect(newItems[0].status).toBe('inactive');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('DynamicFieldList - 빠른 연속 편집 (stale closure 방지)', () => {
|
||||
it('빠른 연속 편집 시 모든 수정분이 누적 반영됨', async () => {
|
||||
const onChange = vi.fn();
|
||||
const items = [
|
||||
{ _id: 'item_1', title: 'A', count: 1 },
|
||||
{ _id: 'item_2', title: 'B', count: 2 },
|
||||
{ _id: 'item_3', title: 'C', count: 3 },
|
||||
];
|
||||
|
||||
const { rerender } = render(
|
||||
<DynamicFieldList
|
||||
items={items}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// 첫 번째 항목 title 입력 변경을 시뮬레이션
|
||||
const titleInputs = screen.getAllByPlaceholderText('제목을 입력하세요');
|
||||
fireEvent.change(titleInputs[0], { target: { value: 'A1' } });
|
||||
|
||||
// 리렌더 전에 두 번째 항목도 변경
|
||||
fireEvent.change(titleInputs[1], { target: { value: 'B1' } });
|
||||
|
||||
// 리렌더 전에 세 번째 항목도 변경
|
||||
fireEvent.change(titleInputs[2], { target: { value: 'C1' } });
|
||||
|
||||
// onChange가 3번 호출됨
|
||||
expect(onChange).toHaveBeenCalledTimes(3);
|
||||
|
||||
// 마지막 호출에서 모든 수정분이 반영되어야 함
|
||||
const lastCallItems = onChange.mock.calls[2][0];
|
||||
expect(lastCallItems[0].title).toBe('A1');
|
||||
expect(lastCallItems[1].title).toBe('B1');
|
||||
expect(lastCallItems[2].title).toBe('C1');
|
||||
});
|
||||
|
||||
it('연속 삭제 시 올바른 아이템이 삭제됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const items = [
|
||||
{ _id: 'item_1', title: 'A', count: 1 },
|
||||
{ _id: 'item_2', title: 'B', count: 2 },
|
||||
{ _id: 'item_3', title: 'C', count: 3 },
|
||||
];
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={items}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// 첫 번째 삭제 버튼 클릭
|
||||
const removeButtons = screen.getAllByTitle('삭제');
|
||||
await user.click(removeButtons[0]);
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
const afterFirstDelete = onChange.mock.calls[0][0];
|
||||
expect(afterFirstDelete.length).toBe(2);
|
||||
expect(afterFirstDelete[0]._id).toBe('item_2');
|
||||
expect(afterFirstDelete[1]._id).toBe('item_3');
|
||||
});
|
||||
|
||||
it('편집 후 추가 시 기존 편집분이 유지됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const items = [
|
||||
{ _id: 'item_1', title: '기존 항목', count: 10 },
|
||||
];
|
||||
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={items}
|
||||
columns={simpleColumns}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// 기존 항목 수정
|
||||
const titleInput = screen.getByPlaceholderText('제목을 입력하세요');
|
||||
fireEvent.change(titleInput, { target: { value: '수정된 항목' } });
|
||||
|
||||
// 리렌더 전에 항목 추가
|
||||
const addButton = screen.getByText('항목 추가');
|
||||
await user.click(addButton);
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(2);
|
||||
|
||||
// 추가 호출에서 기존 수정분이 유지되어야 함
|
||||
const afterAdd = onChange.mock.calls[1][0];
|
||||
expect(afterAdd[0].title).toBe('수정된 항목');
|
||||
expect(afterAdd.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DynamicFieldList - 엣지 케이스', () => {
|
||||
it('items가 undefined일 때 에러 없이 렌더링됨', () => {
|
||||
render(
|
||||
<DynamicFieldList
|
||||
items={undefined as any}
|
||||
columns={simpleColumns}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('항목이 없습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('columns가 빈 배열일 때 에러 없이 렌더링됨', () => {
|
||||
const { container } = render(
|
||||
<DynamicFieldList
|
||||
items={simpleItems}
|
||||
columns={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('itemIdKey로 커스텀 ID 필드 사용 가능', () => {
|
||||
const customItems = [
|
||||
{ customId: 'a', title: '항목 A' },
|
||||
{ customId: 'b', title: '항목 B' },
|
||||
];
|
||||
|
||||
const { container } = render(
|
||||
<DynamicFieldList
|
||||
items={customItems}
|
||||
columns={[{ key: 'title', label: '제목', type: 'input' }]}
|
||||
itemIdKey="customId"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { EmptyState, EmptyStateAction } from '../EmptyState';
|
||||
import { IconName } from '../../basic/IconTypes';
|
||||
|
||||
describe('EmptyState', () => {
|
||||
it('컴포넌트가 렌더링됨', () => {
|
||||
render(<EmptyState title="데이터가 없습니다" />);
|
||||
|
||||
expect(screen.getByText('데이터가 없습니다')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('description이 표시됨', () => {
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
description="새 항목을 추가해보세요"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('새 항목을 추가해보세요')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('아이콘이 표시됨', () => {
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
iconName={IconName.Search}
|
||||
/>
|
||||
);
|
||||
|
||||
// 아이콘이 렌더링되는지 확인 (실제로는 SVG 검증이 필요하지만 간략화)
|
||||
expect(screen.getByText('데이터가 없습니다')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('illustration 이미지가 표시됨', () => {
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
illustrationSrc="/empty.svg"
|
||||
illustrationAlt="빈 상태 이미지"
|
||||
/>
|
||||
);
|
||||
|
||||
const image = screen.getByAltText('빈 상태 이미지');
|
||||
expect(image).toBeInTheDocument();
|
||||
expect(image).toHaveAttribute('src', '/empty.svg');
|
||||
});
|
||||
|
||||
it('illustration이 있으면 icon이 표시되지 않음', () => {
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
iconName={IconName.Search}
|
||||
illustrationSrc="/empty.svg"
|
||||
illustrationAlt="빈 상태 이미지"
|
||||
/>
|
||||
);
|
||||
|
||||
// illustration이 우선이므로 이미지만 표시됨
|
||||
expect(screen.getByAltText('빈 상태 이미지')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('액션 버튼이 표시됨', () => {
|
||||
const actions: EmptyStateAction[] = [
|
||||
{ label: '새로 만들기', onClick: vi.fn() },
|
||||
];
|
||||
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('새로 만들기')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('액션 버튼 클릭 시 onClick 핸들러가 호출됨', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClickMock = vi.fn();
|
||||
const actions: EmptyStateAction[] = [
|
||||
{ label: '새로 만들기', onClick: onClickMock },
|
||||
];
|
||||
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByText('새로 만들기');
|
||||
await user.click(button);
|
||||
|
||||
expect(onClickMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('여러 액션 버튼이 표시됨', () => {
|
||||
const actions: EmptyStateAction[] = [
|
||||
{ label: '새로 만들기', onClick: vi.fn(), variant: 'primary' },
|
||||
{ label: '가져오기', onClick: vi.fn(), variant: 'secondary' },
|
||||
];
|
||||
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('새로 만들기')).toBeInTheDocument();
|
||||
expect(screen.getByText('가져오기')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('액션 버튼에 아이콘이 표시됨', () => {
|
||||
const actions: EmptyStateAction[] = [
|
||||
{ label: '추가', onClick: vi.fn(), iconName: IconName.Plus },
|
||||
];
|
||||
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('추가')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('variant별 버튼 스타일이 적용됨', () => {
|
||||
const actions: EmptyStateAction[] = [
|
||||
{ label: '삭제', onClick: vi.fn(), variant: 'danger' },
|
||||
];
|
||||
|
||||
render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByText('삭제');
|
||||
expect(button).toHaveClass('bg-red-600');
|
||||
});
|
||||
|
||||
it('className prop이 적용됨', () => {
|
||||
const { container } = render(
|
||||
<EmptyState
|
||||
title="데이터가 없습니다"
|
||||
className="custom-empty"
|
||||
/>
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-empty');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 3967 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user