v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

@@ -0,0 +1,469 @@
import React, { useState } from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { axe } from 'vitest-axe';
import { ThreeColumnLayout } from '../layout/ThreeColumnLayout';
import { LayoutEditorHeader } from '../composite/LayoutEditorHeader';
import { LayoutFileList, LayoutFileItem } from '../composite/LayoutFileList';
import { CodeEditor } from '../composite/CodeEditor';
import { LayoutHistoryPanel } from '../composite/LayoutHistoryPanel';
import { VersionItem } from '../composite/VersionList';
import { Alert } from '../composite/Alert';
// Monaco Editor mock
vi.mock('@monaco-editor/react', () => ({
default: ({ value, onChange, onMount }: any) => {
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)}
/>
</div>
);
},
}));
/**
* 통합 레이아웃 에디터 컴포넌트
* 실제 사용 시나리오를 시뮬레이션하기 위한 통합 컴포넌트
*/
const IntegratedLayoutEditor: React.FC = () => {
const [files] = useState<LayoutFileItem[]>([
{ id: 1, name: 'main-layout.json', updated_at: '2024-01-01T12:00:00Z' },
{ id: 2, name: 'admin-layout.json', updated_at: '2024-01-02T15:30:00Z' },
{ id: 3, name: 'dashboard.json', updated_at: '2024-01-03T09:15:00Z' },
]);
const [versions] = useState<VersionItem[]>([
{ id: 1, version: 'v1.0.0', created_at: '2024-01-01T10:00:00Z', changes_summary: { added: 5, removed: 2 } },
{ id: 2, version: 'v1.1.0', created_at: '2024-01-02T11:00:00Z', changes_summary: { added: 3, removed: 1 } },
{ id: 3, version: 'v2.0.0', created_at: '2024-01-03T08:00:00Z', changes_summary: { added: 10, removed: 5 } },
]);
const [selectedFileId, setSelectedFileId] = useState<string | number>(1);
const [editorContent, setEditorContent] = useState<string>(
'{"name": "main-layout", "version": "1.0.0"}'
);
const [showAlert, setShowAlert] = useState<boolean>(false);
const [alertMessage, setAlertMessage] = useState<string>('');
const handleSave = () => {
setShowAlert(true);
setAlertMessage('레이아웃이 저장되었습니다.');
setTimeout(() => setShowAlert(false), 3000);
};
const handleFileSelect = (fileId: string | number) => {
setSelectedFileId(fileId);
const file = files.find((f) => f.id === fileId);
if (file) {
setEditorContent(`{"name": "${file.name}", "id": ${fileId}}`);
}
};
const handleRestore = (versionId: string | number) => {
const version = versions.find((v) => v.id === versionId);
if (version) {
setEditorContent(`{"restored": true, "version": "${version.version}"}`);
setShowAlert(true);
setAlertMessage(`버전 ${version.version}으로 복원되었습니다.`);
setTimeout(() => setShowAlert(false), 3000);
}
};
return (
<div className="h-screen flex flex-col">
{/* 헤더 */}
<LayoutEditorHeader
layoutName="레이아웃 편집기"
onBack={() => console.log('Back')}
onPreview={() => console.log('Preview')}
onSave={handleSave}
/>
{/* 알림 */}
{showAlert && (
<Alert
type="success"
message={alertMessage}
dismissible
onDismiss={() => setShowAlert(false)}
/>
)}
{/* 3단 레이아웃 */}
<ThreeColumnLayout
leftWidth="250px"
rightWidth="300px"
leftSlot={
<LayoutFileList
files={files}
selectedId={selectedFileId}
onSelect={handleFileSelect}
/>
}
centerSlot={
<CodeEditor
value={editorContent}
onChange={(value) => setEditorContent(value || '')}
language="json"
/>
}
rightSlot={
<LayoutHistoryPanel
layoutId={selectedFileId}
versions={versions}
onRestore={handleRestore}
/>
}
/>
</div>
);
};
describe('레이아웃 에디터 통합 테스트', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('전체 플로우 테스트', () => {
it('파일 선택 → 편집 → 저장 시나리오가 정상 작동한다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
// 1. 초기 렌더링 확인
expect(screen.getByText('레이아웃 편집기')).toBeInTheDocument();
expect(screen.getByText('main-layout.json')).toBeInTheDocument();
// 2. 파일 선택
const secondFile = screen.getByText('admin-layout.json');
await user.click(secondFile);
// 3. 에디터 내용 변경 확인
await waitFor(() => {
const editor = screen.getByTestId('editor-textarea');
const value = (editor as HTMLTextAreaElement).value;
expect(value).toContain('admin-layout.json');
expect(value).toContain('2');
});
// 4. 저장 버튼 클릭
const saveButton = screen.getByRole('button', { name: /저장/i });
await user.click(saveButton);
// 5. 성공 알림 확인
await waitFor(() => {
expect(screen.getByText('레이아웃이 저장되었습니다.')).toBeInTheDocument();
});
});
it('버전 선택 → 복원 시나리오가 정상 작동한다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
// 1. 버전 목록에서 버전 선택
const versionItem = screen.getByText(/버전 v2\.0\.0/);
await user.click(versionItem);
// 2. 복원 버튼 클릭
const restoreButton = screen.getByRole('button', { name: /복원/i });
await user.click(restoreButton);
// 3. 복원 확인
await waitFor(() => {
expect(screen.getByText(/버전 v2.0.0으로 복원되었습니다/)).toBeInTheDocument();
});
// 4. 에디터 내용이 복원된 버전으로 변경되었는지 확인
await waitFor(() => {
const editor = screen.getByTestId('editor-textarea');
const value = (editor as HTMLTextAreaElement).value;
expect(value).toContain('restored');
expect(value).toContain('v2.0.0');
});
});
it('파일 변경 → 버전 복원 → 저장 복합 시나리오가 정상 작동한다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
// 1. 다른 파일 선택
const thirdFile = screen.getByText('dashboard.json');
await user.click(thirdFile);
await waitFor(() => {
const editor = screen.getByTestId('editor-textarea');
const value = (editor as HTMLTextAreaElement).value;
expect(value).toContain('dashboard.json');
expect(value).toContain('3');
});
// 2. 버전 선택
const versionItem = screen.getByText(/버전 v1\.1\.0/);
await user.click(versionItem);
// 3. 복원
const restoreButton = screen.getByRole('button', { name: /복원/i });
await user.click(restoreButton);
await waitFor(() => {
expect(screen.getByText(/버전 v1.1.0으로 복원되었습니다/)).toBeInTheDocument();
});
// 4. 알림 사라질 때까지 대기
await waitFor(
() => {
expect(screen.queryByText(/버전 v1.1.0으로 복원되었습니다/)).not.toBeInTheDocument();
},
{ timeout: 4000 }
);
// 5. 저장
const saveButton = screen.getByRole('button', { name: /저장/i });
await user.click(saveButton);
await waitFor(() => {
expect(screen.getByText('레이아웃이 저장되었습니다.')).toBeInTheDocument();
});
});
});
describe('컴포넌트 간 상호작용 테스트', () => {
it('파일 선택 시 에디터 내용이 변경된다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
const files = ['main-layout.json', 'admin-layout.json', 'dashboard.json'];
for (let i = 0; i < files.length; i++) {
const fileElement = screen.getByText(files[i]);
await user.click(fileElement);
await waitFor(() => {
const editor = screen.getByTestId('editor-textarea');
const value = (editor as HTMLTextAreaElement).value;
expect(value).toContain(files[i]);
expect(value).toContain(String(i + 1));
});
}
});
it('버전 선택 없이 복원 버튼은 비활성화된다', () => {
render(<IntegratedLayoutEditor />);
const restoreButton = screen.getByRole('button', { name: /복원/i });
expect(restoreButton).toBeDisabled();
});
it('버전 선택 시 복원 버튼이 활성화된다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
const restoreButton = screen.getByRole('button', { name: /복원/i });
expect(restoreButton).toBeDisabled();
const versionItem = screen.getByText(/버전 v1\.0\.0/);
await user.click(versionItem);
expect(restoreButton).not.toBeDisabled();
});
});
describe('접근성 테스트', () => {
it('전체 레이아웃이 적절한 ARIA 속성을 가진다', () => {
render(<IntegratedLayoutEditor />);
const historyPanel = screen.getByRole('region', { name: '레이아웃 히스토리 패널' });
expect(historyPanel).toBeInTheDocument();
const fileList = screen.getByRole('listbox', { name: '레이아웃 파일 목록' });
expect(fileList).toBeInTheDocument();
});
it('LayoutEditorHeader가 적절한 button 역할을 가진다', () => {
render(
<LayoutEditorHeader
layoutName="테스트 헤더"
onBack={vi.fn()}
onPreview={vi.fn()}
onSave={vi.fn()}
/>
);
const saveButton = screen.getByRole('button', { name: /저장/i });
expect(saveButton).toBeInTheDocument();
const backButton = screen.getByRole('button', { name: /뒤로가기/i });
expect(backButton).toBeInTheDocument();
const previewButton = screen.getByRole('button', { name: /미리보기/i });
expect(previewButton).toBeInTheDocument();
});
it('LayoutFileList가 listbox 역할과 option을 가진다', () => {
const files: LayoutFileItem[] = [
{ id: 1, name: 'file1.json', updated_at: '2024-01-01T10:00:00Z' },
{ id: 2, name: 'file2.json', updated_at: '2024-01-02T11:00:00Z' },
];
render(<LayoutFileList files={files} selectedId={1} onSelect={vi.fn()} />);
const listbox = screen.getByRole('listbox');
expect(listbox).toBeInTheDocument();
const options = screen.getAllByRole('option');
expect(options).toHaveLength(2);
expect(options[0]).toHaveAttribute('aria-selected', 'true');
});
it('LayoutHistoryPanel이 region 역할을 가진다', () => {
const versions: VersionItem[] = [
{ id: 1, version: 'v1.0.0', created_at: '2024-01-01T10:00:00Z', changes_summary: { added: 5, removed: 2 } },
];
render(<LayoutHistoryPanel layoutId={1} versions={versions} onRestore={vi.fn()} />);
const panel = screen.getByRole('region', { name: '레이아웃 히스토리 패널' });
expect(panel).toBeInTheDocument();
});
it('Alert 컴포넌트가 alert 역할을 가진다', () => {
render(
<Alert
type="success"
message="테스트 메시지"
dismissible
onDismiss={vi.fn()}
/>
);
const alert = screen.getByRole('alert');
expect(alert).toBeInTheDocument();
expect(alert).toHaveTextContent('테스트 메시지');
});
});
describe('키보드 네비게이션 테스트', () => {
it('Enter 키로 파일을 선택할 수 있다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
const secondFile = screen.getByText('admin-layout.json').closest('li');
if (secondFile) {
secondFile.focus();
await user.keyboard('{Enter}');
await waitFor(() => {
const editor = screen.getByTestId('editor-textarea');
const value = (editor as HTMLTextAreaElement).value;
expect(value).toContain('admin-layout.json');
expect(value).toContain('2');
});
}
});
});
describe('UI 상태 테스트', () => {
it('파일 선택 시 선택된 항목이 하이라이트된다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
const secondFile = screen.getByText('admin-layout.json').closest('li');
await user.click(secondFile!);
await waitFor(() => {
expect(secondFile).toHaveClass('bg-blue-100');
});
});
it('버전 선택 시 선택된 항목이 하이라이트된다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
const versionItem = screen.getByText(/버전 v2\.0\.0/).closest('li');
await user.click(versionItem!);
await waitFor(() => {
expect(versionItem).toHaveClass('bg-blue-50');
});
});
it('저장 후 알림이 표시되고 자동으로 사라진다', async () => {
const user = userEvent.setup();
render(<IntegratedLayoutEditor />);
const saveButton = screen.getByRole('button', { name: /저장/i });
await user.click(saveButton);
// 알림 표시 확인
await waitFor(() => {
expect(screen.getByText('레이아웃이 저장되었습니다.')).toBeInTheDocument();
});
// 알림 자동 사라짐 확인
await waitFor(
() => {
expect(screen.queryByText('레이아웃이 저장되었습니다.')).not.toBeInTheDocument();
},
{ timeout: 4000 }
);
});
});
describe('엣지 케이스 테스트', () => {
it('빈 파일 목록을 처리할 수 있다', () => {
render(
<LayoutFileList
files={[]}
onSelect={vi.fn()}
/>
);
expect(screen.getByText('파일이 없습니다.')).toBeInTheDocument();
});
it('빈 버전 목록을 처리할 수 있다', () => {
render(
<LayoutHistoryPanel
layoutId={1}
versions={[]}
onRestore={vi.fn()}
/>
);
expect(screen.getByText('버전이 없습니다.')).toBeInTheDocument();
});
it('잘못된 날짜 형식을 처리할 수 있다', () => {
const files: LayoutFileItem[] = [
{ id: 1, name: 'file1.json', updated_at: 'invalid-date' },
];
render(<LayoutFileList files={files} selectedId={1} onSelect={vi.fn()} />);
expect(screen.getByText('invalid-date')).toBeInTheDocument();
});
});
});
@@ -0,0 +1,281 @@
import React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { readFileSync } from 'fs';
import { join } from 'path';
import { CodeEditor } from '../composite/CodeEditor';
import { LayoutFileList, LayoutFileItem } from '../composite/LayoutFileList';
import { VersionList, VersionItem } from '../composite/VersionList';
// Monaco Editor mock
vi.mock('@monaco-editor/react', () => ({
default: ({ value, onChange, onMount }: any) => {
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)}
/>
</div>
);
},
}));
/**
* 픽스처 파일에서 테스트 데이터 로드
*/
const loadFixture = (filename: string): string => {
const fixturePath = join(__dirname, '__fixtures__', filename);
return readFileSync(fixturePath, 'utf-8');
};
/**
* 대량의 파일 목록 생성
*/
const generateLargeFileList = (count: number): LayoutFileItem[] => {
return Array.from({ length: count }, (_, i) => ({
id: i + 1,
name: `layout-file-${i + 1}.json`,
updated_at: new Date(Date.now() - i * 3600000).toISOString(),
}));
};
/**
* 대량의 버전 목록 생성
*/
const generateLargeVersionList = (count: number): VersionItem[] => {
return Array.from({ length: count }, (_, i) => ({
id: i + 1,
version: `v${Math.floor(i / 100)}.${Math.floor((i % 100) / 10)}.${i % 10}`,
created_at: new Date(Date.now() - i * 3600000).toISOString(),
changes_summary: {
added: Math.floor(Math.random() * 20) + 1,
removed: Math.floor(Math.random() * 10),
},
}));
};
describe('레이아웃 에디터 성능 테스트', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
cleanup();
});
describe('CodeEditor 대용량 JSON 처리', () => {
it('1MB JSON 파일을 500ms 이내에 렌더링한다', async () => {
const largeJSON = loadFixture('test-1mb.json');
const startTime = performance.now();
render(<CodeEditor value={largeJSON} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(500);
expect(screen.getByTestId('monaco-editor')).toBeInTheDocument();
});
it('5MB JSON 파일을 2초 이내에 렌더링한다', async () => {
const largeJSON = loadFixture('test-5mb.json');
const startTime = performance.now();
render(<CodeEditor value={largeJSON} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(2000);
expect(screen.getByTestId('monaco-editor')).toBeInTheDocument();
});
it('10MB JSON 파일을 5초 이내에 렌더링한다', async () => {
const largeJSON = loadFixture('test-10mb.json');
const startTime = performance.now();
render(<CodeEditor value={largeJSON} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(5000);
expect(screen.getByTestId('monaco-editor')).toBeInTheDocument();
});
it('대용량 JSON 변경 시 onChange 콜백이 정상 작동한다', async () => {
const largeJSON = loadFixture('test-1mb.json');
const handleChange = vi.fn();
const user = userEvent.setup();
render(<CodeEditor value={largeJSON} onChange={handleChange} />);
const editor = screen.getByTestId('editor-textarea');
await user.type(editor, 'test');
await waitFor(() => {
expect(handleChange).toHaveBeenCalled();
});
});
});
describe('LayoutFileList 대량 데이터 렌더링', () => {
it('100개 파일을 300ms 이내에 렌더링한다', () => {
const files = generateLargeFileList(100);
const startTime = performance.now();
render(<LayoutFileList files={files} selectedId={1} onSelect={vi.fn()} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(300);
expect(screen.getByText('layout-file-1.json')).toBeInTheDocument();
});
it('500개 파일을 1초 이내에 렌더링한다', () => {
const files = generateLargeFileList(500);
const startTime = performance.now();
render(<LayoutFileList files={files} selectedId={1} onSelect={vi.fn()} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(1000);
expect(screen.getByText('layout-file-1.json')).toBeInTheDocument();
});
it('대량 파일 목록에서 파일 선택이 빠르게 동작한다', async () => {
const files = generateLargeFileList(500);
const handleSelect = vi.fn();
const user = userEvent.setup();
render(<LayoutFileList files={files} selectedId={1} onSelect={handleSelect} />);
const file = screen.getByText('layout-file-250.json');
const startTime = performance.now();
await user.click(file);
const endTime = performance.now();
const selectTime = endTime - startTime;
expect(selectTime).toBeLessThan(500);
expect(handleSelect).toHaveBeenCalledWith(250);
});
});
describe('VersionList 대량 데이터 렌더링', () => {
it('100개 버전을 300ms 이내에 렌더링한다', () => {
const versions = generateLargeVersionList(100);
const startTime = performance.now();
render(<VersionList versions={versions} onSelect={vi.fn()} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(300);
expect(screen.getByText(/버전 v0\.0\.0/)).toBeInTheDocument();
});
it('500개 버전을 1초 이내에 렌더링한다', () => {
const versions = generateLargeVersionList(500);
const startTime = performance.now();
render(<VersionList versions={versions} onSelect={vi.fn()} />);
const endTime = performance.now();
const renderTime = endTime - startTime;
expect(renderTime).toBeLessThan(1000);
expect(screen.getByText(/버전 v0\.0\.0/)).toBeInTheDocument();
});
it('대량 버전 목록에서 버전 선택이 빠르게 동작한다', async () => {
const versions = generateLargeVersionList(500);
const handleSelect = vi.fn();
const user = userEvent.setup();
render(<VersionList versions={versions} selectedId={1} onSelect={handleSelect} />);
const version = screen.getByText(/버전 v2\.5\.0/);
const startTime = performance.now();
await user.click(version);
const endTime = performance.now();
const selectTime = endTime - startTime;
expect(selectTime).toBeLessThan(500);
expect(handleSelect).toHaveBeenCalledWith(251); // ID는 1부터 시작하므로 251번째
});
});
describe('빈번한 리렌더링 성능', () => {
it('CodeEditor가 빠르게 리렌더링된다', () => {
const { rerender } = render(<CodeEditor value="test1" />);
const startTime = performance.now();
for (let i = 0; i < 10; i++) {
rerender(<CodeEditor value={`test${i}`} />);
}
const endTime = performance.now();
const totalRerenderTime = endTime - startTime;
expect(totalRerenderTime).toBeLessThan(100);
});
it('LayoutFileList가 선택 변경 시 빠르게 리렌더링된다', () => {
const files = generateLargeFileList(100);
const { rerender } = render(
<LayoutFileList files={files} selectedId={1} onSelect={vi.fn()} />
);
const startTime = performance.now();
for (let i = 1; i <= 10; i++) {
rerender(
<LayoutFileList files={files} selectedId={i} onSelect={vi.fn()} />
);
}
const endTime = performance.now();
const totalRerenderTime = endTime - startTime;
expect(totalRerenderTime).toBeLessThan(500);
});
it('VersionList가 선택 변경 시 빠르게 리렌더링된다', () => {
const versions = generateLargeVersionList(100);
const { rerender } = render(
<VersionList versions={versions} selectedId={1} onSelect={vi.fn()} />
);
const startTime = performance.now();
for (let i = 1; i <= 10; i++) {
rerender(
<VersionList versions={versions} selectedId={i} onSelect={vi.fn()} />
);
}
const endTime = performance.now();
const rerenderTime = endTime - startTime;
// CI 환경 및 테스트 환경에 따라 성능이 다를 수 있으므로 여유롭게 설정
expect(rerenderTime).toBeLessThan(500);
});
});
});
@@ -0,0 +1,21 @@
import React from 'react';
export interface AProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
/**
* 기본 a(링크) 컴포넌트
*/
export const A: React.FC<AProps> = ({
children,
className = '',
...props
}) => {
return (
<a
className={className}
{...props}
>
{children}
</a>
);
};
@@ -0,0 +1,38 @@
import React, { forwardRef } from 'react';
// G7Core 전역 객체의 스타일 헬퍼 접근
const G7Core = () => (window as any).G7Core;
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'danger' | 'success';
size?: 'sm' | 'md' | 'lg';
}
/**
* 기본 버튼 컴포넌트
*/
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(({
children,
variant = 'primary',
size = 'md',
className = '',
...props
}, ref) => {
const baseClasses = 'inline-flex items-center justify-center';
// G7Core.style.mergeClasses를 사용하여 충돌하는 Tailwind 클래스 병합
const mergedClassName = G7Core()?.style?.mergeClasses?.(baseClasses, className)
?? `${baseClasses} ${className}`;
return (
<button
ref={ref}
className={mergedClassName}
{...props}
>
{children}
</button>
);
});
Button.displayName = 'Button';
@@ -0,0 +1,52 @@
import React, { forwardRef, useEffect, useRef } from 'react';
export interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
/**
* indeterminate 상태 (부분 선택 상태)
*
* 부모-자식 체크박스 연동에서 일부 자식만 선택되었을 때 사용합니다.
* HTML checkbox의 indeterminate 속성을 JavaScript로 설정합니다.
*/
indeterminate?: boolean;
}
/**
* 기본 체크박스 컴포넌트
*
* forwardRef를 사용하여 ref 전달을 지원합니다.
* indeterminate prop을 통해 부분 선택 상태를 표시할 수 있습니다.
*/
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
({ label, className = '', indeterminate = false, ...props }, ref) => {
const internalRef = useRef<HTMLInputElement>(null);
// 외부 ref와 내부 ref를 병합
const combinedRef = (node: HTMLInputElement | null) => {
internalRef.current = node;
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
ref.current = node;
}
};
// indeterminate 상태 설정 (DOM 속성이므로 JavaScript로 설정해야 함)
useEffect(() => {
if (internalRef.current) {
internalRef.current.indeterminate = indeterminate;
}
}, [indeterminate]);
return (
<input
ref={combinedRef}
type="checkbox"
className={className}
{...props}
/>
);
}
);
Checkbox.displayName = 'Checkbox';
@@ -0,0 +1,24 @@
import React from 'react';
export interface CodeProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 code 컴포넌트
*
* 인라인 코드 또는 코드 스니펫을 표시하기 위한 기본 컴포넌트입니다.
* HTML <code> 태그를 래핑합니다.
*/
export const Code: React.FC<CodeProps> = ({
children,
className = '',
...props
}) => {
return (
<code
className={className}
{...props}
>
{children}
</code>
);
};
@@ -0,0 +1,24 @@
import React from 'react';
export interface DivProps extends React.HTMLAttributes<HTMLDivElement> {
ref?: React.Ref<HTMLDivElement>;
}
/**
* 기본 div 컴포넌트
*/
export const Div = React.forwardRef<HTMLDivElement, DivProps>(({
children,
className = '',
...props
}, ref) => {
return (
<div
ref={ref}
className={className}
{...props}
>
{children}
</div>
);
});
@@ -0,0 +1,116 @@
import React, { forwardRef, useRef, useCallback, useState } from 'react';
export interface FileInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type' | 'onChange' | 'onError'> {
/** 허용되는 파일 확장자 (예: ".zip,.pdf") */
accept?: string;
/** 최대 파일 크기 (MB) */
maxSize?: number;
/** 파일 선택 시 콜백 */
onChange?: (file: File | null) => void;
/** 에러 발생 시 콜백 */
onError?: (error: string) => void;
/** 버튼 텍스트 */
buttonText?: string;
/** 빈 상태 텍스트 */
placeholder?: string;
}
/**
* 파일 업로드 입력 컴포넌트
*
* ZIP 파일 등의 파일 업로드를 처리하며, 파일 크기 검증을 지원합니다.
*/
export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
accept,
maxSize,
onChange,
onError,
buttonText = 'Browse',
placeholder = 'No file selected',
className = '',
disabled,
...props
}, ref) => {
const internalRef = useRef<HTMLInputElement>(null);
const inputRef = (ref as React.RefObject<HTMLInputElement>) || internalRef;
const [fileName, setFileName] = useState<string>('');
const handleClick = useCallback(() => {
if (!disabled && inputRef.current) {
inputRef.current.click();
}
}, [disabled, inputRef]);
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null;
if (!file) {
setFileName('');
onChange?.(null);
return;
}
// 파일 크기 검증 (MB 단위)
if (maxSize && file.size > maxSize * 1024 * 1024) {
const errorMsg = `File size exceeds ${maxSize}MB limit`;
onError?.(errorMsg);
// 입력 초기화
if (inputRef.current) {
inputRef.current.value = '';
}
setFileName('');
return;
}
setFileName(file.name);
onChange?.(file);
}, [maxSize, onChange, onError, inputRef]);
const handleClear = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
if (inputRef.current) {
inputRef.current.value = '';
}
setFileName('');
onChange?.(null);
}, [onChange, inputRef]);
return (
<div className={`flex items-center gap-2 ${className}`}>
<input
ref={inputRef}
type="file"
accept={accept}
onChange={handleChange}
disabled={disabled}
className="hidden"
{...props}
/>
<button
type="button"
onClick={handleClick}
disabled={disabled}
className="px-4 py-2 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
{buttonText}
</button>
<span className="flex-1 text-sm text-gray-600 dark:text-gray-400 truncate">
{fileName || placeholder}
</span>
{fileName && !disabled && (
<button
type="button"
onClick={handleClear}
className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
aria-label="Clear file"
>
<svg className="w-4 h-4" 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>
);
});
FileInput.displayName = 'FileInput';
@@ -0,0 +1,21 @@
import React from 'react';
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {}
/**
* 기본 form 컴포넌트
*/
export const Form: React.FC<FormProps> = ({
children,
className = '',
...props
}) => {
return (
<form
className={className}
{...props}
>
{children}
</form>
);
};
@@ -0,0 +1,35 @@
import React from 'react';
export interface FragmentProps {
children?: React.ReactNode;
className?: string;
style?: React.CSSProperties;
}
/**
* Fragment 기본 컴포넌트
*
* React.Fragment와 유사하게 DOM 요소를 추가하지 않고 children만 렌더링합니다.
* iterator와 함께 사용하여 불필요한 wrapper div 없이 반복 렌더링할 때 유용합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "type": "basic",
* "name": "Fragment",
* "iterator": {
* "source": "{{items}}",
* "item": "item"
* },
* "children": [
* {
* "type": "basic",
* "name": "Button",
* "text": "{{item.label}}"
* }
* ]
* }
*/
export const Fragment: React.FC<FragmentProps> = ({ children }) => {
return <>{children}</>;
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H1Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h1 제목 컴포넌트
*/
export const H1: React.FC<H1Props> = ({
children,
className = '',
...props
}) => {
return (
<h1
className={className}
{...props}
>
{children}
</h1>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H2Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h2 제목 컴포넌트
*/
export const H2: React.FC<H2Props> = ({
children,
className = '',
...props
}) => {
return (
<h2
className={className}
{...props}
>
{children}
</h2>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H3Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h3 제목 컴포넌트
*/
export const H3: React.FC<H3Props> = ({
children,
className = '',
...props
}) => {
return (
<h3
className={className}
{...props}
>
{children}
</h3>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H4Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h4 제목 컴포넌트
*/
export const H4: React.FC<H4Props> = ({
children,
className = '',
...props
}) => {
return (
<h4
className={className}
{...props}
>
{children}
</h4>
);
};
@@ -0,0 +1,18 @@
import React from 'react';
export interface HrProps extends React.HTMLAttributes<HTMLHRElement> {}
/**
* 기본 hr(수평선) 컴포넌트
*/
export const Hr: React.FC<HrProps> = ({
className = '',
...props
}) => {
return (
<hr
className={className}
{...props}
/>
);
};
@@ -0,0 +1,27 @@
import React from 'react';
export interface IProps extends React.HTMLAttributes<HTMLElement> {
className?: string;
children?: React.ReactNode;
style?: React.CSSProperties;
}
/**
* I 기본 컴포넌트
*
* HTML <i> 태그를 래핑한 기본 컴포넌트입니다.
* 주로 아이콘 폰트 (FontAwesome 등)와 함께 사용됩니다.
*
* @example
* ```tsx
* <I className="fas fa-user" />
* <I className="fas fa-home" />
* ```
*/
export const I: React.FC<IProps> = ({ className = '', children, style, ...props }) => {
return (
<i className={className} style={style} {...props}>
{children}
</i>
);
};
@@ -0,0 +1,166 @@
import React from 'react';
import { IconName, IconStyle, IconSize } from './IconTypes';
export interface IconProps extends Omit<React.HTMLAttributes<HTMLElement>, 'style'> {
/**
* 아이콘 이름 (Font Awesome 클래스명 또는 IconName enum)
*
* @example
* // 문자열로 직접 지정
* <Icon name="fa-user" />
*
* // enum 사용 (타입 안전)
* <Icon name={IconName.User} />
*/
name: string | IconName;
/**
* 아이콘 스타일 (Font Awesome 5/6)
*
* - solid: fas (기본값)
* - regular: far
* - light: fal
* - duotone: fad
* - brands: fab
*/
iconStyle?: IconStyle;
/**
* CSS 스타일 객체 (HTML style 속성)
*/
style?: React.CSSProperties;
/**
* 아이콘 크기
*
* @default 'md'
*/
size?: IconSize;
/**
* 색상 (Tailwind 클래스 또는 CSS 색상)
*/
color?: string;
/**
* 회전 애니메이션 활성화
*/
spin?: boolean;
/**
* 펄스 애니메이션 활성화 (8단계 회전)
*/
pulse?: boolean;
/**
* 고정 너비 (아이콘 정렬 시 유용)
*/
fixedWidth?: boolean;
/**
* 접근성 레이블 (자동 생성 가능)
*/
ariaLabel?: string;
}
/**
* Font Awesome 아이콘 컴포넌트
*
* Font Awesome 5/6 버전과 호환되며 다양한 props를 지원합니다.
*
* @example
* // 기본 사용
* <Icon name="fa-user" />
*
* // enum 사용 (타입 안전)
* <Icon name={IconName.Search} />
*
* // 스타일 및 크기 지정
* <Icon name={IconName.Heart} style="regular" size="2x" />
*
* // 애니메이션
* <Icon name={IconName.Spinner} spin />
* <Icon name={IconName.CircleNotch} pulse />
*
* // 색상 지정
* <Icon name={IconName.Star} color="text-yellow-500" />
*
* // 접근성
* <Icon name={IconName.User} ariaLabel="사용자 프로필" />
*/
export const Icon: React.FC<IconProps> = ({
name,
iconStyle = 'solid',
size,
color,
spin = false,
pulse = false,
fixedWidth = false,
ariaLabel,
className = '',
style,
...props
}) => {
// Font Awesome 스타일 클래스 매핑
const styleClassMap: Record<IconStyle, string> = {
solid: 'fas',
regular: 'far',
light: 'fal',
duotone: 'fad',
brands: 'fab',
};
// 스타일 접두사를 IconStyle로 변환하는 매핑
const stylePrefixMap: Record<string, IconStyle> = {
'fa-solid': 'solid',
'fa-regular': 'regular',
'fa-light': 'light',
'fa-duotone': 'duotone',
'fa-brands': 'brands',
};
const nameStr = typeof name === 'string' ? name : String(name);
// "fa-regular fa-pen-to-square" 형식 파싱
let resolvedStyle = iconStyle;
let iconName = nameStr;
// 스타일 접두사가 포함된 경우 파싱 (예: "fa-regular fa-pen-to-square")
for (const [prefix, styleValue] of Object.entries(stylePrefixMap)) {
if (nameStr.startsWith(prefix + ' ')) {
resolvedStyle = styleValue;
iconName = nameStr.substring(prefix.length + 1); // 스타일 접두사와 공백 제거
break;
}
}
// 아이콘 이름에서 'fa-' 접두사 제거 (이미 있으면)
iconName = iconName.replace(/^fa-/, '');
// 클래스 조합
const classes = [
styleClassMap[resolvedStyle],
`fa-${iconName}`,
size && `fa-${size}`,
spin && 'fa-spin',
pulse && 'fa-pulse',
fixedWidth && 'fa-fw',
color,
className,
]
.filter(Boolean)
.join(' ');
// 접근성: ariaLabel이 없으면 name에서 생성
const accessibilityLabel = ariaLabel || iconName.replace(/-/g, ' ');
return (
<i
className={classes}
style={style}
aria-label={accessibilityLabel}
role="img"
{...props}
/>
);
};
@@ -0,0 +1,291 @@
/**
* Font Awesome 아이콘 스타일
*/
export type IconStyle = 'solid' | 'regular' | 'light' | 'duotone' | 'brands';
/**
* Font Awesome 아이콘 크기
*/
export type IconSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2x' | '3x' | '4x' | '5x';
/**
* 자주 사용되는 Font Awesome 아이콘 이름
*
* @example
* // 사용 예시
* <Icon name="user" />
* <Icon name="search" />
* <Icon name="shopping-cart" />
*/
export enum IconName {
// 사용자 및 계정
User = 'fa-user',
Users = 'fa-users',
UserCircle = 'fa-user-circle',
UserPlus = 'fa-user-plus',
UserMinus = 'fa-user-minus',
UserShield = 'fa-user-shield',
// 액션 아이콘
Search = 'fa-search',
Edit = 'fa-edit',
Pencil = 'fa-pencil-alt',
Trash = 'fa-trash',
Save = 'fa-save',
Plus = 'fa-plus',
Minus = 'fa-minus',
Check = 'fa-check',
Times = 'fa-times',
Download = 'fa-download',
Upload = 'fa-upload',
Copy = 'fa-copy',
ExternalLink = 'fa-external-link-alt',
// 네비게이션
Home = 'fa-home',
CaretRight = 'fa-caret-right',
CaretDown = 'fa-caret-down',
ChevronLeft = 'fa-chevron-left',
ChevronRight = 'fa-chevron-right',
ChevronUp = 'fa-chevron-up',
ChevronDown = 'fa-chevron-down',
AngleLeft = 'fa-angle-left',
AngleRight = 'fa-angle-right',
AngleUp = 'fa-angle-up',
AngleDown = 'fa-angle-down',
ArrowUp = 'fa-arrow-up',
ArrowDown = 'fa-arrow-down',
ArrowLeft = 'fa-arrow-left',
ArrowRight = 'fa-arrow-right',
Bars = 'fa-bars',
EllipsisVertical = 'fa-ellipsis-v',
EllipsisHorizontal = 'fa-ellipsis-h',
// 상태 아이콘
CheckCircle = 'fa-check-circle',
TimesCircle = 'fa-times-circle',
ExclamationCircle = 'fa-exclamation-circle',
ExclamationTriangle = 'fa-exclamation-triangle',
InfoCircle = 'fa-info-circle',
QuestionCircle = 'fa-question-circle',
XCircle = 'fa-times-circle',
// 이커머스
ShoppingCart = 'fa-shopping-cart',
ShoppingBag = 'fa-shopping-bag',
CreditCard = 'fa-credit-card',
Tag = 'fa-tag',
Tags = 'fa-tags',
// 파일 및 문서
File = 'fa-file',
FileAlt = 'fa-file-alt',
Folder = 'fa-folder',
FolderOpen = 'fa-folder-open',
// 통신
Envelope = 'fa-envelope',
Phone = 'fa-phone',
Comment = 'fa-comment',
Comments = 'fa-comments',
// 설정
Cog = 'fa-cog',
Cogs = 'fa-cogs',
Settings = 'fa-cog',
Wrench = 'fa-wrench',
Sliders = 'fa-sliders-h',
// 미디어
Image = 'fa-image',
Images = 'fa-images',
Video = 'fa-video',
Camera = 'fa-camera',
// 소셜
Heart = 'fa-heart',
Star = 'fa-star',
ThumbsUp = 'fa-thumbs-up',
ThumbsDown = 'fa-thumbs-down',
Share = 'fa-share',
// 시간
Clock = 'fa-clock',
Calendar = 'fa-calendar',
CalendarAlt = 'fa-calendar-alt',
// 기타
Lock = 'fa-lock',
Unlock = 'fa-unlock',
Eye = 'fa-eye',
EyeSlash = 'fa-eye-slash',
Bell = 'fa-bell',
Flag = 'fa-flag',
Map = 'fa-map',
MapMarker = 'fa-map-marker-alt',
Globe = 'fa-globe',
Link = 'fa-link',
Unlink = 'fa-unlink',
Sun = 'fa-sun',
Moon = 'fa-moon',
// 차트 및 통계
ChartBar = 'fa-chart-bar',
ChartLine = 'fa-chart-line',
ChartPie = 'fa-chart-pie',
ChartArea = 'fa-chart-area',
// 스피너 (로딩)
Spinner = 'fa-spinner',
CircleNotch = 'fa-circle-notch',
// 배지 아이콘
CheckBadge = 'fa-badge-check',
// 확장 시스템 (모듈/플러그인/템플릿)
Cube = 'fa-cube',
Cubes = 'fa-cubes',
Plug = 'fa-plug',
PuzzlePiece = 'fa-puzzle-piece',
Palette = 'fa-palette',
}
/**
* 문자열 아이콘 이름을 IconName enum으로 매핑합니다.
* JSON 레이아웃에서 문자열로 아이콘 이름을 지정할 때 사용합니다.
*/
export const iconNameMap: Record<string, IconName> = {
// 사용자 및 계정
'user': IconName.User,
'users': IconName.Users,
'user-circle': IconName.UserCircle,
'user-plus': IconName.UserPlus,
'user-minus': IconName.UserMinus,
'user-shield': IconName.UserShield,
// 액션 아이콘
'search': IconName.Search,
'edit': IconName.Edit,
'pencil': IconName.Pencil,
'trash': IconName.Trash,
'save': IconName.Save,
'plus': IconName.Plus,
'minus': IconName.Minus,
'check': IconName.Check,
'times': IconName.Times,
'download': IconName.Download,
'upload': IconName.Upload,
'copy': IconName.Copy,
'external-link': IconName.ExternalLink,
// 네비게이션
'home': IconName.Home,
'caret-right': IconName.CaretRight,
'caret-down': IconName.CaretDown,
'chevron-left': IconName.ChevronLeft,
'chevron-right': IconName.ChevronRight,
'chevron-up': IconName.ChevronUp,
'chevron-down': IconName.ChevronDown,
'angle-left': IconName.AngleLeft,
'angle-right': IconName.AngleRight,
'angle-up': IconName.AngleUp,
'angle-down': IconName.AngleDown,
'arrow-up': IconName.ArrowUp,
'arrow-down': IconName.ArrowDown,
'arrow-left': IconName.ArrowLeft,
'arrow-right': IconName.ArrowRight,
'bars': IconName.Bars,
'ellipsis-vertical': IconName.EllipsisVertical,
'ellipsis-v': IconName.EllipsisVertical,
'ellipsis-horizontal': IconName.EllipsisHorizontal,
'ellipsis-h': IconName.EllipsisHorizontal,
// 상태 아이콘
'check-circle': IconName.CheckCircle,
'times-circle': IconName.TimesCircle,
'x-circle': IconName.XCircle,
'exclamation-circle': IconName.ExclamationCircle,
'exclamation-triangle': IconName.ExclamationTriangle,
'info-circle': IconName.InfoCircle,
'question-circle': IconName.QuestionCircle,
// 이커머스
'shopping-cart': IconName.ShoppingCart,
'shopping-bag': IconName.ShoppingBag,
'credit-card': IconName.CreditCard,
'tag': IconName.Tag,
'tags': IconName.Tags,
// 파일 및 문서
'file': IconName.File,
'file-alt': IconName.FileAlt,
'folder': IconName.Folder,
'folder-open': IconName.FolderOpen,
// 통신
'envelope': IconName.Envelope,
'phone': IconName.Phone,
'comment': IconName.Comment,
'comments': IconName.Comments,
// 설정
'cog': IconName.Cog,
'cogs': IconName.Cogs,
'settings': IconName.Settings,
'wrench': IconName.Wrench,
'sliders': IconName.Sliders,
// 미디어
'image': IconName.Image,
'images': IconName.Images,
'video': IconName.Video,
'camera': IconName.Camera,
// 소셜
'heart': IconName.Heart,
'star': IconName.Star,
'thumbs-up': IconName.ThumbsUp,
'thumbs-down': IconName.ThumbsDown,
'share': IconName.Share,
// 시간
'clock': IconName.Clock,
'calendar': IconName.Calendar,
'calendar-alt': IconName.CalendarAlt,
// 기타
'lock': IconName.Lock,
'unlock': IconName.Unlock,
'eye': IconName.Eye,
'eye-slash': IconName.EyeSlash,
'bell': IconName.Bell,
'flag': IconName.Flag,
'map': IconName.Map,
'map-marker': IconName.MapMarker,
'globe': IconName.Globe,
'link': IconName.Link,
'unlink': IconName.Unlink,
'sun': IconName.Sun,
'moon': IconName.Moon,
// 차트 및 통계
'chart-bar': IconName.ChartBar,
'chart-line': IconName.ChartLine,
'chart-pie': IconName.ChartPie,
'chart-area': IconName.ChartArea,
// 스피너 (로딩)
'spinner': IconName.Spinner,
'circle-notch': IconName.CircleNotch,
// 배지 아이콘
'check-badge': IconName.CheckBadge,
'badge-check': IconName.CheckBadge,
// 확장 시스템 (모듈/플러그인/템플릿)
'cube': IconName.Cube,
'cubes': IconName.Cubes,
'plug': IconName.Plug,
'puzzle-piece': IconName.PuzzlePiece,
'palette': IconName.Palette,
};
@@ -0,0 +1,20 @@
import React from 'react';
export interface ImgProps extends React.ImgHTMLAttributes<HTMLImageElement> {}
/**
* 기본 이미지 컴포넌트
*/
export const Img: React.FC<ImgProps> = ({
className = '',
alt = '',
...props
}) => {
return (
<img
className={className}
alt={alt}
{...props}
/>
);
};
@@ -0,0 +1,159 @@
import React, { useRef, useCallback, useState, useEffect, forwardRef, useImperativeHandle } from 'react';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
}
/**
* 기본 입력 필드 컴포넌트
*
* IME(한글 등) 조합 중에는 외부 onChange 이벤트를 발생시키지 않습니다.
* 내부 로컬 상태를 사용하여 입력을 처리하고, 조합이 완료되면 외부에 알립니다.
*
* forwardRef를 사용하여 외부에서 ref로 input 요소에 접근할 수 있습니다.
* 예: indeterminate 상태 설정 시 ref.current.indeterminate = true
*/
export const Input = forwardRef<HTMLInputElement, InputProps>(({
label,
error,
className = '',
onChange,
onKeyPress,
value,
defaultValue,
type = 'text',
checked,
defaultChecked,
...props
}, ref) => {
// radio/checkbox 타입인지 확인
const isCheckableType = type === 'radio' || type === 'checkbox';
// IME 조합 중인지 추적 (text input에만 필요)
const isComposingRef = useRef(false);
// input 요소 참조
const internalRef = useRef<HTMLInputElement>(null);
// 외부 ref와 내부 ref를 연결
useImperativeHandle(ref, () => internalRef.current as HTMLInputElement);
// 내부 로컬 값 (IME 조합 중에도 화면에 표시됨) - text input에만 사용
const [localValue, setLocalValue] = useState<string>(
(value as string) ?? (defaultValue as string) ?? ''
);
// 외부 value prop이 변경되면 로컬 값도 동기화 (text input에만 적용)
// 단, 사용자가 입력 중(포커스 상태)이면 동기화 건너뜀 (debounce 대기 중 stale value 플리커 방지)
useEffect(() => {
if (!isCheckableType && !isComposingRef.current && value !== undefined) {
const isFocused = internalRef.current && document.activeElement === internalRef.current;
if (isFocused) {
return;
}
setLocalValue(value as string);
}
}, [value, isCheckableType]);
const handleCompositionStart = useCallback(() => {
isComposingRef.current = true;
}, []);
const handleCompositionEnd = useCallback(
(e: React.CompositionEvent<HTMLInputElement>) => {
isComposingRef.current = false;
// 조합 완료 후 onChange 이벤트 발생
if (onChange) {
// 현재 input의 실제 값을 사용
const currentValue = (e.target as HTMLInputElement).value;
setLocalValue(currentValue);
// 새로운 ChangeEvent 생성
const changeEvent = new Event('change', { bubbles: true }) as unknown as React.ChangeEvent<HTMLInputElement>;
Object.defineProperty(changeEvent, 'target', {
writable: false,
value: { value: currentValue },
});
Object.defineProperty(changeEvent, 'currentTarget', {
writable: false,
value: { value: currentValue },
});
onChange(changeEvent);
}
},
[onChange]
);
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
// 항상 로컬 값은 업데이트 (화면에 입력이 보이도록)
setLocalValue(newValue);
// IME 조합 중이면 외부 onChange를 호출하지 않음
if (isComposingRef.current) {
return;
}
if (onChange) {
onChange(e);
}
},
[onChange]
);
const handleKeyPress = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
// IME 조합 중이면 keypress 무시 (Enter 등)
if (isComposingRef.current) {
return;
}
if (onKeyPress) {
onKeyPress(e);
}
},
[onKeyPress]
);
// HTML 표준 속성이 아닌 것들을 필터링 (템플릿 엔진 내부 속성)
const { loadingactions, formdata, ...validProps } = props as any;
// radio/checkbox: checked 속성 사용
// text input: value 속성 사용 (IME 처리 포함)
if (isCheckableType) {
return (
<input
ref={internalRef}
type={type}
className={className}
onChange={onChange}
checked={checked}
defaultChecked={defaultChecked}
value={value}
{...validProps}
/>
);
}
// text input: controlled/uncontrolled 구분
const inputProps = value !== undefined
? { value: localValue }
: { defaultValue };
return (
<input
ref={internalRef}
type={type}
className={className}
onChange={handleChange}
onKeyPress={handleKeyPress}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
{...inputProps}
{...validProps}
/>
);
});
// displayName 설정 (React DevTools에서 컴포넌트 이름 표시)
Input.displayName = 'Input';
@@ -0,0 +1,21 @@
import React from 'react';
export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {}
/**
* 기본 레이블 컴포넌트
*/
export const Label: React.FC<LabelProps> = ({
children,
className = '',
...props
}) => {
return (
<label
className={className}
{...props}
>
{children}
</label>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface LiProps extends React.LiHTMLAttributes<HTMLLIElement> {}
/**
* 기본 li(목록 항목) 컴포넌트
*/
export const Li: React.FC<LiProps> = ({
children,
className = '',
...props
}) => {
return (
<li
className={className}
{...props}
>
{children}
</li>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface NavProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 nav 컴포넌트
*/
export const Nav: React.FC<NavProps> = ({
children,
className = '',
...props
}) => {
return (
<nav
className={className}
{...props}
>
{children}
</nav>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface OlProps extends React.HTMLAttributes<HTMLOListElement> {}
/**
* 기본 ol(순서있는 목록) 컴포넌트
*/
export const Ol: React.FC<OlProps> = ({
children,
className = '',
...props
}) => {
return (
<ol
className={className}
{...props}
>
{children}
</ol>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface OptgroupProps extends React.OptgroupHTMLAttributes<HTMLOptGroupElement> {}
/**
* 기본 optgroup 컴포넌트 (Select 내부에서 옵션 그룹화)
*/
export const Optgroup: React.FC<OptgroupProps> = ({
children,
className = '',
...props
}) => {
return (
<optgroup
className={className}
{...props}
>
{children}
</optgroup>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface OptionProps extends React.OptionHTMLAttributes<HTMLOptionElement> {}
/**
* 기본 option 컴포넌트 (Select 내부에서 사용)
*/
export const Option: React.FC<OptionProps> = ({
children,
className = '',
...props
}) => {
return (
<option
className={className}
{...props}
>
{children}
</option>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface PProps extends React.HTMLAttributes<HTMLParagraphElement> {}
/**
* 기본 p(단락) 컴포넌트
*/
export const P: React.FC<PProps> = ({
children,
className = '',
...props
}) => {
return (
<p
className={className}
{...props}
>
{children}
</p>
);
};
@@ -0,0 +1,24 @@
import React from 'react';
export interface PreProps extends React.HTMLAttributes<HTMLPreElement> {}
/**
* 기본 pre 컴포넌트
*
* 서식이 지정된 텍스트를 표시하기 위한 기본 컴포넌트입니다.
* HTML <pre> 태그를 래핑합니다.
*/
export const Pre: React.FC<PreProps> = ({
children,
className = '',
...props
}) => {
return (
<pre
className={className}
{...props}
>
{children}
</pre>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface SectionProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 section 컴포넌트
*/
export const Section: React.FC<SectionProps> = ({
children,
className = '',
...props
}) => {
return (
<section
className={className}
{...props}
>
{children}
</section>
);
};
@@ -0,0 +1,232 @@
import React, { useMemo, useState, useRef, useEffect } from 'react';
import { Div } from './Div';
import { Button } from './Button';
import { Span } from './Span';
import { Svg } from './Svg';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:Select')) ?? {
log: (...args: unknown[]) => console.log('[Comp:Select]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:Select]', ...args),
error: (...args: unknown[]) => console.error('[Comp:Select]', ...args),
};
export interface SelectOption {
value: string | number;
label: string;
disabled?: boolean;
}
export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectElement>, 'onChange'> {
label?: string;
error?: string;
options?: SelectOption[] | string[];
onChange?: (e: React.ChangeEvent<HTMLSelectElement> | { target: { value: string | number } }) => void;
}
/**
* 로케일 코드를 사람이 읽을 수 있는 이름으로 변환
*/
function 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;
}
/**
* 커스텀 Select 컴포넌트
*
* options prop을 사용하여 드롭다운 메뉴를 생성합니다.
* 둥근 모서리, 그림자, 체크마크가 있는 커스텀 스타일을 지원합니다.
*/
export const Select: React.FC<SelectProps> = ({
children,
label,
error,
options,
className = '',
value,
onChange,
disabled,
...props
}) => {
const [isOpen, setIsOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
// options를 SelectOption[] 형식으로 정규화
const normalizedOptions = useMemo((): SelectOption[] | null => {
if (!options) return null;
// 배열이 아닌 경우 (바인딩 에러 또는 잘못된 prop)
if (!Array.isArray(options)) {
logger.warn('options prop is not an array:', options);
return null;
}
// 빈 배열인 경우
if (options.length === 0) return [];
// string[] 배열인 경우
if (typeof options[0] === 'string') {
return (options as string[]).map((locale): SelectOption => ({
value: locale,
label: getLocaleName(locale),
}));
}
// SelectOption[] 배열인 경우 (기존 동작)
return options as SelectOption[];
}, [options]);
// 현재 선택된 옵션의 라벨 가져오기
const selectedLabel = useMemo(() => {
if (!normalizedOptions) return '';
const selected = normalizedOptions.find(opt => String(opt.value) === String(value));
return selected?.label || '';
}, [normalizedOptions, 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 = () => {
if (!disabled) {
setIsOpen(!isOpen);
}
};
const handleSelect = (optionValue: string | number) => {
if (onChange) {
// ActionDispatcher가 이벤트를 인식할 수 있도록 preventDefault 메서드 포함
const syntheticEvent = {
target: { value: optionValue },
preventDefault: () => {},
stopPropagation: () => {},
type: 'change',
};
onChange(syntheticEvent as any);
}
setIsOpen(false);
buttonRef.current?.focus();
};
// options가 없으면 기본 select 사용 (children 지원)
if (!normalizedOptions) {
return (
<select
className={className}
value={value}
onChange={onChange as React.ChangeEventHandler<HTMLSelectElement>}
disabled={disabled}
{...props}
>
{children}
</select>
);
}
// 기본 스타일 (className이 없을 때 적용)
const hasCustomStyle = className && className.includes('bg-');
// 커스텀 스타일에 텍스트 색상이 없으면 기본 텍스트 색상 보충
const hasTextColor = className && /text-(gray|red|blue|green|yellow|white|black|indigo|purple|pink|orange|amber|emerald|teal|cyan|slate)-\d+|text-white|text-black/.test(className);
const baseButtonClass = hasCustomStyle
? `${className}${hasTextColor ? '' : ' text-gray-700 dark:text-gray-200'}`
: `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 ${className}`;
return (
<Div ref={containerRef} className="relative">
<Button
ref={buttonRef}
type="button"
onClick={handleToggle}
disabled={disabled}
className={`${baseButtonClass} flex items-center justify-between gap-2 text-left cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed`}
aria-haspopup="listbox"
aria-expanded={isOpen}
>
<Span className="truncate">{selectedLabel || '\u00A0'}</Span>
<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="py-2 max-h-60 overflow-auto">
{normalizedOptions.map((option) => {
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 flex items-center justify-between hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${
isSelected ? 'text-blue-600 dark:text-blue-400 font-medium' : 'text-gray-700 dark:text-gray-200'
} ${option.disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
role="option"
aria-selected={isSelected}
>
<Span>{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>
)}
</Button>
);
})}
</Div>
</Div>
)}
</Div>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface SpanProps extends React.HTMLAttributes<HTMLSpanElement> {}
/**
* 기본 span 컴포넌트
*/
export const Span: React.FC<SpanProps> = ({
children,
className = '',
...props
}) => {
return (
<span
className={className}
{...props}
>
{children}
</span>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface SvgProps extends React.SVGAttributes<SVGSVGElement> {}
/**
* 기본 svg 컴포넌트
*/
export const Svg: React.FC<SvgProps> = ({
children,
className = '',
...props
}) => {
return (
<svg
className={className}
{...props}
>
{children}
</svg>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TableProps extends React.TableHTMLAttributes<HTMLTableElement> {}
/**
* 기본 table 컴포넌트
*/
export const Table: React.FC<TableProps> = ({
children,
className = '',
...props
}) => {
return (
<table
className={className}
{...props}
>
{children}
</table>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TbodyProps extends React.HTMLAttributes<HTMLTableSectionElement> {}
/**
* 기본 tbody 컴포넌트
*/
export const Tbody: React.FC<TbodyProps> = ({
children,
className = '',
...props
}) => {
return (
<tbody
className={className}
{...props}
>
{children}
</tbody>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TdProps extends React.TdHTMLAttributes<HTMLTableCellElement> {}
/**
* 기본 td(테이블 데이터 셀) 컴포넌트
*/
export const Td: React.FC<TdProps> = ({
children,
className = '',
...props
}) => {
return (
<td
className={className}
{...props}
>
{children}
</td>
);
};
@@ -0,0 +1,106 @@
import React, { useRef, useCallback, useState, useEffect } from 'react';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
label?: string;
error?: string;
}
/**
* 기본 텍스트 영역 컴포넌트
*
* IME(한글 등) 조합 중에는 외부 onChange 이벤트를 발생시키지 않습니다.
* 내부 로컬 상태를 사용하여 입력을 처리하고, 조합이 완료되면 외부에 알립니다.
*/
export const Textarea: React.FC<TextareaProps> = ({
label,
error,
className = '',
onChange,
value,
defaultValue,
...props
}) => {
// IME 조합 중인지 추적
const isComposingRef = useRef(false);
// textarea 요소 참조
const textareaRef = useRef<HTMLTextAreaElement>(null);
// 내부 로컬 값 (IME 조합 중에도 화면에 표시됨)
const [localValue, setLocalValue] = useState<string>(
(value as string) ?? (defaultValue as string) ?? ''
);
// 외부 value prop이 변경되면 로컬 값도 동기화
useEffect(() => {
if (!isComposingRef.current && value !== undefined) {
setLocalValue(value as string);
}
}, [value]);
const handleCompositionStart = useCallback(() => {
isComposingRef.current = true;
}, []);
const handleCompositionEnd = useCallback(
(e: React.CompositionEvent<HTMLTextAreaElement>) => {
isComposingRef.current = false;
// 조합 완료 후 onChange 이벤트 발생
if (onChange) {
// 현재 textarea의 실제 값을 사용
const currentValue = (e.target as HTMLTextAreaElement).value;
setLocalValue(currentValue);
// 새로운 ChangeEvent 생성
const changeEvent = new Event('change', { bubbles: true }) as unknown as React.ChangeEvent<HTMLTextAreaElement>;
Object.defineProperty(changeEvent, 'target', {
writable: false,
value: { value: currentValue },
});
Object.defineProperty(changeEvent, 'currentTarget', {
writable: false,
value: { value: currentValue },
});
onChange(changeEvent);
}
},
[onChange]
);
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newValue = e.target.value;
// 항상 로컬 값은 업데이트 (화면에 입력이 보이도록)
setLocalValue(newValue);
// IME 조합 중이면 외부 onChange를 호출하지 않음
if (isComposingRef.current) {
return;
}
if (onChange) {
onChange(e);
}
},
[onChange]
);
// HTML 표준 속성이 아닌 것들을 필터링 (템플릿 엔진 내부 속성)
const { loadingactions, formdata, ...validProps } = props as any;
// controlled/uncontrolled 구분
const textareaValueProps = value !== undefined
? { value: localValue }
: { defaultValue };
return (
<textarea
ref={textareaRef}
className={className}
onChange={handleChange}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
{...textareaValueProps}
{...validProps}
/>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TfootProps extends React.HTMLAttributes<HTMLTableSectionElement> {}
/**
* 기본 tfoot 컴포넌트
*/
export const Tfoot: React.FC<TfootProps> = ({
children,
className = '',
...props
}) => {
return (
<tfoot
className={className}
{...props}
>
{children}
</tfoot>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface ThProps extends React.ThHTMLAttributes<HTMLTableCellElement> {}
/**
* 기본 th(테이블 헤더 셀) 컴포넌트
*/
export const Th: React.FC<ThProps> = ({
children,
className = '',
...props
}) => {
return (
<th
className={className}
{...props}
>
{children}
</th>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TheadProps extends React.HTMLAttributes<HTMLTableSectionElement> {}
/**
* 기본 thead 컴포넌트
*/
export const Thead: React.FC<TheadProps> = ({
children,
className = '',
...props
}) => {
return (
<thead
className={className}
{...props}
>
{children}
</thead>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TrProps extends React.HTMLAttributes<HTMLTableRowElement> {}
/**
* 기본 tr(테이블 행) 컴포넌트
*/
export const Tr: React.FC<TrProps> = ({
children,
className = '',
...props
}) => {
return (
<tr
className={className}
{...props}
>
{children}
</tr>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface UlProps extends React.HTMLAttributes<HTMLUListElement> {}
/**
* 기본 ul(순서없는 목록) 컴포넌트
*/
export const Ul: React.FC<UlProps> = ({
children,
className = '',
...props
}) => {
return (
<ul
className={className}
{...props}
>
{children}
</ul>
);
};
@@ -0,0 +1,156 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from '../Button';
describe('Button 컴포넌트', () => {
describe('기본 렌더링', () => {
it('자식 요소를 렌더링한다', () => {
render(<Button>클릭하기</Button>);
expect(screen.getByText('클릭하기')).toBeTruthy();
});
it('기본 variant는 primary이다', () => {
const { container } = render(<Button>버튼</Button>);
const button = container.querySelector('button');
expect(button).toBeTruthy();
});
it('기본 size는 md이다', () => {
const { container } = render(<Button>버튼</Button>);
const button = container.querySelector('button');
expect(button).toBeTruthy();
});
});
describe('Variant Props', () => {
it('primary variant가 적용된다', () => {
render(<Button variant="primary">Primary 버튼</Button>);
expect(screen.getByText('Primary 버튼')).toBeTruthy();
});
it('secondary variant가 적용된다', () => {
render(<Button variant="secondary">Secondary 버튼</Button>);
expect(screen.getByText('Secondary 버튼')).toBeTruthy();
});
it('danger variant가 적용된다', () => {
render(<Button variant="danger">Danger 버튼</Button>);
expect(screen.getByText('Danger 버튼')).toBeTruthy();
});
it('success variant가 적용된다', () => {
render(<Button variant="success">Success 버튼</Button>);
expect(screen.getByText('Success 버튼')).toBeTruthy();
});
});
describe('Size Props', () => {
it('sm size가 적용된다', () => {
render(<Button size="sm">작은 버튼</Button>);
expect(screen.getByText('작은 버튼')).toBeTruthy();
});
it('md size가 적용된다', () => {
render(<Button size="md">중간 버튼</Button>);
expect(screen.getByText('중간 버튼')).toBeTruthy();
});
it('lg size가 적용된다', () => {
render(<Button size="lg">큰 버튼</Button>);
expect(screen.getByText('큰 버튼')).toBeTruthy();
});
});
describe('이벤트 핸들링', () => {
it('onClick 핸들러가 호출된다', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>클릭</Button>);
const button = screen.getByText('클릭');
fireEvent.click(button);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('disabled 상태에서는 클릭 이벤트가 발생하지 않는다', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick} disabled>비활성 버튼</Button>);
const button = screen.getByText('비활성 버튼');
fireEvent.click(button);
expect(handleClick).not.toHaveBeenCalled();
});
});
describe('HTML 속성', () => {
it('type 속성이 적용된다', () => {
const { container } = render(<Button type="submit">제출</Button>);
const button = container.querySelector('button');
expect(button?.type).toBe('submit');
});
it('disabled 속성이 적용된다', () => {
const { container } = render(<Button disabled>비활성</Button>);
const button = container.querySelector('button');
expect(button?.disabled).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Button name="testButton">버튼</Button>);
const button = container.querySelector('button');
expect(button?.name).toBe('testButton');
});
it('value 속성이 적용된다', () => {
const { container } = render(<Button value="testValue">버튼</Button>);
const button = container.querySelector('button');
expect(button?.value).toBe('testValue');
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Button className="custom-button">버튼</Button>);
const button = container.querySelector('button');
expect(button?.className).toContain('custom-button');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Button aria-label="사용자 정의 레이블">버튼</Button>);
const button = container.querySelector('button');
expect(button?.getAttribute('aria-label')).toBe('사용자 정의 레이블');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Button data-testid="test-button">버튼</Button>);
const button = container.querySelector('button');
expect(button?.getAttribute('data-testid')).toBe('test-button');
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleClick = vi.fn();
const { container } = render(
<Button
variant="danger"
size="lg"
className="custom-class"
onClick={handleClick}
type="button"
>
복합 버튼
</Button>
);
const button = container.querySelector('button');
expect(button).toBeTruthy();
expect(button?.className).toContain('custom-class');
expect(button?.type).toBe('button');
fireEvent.click(button!);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,254 @@
import { describe, it, expect, vi } from 'vitest';
import { render, fireEvent } from '@testing-library/react';
import React from 'react';
import { Checkbox } from '../Checkbox';
describe('Checkbox 컴포넌트', () => {
describe('기본 렌더링', () => {
it('checkbox 요소가 렌더링된다', () => {
const { container } = render(<Checkbox />);
const checkbox = container.querySelector('input[type="checkbox"]');
expect(checkbox).toBeTruthy();
});
it('type이 checkbox이다', () => {
const { container } = render(<Checkbox />);
const checkbox = container.querySelector('input');
expect(checkbox?.type).toBe('checkbox');
});
it('기본적으로 체크되지 않은 상태이다', () => {
const { container } = render(<Checkbox />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
});
});
describe('Checked 상태', () => {
it('checked prop이 true일 때 체크된다', () => {
const { container } = render(<Checkbox checked onChange={() => {}} />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
it('checked prop이 false일 때 체크되지 않는다', () => {
const { container } = render(<Checkbox checked={false} onChange={() => {}} />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
});
it('defaultChecked prop이 적용된다', () => {
const { container } = render(<Checkbox defaultChecked />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
});
describe('이벤트 핸들링', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Checkbox onChange={handleChange} />);
const checkbox = container.querySelector('input')!;
fireEvent.click(checkbox);
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('클릭 시 체크 상태가 토글된다', () => {
const TestComponent = () => {
const [checked, setChecked] = React.useState(false);
return <Checkbox checked={checked} onChange={() => setChecked(!checked)} />;
};
const { container } = render(<TestComponent />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
fireEvent.click(checkbox);
expect(checkbox.checked).toBe(true);
fireEvent.click(checkbox);
expect(checkbox.checked).toBe(false);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(<Checkbox onFocus={handleFocus} />);
const checkbox = container.querySelector('input')!;
fireEvent.focus(checkbox);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(<Checkbox onBlur={handleBlur} />);
const checkbox = container.querySelector('input')!;
fireEvent.blur(checkbox);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
});
describe('HTML 속성', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(<Checkbox disabled />);
const checkbox = container.querySelector('input');
expect(checkbox?.disabled).toBe(true);
});
it('disabled 상태에서 클릭하면 상태가 변하지 않는다', () => {
const { container } = render(<Checkbox disabled />);
const checkbox = container.querySelector('input') as HTMLInputElement;
const initialChecked = checkbox.checked;
fireEvent.click(checkbox);
// disabled 상태에서도 React는 이벤트를 발생시키지만, 실제로는 변경되지 않음
expect(checkbox.disabled).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(<Checkbox required />);
const checkbox = container.querySelector('input');
expect(checkbox?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Checkbox name="terms" />);
const checkbox = container.querySelector('input');
expect(checkbox?.name).toBe('terms');
});
it('value 속성이 적용된다', () => {
const { container } = render(<Checkbox value="agree" />);
const checkbox = container.querySelector('input');
expect(checkbox?.value).toBe('agree');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Checkbox id="terms-checkbox" />);
const checkbox = container.querySelector('input');
expect(checkbox?.id).toBe('terms-checkbox');
});
it('readOnly 속성이 적용된다', () => {
const { container } = render(<Checkbox readOnly />);
const checkbox = container.querySelector('input');
expect(checkbox?.readOnly).toBe(true);
});
});
describe('Label Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Checkbox label="약관 동의" />);
const checkbox = container.querySelector('input');
expect(checkbox).toBeTruthy();
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Checkbox className="custom-checkbox" />);
const checkbox = container.querySelector('input');
expect(checkbox?.className).toContain('custom-checkbox');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Checkbox aria-label="약관 동의" />);
const checkbox = container.querySelector('input');
expect(checkbox?.getAttribute('aria-label')).toBe('약관 동의');
});
it('checked 속성이 체크 상태를 나타낸다', () => {
const { container } = render(<Checkbox checked onChange={() => {}} />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
it('data 속성이 적용된다', () => {
const { container } = render(<Checkbox data-testid="test-checkbox" />);
const checkbox = container.querySelector('input');
expect(checkbox?.getAttribute('data-testid')).toBe('test-checkbox');
});
});
describe('Form 통합', () => {
it('form 제출 시 checkbox 값이 포함된다', () => {
const handleSubmit = vi.fn((e) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
return formData.get('terms');
});
const { container } = render(
<form onSubmit={handleSubmit}>
<Checkbox name="terms" value="agree" defaultChecked />
<button type="submit">제출</button>
</form>
);
const form = container.querySelector('form')!;
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalled();
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Checkbox
id="terms"
name="terms"
value="agree"
checked={true}
onChange={handleChange}
required
className="custom-checkbox"
aria-label="약관 동의"
/>
);
const checkbox = container.querySelector('input')!;
expect(checkbox.id).toBe('terms');
expect(checkbox.name).toBe('terms');
expect(checkbox.value).toBe('agree');
expect((checkbox as HTMLInputElement).checked).toBe(true);
expect(checkbox.required).toBe(true);
expect(checkbox.className).toContain('custom-checkbox');
expect(checkbox.getAttribute('aria-label')).toBe('약관 동의');
fireEvent.click(checkbox);
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
describe('Indeterminate 상태', () => {
it('indeterminate ref를 통해 설정할 수 있다', () => {
const TestComponent = () => {
const checkboxRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
if (checkboxRef.current) {
checkboxRef.current.indeterminate = true;
}
}, []);
return <Checkbox ref={checkboxRef} />;
};
const { container } = render(<TestComponent />);
const checkbox = container.querySelector('input') as HTMLInputElement;
// indeterminate는 DOM 속성이므로 직접 확인
expect(checkbox.indeterminate).toBe(true);
});
});
});
@@ -0,0 +1,100 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Code } from '../Code';
describe('Code 컴포넌트', () => {
it('code 요소가 렌더링된다', () => {
const { container } = render(<Code>const x = 1;</Code>);
const code = container.querySelector('code');
expect(code).toBeTruthy();
expect(code?.textContent).toBe('const x = 1;');
});
it('자식 요소를 렌더링한다', () => {
render(<Code>console.log("Hello");</Code>);
expect(screen.getByText('console.log("Hello");')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Code className="custom-code">코드</Code>);
const code = container.querySelector('code');
expect(code?.className).toContain('custom-code');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Code onClick={handleClick}>클릭 가능한 코드</Code>);
const code = screen.getByText('클릭 가능한 코드');
fireEvent.click(code);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('id 속성이 적용된다', () => {
const { container } = render(<Code id="code-snippet">snippet</Code>);
const code = container.querySelector('code');
expect(code?.id).toBe('code-snippet');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Code data-testid="test-code">테스트</Code>);
const code = container.querySelector('code');
expect(code?.getAttribute('data-testid')).toBe('test-code');
});
it('style 속성이 적용된다', () => {
const style = { color: 'red', fontSize: '12px' };
const { container } = render(<Code style={style}>styled code</Code>);
const code = container.querySelector('code') as HTMLElement;
expect(code.style.color).toBe('red');
expect(code.style.fontSize).toBe('12px');
});
it('aria 속성이 적용된다', () => {
const { container } = render(<Code aria-label="코드 스니펫">snippet</Code>);
const code = container.querySelector('code');
expect(code?.getAttribute('aria-label')).toBe('코드 스니펫');
});
it('빈 className이어도 렌더링된다', () => {
const { container } = render(<Code>코드</Code>);
const code = container.querySelector('code');
expect(code).toBeTruthy();
expect(code?.className).toBe('');
});
it('여러 줄 코드를 렌더링한다', () => {
const multilineCode = 'const x = 1;\nconst y = 2;';
render(<Code>{multilineCode}</Code>);
expect(screen.getByText(/const x = 1/)).toBeTruthy();
});
it('복합 Props가 함께 적용된다', () => {
const handleClick = vi.fn();
const { container } = render(
<Code
id="main-code"
className="bg-gray-100 text-sm"
style={{ padding: '4px' }}
onClick={handleClick}
data-testid="code-block"
>
npm install
</Code>
);
const code = container.querySelector('code')!;
expect(code.id).toBe('main-code');
expect(code.className).toContain('bg-gray-100');
expect(code.className).toContain('text-sm');
expect((code as HTMLElement).style.padding).toBe('4px');
expect(code.getAttribute('data-testid')).toBe('code-block');
fireEvent.click(code);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('특수 문자가 포함된 코드를 렌더링한다', () => {
render(<Code>{'<div>Hello</div>'}</Code>);
expect(screen.getByText('<div>Hello</div>')).toBeTruthy();
});
});
@@ -0,0 +1,222 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { FileInput } from '../FileInput';
describe('FileInput 컴포넌트', () => {
describe('기본 렌더링', () => {
it('기본 버튼 텍스트와 placeholder가 렌더링된다', () => {
render(<FileInput />);
expect(screen.getByText('Browse')).toBeTruthy();
expect(screen.getByText('No file selected')).toBeTruthy();
});
it('커스텀 버튼 텍스트가 적용된다', () => {
render(<FileInput buttonText="파일 선택" />);
expect(screen.getByText('파일 선택')).toBeTruthy();
});
it('커스텀 placeholder가 적용된다', () => {
render(<FileInput placeholder="파일을 선택하세요" />);
expect(screen.getByText('파일을 선택하세요')).toBeTruthy();
});
it('숨겨진 file input이 렌더링된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]');
expect(fileInput).toBeTruthy();
expect(fileInput?.className).toContain('hidden');
});
});
describe('파일 선택', () => {
it('버튼 클릭 시 file input이 트리거된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const clickSpy = vi.spyOn(fileInput, 'click');
const button = screen.getByText('Browse');
fireEvent.click(button);
expect(clickSpy).toHaveBeenCalled();
});
it('파일 선택 시 onChange 콜백이 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<FileInput onChange={handleChange} />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test content'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleChange).toHaveBeenCalledWith(file);
});
it('파일 선택 시 파일명이 표시된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test content'], 'module.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(screen.getByText('module.zip')).toBeTruthy();
});
});
describe('파일 크기 검증', () => {
it('파일 크기가 maxSize를 초과하면 onError가 호출된다', () => {
const handleError = vi.fn();
const handleChange = vi.fn();
const { container } = render(
<FileInput maxSize={1} onChange={handleChange} onError={handleError} />
);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
// 2MB 파일 생성 (maxSize 1MB 초과)
const largeContent = new ArrayBuffer(2 * 1024 * 1024);
const file = new File([largeContent], 'large.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleError).toHaveBeenCalledWith('File size exceeds 1MB limit');
expect(handleChange).not.toHaveBeenCalled();
});
it('파일 크기가 maxSize 이내이면 정상 처리된다', () => {
const handleError = vi.fn();
const handleChange = vi.fn();
const { container } = render(
<FileInput maxSize={5} onChange={handleChange} onError={handleError} />
);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
// 1MB 파일 생성 (maxSize 5MB 이내)
const content = new ArrayBuffer(1 * 1024 * 1024);
const file = new File([content], 'small.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleError).not.toHaveBeenCalled();
expect(handleChange).toHaveBeenCalledWith(file);
});
});
describe('파일 초기화', () => {
it('파일 선택 후 클리어 버튼이 표시된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
const clearButton = screen.getByLabelText('Clear file');
expect(clearButton).toBeTruthy();
});
it('클리어 버튼 클릭 시 파일이 초기화된다', () => {
const handleChange = vi.fn();
const { container } = render(<FileInput onChange={handleChange} />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleChange).toHaveBeenCalledWith(file);
const clearButton = screen.getByLabelText('Clear file');
fireEvent.click(clearButton);
expect(handleChange).toHaveBeenLastCalledWith(null);
expect(screen.getByText('No file selected')).toBeTruthy();
});
});
describe('비활성화 상태', () => {
it('disabled 상태에서 버튼이 비활성화된다', () => {
render(<FileInput disabled />);
const button = screen.getByText('Browse');
expect(button).toHaveProperty('disabled', true);
});
it('disabled 상태에서 file input이 비활성화된다', () => {
const { container } = render(<FileInput disabled />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
expect(fileInput.disabled).toBe(true);
});
it('disabled 상태에서 클리어 버튼이 표시되지 않는다', () => {
const { container } = render(<FileInput disabled />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
const clearButton = screen.queryByLabelText('Clear file');
expect(clearButton).toBeNull();
});
});
describe('accept 속성', () => {
it('accept 속성이 file input에 적용된다', () => {
const { container } = render(<FileInput accept=".zip,.tar.gz" />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
expect(fileInput.accept).toBe('.zip,.tar.gz');
});
});
describe('className 속성', () => {
it('className이 wrapper에 적용된다', () => {
const { container } = render(<FileInput className="custom-class" />);
const wrapper = container.firstChild as HTMLElement;
expect(wrapper.className).toContain('custom-class');
});
});
describe('빈 파일 선택', () => {
it('파일 선택 없이 change 이벤트 발생 시 onChange에 null이 전달된다', () => {
const handleChange = vi.fn();
const { container } = render(<FileInput onChange={handleChange} />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(fileInput, 'files', {
value: [],
writable: false,
});
fireEvent.change(fileInput);
expect(handleChange).toHaveBeenCalledWith(null);
});
});
});
@@ -0,0 +1,176 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Form } from '../Form';
describe('Form 컴포넌트', () => {
describe('기본 렌더링', () => {
it('form 요소가 렌더링된다', () => {
const { container } = render(<Form>Form Content</Form>);
const form = container.querySelector('form');
expect(form).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(<Form>Test Form Content</Form>);
expect(screen.getByText('Test Form Content')).toBeTruthy();
});
});
describe('이벤트 핸들링', () => {
it('onSubmit 핸들러가 호출된다', () => {
const handleSubmit = vi.fn((e) => e.preventDefault());
const { container } = render(<Form onSubmit={handleSubmit}>Submit Form</Form>);
const form = container.querySelector('form')!;
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
it('onReset 핸들러가 호출된다', () => {
const handleReset = vi.fn();
const { container } = render(<Form onReset={handleReset}>Reset Form</Form>);
const form = container.querySelector('form')!;
fireEvent.reset(form);
expect(handleReset).toHaveBeenCalledTimes(1);
});
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Form onChange={handleChange}>
<input type="text" name="test" />
</Form>
);
const input = container.querySelector('input')!;
fireEvent.change(input, { target: { value: 'test value' } });
expect(handleChange).toHaveBeenCalled();
});
});
describe('HTML 속성', () => {
it('action 속성이 적용된다', () => {
const { container } = render(<Form action="/submit">Form</Form>);
const form = container.querySelector('form');
expect(form?.action).toContain('/submit');
});
it('method 속성이 적용된다', () => {
const { container } = render(<Form method="post">Form</Form>);
const form = container.querySelector('form');
expect(form?.method).toBe('post');
});
it('encType 속성이 적용된다', () => {
const { container } = render(<Form encType="multipart/form-data">Form</Form>);
const form = container.querySelector('form');
expect(form?.enctype).toBe('multipart/form-data');
});
it('target 속성이 적용된다', () => {
const { container } = render(<Form target="_blank">Form</Form>);
const form = container.querySelector('form');
expect(form?.target).toBe('_blank');
});
it('autoComplete 속성이 적용된다', () => {
const { container } = render(<Form autoComplete="off">Form</Form>);
const form = container.querySelector('form');
expect(form?.getAttribute('autocomplete')).toBe('off');
});
it('noValidate 속성이 적용된다', () => {
const { container } = render(<Form noValidate>Form</Form>);
const form = container.querySelector('form');
expect(form?.noValidate).toBe(true);
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Form className="custom-form">Form</Form>);
const form = container.querySelector('form');
expect(form?.className).toContain('custom-form');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Form id="login-form">Form</Form>);
const form = container.querySelector('form');
expect(form?.id).toBe('login-form');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Form data-testid="test-form">Form</Form>);
const form = container.querySelector('form');
expect(form?.getAttribute('data-testid')).toBe('test-form');
});
it('name 속성이 적용된다', () => {
const { container } = render(<Form name="registration">Form</Form>);
const form = container.querySelector('form');
expect(form?.name).toBe('registration');
});
});
describe('복잡한 Form 구조', () => {
it('여러 input 요소를 포함한다', () => {
const { container } = render(
<Form>
<input type="text" name="username" placeholder="사용자명" />
<input type="password" name="password" placeholder="비밀번호" />
<button type="submit">제출</button>
</Form>
);
expect(screen.getByPlaceholderText('사용자명')).toBeTruthy();
expect(screen.getByPlaceholderText('비밀번호')).toBeTruthy();
expect(screen.getByText('제출')).toBeTruthy();
});
it('중첩된 div와 label을 포함한다', () => {
render(
<Form>
<div>
<label htmlFor="email">이메일</label>
<input type="email" id="email" name="email" />
</div>
</Form>
);
expect(screen.getByLabelText('이메일')).toBeTruthy();
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleSubmit = vi.fn((e) => e.preventDefault());
const { container } = render(
<Form
method="post"
action="/api/submit"
onSubmit={handleSubmit}
className="custom-form"
autoComplete="off"
noValidate
>
<input type="text" name="field" />
<button type="submit">제출</button>
</Form>
);
const form = container.querySelector('form')!;
expect(form.method).toBe('post');
expect(form.action).toContain('/api/submit');
expect(form.className).toContain('custom-form');
expect(form.getAttribute('autocomplete')).toBe('off');
expect(form.noValidate).toBe(true);
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,262 @@
import { describe, it, expect } from 'vitest';
import { render } from '@testing-library/react';
import { Icon } from '../Icon';
import { IconName } from '../IconTypes';
describe('Icon 컴포넌트', () => {
describe('기본 렌더링', () => {
it('아이콘이 렌더링된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon).toBeTruthy();
});
it('문자열 name prop으로 렌더링된다', () => {
const { container } = render(<Icon name="fa-user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
it('IconName enum으로 렌더링된다', () => {
const { container } = render(<Icon name={IconName.User} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
it('기본 iconStyle은 solid이다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fas');
});
});
describe('Icon Style', () => {
it('solid 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="solid" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fas');
});
it('regular 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="regular" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('far');
});
it('light 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="light" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fal');
});
it('duotone 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="duotone" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fad');
});
it('brands 스타일이 적용된다', () => {
const { container } = render(<Icon name="facebook" iconStyle="brands" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fab');
});
});
describe('Icon Size', () => {
it('xs 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="xs" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-xs');
});
it('sm 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="sm" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-sm');
});
it('lg 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="lg" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-lg');
});
it('2x 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="2x" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-2x');
});
it('3x 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="3x" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-3x');
});
});
describe('Icon Animation', () => {
it('spin 애니메이션이 적용된다', () => {
const { container } = render(<Icon name="spinner" spin />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-spin');
});
it('pulse 애니메이션이 적용된다', () => {
const { container } = render(<Icon name="circle-notch" pulse />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-pulse');
});
it('spin과 pulse가 함께 적용되지 않는다', () => {
const { container } = render(<Icon name="spinner" spin pulse />);
const icon = container.querySelector('i');
// 둘 다 true지만 일반적으로 하나만 사용해야 함
expect(icon?.className).toContain('fa-spin');
expect(icon?.className).toContain('fa-pulse');
});
});
describe('Fixed Width', () => {
it('fixedWidth가 적용된다', () => {
const { container } = render(<Icon name="user" fixedWidth />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-fw');
});
it('fixedWidth가 false일 때 적용되지 않는다', () => {
const { container } = render(<Icon name="user" fixedWidth={false} />);
const icon = container.querySelector('i');
expect(icon?.className).not.toContain('fa-fw');
});
});
describe('Color', () => {
it('color prop이 클래스로 적용된다', () => {
const { container } = render(<Icon name="heart" color="text-red-500" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('text-red-500');
});
it('여러 색상 클래스가 적용된다', () => {
const { container } = render(<Icon name="star" color="text-yellow-400 dark:text-yellow-300" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('text-yellow-400');
expect(icon?.className).toContain('dark:text-yellow-300');
});
});
describe('Accessibility', () => {
it('role="img"가 적용된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('role')).toBe('img');
});
it('기본 aria-label이 생성된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('aria-label')).toBe('user');
});
it('하이픈이 공백으로 변환된다', () => {
const { container } = render(<Icon name="shopping-cart" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('aria-label')).toBe('shopping cart');
});
it('사용자 정의 ariaLabel이 적용된다', () => {
const { container } = render(<Icon name="user" ariaLabel="사용자 프로필" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('aria-label')).toBe('사용자 프로필');
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Icon name="user" className="custom-icon" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('custom-icon');
});
it('style prop이 적용된다', () => {
const { container } = render(<Icon name="user" style={{ fontSize: '24px', color: 'red' }} />);
const icon = container.querySelector('i') as HTMLElement;
expect(icon.style.fontSize).toBe('24px');
expect(icon.style.color).toBe('red');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Icon name="user" data-testid="test-icon" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('data-testid')).toBe('test-icon');
});
});
describe('IconName enum 사용', () => {
it('User 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.User} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
it('Search 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.Search} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-search');
});
it('ShoppingCart 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.ShoppingCart} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-shopping-cart');
});
it('Heart 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.Heart} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-heart');
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const { container } = render(
<Icon
name={IconName.Spinner}
iconStyle="solid"
size="2x"
color="text-blue-500"
spin
fixedWidth
ariaLabel="로딩 중"
className="custom-spinner"
/>
);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fas');
expect(icon?.className).toContain('fa-spinner');
expect(icon?.className).toContain('fa-2x');
expect(icon?.className).toContain('text-blue-500');
expect(icon?.className).toContain('fa-spin');
expect(icon?.className).toContain('fa-fw');
expect(icon?.className).toContain('custom-spinner');
expect(icon?.getAttribute('aria-label')).toBe('로딩 중');
});
});
describe('아이콘 이름 처리', () => {
it('fa- 접두사가 있는 경우 중복 제거된다', () => {
const { container } = render(<Icon name="fa-user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
expect(icon?.className).not.toContain('fa-fa-user');
});
it('fa- 접두사가 없는 경우 자동 추가된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
});
});
@@ -0,0 +1,462 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Input } from '../Input';
describe('Input 컴포넌트', () => {
describe('기본 렌더링', () => {
it('input 요소가 렌더링된다', () => {
const { container } = render(<Input />);
const input = container.querySelector('input');
expect(input).toBeTruthy();
});
it('placeholder가 표시된다', () => {
render(<Input placeholder="이름을 입력하세요" />);
expect(screen.getByPlaceholderText('이름을 입력하세요')).toBeTruthy();
});
it('value가 설정된다', () => {
const { container } = render(<Input value="테스트 값" onChange={() => {}} />);
const input = container.querySelector('input') as HTMLInputElement;
expect(input.value).toBe('테스트 값');
});
});
describe('Input Type', () => {
it('text type이 적용된다', () => {
const { container } = render(<Input type="text" />);
const input = container.querySelector('input');
expect(input?.type).toBe('text');
});
it('password type이 적용된다', () => {
const { container } = render(<Input type="password" />);
const input = container.querySelector('input');
expect(input?.type).toBe('password');
});
it('email type이 적용된다', () => {
const { container } = render(<Input type="email" />);
const input = container.querySelector('input');
expect(input?.type).toBe('email');
});
it('number type이 적용된다', () => {
const { container } = render(<Input type="number" />);
const input = container.querySelector('input');
expect(input?.type).toBe('number');
});
it('tel type이 적용된다', () => {
const { container } = render(<Input type="tel" />);
const input = container.querySelector('input');
expect(input?.type).toBe('tel');
});
it('url type이 적용된다', () => {
const { container } = render(<Input type="url" />);
const input = container.querySelector('input');
expect(input?.type).toBe('url');
});
it('date type이 적용된다', () => {
const { container } = render(<Input type="date" />);
const input = container.querySelector('input');
expect(input?.type).toBe('date');
});
});
describe('이벤트 핸들링', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input onChange={handleChange} />);
const input = container.querySelector('input')!;
fireEvent.change(input, { target: { value: '새 값' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(<Input onFocus={handleFocus} />);
const input = container.querySelector('input')!;
fireEvent.focus(input);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(<Input onBlur={handleBlur} />);
const input = container.querySelector('input')!;
fireEvent.blur(input);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
it('onKeyDown 핸들러가 호출된다', () => {
const handleKeyDown = vi.fn();
const { container } = render(<Input onKeyDown={handleKeyDown} />);
const input = container.querySelector('input')!;
fireEvent.keyDown(input, { key: 'Enter' });
expect(handleKeyDown).toHaveBeenCalledTimes(1);
});
});
describe('HTML 속성', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(<Input disabled />);
const input = container.querySelector('input');
expect(input?.disabled).toBe(true);
});
it('readonly 속성이 적용된다', () => {
const { container } = render(<Input readOnly />);
const input = container.querySelector('input');
expect(input?.readOnly).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(<Input required />);
const input = container.querySelector('input');
expect(input?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Input name="username" />);
const input = container.querySelector('input');
expect(input?.name).toBe('username');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Input id="email-input" />);
const input = container.querySelector('input');
expect(input?.id).toBe('email-input');
});
it('maxLength 속성이 적용된다', () => {
const { container } = render(<Input maxLength={10} />);
const input = container.querySelector('input');
expect(input?.maxLength).toBe(10);
});
it('minLength 속성이 적용된다', () => {
const { container } = render(<Input minLength={3} />);
const input = container.querySelector('input');
expect(input?.minLength).toBe(3);
});
it('pattern 속성이 적용된다', () => {
const { container } = render(<Input pattern="[0-9]{3}-[0-9]{4}" />);
const input = container.querySelector('input');
expect(input?.pattern).toBe('[0-9]{3}-[0-9]{4}');
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Input label="사용자 이름" />);
const input = container.querySelector('input');
expect(input).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Input error="필수 입력 항목입니다" />);
const input = container.querySelector('input');
expect(input).toBeTruthy();
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Input className="custom-input" />);
const input = container.querySelector('input');
expect(input?.className).toContain('custom-input');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Input aria-label="이메일 입력" />);
const input = container.querySelector('input');
expect(input?.getAttribute('aria-label')).toBe('이메일 입력');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Input data-testid="test-input" />);
const input = container.querySelector('input');
expect(input?.getAttribute('data-testid')).toBe('test-input');
});
it('autoComplete 속성이 적용된다', () => {
const { container } = render(<Input autoComplete="off" />);
const input = container.querySelector('input');
expect(input?.getAttribute('autocomplete')).toBe('off');
});
// autoFocus는 jsdom 환경에서 제대로 테스트되지 않으므로 생략
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Input
type="email"
name="email"
placeholder="이메일을 입력하세요"
required
className="custom-input"
onChange={handleChange}
/>
);
const input = container.querySelector('input')!;
expect(input.type).toBe('email');
expect(input.name).toBe('email');
expect(input.placeholder).toBe('이메일을 입력하세요');
expect(input.required).toBe(true);
expect(input.className).toContain('custom-input');
fireEvent.change(input, { target: { value: 'test@example.com' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
describe('IME 조합 처리 (한글 입력)', () => {
it('IME 조합 중에는 onChange가 호출되지 않는다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')!;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 입력 (한글 'ㄱ' -> '가' -> '간')
fireEvent.change(input, { target: { value: 'ㄱ' } });
fireEvent.change(input, { target: { value: '가' } });
fireEvent.change(input, { target: { value: '간' } });
// IME 조합 중에는 onChange가 호출되지 않아야 함
expect(handleChange).not.toHaveBeenCalled();
});
it('IME 조합 완료 후 onChange가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')! as HTMLInputElement;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 입력 - input의 실제 value를 설정
Object.defineProperty(input, 'value', { value: '한글', writable: true });
fireEvent.change(input, { target: { value: '한글' } });
// IME 조합 완료
fireEvent.compositionEnd(input);
// 조합 완료 후 onChange가 호출되어야 함
expect(handleChange).toHaveBeenCalledTimes(1);
// onChange에 전달된 이벤트의 target.value가 '한글'이어야 함
expect(handleChange.mock.calls[0][0].target.value).toBe('한글');
});
it('IME 조합 중에도 화면에 입력이 표시된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')! as HTMLInputElement;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 입력
fireEvent.change(input, { target: { value: '테스트' } });
// 화면에는 입력이 표시되어야 함 (로컬 상태)
expect(input.value).toBe('테스트');
});
it('영문 입력 시 onChange가 즉시 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')!;
// 영문 입력 (IME 조합 없음)
fireEvent.change(input, { target: { value: 'a' } });
// 즉시 onChange가 호출되어야 함
expect(handleChange).toHaveBeenCalledTimes(1);
});
// TODO: IME 테스트는 happy-dom 환경에서 composition 이벤트가 실제 브라우저처럼 동작하지 않아 건너뜀
it.skip('IME 조합 후 영문 입력 시 onChange가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')! as HTMLInputElement;
// IME 조합 시작 및 완료
fireEvent.compositionStart(input);
Object.defineProperty(input, 'value', { value: '한', writable: true });
fireEvent.change(input, { target: { value: '한' } });
fireEvent.compositionEnd(input);
// 한글 조합 완료로 1회
expect(handleChange).toHaveBeenCalledTimes(1);
// 영문 입력
fireEvent.change(input, { target: { value: '한a' } });
// 영문 입력으로 추가 1회
expect(handleChange).toHaveBeenCalledTimes(2);
});
it('외부 value prop이 변경되면 로컬 값도 동기화된다', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="초기값" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
expect(input.value).toBe('초기값');
// 외부에서 value 변경
rerender(<Input value="변경된값" onChange={handleChange} />);
await waitFor(() => {
expect(input.value).toBe('변경된값');
});
});
it('포커스 상태에서 외부 value prop 변경 시 로컬 값이 동기화되지 않는다 (플리커 방지)', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="2000" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
expect(input.value).toBe('2000');
// 사용자가 Input에 포커스 (입력 중 상태)
input.focus();
expect(document.activeElement).toBe(input);
// 사용자 입력으로 로컬 값 변경
fireEvent.change(input, { target: { value: '30000' } });
expect(input.value).toBe('30000');
// 부모 리렌더링으로 stale value prop 전달 (debounce 대기 중 발생하는 시나리오)
rerender(<Input value="2000" onChange={handleChange} />);
// 포커스 상태이므로 stale value로 동기화되지 않아야 함
await waitFor(() => {
expect(input.value).toBe('30000');
});
});
it('포커스 해제 후 외부 value prop 변경 시 로컬 값이 정상 동기화된다', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="초기값" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
// 포커스 후 해제
input.focus();
input.blur();
expect(document.activeElement).not.toBe(input);
// 외부에서 value 변경
rerender(<Input value="새값" onChange={handleChange} />);
// 포커스 해제 상태이므로 정상 동기화
await waitFor(() => {
expect(input.value).toBe('새값');
});
});
it('포커스 상태에서 연속 입력 시 마지막 입력값이 유지된다', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="100" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
input.focus();
// 연속 입력 (100 → 1000 → 10000 → 100000)
fireEvent.change(input, { target: { value: '1000' } });
fireEvent.change(input, { target: { value: '10000' } });
fireEvent.change(input, { target: { value: '100000' } });
// 중간에 stale value로 리렌더링
rerender(<Input value="100" onChange={handleChange} />);
// 마지막 입력값 유지
await waitFor(() => {
expect(input.value).toBe('100000');
});
});
it('defaultValue로 초기값이 설정된다', () => {
const { container } = render(<Input defaultValue="기본값" />);
const input = container.querySelector('input')! as HTMLInputElement;
expect(input.value).toBe('기본값');
});
it('value 없이 defaultValue만 있으면 uncontrolled로 동작한다', () => {
const handleChange = vi.fn();
const { container } = render(
<Input defaultValue="기본값" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
// 직접 입력
fireEvent.change(input, { target: { value: '새값' } });
// onChange가 호출되어야 함
expect(handleChange).toHaveBeenCalledTimes(1);
});
// TODO: IME 테스트는 happy-dom 환경에서 composition 이벤트가 실제 브라우저처럼 동작하지 않아 건너뜀
// 실제 브라우저 환경에서 E2E 테스트로 검증 필요
it.skip('IME 조합 중에는 onKeyPress가 호출되지 않는다', () => {
const handleKeyPress = vi.fn();
const { container } = render(<Input value="" onChange={() => {}} onKeyPress={handleKeyPress} />);
const input = container.querySelector('input')!;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 Enter 키
fireEvent.keyPress(input, { key: 'Enter' });
// IME 조합 중에는 onKeyPress가 호출되지 않아야 함
expect(handleKeyPress).not.toHaveBeenCalled();
});
// TODO: IME 테스트는 happy-dom 환경에서 composition 이벤트가 실제 브라우저처럼 동작하지 않아 건너뜀
it.skip('IME 조합 완료 후 onKeyPress가 호출된다', () => {
const handleKeyPress = vi.fn();
const { container } = render(<Input value="" onChange={() => {}} onKeyPress={handleKeyPress} />);
const input = container.querySelector('input')!;
// IME 조합 시작 및 완료
fireEvent.compositionStart(input);
fireEvent.compositionEnd(input);
// Enter 키
fireEvent.keyPress(input, { key: 'Enter' });
// 조합 완료 후 onKeyPress가 호출되어야 함
expect(handleKeyPress).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,502 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { A } from '../A';
import { Ul } from '../Ul';
import { Li } from '../Li';
import { Nav } from '../Nav';
import { Section } from '../Section';
import { Div } from '../Div';
import { Img } from '../Img';
import { Svg } from '../Svg';
import { Hr } from '../Hr';
describe('기타 컴포넌트', () => {
describe('A (링크) 컴포넌트', () => {
it('a 요소가 렌더링된다', () => {
const { container } = render(<A href="/test">링크 텍스트</A>);
const a = container.querySelector('a');
expect(a).toBeTruthy();
expect(a?.href).toContain('/test');
});
it('자식 요소를 렌더링한다', () => {
render(<A href="#">클릭하세요</A>);
expect(screen.getByText('클릭하세요')).toBeTruthy();
});
it('href 속성이 적용된다', () => {
const { container } = render(<A href="https://example.com">외부 링크</A>);
const a = container.querySelector('a');
expect(a?.href).toBe('https://example.com/');
});
it('target 속성이 적용된다', () => {
const { container } = render(
<A href="/page" target="_blank">
새 탭에서 열기
</A>
);
const a = container.querySelector('a');
expect(a?.target).toBe('_blank');
});
it('rel 속성이 적용된다', () => {
const { container } = render(
<A href="https://external.com" rel="noopener noreferrer">
외부 링크
</A>
);
const a = container.querySelector('a');
expect(a?.rel).toBe('noopener noreferrer');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn((e) => e.preventDefault());
render(
<A href="#" onClick={handleClick}>
클릭 가능한 링크
</A>
);
const a = screen.getByText('클릭 가능한 링크');
fireEvent.click(a);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<A href="#" className="custom-link">
링크
</A>
);
const a = container.querySelector('a');
expect(a?.className).toContain('custom-link');
});
it('download 속성이 적용된다', () => {
const { container } = render(
<A href="/file.pdf" download="document.pdf">
다운로드
</A>
);
const a = container.querySelector('a');
expect(a?.download).toBe('document.pdf');
});
});
describe('Ul (순서없는 목록) 컴포넌트', () => {
it('ul 요소가 렌더링된다', () => {
const { container } = render(
<Ul>
<li>항목</li>
</Ul>
);
const ul = container.querySelector('ul');
expect(ul).toBeTruthy();
});
it('자식 li 요소를 렌더링한다', () => {
render(
<Ul>
<li>항목 1</li>
<li>항목 2</li>
</Ul>
);
expect(screen.getByText('항목 1')).toBeTruthy();
expect(screen.getByText('항목 2')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Ul className="custom-ul">
<li>항목</li>
</Ul>
);
const ul = container.querySelector('ul');
expect(ul?.className).toContain('custom-ul');
});
});
describe('Li (목록 항목) 컴포넌트', () => {
it('li 요소가 렌더링된다', () => {
const { container } = render(
<ul>
<Li>목록 항목</Li>
</ul>
);
const li = container.querySelector('li');
expect(li).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<ul>
<Li>테스트 항목</Li>
</ul>
);
expect(screen.getByText('테스트 항목')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<ul>
<Li className="custom-li">항목</Li>
</ul>
);
const li = container.querySelector('li');
expect(li?.className).toContain('custom-li');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(
<ul>
<Li onClick={handleClick}>클릭 가능한 항목</Li>
</ul>
);
const li = screen.getByText('클릭 가능한 항목');
fireEvent.click(li);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
describe('Nav (네비게이션) 컴포넌트', () => {
it('nav 요소가 렌더링된다', () => {
const { container } = render(
<Nav>
<a href="/">홈</a>
</Nav>
);
const nav = container.querySelector('nav');
expect(nav).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<Nav>
<ul>
<li>메뉴 1</li>
<li>메뉴 2</li>
</ul>
</Nav>
);
expect(screen.getByText('메뉴 1')).toBeTruthy();
expect(screen.getByText('메뉴 2')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Nav className="main-nav">
<ul>
<li>메뉴</li>
</ul>
</Nav>
);
const nav = container.querySelector('nav');
expect(nav?.className).toContain('main-nav');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Nav aria-label="주 메뉴">내용</Nav>);
const nav = container.querySelector('nav');
expect(nav?.getAttribute('aria-label')).toBe('주 메뉴');
});
});
describe('Section 컴포넌트', () => {
it('section 요소가 렌더링된다', () => {
const { container } = render(<Section>섹션 내용</Section>);
const section = container.querySelector('section');
expect(section).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<Section>
<h2>섹션 제목</h2>
<p>섹션 내용</p>
</Section>
);
expect(screen.getByText('섹션 제목')).toBeTruthy();
expect(screen.getByText('섹션 내용')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Section className="custom-section">내용</Section>);
const section = container.querySelector('section');
expect(section?.className).toContain('custom-section');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Section id="about">소개</Section>);
const section = container.querySelector('section');
expect(section?.id).toBe('about');
});
});
describe('Div 컴포넌트', () => {
it('div 요소가 렌더링된다', () => {
const { container } = render(<Div>div 내용</Div>);
const div = container.querySelector('div');
expect(div).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(<Div>테스트 내용</Div>);
expect(screen.getByText('테스트 내용')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Div className="container mx-auto">내용</Div>);
const div = container.querySelector('div');
expect(div?.className).toContain('container');
expect(div?.className).toContain('mx-auto');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Div onClick={handleClick}>클릭 가능한 div</Div>);
const div = screen.getByText('클릭 가능한 div');
fireEvent.click(div);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('style 속성이 적용된다', () => {
const { container } = render(
<Div style={{ padding: '20px', backgroundColor: 'blue' }}>내용</Div>
);
const div = container.querySelector('div') as HTMLElement;
expect(div.style.padding).toBe('20px');
expect(div.style.backgroundColor).toBe('blue');
});
it('중첩된 div가 렌더링된다', () => {
const { container } = render(
<Div className="outer">
<Div className="inner">중첩된 내용</Div>
</Div>
);
const outerDiv = container.querySelector('.outer');
const innerDiv = container.querySelector('.inner');
expect(outerDiv).toBeTruthy();
expect(innerDiv).toBeTruthy();
});
});
describe('Img 컴포넌트', () => {
it('img 요소가 렌더링된다', () => {
const { container } = render(<Img src="/test.jpg" alt="테스트 이미지" />);
const img = container.querySelector('img');
expect(img).toBeTruthy();
});
it('src 속성이 적용된다', () => {
const { container } = render(<Img src="/image.png" alt="이미지" />);
const img = container.querySelector('img');
expect(img?.src).toContain('/image.png');
});
it('alt 속성이 적용된다', () => {
const { container } = render(<Img src="/test.jpg" alt="설명 텍스트" />);
const img = container.querySelector('img');
expect(img?.alt).toBe('설명 텍스트');
});
it('기본 alt는 빈 문자열이다', () => {
const { container } = render(<Img src="/test.jpg" />);
const img = container.querySelector('img');
expect(img?.alt).toBe('');
});
it('width와 height 속성이 적용된다', () => {
const { container } = render(<Img src="/test.jpg" alt="이미지" width={200} height={150} />);
const img = container.querySelector('img');
expect(img?.width).toBe(200);
expect(img?.height).toBe(150);
});
it('loading 속성이 적용된다', () => {
const { container } = render(<Img src="/test.jpg" alt="이미지" loading="lazy" />);
const img = container.querySelector('img');
expect(img?.getAttribute('loading')).toBe('lazy');
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Img src="/test.jpg" alt="이미지" className="rounded-lg" />);
const img = container.querySelector('img');
expect(img?.className).toContain('rounded-lg');
});
it('onLoad 이벤트가 작동한다', () => {
const handleLoad = vi.fn();
const { container } = render(<Img src="/test.jpg" alt="이미지" onLoad={handleLoad} />);
const img = container.querySelector('img')!;
fireEvent.load(img);
expect(handleLoad).toHaveBeenCalledTimes(1);
});
it('onError 이벤트가 작동한다', () => {
const handleError = vi.fn();
const { container } = render(<Img src="/invalid.jpg" alt="이미지" onError={handleError} />);
const img = container.querySelector('img')!;
fireEvent.error(img);
expect(handleError).toHaveBeenCalledTimes(1);
});
});
describe('Svg 컴포넌트', () => {
it('svg 요소가 렌더링된다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg).toBeTruthy();
});
it('viewBox 속성이 적용된다', () => {
const { container } = render(
<Svg viewBox="0 0 100 100">
<rect x="0" y="0" width="100" height="100" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('viewBox')).toBe('0 0 100 100');
});
it('width와 height 속성이 적용된다', () => {
const { container } = render(
<Svg width="24" height="24">
<path d="M0 0h24v24H0z" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('width')).toBe('24');
expect(svg?.getAttribute('height')).toBe('24');
});
it('자식 요소를 렌더링한다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" fill="blue" />
<rect x="5" y="5" width="14" height="14" fill="red" />
</Svg>
);
const svg = container.querySelector('svg');
const circle = svg?.querySelector('circle');
const rect = svg?.querySelector('rect');
expect(circle).toBeTruthy();
expect(rect).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Svg className="icon icon-lg" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.className.baseVal).toContain('icon');
expect(svg?.className.baseVal).toContain('icon-lg');
});
it('fill과 stroke 속성이 적용된다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('fill')).toBe('none');
expect(svg?.getAttribute('stroke')).toBe('currentColor');
});
it('aria 속성이 적용된다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24" aria-label="아이콘 설명" role="img">
<path d="M0 0h24v24H0z" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('aria-label')).toBe('아이콘 설명');
expect(svg?.getAttribute('role')).toBe('img');
});
});
describe('복합 사용 사례', () => {
it('Nav 안에 Ul과 Li가 중첩된다', () => {
render(
<Nav>
<Ul>
<Li>
<A href="/">홈</A>
</Li>
<Li>
<A href="/about">소개</A>
</Li>
</Ul>
</Nav>
);
expect(screen.getByText('홈')).toBeTruthy();
expect(screen.getByText('소개')).toBeTruthy();
});
it('Section 안에 여러 컴포넌트가 중첩된다', () => {
render(
<Section>
<Div className="header">
<h2>섹션 제목</h2>
</Div>
<Div className="content">
<p>내용</p>
<Ul>
<Li>항목 1</Li>
<Li>항목 2</Li>
</Ul>
</Div>
</Section>
);
expect(screen.getByText('섹션 제목')).toBeTruthy();
expect(screen.getByText('항목 1')).toBeTruthy();
});
it('Div 안에 Img와 텍스트가 함께 렌더링된다', () => {
const { container } = render(
<Div className="card">
<Img src="/product.jpg" alt="상품 이미지" className="card-image" />
<Div className="card-body">
<h3>상품명</h3>
<p>상품 설명</p>
</Div>
</Div>
);
const img = container.querySelector('img');
expect(img?.src).toContain('/product.jpg');
expect(screen.getByText('상품명')).toBeTruthy();
});
});
describe('Hr (수평선) 컴포넌트', () => {
it('hr 요소가 렌더링된다', () => {
const { container } = render(<Hr />);
const hr = container.querySelector('hr');
expect(hr).toBeTruthy();
});
it('className이 적용된다', () => {
const { container } = render(<Hr className="border-gray-100 dark:border-gray-800 mb-4" />);
const hr = container.querySelector('hr');
expect(hr?.className).toContain('border-gray-100');
expect(hr?.className).toContain('dark:border-gray-800');
});
it('추가 HTML 속성이 전달된다', () => {
const { container } = render(<Hr data-testid="divider" />);
const hr = container.querySelector('hr');
expect(hr?.getAttribute('data-testid')).toBe('divider');
});
});
});
@@ -0,0 +1,617 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import { Select } from '../Select';
describe('Select 컴포넌트', () => {
describe('기본 렌더링 (children 모드)', () => {
it('select 요소가 렌더링된다', () => {
const { container } = render(
<Select>
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
it('option 요소가 렌더링된다', () => {
render(
<Select>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
expect(screen.getByText('옵션 1')).toBeTruthy();
expect(screen.getByText('옵션 2')).toBeTruthy();
});
it('기본 선택 옵션이 표시된다', () => {
const { container } = render(
<Select defaultValue="2">
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe('2');
});
});
describe('이벤트 핸들링 (children 모드)', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Select onChange={handleChange}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.change(select, { target: { value: '2' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(
<Select onFocus={handleFocus}>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.focus(select);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(
<Select onBlur={handleBlur}>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.blur(select);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
});
describe('value 및 제어 컴포넌트 (children 모드)', () => {
it('value prop이 적용된다', () => {
const { container } = render(
<Select value="2" onChange={() => {}}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
<option value="3">옵션 3</option>
</Select>
);
const select = container.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe('2');
});
it('제어 컴포넌트로 작동한다', () => {
const TestComponent = () => {
const [value, setValue] = React.useState('1');
return (
<Select value={value} onChange={(e) => setValue(String(e.target.value))}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
};
const { container } = render(<TestComponent />);
const select = container.querySelector('select')!;
expect((select as HTMLSelectElement).value).toBe('1');
fireEvent.change(select, { target: { value: '2' } });
expect((select as HTMLSelectElement).value).toBe('2');
});
});
describe('HTML 속성 (children 모드)', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(
<Select disabled>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.disabled).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(
<Select required>
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(
<Select name="category">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.name).toBe('category');
});
it('id 속성이 적용된다', () => {
const { container } = render(
<Select id="category-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.id).toBe('category-select');
});
it('multiple 속성이 적용된다', () => {
const { container } = render(
<Select multiple>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.multiple).toBe(true);
});
it('size 속성이 적용된다', () => {
const { container } = render(
<Select size={3}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.size).toBe(3);
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(
<Select label="카테고리 선택">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(
<Select error="카테고리를 선택해주세요">
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
});
describe('사용자 정의 Props (children 모드)', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Select className="custom-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.className).toContain('custom-select');
});
it('aria-label이 적용된다', () => {
const { container } = render(
<Select aria-label="카테고리 선택">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.getAttribute('aria-label')).toBe('카테고리 선택');
});
it('data 속성이 적용된다', () => {
const { container } = render(
<Select data-testid="test-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.getAttribute('data-testid')).toBe('test-select');
});
});
describe('optgroup 지원', () => {
it('optgroup이 렌더링된다', () => {
render(
<Select>
<optgroup label="그룹 1">
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</optgroup>
<optgroup label="그룹 2">
<option value="3">옵션 3</option>
<option value="4">옵션 4</option>
</optgroup>
</Select>
);
expect(screen.getByText('옵션 1')).toBeTruthy();
expect(screen.getByText('옵션 3')).toBeTruthy();
});
});
describe('복합 Props (children 모드)', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Select
name="category"
value="2"
onChange={handleChange}
required
className="custom-select"
aria-label="카테고리 선택"
>
<option value="">선택하세요</option>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
<option value="3">옵션 3</option>
</Select>
);
const select = container.querySelector('select')!;
expect(select.name).toBe('category');
expect((select as HTMLSelectElement).value).toBe('2');
expect(select.required).toBe(true);
expect(select.className).toContain('custom-select');
expect(select.getAttribute('aria-label')).toBe('카테고리 선택');
fireEvent.change(select, { target: { value: '3' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
// ========================================
// 커스텀 드롭다운 모드 (options prop 사용)
// ========================================
describe('커스텀 드롭다운 렌더링 (options 모드)', () => {
const options = [
{ value: '', label: '전체' },
{ value: 'name', label: '이름' },
{ value: 'email', label: '이메일' },
];
it('options prop으로 커스텀 드롭다운이 렌더링된다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
// 버튼이 렌더링되어야 함 (select가 아닌 button)
const button = screen.getByRole('button');
expect(button).toBeTruthy();
});
it('선택된 옵션의 라벨이 버튼에 표시된다', () => {
render(<Select options={options} value="name" onChange={() => {}} />);
expect(screen.getByText('이름')).toBeTruthy();
});
it('빈 값일 때 해당 옵션의 라벨이 표시된다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
expect(screen.getByText('전체')).toBeTruthy();
});
it('버튼 클릭 시 드롭다운이 열린다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 드롭다운 메뉴가 열림 (listbox)
const listbox = screen.getByRole('listbox');
expect(listbox).toBeTruthy();
// 모든 옵션이 표시됨 (옵션은 role="option"으로 찾음)
const optionElements = screen.getAllByRole('option');
expect(optionElements.length).toBe(3);
});
it('옵션 클릭 시 onChange가 호출되고 드롭다운이 닫힌다', () => {
const handleChange = vi.fn();
render(<Select options={options} value="" onChange={handleChange} />);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
// 옵션 선택
const nameOption = screen.getAllByRole('option').find(
opt => opt.textContent?.includes('이름')
);
fireEvent.click(nameOption!);
// onChange가 호출됨 (synthetic event 형식)
expect(handleChange).toHaveBeenCalledTimes(1);
expect(handleChange).toHaveBeenCalledWith(
expect.objectContaining({
target: { value: 'name' },
type: 'change',
})
);
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
it('선택된 옵션에 체크마크가 표시된다', () => {
render(<Select options={options} value="email" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 선택된 옵션 찾기
const selectedOption = screen.getAllByRole('option').find(
opt => opt.getAttribute('aria-selected') === 'true'
);
expect(selectedOption).toBeTruthy();
expect(selectedOption?.textContent).toContain('이메일');
});
it('disabled 상태에서 클릭이 작동하지 않는다', () => {
render(<Select options={options} value="" onChange={() => {}} disabled />);
const button = screen.getByRole('button');
expect(button).toHaveProperty('disabled', true);
fireEvent.click(button);
// 드롭다운이 열리지 않음
expect(screen.queryByRole('listbox')).toBeNull();
});
it('외부 클릭 시 드롭다운이 닫힌다', () => {
render(
<div>
<Select options={options} value="" onChange={() => {}} />
<div data-testid="outside">외부 영역</div>
</div>
);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByRole('listbox')).toBeTruthy();
// 외부 클릭
const outside = screen.getByTestId('outside');
fireEvent.mouseDown(outside);
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
it('ESC 키로 드롭다운이 닫힌다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByRole('listbox')).toBeTruthy();
// ESC 키 입력
fireEvent.keyDown(document, { key: 'Escape' });
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
});
describe('커스텀 드롭다운 스타일 (options 모드)', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
it('기본 스타일이 적용된다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.className).toContain('bg-gray-100');
expect(button.className).toContain('rounded-xl');
});
it('커스텀 className이 적용된다', () => {
render(
<Select
options={options}
value="1"
onChange={() => {}}
className="bg-blue-100 custom-class"
/>
);
const button = screen.getByRole('button');
expect(button.className).toContain('bg-blue-100');
expect(button.className).toContain('custom-class');
});
it('드롭다운 메뉴가 둥근 모서리를 가진다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const listbox = screen.getByRole('listbox');
expect(listbox.className).toContain('rounded-2xl');
expect(listbox.className).toContain('shadow-lg');
});
});
describe('string[] options 지원', () => {
it('string 배열을 옵션으로 변환한다', () => {
render(<Select options={['ko', 'en']} value="ko" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 로케일 이름으로 변환됨 (role="option"으로 찾음)
const optionElements = screen.getAllByRole('option');
const labels = optionElements.map(opt => opt.textContent);
expect(labels).toContain('한국어');
expect(labels).toContain('English');
});
it('알 수 없는 로케일은 그대로 표시된다', () => {
render(<Select options={['unknown']} value="unknown" onChange={() => {}} />);
expect(screen.getByText('unknown')).toBeTruthy();
});
});
describe('disabled 옵션 지원', () => {
it('disabled 옵션이 비활성화된다', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2', disabled: true },
];
const handleChange = vi.fn();
render(<Select options={options} value="1" onChange={handleChange} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const disabledOption = screen.getAllByRole('option').find(
opt => opt.textContent?.includes('옵션 2')
);
expect(disabledOption).toHaveProperty('disabled', true);
// 클릭해도 onChange가 호출되지 않음
fireEvent.click(disabledOption!);
expect(handleChange).not.toHaveBeenCalled();
});
});
describe('접근성 (options 모드)', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
it('aria-haspopup 속성이 있다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.getAttribute('aria-haspopup')).toBe('listbox');
});
it('aria-expanded가 열림 상태를 반영한다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.getAttribute('aria-expanded')).toBe('false');
fireEvent.click(button);
expect(button.getAttribute('aria-expanded')).toBe('true');
});
it('옵션에 role="option"이 있다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const optionElements = screen.getAllByRole('option');
expect(optionElements.length).toBe(2);
});
it('선택된 옵션에 aria-selected="true"가 있다', () => {
render(<Select options={options} value="2" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const selectedOption = screen.getAllByRole('option').find(
opt => opt.getAttribute('aria-selected') === 'true'
);
expect(selectedOption?.textContent).toContain('옵션 2');
});
});
describe('제어 컴포넌트 (options 모드)', () => {
it('value 변경에 따라 표시가 업데이트된다', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
const TestComponent = () => {
const [value, setValue] = React.useState('1');
return (
<div>
<Select
options={options}
value={value}
onChange={(e) => setValue(String(e.target.value))}
/>
<button onClick={() => setValue('2')}>변경</button>
</div>
);
};
render(<TestComponent />);
// 초기값 확인
expect(screen.getByText('옵션 1')).toBeTruthy();
// 외부에서 값 변경
fireEvent.click(screen.getByText('변경'));
// 표시가 업데이트됨
expect(screen.getByText('옵션 2')).toBeTruthy();
});
});
describe('빈 options 처리', () => {
it('빈 배열일 때도 렌더링된다', () => {
render(<Select options={[]} value="" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button).toBeTruthy();
});
it('options가 배열이 아닐 때 기본 select로 폴백된다', () => {
// @ts-expect-error - 의도적으로 잘못된 타입 전달
const { container } = render(<Select options="invalid" />);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
});
});
@@ -0,0 +1,521 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Table } from '../Table';
import { Thead } from '../Thead';
import { Tbody } from '../Tbody';
import { Tr } from '../Tr';
import { Th } from '../Th';
import { Td } from '../Td';
describe('Table 컴포넌트', () => {
describe('기본 렌더링', () => {
it('table 요소가 렌더링된다', () => {
const { container } = render(
<Table>
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<Table>
<tbody>
<tr>
<td>테스트 데이터</td>
</tr>
</tbody>
</Table>
);
expect(screen.getByText('테스트 데이터')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Table className="custom-table">
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table?.className).toContain('custom-table');
});
});
describe('Thead 컴포넌트', () => {
it('thead 요소가 렌더링된다', () => {
const { container } = render(
<table>
<Thead>
<tr>
<th>헤더</th>
</tr>
</Thead>
</table>
);
const thead = container.querySelector('thead');
expect(thead).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<Thead>
<tr>
<th>컬럼명</th>
</tr>
</Thead>
</table>
);
expect(screen.getByText('컬럼명')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<Thead className="custom-thead">
<tr>
<th>헤더</th>
</tr>
</Thead>
</table>
);
const thead = container.querySelector('thead');
expect(thead?.className).toContain('custom-thead');
});
});
describe('Tbody 컴포넌트', () => {
it('tbody 요소가 렌더링된다', () => {
const { container } = render(
<table>
<Tbody>
<tr>
<td>데이터</td>
</tr>
</Tbody>
</table>
);
const tbody = container.querySelector('tbody');
expect(tbody).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<Tbody>
<tr>
<td>테스트 데이터</td>
</tr>
</Tbody>
</table>
);
expect(screen.getByText('테스트 데이터')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<Tbody className="custom-tbody">
<tr>
<td>데이터</td>
</tr>
</Tbody>
</table>
);
const tbody = container.querySelector('tbody');
expect(tbody?.className).toContain('custom-tbody');
});
});
describe('Tr 컴포넌트', () => {
it('tr 요소가 렌더링된다', () => {
const { container } = render(
<table>
<tbody>
<Tr>
<td>셀</td>
</Tr>
</tbody>
</table>
);
const tr = container.querySelector('tr');
expect(tr).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<tbody>
<Tr>
<td>테스트 셀</td>
</Tr>
</tbody>
</table>
);
expect(screen.getByText('테스트 셀')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<tbody>
<Tr className="custom-tr">
<td>셀</td>
</Tr>
</tbody>
</table>
);
const tr = container.querySelector('tr');
expect(tr?.className).toContain('custom-tr');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(
<table>
<tbody>
<Tr onClick={handleClick}>
<td>클릭 가능한 행</td>
</Tr>
</tbody>
</table>
);
const tr = screen.getByText('클릭 가능한 행').closest('tr')!;
fireEvent.click(tr);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
describe('Th 컴포넌트', () => {
it('th 요소가 렌더링된다', () => {
const { container } = render(
<table>
<thead>
<tr>
<Th>헤더 셀</Th>
</tr>
</thead>
</table>
);
const th = container.querySelector('th');
expect(th).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<thead>
<tr>
<Th>이름</Th>
</tr>
</thead>
</table>
);
expect(screen.getByText('이름')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<thead>
<tr>
<Th className="custom-th">헤더</Th>
</tr>
</thead>
</table>
);
const th = container.querySelector('th');
expect(th?.className).toContain('custom-th');
});
it('scope 속성이 적용된다', () => {
const { container } = render(
<table>
<thead>
<tr>
<Th scope="col">컬럼</Th>
</tr>
</thead>
</table>
);
const th = container.querySelector('th');
expect(th?.scope).toBe('col');
});
it('onClick 이벤트가 작동한다 (정렬 가능한 헤더)', () => {
const handleClick = vi.fn();
render(
<table>
<thead>
<tr>
<Th onClick={handleClick}>정렬 가능한 컬럼</Th>
</tr>
</thead>
</table>
);
const th = screen.getByText('정렬 가능한 컬럼');
fireEvent.click(th);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
describe('Td 컴포넌트', () => {
it('td 요소가 렌더링된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td>데이터 셀</Td>
</tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<tbody>
<tr>
<Td>홍길동</Td>
</tr>
</tbody>
</table>
);
expect(screen.getByText('홍길동')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td className="custom-td">데이터</Td>
</tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td?.className).toContain('custom-td');
});
it('colSpan 속성이 적용된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td colSpan={2}>병합된 셀</Td>
</tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td?.colSpan).toBe(2);
});
it('rowSpan 속성이 적용된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td rowSpan={2}>세로 병합</Td>
</tr>
<tr></tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td?.rowSpan).toBe(2);
});
});
describe('완전한 테이블 구조', () => {
it('thead와 tbody를 포함한 완전한 테이블이 렌더링된다', () => {
const { container } = render(
<Table>
<Thead>
<Tr>
<Th>이름</Th>
<Th>나이</Th>
<Th>이메일</Th>
</Tr>
</Thead>
<Tbody>
<Tr>
<Td>홍길동</Td>
<Td>30</Td>
<Td>hong@example.com</Td>
</Tr>
<Tr>
<Td>김철수</Td>
<Td>25</Td>
<Td>kim@example.com</Td>
</Tr>
</Tbody>
</Table>
);
const table = container.querySelector('table');
const thead = container.querySelector('thead');
const tbody = container.querySelector('tbody');
const ths = container.querySelectorAll('th');
const trs = tbody?.querySelectorAll('tr');
expect(table).toBeTruthy();
expect(thead).toBeTruthy();
expect(tbody).toBeTruthy();
expect(ths.length).toBe(3);
expect(trs?.length).toBe(2);
expect(screen.getByText('홍길동')).toBeTruthy();
expect(screen.getByText('김철수')).toBeTruthy();
});
it('여러 행과 열을 렌더링한다', () => {
render(
<Table>
<Tbody>
<Tr>
<Td>1</Td>
<Td>A</Td>
<Td>Alpha</Td>
</Tr>
<Tr>
<Td>2</Td>
<Td>B</Td>
<Td>Beta</Td>
</Tr>
<Tr>
<Td>3</Td>
<Td>C</Td>
<Td>Gamma</Td>
</Tr>
</Tbody>
</Table>
);
expect(screen.getByText('Alpha')).toBeTruthy();
expect(screen.getByText('Beta')).toBeTruthy();
expect(screen.getByText('Gamma')).toBeTruthy();
});
});
describe('HTML 속성', () => {
it('cellPadding이 적용된다', () => {
const { container } = render(
<Table cellPadding={10}>
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table?.cellPadding).toBe('10');
});
it('cellSpacing이 적용된다', () => {
const { container } = render(
<Table cellSpacing={5}>
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table?.cellSpacing).toBe('5');
});
});
describe('접근성', () => {
it('caption을 포함할 수 있다', () => {
render(
<Table>
<caption>사용자 목록</caption>
<Tbody>
<Tr>
<Td>데이터</Td>
</Tr>
</Tbody>
</Table>
);
expect(screen.getByText('사용자 목록')).toBeTruthy();
});
it('th의 scope 속성이 접근성을 향상시킨다', () => {
const { container } = render(
<Table>
<Thead>
<Tr>
<Th scope="col">이름</Th>
<Th scope="col">나이</Th>
</Tr>
</Thead>
<Tbody>
<Tr>
<Th scope="row">홍길동</Th>
<Td>30</Td>
</Tr>
</Tbody>
</Table>
);
const ths = container.querySelectorAll('th');
const colHeaders = Array.from(ths).filter((th) => th.scope === 'col');
const rowHeaders = Array.from(ths).filter((th) => th.scope === 'row');
expect(colHeaders.length).toBe(2);
expect(rowHeaders.length).toBe(1);
});
});
describe('복합 Props', () => {
it('여러 props와 스타일이 함께 적용된다', () => {
const { container } = render(
<Table className="border-collapse w-full" cellPadding={8}>
<Thead className="bg-gray-100">
<Tr>
<Th className="text-left" scope="col">
컬럼 1
</Th>
<Th className="text-right" scope="col">
컬럼 2
</Th>
</Tr>
</Thead>
<Tbody>
<Tr className="hover:bg-gray-50">
<Td className="py-2">데이터 1</Td>
<Td className="py-2 text-right">데이터 2</Td>
</Tr>
</Tbody>
</Table>
);
const table = container.querySelector('table');
const thead = container.querySelector('thead');
const tr = container.querySelector('tbody tr');
expect(table?.className).toContain('border-collapse');
expect(table?.className).toContain('w-full');
expect(thead?.className).toContain('bg-gray-100');
expect(tr?.className).toContain('hover:bg-gray-50');
});
});
});
@@ -0,0 +1,278 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import { Textarea } from '../Textarea';
describe('Textarea 컴포넌트', () => {
describe('기본 렌더링', () => {
it('textarea 요소가 렌더링된다', () => {
const { container } = render(<Textarea />);
const textarea = container.querySelector('textarea');
expect(textarea).toBeTruthy();
});
it('placeholder가 표시된다', () => {
render(<Textarea placeholder="내용을 입력하세요" />);
expect(screen.getByPlaceholderText('내용을 입력하세요')).toBeTruthy();
});
it('value가 설정된다', () => {
const { container } = render(<Textarea value="테스트 내용" onChange={() => {}} />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.value).toBe('테스트 내용');
});
it('defaultValue가 설정된다', () => {
const { container } = render(<Textarea defaultValue="기본 내용" />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.value).toBe('기본 내용');
});
});
describe('이벤트 핸들링', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Textarea onChange={handleChange} />);
const textarea = container.querySelector('textarea')!;
fireEvent.change(textarea, { target: { value: '새 내용' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(<Textarea onFocus={handleFocus} />);
const textarea = container.querySelector('textarea')!;
fireEvent.focus(textarea);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(<Textarea onBlur={handleBlur} />);
const textarea = container.querySelector('textarea')!;
fireEvent.blur(textarea);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
it('onKeyDown 핸들러가 호출된다', () => {
const handleKeyDown = vi.fn();
const { container } = render(<Textarea onKeyDown={handleKeyDown} />);
const textarea = container.querySelector('textarea')!;
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(handleKeyDown).toHaveBeenCalledTimes(1);
});
it('onKeyUp 핸들러가 호출된다', () => {
const handleKeyUp = vi.fn();
const { container } = render(<Textarea onKeyUp={handleKeyUp} />);
const textarea = container.querySelector('textarea')!;
fireEvent.keyUp(textarea, { key: 'a' });
expect(handleKeyUp).toHaveBeenCalledTimes(1);
});
});
describe('제어 컴포넌트', () => {
it('제어 컴포넌트로 작동한다', () => {
const TestComponent = () => {
const [value, setValue] = React.useState('초기값');
return <Textarea value={value} onChange={(e) => setValue(e.target.value)} />;
};
const { container } = render(<TestComponent />);
const textarea = container.querySelector('textarea')!;
expect((textarea as HTMLTextAreaElement).value).toBe('초기값');
fireEvent.change(textarea, { target: { value: '변경된 값' } });
expect((textarea as HTMLTextAreaElement).value).toBe('변경된 값');
});
});
describe('HTML 속성', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(<Textarea disabled />);
const textarea = container.querySelector('textarea');
expect(textarea?.disabled).toBe(true);
});
it('readOnly 속성이 적용된다', () => {
const { container } = render(<Textarea readOnly />);
const textarea = container.querySelector('textarea');
expect(textarea?.readOnly).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(<Textarea required />);
const textarea = container.querySelector('textarea');
expect(textarea?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Textarea name="description" />);
const textarea = container.querySelector('textarea');
expect(textarea?.name).toBe('description');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Textarea id="comment-textarea" />);
const textarea = container.querySelector('textarea');
expect(textarea?.id).toBe('comment-textarea');
});
it('rows 속성이 적용된다', () => {
const { container } = render(<Textarea rows={5} />);
const textarea = container.querySelector('textarea');
expect(textarea?.rows).toBe(5);
});
it('cols 속성이 적용된다', () => {
const { container } = render(<Textarea cols={50} />);
const textarea = container.querySelector('textarea');
expect(textarea?.cols).toBe(50);
});
it('maxLength 속성이 적용된다', () => {
const { container } = render(<Textarea maxLength={100} />);
const textarea = container.querySelector('textarea');
expect(textarea?.maxLength).toBe(100);
});
it('minLength 속성이 적용된다', () => {
const { container } = render(<Textarea minLength={10} />);
const textarea = container.querySelector('textarea');
expect(textarea?.minLength).toBe(10);
});
it('wrap 속성이 적용된다', () => {
const { container } = render(<Textarea wrap="hard" />);
const textarea = container.querySelector('textarea');
expect(textarea?.wrap).toBe('hard');
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Textarea label="설명" />);
const textarea = container.querySelector('textarea');
expect(textarea).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Textarea error="필수 입력 항목입니다" />);
const textarea = container.querySelector('textarea');
expect(textarea).toBeTruthy();
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Textarea className="custom-textarea" />);
const textarea = container.querySelector('textarea');
expect(textarea?.className).toContain('custom-textarea');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Textarea aria-label="댓글 입력" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('aria-label')).toBe('댓글 입력');
});
it('aria-describedby가 적용된다', () => {
const { container } = render(<Textarea aria-describedby="description-help" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('aria-describedby')).toBe('description-help');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Textarea data-testid="test-textarea" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('data-testid')).toBe('test-textarea');
});
it('autoComplete 속성이 적용된다', () => {
const { container } = render(<Textarea autoComplete="off" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('autocomplete')).toBe('off');
});
// autoFocus는 jsdom 환경에서 제대로 테스트되지 않으므로 생략
it('spellCheck 속성이 적용된다', () => {
const { container } = render(<Textarea spellCheck={false} />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('spellcheck')).toBe('false');
});
});
describe('Resize 동작', () => {
it('기본 resize 동작이 유지된다', () => {
const { container } = render(<Textarea />);
const textarea = container.querySelector('textarea');
// CSS resize 속성은 기본적으로 'both' 또는 브라우저 기본값
expect(textarea).toBeTruthy();
});
it('resize 스타일을 커스텀할 수 있다', () => {
const { container } = render(<Textarea style={{ resize: 'vertical' }} />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.style.resize).toBe('vertical');
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Textarea
name="description"
value="테스트 내용"
onChange={handleChange}
rows={5}
cols={40}
maxLength={500}
required
className="custom-textarea"
aria-label="상품 설명"
placeholder="상품 설명을 입력하세요"
/>
);
const textarea = container.querySelector('textarea')!;
expect(textarea.name).toBe('description');
expect((textarea as HTMLTextAreaElement).value).toBe('테스트 내용');
expect(textarea.rows).toBe(5);
expect(textarea.cols).toBe(40);
expect(textarea.maxLength).toBe(500);
expect(textarea.required).toBe(true);
expect(textarea.className).toContain('custom-textarea');
expect(textarea.getAttribute('aria-label')).toBe('상품 설명');
expect(textarea.placeholder).toBe('상품 설명을 입력하세요');
fireEvent.change(textarea, { target: { value: '새 내용' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
describe('줄바꿈 처리', () => {
it('여러 줄 텍스트를 처리한다', () => {
const multilineText = '첫 번째 줄\n두 번째 줄\n세 번째 줄';
const { container } = render(<Textarea value={multilineText} onChange={() => {}} />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.value).toBe(multilineText);
});
});
});
@@ -0,0 +1,295 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { H1 } from '../H1';
import { H2 } from '../H2';
import { H3 } from '../H3';
import { P } from '../P';
import { Span } from '../Span';
import { Label } from '../Label';
describe('Typography 컴포넌트', () => {
describe('H1 컴포넌트', () => {
it('h1 요소가 렌더링된다', () => {
const { container } = render(<H1>제목 1</H1>);
const h1 = container.querySelector('h1');
expect(h1).toBeTruthy();
expect(h1?.textContent).toBe('제목 1');
});
it('자식 요소를 렌더링한다', () => {
render(<H1>Main Heading</H1>);
expect(screen.getByText('Main Heading')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<H1 className="custom-h1">제목</H1>);
const h1 = container.querySelector('h1');
expect(h1?.className).toContain('custom-h1');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<H1 onClick={handleClick}>클릭 가능한 제목</H1>);
const h1 = screen.getByText('클릭 가능한 제목');
fireEvent.click(h1);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('id 속성이 적용된다', () => {
const { container } = render(<H1 id="main-title">제목</H1>);
const h1 = container.querySelector('h1');
expect(h1?.id).toBe('main-title');
});
});
describe('H2 컴포넌트', () => {
it('h2 요소가 렌더링된다', () => {
const { container } = render(<H2>제목 2</H2>);
const h2 = container.querySelector('h2');
expect(h2).toBeTruthy();
expect(h2?.textContent).toBe('제목 2');
});
it('자식 요소를 렌더링한다', () => {
render(<H2>Sub Heading</H2>);
expect(screen.getByText('Sub Heading')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<H2 className="custom-h2">제목</H2>);
const h2 = container.querySelector('h2');
expect(h2?.className).toContain('custom-h2');
});
});
describe('H3 컴포넌트', () => {
it('h3 요소가 렌더링된다', () => {
const { container } = render(<H3>제목 3</H3>);
const h3 = container.querySelector('h3');
expect(h3).toBeTruthy();
expect(h3?.textContent).toBe('제목 3');
});
it('자식 요소를 렌더링한다', () => {
render(<H3>Section Heading</H3>);
expect(screen.getByText('Section Heading')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<H3 className="custom-h3">제목</H3>);
const h3 = container.querySelector('h3');
expect(h3?.className).toContain('custom-h3');
});
});
describe('P 컴포넌트', () => {
it('p 요소가 렌더링된다', () => {
const { container } = render(<P>단락 텍스트</P>);
const p = container.querySelector('p');
expect(p).toBeTruthy();
expect(p?.textContent).toBe('단락 텍스트');
});
it('자식 요소를 렌더링한다', () => {
render(<P>This is a paragraph.</P>);
expect(screen.getByText('This is a paragraph.')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<P className="custom-paragraph">텍스트</P>);
const p = container.querySelector('p');
expect(p?.className).toContain('custom-paragraph');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<P onClick={handleClick}>클릭 가능한 단락</P>);
const p = screen.getByText('클릭 가능한 단락');
fireEvent.click(p);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('여러 줄 텍스트를 렌더링한다', () => {
const multilineText = '첫 번째 줄\n두 번째 줄';
render(<P>{multilineText}</P>);
expect(screen.getByText(/첫 번째 줄/)).toBeTruthy();
});
});
describe('Span 컴포넌트', () => {
it('span 요소가 렌더링된다', () => {
const { container } = render(<Span>인라인 텍스트</Span>);
const span = container.querySelector('span');
expect(span).toBeTruthy();
expect(span?.textContent).toBe('인라인 텍스트');
});
it('자식 요소를 렌더링한다', () => {
render(<Span>Inline text</Span>);
expect(screen.getByText('Inline text')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Span className="custom-span">텍스트</Span>);
const span = container.querySelector('span');
expect(span?.className).toContain('custom-span');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Span onClick={handleClick}>클릭 가능한 span</Span>);
const span = screen.getByText('클릭 가능한 span');
fireEvent.click(span);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('data 속성이 적용된다', () => {
const { container } = render(<Span data-testid="test-span">텍스트</Span>);
const span = container.querySelector('span');
expect(span?.getAttribute('data-testid')).toBe('test-span');
});
});
describe('Label 컴포넌트', () => {
it('label 요소가 렌더링된다', () => {
const { container } = render(<Label>레이블 텍스트</Label>);
const label = container.querySelector('label');
expect(label).toBeTruthy();
expect(label?.textContent).toBe('레이블 텍스트');
});
it('자식 요소를 렌더링한다', () => {
render(<Label>Form Label</Label>);
expect(screen.getByText('Form Label')).toBeTruthy();
});
it('htmlFor 속성이 적용된다', () => {
const { container } = render(<Label htmlFor="input-id">레이블</Label>);
const label = container.querySelector('label');
expect(label?.htmlFor).toBe('input-id');
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Label className="custom-label">레이블</Label>);
const label = container.querySelector('label');
expect(label?.className).toContain('custom-label');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Label onClick={handleClick}>클릭 가능한 레이블</Label>);
const label = screen.getByText('클릭 가능한 레이블');
fireEvent.click(label);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('input과 연결된다', () => {
const { container } = render(
<>
<Label htmlFor="test-input">이름</Label>
<input id="test-input" type="text" />
</>
);
const label = container.querySelector('label');
const input = container.querySelector('input');
expect(label?.htmlFor).toBe('test-input');
expect(input?.id).toBe('test-input');
});
});
describe('공통 HTML 속성', () => {
it('모든 컴포넌트에 style 속성이 적용된다', () => {
const style = { color: 'red', fontSize: '20px' };
const { container: h1Container } = render(<H1 style={style}>H1</H1>);
const { container: pContainer } = render(<P style={style}>P</P>);
const { container: spanContainer } = render(<Span style={style}>Span</Span>);
const h1 = h1Container.querySelector('h1') as HTMLElement;
const p = pContainer.querySelector('p') as HTMLElement;
const span = spanContainer.querySelector('span') as HTMLElement;
expect(h1.style.color).toBe('red');
expect(p.style.color).toBe('red');
expect(span.style.color).toBe('red');
});
it('모든 컴포넌트에 aria 속성이 적용된다', () => {
const { container: h1Container } = render(<H1 aria-label="메인 제목">H1</H1>);
const { container: pContainer } = render(<P aria-describedby="desc">P</P>);
const { container: spanContainer } = render(<Span role="status">Span</Span>);
const h1 = h1Container.querySelector('h1');
const p = pContainer.querySelector('p');
const span = spanContainer.querySelector('span');
expect(h1?.getAttribute('aria-label')).toBe('메인 제목');
expect(p?.getAttribute('aria-describedby')).toBe('desc');
expect(span?.getAttribute('role')).toBe('status');
});
});
describe('중첩된 요소', () => {
it('P 안에 Span이 중첩된다', () => {
render(
<P>
일반 텍스트 <Span className="highlight">강조 텍스트</Span> 계속
</P>
);
expect(screen.getByText(/일반 텍스트/)).toBeTruthy();
expect(screen.getByText('강조 텍스트')).toBeTruthy();
});
it('Label 안에 Span이 중첩된다', () => {
render(
<Label>
<Span>필수</Span> 사용자명
</Label>
);
expect(screen.getByText('필수')).toBeTruthy();
expect(screen.getByText(/사용자명/)).toBeTruthy();
});
it('H1 안에 Span이 중첩된다', () => {
render(
<H1>
메인 제목 <Span className="subtitle">부제목</Span>
</H1>
);
expect(screen.getByText(/메인 제목/)).toBeTruthy();
expect(screen.getByText('부제목')).toBeTruthy();
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleClick = vi.fn();
const { container } = render(
<P
id="intro"
className="text-lg text-gray-700"
style={{ marginBottom: '20px' }}
onClick={handleClick}
data-testid="intro-paragraph"
>
소개 텍스트
</P>
);
const p = container.querySelector('p')!;
expect(p.id).toBe('intro');
expect(p.className).toContain('text-lg');
expect(p.className).toContain('text-gray-700');
expect((p as HTMLElement).style.marginBottom).toBe('20px');
expect(p.getAttribute('data-testid')).toBe('intro-paragraph');
fireEvent.click(p);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,46 @@
/**
* 기본 HTML 매핑 컴포넌트 Export
*
* DOM 요소에 직접 매핑되는 기본 컴포넌트들
*/
export { Button, type ButtonProps } from './Button';
export { FileInput, type FileInputProps } from './FileInput';
export { Input, type InputProps } from './Input';
export { Textarea, type TextareaProps } from './Textarea';
export { Label, type LabelProps } from './Label';
export { Div, type DivProps } from './Div';
export { Span, type SpanProps } from './Span';
export { P, type PProps } from './P';
export { Img, type ImgProps } from './Img';
export { H1, type H1Props } from './H1';
export { H2, type H2Props } from './H2';
export { H3, type H3Props } from './H3';
export { H4, type H4Props } from './H4';
export { Ul, type UlProps } from './Ul';
export { Ol, type OlProps } from './Ol';
export { Li, type LiProps } from './Li';
export { A, type AProps } from './A';
export { Form, type FormProps } from './Form';
export { Select, type SelectProps } from './Select';
export { Option, type OptionProps } from './Option';
export { Optgroup, type OptgroupProps } from './Optgroup';
export { Checkbox, type CheckboxProps } from './Checkbox';
export { Table, type TableProps } from './Table';
export { Thead, type TheadProps } from './Thead';
export { Tbody, type TbodyProps } from './Tbody';
export { Tfoot, type TfootProps } from './Tfoot';
export { Tr, type TrProps } from './Tr';
export { Th, type ThProps } from './Th';
export { Td, type TdProps } from './Td';
export { Nav, type NavProps } from './Nav';
export { Section, type SectionProps } from './Section';
export { Svg, type SvgProps } from './Svg';
export { Icon, type IconProps } from './Icon';
export { Code, type CodeProps } from './Code';
export { Pre, type PreProps } from './Pre';
export { Fragment, type FragmentProps } from './Fragment';
export { Hr, type HrProps } from './Hr';
// Icon 타입 정의 (enum 및 타입)
export { IconName, type IconStyle, type IconSize } from './IconTypes';
@@ -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>
);
};
@@ -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;
@@ -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;
@@ -0,0 +1,16 @@
/**
* DynamicFieldList 컴포넌트 모듈
*
* 동적 필드 목록을 관리하는 컴포넌트를 내보냅니다.
*/
export { DynamicFieldList } from './DynamicFieldList';
export { DynamicFieldListItem } from './DynamicFieldListItem';
export type {
ColumnType,
SelectOption,
DynamicFieldColumn,
RowAction,
DynamicFieldListProps,
DynamicFieldListItemProps,
} from './types';
@@ -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';
@@ -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;
@@ -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;
@@ -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;
@@ -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;
@@ -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';
@@ -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;
}
@@ -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>
);
};
@@ -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>
);
};
Loaded 100 of 3967 files, more files were not shown because too many files have changed in this diff. Show more