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,136 @@
/**
* @file board-401-error-handling.test.tsx
* @description 게시판 목록/상세 - 비로그인 접근 시 401 errorHandling 검증 (이슈 #228 B-5)
*
* 검증 항목:
* 1. show.json / index.json 데이터소스에 401 errorHandling이 정의되어 있는가
* 2. 401 핸들러가 sequence(toast → navigate /login?redirect=...) 방식인가
* 3. navigate params에 redirect 쿼리가 포함되어 있는가
* 4. auth_required가 아닌 auth_mode: "optional"이 사용되는가
* 5. 기존 403/404 핸들러가 유지되는가
*/
import { describe, it, expect } from 'vitest';
import showLayout from '../../../layouts/board/show.json';
import indexLayout from '../../../layouts/board/index.json';
function getDataSource(layout: any, dataSourceId: string) {
return (layout.data_sources ?? []).find((s: any) => s.id === dataSourceId) ?? null;
}
function getDataSourceErrorHandling(layout: any, dataSourceId: string) {
const ds = getDataSource(layout, dataSourceId);
return ds?.errorHandling ?? null;
}
describe('게시판 401 errorHandling — sequence + redirect 방식 (이슈 #228 B-5)', () => {
describe('show.json — auth_mode 및 데이터소스 401', () => {
// redirect: /board/{{route.slug}}/posts/{{route.id}}
const ds = getDataSource(showLayout, 'post');
const dsErrorHandling = ds?.errorHandling ?? null;
it('auth_mode가 optional이어야 한다 (auth_required 사용 금지)', () => {
expect(ds?.auth_mode).toBe('optional');
expect(ds?.auth_required).toBeUndefined();
});
it('데이터소스 errorHandling에 401이 정의되어야 한다', () => {
expect(dsErrorHandling?.['401']).toBeDefined();
});
it('401 핸들러가 sequence 타입이어야 한다', () => {
expect(dsErrorHandling?.['401']?.handler).toBe('sequence');
});
it('sequence actions 배열이 존재해야 한다', () => {
expect(Array.isArray(dsErrorHandling?.['401']?.actions)).toBe(true);
expect(dsErrorHandling?.['401']?.actions.length).toBeGreaterThanOrEqual(2);
});
it('첫 번째 action이 toast 핸들러이어야 한다', () => {
const toastAction = dsErrorHandling?.['401']?.actions[0];
expect(toastAction?.handler).toBe('toast');
});
it('두 번째 action이 navigate 핸들러이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.handler).toBe('navigate');
});
it('navigate path가 /login이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.path).toBe('/login');
});
it('navigate query에 redirect 파라미터가 없어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.query).toBeUndefined();
});
it('기존 403 핸들러가 유지되어야 한다', () => {
expect(dsErrorHandling?.['403']).toBeDefined();
expect(dsErrorHandling?.['403']?.handler).toBe('showErrorPage');
});
it('기존 404 핸들러가 유지되어야 한다', () => {
expect(dsErrorHandling?.['404']).toBeDefined();
expect(dsErrorHandling?.['404']?.handler).toBe('showErrorPage');
});
it('레이아웃 최상위에 errorHandling이 없어야 한다', () => {
expect((showLayout as any).errorHandling).toBeUndefined();
});
});
describe('index.json — auth_mode 및 데이터소스 401', () => {
const ds = getDataSource(indexLayout, 'posts');
const dsErrorHandling = ds?.errorHandling ?? null;
it('auth_mode가 optional이어야 한다 (auth_required 사용 금지)', () => {
expect(ds?.auth_mode).toBe('optional');
expect(ds?.auth_required).toBeUndefined();
});
it('데이터소스 errorHandling에 401이 정의되어야 한다', () => {
expect(dsErrorHandling?.['401']).toBeDefined();
});
it('401 핸들러가 sequence 타입이어야 한다', () => {
expect(dsErrorHandling?.['401']?.handler).toBe('sequence');
});
it('sequence actions 배열이 존재해야 한다', () => {
expect(Array.isArray(dsErrorHandling?.['401']?.actions)).toBe(true);
expect(dsErrorHandling?.['401']?.actions.length).toBeGreaterThanOrEqual(2);
});
it('첫 번째 action이 toast 핸들러이어야 한다', () => {
const toastAction = dsErrorHandling?.['401']?.actions[0];
expect(toastAction?.handler).toBe('toast');
});
it('두 번째 action이 navigate 핸들러이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.handler).toBe('navigate');
});
it('navigate path가 /login이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.path).toBe('/login');
});
it('navigate query에 redirect 파라미터가 없어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.query).toBeUndefined();
});
it('기존 403 핸들러가 유지되어야 한다', () => {
expect(dsErrorHandling?.['403']).toBeDefined();
expect(dsErrorHandling?.['403']?.handler).toBe('showErrorPage');
});
it('레이아웃 최상위에 errorHandling이 없어야 한다', () => {
expect((indexLayout as any).errorHandling).toBeUndefined();
});
});
});
@@ -0,0 +1,212 @@
/**
* @file board-comment-author-buttons.test.tsx
* @description 게시글 상세 - 본인 댓글/답글 수정·삭제 버튼 표시 조건 테스트 (이슈 #228 B-4)
*
* 검증 항목:
* 1. 본인 댓글 (is_author=true) + 게시글 권한(can_write_comments=true) → 수정/삭제 버튼 표시
* 2. 본인 댓글 + can_write_comments=false → 수정/삭제 버튼 미표시
* 3. 타인 댓글 (is_author=false) + 권한 없음 → 수정/삭제 버튼 미표시
* 4. 비회원 댓글 (is_guest_comment=true) → 수정/삭제 버튼 표시
* 5. manager 권한 (can_manage=true) → 타인 댓글도 수정/삭제 버튼 표시
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestButton: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
type?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, children, text, onClick, 'data-testid': testId }) => (
<button className={className} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
// ============================================================
// 컴포넌트 레지스트리 설정
// ============================================================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
};
return registry;
}
// ============================================================
// 댓글 버튼 조건 테스트용 레이아웃 (컴포넌트 정의만)
// _comment_item.json의 수정/삭제 버튼 if 조건 재현
// ============================================================
const commentButtonLayout = {
version: '1.0.0',
layout_name: 'comment_author_buttons_test',
components: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'comment-item' },
children: [
{
comment: '더보기 드롭다운 컨테이너 (버튼들을 감싸는 부모)',
type: 'basic',
name: 'Div',
if: '{{!comment?.deleted_at && comment?.status !== \'blinded\' && ((comment?.is_author && post?.data?.abilities?.can_write_comments) || comment?.is_guest_comment || post?.data?.abilities?.can_manage || (post?.data?.abilities?.can_write_comments && (comment?.depth ?? 0) < (post?.data?.board?.max_comment_depth ?? 10)))}}',
props: { 'data-testid': 'dropdown-menu' },
children: [
{
comment: '수정 버튼 ((본인 + 권한) || 비회원 || manager)',
type: 'basic',
name: 'Button',
if: '{{(comment?.is_author && post?.data?.abilities?.can_write_comments) || comment?.is_guest_comment || post?.data?.abilities?.can_manage}}',
props: { 'data-testid': 'btn-edit' },
children: [{ type: 'basic', name: 'Span', text: '수정' }],
},
{
comment: '삭제 버튼 ((본인 + 권한) || 비회원 || manager)',
type: 'basic',
name: 'Button',
if: '{{(comment?.is_author && post?.data?.abilities?.can_write_comments) || comment?.is_guest_comment || post?.data?.abilities?.can_manage}}',
props: { 'data-testid': 'btn-delete' },
children: [{ type: 'basic', name: 'Span', text: '삭제' }],
},
],
},
],
},
],
};
function makeInitialData(comment: Record<string, any>, postAbilities: Record<string, any>) {
return {
comment,
post: {
data: {
abilities: postAbilities,
},
},
};
}
// ============================================================
// 테스트
// ============================================================
describe('댓글 수정/삭제 버튼 표시 조건 (이슈 #228 B-4)', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
it('본인 댓글 + can_write_comments=true → 수정/삭제 버튼 표시', async () => {
const initialData = makeInitialData(
{ is_author: true, is_guest_comment: false },
{ can_write_comments: true, can_manage: false },
);
const testUtils = createLayoutTest(commentButtonLayout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('btn-edit')).toBeInTheDocument();
expect(screen.getByTestId('btn-delete')).toBeInTheDocument();
testUtils.cleanup();
});
it('본인 댓글 + can_write_comments=false → 수정/삭제 버튼 미표시', async () => {
const initialData = makeInitialData(
{ is_author: true, is_guest_comment: false },
{ can_write_comments: false, can_manage: false },
);
const testUtils = createLayoutTest(commentButtonLayout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.queryByTestId('btn-edit')).not.toBeInTheDocument();
expect(screen.queryByTestId('btn-delete')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('타인 댓글 + 권한 없음 → 수정/삭제 버튼 미표시', async () => {
const initialData = makeInitialData(
{ is_author: false, is_guest_comment: false },
{ can_write_comments: true, can_manage: false },
);
const testUtils = createLayoutTest(commentButtonLayout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.queryByTestId('btn-edit')).not.toBeInTheDocument();
expect(screen.queryByTestId('btn-delete')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('비회원 댓글 (is_guest_comment=true) → 수정/삭제 버튼 표시', async () => {
const initialData = makeInitialData(
{ is_author: false, is_guest_comment: true },
{ can_write_comments: false, can_manage: false },
);
const testUtils = createLayoutTest(commentButtonLayout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('btn-edit')).toBeInTheDocument();
expect(screen.getByTestId('btn-delete')).toBeInTheDocument();
testUtils.cleanup();
});
it('manager 권한 (can_manage=true) → 타인 댓글도 수정/삭제 버튼 표시', async () => {
const initialData = makeInitialData(
{ is_author: false, is_guest_comment: false },
{ can_write_comments: false, can_manage: true },
);
const testUtils = createLayoutTest(commentButtonLayout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('btn-edit')).toBeInTheDocument();
expect(screen.getByTestId('btn-delete')).toBeInTheDocument();
testUtils.cleanup();
});
});
@@ -0,0 +1,298 @@
/**
* @file board-deleted-toggle.test.tsx
* @description 게시판 목록/상세 - 삭제 글/댓글 포함 토글 UI 렌더링 회귀 테스트
*
* 검증 항목:
* 1. can_view_deleted = true → 토글 버튼 렌더링
* 2. can_view_deleted = false → 토글 버튼 미렌더링
* 3. can_manage = true → 댓글 섹션 토글 버튼 렌더링 (헤더 오른쪽)
* 4. can_manage = false → 댓글 섹션 토글 버튼 미렌더링
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
onClick?: () => void;
}> = ({ type, className, children, 'data-testid': testId, onClick }) => (
<button type={type as any} className={className} data-testid={testId} onClick={onClick}>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>
{children || text}
</span>
);
const TestH3: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<h3 className={className} data-testid={testId}>
{children}
</h3>
);
// ============================================================
// 컴포넌트 레지스트리 설정
// ============================================================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
};
return registry;
}
// ============================================================
// 테스트용 레이아웃 JSON (토글 블록만 추출)
// ============================================================
/** 게시글 목록 토글 — can_view_deleted 조건부 렌더링 */
const postToggleLayoutJson = {
version: '1.0.0',
layout_name: 'board_post_deleted_toggle_test',
data_sources: [
{
id: 'posts',
type: 'api',
endpoint: '/api/modules/sirsoft-board/boards/test/posts',
method: 'GET',
auto_fetch: true,
},
],
components: [
{
comment: '삭제된 게시글 포함 토글 (manager 권한 보유 시에만 표시)',
type: 'basic',
name: 'Button',
if: '{{posts?.data?.abilities?.can_view_deleted}}',
props: {
type: 'button',
'data-testid': 'include-deleted-toggle',
className: 'inline-flex items-center gap-1.5 px-3 py-2 border border-gray-300 rounded-lg text-sm',
},
children: [
{
type: 'basic',
name: 'Span',
text: 'Include deleted posts',
},
],
},
],
};
/** 댓글 섹션 헤더 — 오른쪽에 토글 버튼 배치 */
const commentToggleLayoutJson = {
version: '1.0.0',
layout_name: 'board_comment_deleted_toggle_test',
data_sources: [
{
id: 'post',
type: 'api',
endpoint: '/api/modules/sirsoft-board/boards/test/posts/1',
method: 'GET',
auto_fetch: true,
},
],
components: [
{
type: 'basic',
name: 'H3',
props: {
'data-testid': 'comment-header',
className: 'flex items-center justify-between px-6 pt-6 pb-4',
},
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2' },
children: [
{
type: 'basic',
name: 'Span',
text: 'Comments',
},
],
},
{
comment: '삭제된 댓글 포함 토글 (manager 권한 보유 시에만 표시)',
type: 'basic',
name: 'Button',
if: '{{post?.data?.abilities?.can_manage}}',
props: {
type: 'button',
'data-testid': 'include-deleted-comments-toggle',
className: 'inline-flex items-center gap-1.5 px-3 py-2 border border-gray-300 rounded-lg text-sm',
},
children: [
{
type: 'basic',
name: 'Span',
text: 'Include deleted comments',
},
],
},
],
},
],
};
// ============================================================
// 테스트
// ============================================================
describe('게시판 삭제 글 포함 토글 UI 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
it('can_view_deleted = true → 게시글 토글 버튼 렌더링', async () => {
const testUtils = createLayoutTest(postToggleLayoutJson);
testUtils.mockApi('posts', {
response: {
data: {
abilities: { can_view_deleted: true },
},
},
});
await testUtils.render();
expect(screen.getByTestId('include-deleted-toggle')).toBeInTheDocument();
testUtils.cleanup();
});
it('can_view_deleted = false → 게시글 토글 버튼 미렌더링', async () => {
const testUtils = createLayoutTest(postToggleLayoutJson);
testUtils.mockApi('posts', {
response: {
data: {
abilities: { can_view_deleted: false },
},
},
});
await testUtils.render();
expect(screen.queryByTestId('include-deleted-toggle')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('can_view_deleted 없음 → 게시글 토글 미렌더링', async () => {
const testUtils = createLayoutTest(postToggleLayoutJson);
testUtils.mockApi('posts', {
response: {
data: {
abilities: {},
},
},
});
await testUtils.render();
expect(screen.queryByTestId('include-deleted-toggle')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('게시판 삭제 댓글 포함 토글 UI 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
it('can_manage = true → 댓글 토글 버튼이 헤더 오른쪽에 렌더링', async () => {
const testUtils = createLayoutTest(commentToggleLayoutJson);
testUtils.mockApi('post', {
response: {
data: {
abilities: { can_manage: true },
comments: [],
},
},
});
await testUtils.render();
const header = screen.getByTestId('comment-header');
const toggleBtn = screen.getByTestId('include-deleted-comments-toggle');
expect(toggleBtn).toBeInTheDocument();
expect(header).toContainElement(toggleBtn);
testUtils.cleanup();
});
it('can_manage = false → 댓글 토글 미렌더링', async () => {
const testUtils = createLayoutTest(commentToggleLayoutJson);
testUtils.mockApi('post', {
response: {
data: {
abilities: { can_manage: false },
comments: [],
},
},
});
await testUtils.render();
expect(screen.queryByTestId('include-deleted-comments-toggle')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('can_manage 없음 → 댓글 토글 미렌더링', async () => {
const testUtils = createLayoutTest(commentToggleLayoutJson);
testUtils.mockApi('post', {
response: {
data: {
abilities: {},
comments: [],
},
},
});
await testUtils.render();
expect(screen.queryByTestId('include-deleted-comments-toggle')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
@@ -0,0 +1,333 @@
/**
* @file board-form-type-renderer.test.tsx
* @description 게시글 작성/수정 - _type_renderer 유형별 분기 렌더링 테스트 (이슈 #153)
*
* 검증 항목:
* 1. basic 유형: 폼 영역 렌더링
* 2. gallery 유형: 폼 영역 렌더링 (현재 basic 공유)
* 3. card 유형: 폼 영역 렌더링 (현재 basic 공유)
* 4. 알 수 없는 유형 fallback: basic으로 렌더링
* 5. 비밀번호 확인 조건부 렌더링 (requires_password)
* 6. dataKey 2단계 partial 전파 검증 (trackChanges/blur_until_loaded)
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestButton: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
type?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, children, text, onClick, 'data-testid': testId }) => (
<button className={className} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h1 className={className}>{children || text}</h1>
);
const TestInput: React.FC<{
type?: string;
name?: string;
className?: string;
placeholder?: string;
'data-testid'?: string;
}> = ({ type, name, className, placeholder, 'data-testid': testId }) => (
<input type={type} name={name} className={className} placeholder={placeholder} data-testid={testId} />
);
const TestForm: React.FC<{
id?: string;
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ id, className, children, 'data-testid': testId }) => (
<form id={id} className={className} data-testid={testId}>
{children}
</form>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={className} data-icon={name} data-size={size} />
);
const TestContainer: React.FC<{
className?: string;
children?: React.ReactNode;
}> = ({ className, children }) => (
<div className={className} data-testid="container">
{children}
</div>
);
const TestHtmlEditor: React.FC<{
content?: string;
name?: string;
label?: string;
}> = ({ name }) => (
<div data-testid={`html-editor-${name ?? 'content'}`} />
);
// ============================================================
// 컴포넌트 레지스트리 설정
// ============================================================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Form: { component: TestForm, metadata: { name: 'Form', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'composite' } },
Container: { component: TestContainer, metadata: { name: 'Container', type: 'layout' } },
HtmlEditor: { component: TestHtmlEditor, metadata: { name: 'HtmlEditor', type: 'composite' } },
};
return registry;
}
// ============================================================
// 공통 mock 데이터
// ============================================================
function makeFormMeta(overrides: Record<string, any> = {}) {
return {
data: {
board: {
name: '자유게시판',
type: 'basic',
categories: [],
secret_mode: 'disabled',
use_file_upload: false,
user_permissions: { manager: false, attachments_upload: false },
},
requires_password: false,
parent_post: null,
author: null,
attachments: [],
...overrides,
},
};
}
// ============================================================
// _type_renderer 유형별 분기 테스트용 레이아웃 JSON
// (partial 분리된 내용을 인라인으로 포함)
// ============================================================
function makeFormLayout(boardType: string, formMetaOverrides: Record<string, any> = {}) {
const formMetaData = makeFormMeta({
board: {
name: '자유게시판',
type: boardType,
categories: [],
secret_mode: 'disabled',
use_file_upload: false,
user_permissions: { manager: false, attachments_upload: false },
},
...formMetaOverrides,
});
const layout = {
version: '1.0.0',
layout_name: 'board_form_type_renderer_test',
// data_sources 없음 - initialData로 직접 주입 (static type은 processDataSources에서 미처리)
components: [
{
comment: '_type_renderer 인라인 재현 (비밀번호 확인 Div + 유형 분기)',
type: 'basic',
name: 'Div',
if: "{{!form_meta?.data?.requires_password || _local.passwordVerified || form_meta?.data?.board?.user_permissions?.manager}}",
props: { 'data-testid': 'type-renderer' },
children: [
{
comment: 'basic + fallback',
type: 'basic',
name: 'Div',
if: "{{form_meta?.data?.board?.type === 'basic' || !['gallery','card'].includes(form_meta?.data?.board?.type ?? 'basic')}}",
props: { 'data-testid': 'form-basic' },
children: [
{ type: 'basic', name: 'Span', text: 'basic-form', props: { 'data-testid': 'form-basic-label' } },
],
},
{
comment: 'gallery 유형',
type: 'basic',
name: 'Div',
if: "{{form_meta?.data?.board?.type === 'gallery'}}",
props: { 'data-testid': 'form-gallery' },
children: [
{ type: 'basic', name: 'Span', text: 'gallery-form', props: { 'data-testid': 'form-gallery-label' } },
],
},
{
comment: 'card 유형',
type: 'basic',
name: 'Div',
if: "{{form_meta?.data?.board?.type === 'card'}}",
props: { 'data-testid': 'form-card' },
children: [
{ type: 'basic', name: 'Span', text: 'card-form', props: { 'data-testid': 'form-card-label' } },
],
},
],
},
],
};
return { layout, initialData: { form_meta: formMetaData, form_data: null } };
}
// ============================================================
// 테스트
// ============================================================
describe('board/form _type_renderer 유형별 분기 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('[1] basic 유형', () => {
it('form-basic 영역이 렌더링되고 form-gallery/form-card는 렌더링되지 않는다', async () => {
const { layout, initialData } = makeFormLayout('basic');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('form-basic')).toBeInTheDocument();
expect(screen.queryByTestId('form-gallery')).not.toBeInTheDocument();
expect(screen.queryByTestId('form-card')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[2] gallery 유형', () => {
it('form-gallery 영역이 렌더링되고 form-basic/form-card는 렌더링되지 않는다', async () => {
const { layout, initialData } = makeFormLayout('gallery');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('form-gallery')).toBeInTheDocument();
expect(screen.queryByTestId('form-basic')).not.toBeInTheDocument();
expect(screen.queryByTestId('form-card')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[3] card 유형', () => {
it('form-card 영역이 렌더링되고 form-basic/form-gallery는 렌더링되지 않는다', async () => {
const { layout, initialData } = makeFormLayout('card');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('form-card')).toBeInTheDocument();
expect(screen.queryByTestId('form-basic')).not.toBeInTheDocument();
expect(screen.queryByTestId('form-gallery')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[4] 알 수 없는 유형 fallback', () => {
it('unknown 유형은 basic으로 fallback 렌더링된다', async () => {
const { layout, initialData } = makeFormLayout('unknown_type');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('form-basic')).toBeInTheDocument();
expect(screen.queryByTestId('form-gallery')).not.toBeInTheDocument();
expect(screen.queryByTestId('form-card')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[5] 비밀번호 확인 조건부 렌더링', () => {
it('requires_password=false이면 폼이 표시된다', async () => {
const { layout, initialData } = makeFormLayout('basic', { requires_password: false });
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('type-renderer')).toBeInTheDocument();
testUtils.cleanup();
});
it('requires_password=true이고 passwordVerified=false이면 폼이 숨겨진다', async () => {
const { layout, initialData } = makeFormLayout('basic', { requires_password: true });
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.queryByTestId('type-renderer')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('requires_password=true이고 manager=true이면 폼이 표시된다', async () => {
const { layout, initialData } = makeFormLayout('basic', {
requires_password: true,
board: {
name: '자유게시판',
type: 'basic',
categories: [],
secret_mode: 'disabled',
use_file_upload: false,
user_permissions: { manager: true, attachments_upload: false },
},
});
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('type-renderer')).toBeInTheDocument();
testUtils.cleanup();
});
});
});
@@ -0,0 +1,335 @@
/**
* @file board-index-blur.test.tsx
* @description 게시판 목록 - 블라인드/삭제 게시글 표시 처리 회귀 테스트
*
* 검증 항목:
* 1. [basic] 블라인드 게시글 제목에 연한 색상(text-gray-400) 클래스 적용
* 2. [basic] 삭제된 게시글 제목에 연한 색상(text-gray-400) 클래스 적용
* 3. [basic] 일반 게시글 제목에 연한 기본 색상(text-gray-700) 클래스 적용
* 4. [card/gallery] 블라인드 게시글도 썸네일 있으면 이미지 표시
* 5. [card/gallery] 삭제된 게시글도 썸네일 있으면 이미지 표시
* 6. [card/gallery] 썸네일 없으면 플레이스홀더 표시
* 7. [card/gallery] 블라인드 게시글 플레이스홀더에 연한 색상(text-gray-400) 클래스 적용
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestButton: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, children, text, onClick, 'data-testid': testId }) => (
<button className={className} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>
{children || text}
</span>
);
const TestImg: React.FC<{
src?: string;
alt?: string;
className?: string;
'data-testid'?: string;
}> = ({ src, alt, className, 'data-testid': testId }) => (
<img src={src} alt={alt} className={className} data-testid={testId} />
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={className} data-icon={name} data-size={size} />
);
const TestH3: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<h3 className={className} data-testid={testId}>
{children || text}
</h3>
);
const TestAvatar: React.FC<{
author?: unknown;
size?: string;
className?: string;
}> = ({ className }) => <span className={className} data-testid="avatar" />;
const TestUserInfo: React.FC<{
author?: unknown;
showDropdown?: boolean;
stopPropagation?: boolean;
className?: string;
}> = ({ className }) => <span className={className} data-testid="userinfo" />;
const TestHtmlContent: React.FC<{
content?: string;
isHtml?: boolean;
className?: string;
'data-testid'?: string;
}> = ({ content, className, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{content}
</div>
);
// ============================================================
// 컴포넌트 레지스트리 설정
// ============================================================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Img: { component: TestImg, metadata: { name: 'Img', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
Avatar: { component: TestAvatar, metadata: { name: 'Avatar', type: 'composite' } },
UserInfo: { component: TestUserInfo, metadata: { name: 'UserInfo', type: 'composite' } },
HtmlContent: { component: TestHtmlContent, metadata: { name: 'HtmlContent', type: 'composite' } },
};
return registry;
}
// ============================================================
// 레이아웃 JSON
// ============================================================
/**
* basic형 제목 행 색상 처리 테스트 레이아웃
* 블라인드/삭제 시 text-gray-400, 정상 시 text-gray-700
*/
const basicTitleColorLayoutJson = {
version: '1.0.0',
layout_name: 'board_basic_color_test',
components: [
{
type: 'basic',
name: 'Span',
props: {
'data-testid': 'post-title',
className:
"text-sm font-medium truncate {{(_local.post?.status === 'blinded' || _local.post?.deleted_at) ? 'text-gray-400 dark:text-gray-500' : 'text-gray-700 dark:text-gray-300'}}",
},
text: '{{_local.post?.title}}',
},
],
};
/**
* card/gallery형 이미지 조건 테스트 레이아웃
* - 썸네일 있으면 항상 표시 (블라인드/삭제 여부 무관)
* - 썸네일 없으면 플레이스홀더 표시
*/
const imageThumbnailConditionLayoutJson = {
version: '1.0.0',
layout_name: 'board_image_condition_test',
components: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'image-area' },
children: [
{
type: 'basic',
name: 'Img',
if: "{{_local.post?.thumbnail}}",
props: {
src: '{{_local.post?.thumbnail}}',
alt: '{{_local.post?.title}}',
'data-testid': 'post-img',
className: 'w-full h-full object-cover',
},
},
{
type: 'basic',
name: 'Div',
if: "{{!_local.post?.thumbnail}}",
props: {
'data-testid': 'post-placeholder',
className:
"w-full h-full flex items-center justify-center gap-2 bg-gray-200 dark:bg-gray-700",
},
},
],
},
],
};
/**
* card/gallery형 플레이스홀더 색상 테스트 레이아웃
* 이미지 없는 경우의 플레이스홀더 텍스트 색상 처리
*/
const imagePlaceholderColorLayoutJson = {
version: '1.0.0',
layout_name: 'board_placeholder_color_test',
components: [
{
type: 'basic',
name: 'Div',
props: {
'data-testid': 'post-placeholder',
className:
"w-full h-full flex items-center justify-center {{(_local.post?.status === 'blinded' || _local.post?.deleted_at) ? 'text-gray-400 dark:text-gray-500' : 'text-gray-500 dark:text-gray-400'}}",
},
},
],
};
// ============================================================
// 테스트
// ============================================================
describe('게시판 목록 - 블라인드/삭제 게시글 표시 처리', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('[basic] 제목 색상 처리', () => {
it('블라인드 게시글 제목에 연한 색상(text-gray-400) 클래스가 적용된다', async () => {
const testUtils = createLayoutTest(basicTitleColorLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 1, title: '블라인드 글', status: 'blinded', deleted_at: null } },
},
});
await testUtils.render();
const titleEl = screen.getByTestId('post-title');
expect(titleEl.className).toContain('text-gray-400');
expect(titleEl.className).not.toContain('text-gray-700');
testUtils.cleanup();
});
it('삭제된 게시글 제목에 연한 색상(text-gray-400) 클래스가 적용된다', async () => {
const testUtils = createLayoutTest(basicTitleColorLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 2, title: '삭제된 글', status: 'published', deleted_at: '2024-01-01 00:00:00' } },
},
});
await testUtils.render();
const titleEl = screen.getByTestId('post-title');
expect(titleEl.className).toContain('text-gray-400');
expect(titleEl.className).not.toContain('text-gray-700');
testUtils.cleanup();
});
it('일반 게시글 제목에 기본 색상(text-gray-700) 클래스가 적용된다', async () => {
const testUtils = createLayoutTest(basicTitleColorLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 3, title: '일반 글', status: 'published', deleted_at: null } },
},
});
await testUtils.render();
const titleEl = screen.getByTestId('post-title');
expect(titleEl.className).toContain('text-gray-700');
expect(titleEl.className).not.toContain('text-gray-400');
testUtils.cleanup();
});
});
describe('[card/gallery] 이미지 표시 조건 처리 (썸네일 있으면 항상 표시)', () => {
it('블라인드 게시글도 썸네일이 있으면 이미지가 표시된다', async () => {
const testUtils = createLayoutTest(imageThumbnailConditionLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 1, title: '블라인드 글', status: 'blinded', deleted_at: null, thumbnail: '/img/thumb1.jpg' } },
},
});
await testUtils.render();
expect(screen.getByTestId('post-img')).toBeTruthy();
expect(screen.queryByTestId('post-placeholder')).toBeNull();
testUtils.cleanup();
});
it('삭제된 게시글도 썸네일이 있으면 이미지가 표시된다', async () => {
const testUtils = createLayoutTest(imageThumbnailConditionLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 2, title: '삭제된 글', status: 'published', deleted_at: '2024-01-01 00:00:00', thumbnail: '/img/thumb2.jpg' } },
},
});
await testUtils.render();
expect(screen.getByTestId('post-img')).toBeTruthy();
expect(screen.queryByTestId('post-placeholder')).toBeNull();
testUtils.cleanup();
});
it('썸네일이 없으면 플레이스홀더가 표시된다', async () => {
const testUtils = createLayoutTest(imageThumbnailConditionLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 3, title: '이미지없음', status: 'published', deleted_at: null, thumbnail: null } },
},
});
await testUtils.render();
expect(screen.queryByTestId('post-img')).toBeNull();
expect(screen.getByTestId('post-placeholder')).toBeTruthy();
testUtils.cleanup();
});
it('블라인드 게시글 플레이스홀더에 연한 색상(text-gray-400) 클래스가 적용된다', async () => {
const testUtils = createLayoutTest(imagePlaceholderColorLayoutJson, {
componentRegistry: registry,
initialState: {
_local: { post: { id: 4, title: '블라인드 이미지없음', status: 'blinded', deleted_at: null, thumbnail: null } },
},
});
await testUtils.render();
const placeholderEl = screen.getByTestId('post-placeholder');
expect(placeholderEl.className).toContain('text-gray-400');
expect(placeholderEl.className).not.toContain('text-gray-500 dark:text-gray-400');
testUtils.cleanup();
});
});
});
@@ -0,0 +1,549 @@
/**
* @file board-show-type-renderer.test.tsx
* @description 게시글 상세 - _type_renderer 유형별 분기 렌더링 테스트 (이슈 #153)
*
* 검증 항목:
* 1. basic 유형: 게시글 본문(제목, 작성자, 내용) 렌더링
* 2. gallery 유형: basic과 동일한 show.json 사용 (현재 동일 구현)
* 3. card 유형: basic과 동일한 show.json 사용 (현재 동일 구현)
* 4. 알 수 없는 유형 fallback: basic으로 렌더링
* 5. 이전글/다음글 네비게이션 버튼 조건부 렌더링
* 6. 답글 섹션 iteration.source {{ }} 버그 수정 검증 (replies 목록 렌더링)
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestButton: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
type?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, children, text, onClick, 'data-testid': testId }) => (
<button className={className} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h1 className={className}>{children || text}</h1>
);
const TestH3: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h3 className={className}>{children || text}</h3>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestA: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
href?: string;
'data-testid'?: string;
}> = ({ className, children, text, href, 'data-testid': testId }) => (
<a className={className} href={href} data-testid={testId}>
{children || text}
</a>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={className} data-icon={name} data-size={size} />
);
const TestContainer: React.FC<{
className?: string;
children?: React.ReactNode;
}> = ({ className, children }) => (
<div className={className} data-testid="container">
{children}
</div>
);
const TestAvatar: React.FC<{
author?: any;
size?: string;
}> = ({ author }) => (
<span data-testid="avatar">{author?.name ?? ''}</span>
);
const TestUserInfo: React.FC<{
author?: any;
subText?: string;
layout?: string;
}> = ({ author, subText }) => (
<span data-testid="user-info">
{author?.name ?? ''} {subText}
</span>
);
const TestHtmlContent: React.FC<{
content?: string;
isHtml?: boolean;
className?: string;
}> = ({ content }) => (
<div data-testid="html-content">{content}</div>
);
// ============================================================
// 컴포넌트 레지스트리 설정
// ============================================================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
A: { component: TestA, metadata: { name: 'A', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'composite' } },
Container: { component: TestContainer, metadata: { name: 'Container', type: 'layout' } },
Avatar: { component: TestAvatar, metadata: { name: 'Avatar', type: 'composite' } },
UserInfo: { component: TestUserInfo, metadata: { name: 'UserInfo', type: 'composite' } },
HtmlContent: { component: TestHtmlContent, metadata: { name: 'HtmlContent', type: 'composite' } },
};
return registry;
}
// ============================================================
// 공통 mock post 데이터
// ============================================================
function makePost(overrides: Record<string, any> = {}) {
return {
data: {
id: 1,
title: '테스트 게시글',
content: '게시글 내용입니다.',
content_mode: 'text',
status: 'published',
is_notice: false,
is_secret: false,
is_new: false,
is_author: true,
is_guest_post: false,
deleted_at: null,
view_count: 42,
comment_count: 3,
created_at: '2026-03-06',
author: { name: '홍길동', email: 'hong@example.com' },
board: {
name: '자유게시판',
type: 'basic',
use_comment: true,
use_reply: false,
use_report: false,
show_view_count: true,
},
permissions: {
posts_write: true,
comments_read: true,
manager: false,
},
navigation: {
prev: null,
next: null,
},
replies: [],
comments: [],
...overrides,
},
};
}
// ============================================================
// _type_renderer 유형별 분기 테스트용 레이아웃 JSON
// (partial 분리된 내용을 인라인으로 포함)
// ============================================================
function makeShowLayout(boardType: string, postOverrides: Record<string, any> = {}) {
const postData = makePost({ board: { name: '자유게시판', type: boardType, use_comment: false, use_reply: false, use_report: false, show_view_count: true }, ...postOverrides });
const layout = {
version: '1.0.0',
layout_name: 'board_show_type_renderer_test',
// data_sources 없음 - initialData로 직접 주입 (static type은 processDataSources에서 미처리)
components: [
{
comment: '_type_renderer 인라인 재현',
type: 'basic',
name: 'Div',
children: [
{
comment: 'navigation (인라인)',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'navigation' },
children: [
{
comment: '이전글 버튼',
type: 'basic',
name: 'Button',
if: '{{post?.data?.navigation?.prev?.id}}',
props: { 'data-testid': 'btn-prev' },
children: [
{ type: 'basic', name: 'Span', text: '$t:board.prev' },
],
},
{
comment: '다음글 버튼',
type: 'basic',
name: 'Button',
if: '{{post?.data?.navigation?.next?.id}}',
props: { 'data-testid': 'btn-next' },
children: [
{ type: 'basic', name: 'Span', text: '$t:board.next' },
],
},
],
},
{
comment: 'basic 유형 (fallback 포함)',
type: 'basic',
name: 'Div',
if: "{{post?.data?.board?.type === 'basic' || !['gallery','card'].includes(post?.data?.board?.type ?? 'basic')}}",
props: { 'data-testid': 'show-basic' },
children: [
{
type: 'basic',
name: 'H1',
text: '{{post?.data?.title ?? ""}}',
props: { 'data-testid': 'post-title' },
},
{
type: 'composite',
name: 'HtmlContent',
if: "{{post?.data?.status !== 'blinded' && post?.data?.content !== null}}",
props: {
content: '{{post?.data?.content ?? ""}}',
isHtml: "{{(post?.data?.content_mode ?? 'text') === 'html'}}",
},
},
],
},
{
comment: 'gallery 유형',
type: 'basic',
name: 'Div',
if: "{{post?.data?.board?.type === 'gallery'}}",
props: { 'data-testid': 'show-gallery' },
children: [
{
type: 'basic',
name: 'H1',
text: '{{post?.data?.title ?? ""}}',
},
],
},
{
comment: 'card 유형',
type: 'basic',
name: 'Div',
if: "{{post?.data?.board?.type === 'card'}}",
props: { 'data-testid': 'show-card' },
children: [
{
type: 'basic',
name: 'H1',
text: '{{post?.data?.title ?? ""}}',
},
],
},
],
},
],
};
return { layout, initialData: { post: postData } };
}
// ============================================================
// 답글 iteration 테스트용 레이아웃 JSON
// (iteration.source {{ }} 버그 수정 검증)
// ============================================================
// data_sources: static은 processDataSources에서 처리되지 않으므로 initialData로 주입
const repliesIterationInitialData = {
post: {
data: {
id: 1,
title: '답글 테스트',
board: { type: 'basic', use_comment: false },
permissions: { comments_read: true },
is_secret: false,
content: '내용',
replies: [
{ id: 10, title: '첫 번째 답글', content: '답글 내용 1', is_secret: false, deleted_at: null, author: { name: '답글작성자1' }, created_at: '2026-03-06' },
{ id: 20, title: '두 번째 답글', content: '답글 내용 2', is_secret: false, deleted_at: null, author: { name: '답글작성자2' }, created_at: '2026-03-06' },
],
},
},
};
const repliesIterationLayout = {
version: '1.0.0',
layout_name: 'board_show_replies_iteration_test',
components: [
{
comment: '답글 섹션 - iteration.source {{ }} 수정 후 정상 동작 검증',
type: 'basic',
name: 'Div',
if: '{{(post?.data?.replies ?? []).length > 0}}',
props: { 'data-testid': 'replies-section' },
children: [
{
type: 'basic',
name: 'Div',
iteration: {
source: '{{post?.data?.replies ?? []}}',
item_var: 'reply',
index_var: 'replyIndex',
},
children: [
{
type: 'basic',
name: 'A',
props: {
href: '/board/test/{{reply.id}}',
'data-testid': 'reply-title-link',
},
text: '{{reply?.title ?? ""}}',
},
],
},
],
},
],
};
// ============================================================
// 테스트
// ============================================================
describe('board/show _type_renderer 유형별 분기 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('[1] basic 유형', () => {
it('show-basic 영역이 렌더링되고 show-gallery/show-card는 렌더링되지 않는다', async () => {
const { layout, initialData } = makeShowLayout('basic');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('show-basic')).toBeInTheDocument();
expect(screen.queryByTestId('show-gallery')).not.toBeInTheDocument();
expect(screen.queryByTestId('show-card')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('게시글 제목이 표시된다', async () => {
const { layout, initialData } = makeShowLayout('basic');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByText('테스트 게시글')).toBeInTheDocument();
testUtils.cleanup();
});
it('게시글 내용이 HtmlContent로 렌더링된다', async () => {
const { layout, initialData } = makeShowLayout('basic');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
const htmlContent = screen.getByTestId('html-content');
expect(htmlContent).toBeInTheDocument();
expect(htmlContent.textContent).toBe('게시글 내용입니다.');
testUtils.cleanup();
});
});
describe('[2] gallery 유형', () => {
it('show-gallery 영역이 렌더링되고 show-basic은 렌더링되지 않는다', async () => {
const { layout, initialData } = makeShowLayout('gallery');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('show-gallery')).toBeInTheDocument();
expect(screen.queryByTestId('show-basic')).not.toBeInTheDocument();
expect(screen.queryByTestId('show-card')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[3] card 유형', () => {
it('show-card 영역이 렌더링되고 show-basic/show-gallery는 렌더링되지 않는다', async () => {
const { layout, initialData } = makeShowLayout('card');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('show-card')).toBeInTheDocument();
expect(screen.queryByTestId('show-basic')).not.toBeInTheDocument();
expect(screen.queryByTestId('show-gallery')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[4] 알 수 없는 유형 fallback', () => {
it('unknown 유형은 basic으로 fallback 렌더링된다', async () => {
const { layout, initialData } = makeShowLayout('unknown_type');
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('show-basic')).toBeInTheDocument();
expect(screen.queryByTestId('show-gallery')).not.toBeInTheDocument();
expect(screen.queryByTestId('show-card')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[5] 네비게이션 - 이전글/다음글 버튼 조건부 렌더링', () => {
it('prev/next 모두 없으면 버튼이 렌더링되지 않는다', async () => {
const { layout, initialData } = makeShowLayout('basic', { navigation: { prev: null, next: null } });
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.queryByTestId('btn-prev')).not.toBeInTheDocument();
expect(screen.queryByTestId('btn-next')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('prev가 있으면 이전글 버튼이 렌더링된다', async () => {
const { layout, initialData } = makeShowLayout('basic', { navigation: { prev: { id: 5 }, next: null } });
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('btn-prev')).toBeInTheDocument();
expect(screen.queryByTestId('btn-next')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('next가 있으면 다음글 버튼이 렌더링된다', async () => {
const { layout, initialData } = makeShowLayout('basic', { navigation: { prev: null, next: { id: 7 } } });
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.queryByTestId('btn-prev')).not.toBeInTheDocument();
expect(screen.getByTestId('btn-next')).toBeInTheDocument();
testUtils.cleanup();
});
it('prev/next 모두 있으면 두 버튼 모두 렌더링된다', async () => {
const { layout, initialData } = makeShowLayout('basic', { navigation: { prev: { id: 5 }, next: { id: 7 } } });
const testUtils = createLayoutTest(layout as any, { componentRegistry: registry, initialData });
await testUtils.render();
expect(screen.getByTestId('btn-prev')).toBeInTheDocument();
expect(screen.getByTestId('btn-next')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('[6] 답글 iteration.source {{ }} 버그 수정 검증', () => {
/**
* 증상: 원본 show.json line 1252에서 iteration.source가 {{ }} 없이
* "post?.data?.replies ?? []" 로 작성되어 answers 목록이 렌더링되지 않는 버그.
* 해결: types/basic/show.json에서 "{{post?.data?.replies ?? []}}" 로 수정.
*/
it('replies가 있을 때 iteration으로 각 답글 제목 링크가 렌더링된다', async () => {
const testUtils = createLayoutTest(repliesIterationLayout as any, { componentRegistry: registry, initialData: repliesIterationInitialData });
await testUtils.render();
expect(screen.getByTestId('replies-section')).toBeInTheDocument();
const links = screen.getAllByTestId('reply-title-link');
expect(links).toHaveLength(2);
expect(links[0].textContent).toBe('첫 번째 답글');
expect(links[1].textContent).toBe('두 번째 답글');
testUtils.cleanup();
});
it('replies가 비어있으면 답글 섹션이 렌더링되지 않는다', async () => {
const noRepliesInitialData = {
post: {
data: {
id: 1,
title: '답글 없는 게시글',
board: { type: 'basic' },
permissions: { comments_read: true },
is_secret: false,
content: '내용',
replies: [],
},
},
};
const testUtils = createLayoutTest(repliesIterationLayout as any, { componentRegistry: registry, initialData: noRepliesInitialData });
await testUtils.render();
expect(screen.queryByTestId('replies-section')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,460 @@
/**
* @file login.test.tsx
* @description 로그인 폼 레이아웃 렌더링 테스트 (Issue #72)
*
* 테스트 케이스:
* - 기본 렌더링: 로그인 폼 구성 요소 확인
* - 로딩 상태: 버튼 스피너 표시, 입력 필드 비활성화, 블러 오버레이 미표시
* - 에러 표시: API 에러 메시지 렌더링
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
createLayoutTest,
screen,
waitFor,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button
type={type as 'button' | 'submit' | 'reset'}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children || text}
</button>
);
const TestInput: React.FC<{
type?: string;
name?: string;
placeholder?: string;
required?: boolean;
disabled?: boolean;
className?: string;
'data-testid'?: string;
}> = ({ type, name, placeholder, required, disabled, className, 'data-testid': testId }) => (
<input
type={type}
name={name}
placeholder={placeholder}
required={required}
disabled={disabled}
className={className}
data-testid={testId}
/>
);
const TestPasswordInput: React.FC<{
name?: string;
placeholder?: string;
required?: boolean;
disabled?: boolean;
showToggle?: boolean;
error?: string;
className?: string;
'data-testid'?: string;
}> = ({ name, placeholder, required, disabled, className, 'data-testid': testId }) => (
<input
type="password"
name={name}
placeholder={placeholder}
required={required}
disabled={disabled}
className={className}
data-testid={testId}
/>
);
const TestForm: React.FC<{
className?: string;
children?: React.ReactNode;
onSubmit?: (e: React.FormEvent) => void;
'data-testid'?: string;
}> = ({ className, children, onSubmit, 'data-testid': testId }) => (
<form className={className} onSubmit={onSubmit} data-testid={testId}>{children}</form>
);
const TestLabel: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<label className={className} data-testid={testId}>{children || text}</label>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<p className={className} data-testid={testId}>{children || text}</p>
);
const TestFragment: React.FC<{ children?: React.ReactNode }> =
({ children }) => <>{children}</>;
// ========== 테스트용 레이아웃 Fixture ==========
/**
* 로그인 폼 레이아웃 (partial을 해결한 형태)
* _login_form.json 기반 — 오버레이 제거 후 상태
*/
const loginFormFixture = {
version: '1.0.0',
layout_name: 'auth/login',
state: {},
components: [
{
id: 'login-form',
type: 'basic',
name: 'Form',
props: { className: 'space-y-6', 'data-testid': 'login-form' },
children: [
// API 에러 메시지
{
id: 'login-error',
type: 'basic',
name: 'Div',
if: '{{_global.loginError}}',
props: {
className: 'p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800',
'data-testid': 'login-error',
},
children: [
{
type: 'basic',
name: 'P',
props: { className: 'text-sm text-red-600 dark:text-red-400' },
text: '{{_global.loginError}}',
},
],
},
// 이메일 입력 필드
{
id: 'email-field',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'email-field' },
children: [
{
type: 'basic',
name: 'Label',
props: { className: 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3' },
text: '이메일',
},
{
type: 'basic',
name: 'Input',
props: {
type: 'email',
name: 'email',
placeholder: '이메일을 입력하세요',
required: true,
disabled: '{{_global.isLoggingIn}}',
'data-testid': 'email-input',
},
},
],
},
// 비밀번호 입력 필드
{
id: 'password-field',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'password-field' },
children: [
{
type: 'basic',
name: 'Label',
props: { className: 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3' },
text: '비밀번호',
},
{
type: 'basic',
name: 'PasswordInput',
props: {
name: 'password',
placeholder: '비밀번호를 입력하세요',
required: true,
disabled: '{{_global.isLoggingIn}}',
showToggle: true,
'data-testid': 'password-input',
},
},
],
},
// 제출 버튼
{
id: 'submit-button',
type: 'basic',
name: 'Button',
props: {
type: 'submit',
className: 'w-full py-3 mt-12 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg font-medium hover:bg-gray-800 dark:hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2',
disabled: '{{_global.isLoggingIn}}',
'data-testid': 'login-submit-btn',
},
children: [
{
id: 'button-spinner',
type: 'basic',
name: 'Div',
if: '{{_global.isLoggingIn}}',
props: {
className: 'w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin',
'data-testid': 'button-spinner',
},
},
{
type: 'basic',
name: 'Span',
if: '{{!_global.isLoggingIn}}',
text: '로그인',
},
{
type: 'basic',
name: 'Span',
if: '{{_global.isLoggingIn}}',
props: { 'data-testid': 'login-processing-text' },
text: '로그인 중...',
},
],
},
],
actions: [
{
type: 'submit',
handler: 'sequence',
actions: [
{
handler: 'setState',
params: {
target: 'global',
isLoggingIn: true,
loginError: null,
loginErrors: null,
},
},
{
handler: 'login',
target: 'user',
params: {
body: {
email: '{{form.email}}',
password: '{{form.password}}',
},
},
onSuccess: [
{ handler: 'setState', params: { target: 'global', currentUser: '{{response.user}}' } },
{ handler: 'setState', params: { target: 'global', isLoggingIn: false } },
{ handler: 'toast', params: { type: 'success', message: '로그인 성공' } },
{ handler: 'navigate', params: { path: '{{query.redirect ?? "/"}}' } },
],
onError: [
{ handler: 'setState', params: { target: 'global', isLoggingIn: false, loginError: '{{error.message}}', loginErrors: '{{error.errors}}' } },
],
},
],
},
],
},
],
};
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
PasswordInput: { component: TestPasswordInput, metadata: { name: 'PasswordInput', type: 'basic' } },
Form: { component: TestForm, metadata: { name: 'Form', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ========== 테스트 케이스 ==========
describe('로그인 폼 레이아웃 렌더링 (Issue #72)', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('기본 렌더링', () => {
it('로그인 폼이 이메일, 비밀번호, 제출 버튼과 함께 렌더링된다', async () => {
// Given
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
});
// When
await testUtils.render();
// Then
expect(screen.getByTestId('login-form')).toBeInTheDocument();
expect(screen.getByTestId('email-field')).toBeInTheDocument();
expect(screen.getByTestId('email-input')).toBeInTheDocument();
expect(screen.getByTestId('password-field')).toBeInTheDocument();
expect(screen.getByTestId('password-input')).toBeInTheDocument();
expect(screen.getByTestId('login-submit-btn')).toBeInTheDocument();
testUtils.cleanup();
});
it('초기 상태에서 에러 메시지가 표시되지 않는다', async () => {
// Given: loginError가 없는 초기 상태
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
});
// When
await testUtils.render();
// Then: 에러 div가 렌더링되지 않음
expect(screen.queryByTestId('login-error')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('로딩 상태 (isLoggingIn)', () => {
it('로그인 중 블러 오버레이가 표시되지 않는다 (Issue #72 핵심)', async () => {
// Given: isLoggingIn=true 상태
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
initialState: { _global: { isLoggingIn: true } },
});
// When
await testUtils.render();
// Then: backdrop-blur 오버레이가 존재하지 않음
const allDivs = document.querySelectorAll('div');
const hasBackdropBlur = Array.from(allDivs).some(
(div) => div.className && div.className.includes('backdrop-blur')
);
expect(hasBackdropBlur).toBe(false);
// But: 버튼 내 스피너는 표시됨
expect(screen.getByTestId('button-spinner')).toBeInTheDocument();
testUtils.cleanup();
});
it('로그인 중 버튼에 스피너와 "로그인 중..." 텍스트가 표시된다', async () => {
// Given
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
initialState: { _global: { isLoggingIn: true } },
});
// When
await testUtils.render();
// Then
expect(screen.getByTestId('button-spinner')).toBeInTheDocument();
expect(screen.getByTestId('login-processing-text')).toBeInTheDocument();
testUtils.cleanup();
});
it('로그인 중 입력 필드가 비활성화된다', async () => {
// Given
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
initialState: { _global: { isLoggingIn: true } },
});
// When
await testUtils.render();
// Then
expect(screen.getByTestId('email-input')).toBeDisabled();
expect(screen.getByTestId('password-input')).toBeDisabled();
expect(screen.getByTestId('login-submit-btn')).toBeDisabled();
testUtils.cleanup();
});
it('로그인 중이 아닐 때 스피너가 표시되지 않는다', async () => {
// Given: isLoggingIn=false (기본)
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
initialState: { _global: { isLoggingIn: false } },
});
// When
await testUtils.render();
// Then
expect(screen.queryByTestId('button-spinner')).not.toBeInTheDocument();
expect(screen.queryByTestId('login-processing-text')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('에러 표시', () => {
it('loginError 설정 시 에러 메시지가 표시된다', async () => {
// Given
const testUtils = createLayoutTest(loginFormFixture, {
componentRegistry: registry,
initialState: { _global: { loginError: '이메일 또는 비밀번호가 올바르지 않습니다.' } },
});
// When
await testUtils.render();
// Then
expect(screen.getByTestId('login-error')).toBeInTheDocument();
testUtils.cleanup();
});
});
});
@@ -0,0 +1,476 @@
/**
* @file mypage-addresses.test.tsx
* @description 마이페이지 배송지 관리 레이아웃 렌더링 테스트
*
* 테스트 케이스 (8개)
* - 기본 렌더링: 배송지 목록 렌더링
* - 빈 상태: 배송지가 없을 때 빈 상태 표시
* - 기본 배송지 뱃지: is_default 배송지에 뱃지 표시
* - 새 배송지 추가 버튼: 추가 버튼 렌더링
* - 배송지 수정 버튼: 수정 버튼 렌더링
* - 배송지 삭제 확인: 삭제 시 확인 메시지
* - 배송지 추가 API 호출: apiCall 핸들러 검증
* - 422 검증 에러 표시: 필드별 에러 표시
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
createLayoutTest,
screen,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button
type={type as 'button' | 'submit' | 'reset'}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children || text}
</button>
);
const TestH2: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <h2 className={className} data-testid={testId}>{children || text}</h2>;
const TestIcon: React.FC<{ name?: string; className?: string; 'data-testid'?: string }> =
({ name, className, 'data-testid': testId }) => <i className={`icon-${name} ${className || ''}`} data-icon={name} data-testid={testId} />;
const TestInput: React.FC<{
type?: string;
name?: string;
value?: string;
placeholder?: string;
error?: string;
className?: string;
'data-testid'?: string;
}> = ({ type, name, value, placeholder, error, className, 'data-testid': testId }) => (
<div data-testid={testId}>
<input type={type} name={name} value={value} placeholder={placeholder} className={className} readOnly />
{error && <span className="text-red-500 text-sm">{error}</span>}
</div>
);
const TestP: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <p className={className} data-testid={testId}>{children || text}</p>;
const TestLabel: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <label className={className} data-testid={testId}>{children || text}</label>;
const TestFragment: React.FC<{ children?: React.ReactNode }> =
({ children }) => <>{children}</>;
// ========== 테스트용 레이아웃 Fixture ==========
const addressListFixture = {
version: '1.0.0',
layout_name: 'mypage/addresses',
state: {
editingAddress: null,
errors: {},
},
data_sources: [
{
id: 'userAddresses',
endpoint: '/api/modules/sirsoft-ecommerce/user/addresses',
method: 'GET',
},
],
components: [
{
type: 'basic',
name: 'Div',
props: { className: 'space-y-6', 'data-testid': 'addresses-container' },
children: [
{
comment: '헤더',
type: 'basic',
name: 'Div',
props: { className: 'flex items-center justify-between', 'data-testid': 'addresses-header' },
children: [
{
type: 'basic',
name: 'H2',
props: { className: 'text-xl font-bold', 'data-testid': 'addresses-title' },
text: '배송지 관리',
},
{
type: 'basic',
name: 'Button',
props: { type: 'button', className: 'btn-primary', 'data-testid': 'add-address-btn' },
text: '새 주소 추가',
},
],
},
{
comment: '배송지 목록 (있을 때)',
type: 'basic',
name: 'Div',
if: '{{(userAddresses?.data?.addresses ?? []).length > 0}}',
props: { 'data-testid': 'addresses-list' },
iteration: {
source: '{{userAddresses?.data?.addresses ?? []}}',
item_var: 'addr',
},
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'border rounded-lg p-4', 'data-testid': 'address-card' },
children: [
{
type: 'basic',
name: 'Span',
props: { className: 'font-medium', 'data-testid': 'address-name' },
text: '{{addr.name}}',
},
{
type: 'basic',
name: 'Span',
if: '{{addr.is_default}}',
props: { className: 'badge', 'data-testid': 'default-badge' },
text: '기본 배송지',
},
{
type: 'basic',
name: 'P',
props: { 'data-testid': 'address-detail' },
text: '{{addr.recipient_name}} | {{addr.recipient_phone}}',
},
{
type: 'basic',
name: 'P',
text: '[{{addr.zipcode}}] {{addr.address}} {{addr.address_detail}}',
},
{
type: 'basic',
name: 'Div',
props: { className: 'flex gap-2' },
children: [
{
type: 'basic',
name: 'Button',
props: { type: 'button', 'data-testid': 'edit-address-btn' },
text: '수정',
},
{
type: 'basic',
name: 'Button',
props: { type: 'button', 'data-testid': 'delete-address-btn' },
text: '삭제',
actions: [
{
type: 'click',
confirm: '이 배송지를 삭제하시겠습니까?',
handler: 'apiCall',
target: '/api/modules/sirsoft-ecommerce/user/addresses/{{addr.id}}',
params: { method: 'DELETE' },
},
],
},
],
},
],
},
],
},
{
comment: '빈 상태',
type: 'basic',
name: 'Div',
if: '{{!(userAddresses?.data?.addresses ?? []).length}}',
props: { 'data-testid': 'empty-state' },
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'map-pin', className: 'w-10 h-10' },
},
{
type: 'basic',
name: 'P',
props: { 'data-testid': 'empty-message' },
text: '등록된 배송지가 없습니다.',
},
],
},
],
},
],
};
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
H2: { component: TestH2, metadata: { name: 'H2', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ========== 테스트 ==========
describe('마이페이지 배송지 관리 레이아웃', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
testUtils?.cleanup();
vi.restoreAllMocks();
});
it('배송지 목록을 렌더링한다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: {
data: {
addresses: [
{
id: 1,
name: '집',
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
zipcode: '12345',
address: '서울시 강남구',
address_detail: '101동 201호',
is_default: true,
},
{
id: 2,
name: '회사',
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
zipcode: '54321',
address: '서울시 서초구',
address_detail: '오피스 301호',
is_default: false,
},
],
},
},
});
await testUtils.render();
expect(screen.getByTestId('addresses-container')).toBeInTheDocument();
expect(screen.getByTestId('addresses-title')).toBeInTheDocument();
// iteration이 각 항목에 대해 addresses-list를 렌더링하므로 getAllByTestId 사용
const lists = screen.getAllByTestId('addresses-list');
expect(lists.length).toBeGreaterThan(0);
});
it('배송지가 없을 때 빈 상태를 표시한다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: { data: { addresses: [] } },
});
await testUtils.render();
expect(screen.getByTestId('empty-state')).toBeInTheDocument();
expect(screen.getByTestId('empty-message')).toBeInTheDocument();
});
it('기본 배송지에 뱃지를 표시한다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: {
data: {
addresses: [
{
id: 1,
name: '집',
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
zipcode: '12345',
address: '서울시 강남구',
address_detail: '',
is_default: true,
},
],
},
},
});
await testUtils.render();
expect(screen.getByTestId('default-badge')).toBeInTheDocument();
});
it('새 주소 추가 버튼이 렌더링된다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: { data: { addresses: [] } },
});
await testUtils.render();
expect(screen.getByTestId('add-address-btn')).toBeInTheDocument();
});
it('배송지 수정/삭제 버튼이 렌더링된다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: {
data: {
addresses: [
{
id: 1,
name: '집',
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
zipcode: '12345',
address: '서울시 강남구',
address_detail: '',
is_default: false,
},
],
},
},
});
await testUtils.render();
expect(screen.getByTestId('edit-address-btn')).toBeInTheDocument();
expect(screen.getByTestId('delete-address-btn')).toBeInTheDocument();
});
it('수령인 정보가 렌더링된다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: {
data: {
addresses: [
{
id: 1,
name: '집',
recipient_name: '김철수',
recipient_phone: '010-9999-8888',
zipcode: '12345',
address: '서울시 강남구',
address_detail: '101동',
is_default: false,
},
],
},
},
});
await testUtils.render();
const detail = screen.getByTestId('address-detail');
expect(detail).toBeInTheDocument();
expect(detail.textContent).toContain('김철수');
expect(detail.textContent).toContain('010-9999-8888');
});
it('삭제 버튼에 confirm 속성이 설정되어 있다', () => {
const deleteAction = addressListFixture.components[0].children[1]
.children[0].children[4].children[1].actions[0];
expect(deleteAction.confirm).toBe('이 배송지를 삭제하시겠습니까?');
expect(deleteAction.handler).toBe('apiCall');
expect(deleteAction.params.method).toBe('DELETE');
});
it('기본 배송지가 아닌 항목에는 뱃지가 표시되지 않는다', async () => {
testUtils = createLayoutTest(addressListFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('userAddresses', {
response: {
data: {
addresses: [
{
id: 1,
name: '회사',
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
zipcode: '12345',
address: '서울시 강남구',
address_detail: '',
is_default: false,
},
],
},
},
});
await testUtils.render();
expect(screen.queryByTestId('default-badge')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,389 @@
/**
* 마이페이지 상품 1:1 문의내역 레이아웃 구조 검증 테스트
*
* @description
* - inquiries.json 데이터소스 및 API 엔드포인트 검증
* - _list.json 문의 목록 UI, 필드명 바인딩, 상태 뱃지 검증
* - 비밀글 처리, 답변 조건부 렌더링, 페이지네이션 검증
*/
import { describe, it, expect } from 'vitest';
import inquiriesLayout from '../../../layouts/mypage/inquiries.json';
import listPartial from '../../../layouts/partials/mypage/inquiries/_list.json';
// ========================================================================
// inquiries.json (문의내역 목록 페이지)
// ========================================================================
describe('마이페이지 문의내역 레이아웃 검증 (inquiries.json)', () => {
it('_user_base 레이아웃을 상속해야 함', () => {
expect(inquiriesLayout.extends).toBe('_user_base');
});
it('computed.currentTab이 "inquiries"여야 함', () => {
expect((inquiriesLayout as any).computed?.currentTab).toBe('inquiries');
});
it('데이터소스가 올바른 모듈 API 엔드포인트를 사용해야 함', () => {
const ds = inquiriesLayout.data_sources[0];
expect(ds.id).toBe('myInquiries');
expect(ds.endpoint).toBe('/api/modules/sirsoft-ecommerce/user/inquiries');
expect(ds.method).toBe('GET');
expect(ds.auto_fetch).toBe(true);
expect(ds.auth_required).toBe(true);
});
it('데이터소스에 페이지네이션 파라미터가 있어야 함', () => {
const ds = inquiriesLayout.data_sources[0];
const dsAny = ds as any;
expect(dsAny.params?.page).toContain('query.page');
});
it('init_actions에서 inquiriesPage 초기값을 설정해야 함', () => {
const initActions = (inquiriesLayout as any).init_actions ?? [];
const initAction = initActions.find((a: any) => a.handler === 'setState' && a.params?.target === 'local');
expect(initAction).toBeDefined();
expect(initAction.params.inquiriesPage).toBeDefined();
});
it('transition_overlay 스켈레톤 설정이 있어야 함', () => {
const overlay = (inquiriesLayout as any).transition_overlay;
expect(overlay).toBeDefined();
expect(overlay.enabled).toBe(true);
expect(overlay.style).toBe('skeleton');
expect(overlay.target).toBe('mypage_tab_content');
});
it('_tab_navigation partial을 참조해야 함', () => {
const layoutStr = JSON.stringify(inquiriesLayout);
expect(layoutStr).toContain('partials/mypage/_tab_navigation.json');
});
it('_list.json partial을 참조해야 함', () => {
const layoutStr = JSON.stringify(inquiriesLayout);
expect(layoutStr).toContain('partials/mypage/inquiries/_list.json');
});
it('/api/shop/ 경로를 사용하지 않아야 함', () => {
const ds = inquiriesLayout.data_sources[0];
expect(ds.endpoint).not.toContain('/api/shop/');
});
it('데이터소스 onSuccess에서 inquiry_available 기반 404 처리를 해야 함', () => {
const ds = (inquiriesLayout as any).data_sources[0];
const onSuccess = ds.onSuccess;
expect(onSuccess).toBeDefined();
expect(onSuccess.handler).toBe('conditions');
const condition = onSuccess.conditions?.[0];
expect(condition).toBeDefined();
expect(condition.if).toContain('inquiry_available');
expect(condition.then?.handler).toBe('showErrorPage');
expect(condition.then?.params?.errorCode).toBe(404);
});
});
// ========================================================================
// _list.json (문의 목록 partial)
// ========================================================================
describe('문의내역 목록 partial 구조 검증 (_list.json)', () => {
const listStr = JSON.stringify(listPartial);
describe('Partial 기본 구조', () => {
it('is_partial 메타 속성이 있어야 함', () => {
expect((listPartial as any).meta?.is_partial).toBe(true);
});
it('blur_until_loaded가 myInquiries 데이터소스를 참조해야 함', () => {
const blur = (listPartial as any).blur_until_loaded;
expect(blur?.enabled).toBe(true);
expect(blur?.data_sources).toBe('myInquiries');
});
});
describe('데이터 바인딩 필드명', () => {
it('문의 목록 데이터 경로로 myInquiries.data.items를 사용해야 함', () => {
expect(listStr).toContain('myInquiries.data.items');
});
it('총 개수 경로로 myInquiries.data.meta.total을 사용해야 함', () => {
expect(listStr).toContain('myInquiries.data.meta.total');
});
it('상품명 필드로 item.product_name을 사용해야 함', () => {
expect(listStr).toContain('item.product_name');
});
it('답변 여부 필드로 item.is_answered를 사용해야 함', () => {
expect(listStr).toContain('item.is_answered');
});
it('문의 내용 필드로 item.content를 사용해야 함', () => {
expect(listStr).toContain('item.content');
});
it('답변 내용 필드로 item.reply를 사용해야 함', () => {
expect(listStr).toContain('item.reply');
});
it('작성일 필드로 item.created_at을 사용해야 함', () => {
expect(listStr).toContain('item.created_at');
});
});
describe('반복 렌더링 (iteration)', () => {
it('iteration source가 myInquiries.data.items를 사용해야 함', () => {
expect(listStr).toContain('"source"');
expect(listStr).toContain('myInquiries.data.items');
});
it('iteration 변수명이 item_var: "item"을 사용해야 함 (item/index 금지)', () => {
expect(listStr).toContain('"item_var"');
const hasItemVar = listStr.includes('"item_var":"item"') || listStr.includes('"item_var": "item"');
expect(hasItemVar).toBe(true);
});
it('iteration에서 "index" 변수명을 사용하지 않아야 함', () => {
const iterationMatch = listStr.match(/"item_var"\s*:\s*"([^"]+)"/);
if (iterationMatch) {
expect(iterationMatch[1]).not.toBe('index');
}
});
});
describe('비밀글 처리', () => {
it('본인 글이므로 item.content를 항상 표시해야 함 (비밀글 마스킹 없음)', () => {
expect(listStr).toContain('item.content');
});
it('비밀글 마스킹(secret_content)을 사용하지 않아야 함', () => {
// item.is_secret은 수정 폼 초기값(qnaForm.is_secret)으로 사용되므로 파일에 존재함
// 마스킹 목적(secret_content 다국어 키)은 사용하지 않아야 함
expect(listStr).not.toContain('mypage.inquiries.secret_content');
});
});
describe('답변 상태', () => {
it('답변 완료 상태 다국어 키를 사용해야 함', () => {
expect(listStr).toContain('mypage.inquiries.status.answered');
});
it('답변 대기 상태 다국어 키를 사용해야 함', () => {
expect(listStr).toContain('mypage.inquiries.status.pending');
});
it('답변 내용은 is_answered && reply 조건으로만 표시해야 함', () => {
expect(listStr).toContain('item.is_answered');
expect(listStr).toContain('item.reply');
});
it('답변은 토글 없이 항상 표시되어야 함 (openedReplyId 토글 없음)', () => {
expect(listStr).not.toContain('openedReplyId');
});
it('답변 내용 접근 시 item.reply.content를 사용해야 함', () => {
expect(listStr).toContain('item.reply?.content');
});
});
describe('빈 상태 처리', () => {
it('문의 없음 메시지에 mypage.inquiries.empty 키를 사용해야 함', () => {
expect(listStr).toContain('mypage.inquiries.empty');
});
it('빈 상태에서 쇼핑 이동 버튼이 있어야 함', () => {
expect(listStr).toContain('mypage.inquiries.go_shopping');
});
it('쇼핑 이동 버튼이 navigate 핸들러를 사용해야 함', () => {
const listSection = (listPartial as any).children?.find(
(c: any) => c.comment?.includes('문의 목록')
);
const emptySection = listSection?.children?.find(
(c: any) => c.comment?.includes('문의 없음')
);
const button = emptySection?.children?.find((c: any) => c.name === 'Button');
const navAction = button?.actions?.[0];
expect(navAction?.handler).toBe('navigate');
});
});
describe('페이지네이션', () => {
it('Pagination 컴포넌트가 있어야 함', () => {
expect(listStr).toContain('"name":"Pagination"');
});
it('페이지네이션이 myInquiries.data.meta 경로를 사용해야 함', () => {
expect(listStr).toContain('myInquiries.data.meta.last_page');
expect(listStr).toContain('myInquiries.data.meta.current_page');
});
it('페이지 변경 시 sequence 핸들러로 setState + refetchDataSource를 호출해야 함', () => {
const listChildren = (listPartial as any).children;
const listSection = listChildren?.find((c: any) => c.comment?.includes('문의 목록'));
const paginationChildren = listSection?.children;
const pagination = paginationChildren?.find((c: any) => c.name === 'Pagination');
expect(pagination).toBeDefined();
const pageChangeAction = pagination?.actions?.find(
(a: any) => a.event === 'onPageChange'
);
expect(pageChangeAction).toBeDefined();
expect(pageChangeAction?.handler).toBe('sequence');
const setStateAction = pageChangeAction?.actions?.find(
(a: any) => a.handler === 'setState'
);
expect(setStateAction?.params?.target).toBe('local');
const refetchAction = pageChangeAction?.actions?.find(
(a: any) => a.handler === 'refetchDataSource'
);
expect(refetchAction?.params?.dataSourceId).toBe('myInquiries');
});
});
describe('날짜 표시', () => {
it('질문일에 date 파이프를 사용해야 함', () => {
expect(listStr).toContain('item.created_at | date');
});
it('답변일에 date 파이프를 사용해야 함', () => {
expect(listStr).toContain('item.reply?.created_at | date');
});
});
describe('상품 이미지', () => {
it('상품 썸네일이 있을 때 Img 컴포넌트로 표시해야 함', () => {
expect(listStr).toContain('item.product.thumbnail_url');
expect(listStr).toContain('"name":"Img"');
});
it('상품 썸네일은 조건부로 표시해야 함 (thumbnail_url 있을 때만)', () => {
const hasCondition =
listStr.includes('item.product && item.product.thumbnail_url') ||
listStr.includes('item.product?.thumbnail_url');
expect(hasCondition).toBe(true);
});
});
describe('검색 및 필터', () => {
it('SearchBar 컴포넌트를 사용하지 않아야 함 (검색 입력 제거됨)', () => {
expect(listStr).not.toContain('"name":"SearchBar"');
});
it('inquiriesSearch 상태를 사용하지 않아야 함 (검색 입력 제거됨)', () => {
expect(listStr).not.toContain('inquiriesSearch');
});
it('필터 변경 시 refetchDataSource를 호출해야 함', () => {
expect(listStr).toContain('refetchDataSource');
});
it('답변 상태 필터가 탭 버튼 형태여야 함 (Select 대신 Button)', () => {
expect(listStr).not.toContain('"name":"Select"');
expect(listStr).toContain('inquiriesFilter');
});
it('필터가 inquiriesFilter 상태와 바인딩되어야 함', () => {
expect(listStr).toContain('inquiriesFilter');
});
it('필터 옵션에 mypage.inquiries.filter 다국어 키를 사용해야 함', () => {
expect(listStr).toContain('mypage.inquiries.filter.all');
expect(listStr).toContain('mypage.inquiries.filter.answered');
expect(listStr).toContain('mypage.inquiries.filter.pending');
});
it('검색 placeholder 다국어 키를 사용하지 않아야 함 (placeholder 제거됨)', () => {
expect(listStr).not.toContain('search_placeholder');
});
});
describe('다국어 키 형식', () => {
it('mypage 네임스페이스 키를 사용해야 함 ($t:mypage.inquiries.*)', () => {
expect(listStr).toContain('$t:mypage.inquiries.');
});
it('sirsoft-ecommerce 모듈 네임스페이스를 레이아웃 키에서 사용하지 않아야 함', () => {
expect(listStr).not.toContain('$t:sirsoft-ecommerce.mypage.inquiries');
});
});
describe('수정됨 표시 (Issue #208 개편)', () => {
it('item.updated_at 필드를 사용해야 함', () => {
expect(listStr).toContain('item.updated_at');
});
it('updated_at !== created_at 조건으로 수정됨을 판별해야 함', () => {
expect(listStr).toContain('item.updated_at !== item.created_at');
});
it('수정됨 표시에 mypage.inquiries.updated_label_at 다국어 키를 사용해야 함', () => {
expect(listStr).toContain('mypage.inquiries.updated_label_at');
});
});
describe('삭제 모달 방식 (Issue #208 개편)', () => {
it('삭제 버튼이 apiCall confirm 방식을 사용하지 않아야 함', () => {
expect(listStr).not.toContain('"confirm"');
});
it('삭제 버튼이 openModal 핸들러를 사용해야 함', () => {
expect(listStr).toContain('"openModal"');
});
it('삭제 버튼이 inquiry_delete_modal을 열어야 함', () => {
expect(listStr).toContain('inquiry_delete_modal');
});
it('삭제 시 qnaDeleteSource가 "mypage"로 설정되어야 함', () => {
expect(listStr).toContain('"mypage"');
});
it('삭제 시 qnaDeleteId가 설정되어야 함', () => {
expect(listStr).toContain('qnaDeleteId');
});
it('삭제 시 qnaDeleteIsAnswered가 설정되어야 함', () => {
expect(listStr).toContain('qnaDeleteIsAnswered');
});
});
describe('수정 버튼 모달 방식 (Issue #208 개편)', () => {
it('수정 버튼이 qna_write_modal을 열어야 함', () => {
expect(listStr).toContain('qna_write_modal');
});
it('수정 버튼 클릭 시 qnaCreatedAt이 설정되어야 함', () => {
expect(listStr).toContain('qnaCreatedAt');
});
it('수정 버튼 클릭 시 qnaModalBoardSettings이 설정되어야 함', () => {
expect(listStr).toContain('qnaModalBoardSettings');
});
});
describe('카드 UI 구조 (Issue #208 개편)', () => {
it('개별 카드 레이아웃으로 rounded 클래스를 사용해야 함', () => {
expect(listStr).toContain('rounded');
});
it('수정/삭제 버튼이 펼침 조건(openedInquiryId)에 종속되지 않아야 함', () => {
// 버튼은 카드 헤더에 항상 노출, openedInquiryId는 상세 패널 토글에만 사용
// 버튼 자체의 if 조건에 openedInquiryId가 없어야 함
const parsed = JSON.parse(listStr);
const iterationDiv = parsed?.children
?.find((c: any) => c.comment?.includes('문의 목록'))
?.children?.find((c: any) => c.comment?.includes('카드 목록'))
?.children?.[0]; // iteration Div
const cardDiv = iterationDiv?.children?.[0]; // 개별 카드
const headerDiv = cardDiv?.children?.find((c: any) => c.comment?.includes('카드 헤더'));
const rightDiv = headerDiv?.children?.find((c: any) => c.comment?.includes('오른쪽'));
const editDeleteDiv = rightDiv?.children?.find((c: any) => c.comment?.includes('미답변'));
// 수정/삭제 버튼 영역 자체에 openedInquiryId 조건이 없어야 함
expect(editDeleteDiv?.if ?? '').not.toContain('openedInquiryId');
});
});
});
@@ -0,0 +1,407 @@
/**
* @file order-shipping.test.tsx
* @description 주문 상세 - 배송지 정보 및 배송지 변경 모달 렌더링 테스트
*
* 테스트 케이스 (8개)
* - 기본 렌더링: 배송지 정보 표시
* - 배송지 수정 버튼: payment_complete 상태에서 표시
* - 배송지 수정 버튼 숨김: shipping 상태에서 숨김
* - 배송 메모 표시: delivery_memo가 있을 때 표시
* - 배송 메모 숨김: delivery_memo가 없을 때 숨김
* - 변경 모달: 탭 전환 (저장/직접입력)
* - 변경 모달: confirm 속성 존재
* - 변경 모달: 저장된 배송지 목록 렌더링
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
createLayoutTest,
screen,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button
type={type as 'button' | 'submit' | 'reset'}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children || text}
</button>
);
const TestH3: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <h3 className={className} data-testid={testId}>{children || text}</h3>;
const TestIcon: React.FC<{ name?: string; className?: string; 'data-testid'?: string }> =
({ name, className, 'data-testid': testId }) => <i className={`icon-${name} ${className || ''}`} data-icon={name} data-testid={testId} />;
const TestInput: React.FC<{
type?: string;
name?: string;
value?: string;
placeholder?: string;
className?: string;
readOnly?: boolean;
'data-testid'?: string;
}> = ({ type, name, value, placeholder, className, 'data-testid': testId }) => (
<input type={type} name={name} value={value} placeholder={placeholder} className={className} data-testid={testId} readOnly />
);
const TestP: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <p className={className} data-testid={testId}>{children || text}</p>;
const TestLabel: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <label className={className} data-testid={testId}>{children || text}</label>;
const TestFragment: React.FC<{ children?: React.ReactNode }> =
({ children }) => <>{children}</>;
// ========== Fixture: 배송지 정보 섹션 ==========
const shippingInfoFixture = {
version: '1.0.0',
layout_name: 'mypage/orders/shipping',
data_sources: [
{
id: 'order',
endpoint: '/api/modules/sirsoft-ecommerce/user/orders/1',
method: 'GET',
},
],
components: [
{
type: 'basic',
name: 'Div',
props: { className: 'bg-white rounded-lg p-6', 'data-testid': 'shipping-section' },
children: [
{
comment: '섹션 제목 + 배송지 수정 버튼',
type: 'basic',
name: 'Div',
props: { className: 'flex items-center justify-between mb-4', 'data-testid': 'shipping-header' },
children: [
{
type: 'basic',
name: 'H3',
props: { 'data-testid': 'shipping-title' },
text: '배송지 정보',
},
{
comment: '배송지 수정 버튼 - pending_payment / payment_complete에서만 표시',
type: 'basic',
name: 'Button',
if: "{{order.data.order_status === 'pending_payment' || order.data.order_status === 'payment_complete'}}",
props: { type: 'button', 'data-testid': 'change-address-btn' },
text: '배송지 수정',
},
],
},
{
comment: '받는 분',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'recipient-info' },
children: [
{
type: 'basic',
name: 'Span',
props: { 'data-testid': 'recipient-name' },
text: "{{order.data.shipping_address?.recipient_name ?? ''}}",
},
{
type: 'basic',
name: 'Span',
props: { 'data-testid': 'recipient-phone' },
text: "{{order.data.shipping_address?.recipient_phone ?? ''}}",
},
],
},
{
comment: '주소',
type: 'basic',
name: 'Span',
props: { 'data-testid': 'full-address' },
text: "{{order.data.shipping_address?.full_address ?? ''}}",
},
{
comment: '배송 메모',
type: 'basic',
name: 'Div',
if: '{{order.data.shipping_address?.delivery_memo}}',
props: { 'data-testid': 'delivery-memo' },
children: [
{
type: 'basic',
name: 'Span',
text: "{{order.data.shipping_address?.delivery_memo ?? ''}}",
},
],
},
],
},
],
};
// ========== Fixture: 변경 모달 JSON 구조 검증용 ==========
const changeAddressModalFixture = {
actions: [
{
comment: '저장된 배송지 선택 모드',
type: 'click',
if: "{{(_local.changeAddressMode ?? 'saved') === 'saved' && _local.selectedAddressId}}",
confirm: '$t:mypage.order_detail.confirm_change_address',
handler: 'apiCall',
auth_required: true,
target: '/api/modules/sirsoft-ecommerce/user/orders/{{order.data.id}}/shipping-address',
params: {
method: 'PUT',
body: { address_id: '{{_local.selectedAddressId}}' },
},
},
{
comment: '직접 입력 모드',
type: 'click',
if: "{{(_local.changeAddressMode ?? 'saved') === 'manual'}}",
confirm: '$t:mypage.order_detail.confirm_change_address',
handler: 'apiCall',
auth_required: true,
target: '/api/modules/sirsoft-ecommerce/user/orders/{{order.data.id}}/shipping-address',
params: {
method: 'PUT',
body: '{{_local.manualAddress}}',
},
},
],
};
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ========== 테스트 ==========
describe('주문 상세 - 배송지 정보', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
testUtils?.cleanup();
vi.restoreAllMocks();
});
it('배송지 정보를 렌더링한다', async () => {
testUtils = createLayoutTest(shippingInfoFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('order', {
response: {
data: {
id: 1,
order_status: 'payment_complete',
shipping_address: {
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
full_address: '[12345] 서울시 강남구 테헤란로 101동 201호',
delivery_memo: null,
},
shippings: [],
},
},
});
await testUtils.render();
expect(screen.getByTestId('shipping-section')).toBeInTheDocument();
expect(screen.getByTestId('shipping-title')).toBeInTheDocument();
expect(screen.getByTestId('recipient-name')).toBeInTheDocument();
expect(screen.getByTestId('recipient-phone')).toBeInTheDocument();
});
it('payment_complete 상태에서 배송지 수정 버튼이 표시된다', async () => {
testUtils = createLayoutTest(shippingInfoFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('order', {
response: {
data: {
id: 1,
order_status: 'payment_complete',
shipping_address: {
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
full_address: '[12345] 서울시 강남구',
},
shippings: [],
},
},
});
await testUtils.render();
expect(screen.getByTestId('change-address-btn')).toBeInTheDocument();
});
it('shipping 상태에서 배송지 수정 버튼이 숨겨진다', async () => {
testUtils = createLayoutTest(shippingInfoFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('order', {
response: {
data: {
id: 1,
order_status: 'shipping',
shipping_address: {
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
full_address: '[12345] 서울시 강남구',
},
shippings: [],
},
},
});
await testUtils.render();
expect(screen.queryByTestId('change-address-btn')).not.toBeInTheDocument();
});
it('배송 메모가 있을 때 표시된다', async () => {
testUtils = createLayoutTest(shippingInfoFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('order', {
response: {
data: {
id: 1,
order_status: 'payment_complete',
shipping_address: {
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
full_address: '[12345] 서울시 강남구',
delivery_memo: '부재 시 경비실에 맡겨주세요',
},
shippings: [],
},
},
});
await testUtils.render();
expect(screen.getByTestId('delivery-memo')).toBeInTheDocument();
});
it('배송 메모가 없으면 숨겨진다', async () => {
testUtils = createLayoutTest(shippingInfoFixture, {
componentRegistry: registry,
auth: { isAuthenticated: true, user: { id: 1, name: 'Test User' } },
});
testUtils.mockApi('order', {
response: {
data: {
id: 1,
order_status: 'payment_complete',
shipping_address: {
recipient_name: '홍길동',
recipient_phone: '010-1234-5678',
full_address: '[12345] 서울시 강남구',
delivery_memo: null,
},
shippings: [],
},
},
});
await testUtils.render();
expect(screen.queryByTestId('delivery-memo')).not.toBeInTheDocument();
});
});
describe('주문 배송지 변경 모달 구조 검증', () => {
it('저장된 배송지 모드 apiCall에 confirm 속성이 있다', () => {
const savedAction = changeAddressModalFixture.actions[0];
expect(savedAction.confirm).toBe('$t:mypage.order_detail.confirm_change_address');
expect(savedAction.handler).toBe('apiCall');
expect(savedAction.params.method).toBe('PUT');
});
it('직접 입력 모드 apiCall에 confirm 속성이 있다', () => {
const manualAction = changeAddressModalFixture.actions[1];
expect(manualAction.confirm).toBe('$t:mypage.order_detail.confirm_change_address');
expect(manualAction.handler).toBe('apiCall');
expect(manualAction.params.method).toBe('PUT');
});
it('배송지 수정 버튼 조건에 pending_payment과 payment_complete만 포함한다', () => {
const ifCondition = shippingInfoFixture.components[0].children[0].children[1].if;
expect(ifCondition).toContain('pending_payment');
expect(ifCondition).toContain('payment_complete');
expect(ifCondition).not.toContain('preparing');
expect(ifCondition).not.toContain('shipping_ready');
expect(ifCondition).not.toContain('shipping_hold');
expect(ifCondition).not.toContain('pending_order');
});
});
@@ -0,0 +1,469 @@
/**
* @file order_complete.test.tsx
* @description 주문 완료 페이지 레이아웃 렌더링 테스트
*
* 테스트 케이스:
* - 기본 렌더링: 주문 완료 메시지 표시
* - 무통장입금 안내: 입금 계좌 정보 표시
* - 가상계좌 안내: 가상계좌 정보 표시
* - 카드 결제 완료: 결제 완료 메시지 표시
* - 배송지 저장 버튼: 로그인 사용자에게만 표시
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
createLayoutTest,
screen,
waitFor,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button
type={type as 'button' | 'submit' | 'reset'}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children || text}
</button>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<h1 className={className} data-testid={testId}>{children || text}</h1>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<p className={className} data-testid={testId}>{children || text}</p>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
'data-testid'?: string;
}> = ({ name, className, 'data-testid': testId }) => (
<i className={className} data-testid={testId} data-icon={name} />
);
const TestImg: React.FC<{
src?: string;
alt?: string;
className?: string;
'data-testid'?: string;
}> = ({ src, alt, className, 'data-testid': testId }) => (
<img src={src} alt={alt} className={className} data-testid={testId} />
);
// ========== 테스트 데이터 ==========
const mockOrderDataCard = {
data: {
id: 1,
order_number: 'ORD-20260205-001',
status: 'confirmed',
total_amount: 33000,
total_amount_formatted: '33,000원',
subtotal_formatted: '30,000원',
total_shipping_fee_formatted: '3,000원',
total_discount: 0,
payment: {
payment_method: 'card',
status: 'completed',
},
shipping_address: {
recipient_name: '김철수',
recipient_phone: '010-1234-5678',
country_code: 'KR',
zipcode: '12345',
address1: '서울시 강남구 테헤란로 123',
address2: '101동 1001호',
},
options: [
{
id: 1,
product_name: '테스트 상품',
option_name: '기본 옵션',
quantity: 2,
unit_price_formatted: '15,000원',
subtotal_formatted: '30,000원',
product_image: '/images/placeholder.png',
},
],
},
};
const mockOrderDataDbank = {
data: {
...mockOrderDataCard.data,
payment: {
payment_method: 'dbank',
status: 'pending',
dbank_name: '국민은행',
dbank_account: '123-456-789012',
dbank_holder: '주식회사 테스트',
deposit_due_at: '2026-02-07 23:59:59',
},
},
};
const mockOrderDataVbank = {
data: {
...mockOrderDataCard.data,
payment: {
payment_method: 'vbank',
status: 'pending',
vbank_name: '신한은행',
vbank_number: '110-123-456789',
vbank_holder: '홍길동',
vbank_due_at: '2026-02-07 23:59:59',
},
},
};
// ========== 테스트 스위트 ==========
describe('주문 완료 페이지 레이아웃', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(() => {
// 컴포넌트 레지스트리 초기화
ComponentRegistry.clear();
ComponentRegistry.register('basic', 'Div', TestDiv);
ComponentRegistry.register('basic', 'Span', TestSpan);
ComponentRegistry.register('basic', 'Button', TestButton);
ComponentRegistry.register('basic', 'H1', TestH1);
ComponentRegistry.register('basic', 'H3', TestH1);
ComponentRegistry.register('basic', 'P', TestP);
ComponentRegistry.register('basic', 'Icon', TestIcon);
ComponentRegistry.register('basic', 'Img', TestImg);
ComponentRegistry.register('layout', 'Container', TestDiv);
});
afterEach(() => {
if (testUtils) {
testUtils.cleanup();
}
vi.clearAllMocks();
});
describe('카드 결제 완료', () => {
it('카드 결제 완료 메시지가 표시되어야 함', async () => {
const orderCompleteLayout = {
version: '1.0.0',
layout_name: 'test/order_complete',
data_sources: [
{
id: 'orderData',
type: 'api',
endpoint: '/api/test/order',
method: 'GET',
auto_fetch: true,
},
],
children: [
{
type: 'basic',
name: 'Div',
'data-testid': 'card-complete',
if: "{{orderData?.data?.payment?.payment_method === 'card'}}",
children: [
{
type: 'basic',
name: 'H1',
'data-testid': 'card-title',
text: '결제가 완료되었습니다',
},
],
},
],
};
testUtils = createLayoutTest(orderCompleteLayout);
testUtils.mockApi('orderData', { response: mockOrderDataCard });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('card-complete')).toBeInTheDocument();
expect(screen.getByTestId('card-title')).toHaveTextContent('결제가 완료되었습니다');
});
});
});
describe('무통장입금 안내', () => {
it('무통장입금 안내가 표시되어야 함', async () => {
const dbankLayout = {
version: '1.0.0',
layout_name: 'test/order_complete_dbank',
data_sources: [
{
id: 'orderData',
type: 'api',
endpoint: '/api/test/order',
method: 'GET',
auto_fetch: true,
},
],
children: [
{
type: 'basic',
name: 'Div',
'data-testid': 'dbank-info',
if: "{{orderData?.data?.payment?.payment_method === 'dbank'}}",
children: [
{
type: 'basic',
name: 'Span',
'data-testid': 'dbank-name',
text: '{{orderData?.data?.payment?.dbank_name}}',
},
{
type: 'basic',
name: 'Span',
'data-testid': 'dbank-account',
text: '{{orderData?.data?.payment?.dbank_account}}',
},
],
},
],
};
testUtils = createLayoutTest(dbankLayout);
testUtils.mockApi('orderData', { response: mockOrderDataDbank });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('dbank-info')).toBeInTheDocument();
expect(screen.getByTestId('dbank-name')).toHaveTextContent('국민은행');
expect(screen.getByTestId('dbank-account')).toHaveTextContent('123-456-789012');
});
});
});
describe('가상계좌 안내', () => {
it('가상계좌 정보가 표시되어야 함', async () => {
const vbankLayout = {
version: '1.0.0',
layout_name: 'test/order_complete_vbank',
data_sources: [
{
id: 'orderData',
type: 'api',
endpoint: '/api/test/order',
method: 'GET',
auto_fetch: true,
},
],
children: [
{
type: 'basic',
name: 'Div',
'data-testid': 'vbank-info',
if: "{{orderData?.data?.payment?.payment_method === 'vbank'}}",
children: [
{
type: 'basic',
name: 'Span',
'data-testid': 'vbank-name',
text: '{{orderData?.data?.payment?.vbank_name}}',
},
{
type: 'basic',
name: 'Span',
'data-testid': 'vbank-number',
text: '{{orderData?.data?.payment?.vbank_number}}',
},
],
},
],
};
testUtils = createLayoutTest(vbankLayout);
testUtils.mockApi('orderData', { response: mockOrderDataVbank });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('vbank-info')).toBeInTheDocument();
expect(screen.getByTestId('vbank-name')).toHaveTextContent('신한은행');
expect(screen.getByTestId('vbank-number')).toHaveTextContent('110-123-456789');
});
});
});
describe('배송지 저장 버튼', () => {
it('로그인 사용자에게 배송지 저장 버튼이 표시되어야 함', async () => {
const saveAddressLayout = {
version: '1.0.0',
layout_name: 'test/order_complete_save_address',
state: {
_global: {
auth: {
isLoggedIn: true,
},
},
},
data_sources: [
{
id: 'orderData',
type: 'api',
endpoint: '/api/test/order',
method: 'GET',
auto_fetch: true,
},
],
children: [
{
type: 'basic',
name: 'Button',
'data-testid': 'save-address-btn',
if: '{{_global.auth?.isLoggedIn}}',
text: '이 배송지를 저장하기',
},
],
};
testUtils = createLayoutTest(saveAddressLayout);
testUtils.mockApi('orderData', { response: mockOrderDataCard });
testUtils.setGlobalState('auth', { isLoggedIn: true });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('save-address-btn')).toBeInTheDocument();
expect(screen.getByTestId('save-address-btn')).toHaveTextContent('이 배송지를 저장하기');
});
});
it('비로그인 사용자에게 배송지 저장 버튼이 숨겨져야 함', async () => {
const saveAddressLayout = {
version: '1.0.0',
layout_name: 'test/order_complete_guest',
state: {
_global: {
auth: {
isLoggedIn: false,
},
},
},
data_sources: [
{
id: 'orderData',
type: 'api',
endpoint: '/api/test/order',
method: 'GET',
auto_fetch: true,
},
],
children: [
{
type: 'basic',
name: 'Button',
'data-testid': 'save-address-btn',
if: '{{_global.auth?.isLoggedIn}}',
text: '이 배송지를 저장하기',
},
],
};
testUtils = createLayoutTest(saveAddressLayout);
testUtils.mockApi('orderData', { response: mockOrderDataCard });
testUtils.setGlobalState('auth', { isLoggedIn: false });
await testUtils.render();
// 버튼이 렌더링되지 않아야 함
expect(screen.queryByTestId('save-address-btn')).not.toBeInTheDocument();
});
});
describe('주문 상품 목록', () => {
it('주문 상품이 표시되어야 함', async () => {
const orderItemsLayout = {
version: '1.0.0',
layout_name: 'test/order_items',
data_sources: [
{
id: 'orderData',
type: 'api',
endpoint: '/api/test/order',
method: 'GET',
auto_fetch: true,
},
],
children: [
{
type: 'basic',
name: 'Div',
'data-testid': 'order-items',
children: [
{
type: 'basic',
name: 'Div',
iteration: {
source: '{{orderData?.data?.options ?? []}}',
item_var: 'item',
index_var: 'idx',
},
children: [
{
type: 'basic',
name: 'P',
'data-testid': 'product-name',
text: '{{item.product_name}}',
},
],
},
],
},
],
};
testUtils = createLayoutTest(orderItemsLayout);
testUtils.mockApi('orderData', { response: mockOrderDataCard });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('order-items')).toBeInTheDocument();
expect(screen.getByTestId('product-name')).toHaveTextContent('테스트 상품');
});
});
});
});
@@ -0,0 +1,392 @@
/**
* @file page-show.test.tsx
* @description 페이지 상세 레이아웃 렌더링 테스트 (Issue #99)
*
* 테스트 케이스:
* - 기본 렌더링: 페이지 데이터 있을 때 제목/본문/첨부파일 영역 확인
* - 조건부 렌더링: 데이터 없을 때 not_found 영역 표시, 데이터 있을 때 back_button 표시
* - 첨부파일: 없을 때 섹션 미표시, 있을 때 섹션 표시
* - 상태 배지: draft/archived 상태에 따른 배지 조건부 렌더링
* - 관리자 편집 버튼: 관리자만 표시
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import {
createLayoutTest,
screen,
waitFor,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{ className?: string; children?: React.ReactNode; 'data-testid'?: string }> =
({ className, children, 'data-testid': testId }) => <div className={className} data-testid={testId}>{children}</div>;
const TestSpan: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <span className={className} data-testid={testId}>{children ?? text}</span>;
const TestH1: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <h1 className={className} data-testid={testId}>{children ?? text}</h1>;
const TestH2: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <h2 className={className} data-testid={testId}>{children ?? text}</h2>;
const TestP: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <p className={className} data-testid={testId}>{children ?? text}</p>;
const TestA: React.FC<{ href?: string; className?: string; children?: React.ReactNode; 'data-testid'?: string }> =
({ href, className, children, 'data-testid': testId }) => <a href={href} className={className} data-testid={testId}>{children}</a>;
const TestButton: React.FC<{ type?: string; className?: string; children?: React.ReactNode; text?: string; onClick?: () => void; 'data-testid'?: string }> =
({ type, className, children, text, onClick, 'data-testid': testId }) => (
<button type={type as 'button' | 'submit'} className={className} onClick={onClick} data-testid={testId}>{children ?? text}</button>
);
const TestIcon: React.FC<{ name?: string; className?: string; 'data-testid'?: string }> =
({ name, 'data-testid': testId }) => <i data-testid={testId} data-icon={name} />;
const TestHtmlContent: React.FC<{ content?: string; className?: string; isHtml?: boolean; 'data-testid'?: string }> =
({ content, 'data-testid': testId }) => <div data-testid={testId} dangerouslySetInnerHTML={{ __html: content ?? '' }} />;
const TestContainer: React.FC<{ className?: string; children?: React.ReactNode }> =
({ className, children }) => <div className={className}>{children}</div>;
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
// ========== 레이아웃 Fixture ==========
/**
* page/show.json의 핵심 구조 (data_sources 포함)
*/
const pageShowFixture = {
version: '1.0.0',
layout_name: 'page/show',
state: {},
data_sources: [
{
id: 'page',
type: 'api',
endpoint: '/api/pages/terms',
method: 'GET',
auto_fetch: true,
auth_mode: 'optional',
loading_strategy: 'blocking',
fallback: { data: null },
},
],
components: [
{
id: 'page_content_card',
type: 'basic',
name: 'Div',
if: '{{page?.data}}',
props: { 'data-testid': 'page-content-card' },
children: [
{
type: 'basic',
name: 'H1',
props: { 'data-testid': 'page-title' },
text: '{{page?.data?.title ?? ""}}',
},
{
type: 'basic',
name: 'Span',
if: '{{page?.data?.status === "draft"}}',
props: { 'data-testid': 'badge-draft' },
text: 'status_draft',
},
{
type: 'basic',
name: 'Span',
if: '{{page?.data?.status === "archived"}}',
props: { 'data-testid': 'badge-archived' },
text: 'status_archived',
},
{
id: 'page_admin_edit_button',
type: 'basic',
name: 'A',
if: '{{_global.currentUser?.is_admin}}',
props: { 'data-testid': 'admin-edit-btn', href: '/admin/pages/{{page?.data?.id}}/edit' },
children: [{ type: 'basic', name: 'Span', text: 'admin_edit' }],
},
{
type: 'composite',
name: 'HtmlContent',
props: {
'data-testid': 'page-html-content',
content: '{{page?.data?.content ?? ""}}',
},
},
{
id: 'page_attachments_section',
type: 'basic',
name: 'Div',
if: '{{(page?.data?.attachments ?? []).length > 0}}',
props: { 'data-testid': 'attachments-section' },
children: [
{
type: 'basic',
name: 'Span',
text: 'attachments',
},
],
},
],
},
{
id: 'page_not_found',
type: 'basic',
name: 'Div',
if: '{{!page?.data && !page?.loading}}',
props: { 'data-testid': 'page-not-found' },
children: [
{ type: 'basic', name: 'H2', text: 'not_found_title', props: { 'data-testid': 'not-found-title' } },
],
},
{
id: 'page_back_button',
type: 'basic',
name: 'Div',
if: '{{page?.data}}',
props: { 'data-testid': 'back-button-area' },
children: [
{
type: 'basic',
name: 'Button',
props: { type: 'button', 'data-testid': 'back-button' },
children: [{ type: 'basic', name: 'Span', text: 'back_to_home' }],
},
],
},
],
};
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
H2: { component: TestH2, metadata: { name: 'H2', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
A: { component: TestA, metadata: { name: 'A', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
HtmlContent: { component: TestHtmlContent, metadata: { name: 'HtmlContent', type: 'composite' } },
Container: { component: TestContainer, metadata: { name: 'Container', type: 'layout' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ========== 헬퍼 ==========
/**
* mockApi URL 추출 규칙:
* endpoint "/api/pages/terms" → parts[2] = "terms" → dataSourceId = "terms"
* createMockResponse(response)가 { success: true, data: response } 로 래핑됨
* 언래핑 후 page = response 이므로,
* 레이아웃에서 page?.data?.title 접근하려면 response = { data: { id, title, ... } } 형태로 설정
*/
function makePageApiResponse(overrides: Record<string, unknown> = {}) {
return {
response: {
data: {
id: 1,
title: '이용약관',
content: '<p>내용</p>',
status: 'active',
attachments: [],
version: 1,
...overrides,
},
},
};
}
// ========== 테스트 케이스 ==========
describe('page/show.json 레이아웃 렌더링 (Issue #99)', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('기본 렌더링 - 페이지 데이터 있음', () => {
it('페이지 데이터가 있으면 콘텐츠 카드가 렌더링된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse());
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('page-content-card')).toBeInTheDocument();
});
expect(screen.queryByTestId('page-not-found')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('페이지 제목이 렌더링된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse({ title: '이용약관' }));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('page-title')).toHaveTextContent('이용약관');
});
testUtils.cleanup();
});
it('홈으로 돌아가기 버튼이 렌더링된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse());
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('back-button-area')).toBeInTheDocument();
});
testUtils.cleanup();
});
});
describe('조건부 렌더링 - 페이지 데이터 없음', () => {
it('페이지 데이터가 null이면 not_found가 표시된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', { response: { data: null } });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('page-not-found')).toBeInTheDocument();
});
expect(screen.queryByTestId('page-content-card')).not.toBeInTheDocument();
expect(screen.queryByTestId('back-button-area')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('상태 배지 조건부 렌더링', () => {
it('active 상태에서는 draft/archived 배지가 표시되지 않는다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse({ status: 'active' }));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('page-content-card')).toBeInTheDocument();
});
expect(screen.queryByTestId('badge-draft')).not.toBeInTheDocument();
expect(screen.queryByTestId('badge-archived')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('draft 상태에서는 draft 배지가 표시된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse({ status: 'draft' }));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('badge-draft')).toBeInTheDocument();
});
expect(screen.queryByTestId('badge-archived')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('archived 상태에서는 archived 배지가 표시된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse({ status: 'archived' }));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('badge-archived')).toBeInTheDocument();
});
expect(screen.queryByTestId('badge-draft')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('첨부파일 섹션', () => {
it('첨부파일이 없으면 첨부파일 섹션이 표시되지 않는다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse({ attachments: [] }));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('page-content-card')).toBeInTheDocument();
});
expect(screen.queryByTestId('attachments-section')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('첨부파일이 있으면 첨부파일 섹션이 표시된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, { componentRegistry: registry });
testUtils.mockApi('terms', makePageApiResponse({
attachments: [{ original_filename: 'test.pdf', download_url: '/download/1', is_image: false }],
}));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('attachments-section')).toBeInTheDocument();
});
testUtils.cleanup();
});
});
describe('관리자 편집 버튼', () => {
it('일반 사용자에게는 편집 버튼이 표시되지 않는다', async () => {
const testUtils = createLayoutTest(pageShowFixture, {
componentRegistry: registry,
initialState: { _global: { currentUser: { is_admin: false } } },
});
testUtils.mockApi('terms', makePageApiResponse());
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('page-content-card')).toBeInTheDocument();
});
expect(screen.queryByTestId('admin-edit-btn')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('관리자에게는 편집 버튼이 표시된다', async () => {
const testUtils = createLayoutTest(pageShowFixture, {
componentRegistry: registry,
initialState: { _global: { currentUser: { is_admin: true } } },
});
testUtils.mockApi('terms', makePageApiResponse({ id: 5 }));
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('admin-edit-btn')).toBeInTheDocument();
});
testUtils.cleanup();
});
});
});
@@ -0,0 +1,278 @@
/**
* @file profile-edit.test.tsx
* @description 프로필 편집/아바타 변경 후 헤더 프로필 갱신 테스트
*
* 테스트 케이스 (3개)
* - 기본 렌더링: 프로필 편집 폼 렌더링
* - API 연동: 프로필 수정 성공 시 user + current_user 데이터소스 리패치
* - AvatarUploader 액션: uploadSuccessActions/deleteSuccessActions props 동작
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
createLayoutTest,
screen,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button
type={type as 'button' | 'submit' | 'reset'}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children || text}
</button>
);
const TestH1: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <h1 className={className} data-testid={testId}>{children || text}</h1>;
const TestIcon: React.FC<{ name?: string; className?: string; size?: string; 'data-testid'?: string }> =
({ name, className, 'data-testid': testId }) => <i className={`icon-${name} ${className || ''}`} data-icon={name} data-testid={testId} />;
const TestFragment: React.FC<{ children?: React.ReactNode }> =
({ children }) => <>{children}</>;
const TestContainer: React.FC<{ children?: React.ReactNode; className?: string }> =
({ children, className }) => <div className={`container ${className || ''}`}>{children}</div>;
// ========== 테스트용 레이아웃 Fixture ==========
/**
* 프로필 편집 저장 시 user + current_user 리패치 검증용 fixture
*/
const profileEditLayoutFixture = {
version: '1.0.0',
layout_name: 'mypage/profile/edit',
state: {
isPasswordVerified: true,
isSavingProfile: false,
profileErrors: null,
profileEditForm: {
name: '테스트유저',
nickname: '닉네임',
email: 'test@example.com',
},
},
data_sources: [
{
id: 'user',
type: 'api',
endpoint: '/api/me',
method: 'GET',
auto_fetch: true,
},
{
id: 'current_user',
type: 'api',
endpoint: '/api/auth/user',
method: 'GET',
auto_fetch: true,
},
],
components: [
{
id: 'profile-edit-form',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'profile-edit-form' },
children: [
{
type: 'basic',
name: 'H1',
text: '프로필 편집',
props: { 'data-testid': 'page-title' },
},
{
id: 'save-profile-btn',
type: 'basic',
name: 'Button',
text: '저장',
props: { 'data-testid': 'save-profile-btn', type: 'button' },
actions: [
{
type: 'click',
handler: 'apiCall',
auth_required: true,
target: '/api/me',
params: {
method: 'PUT',
body: '{{_local?.profileEditForm}}',
},
onSuccess: [
{
handler: 'setState',
params: {
target: 'local',
isSavingProfile: false,
profileErrors: null,
},
},
{
handler: 'refetchDataSource',
params: { dataSourceId: 'user' },
},
{
handler: 'refetchDataSource',
params: { dataSourceId: 'current_user' },
},
{
handler: 'toast',
params: { type: 'success', message: '$t:mypage.profile.updated' },
},
{
handler: 'navigate',
params: { path: '/mypage/profile' },
},
],
onError: [
{
handler: 'setState',
params: {
target: 'local',
isSavingProfile: false,
profileErrors: '{{error.errors ?? null}}',
},
},
],
},
],
},
],
},
],
};
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
Container: { component: TestContainer, metadata: { name: 'Container', type: 'layout' } },
};
return registry;
}
// ========== 테스트 케이스 ==========
describe('프로필 편집 페이지 레이아웃 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('기본 렌더링 테스트', () => {
it('프로필 편집 폼이 렌더링된다', async () => {
const testUtils = createLayoutTest(profileEditLayoutFixture, {
componentRegistry: registry,
});
testUtils.mockApi('user', {
response: { data: { name: '테스트유저', nickname: '닉네임', email: 'test@example.com' } },
});
testUtils.mockApi('current_user', {
response: { data: { name: '테스트유저', avatar: null } },
});
await testUtils.render();
expect(screen.getByTestId('profile-edit-form')).toBeInTheDocument();
expect(screen.getByTestId('save-profile-btn')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('API 연동 테스트', () => {
it('프로필 수정 onSuccess에 current_user 리패치가 포함되어 있다', () => {
// _edit.json의 onSuccess 배열에 current_user 리패치가 존재하는지 구조 검증
const saveAction = profileEditLayoutFixture.components[0].children![1].actions![0];
const onSuccessHandlers = saveAction.onSuccess as Array<{ handler: string; params?: Record<string, any> }>;
const refetchHandlers = onSuccessHandlers.filter(h => h.handler === 'refetchDataSource');
const dataSourceIds = refetchHandlers.map(h => h.params?.dataSourceId);
expect(dataSourceIds).toContain('user');
expect(dataSourceIds).toContain('current_user');
});
it('프로필 수정 성공 시 상태가 초기화된다', async () => {
const testUtils = createLayoutTest(profileEditLayoutFixture, {
componentRegistry: registry,
initialState: {
_local: {
isPasswordVerified: true,
isSavingProfile: true,
profileErrors: { name: ['에러'] },
profileEditForm: { name: '수정됨', nickname: '닉', email: 'a@b.com' },
},
},
});
testUtils.mockApi('user', { response: { data: { name: '테스트유저' } } });
testUtils.mockApi('current_user', { response: { data: { name: '테스트유저' } } });
await testUtils.render();
await testUtils.triggerAction({
handler: 'apiCall',
target: '/api/me',
params: { method: 'PUT', body: { name: '수정됨' } },
onSuccess: profileEditLayoutFixture.components[0].children![1].actions![0].onSuccess,
onError: profileEditLayoutFixture.components[0].children![1].actions![0].onError,
});
const state = testUtils.getState();
expect(state._local.isSavingProfile).toBe(false);
expect(state._local.profileErrors).toBeNull();
testUtils.cleanup();
});
});
});
@@ -0,0 +1,339 @@
/**
* @file search-pages-section.test.tsx
* @description 통합검색 pages 섹션 Partial 렌더링 테스트 (Issue #99)
*
* 테스트 케이스:
* - 기본 렌더링: all 탭에서 섹션 헤더 표시
* - 검색 결과: 아이템이 있을 때 목록 렌더링
* - 빈 상태: 아이템 없을 때 안내 메시지 표시
* - 전체보기 버튼: pages_count > 0 일 때만 표시
* - 탭 전환: pages 탭에서는 헤더 미표시
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import {
createLayoutTest,
screen,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{ className?: string; children?: React.ReactNode; 'data-testid'?: string }> =
({ className, children, 'data-testid': testId }) => <div className={className} data-testid={testId}>{children}</div>;
const TestSpan: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <span className={className} data-testid={testId}>{children ?? text}</span>;
const TestP: React.FC<{ className?: string; children?: React.ReactNode; text?: string; 'data-testid'?: string }> =
({ className, children, text, 'data-testid': testId }) => <p className={className} data-testid={testId}>{children ?? text}</p>;
const TestButton: React.FC<{ className?: string; children?: React.ReactNode; text?: string; onClick?: () => void; 'data-testid'?: string }> =
({ className, children, text, onClick, 'data-testid': testId }) => (
<button className={className} onClick={onClick} data-testid={testId}>{children ?? text}</button>
);
const TestIcon: React.FC<{ name?: string; size?: string; className?: string }> =
({ name }) => <i data-icon={name} />;
const TestHtmlContent: React.FC<{ content?: string; className?: string; 'data-testid'?: string }> =
({ content, 'data-testid': testId }) => <div data-testid={testId} dangerouslySetInnerHTML={{ __html: content ?? '' }} />;
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
// ========== 레이아웃 Fixture ==========
/**
* pages/_section.json 핵심 구조 (Partial이므로 단일 루트 Div)
*/
const pagesSectionFixture = {
version: '1.0.0',
layout_name: 'partials/search/pages/_section',
state: {},
components: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'pages-section-root' },
children: [
{
// 섹션 헤더 (all 탭에서만)
type: 'basic',
name: 'Div',
if: '{{(_global.searchActiveTab ?? "all") === "all"}}',
props: { 'data-testid': 'section-header' },
children: [
{ type: 'basic', name: 'Icon', props: { name: 'file-alt' } },
{ type: 'basic', name: 'Span', props: { 'data-testid': 'pages-tab-label' }, text: 'search.tabs.pages' },
{ type: 'basic', name: 'Span', props: { 'data-testid': 'pages-count' }, text: '{{searchResults?.data?.pages_count ?? 0}}' },
{
type: 'basic',
name: 'Button',
if: '{{(searchResults?.data?.pages_count ?? 0) > 0}}',
props: { 'data-testid': 'view-all-btn' },
children: [
{ type: 'basic', name: 'Span', text: 'search.view_all' },
],
actions: [
{
type: 'click',
handler: 'sequence',
actions: [
{ handler: 'setState', params: { target: 'global', searchActiveTab: 'pages', searchPage: 1 } },
{ handler: 'refetchDataSource', params: { dataSourceId: 'searchResults' } },
],
},
],
},
],
},
{
// 페이지 목록
type: 'basic',
name: 'Div',
if: '{{searchResults?.data?.pages?.items?.length > 0}}',
iteration: {
source: '{{searchResults?.data?.pages?.items ?? []}}',
item_var: 'page',
index_var: 'pageIdx',
},
children: [
{
type: 'basic',
name: 'Button',
props: { 'data-testid': 'page-item-btn' },
actions: [{ type: 'click', handler: 'navigate', params: { path: '{{page.url}}' } }],
children: [
{
type: 'composite',
name: 'HtmlContent',
props: { 'data-testid': 'page-item-title', content: '{{page.title_highlighted ?? page.title}}' },
},
{
type: 'composite',
name: 'HtmlContent',
props: { 'data-testid': 'page-item-preview', content: '{{page.content_preview_highlighted ?? page.content_preview}}' },
},
{
type: 'basic',
name: 'P',
props: { 'data-testid': 'page-item-date' },
text: 'search.page_published_at|date={{page.published_at ?? ""}}',
},
],
},
],
},
{
// 결과 없음
type: 'basic',
name: 'Div',
if: '{{!searchResults?.data?.pages?.items || searchResults?.data?.pages?.items?.length === 0}}',
props: { 'data-testid': 'pages-empty' },
children: [
{ type: 'basic', name: 'Span', text: 'search.empty.pages_in_all' },
],
},
],
},
],
};
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
HtmlContent: { component: TestHtmlContent, metadata: { name: 'HtmlContent', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ========== 헬퍼 ==========
function makeFakePageItem(overrides: Partial<{
title: string;
title_highlighted: string;
content_preview: string;
content_preview_highlighted: string;
published_at: string;
url: string;
}> = {}) {
return {
id: 1,
slug: 'terms',
title: '이용약관',
title_highlighted: '<mark>이용</mark>약관',
content_preview: '본 약관은...',
content_preview_highlighted: '본 <mark>약관</mark>은...',
published_at: '2026-02-01',
url: '/page/terms',
...overrides,
};
}
// ========== 테스트 케이스 ==========
describe('partials/search/pages/_section.json 렌더링 (Issue #99)', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('섹션 헤더 (all 탭)', () => {
it('all 탭에서 섹션 헤더가 표시된다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
initialData: { searchResults: { data: { pages_count: 0, pages: { items: [] } } } },
});
await testUtils.render();
expect(screen.getByTestId('section-header')).toBeInTheDocument();
testUtils.cleanup();
});
it('pages 탭에서는 섹션 헤더가 표시되지 않는다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'pages' } },
initialData: { searchResults: { data: { pages_count: 3, pages: { items: [makeFakePageItem()] } } } },
});
await testUtils.render();
expect(screen.queryByTestId('section-header')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('searchActiveTab 미설정 시 all 탭으로 간주하여 헤더가 표시된다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: {} },
initialData: { searchResults: { data: { pages_count: 0, pages: { items: [] } } } },
});
await testUtils.render();
expect(screen.getByTestId('section-header')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('전체보기 버튼', () => {
it('pages_count가 0이면 전체보기 버튼이 표시되지 않는다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
initialData: { searchResults: { data: { pages_count: 0, pages: { items: [] } } } },
});
await testUtils.render();
expect(screen.queryByTestId('view-all-btn')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('pages_count가 1 이상이면 전체보기 버튼이 표시된다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
initialData: { searchResults: { data: { pages_count: 3, pages: { items: [makeFakePageItem()] } } } },
});
await testUtils.render();
expect(screen.getByTestId('view-all-btn')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('검색 결과 목록', () => {
it('아이템이 있으면 페이지 목록이 렌더링된다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
initialData: {
searchResults: {
data: {
pages_count: 1,
pages: { items: [makeFakePageItem()] },
},
},
},
});
await testUtils.render();
expect(screen.getByTestId('page-item-btn')).toBeInTheDocument();
expect(screen.queryByTestId('pages-empty')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('아이템이 없으면 빈 상태 안내가 표시된다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
initialData: { searchResults: { data: { pages_count: 0, pages: { items: [] } } } },
});
await testUtils.render();
expect(screen.queryByTestId('page-item-btn')).not.toBeInTheDocument();
expect(screen.getByTestId('pages-empty')).toBeInTheDocument();
testUtils.cleanup();
});
it('아이템의 url이 /page/{slug} 형식으로 바인딩된다', async () => {
const item = makeFakePageItem({ url: '/page/terms' });
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
initialData: { searchResults: { data: { pages_count: 1, pages: { items: [item] } } } },
});
await testUtils.render();
// navigate 핸들러가 /page/terms 경로를 사용하는지
// (page.url 바인딩이 올바르게 /page/ 형식인지 검증)
const btn = screen.getByTestId('page-item-btn');
expect(btn).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('빈 상태 (searchResults 미정의)', () => {
it('searchResults 데이터가 없어도 에러 없이 렌더링된다', async () => {
const testUtils = createLayoutTest(pagesSectionFixture, {
componentRegistry: registry,
initialState: { _global: { searchActiveTab: 'all' } },
});
await testUtils.render();
expect(screen.getByTestId('pages-section-root')).toBeInTheDocument();
expect(screen.getByTestId('pages-empty')).toBeInTheDocument();
testUtils.cleanup();
});
});
});
@@ -0,0 +1,363 @@
/**
* @file shop-guest-access.test.tsx
* @description 비회원(Guest) 상품 조회 접근 테스트 (Issue #21)
*
* 테스트 케이스:
* - _user_base.json의 current_user 401이 하위 레이아웃으로 전파되지 않음
* - 비회원이 상품 상세 페이지에서 401 에러 페이지를 보지 않음
* - 비회원이 상품 목록 페이지에서 권한 없음 배너를 보지 않음
* - 상품 API 자체가 403을 반환하면 에러 UI가 정상 표시됨
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
createLayoutTest,
screen,
waitFor,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ========== 테스트용 컴포넌트 정의 ==========
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<h1 className={className} data-testid={testId}>{children || text}</h1>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<p className={className} data-testid={testId}>{children || text}</p>
);
const TestFragment: React.FC<{ children?: React.ReactNode }> =
({ children }) => <>{children}</>;
// ========== 컴포넌트 레지스트리 설정 ==========
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ========== 테스트용 레이아웃 Fixture ==========
/**
* 상품 목록 레이아웃 (shop/index 단순화)
*
* 핵심: current_user 401 시 productAccessDenied가 true가 되지 않아야 함
* - current_user 데이터소스: auth_required=true, 401시 errorHandling으로 전파 방지
* - 레이아웃 errorHandling.401: setState productAccessDenied=true
* - 비회원이면 current_user 401 → datasource-level에서 차단 → 레이아웃 401 미발동
*/
const shopIndexFixture = {
version: '1.0.0',
layout_name: 'shop/index',
errorHandling: {
'401': {
handler: 'setState',
params: {
target: 'local',
productAccessDenied: true,
},
},
'403': {
handler: 'setState',
params: {
target: 'local',
productAccessDenied: true,
},
},
},
data_sources: [
{
id: 'current_user',
type: 'api',
endpoint: '/api/auth/user',
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
initGlobal: 'currentUser',
fallback: { data: [] },
errorHandling: {
'401': {
comment: '비회원의 /api/auth/user 401은 정상 — fallback 사용, 레이아웃 에러 핸들링으로 전파 방지',
handler: 'suppress',
},
},
},
{
id: 'products',
type: 'api',
endpoint: '/api/modules/sirsoft-ecommerce/products',
method: 'GET',
auth_mode: 'optional',
auto_fetch: true,
loading_strategy: 'progressive',
fallback: {
data: [],
meta: { current_page: 1, last_page: 1, per_page: 12, total: 0 },
},
},
],
slots: {
content: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'shop-index-content' },
children: [
{
type: 'basic',
name: 'H1',
props: { 'data-testid': 'shop-title' },
text: '쇼핑몰',
},
{
comment: '상품 조회 권한 없음 안내 배너',
type: 'basic',
name: 'Div',
if: '{{_local.productAccessDenied === true}}',
props: {
className: 'mb-6 p-4 bg-yellow-50',
'data-testid': 'access-denied-banner',
},
children: [
{
type: 'basic',
name: 'Span',
text: '상품 조회 권한이 없습니다.',
},
],
},
{
comment: '상품 목록',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'product-list' },
children: [
{
type: 'basic',
name: 'Span',
text: '상품 목록 영역',
},
],
},
],
},
],
},
};
/**
* 상품 상세 레이아웃 (shop/show 단순화)
*
* 핵심: current_user 401 시 showErrorPage가 호출되지 않아야 함
* - 레이아웃 errorHandling.401: showErrorPage
* - 비회원이면 current_user 401 → datasource-level에서 차단 → showErrorPage 미발동
*/
const shopShowFixture = {
version: '1.0.0',
layout_name: 'shop/show',
errorHandling: {
'401': {
handler: 'showErrorPage',
params: {
errorCode: 401,
target: 'content',
},
},
},
data_sources: [
{
id: 'current_user',
type: 'api',
endpoint: '/api/auth/user',
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
initGlobal: 'currentUser',
fallback: { data: [] },
errorHandling: {
'401': {
comment: '비회원의 /api/auth/user 401은 정상 — fallback 사용, 레이아웃 에러 핸들링으로 전파 방지',
handler: 'suppress',
},
},
},
{
id: 'product',
type: 'api',
endpoint: '/api/modules/sirsoft-ecommerce/products/1',
method: 'GET',
auto_fetch: true,
auth_mode: 'optional',
loading_strategy: 'progressive',
fallback: { data: null },
},
],
slots: {
content: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'shop-show-content' },
children: [
{
type: 'basic',
name: 'H1',
props: { 'data-testid': 'product-name' },
text: '{{product?.data?.name ?? "상품 정보"}}',
},
{
type: 'basic',
name: 'P',
props: { 'data-testid': 'product-description' },
text: '{{product?.data?.description ?? ""}}',
},
],
},
],
},
};
// ========== 테스트 케이스 ==========
describe('비회원(Guest) 상품 조회 접근 (Issue #21)', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('상품 목록 페이지 (shop/index)', () => {
it('비회원일 때 current_user 401이 발생해도 권한 없음 배너가 표시되지 않는다', async () => {
// Given: current_user는 401, products는 200 (비회원이지만 상품 조회 권한 있음)
const testUtils = createLayoutTest(shopIndexFixture, {
componentRegistry: registry,
});
testUtils.mockApiError('current_user', 401, 'Unauthenticated');
testUtils.mockApi('products', {
response: {
data: [{ id: 1, name: '테스트 상품' }],
meta: { current_page: 1, last_page: 1, per_page: 12, total: 1 },
},
});
// When
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('shop-index-content')).toBeInTheDocument();
});
// Then: 권한 없음 배너가 표시되지 않아야 함
expect(screen.queryByTestId('access-denied-banner')).not.toBeInTheDocument();
// And: 상품 목록은 정상 표시
expect(screen.getByTestId('product-list')).toBeInTheDocument();
testUtils.cleanup();
});
it('비회원일 때 current_user 401이 발생해도 상품 목록이 정상 렌더링된다', async () => {
// Given: current_user는 401, products는 200
const testUtils = createLayoutTest(shopIndexFixture, {
componentRegistry: registry,
});
testUtils.mockApiError('current_user', 401, 'Unauthenticated');
testUtils.mockApi('products', {
response: {
data: [
{ id: 1, name: '상품 A' },
{ id: 2, name: '상품 B' },
],
meta: { current_page: 1, last_page: 1, per_page: 12, total: 2 },
},
});
// When
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('shop-index-content')).toBeInTheDocument();
});
// Then: 상품 목록이 정상 렌더링되고, 권한 없음 배너 미표시
expect(screen.getByTestId('product-list')).toBeInTheDocument();
expect(screen.getByTestId('shop-title')).toBeInTheDocument();
expect(screen.queryByTestId('access-denied-banner')).not.toBeInTheDocument();
testUtils.cleanup();
});
});
describe('상품 상세 페이지 (shop/show)', () => {
it('비회원일 때 current_user 401이 발생해도 상품 상세가 정상 렌더링된다', async () => {
// Given: current_user는 401, product는 200
const testUtils = createLayoutTest(shopShowFixture, {
componentRegistry: registry,
});
testUtils.mockApiError('current_user', 401, 'Unauthenticated');
testUtils.mockApi('product', {
response: {
data: { id: 1, name: '테스트 상품', description: '상품 설명' },
},
});
// When
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('shop-show-content')).toBeInTheDocument();
});
// Then: 상품 정보가 정상 렌더링
expect(screen.getByTestId('product-name')).toBeInTheDocument();
expect(screen.getByTestId('product-description')).toBeInTheDocument();
testUtils.cleanup();
});
});
});
File diff suppressed because it is too large. Load diff
@@ -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,26 @@
import React, { forwardRef } from 'react';
export interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
}
/**
* 기본 체크박스 컴포넌트
*
* forwardRef를 사용하여 ref 전달을 지원합니다.
* indeterminate 상태 등을 설정할 때 ref가 필요합니다.
*/
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
({ label, className = '', ...props }, ref) => {
return (
<input
ref={ref}
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,121 @@
import React, { forwardRef, useRef, useCallback, useState } from 'react';
import { Div } from './Div';
import { Span } from './Span';
import { Svg } from './Svg';
import { Input } from './Input';
import { Button } from './Button';
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 as any}
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,24 @@
import React from 'react';
export interface FooterProps extends React.HTMLAttributes<HTMLElement> {
ref?: React.Ref<HTMLElement>;
}
/**
* 기본 footer 컴포넌트
*/
export const Footer = React.forwardRef<HTMLElement, FooterProps>(({
children,
className = '',
...props
}, ref) => {
return (
<footer
ref={ref}
className={className}
{...props}
>
{children}
</footer>
);
});
@@ -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,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,24 @@
import React from 'react';
export interface HeaderProps extends React.HTMLAttributes<HTMLElement> {
ref?: React.Ref<HTMLElement>;
}
/**
* 기본 header 컴포넌트
*/
export const Header = React.forwardRef<HTMLElement, HeaderProps>(({
children,
className = '',
...props
}, ref) => {
return (
<header
ref={ref}
className={className}
{...props}
>
{children}
</header>
);
});
@@ -0,0 +1,21 @@
import React from 'react';
export interface HrProps extends React.HTMLAttributes<HTMLHRElement> {
ref?: React.Ref<HTMLHRElement>;
}
/**
* 기본 hr (수평선) 컴포넌트
*/
export const Hr = React.forwardRef<HTMLHRElement, HrProps>(({
className = '',
...props
}, ref) => {
return (
<hr
ref={ref}
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,147 @@
import React from 'react';
import { IconName, IconStyle, IconSize, iconNameMap } 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',
};
// 아이콘 이름 처리: iconNameMap을 사용하여 Lucide 스타일 이름을 FontAwesome으로 변환
const rawName = typeof name === 'string' ? name : String(name);
const mappedName = iconNameMap[rawName];
// 매핑된 이름이 있으면 사용, 없으면 원본 사용 후 'fa-' 접두사 제거
const iconName = mappedName
? String(mappedName).replace(/^fa-/, '')
: rawName.replace(/^fa-/, '');
// 클래스 조합
const classes = [
styleClassMap[iconStyle],
`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,361 @@
/**
* 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',
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',
// 알림 관련
BellSlash = 'fa-bell-slash',
// 문서/책 관련
BookOpen = 'fa-book-open',
// 건물/주소 관련
Building = 'fa-building',
// 파일 관련
FileCircleCheck = 'fa-file-circle-check',
// 마법 관련
WandMagicSparkles = 'fa-wand-magic-sparkles',
// 사용자 관련
UserXmark = 'fa-user-xmark',
// 확장 시스템 (모듈/플러그인)
Cube = 'fa-cube',
Cubes = 'fa-cubes',
Plug = 'fa-plug',
PuzzlePiece = 'fa-puzzle-piece',
// 추가 아이콘 (Lucide 호환)
Fire = 'fa-fire',
CommentDots = 'fa-comment-dots',
DollarSign = 'fa-dollar-sign',
Bars2 = 'fa-bars',
X = 'fa-times',
List = 'fa-list',
ThLarge = 'fa-th-large',
Inbox = 'fa-inbox',
Box = 'fa-box',
PaperPlane = 'fa-paper-plane',
FileText = 'fa-file-alt',
Paperclip = 'fa-paperclip',
Truck = 'fa-truck',
Sync = 'fa-sync',
RotateLeft = 'fa-rotate-left',
MapPin = 'fa-map-marker-alt',
HelpCircle = 'fa-question-circle',
}
/**
* 문자열 아이콘 이름을 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,
'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,
// Lucide 호환 아이콘 매핑
'flame': IconName.Fire,
'fire': IconName.Fire,
'message-square': IconName.CommentDots,
'dollar-sign': IconName.DollarSign,
'menu': IconName.Bars,
'x': IconName.X,
'list': IconName.List,
'layout-grid': IconName.ThLarge,
'th-large': IconName.ThLarge,
'grid': IconName.ThLarge,
'inbox': IconName.Inbox,
'package': IconName.Box,
'box': IconName.Box,
'send': IconName.PaperPlane,
'paper-plane': IconName.PaperPlane,
'file-text': IconName.FileText,
'paperclip': IconName.Paperclip,
'truck': IconName.Truck,
'refresh-cw': IconName.Sync,
'sync': IconName.Sync,
'undo-2': IconName.RotateLeft,
'rotate-left': IconName.RotateLeft,
'map-pin': IconName.MapPin,
'help-circle': IconName.HelpCircle,
// 추가 Lucide 호환 아이콘 매핑
'alert-triangle': IconName.ExclamationTriangle,
'bell-off': IconName.BellSlash,
'book-open': IconName.BookOpen,
'building': IconName.Building,
'edit-2': IconName.Edit,
'edit-3': IconName.Edit,
'file-check': IconName.FileCircleCheck,
'mail': IconName.Envelope,
'sparkles': IconName.WandMagicSparkles,
'trash-2': IconName.Trash,
'user-x': IconName.UserXmark,
};
@@ -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,154 @@
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에만 적용)
useEffect(() => {
if (!isCheckableType && !isComposingRef.current && value !== undefined) {
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,22 @@
import React, { forwardRef } from 'react';
export interface NavProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 nav 컴포넌트
*/
export const Nav = forwardRef<HTMLElement, NavProps>(
({ children, className = '', ...props }, ref) => {
return (
<nav
ref={ref}
className={className}
{...props}
>
{children}
</nav>
);
}
);
Nav.displayName = '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,418 @@
import React, { useState, useCallback, forwardRef, useImperativeHandle, useRef, useEffect, useMemo } from 'react';
import { Icon } from './Icon';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as unknown as { G7Core?: { t?: (key: string, params?: Record<string, string | number>) => string } })
.G7Core?.t?.(key, params) ?? key;
/**
* 비밀번호 검증 규칙 정의
*/
export interface PasswordRule {
/** 규칙 식별자 */
key: string;
/** 규칙 설명 (다국어 키) */
labelKey: string;
/** 검증 함수 (param은 규칙별 설정값) */
validate: (value: string, param?: number) => boolean;
/** 기본 파라미터 값 */
defaultParam?: number;
}
/**
* 사용 가능한 모든 비밀번호 검증 규칙
*
* JSON 레이아웃에서 enableRules prop으로 키를 지정하여 선택적으로 활성화
* 파라미터가 있는 규칙은 "규칙명:값" 형식으로 지정 (예: "minLength:12")
*/
export const availablePasswordRules: Record<string, PasswordRule> = {
minLength: {
key: 'minLength',
labelKey: 'auth.password_input.rules.minLength',
defaultParam: 6,
validate: (value: string, param = 6) => value.length >= param,
},
maxLength: {
key: 'maxLength',
labelKey: 'auth.password_input.rules.maxLength',
defaultParam: 20,
validate: (value: string, param = 20) => value.length <= param,
},
hasUppercase: {
key: 'hasUppercase',
labelKey: 'auth.password_input.rules.hasUppercase',
validate: (value: string) => /[A-Z]/.test(value),
},
hasLowercase: {
key: 'hasLowercase',
labelKey: 'auth.password_input.rules.hasLowercase',
validate: (value: string) => /[a-z]/.test(value),
},
hasNumber: {
key: 'hasNumber',
labelKey: 'auth.password_input.rules.hasNumber',
validate: (value: string) => /[0-9]/.test(value),
},
hasSpecial: {
key: 'hasSpecial',
labelKey: 'auth.password_input.rules.hasSpecial',
validate: (value: string) => /[!@#$%^&*(),.?":{}|<>]/.test(value),
},
noSpaces: {
key: 'noSpaces',
labelKey: 'auth.password_input.rules.noSpaces',
validate: (value: string) => !/\s/.test(value),
},
minTypes: {
key: 'minTypes',
labelKey: 'auth.password_input.rules.minTypes',
defaultParam: 3,
validate: (value: string, param = 3) => {
let types = 0;
if (/[A-Z]/.test(value)) types++;
if (/[a-z]/.test(value)) types++;
if (/[0-9]/.test(value)) types++;
if (/[!@#$%^&*(),.?":{}|<>]/.test(value)) types++;
return types >= param;
},
},
};
/**
* 기본 비밀번호 검증 규칙
*
* 백엔드 검증 규칙(RegisterRequest.php)과 동일:
* - password: required|string|min:6|confirmed
*/
export const defaultPasswordRules: PasswordRule[] = [
availablePasswordRules.minLength,
];
/**
* 파싱된 규칙 (규칙 + 파라미터)
*/
interface ParsedRule {
rule: PasswordRule;
param?: number;
}
/**
* enableRules 문자열을 파싱하여 규칙과 파라미터를 추출
* 예: "minLength:12" → { rule: minLengthRule, param: 12 }
* 예: "hasUppercase" → { rule: hasUppercaseRule, param: undefined }
*
* @param ruleString 규칙 문자열 (예: "minLength:12" 또는 "hasUppercase")
* @returns 파싱된 규칙 또는 null (규칙이 존재하지 않는 경우)
*/
function parseRuleString(ruleString: string): ParsedRule | null {
const [key, paramStr] = ruleString.split(':');
const rule = availablePasswordRules[key];
if (!rule) return null;
const param = paramStr ? parseInt(paramStr, 10) : rule.defaultParam;
return { rule, param: isNaN(param as number) ? rule.defaultParam : param };
}
/**
* PasswordInput에서 사용하지 않는 HTML 속성 목록
* (그누보드7 템플릿 엔진에서 전달되는 커스텀 속성)
*/
interface NonStandardProps {
loadingactions?: unknown;
formdata?: unknown;
}
export interface PasswordInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type'> {
/** 레이블 텍스트 */
label?: string;
/** 에러 메시지 */
error?: string;
/** 비밀번호 보기/숨기기 버튼 표시 */
showToggle?: boolean;
/** 비밀번호 조건 검증 표시 */
showValidation?: boolean;
/** 비밀번호 확인 모드 (확인 필드로 사용) */
isConfirmField?: boolean;
/** 비밀번호 확인 대상 값 (isConfirmField가 true일 때 필요) */
confirmTarget?: string;
/** 비밀번호 확인 일치 여부 콜백 */
onMatchChange?: (isMatch: boolean) => void;
/** 비밀번호 유효성 변경 콜백 */
onValidityChange?: (isValid: boolean, failedRules: string[]) => void;
/** 커스텀 비밀번호 규칙 (기본 규칙 대체, 코드에서만 사용) */
rules?: PasswordRule[];
/**
* 활성화할 규칙 키 목록 (JSON 레이아웃에서 사용)
* 사용 가능: minLength, maxLength, hasUppercase, hasLowercase, hasNumber, hasSpecial, noSpaces, minTypes
* 파라미터 지정: "규칙명:값" 형식 (예: "minLength:12", "minTypes:3")
* 예: ["minLength:12", "hasUppercase", "hasSpecial"]
*/
enableRules?: string[];
/** 표시할 규칙 키 목록 (지정하지 않으면 전체 표시) */
showRules?: string[];
/** 입력 필드 wrapper 클래스 */
wrapperClassName?: string;
/** 검증 결과 표시 영역 클래스 */
validationClassName?: string;
}
/**
* 비밀번호 입력 컴포넌트
*
* 비밀번호 보기/숨기기 토글, 실시간 조건 검증, 비밀번호 확인 기능을 제공합니다.
*
* @example
* // 기본 사용 (보기/숨기기만)
* <PasswordInput name="password" showToggle />
*
* @example
* // 조건 검증 표시
* <PasswordInput
* name="password"
* showToggle
* showValidation
* onValidityChange={(isValid, failed) => console.log(isValid, failed)}
* />
*
* @example
* // 비밀번호 확인 필드
* <PasswordInput
* name="password_confirmation"
* isConfirmField
* confirmTarget={password}
* onMatchChange={(isMatch) => console.log(isMatch)}
* />
*/
export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
(
{
label,
error,
showToggle = true,
showValidation = false,
isConfirmField = false,
confirmTarget,
onMatchChange,
onValidityChange,
rules,
enableRules,
showRules,
wrapperClassName = '',
validationClassName = '',
className = '',
onChange,
value,
defaultValue,
disabled,
...props
},
ref
) => {
const internalRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => internalRef.current as HTMLInputElement);
// 비밀번호 보기/숨기기 상태
const [showPassword, setShowPassword] = useState(false);
// CapsLock 활성화 상태
const [capsLockOn, setCapsLockOn] = useState(false);
// 내부 값 상태 (controlled/uncontrolled 지원)
const [internalValue, setInternalValue] = useState<string>(
(value as string) ?? (defaultValue as string) ?? ''
);
// 외부 value가 변경되면 동기화
useEffect(() => {
if (value !== undefined) {
setInternalValue(value as string);
}
}, [value]);
// 사용할 규칙 결정: rules > enableRules > defaultPasswordRules
const parsedRules = useMemo((): ParsedRule[] => {
// 1. rules prop이 있으면 그대로 사용 (코드에서 직접 전달, 기본 파라미터 적용)
if (rules && rules.length > 0) {
return rules.map((rule) => ({ rule, param: rule.defaultParam }));
}
// 2. enableRules가 있으면 파싱하여 규칙과 파라미터 추출
if (enableRules && enableRules.length > 0) {
return enableRules
.map((ruleStr) => parseRuleString(ruleStr))
.filter((parsed): parsed is ParsedRule => parsed !== null);
}
// 3. 기본 규칙 사용
return defaultPasswordRules.map((rule) => ({ rule, param: rule.defaultParam }));
}, [rules, enableRules]);
// 표시할 규칙 필터링
const displayRules = useMemo(() => {
if (!showRules || showRules.length === 0) return parsedRules;
return parsedRules.filter((parsed) => showRules.includes(parsed.rule.key));
}, [parsedRules, showRules]);
// 비밀번호 규칙 검증 결과
const validationResults = useMemo(() => {
if (!showValidation || isConfirmField) return {};
return displayRules.reduce((acc, { rule, param }) => {
acc[rule.key] = rule.validate(internalValue, param);
return acc;
}, {} as Record<string, boolean>);
}, [internalValue, displayRules, showValidation, isConfirmField]);
// 비밀번호 확인 일치 여부
const isMatch = useMemo(() => {
if (!isConfirmField || confirmTarget === undefined) return true;
return internalValue === confirmTarget && internalValue.length > 0;
}, [isConfirmField, internalValue, confirmTarget]);
// 전체 유효성 (모든 규칙 통과)
const isAllValid = useMemo(() => {
if (!showValidation) return true;
return Object.values(validationResults).every((v) => v);
}, [validationResults, showValidation]);
// 유효성 변경 콜백
useEffect(() => {
if (onValidityChange && showValidation && !isConfirmField) {
const failedRules = Object.entries(validationResults)
.filter(([, passed]) => !passed)
.map(([key]) => key);
onValidityChange(isAllValid, failedRules);
}
}, [isAllValid, validationResults, onValidityChange, showValidation, isConfirmField]);
// 비밀번호 확인 일치 콜백
useEffect(() => {
if (onMatchChange && isConfirmField) {
onMatchChange(isMatch);
}
}, [isMatch, onMatchChange, isConfirmField]);
// 비밀번호 보기/숨기기 토글
const handleToggle = useCallback(() => {
setShowPassword((prev) => !prev);
}, []);
// 입력값 변경 처리
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInternalValue(newValue);
if (onChange) {
onChange(e);
}
},
[onChange]
);
// CapsLock 상태 감지
const handleKeyEvent = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
setCapsLockOn(e.getModifierState('CapsLock'));
},
[]
);
// HTML 표준 속성이 아닌 것들을 필터링 (타입 안전성 개선)
const { loadingactions, formdata, ...validProps } = props as typeof props & NonStandardProps;
return (
<div className={`relative ${wrapperClassName}`}>
{/* 입력 필드 wrapper */}
<div className="relative">
<input
ref={internalRef}
type={showPassword ? 'text' : 'password'}
className={`${className} ${showToggle ? 'pr-10' : ''}`}
value={value !== undefined ? (value as string) : undefined}
defaultValue={value === undefined ? defaultValue : undefined}
onChange={handleChange}
onKeyDown={handleKeyEvent}
onKeyUp={handleKeyEvent}
disabled={disabled}
{...validProps}
/>
{/* 비밀번호 보기/숨기기 버튼 */}
{showToggle && (
<button
type="button"
onClick={handleToggle}
disabled={disabled}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 disabled:opacity-50 disabled:cursor-not-allowed dark:disabled:opacity-50"
aria-label={showPassword ? t('auth.password_input.hide') : t('auth.password_input.show')}
>
<Icon
name={showPassword ? 'eye-slash' : 'eye'}
className="w-5 h-5"
/>
</button>
)}
</div>
{/* CapsLock 경고 */}
{capsLockOn && !showPassword && (
<div className="mt-2 flex items-center gap-1.5 text-sm text-yellow-600 dark:text-yellow-400">
<Icon name="triangle-exclamation" className="w-4 h-4" />
<span>{t('auth.password_input.caps_lock_on')}</span>
</div>
)}
{/* 비밀번호 확인 일치/불일치 표시 */}
{isConfirmField && confirmTarget !== undefined && internalValue.length > 0 && (
<div
className={`mt-2 flex items-center gap-1.5 text-sm ${
isMatch
? 'text-green-600 dark:text-green-400'
: 'text-red-600 dark:text-red-400'
}`}
>
<Icon
name={isMatch ? 'check-circle' : 'xmark-circle'}
className="w-4 h-4"
/>
<span>{isMatch ? t('auth.password_input.match') : t('auth.password_input.mismatch')}</span>
</div>
)}
{/* 비밀번호 조건 검증 표시 */}
{showValidation && !isConfirmField && internalValue.length > 0 && (
<div className={`mt-2 space-y-1 ${validationClassName}`}>
{displayRules.map(({ rule, param }) => {
const passed = validationResults[rule.key];
// 파라미터가 있는 규칙은 라벨에 파라미터 값 전달
const labelParams = param !== undefined ? { count: param } : undefined;
return (
<div
key={rule.key}
className={`flex items-center gap-1.5 text-sm ${
passed
? 'text-green-600 dark:text-green-400'
: 'text-gray-500 dark:text-gray-400'
}`}
>
<Icon
name={passed ? 'check-circle' : 'circle'}
className="w-4 h-4"
/>
<span>{t(rule.labelKey, labelParams)}</span>
</div>
);
})}
</div>
)}
{/* 에러 메시지 */}
{error && (
<p className="mt-1 text-sm text-red-600 dark:text-red-400">{error}</p>
)}
</div>
);
}
);
PasswordInput.displayName = 'PasswordInput';
@@ -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 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,434 @@
/**
* PasswordInput 컴포넌트 테스트
*
* @description 비밀번호 입력 컴포넌트의 동작을 테스트합니다.
*/
import { render, screen, fireEvent, act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { PasswordInput, defaultPasswordRules, availablePasswordRules } from '../PasswordInput';
// Icon 컴포넌트 Mock
vi.mock('../Icon', () => ({
Icon: ({ name, className }: { name: string; className?: string }) => (
<i data-testid={`icon-${name}`} className={className} />
),
}));
// 다국어 키 -> 텍스트 매핑 (테스트용)
const translations: Record<string, string> = {
'auth.password_input.show': '비밀번호 보기',
'auth.password_input.hide': '비밀번호 숨기기',
'auth.password_input.match': '비밀번호가 일치합니다',
'auth.password_input.mismatch': '비밀번호가 일치하지 않습니다',
'auth.password_input.caps_lock_on': 'CapsLock이 켜져 있습니다',
'auth.password_input.rules.minLength': '최소 8자 이상',
'auth.password_input.rules.hasUppercase': '대문자 포함',
'auth.password_input.rules.hasLowercase': '소문자 포함',
'auth.password_input.rules.hasNumber': '숫자 포함',
'auth.password_input.rules.hasSpecial': '특수문자 포함',
};
// G7Core.t() Mock 설정
const mockT = vi.fn((key: string) => translations[key] ?? key);
describe('PasswordInput 컴포넌트', () => {
beforeEach(() => {
// G7Core Mock 설정
(window as unknown as { G7Core: { t: typeof mockT } }).G7Core = {
t: mockT,
};
});
afterEach(() => {
vi.clearAllMocks();
delete (window as unknown as { G7Core?: unknown }).G7Core;
});
describe('렌더링', () => {
it('기본 렌더링이 되어야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
expect(input).toBeInTheDocument();
expect(input).toHaveAttribute('type', 'password');
});
it('showToggle=true일 때 토글 버튼이 렌더링되어야 함', () => {
render(<PasswordInput name="password" showToggle={true} />);
const toggleButton = screen.getByRole('button', { name: /비밀번호 보기/i });
expect(toggleButton).toBeInTheDocument();
});
it('showToggle=false일 때 토글 버튼이 렌더링되지 않아야 함', () => {
render(<PasswordInput name="password" showToggle={false} />);
const toggleButton = screen.queryByRole('button');
expect(toggleButton).not.toBeInTheDocument();
});
it('에러 메시지가 표시되어야 함', () => {
render(<PasswordInput name="password" error="비밀번호 오류" />);
expect(screen.getByText('비밀번호 오류')).toBeInTheDocument();
});
});
describe('비밀번호 보기/숨기기', () => {
it('토글 버튼 클릭 시 비밀번호가 표시되어야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
const toggleButton = screen.getByRole('button', { name: /비밀번호 보기/i });
// 초기 상태: password 타입
expect(input).toHaveAttribute('type', 'password');
// 토글 클릭
fireEvent.click(toggleButton);
// 변경 상태: text 타입
expect(input).toHaveAttribute('type', 'text');
});
it('토글 버튼 두 번 클릭 시 비밀번호가 다시 숨겨져야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
const toggleButton = screen.getByRole('button', { name: /비밀번호 보기/i });
// 두 번 클릭
fireEvent.click(toggleButton);
fireEvent.click(toggleButton);
expect(input).toHaveAttribute('type', 'password');
});
it('disabled 상태에서 토글 버튼도 비활성화되어야 함', () => {
render(<PasswordInput name="password" disabled />);
const toggleButton = screen.getByRole('button');
expect(toggleButton).toBeDisabled();
});
});
describe('비밀번호 검증', () => {
it('showValidation=true일 때 검증 규칙이 표시되어야 함', () => {
render(
<PasswordInput
name="password"
showValidation={true}
enableRules={['minLength', 'hasUppercase', 'hasLowercase', 'hasNumber', 'hasSpecial']}
defaultValue="test"
data-testid="password-input"
/>
);
// 기본 규칙들이 표시되어야 함
expect(screen.getByText('최소 8자 이상')).toBeInTheDocument();
expect(screen.getByText('대문자 포함')).toBeInTheDocument();
expect(screen.getByText('소문자 포함')).toBeInTheDocument();
expect(screen.getByText('숫자 포함')).toBeInTheDocument();
expect(screen.getByText('특수문자 포함')).toBeInTheDocument();
});
it('조건 충족 시 체크 아이콘이 표시되어야 함', () => {
render(
<PasswordInput
name="password"
showValidation={true}
enableRules={['minLength', 'hasLowercase', 'hasNumber']}
defaultValue="test1234"
data-testid="password-input"
/>
);
// 8자 이상, 소문자, 숫자 조건 충족
// check-circle 아이콘이 표시되어야 함
const checkIcons = screen.getAllByTestId('icon-check-circle');
expect(checkIcons.length).toBeGreaterThan(0);
});
it('showRules로 표시할 규칙을 제한할 수 있어야 함', () => {
render(
<PasswordInput
name="password"
showValidation={true}
enableRules={['minLength', 'hasUppercase', 'hasNumber', 'hasSpecial']}
showRules={['minLength', 'hasNumber']}
defaultValue="test"
data-testid="password-input"
/>
);
// 지정한 규칙만 표시
expect(screen.getByText('최소 8자 이상')).toBeInTheDocument();
expect(screen.getByText('숫자 포함')).toBeInTheDocument();
// 지정하지 않은 규칙은 표시되지 않음
expect(screen.queryByText('대문자 포함')).not.toBeInTheDocument();
expect(screen.queryByText('특수문자 포함')).not.toBeInTheDocument();
});
it('onValidityChange 콜백이 호출되어야 함', () => {
const onValidityChange = vi.fn();
render(
<PasswordInput
name="password"
showValidation={true}
onValidityChange={onValidityChange}
defaultValue="Test1234!"
data-testid="password-input"
/>
);
// 기본 규칙(minLength)만 적용되므로 모든 조건 충족 시 isValid=true
expect(onValidityChange).toHaveBeenCalledWith(true, []);
});
it('빈 값일 때 검증 결과가 표시되지 않아야 함', () => {
render(
<PasswordInput
name="password"
showValidation={true}
data-testid="password-input"
/>
);
// 검증 규칙 텍스트가 표시되지 않아야 함
expect(screen.queryByText('최소 8자 이상')).not.toBeInTheDocument();
});
});
describe('비밀번호 확인', () => {
it('isConfirmField=true일 때 일치 여부가 표시되어야 함', () => {
render(
<PasswordInput
name="password_confirmation"
isConfirmField={true}
confirmTarget="password123"
defaultValue="password123"
data-testid="confirm-input"
/>
);
expect(screen.getByText('비밀번호가 일치합니다')).toBeInTheDocument();
});
it('비밀번호가 일치하지 않을 때 불일치 메시지가 표시되어야 함', () => {
render(
<PasswordInput
name="password_confirmation"
isConfirmField={true}
confirmTarget="password123"
defaultValue="different"
data-testid="confirm-input"
/>
);
expect(screen.getByText('비밀번호가 일치하지 않습니다')).toBeInTheDocument();
});
it('onMatchChange 콜백이 호출되어야 함', () => {
const onMatchChange = vi.fn();
render(
<PasswordInput
name="password_confirmation"
isConfirmField={true}
confirmTarget="password123"
onMatchChange={onMatchChange}
defaultValue="password123"
data-testid="confirm-input"
/>
);
expect(onMatchChange).toHaveBeenCalledWith(true);
});
it('빈 값일 때 일치 여부가 표시되지 않아야 함', () => {
render(
<PasswordInput
name="password_confirmation"
isConfirmField={true}
confirmTarget="password123"
data-testid="confirm-input"
/>
);
expect(screen.queryByText('비밀번호가 일치합니다')).not.toBeInTheDocument();
expect(screen.queryByText('비밀번호가 일치하지 않습니다')).not.toBeInTheDocument();
});
});
describe('입력 처리', () => {
it('onChange가 호출되어야 함', () => {
const onChange = vi.fn();
render(
<PasswordInput
name="password"
onChange={onChange}
data-testid="password-input"
/>
);
const input = screen.getByTestId('password-input');
fireEvent.change(input, { target: { value: 'newpassword' } });
expect(onChange).toHaveBeenCalled();
});
it('controlled 모드에서 value prop이 적용되어야 함', () => {
render(
<PasswordInput
name="password"
value="controlled-value"
onChange={vi.fn()}
data-testid="password-input"
/>
);
const input = screen.getByTestId('password-input');
expect(input).toHaveValue('controlled-value');
});
});
describe('availablePasswordRules', () => {
it('minLength 규칙이 올바르게 동작해야 함', () => {
const rule = availablePasswordRules.minLength;
// defaultParam=6 이므로 6자 미만이면 false, 6자 이상이면 true
expect(rule.validate('12345')).toBe(false); // 5자 - 미달
expect(rule.validate('123456')).toBe(true); // 6자 - 통과 (defaultParam=6)
});
it('hasUppercase 규칙이 올바르게 동작해야 함', () => {
const rule = availablePasswordRules.hasUppercase;
expect(rule.validate('lowercase')).toBe(false);
expect(rule.validate('Uppercase')).toBe(true);
});
it('hasLowercase 규칙이 올바르게 동작해야 함', () => {
const rule = availablePasswordRules.hasLowercase;
expect(rule.validate('UPPERCASE')).toBe(false);
expect(rule.validate('lowerCASE')).toBe(true);
});
it('hasNumber 규칙이 올바르게 동작해야 함', () => {
const rule = availablePasswordRules.hasNumber;
expect(rule.validate('noNumbers')).toBe(false);
expect(rule.validate('has1Number')).toBe(true);
});
it('hasSpecial 규칙이 올바르게 동작해야 함', () => {
const rule = availablePasswordRules.hasSpecial;
expect(rule.validate('noSpecial')).toBe(false);
expect(rule.validate('has@Special')).toBe(true);
});
});
describe('다국어 지원', () => {
it('G7Core.t()가 호출되어야 함', () => {
render(
<PasswordInput
name="password"
showValidation={true}
defaultValue="test"
data-testid="password-input"
/>
);
// t() 함수가 규칙 라벨 번역을 위해 호출되었는지 확인
// 참고: showToggle=true(기본값)이면 'auth.password_input.show'가 먼저 호출됨
// 규칙 번역 시 count 파라미터도 함께 전달됨 (defaultParam=6)
expect(mockT).toHaveBeenCalledWith('auth.password_input.rules.minLength', { count: 6 });
});
it('비밀번호 확인 시 다국어 메시지가 표시되어야 함', () => {
render(
<PasswordInput
name="password_confirmation"
isConfirmField={true}
confirmTarget="password123"
defaultValue="password123"
data-testid="confirm-input"
/>
);
// 일치 메시지 번역이 호출되었는지 확인 (호출 순서는 showToggle 버튼 aria-label이 먼저)
expect(mockT).toHaveBeenCalledWith('auth.password_input.match', undefined);
});
});
describe('defaultPasswordRules', () => {
it('기본 규칙에 minLength만 포함되어야 함', () => {
expect(defaultPasswordRules).toHaveLength(1);
expect(defaultPasswordRules[0].key).toBe('minLength');
});
});
describe('CapsLock 감지', () => {
/**
* jsdom에서 fireEvent로 getModifierState를 전달해도 React 이벤트에 반영되지 않음
* KeyboardEvent를 직접 생성하고 getModifierState를 프로토타입에 추가해야 함
* 또한 dispatchEvent는 React 상태 업데이트를 일으키므로 act()로 래핑 필요
*/
const createKeyboardEvent = (type: 'keydown' | 'keyup', capsLockOn: boolean) => {
const event = new KeyboardEvent(type, { bubbles: true, key: 'A' });
Object.defineProperty(event, 'getModifierState', {
value: (key: string) => key === 'CapsLock' && capsLockOn,
});
return event;
};
it('CapsLock이 켜져 있을 때 경고 메시지가 표시되어야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
// CapsLock이 켜진 상태로 keyDown 이벤트 발생
act(() => {
input.dispatchEvent(createKeyboardEvent('keydown', true));
});
expect(screen.getByText('CapsLock이 켜져 있습니다')).toBeInTheDocument();
});
it('CapsLock이 꺼지면 경고 메시지가 사라져야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
// CapsLock 켜짐
act(() => {
input.dispatchEvent(createKeyboardEvent('keydown', true));
});
expect(screen.getByText('CapsLock이 켜져 있습니다')).toBeInTheDocument();
// CapsLock 꺼짐
act(() => {
input.dispatchEvent(createKeyboardEvent('keyup', false));
});
expect(screen.queryByText('CapsLock이 켜져 있습니다')).not.toBeInTheDocument();
});
it('비밀번호가 보이는 상태에서는 CapsLock 경고가 표시되지 않아야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
const toggleButton = screen.getByRole('button', { name: /비밀번호 보기/i });
// CapsLock 켜짐
act(() => {
input.dispatchEvent(createKeyboardEvent('keydown', true));
});
// 비밀번호 보기 활성화
fireEvent.click(toggleButton);
// CapsLock 경고가 표시되지 않아야 함 (showPassword=true면 경고 숨김)
expect(screen.queryByText('CapsLock이 켜져 있습니다')).not.toBeInTheDocument();
});
it('CapsLock 경고 아이콘이 올바르게 표시되어야 함', () => {
render(<PasswordInput name="password" data-testid="password-input" />);
const input = screen.getByTestId('password-input');
act(() => {
input.dispatchEvent(createKeyboardEvent('keydown', true));
});
// triangle-exclamation 아이콘이 표시되어야 함
expect(screen.getByTestId('icon-triangle-exclamation')).toBeInTheDocument();
});
});
});
@@ -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 { PasswordInput, type PasswordInputProps, type PasswordRule, defaultPasswordRules, availablePasswordRules } from './PasswordInput';
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 { 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 { Footer, type FooterProps } from './Footer';
export { Header, type HeaderProps } from './Header';
export { Hr, type HrProps } from './Hr';
// Icon 타입 정의 (enum 및 타입)
export { IconName, type IconStyle, type IconSize } from './IconTypes';
@@ -0,0 +1,194 @@
import React, { useMemo } from 'react';
import { Div } from '../basic/Div';
import { Img } from '../basic/Img';
import { Icon } from '../basic/Icon';
/**
* 아바타 크기 타입
*/
export type AvatarSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl' | '5xl';
/**
* 사이즈별 Tailwind 클래스 매핑
* - 크기 (w/h) + 텍스트 크기 (이니셜용)
*/
const SIZE_CLASSES: Record<AvatarSize, string> = {
xs: 'w-6 h-6 text-xs', // 24px
sm: 'w-8 h-8 text-sm', // 32px
md: 'w-10 h-10 text-base', // 40px
lg: 'w-12 h-12 text-lg', // 48px
xl: 'w-16 h-16 text-xl', // 64px
'2xl': 'w-24 h-24 text-2xl', // 96px
'3xl': 'w-32 h-32 text-3xl', // 128px
'4xl': 'w-40 h-40 text-4xl', // 160px
'5xl': 'w-48 h-48 text-5xl', // 192px
} as const;
/**
* 기본 컨테이너 스타일 (공통)
*/
const BASE_CONTAINER_CLASSES = 'rounded-full overflow-hidden flex-shrink-0 border border-gray-200 dark:border-gray-700';
/**
* 탈퇴 사용자 스타일
*/
const WITHDRAWN_CLASSES = 'grayscale opacity-50';
/**
* 이니셜 배경 스타일
*/
const INITIAL_BG_CLASSES = {
normal: 'bg-gradient-to-br from-blue-500 to-purple-600',
withdrawn: 'bg-gray-300 dark:bg-gray-600',
guest: 'bg-gray-200 dark:bg-gray-700',
} as const;
/**
* Author 객체 인터페이스
*/
export interface AuthorInfo {
/** 사용자 ID */
id?: string | number;
/** 사용자 이름 */
name?: string;
/** 아바타 URL */
avatar?: string;
/** 사용자 상태 */
status?: 'active' | 'inactive' | 'blocked' | 'withdrawn';
/** 비회원 여부 */
is_guest?: boolean;
}
export interface AvatarProps {
/**
* 작성자 객체 (권장)
* API 응답의 author 객체를 그대로 전달하면 됩니다.
* 개별 props(name, avatar 등)가 함께 전달되면 개별 props가 우선합니다.
*/
author?: AuthorInfo;
/** 사용자 이름 (author.name보다 우선) */
name?: string;
/** 아바타 이미지 URL (author.avatar보다 우선) */
avatar?: string;
/** 사이즈 @default 'md' */
size?: AvatarSize;
/** 추가 className */
className?: string;
/** 레이아웃 JSON text 속성 (name보다 우선) */
text?: string;
/** 탈퇴한 사용자 여부 (author.status === 'withdrawn'과 OR 조건) @default false */
isWithdrawn?: boolean;
/** 비회원 여부 (author.is_guest보다 우선) @default false */
isGuest?: boolean;
}
/**
* Avatar 컴포넌트
*
* 사용자 아바타를 표시하는 재사용 가능한 composite 컴포넌트입니다.
* - 아바타 이미지가 있으면 이미지 표시
* - 이미지가 없으면 이름의 첫 글자(이니셜) 표시
* - 비회원: 연한 회색 배경 + 사람 실루엣 아이콘
* - 탈퇴한 사용자: 회색 빈 원 (그레이스케일 + 투명도)
*
* ## Props 우선순위
* 명시적으로 전달한 props가 author에서 추출한 값보다 우선합니다.
* - 이름: text > name > author.name
* - 아바타: avatar > author.avatar
* - 비회원 여부: isGuest > author.is_guest
* - 탈퇴 여부: isWithdrawn || author.status === 'withdrawn'
*
* @example
* // 레이아웃 JSON에서 사용 (author 객체 전달 - 권장)
* {
* "type": "composite",
* "name": "Avatar",
* "props": {
* "author": "{{post.author}}",
* "size": "md"
* }
* }
*
* @example
* // author와 개별 props 혼합 사용 (개별 props가 우선)
* {
* "type": "composite",
* "name": "Avatar",
* "props": {
* "author": "{{post.author}}",
* "avatar": "/images/custom-avatar.png",
* "size": "md"
* }
* }
* // author.avatar가 있어도 "/images/custom-avatar.png"이 표시됨
*/
export const Avatar: React.FC<AvatarProps> = ({
author,
name,
avatar,
size = 'md',
className = '',
text,
isWithdrawn = false,
isGuest = false,
}) => {
// 명시적 props > author 추출값 순서로 결정
const actualAvatar = avatar ?? author?.avatar;
const actualName = text ?? name ?? author?.name ?? '?';
const actualIsWithdrawn = isWithdrawn || author?.status === 'withdrawn';
const actualIsGuest = isGuest || author?.is_guest || false;
// 컨테이너 클래스 메모이제이션
const containerClasses = useMemo(() => {
const sizeClass = SIZE_CLASSES[size] || SIZE_CLASSES.md;
const withdrawnClass = actualIsWithdrawn ? WITHDRAWN_CLASSES : '';
return [sizeClass, BASE_CONTAINER_CLASSES, withdrawnClass, className]
.filter(Boolean)
.join(' ');
}, [size, actualIsWithdrawn, className]);
// 이니셜 배경 클래스
const initialBgClass = actualIsGuest
? INITIAL_BG_CLASSES.guest
: actualIsWithdrawn
? INITIAL_BG_CLASSES.withdrawn
: INITIAL_BG_CLASSES.normal;
// 비회원: 사람 실루엣 아이콘 (연한 회색), 탈퇴 사용자: 사람 실루엣 아이콘 (진한 회색), 일반: 이니셜
const renderContent = () => {
if (actualIsGuest) {
return (
<Div className={`w-full h-full flex items-center justify-center ${initialBgClass}`}>
<Icon name="user" className="text-gray-400 dark:text-gray-500" />
</Div>
);
}
if (actualIsWithdrawn) {
return (
<Div className={`w-full h-full flex items-center justify-center ${initialBgClass}`}>
<Icon name="user" className="text-gray-500 dark:text-gray-400" />
</Div>
);
}
return (
<Div className={`w-full h-full flex items-center justify-center text-white font-semibold ${initialBgClass}`}>
{actualName.charAt(0).toUpperCase()}
</Div>
);
};
return (
<Div className={containerClasses}>
{actualAvatar && !actualIsGuest && !actualIsWithdrawn ? (
<Img
src={actualAvatar}
alt={actualName}
className="w-full h-full object-cover"
/>
) : (
renderContent()
)}
</Div>
);
};
@@ -0,0 +1,538 @@
/**
* AvatarUploader 컴포넌트
*
* 프로필 아바타 이미지 업로드를 위한 컴포넌트입니다.
* - 원형 아바타 UI
* - 파일 선택 시 즉시 업로드
* - 업로드/삭제 API 지원
* - 업로드 오류 표시
* - 삭제 확인 다이얼로그
*
* @module composite/AvatarUploader
*/
import { useRef, useState, useCallback, useEffect } from 'react';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { Label } from '../basic/Label';
import { Input } from '../basic/Input';
import { Img } from '../basic/Img';
import { Avatar } from './Avatar';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
export interface AvatarUploaderProps {
/** 현재 아바타 URL */
src?: string;
/** 이미지 없을 때 표시할 텍스트 (이니셜) */
fallbackText?: string;
/** 아바타 크기 */
size?: 'sm' | 'md' | 'lg' | 'xl' | '2xl';
/** 업로드 API 엔드포인트 (기본: /api/me/avatar) */
uploadEndpoint?: string;
/** 삭제 API 엔드포인트 (기본: /api/me/avatar) */
deleteEndpoint?: string;
/** 업로드 성공 콜백 */
onUploadSuccess?: (data: { avatar: string; attachment_id: number }) => void;
/** 업로드 에러 콜백 */
onUploadError?: (error: Error) => void;
/** 삭제 성공 콜백 */
onDeleteSuccess?: () => void;
/** 삭제 에러 콜백 */
onDeleteError?: (error: Error) => void;
/** 삭제 버튼 표시 여부 */
showDeleteButton?: boolean;
/** 허용 파일 타입 (기본: image/*) */
accept?: string;
/** 최대 파일 크기 (MB, 기본: 5) */
maxSize?: number;
/** 추가 CSS 클래스 */
className?: string;
/** 업로드 버튼 텍스트 */
uploadButtonText?: string;
/** 삭제 버튼 텍스트 */
deleteButtonText?: string;
/** 읽기 전용 모드 */
readOnly?: boolean;
/** 삭제 확인 다이얼로그 표시 여부 (기본: true) */
confirmDelete?: boolean;
/** 삭제 확인 메시지 */
deleteConfirmMessage?: string;
/** 업로드 확인 다이얼로그 표시 여부 (기본: true) */
confirmUpload?: boolean;
/** 업로드 확인 메시지 */
uploadConfirmMessage?: string;
/** 업로드 성공 시 실행할 액션 배열 (G7Core.dispatch) */
uploadSuccessActions?: Array<Record<string, any>>;
/** 업로드 실패 시 실행할 액션 배열 */
uploadErrorActions?: Array<Record<string, any>>;
/** 삭제 성공 시 실행할 액션 배열 */
deleteSuccessActions?: Array<Record<string, any>>;
/** 삭제 실패 시 실행할 액션 배열 */
deleteErrorActions?: Array<Record<string, any>>;
}
// AvatarUploader size를 Avatar size로 매핑
// AvatarUploader는 프로필 편집용으로 더 큰 사이즈 사용
const avatarSizeMap: Record<string, 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl' | '5xl'> = {
sm: 'md', // AvatarUploader sm → Avatar md (w-10, 40px)
md: 'lg', // AvatarUploader md → Avatar lg (w-12, 48px)
lg: 'xl', // AvatarUploader lg → Avatar xl (w-16, 64px)
xl: '2xl', // AvatarUploader xl → Avatar 2xl (w-24, 96px)
'2xl': '3xl', // AvatarUploader 2xl → Avatar 3xl (w-32, 128px)
};
export function AvatarUploader({
src,
fallbackText = 'U',
size = 'lg',
uploadEndpoint = '/api/me/avatar',
deleteEndpoint = '/api/me/avatar',
onUploadSuccess,
onUploadError,
onDeleteSuccess,
onDeleteError,
showDeleteButton = true,
accept = 'image/*',
maxSize = 5,
className = '',
uploadButtonText,
deleteButtonText,
readOnly = false,
confirmDelete = true,
deleteConfirmMessage,
confirmUpload = true,
uploadConfirmMessage,
uploadSuccessActions,
uploadErrorActions,
deleteSuccessActions,
deleteErrorActions,
}: AvatarUploaderProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
// undefined: 초기 상태(props 사용), null: 삭제됨, string: 새 이미지 URL
const [localAvatarUrl, setLocalAvatarUrl] = useState<string | null | undefined>(undefined);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showUploadConfirm, setShowUploadConfirm] = useState(false);
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const inputId = useRef(`avatar-upload-${Math.random().toString(36).slice(2, 11)}`).current;
// 파일 선택 시 미리보기 URL 생성
useEffect(() => {
if (pendingFile) {
const url = URL.createObjectURL(pendingFile);
setPreviewUrl(url);
return () => URL.revokeObjectURL(url);
} else {
setPreviewUrl(null);
}
}, [pendingFile]);
// 다국어 텍스트 가져오기
const t = useCallback((key: string): string => {
return G7Core?.t?.(key) ?? key;
}, []);
// CSRF 토큰 가져오기
const getCsrfToken = useCallback((): string | null => {
const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/);
if (match) {
return decodeURIComponent(match[1]);
}
return null;
}, []);
// 인증 토큰 가져오기 (ApiClient에서 토큰 조회)
const getAuthToken = useCallback((): string | null => {
return G7Core?.api?.getToken?.() ?? null;
}, []);
// 실제 업로드 실행 함수
const executeUpload = useCallback(async (file: File) => {
setShowUploadConfirm(false);
setPendingFile(null);
setIsUploading(true);
setErrorMessage(null);
try {
// FormData 생성
const formData = new FormData();
formData.append('avatar', file);
// API 호출
const csrfToken = getCsrfToken();
const authToken = getAuthToken();
const response = await fetch(uploadEndpoint, {
method: 'POST',
headers: {
Accept: 'application/json',
...(csrfToken && { 'X-XSRF-TOKEN': csrfToken }),
...(authToken && { Authorization: `Bearer ${authToken}` }),
},
credentials: 'include',
body: formData,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || t('attachment.upload_failed'));
}
const data = await response.json();
const result = data.data || data;
// 로컬 상태 즉시 업데이트 (빠른 피드백)
if (result.avatar) {
setLocalAvatarUrl(result.avatar);
}
onUploadSuccess?.(result);
G7Core?.toast?.success?.(t('mypage.profile.avatar_uploaded'));
// 액션 props가 있으면 dispatch, 없으면 기본 동작(user 리패치)
if (uploadSuccessActions?.length) {
uploadSuccessActions.forEach(action => G7Core?.dispatch?.(action));
} else {
G7Core?.refetchDataSource?.('user');
}
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
setErrorMessage(err.message);
onUploadError?.(err);
G7Core?.toast?.error?.(err.message);
if (uploadErrorActions?.length) {
uploadErrorActions.forEach(action => G7Core?.dispatch?.(action));
}
} finally {
setIsUploading(false);
// 입력 초기화 (같은 파일 재선택 가능)
if (inputRef.current) {
inputRef.current.value = '';
}
}
}, [uploadEndpoint, onUploadSuccess, onUploadError, getCsrfToken, getAuthToken, t]);
// 파일 선택 핸들러
const handleFileChange = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
// 오류 상태 초기화
setErrorMessage(null);
// 파일 크기 검증
const maxBytes = maxSize * 1024 * 1024;
if (file.size > maxBytes) {
const error = new Error(t('attachment.file_too_large').replace(':max', `${maxSize}MB`));
setErrorMessage(error.message);
onUploadError?.(error);
G7Core?.toast?.error?.(error.message);
return;
}
// 파일 타입 검증
if (accept && !file.type.match(accept.replace('*', '.*'))) {
const error = new Error(t('attachment.invalid_file_type'));
setErrorMessage(error.message);
onUploadError?.(error);
G7Core?.toast?.error?.(error.message);
return;
}
// 확인 다이얼로그 표시 또는 즉시 업로드
if (confirmUpload) {
setPendingFile(file);
setShowUploadConfirm(true);
} else {
executeUpload(file);
}
},
[maxSize, accept, onUploadError, confirmUpload, executeUpload, t]
);
// 삭제 실행 함수
const executeDelete = useCallback(async () => {
setShowDeleteConfirm(false);
setIsDeleting(true);
setErrorMessage(null);
try {
const csrfToken = getCsrfToken();
const authToken = getAuthToken();
const response = await fetch(deleteEndpoint, {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(csrfToken && { 'X-XSRF-TOKEN': csrfToken }),
...(authToken && { Authorization: `Bearer ${authToken}` }),
},
credentials: 'include',
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || t('attachment.delete_failed'));
}
// 로컬 상태 즉시 업데이트 (빠른 피드백)
setLocalAvatarUrl(null);
onDeleteSuccess?.();
G7Core?.toast?.success?.(t('mypage.profile.avatar_deleted'));
// 액션 props가 있으면 dispatch, 없으면 기본 동작(user 리패치)
if (deleteSuccessActions?.length) {
deleteSuccessActions.forEach(action => G7Core?.dispatch?.(action));
} else {
G7Core?.refetchDataSource?.('user');
}
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
setErrorMessage(err.message);
onDeleteError?.(err);
G7Core?.toast?.error?.(err.message);
if (deleteErrorActions?.length) {
deleteErrorActions.forEach(action => G7Core?.dispatch?.(action));
}
} finally {
setIsDeleting(false);
}
}, [deleteEndpoint, onDeleteSuccess, onDeleteError, getCsrfToken, getAuthToken, t]);
// 삭제 버튼 클릭 핸들러 (확인 다이얼로그 표시 또는 즉시 삭제)
const handleDeleteClick = useCallback(() => {
if (confirmDelete) {
setShowDeleteConfirm(true);
} else {
executeDelete();
}
}, [confirmDelete, executeDelete]);
// 삭제 취소
const handleDeleteCancel = useCallback(() => {
setShowDeleteConfirm(false);
}, []);
// 업로드 취소
const handleUploadCancel = useCallback(() => {
setShowUploadConfirm(false);
setPendingFile(null);
// 입력 초기화 (같은 파일 재선택 가능)
if (inputRef.current) {
inputRef.current.value = '';
}
}, []);
// 업로드 확인
const handleUploadConfirm = useCallback(() => {
if (pendingFile) {
executeUpload(pendingFile);
}
}, [pendingFile, executeUpload]);
// 로컬 상태 우선 사용: undefined면 props 사용, null이면 삭제됨, string이면 새 이미지
const currentAvatarUrl = localAvatarUrl === undefined ? src : localAvatarUrl;
const hasAvatar = !!currentAvatarUrl;
// Avatar 컴포넌트에 전달할 사이즈
const avatarSize = avatarSizeMap[size] || 'lg';
// 현재 표시 모드 결정
const isConfirmMode = showDeleteConfirm || showUploadConfirm;
// 버튼 영역 렌더링
const renderButtons = () => (
<Div className="flex items-center justify-center gap-2">
{/* 숨겨진 파일 입력 */}
<Input
ref={inputRef}
id={inputId}
type="file"
accept={accept}
className="hidden"
onChange={handleFileChange}
disabled={isUploading}
/>
{/* 이미지 없을 때: 이미지 등록 버튼 */}
{!hasAvatar && (
<Label
htmlFor={inputId}
className={`inline-flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer ${
isUploading ? 'opacity-50 cursor-not-allowed' : ''
}`}
>
{isUploading ? (
<Icon name="spinner" size="sm" className="animate-spin" />
) : (
<Icon name="image" size="sm" />
)}
<Span>{uploadButtonText || t('mypage.profile.register_avatar')}</Span>
</Label>
)}
{/* 이미지 있을 때: 변경 + 삭제 버튼 */}
{hasAvatar && (
<>
<Label
htmlFor={inputId}
className={`inline-flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer ${
isUploading ? 'opacity-50 cursor-not-allowed' : ''
}`}
>
{isUploading ? (
<Icon name="spinner" size="sm" className="animate-spin" />
) : (
<Icon name="upload" size="sm" />
)}
<Span>{uploadButtonText || t('common.change')}</Span>
</Label>
{showDeleteButton && (
<Button
type="button"
className="inline-flex items-center gap-2 px-4 py-2 border border-red-300 dark:border-red-600 text-red-600 dark:text-red-400 rounded-lg text-sm font-medium hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
onClick={handleDeleteClick}
disabled={isDeleting}
>
{isDeleting ? (
<Icon name="spinner" size="sm" className="animate-spin" />
) : (
<Icon name="trash-2" size="sm" />
)}
<Span>{deleteButtonText || t('common.delete')}</Span>
</Button>
)}
</>
)}
</Div>
);
return (
<Div className={`flex flex-col items-center gap-3 ${className}`}>
{/* 아바타 이미지 - 업로드 확인 시 미리보기 표시 */}
{showUploadConfirm && previewUrl ? (
<Div className="relative">
<Img
src={previewUrl}
alt="Preview"
className={`rounded-full object-cover ${
size === 'sm' ? 'w-10 h-10' :
size === 'md' ? 'w-12 h-12' :
size === 'lg' ? 'w-16 h-16' :
size === 'xl' ? 'w-24 h-24' :
'w-32 h-32'
}`}
/>
<Div className="absolute inset-0 rounded-full bg-blue-500/20 border-2 border-blue-500 border-dashed" />
</Div>
) : (
<Avatar
avatar={currentAvatarUrl || undefined}
name={fallbackText}
size={avatarSize}
/>
)}
{/* 버튼/확인 영역 */}
{!readOnly && (
<Div className="w-[220px] flex flex-col items-center gap-2">
{/* 업로드 확인 박스 */}
{showUploadConfirm && pendingFile && (
<Div className="w-full p-3 bg-blue-50 dark:bg-blue-950/50 border border-blue-200 dark:border-blue-800 rounded-lg">
<Div className="flex items-center gap-2 mb-2">
<Icon name="upload" size="sm" className="text-blue-600 dark:text-blue-400 shrink-0" />
<Span className="text-sm font-medium text-blue-800 dark:text-blue-300">
{uploadConfirmMessage || t('mypage.profile.upload_avatar_confirm')}
</Span>
</Div>
<Div className="text-xs text-blue-600 dark:text-blue-400 truncate mb-3" title={pendingFile.name}>
{pendingFile.name} ({(pendingFile.size / 1024 / 1024).toFixed(2)}MB)
</Div>
<Div className="grid grid-cols-2 gap-2">
<Button
type="button"
className="inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium transition-colors disabled:opacity-50"
onClick={handleUploadConfirm}
disabled={isUploading}
>
{isUploading ? (
<Icon name="spinner" size="sm" className="animate-spin" />
) : (
<Icon name="check" size="sm" />
)}
<Span>{t('common.confirm')}</Span>
</Button>
<Button
type="button"
className="inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-md text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
onClick={handleUploadCancel}
>
<Span>{t('common.cancel')}</Span>
</Button>
</Div>
</Div>
)}
{/* 삭제 확인 박스 */}
{showDeleteConfirm && (
<Div className="w-full p-3 bg-red-50 dark:bg-red-950/50 border border-red-200 dark:border-red-800 rounded-lg">
<Div className="flex items-center gap-2 mb-2">
<Icon name="alert-triangle" size="sm" className="text-red-600 dark:text-red-400 shrink-0" />
<Span className="text-sm font-medium text-red-800 dark:text-red-300">
{deleteConfirmMessage || t('mypage.profile.delete_avatar_confirm')}
</Span>
</Div>
<Div className="grid grid-cols-2 gap-2">
<Button
type="button"
className="inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md text-sm font-medium transition-colors disabled:opacity-50"
onClick={executeDelete}
disabled={isDeleting}
>
{isDeleting ? (
<Icon name="spinner" size="sm" className="animate-spin" />
) : (
<Icon name="trash-2" size="sm" />
)}
<Span>{t('common.delete')}</Span>
</Button>
<Button
type="button"
className="inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-md text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
onClick={handleDeleteCancel}
>
<Span>{t('common.cancel')}</Span>
</Button>
</Div>
</Div>
)}
{/* 기본 모드 - 버튼들 */}
{!isConfirmMode && renderButtons()}
</Div>
)}
{/* 오류 메시지 표시 */}
{errorMessage && !isConfirmMode && (
<Div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
<Icon name="alert-circle" size="sm" />
<Span>{errorMessage}</Span>
</Div>
)}
</Div>
);
}
export default AvatarUploader;
@@ -0,0 +1,146 @@
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 { I } from '../basic/I';
// 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 && (
<I className="fa-solid fa-spinner w-4 h-4 animate-spin" />
)}
<Span>{isLoading ? resolvedLoadingText : resolvedConfirmText}</Span>
</Button>
</Div>
</Modal>
);
};
@@ -0,0 +1,168 @@
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
/**
* G7Core 다국어 헬퍼
*
* @param key 다국어 키
* @return 번역된 문자열
*/
const t = (key: string): string =>
(window as any).G7Core?.t?.(key) ?? key;
export interface ExpandableContentProps {
/**
* 접힌 상태의 최대 높이 (px)
* @default 500
*/
maxHeight?: number;
/**
* 펼치기 버튼 텍스트
*/
expandText?: string;
/**
* 접기 버튼 텍스트
*/
collapseText?: string;
/**
* 사용자 정의 클래스
*/
className?: string;
/**
* children 렌더링
*/
children?: React.ReactNode;
}
/**
* ExpandableContent 컴포넌트
*
* 콘텐츠가 maxHeight를 초과하면 그라데이션 오버레이와 펼치기/접기 버튼을 표시합니다.
* 콘텐츠가 짧으면 버튼/그라데이션 없이 전체 콘텐츠를 그대로 표시합니다.
*
* @example
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "ExpandableContent",
* "props": { "maxHeight": 500 },
* "children": [
* {
* "type": "composite",
* "name": "HtmlContent",
* "props": { "content": "{{product.data?.description_localized ?? ''}}" }
* }
* ]
* }
*/
export const ExpandableContent: React.FC<ExpandableContentProps> = ({
maxHeight = 500,
expandText,
collapseText,
className = '',
children,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const [needsExpand, setNeedsExpand] = useState(false);
const contentRef = useRef<HTMLDivElement>(null);
/**
* 콘텐츠 높이를 측정하여 펼치기 버튼 필요 여부를 결정합니다.
*/
const checkHeight = useCallback(() => {
if (contentRef.current) {
const scrollHeight = contentRef.current.scrollHeight;
setNeedsExpand(scrollHeight > maxHeight);
}
}, [maxHeight]);
useEffect(() => {
checkHeight();
// 이미지 로드 후 높이 재측정
const container = contentRef.current;
if (!container) return;
const images = container.querySelectorAll('img');
images.forEach((img) => {
if (!img.complete) {
img.addEventListener('load', checkHeight);
}
});
// ResizeObserver로 동적 콘텐츠 변경 감지
let observer: ResizeObserver | null = null;
if (typeof ResizeObserver !== 'undefined') {
observer = new ResizeObserver(checkHeight);
observer.observe(container);
}
return () => {
images.forEach((img) => {
img.removeEventListener('load', checkHeight);
});
observer?.disconnect();
};
}, [checkHeight, children]);
const toggleExpand = () => {
setIsExpanded((prev) => !prev);
};
const resolvedExpandText = expandText || t('sirsoft-ecommerce.shop.product.expand_detail');
const resolvedCollapseText = collapseText || t('sirsoft-ecommerce.shop.product.collapse_detail');
return (
<Div className={className}>
{/* 콘텐츠 컨테이너 */}
<Div className="relative">
<Div
ref={contentRef}
className={
!isExpanded && needsExpand
? 'overflow-hidden transition-[max-height] duration-300 ease-in-out'
: 'transition-[max-height] duration-300 ease-in-out'
}
style={
!isExpanded && needsExpand
? { maxHeight: `${maxHeight}px` }
: undefined
}
>
{children}
</Div>
{/* 그라데이션 오버레이 */}
{!isExpanded && needsExpand && (
<Div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-white dark:from-gray-900 to-transparent pointer-events-none" />
)}
</Div>
{/* 펼치기/접기 버튼 (전체 너비 바 스타일) */}
{needsExpand && (
<Button
type="button"
onClick={toggleExpand}
className="flex items-center justify-center w-full py-3.5 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer gap-1.5"
>
<Span className="text-sm font-semibold text-gray-600 dark:text-gray-400">
{isExpanded ? resolvedCollapseText : resolvedExpandText}
</Span>
<Icon
name={isExpanded ? 'chevron-up' : 'chevron-down'}
size="sm"
/>
</Button>
)}
</Div>
);
};
export default ExpandableContent;
@@ -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,104 @@
/**
* 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;
/** 자식 요소 */
children?: React.ReactNode;
}
export const FileDropZone: React.FC<FileDropZoneProps> = ({
isDragOver,
canAddMore,
onFiles,
setIsDragOver,
inputRef,
accept,
maxFiles,
maxSize,
children,
}) => {
return (
<Div
className={`
relative border-2 border-dashed rounded-lg transition-colors
${
isDragOver
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-300 dark:border-gray-600'
}
`}
onDragOver={(e) => {
e.preventDefault();
if (canAddMore) setIsDragOver(true);
}}
onDragLeave={() => setIsDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setIsDragOver(false);
if (canAddMore) {
onFiles(e.dataTransfer.files);
}
}}
>
<input
ref={inputRef}
type="file"
multiple
accept={accept}
onChange={(e) => e.target.files && onFiles(e.target.files)}
className="hidden"
/>
{/* 파일이 없을 때: 빈 드롭존 */}
{!children && (
<Div
className="p-8 text-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors"
onClick={() => 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,153 @@
/**
* 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;
}
export const FileList: React.FC<FileListProps> = ({
allItems,
canAddMore,
totalCount,
maxFiles,
maxSize,
accept,
onRemove,
onRetry,
onImageClick,
onDownload,
onDragEnd,
onAddClick,
enablePrimarySelection,
primaryFileId,
onPrimaryChange,
}) => {
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
}
/>
);
})}
{/* 추가 버튼 (더 추가할 수 있을 때만) */}
{canAddMore && (
<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,287 @@
/**
* FileUploader 컴포넌트
*
* 파일 업로드를 위한 통합 컴포넌트입니다.
* - 드래그 앤 드롭 지원
* - 이미지 압축
* - 병렬 업로드
* - 순서 변경
* - 이미지 갤러리
*
* @module composite/FileUploader
*/
import { forwardRef, useImperativeHandle, useMemo, useRef, useCallback } 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';
/** 안정적인 빈 배열 참조 — 매 렌더마다 새 [] 생성 방지 (useEffect 무한 루프 방지) */
const EMPTY_FILES: Attachment[] = [];
const EMPTY_ROLE_IDS: number[] = [];
// ========== Main Component ==========
export const FileUploader = forwardRef<FileUploaderRef, FileUploaderProps>(
(
{
uploadTriggerEvent,
attachmentableType,
attachmentableId,
collection = 'default',
maxFiles = 10,
maxSize = 10,
maxConcurrentUploads = 3,
accept,
imageCompression: compressionOptions,
roleIds = EMPTY_ROLE_IDS,
autoUpload = true,
onFilesChange,
onChange,
onUploadComplete,
onUploadError,
onRemove,
onReorder,
initialFiles = EMPTY_FILES,
className = '',
confirmBeforeRemove = false,
confirmRemoveTitle,
confirmRemoveMessage,
apiEndpoints,
uploadParams,
enablePrimarySelection = false,
primaryFileId,
onPrimaryChange,
},
ref
) => {
// API 엔드포인트 기본값 설정 (User 템플릿용 기본 경로)
const endpoints = {
upload: apiEndpoints?.upload ?? '/api/attachments',
delete: apiEndpoints?.delete ?? '/api/attachments/:id',
reorder: apiEndpoints?.reorder ?? '/api/attachments/reorder',
};
// onFilesChange 래퍼: ActionDispatcher 호환 형태로 변환
// ActionDispatcher는 type: "change" → onChange prop으로 매핑하므로,
// onChange가 설정될 수 있음. onFilesChange는 직접 props 전달 시 사용.
// ref로 안정화: ActionDispatcher가 매 렌더마다 새 함수를 바인딩하므로
// 직접 의존하면 useMemo/useEffect 무한 루프 발생. ref로 최신 참조만 유지.
const callbackRef = useRef(onChange ?? onFilesChange);
callbackRef.current = onChange ?? onFilesChange;
const wrappedOnFilesChange = useCallback(
(files: import('./types').PendingFile[]) => {
const cb = callbackRef.current;
if (!cb) return;
// ActionDispatcher 호환: { target: { value: files } } 형태로 전달
const syntheticEvent = {
target: { value: files, files },
preventDefault: () => {},
stopPropagation: () => {},
};
cb(syntheticEvent as any);
},
[] // ref 기반이므로 의존성 불필요 — 안정적인 단일 참조
);
// 핵심 로직 훅 사용
const uploader = useFileUploader({
attachmentableType,
attachmentableId,
collection,
maxFiles,
maxSize,
maxConcurrentUploads,
accept,
imageCompression: compressionOptions,
roleIds,
autoUpload,
initialFiles,
endpoints,
onFilesChange: wrappedOnFilesChange,
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}
>
{/* 파일이 있을 때만 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}
/>
)}
</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,268 @@
/**
* 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;
export interface SortableThumbnailItemProps {
file: PendingFile | (Attachment & { status?: string });
onRemove: () => void;
onRetry?: () => void;
/** 이미지 클릭 시 갤러리 열기 */
onImageClick?: () => void;
/** 비이미지 파일 클릭/다운로드 시 호출 */
onDownload?: () => void;
/** 대표 이미지 여부 */
isPrimary?: boolean;
/** 대표 이미지 설정 클릭 핸들러 */
onPrimaryClick?: () => void;
}
export const SortableThumbnailItem: React.FC<SortableThumbnailItemProps> = ({
file,
onRemove,
onRetry,
onImageClick,
onDownload,
isPrimary,
onPrimaryClick,
}) => {
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) {
console.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>
)}
{/* 호버 시 액션 버튼들 */}
<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">
{/* 드래그 핸들 */}
<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,169 @@
/**
* 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;
/** 파일 변경 콜백 (직접 props 전달 시) */
onFilesChange?: (files: PendingFile[]) => void;
/** 파일 변경 콜백 (ActionDispatcher type: "change" → onChange 매핑용) */
onChange?: (...args: any[]) => void;
/** 업로드 완료 콜백 */
onUploadComplete?: (attachments: Attachment[]) => void;
/** 업로드 에러 콜백 */
onUploadError?: (error: string, file: File) => void;
/** 삭제 콜백 */
onRemove?: (id: number | string) => void;
/** 순서 변경 콜백 (reorder 완료 후 정렬된 기존 파일 목록 전달) */
onReorder?: (files: Attachment[]) => void;
/** 초기 첨부파일 목록 */
initialFiles?: Attachment[];
/** 추가 CSS 클래스 */
className?: string;
/**
* 삭제 전 확인 모달 표시 여부 (기존 첨부파일만 적용)
* true: 삭제 확인 모달 표시 후 삭제
* false: 즉시 삭제 (기본값)
*/
confirmBeforeRemove?: boolean;
/** 삭제 확인 모달 제목 (다국어 키 또는 문자열) */
confirmRemoveTitle?: string;
/** 삭제 확인 모달 메시지 (다국어 키 또는 문자열) */
confirmRemoveMessage?: string;
/**
* 업로드 시 추가로 전송할 파라미터
*/
uploadParams?: Record<string, string>;
/**
* 대표 파일(이미지) 선택 기능 활성화
*/
enablePrimarySelection?: boolean;
/**
* 현재 대표 파일 식별자 (ID 또는 hash)
*/
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/attachments) */
upload?: string;
/** 파일 삭제 API - :id를 실제 ID로 치환 (기본값: /api/attachments/:id) */
delete?: string;
/** 순서 변경 API (기본값: /api/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,787 @@
/**
* useFileUploader Hook
*
* FileUploader의 핵심 로직을 담당하는 훅입니다.
* - 파일 추가/삭제/업로드
* - 이미지 압축
* - 병렬 업로드 큐
* - 순서 변경
*
* @module composite/FileUploader/useFileUploader
*/
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
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)[]>([]);
// initialFiles 참조 안정성 — 외부에서 매 렌더마다 새 배열이 전달되는 경우 방어
const prevInitialFilesRef = useRef<Attachment[]>(initialFiles);
// 이미지 갤러리 상태
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());
// 대기 파일 변경 시 콜백
useEffect(() => {
onFilesChange?.(pendingFiles);
}, [pendingFiles, onFilesChange]);
// initialFiles 참조 안정화 — 매 렌더마다 새 배열이 전달되어도 내용이 같으면 무시
const stableInitialFiles = useMemo(() => {
const prev = prevInitialFilesRef.current;
// 동일 참조면 즉시 반환
if (prev === initialFiles) return prev;
// 길이가 다르면 실제 변경
if (prev.length !== initialFiles.length) {
prevInitialFilesRef.current = initialFiles;
return initialFiles;
}
// 빈 배열끼리는 항상 동일 (가장 흔한 케이스 — 무한 루프 방지)
if (prev.length === 0 && initialFiles.length === 0) return prev;
// ID 기반 얕은 비교
const changed = initialFiles.some((f, i) => f.id !== prev[i]?.id);
if (changed) {
prevInitialFilesRef.current = initialFiles;
return initialFiles;
}
return prev;
}, [initialFiles]);
// initialFiles prop 변경 시 existingFiles 동기화 (삭제/순서변경된 경우 제외)
useEffect(() => {
// 순서가 변경된 후에는 initialFiles 동기화를 무시
if (hasReorderedRef.current) {
return;
}
const filteredFiles = stableInitialFiles.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]);
}, [stableInitialFiles]);
// 이미지 압축
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;
}
// 확장자/MIME 타입 검증
if (accept) {
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
const acceptedTypes = accept.split(',').map((e) => e.trim().toLowerCase());
const isAccepted = acceptedTypes.some((accepted) => {
// MIME 타입 와일드카드 (예: image/*, video/*, audio/*)
if (accepted.includes('/')) {
if (accepted.endsWith('/*')) {
const mimePrefix = accepted.slice(0, -2);
return file.type.toLowerCase().startsWith(mimePrefix + '/');
}
// 정확한 MIME 타입 매칭 (예: image/jpeg)
return file.type.toLowerCase() === accepted;
}
// 확장자 매칭 (예: .jpg, .png)
return ext === accepted;
});
if (!isAccepted) {
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 {
console.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) {
console.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,214 @@
/**
* Footer 컴포넌트
*
* 사이트 하단 푸터 컴포넌트입니다.
* 사이트 정보, 링크 그룹, 소셜 링크, 저작권 표시를 포함합니다.
*
* @see 화면 구성:
* ┌─────────────────────────────────────────────────────────────────┐
* │ [사이트명] │
* │ 함께 성장하는 커뮤니티 │
* ├────────────┬────────────┬────────────┬────────────────────────────┤
* │ 커뮤니티 │ 정보 │ 정책 │ [GitHub] [Twitter] [Discord]│
* ├─────────────────────────────────────────────────────────────────┤
* │ © 2026 사이트명. All rights reserved. Made with ❤️ │
* └─────────────────────────────────────────────────────────────────┘
*/
import React from 'react';
// 기본 컴포넌트 import
import { Div } from '../basic/Div';
import { A } from '../basic/A';
import { Button } from '../basic/Button';
import { H3 } from '../basic/H3';
import { H4 } from '../basic/H4';
import { P } from '../basic/P';
import { Ul } from '../basic/Ul';
import { Li } from '../basic/Li';
import { Footer as FooterBasic } from '../basic/Footer';
import { Icon } from '../basic/Icon';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'navigate',
params: { path },
});
};
interface SocialLinks {
github?: string;
twitter?: string;
discord?: string;
facebook?: string;
instagram?: string;
}
interface FooterLink {
label: string;
href: string;
}
interface FooterLinkGroup {
title: string;
links: FooterLink[];
}
interface FooterProps {
/** 사이트 이름 */
siteName?: string;
/** 사이트 설명 */
siteDescription?: string;
/** 저작권 텍스트 */
copyrightText?: string;
/** 소셜 미디어 링크 */
socialLinks?: SocialLinks;
/** 링크 그룹 (미지정 시 기본값 사용) */
linkGroups?: FooterLinkGroup[];
/** 추가 CSS 클래스 */
className?: string;
}
/**
* 사이트 푸터 컴포넌트
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "Footer",
* "props": {
* "siteName": "{{_global.settings.site_name}}",
* "siteDescription": "{{_global.settings.site_description}}",
* "copyrightText": "{{_global.settings.copyright_text}}",
* "socialLinks": {
* "github": "https://github.com/...",
* "twitter": "https://twitter.com/...",
* "discord": "https://discord.gg/..."
* }
* }
* }
* ```
*/
const Footer: React.FC<FooterProps> = ({
siteName = '그누보드7',
siteDescription,
copyrightText,
socialLinks = {},
linkGroups,
className = '',
}) => {
const currentYear = new Date().getFullYear();
// 기본 링크 그룹
const defaultLinkGroups: FooterLinkGroup[] = [
{
title: t('footer.community'),
links: [
{ label: t('nav.home'), href: '/' },
{ label: t('nav.popular'), href: '/boards/popular' },
{ label: t('footer.all_boards'), href: '/boards' },
],
},
{
title: t('footer.info'),
links: [
{ label: t('footer.about'), href: '/page/about' },
{ label: t('footer.faq'), href: '/page/faq' },
{ label: t('footer.contact'), href: '/page/contact' },
],
},
{
title: t('footer.policy'),
links: [
{ label: t('footer.terms'), href: '/page/terms' },
{ label: t('footer.privacy'), href: '/page/privacy' },
{ label: t('footer.refund'), href: '/page/refund' },
],
},
];
const groups = linkGroups || defaultLinkGroups;
// 소셜 아이콘 이름 매핑
const socialIconMap: Record<keyof SocialLinks, string> = {
github: 'github',
twitter: 'twitter',
discord: 'discord',
facebook: 'facebook',
instagram: 'instagram',
};
return (
<FooterBasic className={`bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800 ${className}`}>
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<Div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-8">
{/* 사이트 정보 */}
<Div className="lg:col-span-2">
<H3 className="text-lg font-bold text-gray-900 dark:text-white">{siteName}</H3>
{siteDescription && (
<P className="mt-2 text-sm text-gray-600 dark:text-gray-400">{siteDescription}</P>
)}
{/* 소셜 링크 */}
<Div className="mt-4 flex items-center gap-4">
{Object.entries(socialLinks).map(([type, url]) =>
url ? (
<A
key={type}
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
aria-label={type}
>
<Icon name={socialIconMap[type as keyof SocialLinks]} className="w-5 h-5" />
</A>
) : null
)}
</Div>
</Div>
{/* 링크 그룹 */}
{groups.map((group, index) => (
<Div key={index}>
<H4 className="text-sm font-semibold text-gray-900 dark:text-white uppercase tracking-wider">
{group.title}
</H4>
<Ul className="mt-4 space-y-2">
{group.links.map((link, linkIndex) => (
<Li key={linkIndex}>
<Button
onClick={() => navigate(link.href)}
className="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white cursor-pointer"
>
{link.label}
</Button>
</Li>
))}
</Ul>
</Div>
))}
</Div>
{/* 저작권 */}
<Div className="mt-8 pt-8 border-t border-gray-200 dark:border-gray-800 flex flex-col sm:flex-row justify-between items-center gap-4">
<P className="text-sm text-gray-500 dark:text-gray-400">
{copyrightText || `© ${currentYear} ${siteName}. All rights reserved.`}
</P>
<P className="text-sm text-gray-500 dark:text-gray-400">
{t('footer.powered_by')}
</P>
</Div>
</Div>
</FooterBasic>
);
};
export default Footer;
@@ -0,0 +1,488 @@
/**
* Header 컴포넌트
*
* 사이트 상단 헤더 컴포넌트입니다.
* 로고, 검색바, 네비게이션, 사용자 메뉴, 장바구니, 알림을 포함합니다.
*
* @see 화면 구성:
* ┌─────────────────────────────────────────────────────────────────┐
* │ [Logo] [검색바................] [🔔] [🛒(3)] [👤 닉네임 ▼] │
* ├─────────────────────────────────────────────────────────────────┤
* │ [홈] [🔥인기] [🛒쇼핑] [자유게시판] [질문답변] [갤러리] [더보기▼] │
* └─────────────────────────────────────────────────────────────────┘
*/
import React, { useState, useRef, useEffect } from 'react';
// 기본 컴포넌트 import
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Input } from '../basic/Input';
import { Span } from '../basic/Span';
import { Img } from '../basic/Img';
import { Icon } from '../basic/Icon';
import { Form } from '../basic/Form';
import { Nav } from '../basic/Nav';
import { Header as HeaderBasic } from '../basic/Header';
import { Hr } from '../basic/Hr';
import { A } from '../basic/A';
// ThemeToggle 컴포넌트 import
import { ThemeToggle } from './ThemeToggle';
// Avatar 컴포넌트 import
import { Avatar } from './Avatar';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'navigate',
params: { path },
});
};
interface Board {
id: number;
name: string;
slug: string;
icon?: string;
}
interface User {
uuid: string;
name: string;
avatar?: string;
is_admin?: boolean;
}
interface HeaderProps {
/** 사이트 로고 URL */
logo?: string;
/** 사이트 이름 */
siteName?: string;
/** 현재 로그인된 사용자 */
user?: User | null;
/** 장바구니 아이템 수 */
cartCount?: number;
/** 읽지 않은 알림 수 */
notificationCount?: number;
/** 게시판 목록 */
boards?: Board[];
/** 탭에 표시할 최대 게시판 수 */
maxVisibleBoards?: number;
/** 모바일 메뉴 열기 콜백 */
onMobileMenuOpen?: () => void;
/** 사용 가능한 언어 목록 */
availableLocales?: string[];
/** 현재 언어 */
currentLocale?: string;
/** 쇼핑몰 기본 경로 (예: "/shop", "/") */
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
}
/**
* 사이트 헤더 컴포넌트
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "Header",
* "props": {
* "logo": "{{_global.settings.site_logo}}",
* "siteName": "{{_global.settings.site_name}}",
* "user": "{{_global.currentUser}}",
* "cartCount": "{{_global.cartCount}}",
* "notificationCount": "{{_global.notificationCount}}",
* "boards": "{{boards.data}}",
* "maxVisibleBoards": 5
* }
* }
* ```
*/
const Header: React.FC<HeaderProps> = ({
logo,
siteName = '그누보드7',
user,
cartCount = 0,
notificationCount = 0,
boards = [],
maxVisibleBoards = 5,
onMobileMenuOpen,
availableLocales = [],
currentLocale = 'ko',
shopBase = '/shop',
className = '',
}) => {
const [searchQuery, setSearchQuery] = useState('');
const [showUserMenu, setShowUserMenu] = useState(false);
const [showMoreBoards, setShowMoreBoards] = useState(false);
const [dropdownPosition, setDropdownPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
const [currentPath, setCurrentPath] = useState(window.location.pathname);
const userMenuRef = useRef<HTMLDivElement>(null);
const moreButtonRef = useRef<HTMLDivElement>(null);
// 경로 변경 감지 (SPA 네비게이션 대응)
useEffect(() => {
const handlePopState = () => setCurrentPath(window.location.pathname);
window.addEventListener('popstate', handlePopState);
// G7Core의 navigate 이벤트 감지
const originalPushState = history.pushState;
history.pushState = function(...args) {
originalPushState.apply(this, args);
setCurrentPath(window.location.pathname);
};
return () => {
window.removeEventListener('popstate', handlePopState);
history.pushState = originalPushState;
};
}, []);
// 경로 매칭 헬퍼 함수
const isActiveRoute = (path: string, exact = false): boolean => {
if (exact) {
return currentPath === path;
}
return currentPath === path || currentPath.startsWith(path + '/');
};
// 쇼핑 관련 경로 체크 (products, cart, checkout, category 등)
const isShopActive = (): boolean => {
const base = shopBase === '/' ? '' : shopBase;
return currentPath.startsWith(`${base}/products`) ||
currentPath.startsWith(`${base}/cart`) ||
currentPath.startsWith(`${base}/checkout`) ||
currentPath.startsWith(`${base}/category`);
};
// 네비게이션 버튼 스타일
const getNavButtonClass = (isActive: boolean): string => {
const baseClass = 'px-3 py-2 text-sm font-medium whitespace-nowrap cursor-pointer rounded-lg transition-colors';
if (isActive) {
return `${baseClass} bg-gray-900 text-white dark:bg-white dark:text-gray-900`;
}
return `${baseClass} text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800`;
};
// 메뉴 외부 클릭 시 닫기
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
setShowUserMenu(false);
}
if (moreButtonRef.current && !moreButtonRef.current.contains(event.target as Node)) {
setShowMoreBoards(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const visibleBoards = boards.slice(0, maxVisibleBoards);
const hiddenBoards = boards.slice(maxVisibleBoards);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
if (searchQuery.trim()) {
navigate(`/search?q=${encodeURIComponent(searchQuery)}`);
}
};
const handleLogout = async () => {
// G7Core.dispatch를 사용하여 logout 핸들러 호출
// AuthManager가 토큰 삭제, 상태 초기화, 리다이렉트를 처리
(window as any).G7Core?.dispatch?.({
handler: 'logout',
});
};
// 언어 변경 핸들러
const handleLocaleChange = (locale: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'setLocale',
target: locale,
});
setShowUserMenu(false);
};
return (
<HeaderBasic className={`sticky top-0 z-50 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 ${className}`}>
{/* 상단 바 */}
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Div className="flex items-center justify-between h-16">
{/* 로고 */}
<Button onClick={() => navigate('/')} className="flex items-center gap-2 flex-shrink-0 cursor-pointer">
{logo ? (
<Img src={logo} alt={siteName} className="h-8" />
) : (
<Span className="text-xl font-bold text-gray-900 dark:text-white">{siteName}</Span>
)}
</Button>
{/* 검색바 (데스크톱) */}
<Form onSubmit={handleSearch} className="hidden md:flex flex-1 max-w-lg mx-8">
<Div className="relative w-full">
<Input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('common.search_placeholder')}
className="w-full px-4 py-2 pl-10 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<Icon
name="search"
className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500"
/>
</Div>
</Form>
{/* 우측 액션 버튼들 */}
<Div className="flex items-center gap-2">
{/* 다크모드 전환 */}
<ThemeToggle
autoText={t('common.theme.auto')}
lightText={t('common.theme.light')}
darkText={t('common.theme.dark')}
/>
{/* 알림 */}
<Button onClick={() => navigate('/notifications')} className="relative p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white cursor-pointer">
<Icon name="bell" className="w-5 h-5" />
{notificationCount > 0 && (
<Span className="absolute -top-1 -right-1 w-5 h-5 flex items-center justify-center text-xs bg-red-500 text-white rounded-full">
{notificationCount > 99 ? '99+' : notificationCount}
</Span>
)}
</Button>
{/* 장바구니 */}
<Button onClick={() => navigate(`${shopBase}/cart`)} className="relative p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white cursor-pointer">
<Icon name="shopping-cart" className="w-5 h-5" />
{cartCount > 0 && (
<Span className="absolute -top-1 -right-1 w-5 h-5 flex items-center justify-center text-xs bg-blue-500 text-white rounded-full">
{cartCount > 99 ? '99+' : cartCount}
</Span>
)}
</Button>
{/* 사용자 메뉴 */}
{user?.uuid ? (
<Div ref={userMenuRef} className="relative">
<Button
onClick={() => setShowUserMenu(!showUserMenu)}
className="flex items-center gap-2 p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
>
<Avatar
avatar={user.avatar}
name={user.name}
size="sm"
/>
<Span className="hidden sm:inline text-sm font-medium">{user.name}</Span>
<Icon name="chevron-down" className="w-4 h-4" />
</Button>
{/* 드롭다운 메뉴 */}
{showUserMenu && (
<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 py-1 z-50">
{/* 사용자 정보 헤더 */}
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<Div className="flex items-center gap-3">
<Avatar
avatar={user.avatar}
name={user.name}
size="md"
/>
<Div>
<Div className="text-sm font-medium text-gray-900 dark:text-white">{user.name}</Div>
<Div className="text-xs text-gray-500 dark:text-gray-400">{t('common.member')}</Div>
</Div>
</Div>
</Div>
{/* 메뉴 항목 */}
<Div className="py-1">
{/* 관리자 메뉴 (is_admin일 때만 표시) - 하이퍼링크로 전체 페이지 새로고침 */}
{user.is_admin && (
<>
<A
href="/admin"
className="block w-full text-left px-4 py-2 text-sm text-blue-600 dark:text-blue-400 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer font-medium"
>
<Icon name="settings" className="inline w-4 h-4 mr-2" />
{t('common.admin_menu')}
</A>
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
</>
)}
<Button onClick={() => { navigate('/mypage'); setShowUserMenu(false); }} className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer">
<Icon name="user" className="inline w-4 h-4 mr-2" />
{t('common.mypage')}
</Button>
<Button onClick={() => { navigate('/mypage/orders'); setShowUserMenu(false); }} className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer">
<Icon name="shopping-bag" className="inline w-4 h-4 mr-2" />
{t('mypage.tabs.orders')}
</Button>
<Button onClick={() => { navigate('/mypage/wishlist'); setShowUserMenu(false); }} className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer">
<Icon name="heart" className="inline w-4 h-4 mr-2" />
{t('mypage.tabs.wishlist')}
</Button>
</Div>
{/* 언어 선택 (availableLocales가 있을 때만 표시) */}
{availableLocales && availableLocales.length > 1 && (
<>
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
<Div className="py-1">
<Div className="px-4 py-2 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
{t('common.language')}
</Div>
{availableLocales.map((locale) => (
<Button
key={locale}
onClick={() => handleLocaleChange(locale)}
className={`block w-full text-left px-4 py-2 text-sm cursor-pointer ${
locale === currentLocale
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Icon name="globe" className="inline w-4 h-4 mr-2" />
{locale === 'ko' ? '한국어' : locale === 'en' ? 'English' : locale.toUpperCase()}
</Button>
))}
</Div>
</>
)}
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
<Button
onClick={handleLogout}
className="block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer"
>
<Icon name="log-out" className="inline w-4 h-4 mr-2" />
{t('auth.logout')}
</Button>
</Div>
)}
</Div>
) : (
<Div className="flex items-center gap-2">
<Button
onClick={() => navigate('/login')}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
>
{t('auth.login')}
</Button>
<Button
onClick={() => navigate('/register')}
className="px-4 py-2 text-sm font-medium text-white bg-emerald-500 rounded-lg hover:bg-emerald-600 cursor-pointer"
>
{t('auth.register_link')}
</Button>
</Div>
)}
{/* 모바일 햄버거 메뉴 */}
<Button
onClick={onMobileMenuOpen}
className="md:hidden p-2 text-gray-600 dark:text-gray-400"
>
<Icon name="menu" className="w-6 h-6" />
</Button>
</Div>
</Div>
</Div>
{/* 탭 네비게이션 */}
<Nav className="hidden md:block border-t border-gray-200 dark:border-gray-800">
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Div className="flex items-center gap-1 h-12 overflow-x-auto">
<Button onClick={() => navigate('/')} className={getNavButtonClass(isActiveRoute('/', true))}>
{t('nav.home')}
</Button>
<Button onClick={() => navigate('/boards/popular')} className={`flex items-center gap-1 ${getNavButtonClass(isActiveRoute('/boards/popular'))}`}>
<Span className="text-orange-500">🔥</Span>
{t('nav.popular')}
</Button>
<Button onClick={() => navigate(`${shopBase === '/' ? '' : shopBase}/products`)} className={`flex items-center gap-1 ${getNavButtonClass(isShopActive())}`}>
<Span>🛒</Span>
{t('nav.shop')}
</Button>
{/* 게시판 링크 */}
{visibleBoards.map((board) => (
<Button
key={board.id}
onClick={() => navigate(`/board/${board.slug}`)}
className={getNavButtonClass(isActiveRoute(`/board/${board.slug}`))}
>
{board.icon && <Span className="mr-1">{board.icon}</Span>}
{board.name}
</Button>
))}
{/* 더보기 드롭다운 */}
{hiddenBoards.length > 0 && (
<Div ref={moreButtonRef} className="relative">
<Button
onClick={() => {
if (!showMoreBoards && moreButtonRef.current) {
const rect = moreButtonRef.current.getBoundingClientRect();
setDropdownPosition({
top: rect.bottom + 4,
left: rect.left,
});
}
setShowMoreBoards(!showMoreBoards);
}}
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white"
>
{t('nav.more')}
<Icon name="chevron-down" className="w-4 h-4" />
</Button>
{showMoreBoards && (
<Div
className="fixed w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-50"
style={{ top: `${dropdownPosition.top}px`, left: `${dropdownPosition.left}px` }}
>
{hiddenBoards.map((board) => {
const isActive = isActiveRoute(`/board/${board.slug}`);
return (
<Button
key={board.id}
onClick={() => {
navigate(`/board/${board.slug}`);
setShowMoreBoards(false);
}}
className={`block w-full text-left px-4 py-2 text-sm cursor-pointer ${
isActive
? 'bg-gray-900 text-white dark:bg-white dark:text-gray-900'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
{board.icon && <Span className="mr-1">{board.icon}</Span>}
{board.name}
</Button>
);
})}
</Div>
)}
</Div>
)}
</Div>
</Div>
</Nav>
</HeaderBasic>
);
};
export default Header;
@@ -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', 'mark',
'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,266 @@
import React, { useCallback, useState } 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 { 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;
export interface HtmlEditorProps {
/**
* 콘텐츠 값
*/
content?: string;
/**
* 콘텐츠 변경 콜백
* Form 자동 바인딩을 위해 이벤트 객체 형식으로 전달
*/
onChange?: (event: { target: { name: string; value: string } }) => void;
/**
* 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만 표시
*
* @example
* // Layout JSON에서 사용 (자동 바인딩)
* {
* "type": "composite",
* "name": "HtmlEditor",
* "props": {
* "content": "{{_local.form?.content}}",
* "name": "content",
* "htmlFieldName": "content_mode"
* }
* }
*/
export const HtmlEditor: React.FC<HtmlEditorProps> = ({
content = '',
onChange,
isHtml: isHtmlProp = false,
onIsHtmlChange,
rows = 15,
placeholder = '',
label,
showHtmlModeToggle = true,
contentClassName = '',
purifyConfig,
className = '',
name = 'content',
htmlFieldName = 'content_mode',
readOnly = false,
}) => {
// HTML 모드 내부 상태 (Toggle과 동기화)
const [isHtml, setIsHtml] = useState(isHtmlProp);
// 콘텐츠 내부 상태 (입력값 즉시 반영용)
const [localContent, setLocalContent] = useState(content);
// 미리보기 모드 내부 상태 (컴포넌트 자체에서 관리)
const [previewMode, setPreviewMode] = useState(false);
// Props 변경 시 내부 상태 동기화
React.useEffect(() => {
setIsHtml(isHtmlProp);
}, [isHtmlProp]);
// content prop 변경 시 로컬 상태 동기화
React.useEffect(() => {
setLocalContent(content);
}, [content]);
// 콘텐츠 변경 핸들러
const handleContentChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newContent = e.target.value;
// 로컬 상태 즉시 업데이트 (입력 반응성)
setLocalContent(newContent);
// Props 콜백 호출 (G7Core.createChangeEvent 사용으로 ActionDispatcher 호환성 확보)
if (onChange) {
const event = G7Core()?.createChangeEvent?.({ value: newContent, name, type: 'textarea' })
?? { target: { name, value: newContent } };
onChange(event);
}
}, [onChange, name]);
// HTML 모드 변경 핸들러
const handleHtmlModeChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const isHtmlMode = e.target.checked;
// 로컬 상태 즉시 업데이트 (미리보기 버튼 표시용)
setIsHtml(isHtmlMode);
// HTML 모드 비활성화 시 미리보기 모드도 함께 비활성화
if (!isHtmlMode) {
setPreviewMode(false);
}
// Props 콜백 호출 (G7Core.createChangeEvent 사용으로 ActionDispatcher 호환성 확보)
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);
}, []);
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>
{/* 콘텐츠 편집 영역 */}
{!previewMode && (
<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={localContent}
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,339 @@
/**
* ImageGallery 컴포넌트
*
* yet-another-react-lightbox 기반 이미지 갤러리 컴포넌트입니다.
* 줌, 슬라이드쇼, 전체화면, 다운로드 기능을 지원합니다.
*
* @module composite/ImageGallery
*/
import React, { useState, useCallback, useEffect, useRef } from 'react';
import Lightbox, { Slide } from 'yet-another-react-lightbox';
import Zoom from 'yet-another-react-lightbox/plugins/zoom';
import Counter from 'yet-another-react-lightbox/plugins/counter';
import Slideshow from 'yet-another-react-lightbox/plugins/slideshow';
import Fullscreen from 'yet-another-react-lightbox/plugins/fullscreen';
import Thumbnails from 'yet-another-react-lightbox/plugins/thumbnails';
import 'yet-another-react-lightbox/styles.css';
import 'yet-another-react-lightbox/plugins/counter.css';
import 'yet-another-react-lightbox/plugins/thumbnails.css';
import { Button } from '../basic/Button';
import { I } from '../basic/I';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
G7Core?.t?.(key, params) ?? key;
// ========== Types ==========
export interface GalleryImage {
/** 이미지 표시용 URL (라이트박스에서 보여줄 이미지) */
src: string;
/** 다운로드용 URL (src와 다를 수 있음, 없으면 src 사용) */
downloadUrl?: string;
/** 이미지 제목/캡션 */
title?: string;
/** 이미지 설명 */
description?: string;
/** 썸네일 URL (없으면 src 사용) */
thumbnail?: string;
/** 원본 파일명 (다운로드 시 사용) */
filename?: string;
/** 다운로드 시 인증된 요청이 필요한지 여부 (기본값: false) */
downloadRequiresAuth?: boolean;
}
export interface ImageGalleryProps {
/** 갤러리에 표시할 이미지 배열 */
images: GalleryImage[];
/** 라이트박스 열기 여부 */
isOpen: boolean;
/** 라이트박스 닫기 콜백 */
onClose: () => void;
/** 시작 인덱스 (기본값: 0) */
startIndex?: number;
/** 줌 기능 활성화 (기본값: true) */
enableZoom?: boolean;
/** 슬라이드쇼 기능 활성화 (기본값: false) */
enableSlideshow?: boolean;
/** 전체화면 기능 활성화 (기본값: true) */
enableFullscreen?: boolean;
/** 이미지 카운터 표시 (기본값: true) */
showCounter?: boolean;
/** 다운로드 버튼 표시 (기본값: true) */
showDownload?: boolean;
/** 썸네일 네비게이션 표시 (기본값: true) */
showThumbnails?: boolean;
/** 커스텀 다운로드 핸들러 (제공 시 기본 다운로드 로직 대신 실행) */
onDownload?: (image: GalleryImage, index: number) => void;
}
// ========== Helper Functions ==========
/**
* 인증된 이미지 다운로드 (Blob으로 변환 후 다운로드)
*/
const downloadAuthenticatedFile = async (url: string, filename: string): Promise<void> => {
try {
const blob = await G7Core.api.get(url, {
responseType: 'blob',
});
if (blob) {
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(objectUrl);
}
} catch (error) {
console.error('Failed to download file:', error);
G7Core?.toast?.error?.(t('common.download_failed'));
}
};
/**
* 일반 파일 다운로드
*/
const downloadFile = (url: string, filename: string): void => {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
/**
* 이미지 다운로드 실행
*/
export const executeImageDownload = async (image: GalleryImage): Promise<void> => {
const downloadUrl = image.downloadUrl || image.src;
const filename = image.filename || image.title || 'image';
if (image.downloadRequiresAuth) {
await downloadAuthenticatedFile(downloadUrl, filename);
} else {
downloadFile(downloadUrl, filename);
}
};
// ========== Custom Download Button Component ==========
interface DownloadButtonProps {
image: GalleryImage;
index: number;
onDownload?: (image: GalleryImage, index: number) => void;
}
const DownloadButton: React.FC<DownloadButtonProps> = ({ image, index, onDownload }) => {
const [isDownloading, setIsDownloading] = useState(false);
const handleDownload = async (e: React.MouseEvent) => {
e.stopPropagation();
if (onDownload) {
onDownload(image, index);
return;
}
setIsDownloading(true);
try {
await executeImageDownload(image);
} finally {
setIsDownloading(false);
}
};
return (
<Button
type="button"
onClick={handleDownload}
disabled={isDownloading}
className="yarl__button flex items-center justify-center"
aria-label={t('common.download')}
title={t('common.download')}
>
{isDownloading ? (
<I className="fa-solid fa-spinner fa-spin text-white" />
) : (
<I className="fa-solid fa-download text-white" />
)}
</Button>
);
};
// ========== Main Component ==========
export const ImageGallery: React.FC<ImageGalleryProps> = ({
images,
isOpen,
onClose,
startIndex = 0,
enableZoom = true,
enableSlideshow = false,
enableFullscreen = true,
showCounter = true,
showDownload = true,
showThumbnails = true,
onDownload,
}) => {
// 현재 슬라이드 인덱스 (다운로드 버튼용)
const [currentIndex, setCurrentIndex] = useState(startIndex);
// 최신 인덱스를 ref로 추적 (클로저 문제 방지)
const currentIndexRef = useRef(startIndex);
// 이미지를 라이트박스 슬라이드 형식으로 변환 (썸네일 포함)
const slides: Slide[] = images.map((image) => ({
src: image.src,
title: image.title,
description: image.description,
}));
// 활성화할 플러그인 목록
const plugins = [];
if (enableZoom) plugins.push(Zoom);
if (enableSlideshow) plugins.push(Slideshow);
if (enableFullscreen) plugins.push(Fullscreen);
if (showCounter) plugins.push(Counter);
if (showThumbnails) plugins.push(Thumbnails);
// 현재 이미지
const currentImage = images[currentIndex];
// currentIndex가 변경되면 ref도 업데이트
useEffect(() => {
currentIndexRef.current = currentIndex;
}, [currentIndex]);
return (
<Lightbox
open={isOpen}
close={onClose}
slides={slides}
index={currentIndex}
plugins={plugins}
on={{
view: ({ index }) => {
if (index !== currentIndexRef.current) {
setCurrentIndex(index);
}
},
}}
zoom={{
maxZoomPixelRatio: 3,
zoomInMultiplier: 2,
doubleTapDelay: 300,
doubleClickDelay: 300,
doubleClickMaxStops: 2,
keyboardMoveDistance: 50,
wheelZoomDistanceFactor: 100,
pinchZoomDistanceFactor: 100,
scrollToZoom: true,
}}
carousel={{
finite: true,
preload: 2,
padding: '16px',
spacing: '30%',
}}
animation={{
fade: 250,
swipe: 500,
easing: {
fade: 'ease',
swipe: 'ease-out',
navigation: 'ease-in-out',
},
}}
controller={{
closeOnBackdropClick: true,
closeOnPullDown: true,
closeOnPullUp: true,
}}
thumbnails={{
position: 'bottom',
width: 120,
height: 80,
border: 2,
borderRadius: 4,
padding: 4,
gap: 16,
showToggle: false,
vignette: true,
}}
toolbar={{
buttons: [
showDownload && currentImage && (
<DownloadButton
key="download"
image={currentImage}
index={currentIndex}
onDownload={onDownload}
/>
),
'close',
].filter(Boolean),
}}
styles={{
container: {
backgroundColor: 'rgba(0, 0, 0, 0.9)',
},
}}
/>
);
};
// ========== Utility Hook ==========
/**
* ImageGallery를 쉽게 사용하기 위한 커스텀 훅
*
* @example
* const { openGallery, galleryProps } = useImageGallery();
*
* // 이미지 클릭 시
* <img onClick={() => openGallery(images, 0)} />
*
* // 컴포넌트 렌더링
* <ImageGallery {...galleryProps} />
*/
export const useImageGallery = () => {
const [isOpen, setIsOpen] = useState(false);
const [images, setImages] = useState<GalleryImage[]>([]);
const [startIndex, setStartIndex] = useState(0);
const openGallery = useCallback((galleryImages: GalleryImage[], index = 0) => {
setImages(galleryImages);
setStartIndex(index);
setIsOpen(true);
}, []);
const closeGallery = useCallback(() => {
setIsOpen(false);
}, []);
return {
isOpen,
openGallery,
closeGallery,
galleryProps: {
images,
isOpen,
onClose: closeGallery,
startIndex,
},
};
};
ImageGallery.displayName = 'ImageGallery';
export default ImageGallery;
@@ -0,0 +1,274 @@
/**
* MobileNav 컴포넌트
*
* 모바일 환경에서 표시되는 슬라이드 드로어 네비게이션입니다.
* 햄버거 메뉴 클릭 시 좌측에서 슬라이드하며 나타납니다.
*/
import React, { useEffect, useRef } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { P } from '../basic/P';
import { Icon } from '../basic/Icon';
import { Img } from '../basic/Img';
import { Nav } from '../basic/Nav';
import { Ul } from '../basic/Ul';
import { Li } from '../basic/Li';
/**
* G7Core 번역 함수
*/
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
/**
* G7Core navigate 헬퍼
*/
const navigate = (path: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'navigate',
params: { path },
});
};
interface Board {
id: number;
name: string;
slug: string;
icon?: string;
}
interface User {
id: number;
name: string;
avatar?: string;
}
interface MobileNavProps {
/** 드로어 열림 상태 */
isOpen: boolean;
/** 닫기 콜백 */
onClose: () => void;
/** 사이트 로고 URL */
logo?: string;
/** 사이트 이름 */
siteName?: string;
/** 현재 로그인된 사용자 */
user?: User | null;
/** 게시판 목록 */
boards?: Board[];
/** 장바구니 아이템 수 */
cartCount?: number;
}
/**
* 모바일 네비게이션 드로어
*
* @example
* ```tsx
* const [isOpen, setIsOpen] = useState(false);
*
* <MobileNav
* isOpen={isOpen}
* onClose={() => setIsOpen(false)}
* user={currentUser}
* boards={boards}
* />
* ```
*/
const MobileNav: React.FC<MobileNavProps> = ({
isOpen,
onClose,
logo,
siteName = '그누보드7',
user,
boards = [],
cartCount = 0,
}) => {
const drawerRef = useRef<HTMLDivElement>(null);
// ESC 키로 닫기
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onClose();
}
};
if (isOpen) {
document.addEventListener('keydown', handleEscape);
document.body.style.overflow = 'hidden';
}
return () => {
document.removeEventListener('keydown', handleEscape);
document.body.style.overflow = '';
};
}, [isOpen, onClose]);
// 오버레이 클릭으로 닫기
const handleOverlayClick = (e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose();
}
};
if (!isOpen) return null;
return (
<Div
className="fixed inset-0 z-50 lg:hidden"
onClick={handleOverlayClick}
>
{/* 오버레이 */}
<Div className="fixed inset-0 bg-black/50 transition-opacity" />
{/* 드로어 */}
<Div
ref={drawerRef}
className={`fixed inset-y-0 left-0 w-80 max-w-[85vw] bg-white dark:bg-gray-900 shadow-xl transform transition-transform duration-300 ${isOpen ? 'translate-x-0' : '-translate-x-full'}`}
>
{/* 헤더 */}
<Div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800">
<Button onClick={() => { onClose(); navigate('/'); }} className="flex items-center gap-2 cursor-pointer">
{logo ? (
<Img src={logo} alt={siteName} className="h-8" />
) : (
<Span className="text-xl font-bold text-gray-900 dark:text-white">{siteName}</Span>
)}
</Button>
<Button
onClick={onClose}
className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
aria-label="메뉴 닫기"
>
<Icon name="x" className="w-6 h-6" />
</Button>
</Div>
{/* 사용자 정보 */}
{user ? (
<Div className="p-4 border-b border-gray-200 dark:border-gray-800">
<Div className="flex items-center gap-3">
{user.avatar ? (
<Img src={user.avatar} alt={user.name} className="w-12 h-12 rounded-full" />
) : (
<Div className="w-12 h-12 rounded-full bg-blue-500 flex items-center justify-center text-white text-lg font-medium">
{(user.name || 'U').charAt(0).toUpperCase()}
</Div>
)}
<Div>
<P className="font-medium text-gray-900 dark:text-white">{user.name}</P>
<Button onClick={() => { onClose(); navigate('/mypage'); }} className="text-sm text-blue-600 dark:text-blue-400 hover:underline cursor-pointer">
{t('common.mypage')}
</Button>
</Div>
</Div>
</Div>
) : (
<Div className="p-4 border-b border-gray-200 dark:border-gray-800">
<Div className="flex gap-2">
<Button
onClick={() => { onClose(); navigate('/login'); }}
className="flex-1 py-2 text-center text-sm font-medium text-white bg-gray-900 dark:bg-white dark:text-gray-900 rounded-lg cursor-pointer"
>
{t('auth.login')}
</Button>
<Button
onClick={() => { onClose(); navigate('/register'); }}
className="flex-1 py-2 text-center text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer"
>
{t('auth.register')}
</Button>
</Div>
</Div>
)}
{/* 메뉴 */}
<Nav className="p-4 overflow-y-auto max-h-[calc(100vh-200px)]">
<Ul className="space-y-1">
{/* 기본 메뉴 */}
<Li>
<Button
onClick={() => { onClose(); navigate('/'); }}
className="flex items-center gap-3 px-3 py-2 w-full text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer"
>
<Icon name="home" className="w-5 h-5" />
{t('nav.home')}
</Button>
</Li>
<Li>
<Button
onClick={() => { onClose(); navigate('/popular'); }}
className="flex items-center gap-3 px-3 py-2 w-full text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer"
>
<Span className="text-orange-500">🔥</Span>
{t('nav.popular')}
</Button>
</Li>
<Li>
<Button
onClick={() => { onClose(); navigate('/shop'); }}
className="flex items-center gap-3 px-3 py-2 w-full text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer"
>
<Span>🛒</Span>
{t('nav.shop')}
</Button>
</Li>
<Li>
<Button
onClick={() => { onClose(); navigate('/cart'); }}
className="flex items-center gap-3 px-3 py-2 w-full text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer"
>
<Icon name="shopping-cart" className="w-5 h-5" />
{t('nav.cart')}
{cartCount > 0 && (
<Span className="ml-auto px-2 py-0.5 text-xs bg-blue-500 text-white rounded-full">
{cartCount}
</Span>
)}
</Button>
</Li>
{/* 구분선 */}
<Li className="my-4 border-t border-gray-200 dark:border-gray-800" />
{/* 게시판 메뉴 */}
<Li className="px-3 py-2 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
{t('nav.boards')}
</Li>
{boards.map((board) => (
<Li key={board.id}>
<Button
onClick={() => { onClose(); navigate(`/board/${board.slug}`); }}
className="flex items-center gap-3 px-3 py-2 w-full text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer"
>
{board.icon && <Span>{board.icon}</Span>}
{board.name}
</Button>
</Li>
))}
</Ul>
</Nav>
{/* 하단 링크 */}
<Div className="absolute bottom-0 left-0 right-0 p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900">
<Div className="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
<Button onClick={() => { onClose(); navigate('/about'); }} className="hover:text-gray-700 dark:hover:text-gray-200 cursor-pointer">
{t('footer.about')}
</Button>
<Button onClick={() => { onClose(); navigate('/terms'); }} className="hover:text-gray-700 dark:hover:text-gray-200 cursor-pointer">
{t('footer.terms')}
</Button>
<Button onClick={() => { onClose(); navigate('/privacy'); }} className="hover:text-gray-700 dark:hover:text-gray-200 cursor-pointer">
{t('footer.privacy')}
</Button>
</Div>
</Div>
</Div>
</Div>
);
};
export default MobileNav;
@@ -0,0 +1,230 @@
import React, { useEffect, useRef } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
export interface ModalProps {
isOpen: boolean;
onClose: () => void;
title?: string;
/**
* 타이틀 옆에 표시할 아이콘 이름 (Font Awesome)
* @example "lock", "trash", "warning"
*/
icon?: string;
/**
* 아이콘 색상 클래스 (Tailwind)
* @default "text-gray-500"
*/
iconClassName?: string;
/**
* Backdrop(오버레이) 클릭 시 모달 닫기 여부
* @default true
*/
closeOnBackdropClick?: boolean;
/**
* closeOnOverlayClick 별칭 (레이아웃 JSON 호환)
* @default true
*/
closeOnOverlayClick?: boolean;
/**
* 헤더 닫기 버튼 표시 여부
* @default true
*/
showCloseButton?: boolean;
/**
* ESC 키로 모달 닫기 허용 여부
* @default true
*/
closeOnEscape?: boolean;
children?: React.ReactNode;
width?: string;
className?: string;
style?: React.CSSProperties;
}
/**
* Modal 집합 컴포넌트
*
* Div + Button 기본 컴포넌트를 조합하여 모달 UI를 구성합니다.
* ESC 키 닫기, 포커스 트랩, 오버레이 클릭 닫기 기능을 포함합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Modal",
* "props": {
* "isOpen": "{{modals.userEdit}}",
* "title": "사용자 편집",
* "width": "600px"
* },
* "children": [...]
* }
*/
export const Modal: React.FC<ModalProps> = ({
isOpen,
onClose,
title,
icon,
iconClassName = 'text-gray-500 dark:text-gray-400',
closeOnBackdropClick = true,
closeOnOverlayClick,
showCloseButton = true,
closeOnEscape = true,
children,
width = '500px',
className = '',
style,
}) => {
// closeOnOverlayClick 별칭 지원 (레이아웃 JSON 호환)
const shouldCloseOnBackdrop = closeOnOverlayClick !== undefined
? closeOnOverlayClick
: closeOnBackdropClick;
const modalRef = useRef<HTMLDivElement>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
// ESC 키로 모달 닫기
useEffect(() => {
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape' && isOpen && closeOnEscape) {
onClose();
}
};
if (isOpen && closeOnEscape) {
document.addEventListener('keydown', handleEscape);
return () => document.removeEventListener('keydown', handleEscape);
}
}, [isOpen, onClose, closeOnEscape]);
// 포커스 트랩
useEffect(() => {
if (isOpen && modalRef.current) {
// 모달 열릴 때 현재 포커스 저장
previousFocusRef.current = document.activeElement as HTMLElement;
// 모달 내부 포커스 가능한 요소들
const focusableElements = modalRef.current.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const firstElement = focusableElements[0] as HTMLElement;
const lastElement = focusableElements[focusableElements.length - 1] as HTMLElement;
// 첫 번째 요소에 포커스
firstElement?.focus();
// Tab 키 핸들러 (포커스 트랩)
const handleTab = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return;
if (event.shiftKey) {
// Shift + Tab
if (document.activeElement === firstElement) {
event.preventDefault();
lastElement?.focus();
}
} else {
// Tab
if (document.activeElement === lastElement) {
event.preventDefault();
firstElement?.focus();
}
}
};
document.addEventListener('keydown', handleTab);
return () => {
document.removeEventListener('keydown', handleTab);
// 모달 닫힐 때 이전 포커스 복원
previousFocusRef.current?.focus();
};
}
}, [isOpen]);
// body 스크롤 방지
useEffect(() => {
if (isOpen) {
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = '';
};
}
}, [isOpen]);
if (!isOpen) return null;
// z-index를 style에서 가져오거나 기본값 50 사용
const zIndex = style?.zIndex ?? 50;
return (
<Div
className="fixed inset-0 flex items-center justify-center"
style={{ zIndex }}
onClick={shouldCloseOnBackdrop ? onClose : undefined}
>
{/* Overlay */}
<Div
className="absolute inset-0 bg-black/50"
aria-hidden="true"
/>
{/* Modal Content */}
<Div
ref={modalRef}
className={`relative bg-white dark:bg-gray-800 rounded-lg shadow-xl max-h-[90vh] overflow-hidden ${className}`}
style={{ width, ...(style ? { ...style, zIndex: undefined } : {}) }}
onClick={(e) => e.stopPropagation()}
role="dialog"
aria-modal="true"
aria-labelledby={title ? 'modal-title' : undefined}
>
{/* Header */}
{(title || icon || showCloseButton) && (
<Div className="flex items-center justify-between p-4">
{(title || icon) && (
<Div
id="modal-title"
className="flex items-center gap-3 text-lg font-semibold text-gray-900 dark:text-white"
>
{icon && <Icon name={icon} size="md" className={iconClassName} />}
{title}
</Div>
)}
{showCloseButton && (
<Button
onClick={onClose}
className="ml-auto text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 focus:outline-none"
aria-label={t('common.close_modal')}
>
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</Button>
)}
</Div>
)}
{/* Body */}
<Div className="px-6 py-4 overflow-y-auto max-h-[calc(90vh-140px)]">
{children}
</Div>
</Div>
</Div>
);
};
@@ -0,0 +1,70 @@
import React from 'react';
/**
* 페이지 로딩 컴포넌트 Props (엔진에서 전달)
*
* @since engine-v1.29.0
*/
export interface PageLoadingProps {
options?: {
text?: string;
};
}
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
/**
* 페이지 로딩 인디케이터 컴포넌트
*
* transition_overlay의 spinner 스타일에서 사용됩니다.
* 엔진은 타겟 요소 내부에 빈 컨테이너만 삽입하며,
* 포지셔닝/배경/z-index/다크모드 등 모든 비주얼 스타일은
* 이 컴포넌트가 전적으로 결정합니다.
*
* React 트리 외부에 렌더링되므로 인라인 스타일 사용.
*
* @since engine-v1.29.0
*/
const PageLoading: React.FC<PageLoadingProps> = ({ options }) => {
const isDark = document.documentElement.classList.contains('dark');
const bgColor = isDark ? 'rgb(17,24,39)' : 'rgb(249,250,251)';
const spinnerColor = isDark ? '#6b7280' : '#9ca3af';
const textColor = isDark ? '#9ca3af' : '#6b7280';
return (
<div
style={{
position: 'absolute',
inset: 0,
zIndex: 2147483647,
overflow: 'hidden',
background: bgColor,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'flex-start',
paddingTop: '15%',
gap: '12px',
}}
>
<div
style={{
width: '32px',
height: '32px',
border: `3px solid ${spinnerColor}`,
borderTopColor: 'transparent',
borderRadius: '50%',
animation: 'g7-spin 0.8s linear infinite',
}}
/>
<span style={{ color: textColor, fontSize: '14px' }}>
{options?.text || t('nav.loading')}
</span>
</div>
);
};
export default PageLoading;
@@ -0,0 +1,755 @@
import React from 'react';
/**
* 레이아웃 컴포넌트 정의 (엔진에서 전달하는 트리 구조)
*/
interface LayoutComponent {
name?: string;
type?: string;
className?: string;
props?: Record<string, any>;
children?: LayoutComponent[];
iteration?: {
source?: string;
item_var?: string;
index_var?: string;
};
if?: string;
responsive?: {
desktop?: { props?: Record<string, any> };
tablet?: { props?: Record<string, any> };
};
}
/**
* 스켈레톤 컴포넌트 Props (엔진에서 전달)
*/
export interface PageSkeletonProps {
/** 레이아웃 JSON의 components 배열 (전체 컴포넌트 트리) */
components: LayoutComponent[];
/** 스켈레톤 옵션 */
options: {
animation: 'pulse' | 'wave' | 'none';
iteration_count: number;
};
}
/** Tailwind 반응형 breakpoint (px) */
const TAILWIND_BREAKPOINTS: Record<string, number> = {
sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536,
};
/** CSS display 관련 클래스 (Tailwind) */
const DISPLAY_CLASSES = new Set([
'hidden', 'block', 'inline-block', 'inline', 'flex', 'inline-flex',
'grid', 'inline-grid', 'table', 'table-row', 'table-cell',
'contents', 'list-item', 'flow-root',
]);
/** 레이아웃 컨테이너 컴포넌트 이름 목록 (자식 순회) */
const LAYOUT_CONTAINERS = new Set([
'Div', 'Flex', 'Grid', 'Section', 'Article', 'Nav', 'Aside',
'Main', 'Header', 'Footer', 'Fragment', 'Form', 'Container',
]);
/** 텍스트 컴포넌트 → 스켈레톤 바로 치환 */
const TEXT_COMPONENTS = new Set([
'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'P', 'Span', 'Label', 'A',
'Strong', 'Em', 'Small', 'Badge',
]);
/** 인풋 컴포넌트 → 스켈레톤 사각형으로 치환 */
const INPUT_COMPONENTS = new Set([
'Input', 'Textarea', 'Select', 'Checkbox', 'Radio', 'Toggle',
'DatePicker', 'TagInput', 'SearchBar',
]);
/** 미디어 컴포넌트 → 큰 사각형 */
const MEDIA_COMPONENTS = new Set([
'Img', 'Image', 'Avatar', 'AvatarUploader', 'ImageGallery',
'ProductImageViewer', 'FileUploader',
]);
/** 복합 컴포넌트 → 특화된 스켈레톤 */
const COMPOSITE_SKELETONS: Record<string, (animClass: string, iterCount: number) => React.ReactElement> = {
DataGrid: (animClass, iterCount) => (
<div className="w-full border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
<div className={`h-10 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 ${animClass}`}>
<div className="flex items-center h-full px-4 gap-8">
<div className="h-3 w-16 bg-gray-300 dark:bg-gray-600 rounded" />
<div className="h-3 w-24 bg-gray-300 dark:bg-gray-600 rounded" />
<div className="h-3 w-20 bg-gray-300 dark:bg-gray-600 rounded" />
<div className="h-3 w-16 bg-gray-300 dark:bg-gray-600 rounded" />
</div>
</div>
{Array.from({ length: iterCount }, (_, i) => (
<div key={i} className={`h-12 border-b border-gray-100 dark:border-gray-800 ${animClass}`} style={{ animationDelay: `${i * 75}ms` }}>
<div className="flex items-center h-full px-4 gap-8">
<div className="h-3 w-12 bg-gray-200 dark:bg-gray-700 rounded" />
<div className="h-3 flex-1 bg-gray-200 dark:bg-gray-700 rounded" />
<div className="h-3 w-16 bg-gray-100 dark:bg-gray-800 rounded" />
<div className="h-3 w-14 bg-gray-100 dark:bg-gray-800 rounded" />
</div>
</div>
))}
</div>
),
Pagination: (animClass) => (
<div className="flex justify-center gap-1.5 py-3">
{Array.from({ length: 5 }, (_, i) => (
<div key={i} className={`w-8 h-8 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
))}
</div>
),
Tabs: (animClass) => (
<div>
<div className="flex gap-4 border-b border-gray-200 dark:border-gray-700 pb-2 mb-3">
{Array.from({ length: 3 }, (_, i) => (
<div key={i} className={`h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
))}
</div>
<div className={`h-32 bg-gray-100 dark:bg-gray-800 rounded ${animClass}`} />
</div>
),
TabNavigation: (animClass) => (
<div className="flex gap-4 border-b border-gray-200 dark:border-gray-700 pb-2">
{Array.from({ length: 3 }, (_, i) => (
<div key={i} className={`h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
))}
</div>
),
ProductCard: (animClass) => (
<div className="rounded-lg overflow-hidden">
<div className={`h-48 w-full bg-gray-200 dark:bg-gray-700 ${animClass}`} />
<div className="p-3 space-y-2">
<div className={`h-3.5 w-3/4 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
<div className={`h-4 w-1/3 bg-gray-300 dark:bg-gray-600 rounded ${animClass}`} />
</div>
</div>
),
UserInfo: (animClass) => (
<div className={`h-3 w-14 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
),
QuantitySelector: (animClass) => (
<div className={`h-9 w-28 bg-gray-100 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 ${animClass}`} />
),
Header: (animClass) => (
<header className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center gap-8">
<div className={`h-8 w-24 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
<div className="hidden lg:flex items-center gap-6">
{Array.from({ length: 4 }, (_, i) => (
<div key={i} className={`h-3.5 w-16 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
))}
</div>
</div>
<div className="flex items-center gap-4">
{Array.from({ length: 3 }, (_, i) => (
<div key={i} className={`h-8 w-8 bg-gray-200 dark:bg-gray-700 rounded-full ${animClass}`} />
))}
</div>
</div>
</div>
</header>
),
Footer: (animClass) => (
<footer className="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 mt-auto">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="flex flex-col items-center gap-4">
<div className={`h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />
<div className={`h-3 w-48 bg-gray-100 dark:bg-gray-800 rounded ${animClass}`} />
<div className="flex gap-3">
{Array.from({ length: 3 }, (_, i) => (
<div key={i} className={`h-6 w-6 bg-gray-200 dark:bg-gray-700 rounded-full ${animClass}`} />
))}
</div>
<div className={`h-3 w-40 bg-gray-100 dark:bg-gray-800 rounded ${animClass}`} />
</div>
</div>
</footer>
),
Modal: () => <></>,
Toast: () => <></>,
ConfirmDialog: () => <></>,
};
/**
* 조건부 분기 필터링 — 로딩/에러 상태 스킵, 콘텐츠 브랜치 선택
*
* 레이아웃 JSON에서 로딩/에러/콘텐츠 상태가 sibling으로 if 조건으로 분기되는 패턴이 일반적.
* 스켈레톤은 "데이터 로드 완료 후 실제 UI" 형태를 보여줘야 하므로,
* 로딩/에러 분기는 스킵하고 콘텐츠 분기(가장 풍부한 트리)만 렌더링.
*/
function filterChildren(children: LayoutComponent[]): LayoutComponent[] {
if (!children || children.length === 0) return [];
const withIf = children.filter(c => c.if);
const withoutIf = children.filter(c => !c.if);
// if 조건 없는 컴포넌트가 있고, if 있는 것도 있는 경우
// → if 없는 것은 항상 렌더, if 있는 것 중 부정 조건 스킵
if (withoutIf.length > 0 && withIf.length > 0) {
const positiveIf = withIf.filter(c => !isNegativeCondition(c.if!));
// 긍정 조건 여러 개가 상호 배타적 값 분기(=== 'value')이면 richest만 선택
// 예: type === 'basic', type === 'gallery', type === 'card'
if (positiveIf.length > 1 && areMutuallyExclusiveBranches(positiveIf)) {
return [...withoutIf, pickRichestBranch(positiveIf)];
}
return [...withoutIf, ...positiveIf];
}
// 모든 컴포넌트가 if 조건을 가진 경우 → 상호 배타적 분기
// → 부정 조건 스킵 후, 나머지 중 가장 풍부한 브랜치 선택
if (withIf.length > 1 && withoutIf.length === 0) {
const positive = withIf.filter(c => !isNegativeCondition(c.if!));
if (positive.length === 0) {
// 모두 부정 조건 (로딩/에러 상태만) → 전체 스킵
// 스켈레톤은 "데이터 로드 완료 후 UI"를 보여주므로 로딩/에러 분기 불필요
return [];
}
if (positive.length === 1) return positive;
// 긍정 조건 여러 개 → 가장 풍부한 것 선택
return [pickRichestBranch(positive)];
}
return children;
}
/**
* 부정 조건 판별 — 로딩/에러 상태를 나타내는 if 조건
*/
function isNegativeCondition(ifExpr: string): boolean {
const trimmed = ifExpr.replace(/^\{\{|\}\}$/g, '').trim();
return trimmed.startsWith('!') ||
/\b(hasError|isError|isLoading|error|Error)\b/.test(trimmed) ||
// empty state 패턴: length === 0, total === 0, count === 0 등
/===\s*0\s*(\)|\}|$)/.test(trimmed);
}
/**
* 상호 배타적 값 분기 판별
*
* 여러 if 조건이 같은 변수에 대한 `=== 'value'` 패턴이면 상호 배타적.
* 예: type === 'basic', type === 'gallery', type === 'card'
* → 스켈레톤에서 하나만 선택해야 중복 렌더링 방지.
*/
function areMutuallyExclusiveBranches(branches: LayoutComponent[]): boolean {
if (branches.length < 2) return false;
// 각 조건에서 "expr === 'value'" 패턴의 기본 표현식(expr) 추출
const baseExpressions: string[] = [];
for (const branch of branches) {
const trimmed = (branch.if || '').replace(/^\{\{|\}\}$/g, '').trim();
// === 'value' 또는 === "value" 패턴 찾기
const match = trimmed.match(/^(.+?)\s*===\s*['"]/);
if (!match) {
// || 로 연결된 복합 조건에서도 첫 번째 === 패턴 추출 (fallback 분기)
const orMatch = trimmed.match(/(.+?)\s*===\s*['"]/);
if (!orMatch) return false;
baseExpressions.push(orMatch[1].trim());
} else {
baseExpressions.push(match[1].trim());
}
}
// 모든 분기가 같은 기본 표현식을 참조하면 상호 배타적
const first = baseExpressions[0];
return baseExpressions.every(expr => expr === first);
}
/**
* 자손 수 기준 가장 풍부한 분기 선택
*/
function pickRichestBranch(branches: LayoutComponent[]): LayoutComponent {
return branches.reduce((best, curr) =>
countDescendants(curr) > countDescendants(best) ? curr : best
);
}
/**
* 컴포넌트 트리의 총 자손 수 계산
*/
function countDescendants(component: LayoutComponent): number {
if (!component.children) return 0;
return component.children.length +
component.children.reduce((sum, child) => sum + countDescendants(child), 0);
}
/**
* className 내 {{...}} 표현식 해석
*
* 레이아웃 JSON의 className에 {{expr ? 'classA' : 'classB'}} 같은 표현식이 포함될 수 있음.
* 스켈레톤에서는 데이터가 없으므로 표현식을 평가할 수 없음.
* → 삼항 연산자의 true 분기 값을 추출하여 적용 (기본값으로 사용).
* → 단순 표현식(삼항 아닌 경우)은 제거.
*/
function resolveExpressions(className: string): string {
if (!className.includes('{{')) return className;
return className.replace(/\{\{([^}]+)\}\}/g, (_, expr: string) => {
// 삼항 연산자: condition ? 'value1' : 'value2' → value1 추출
const ternaryMatch = expr.match(/\?[\s]*['"]([^'"]*)['"]\s*:\s*['"]/);
if (ternaryMatch) {
return ternaryMatch[1];
}
// 삼항 아닌 단순 표현식 → 제거
return '';
});
}
/**
* 스켈레톤 렌더에 적합한 className 변환
*
* 1. {{...}} 표현식 해석 (삼항 → true 분기, 단순 표현식 → 제거)
* 2. 레이아웃 구조 클래스(flex, grid, gap, padding, margin, max-width 등)는 원본 유지.
* 3. 시각적 클래스(배경색, 텍스트색, 테두리, 그림자 등)는 제거.
*/
function sanitizeClassName(className: string, name: string): string {
if (!className) return '';
// 시각적 클래스 제거 (표현식/반응형은 renderSkeletonNode에서 이미 해석됨)
let sanitized = className;
sanitized = sanitized
.replace(/\b(bg-\S+|text-\S+|border\b|border-\S+|shadow\S*|ring-\S+|outline-\S+|divide-\S+|opacity-\S+|font-\S+|tracking-\S+|leading-\S+|whitespace-\S+|truncate|line-clamp-\S+|underline|no-underline|decoration-\S+|cursor-\S+|hover:\S+|focus:\S+|active:\S+|group-hover:\S+|transition\S*|duration-\S+|ease-\S+|animate-\S+|dark:\S+)\b/g, '')
.replace(/\s{2,}/g, ' ')
.trim();
// Grid: 숫자 컬럼 수 유지 (arbitrary value [...]는 보존 — extractArbitraryGridCols에서 처리)
if (name === 'Grid' || /\bgrid-cols-\d/.test(sanitized)) {
sanitized = sanitized.replace(/\bgrid-cols-(\d+)/g, (_, val) => {
const num = parseInt(val);
return num > 4 ? `grid-cols-${Math.ceil(num / 2)}` : `grid-cols-${num}`;
});
}
return sanitized;
}
/**
* Flex/Grid 컴포넌트의 레이아웃 props를 Tailwind 클래스로 변환
*
* Flex, Grid 컴포넌트는 justify, align, gap 등을 별도 props로 받아
* 실제 렌더 시 Tailwind 클래스로 변환한다.
* 스켈레톤은 이 컴포넌트들을 plain <div>로 대체하므로,
* props → Tailwind 변환을 여기서 수행하여 className에 병합해야 한다.
*
* @since engine-v1.17.0
*/
function resolveLayoutProps(component: LayoutComponent): string {
const { name, props } = component;
if (!props || !name) return '';
const classes: string[] = [];
if (name === 'Flex') {
classes.push('flex');
const direction = props.direction || 'row';
const directionMap: Record<string, string> = {
row: 'flex-row', 'row-reverse': 'flex-row-reverse',
col: 'flex-col', 'col-reverse': 'flex-col-reverse',
};
if (directionMap[direction]) classes.push(directionMap[direction]);
const justify = props.justify || 'start';
const justifyMap: Record<string, string> = {
start: 'justify-start', end: 'justify-end', center: 'justify-center',
between: 'justify-between', around: 'justify-around', evenly: 'justify-evenly',
};
if (justifyMap[justify]) classes.push(justifyMap[justify]);
const align = props.align || 'stretch';
const alignMap: Record<string, string> = {
start: 'items-start', end: 'items-end', center: 'items-center',
baseline: 'items-baseline', stretch: 'items-stretch',
};
if (alignMap[align]) classes.push(alignMap[align]);
const wrap = props.wrap || 'nowrap';
const wrapMap: Record<string, string> = {
wrap: 'flex-wrap', nowrap: 'flex-nowrap', 'wrap-reverse': 'flex-wrap-reverse',
};
if (wrapMap[wrap]) classes.push(wrapMap[wrap]);
if (props.gap && props.gap > 0) classes.push(`gap-${props.gap}`);
}
if (name === 'Grid') {
classes.push('grid');
const cols = props.cols || 1;
classes.push(`grid-cols-${cols}`);
if (props.responsive) {
const r = props.responsive;
if (r.sm) classes.push(`sm:grid-cols-${r.sm}`);
if (r.md) classes.push(`md:grid-cols-${r.md}`);
if (r.lg) classes.push(`lg:grid-cols-${r.lg}`);
if (r.xl) classes.push(`xl:grid-cols-${r.xl}`);
if (r['2xl']) classes.push(`2xl:grid-cols-${r['2xl']}`);
}
if (props.gap !== undefined && props.gap > 0) classes.push(`gap-${props.gap}`);
if (props.rowGap !== undefined && props.rowGap > 0) classes.push(`gap-y-${props.rowGap}`);
if (props.colGap !== undefined && props.colGap > 0) classes.push(`gap-x-${props.colGap}`);
}
return classes.join(' ');
}
/**
* 애니메이션 클래스 결정
*/
function getAnimationClass(animation: string): string {
switch (animation) {
case 'pulse':
return 'animate-pulse';
case 'wave':
return 'animate-pulse'; // wave는 별도 CSS 필요, pulse로 폴백
case 'none':
return '';
default:
return 'animate-pulse';
}
}
/**
* 자식 컴포넌트 렌더링 (조건부 분기 필터링 적용)
*/
function renderChildren(
children: LayoutComponent[] | undefined,
animClass: string,
iterCount: number,
): (React.ReactElement | null)[] {
if (!children || children.length === 0) return [];
const filtered = filterChildren(children);
return filtered.map((child, i) =>
renderSkeletonNode(child, animClass, iterCount, i)
);
}
/**
* 현재 뷰포트에 맞는 className 결정
*
* responsive 속성이 있으면 현재 window 크기에 따라 적절한 className 선택.
* - desktop (lg, 1024px+): responsive.desktop.props.className
* - tablet (md, 768px+): responsive.tablet.props.className
* - 기본: props.className
*/
function resolveClassName(component: LayoutComponent): string {
const baseClassName = component.props?.className || component.className || '';
if (!component.responsive) return baseClassName;
const width = typeof window !== 'undefined' ? window.innerWidth : 1024;
if (width >= 1024 && component.responsive.desktop?.props?.className) {
return component.responsive.desktop.props.className;
}
if (width >= 768 && component.responsive.tablet?.props?.className) {
return component.responsive.tablet.props.className;
}
return baseClassName;
}
/**
* Tailwind 반응형 display 클래스를 현재 뷰포트 기준으로 해석
*
* 레이아웃 JSON의 className에 `hidden lg:grid`, `lg:hidden` 같은 Tailwind 반응형 패턴이 포함됨.
* Tailwind은 빌드 시 CSS로 처리하지만, 스켈레톤은 런타임에서 JS로 해석해야 함.
*
* 동작:
* 1. className에서 display 관련 클래스(hidden, flex, grid 등) + 반응형 접두사(lg:grid 등) 추출
* 2. Tailwind cascade 규칙 적용: base → sm → md → lg → xl → 2xl 순서로 현재 width에 맞는 display 결정
* 3. hidden이면 컴포넌트 숨김, 아니면 해석된 display 클래스 + 나머지 클래스 반환
*/
function resolveResponsiveDisplay(className: string): { visible: boolean; className: string } {
const width = typeof window !== 'undefined' ? window.innerWidth : 1024;
const tokens = className.split(/\s+/).filter(Boolean);
const displayEntries: Array<{ breakpoint: number; display: string }> = [];
const otherClasses: string[] = [];
for (const token of tokens) {
// 반응형 접두사 + display 클래스: "lg:grid", "sm:flex", "md:hidden"
const responsiveMatch = token.match(/^(sm|md|lg|xl|2xl):(.+)$/);
if (responsiveMatch) {
const [, prefix, cls] = responsiveMatch;
if (DISPLAY_CLASSES.has(cls)) {
displayEntries.push({
breakpoint: TAILWIND_BREAKPOINTS[prefix] || 0,
display: cls,
});
continue;
}
// 반응형 접두사지만 display가 아닌 클래스 (lg:gap-4 등) → 뷰포트 체크 후 포함
if ((TAILWIND_BREAKPOINTS[prefix] || 0) <= width) {
otherClasses.push(cls); // 접두사 제거하고 포함
}
continue;
}
// 기본(접두사 없는) display 클래스: "hidden", "flex", "grid"
if (DISPLAY_CLASSES.has(token)) {
displayEntries.push({ breakpoint: 0, display: token });
continue;
}
otherClasses.push(token);
}
// display 클래스가 없으면 그대로 반환
if (displayEntries.length === 0) {
return { visible: true, className };
}
// breakpoint 오름차순 정렬 후 cascade 적용
displayEntries.sort((a, b) => a.breakpoint - b.breakpoint);
let effectiveDisplay = '';
for (const entry of displayEntries) {
if (entry.breakpoint <= width) {
effectiveDisplay = entry.display;
}
}
// 해당 뷰포트에 적용되는 display가 없으면 첫 번째(base) 사용
if (!effectiveDisplay) {
effectiveDisplay = displayEntries[0].display;
}
const visible = effectiveDisplay !== 'hidden';
const resolvedClassName = visible
? [effectiveDisplay, ...otherClasses].join(' ')
: '';
return { visible, className: resolvedClassName };
}
/**
* className에서 arbitrary grid-cols-[...] 값을 추출하여 inline style로 변환
*
* Tailwind의 arbitrary value `grid-cols-[60px_minmax(300px,1fr)_160px]`는
* 빌드 시 동적 표현식({{...}}) 안에 있으면 purge되어 CSS에 포함되지 않음.
* → inline style `gridTemplateColumns`로 변환하여 런타임에서 직접 적용.
*/
function extractArbitraryGridCols(className: string): { className: string; style?: React.CSSProperties } {
const match = className.match(/\bgrid-cols-\[([^\]]+)\]/);
if (!match) return { className };
const value = match[1].replace(/_/g, ' ');
const cleanedClassName = className
.replace(/\bgrid-cols-\[([^\]]+)\]/, '')
.replace(/\s{2,}/g, ' ')
.trim();
return {
className: cleanedClassName,
style: { gridTemplateColumns: value },
};
}
/**
* 단일 컴포넌트를 스켈레톤으로 변환
*/
function renderSkeletonNode(
component: LayoutComponent,
animClass: string,
iterCount: number,
index: number,
): React.ReactElement | null {
const { name, children, iteration } = component;
// 1. responsive 속성에서 뷰포트에 맞는 className 선택
const rawClassName = resolveClassName(component);
// 1.5. Flex/Grid 레이아웃 props → Tailwind 클래스 병합
const layoutClasses = resolveLayoutProps(component);
const mergedClassName = layoutClasses
? `${layoutClasses} ${rawClassName}`.trim()
: rawClassName;
// 2. {{...}} 표현식 해석 (삼항 → true 분기)
const exprResolved = resolveExpressions(mergedClassName);
// 3. Tailwind 반응형 display 클래스 해석 (hidden lg:grid → grid at desktop)
const responsive = resolveResponsiveDisplay(exprResolved);
if (!name) return null;
// 현재 뷰포트에서 숨겨진 컴포넌트 → 스킵
if (!responsive.visible) return null;
const className = responsive.className;
// iteration 블록: 기본 반복 횟수만큼 반복 생성
if (iteration) {
return (
<React.Fragment key={index}>
{Array.from({ length: iterCount }, (_, i) => (
renderSkeletonNode(
{ ...component, iteration: undefined },
animClass,
iterCount,
i,
)
))}
</React.Fragment>
);
}
// 복합 컴포넌트 특화 스켈레톤
if (COMPOSITE_SKELETONS[name]) {
return (
<div key={index} className={className}>
{COMPOSITE_SKELETONS[name](animClass, iterCount)}
</div>
);
}
// 레이아웃 컨테이너: className 유지, 자식 재귀 순회
if (LAYOUT_CONTAINERS.has(name)) {
const sanitized = sanitizeClassName(className, name);
// 자식 없는 leaf 컨테이너 → 스켈레톤 바로 표시
if (!children || children.length === 0) {
const hasDimension = /\b(h-\S|w-\S)/.test(sanitized);
const barClass = hasDimension
? `${sanitized} bg-gray-200 dark:bg-gray-700 rounded ${animClass}`
: `${sanitized} h-3.5 w-full bg-gray-200 dark:bg-gray-700 rounded ${animClass}`.trim();
return <div key={index} className={barClass} />;
}
// 자식 렌더링 (조건부 분기 필터링 적용)
const renderedChildren = renderChildren(children, animClass, iterCount);
const hasContent = renderedChildren.length > 0 && renderedChildren.some(c => c !== null);
// 모든 자식이 필터링됨 (로딩/에러 wrapper 등) → 컨테이너 자체 스킵
if (!hasContent) return null;
// arbitrary grid-cols-[...] → inline style로 변환
const gridResult = extractArbitraryGridCols(sanitized);
return (
<div key={index} className={gridResult.className} style={gridResult.style}>
{renderedChildren}
</div>
);
}
// 비-컨테이너 컴포넌트: 원본 className에서 시각적 클래스(색상 등)를 제거
// 스켈레톤 바의 색상은 고정(gray-200)이므로 원본 bg-red-500 등이 누출되면 안 됨
const sanitizedLeafClass = sanitizeClassName(className, name);
// 텍스트 컴포넌트: 회색 바
if (TEXT_COMPONENTS.has(name)) {
const heightMap: Record<string, string> = {
H1: 'h-7', H2: 'h-6', H3: 'h-5', H4: 'h-5', H5: 'h-4', H6: 'h-4',
P: 'h-3.5', Span: 'h-3', Label: 'h-3', A: 'h-3.5',
Badge: 'h-5 w-16',
};
const widthMap: Record<string, string> = {
H1: 'w-3/5', H2: 'w-2/5', H3: 'w-1/3', H4: 'w-1/3', H5: 'w-1/4', H6: 'w-1/4',
P: 'w-full', Span: 'w-1/4', Label: 'w-1/4', A: 'w-1/3',
Strong: 'w-1/5', Em: 'w-1/4', Small: 'w-1/5', Badge: 'w-16',
};
const height = heightMap[name] || 'h-3.5';
const width = widthMap[name] || 'w-full';
const spacing = name.startsWith('H') ? 'mb-2 mt-1' : 'mb-1.5';
return (
<div key={index} className={`${height} ${width} bg-gray-200 dark:bg-gray-700 rounded ${animClass} ${spacing} ${sanitizedLeafClass}`.trim()} />
);
}
// 인풋 컴포넌트: 사각형
if (INPUT_COMPONENTS.has(name)) {
if (name === 'Textarea') {
return <div key={index} className={`h-20 w-full bg-gray-100 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 mb-2 ${animClass}`} />;
}
if (name === 'Checkbox' || name === 'Radio' || name === 'Toggle') {
return <div key={index} className={`h-5 w-5 bg-gray-200 dark:bg-gray-700 rounded mb-1.5 ${animClass}`} />;
}
return <div key={index} className={`h-9 w-full bg-gray-100 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 mb-2 ${animClass}`} />;
}
// 미디어 컴포넌트: 큰 사각형
if (MEDIA_COMPONENTS.has(name)) {
if (name === 'Avatar' || name === 'AvatarUploader') {
return <div key={index} className={`h-10 w-10 bg-gray-200 dark:bg-gray-700 rounded-full ${animClass}`} />;
}
if (name === 'ProductImageViewer') {
return <div key={index} className={`h-80 w-full bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />;
}
return <div key={index} className={`h-40 w-full bg-gray-200 dark:bg-gray-700 rounded mb-2 ${animClass}`} />;
}
// Button: children이 있으면 래퍼(컨테이너)로 처리, 없으면 바
if (name === 'Button') {
if (children && children.length > 0) {
const sanitized = sanitizeClassName(className, name);
const renderedChildren = renderChildren(children, animClass, iterCount);
const hasContent = renderedChildren.length > 0 && renderedChildren.some(c => c !== null);
if (!hasContent) return null;
// 원본 className에 border/rounded가 있으면 실제 버튼 형태 → 스켈레톤 경계 추가
const hasBorderStyle = /\b(border|rounded|px-\d|py-\d)/.test(rawClassName);
const borderClass = hasBorderStyle
? 'border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 rounded-lg'
: '';
return (
<div key={index} className={`${sanitized} ${borderClass}`.trim()}>
{renderedChildren}
</div>
);
}
return <div key={index} className={`h-9 w-24 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />;
}
// Icon
if (name === 'Icon') {
return <div key={index} className={`h-5 w-5 bg-gray-200 dark:bg-gray-700 rounded ${animClass}`} />;
}
// 기타: children이 있으면 컨테이너로, 없으면 범용 바
if (children && children.length > 0) {
return (
<div key={index} className={sanitizedLeafClass}>
{renderChildren(children, animClass, iterCount)}
</div>
);
}
// 기본 폴백: 범용 스켈레톤 바
return <div key={index} className={`h-3.5 w-full bg-gray-200 dark:bg-gray-700 rounded mb-1.5 ${animClass}`} />;
}
/**
* PageSkeleton — 단일 스켈레톤 렌더러 컴포넌트
*
* 엔진이 레이아웃 JSON의 컴포넌트 트리를 props로 전달하면,
* 재귀적으로 순회하며 각 컴포넌트의 스켈레톤 플레이스홀더를 생성합니다.
*
* - 레이아웃 컨테이너(Div, Flex, Grid 등): className 유지, 자식 순회
* - 텍스트 컴포넌트(H1~H6, P 등): 회색 바
* - 인풋 컴포넌트(Input, Select 등): 사각형
* - 미디어 컴포넌트(Img, Avatar 등): 큰 사각형
* - 복합 컴포넌트(DataGrid, Tabs 등): 특화 스켈레톤
* - iteration 블록: iteration_count 횟수만큼 반복
* - 조건부 분기: 로딩/에러 상태 스킵, 콘텐츠 브랜치만 렌더
*
* @since engine-v1.24.0
*/
export const PageSkeleton: React.FC<PageSkeletonProps> = ({ components, options }) => {
const animClass = getAnimationClass(options.animation);
return (
<div
className="w-full"
role="status"
aria-busy="true"
aria-label="Loading..."
>
{renderChildren(components, animClass, options.iteration_count)}
</div>
);
};
export default PageSkeleton;
@@ -0,0 +1,66 @@
import React, { useState, useEffect } from 'react';
import { Div } from '../basic/Div';
const logger = ((window as any).G7Core?.createLogger?.('Comp:PageTransitionBlur')) ?? {
log: (...args: unknown[]) => console.log('[Comp:PageTransitionBlur]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:PageTransitionBlur]', ...args),
};
export interface PageTransitionBlurProps {
className?: string;
style?: React.CSSProperties;
}
/**
* PageTransitionBlur 컴포넌트
*
* TransitionManager의 isPending 상태를 구독하여 페이지 전환 시
* 전체 콘텐츠에 블러 오버레이를 표시합니다.
* PageTransitionIndicator(z-50)보다 아래 레이어(z-40)에 위치합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "PageTransitionBlur"
* }
*/
export const PageTransitionBlur: React.FC<PageTransitionBlurProps> = ({
className = '',
style,
}) => {
const [isPending, setIsPending] = useState(false);
useEffect(() => {
const transitionManager = (window as any).G7Core?.TransitionManager;
if (!transitionManager) {
logger.warn('TransitionManager를 찾을 수 없습니다.');
return;
}
setIsPending(transitionManager.getIsPending());
const unsubscribe = transitionManager.subscribe((newIsPending: boolean) => {
logger.log('isPending changed:', newIsPending);
setIsPending(newIsPending);
});
return unsubscribe;
}, []);
if (!isPending) {
return null;
}
return (
<Div
className={`fixed inset-0 z-40 bg-white/30 dark:bg-gray-900/30 backdrop-blur-sm transition-opacity duration-150 pointer-events-none ${className}`}
style={style}
role="status"
aria-label="페이지 전환 중"
data-testid="page-transition-blur"
/>
);
};
export default PageTransitionBlur;
@@ -0,0 +1,92 @@
import React, { useState, useEffect } from 'react';
import { Div } from '../basic/Div';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:PageTransition')) ?? {
log: (...args: unknown[]) => console.log('[Comp:PageTransition]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:PageTransition]', ...args),
error: (...args: unknown[]) => console.error('[Comp:PageTransition]', ...args),
};
export interface PageTransitionIndicatorProps {
className?: string;
style?: React.CSSProperties;
}
/**
* PageTransitionIndicator 컴포넌트
*
* TransitionManager의 isPending 상태를 구독하여 페이지 전환 시
* 상단에 로딩 바를 표시합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "PageTransitionIndicator"
* }
*/
export const PageTransitionIndicator: React.FC<PageTransitionIndicatorProps> = ({
className = '',
style,
}) => {
const [isPending, setIsPending] = useState(false);
useEffect(() => {
// G7Core.TransitionManager 접근
const transitionManager = (window as any).G7Core?.TransitionManager;
if (!transitionManager) {
logger.warn('TransitionManager를 찾을 수 없습니다.');
return;
}
// 구독 및 초기 상태 설정
setIsPending(transitionManager.getIsPending());
const unsubscribe = transitionManager.subscribe((newIsPending: boolean) => {
setIsPending(newIsPending);
});
// 정리 함수
return unsubscribe;
}, []);
if (!isPending) {
return null;
}
return (
<Div
className={`fixed top-0 left-0 right-0 z-50 ${className}`}
style={style}
role="progressbar"
aria-label="페이지 로딩 중"
>
<Div className="h-1 bg-gradient-to-r from-blue-500 via-blue-600 to-blue-500 animate-pulse">
<Div
className="h-full bg-blue-700 animate-[loading_1.5s_ease-in-out_infinite]"
style={{
width: '30%',
animation: 'loading 1.5s ease-in-out infinite',
}}
/>
</Div>
<style>{`
@keyframes loading {
0% {
transform: translateX(-100%);
}
50% {
transform: translateX(300%);
}
100% {
transform: translateX(-100%);
}
}
`}</style>
</Div>
);
};
export default PageTransitionIndicator;
@@ -0,0 +1,206 @@
import React, { useMemo } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
export interface PaginationProps {
currentPage: number;
totalPages: number;
onPageChange: (page: number) => void;
maxVisiblePages?: number;
showFirstLast?: boolean;
className?: string;
style?: React.CSSProperties;
prevText?: string;
nextText?: string;
}
/**
* Pagination 집합 컴포넌트
*
* Button + Span 기본 컴포넌트를 조합하여 페이지네이션 UI를 구성합니다.
* 페이지 번호 생성 알고리즘을 포함하며, 많은 페이지 수에 대해 효율적으로 렌더링합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Pagination",
* "props": {
* "currentPage": "{{pagination.current}}",
* "totalPages": "{{pagination.total}}",
* "maxVisiblePages": 5,
* "showFirstLast": true
* }
* }
*/
export const Pagination: React.FC<PaginationProps> = ({
currentPage,
totalPages,
onPageChange,
maxVisiblePages = 5,
showFirstLast = true,
className = '',
style,
prevText,
nextText,
}) => {
// 페이지 번호 생성 알고리즘
const pageNumbers = useMemo(() => {
const pages: (number | string)[] = [];
if (totalPages <= maxVisiblePages + 2) {
// 페이지가 적으면 모두 표시
for (let i = 1; i <= totalPages; i++) {
pages.push(i);
}
} else {
// 페이지가 많으면 축약 표시
const halfVisible = Math.floor(maxVisiblePages / 2);
let startPage = Math.max(2, currentPage - halfVisible);
let endPage = Math.min(totalPages - 1, currentPage + halfVisible);
// 시작 또는 끝 근처일 때 조정
if (currentPage <= halfVisible + 1) {
endPage = maxVisiblePages;
} else if (currentPage >= totalPages - halfVisible) {
startPage = totalPages - maxVisiblePages + 1;
}
// 첫 페이지
pages.push(1);
// 시작 생략 부호
if (startPage > 2) {
pages.push('...');
}
// 중간 페이지들
for (let i = startPage; i <= endPage; i++) {
pages.push(i);
}
// 끝 생략 부호
if (endPage < totalPages - 1) {
pages.push('...');
}
// 마지막 페이지
if (totalPages > 1) {
pages.push(totalPages);
}
}
return pages;
}, [currentPage, totalPages, maxVisiblePages]);
const handlePageClick = (page: number) => {
if (page < 1 || page > totalPages || page === currentPage) return;
onPageChange(page);
};
const handlePrevious = () => {
if (currentPage > 1) {
onPageChange(currentPage - 1);
}
};
const handleNext = () => {
if (currentPage < totalPages) {
onPageChange(currentPage + 1);
}
};
return (
<Div
className={`flex items-center gap-2 ${className}`}
style={style}
role="navigation"
aria-label={t('common.pagination')}
>
{/* First Button */}
{showFirstLast && (
<Button
onClick={() => handlePageClick(1)}
disabled={currentPage === 1}
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
aria-label={t('common.first_page')}
>
&#171;
</Button>
)}
{/* Previous Button */}
<Button
onClick={handlePrevious}
disabled={currentPage === 1}
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
aria-label={t('common.prev_page')}
>
{prevText || <>&#8249;</>}
</Button>
{/* Page Numbers */}
<Div className="flex items-center gap-1">
{pageNumbers.map((page, index) => {
if (page === '...') {
return (
<Span
key={`ellipsis-${index}`}
className="px-3 py-1 text-sm text-gray-500 dark:text-gray-400"
>
...
</Span>
);
}
const pageNum = page as number;
const isActive = pageNum === currentPage;
return (
<Button
key={pageNum}
onClick={() => handlePageClick(pageNum)}
className={`px-3 py-1 text-sm border rounded ${
isActive
? 'bg-blue-500 dark:bg-blue-600 text-white border-blue-500 dark:border-blue-600'
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800'
}`}
aria-label={t('common.page_n', { n: pageNum })}
aria-current={isActive ? 'page' : undefined}
>
{pageNum}
</Button>
);
})}
</Div>
{/* Next Button */}
<Button
onClick={handleNext}
disabled={currentPage === totalPages}
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
aria-label={t('common.next_page')}
>
{nextText || <>&#8250;</>}
</Button>
{/* Last Button */}
{showFirstLast && (
<Button
onClick={() => handlePageClick(totalPages)}
disabled={currentPage === totalPages}
className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800"
aria-label={t('common.last_page')}
>
&#187;
</Button>
)}
</Div>
);
};
@@ -0,0 +1,181 @@
/**
* PostReactions 컴포넌트
*
* 게시글에 대한 리액션(이모지) 버튼 그룹입니다.
* 좋아요, 웃겨요, 동의해요, 감사해요, 놀라워요 5종 리액션을 지원합니다.
*/
import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:PostReactions')) ?? {
log: (...args: unknown[]) => console.log('[Comp:PostReactions]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:PostReactions]', ...args),
error: (...args: unknown[]) => console.error('[Comp:PostReactions]', ...args),
};
/**
* G7Core 번역 함수
*/
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
type ReactionType = 'like' | 'funny' | 'agree' | 'thanks' | 'wow';
interface ReactionCount {
type: ReactionType;
count: number;
}
interface PostReactionsProps {
/** 각 리액션별 카운트 */
reactions: ReactionCount[];
/** 현재 사용자의 리액션 (없으면 null) */
userReaction?: ReactionType | null;
/** 게시글 ID */
postId: number;
/** 리액션 클릭 콜백 */
onReact?: (type: ReactionType) => void;
/** 컴포넌트 크기 */
size?: 'sm' | 'md' | 'lg';
/** 추가 CSS 클래스 */
className?: string;
}
interface ReactionConfig {
type: ReactionType;
emoji: string;
labelKey: string;
activeColor: string;
}
/**
* 리액션 설정
*/
const REACTION_CONFIGS: ReactionConfig[] = [
{ type: 'like', emoji: '👍', labelKey: 'board.reactions.like', activeColor: 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400' },
{ type: 'funny', emoji: '😂', labelKey: 'board.reactions.funny', activeColor: 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 dark:text-yellow-400' },
{ type: 'agree', emoji: '👌', labelKey: 'board.reactions.agree', activeColor: 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400' },
{ type: 'thanks', emoji: '🙏', labelKey: 'board.reactions.thanks', activeColor: 'bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400' },
{ type: 'wow', emoji: '😮', labelKey: 'board.reactions.wow', activeColor: 'bg-orange-100 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400' },
];
/**
* 게시글 리액션 컴포넌트
*
* @example
* ```tsx
* <PostReactions
* reactions={[
* { type: 'like', count: 5 },
* { type: 'funny', count: 2 },
* ]}
* userReaction="like"
* postId={123}
* onReact={(type) => handleReact(type)}
* />
* ```
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "PostReactions",
* "props": {
* "reactions": "{{post.data.reactions}}",
* "userReaction": "{{post.data.user_reaction}}",
* "postId": "{{post.data.id}}"
* }
* }
* ```
*/
const PostReactions: React.FC<PostReactionsProps> = ({
reactions,
userReaction,
postId,
onReact,
size = 'md',
className = '',
}) => {
const sizeClasses = {
sm: 'px-2 py-1 text-xs gap-1',
md: 'px-3 py-1.5 text-sm gap-1.5',
lg: 'px-4 py-2 text-base gap-2',
};
const emojiSizes = {
sm: 'text-sm',
md: 'text-base',
lg: 'text-lg',
};
const getReactionCount = (type: ReactionType): number => {
const reaction = reactions.find((r) => r.type === type);
return reaction?.count ?? 0;
};
const handleClick = async (type: ReactionType) => {
if (onReact) {
onReact(type);
return;
}
// 기본 API 호출
try {
const response = await fetch(`/api/posts/${postId}/reactions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type }),
credentials: 'include',
});
if (!response.ok) {
throw new Error('리액션 처리 실패');
}
// 성공 시 페이지 새로고침 또는 상태 업데이트
window.location.reload();
} catch (error) {
logger.error('리액션 오류:', error);
}
};
return (
<Div className={`flex flex-wrap gap-2 ${className}`}>
{REACTION_CONFIGS.map((config) => {
const count = getReactionCount(config.type);
const isActive = userReaction === config.type;
return (
<Button
key={config.type}
onClick={() => handleClick(config.type)}
className={`
inline-flex items-center rounded-full border transition-colors
${sizeClasses[size]}
${isActive
? `${config.activeColor} border-transparent`
: 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}
`}
title={t(config.labelKey)}
>
<Span className={emojiSizes[size]}>{config.emoji}</Span>
<Span>{t(config.labelKey)}</Span>
{count > 0 && (
<Span className="font-medium">{count}</Span>
)}
</Button>
);
})}
</Div>
);
};
export default PostReactions;
@@ -0,0 +1,309 @@
/**
* ProductCard 컴포넌트
*
* 상품 목록에서 개별 상품을 표시하는 카드 컴포넌트입니다.
* 다중 통화를 지원하며, 할인율 뱃지를 표시합니다.
*/
import React from 'react';
// @ts-ignore - DOMPurify 타입 정의 없음
import DOMPurify from 'dompurify';
// 기본 컴포넌트 import
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { H3 } from '../basic/H3';
import { Img } from '../basic/Img';
// G7Core 전역 상태 훅
const useGlobalState = (key: string) =>
(window as any).G7Core?.state?.get?.(key);
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'navigate',
params: { path },
});
};
interface CurrencyPrice {
value: number;
formatted: string;
}
interface ProductLabel {
name: string;
color: string;
}
interface ProductCardProps {
product: {
id: number;
name?: string | Record<string, string>;
name_localized?: string;
thumbnail_url: string;
primary_category?: string;
selling_price: number;
selling_price_formatted: string;
list_price?: number;
list_price_formatted?: string;
discount_rate?: number;
multi_currency_selling_price?: Record<string, CurrencyPrice>;
multi_currency_list_price?: Record<string, CurrencyPrice>;
/** 검색 하이라이트된 상품명 (HTML) */
name_highlighted?: string;
/** 검색 하이라이트된 설명 (HTML) */
description_highlighted?: string;
/** 짧은 설명 */
short_description?: string;
/** 판매 상태 (on_sale, sold_out, suspended, coming_soon) */
sales_status?: string;
/** 판매 상태 번역 라벨 */
sales_status_label?: string;
/** 브랜드명 */
brand_name?: string;
/** 상품 라벨/뱃지 목록 */
labels?: ProductLabel[];
/** 평균 별점 (0.0 ~ 5.0, 소수점 1자리) */
rating_avg?: number;
/** 전시중 리뷰 수 */
review_count?: number;
};
/** 클릭 시 호출되는 콜백 */
onClick?: (productId: number) => void;
/** 쇼핑몰 base 경로 (예: '/shop', '/store', '/') */
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
}
/**
* 상품 카드 컴포넌트
*
* @example
* ```tsx
* <ProductCard
* product={{
* id: 1,
* name: "프리미엄 울 코트",
* thumbnail_url: "/images/product1.jpg",
* primary_category: "의류",
* selling_price: 189000,
* selling_price_formatted: "189,000원",
* list_price: 259000,
* list_price_formatted: "259,000원",
* discount_rate: 27,
* multi_currency_selling_price: {
* KRW: { value: 189000, formatted: "189,000원" },
* USD: { value: 159, formatted: "$159.00" }
* }
* }}
* />
* ```
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "ProductCard",
* "props": { "product": "{{product}}" }
* }
* ```
*/
/**
* rating_avg(0~5)를 0.5 단위로 반올림하여 별 아이콘 배열을 반환합니다.
* 반환값: 5개 원소, 각각 'full' | 'half' | 'empty'
*/
const getStarTypes = (avg: number): Array<'full' | 'half' | 'empty'> => {
const rounded = Math.round(avg * 2) / 2; // 0.5 단위 반올림
return [1, 2, 3, 4, 5].map((pos) => {
if (rounded >= pos) return 'full';
if (rounded >= pos - 0.5) return 'half';
return 'empty';
});
};
const ProductCard: React.FC<ProductCardProps> = ({
product,
onClick,
shopBase = '/shop',
className = '',
}) => {
const preferredCurrency = useGlobalState('preferredCurrency') || 'KRW';
/**
* 다중 통화 가격을 가져옵니다.
* 선호 통화가 없으면 기본 포맷 가격을 반환합니다.
*/
const getPrice = (field: 'selling_price' | 'list_price'): string | undefined => {
const multiCurrencyField = `multi_currency_${field}` as keyof typeof product;
const multiCurrencyData = product[multiCurrencyField] as Record<string, CurrencyPrice> | undefined;
if (multiCurrencyData && multiCurrencyData[preferredCurrency]) {
return multiCurrencyData[preferredCurrency].formatted;
}
const formattedField = `${field}_formatted` as keyof typeof product;
return product[formattedField] as string | undefined;
};
const displayName = product.name_localized
?? (typeof product.name === 'string' ? product.name : '')
?? '';
const sellingPrice = getPrice('selling_price');
const listPrice = getPrice('list_price');
const hasDiscount = product.discount_rate && product.discount_rate > 0;
const isNotOnSale = product.sales_status && product.sales_status !== 'on_sale';
const labels = product.labels ?? [];
/**
* HTML 하이라이트가 있으면 sanitize하여 반환합니다.
* mark 태그만 허용하여 XSS를 방지합니다.
*/
const sanitizeHighlight = (html: string): string => {
return DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['mark'],
ALLOWED_ATTR: [],
}) as unknown as string;
};
const nameHighlighted = product.name_highlighted;
const descriptionHtml = product.description_highlighted ?? product.short_description;
const handleClick = () => {
if (onClick) {
onClick(product.id);
} else {
const base = shopBase === '/' ? '' : shopBase;
navigate(`${base}/products/${product.id}`);
}
};
return (
<Button
onClick={handleClick}
className={`block w-full text-left group bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow cursor-pointer ${className}`}
>
{/* 이미지 영역 */}
<Div className="relative aspect-square overflow-hidden bg-gray-100 dark:bg-gray-700">
{/* 상품 이미지 */}
<Img
src={product.thumbnail_url}
alt={displayName}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
loading="lazy"
/>
{/* 판매 상태 오버레이 */}
{isNotOnSale && (
<Div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<Span className={`text-lg font-bold ${
product.sales_status === 'sold_out' ? 'text-red-300' :
product.sales_status === 'suspended' ? 'text-amber-300' :
'text-blue-300'
}`} style={{ textShadow: '0 1px 4px rgba(0,0,0,0.6)' }}>
{product.sales_status_label ?? product.sales_status}
</Span>
</Div>
)}
{/* 할인율 뱃지 (좌상단) - 품절/판매중단 시 숨김 */}
{hasDiscount && product.sales_status !== 'sold_out' && product.sales_status !== 'suspended' && (
<Span className="absolute top-2 left-2 px-2 py-1 bg-red-500 text-white text-xs font-bold rounded">
{product.discount_rate}%
</Span>
)}
{/* 상품 라벨/뱃지 (우하단) */}
{labels.length > 0 && (
<Div className="absolute bottom-2 right-2 flex gap-1 flex-wrap justify-end">
{labels.map((label, idx) => (
<Span
key={idx}
className="text-xs text-white font-medium px-1.5 py-0.5 rounded"
style={{ backgroundColor: label.color || '#6b7280' }}
>
{label.name}
</Span>
))}
</Div>
)}
</Div>
{/* 상품 정보 */}
<Div className="p-4">
{/* 카테고리 및 브랜드 */}
<Div className="flex items-center gap-1.5 flex-wrap">
{product.primary_category && (
<Span className="inline-block text-xs font-medium text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/30 px-2 py-0.5 rounded">
{product.primary_category}
</Span>
)}
{product.brand_name && (
<Span className="text-xs text-gray-500 dark:text-gray-400">
{product.brand_name}
</Span>
)}
</Div>
{/* 상품명 */}
{nameHighlighted ? (
<Div
className="mt-1 font-medium text-gray-900 dark:text-white line-clamp-1 [&_mark]:bg-yellow-200 [&_mark]:dark:bg-yellow-500/40 [&_mark]:px-0.5 [&_mark]:rounded"
dangerouslySetInnerHTML={{ __html: sanitizeHighlight(nameHighlighted) }}
/>
) : (
<H3 className="mt-1 font-medium text-gray-900 dark:text-white line-clamp-1">
{displayName}
</H3>
)}
{/* 상품 설명 (검색 결과 등에서 표시) */}
{descriptionHtml && (
<Div
className="mt-1 text-sm text-gray-600 dark:text-gray-400 line-clamp-2 [&_mark]:bg-yellow-200 [&_mark]:dark:bg-yellow-500/40 [&_mark]:px-0.5 [&_mark]:rounded"
dangerouslySetInnerHTML={{ __html: sanitizeHighlight(descriptionHtml) }}
/>
)}
{/* 별점 영역 */}
<Div className="mt-1.5 flex items-center gap-1">
{getStarTypes(product.rating_avg ?? 0).map((type, idx) => (
<Span
key={idx}
className={`text-xs ${type === 'empty' ? 'text-gray-300 dark:text-gray-600' : 'text-yellow-400'}`}
>
{type === 'full' && <i className="fa-solid fa-star" />}
{type === 'half' && <i className="fa-solid fa-star-half-stroke" />}
{type === 'empty' && <i className="fa-regular fa-star" />}
</Span>
))}
<Span className="text-xs text-gray-600 dark:text-gray-400 ml-0.5">
{(product.rating_avg ?? 0).toFixed(1)}
</Span>
<Span className="text-xs text-gray-400 dark:text-gray-500">
({product.review_count ?? 0})
</Span>
</Div>
{/* 가격 영역 */}
<Div className="mt-2 flex items-baseline gap-2">
<Span className="font-bold text-gray-900 dark:text-white">
{sellingPrice}
</Span>
{listPrice && hasDiscount && (
<Span className="text-sm text-gray-500 dark:text-gray-400 line-through">
{listPrice}
</Span>
)}
</Div>
</Div>
</Button>
);
};
export default ProductCard;
@@ -0,0 +1,145 @@
/**
* ProductImageViewer 컴포넌트
*
* 상품 상세 페이지용 이미지 뷰어입니다.
* 메인 이미지 + 썸네일 리스트 + 라이트박스(ImageGallery) 연동을 지원합니다.
*
* @module composite/ProductImageViewer
*/
import React, { useState, useMemo } from 'react';
import { Div } from '../basic/Div';
import { Img } from '../basic/Img';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { ImageGallery, useImageGallery, GalleryImage } from './ImageGallery';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
const t = (key: string, params?: Record<string, string | number>) =>
G7Core?.t?.(key, params) ?? key;
// ========== Types ==========
export interface ProductImage {
/** 이미지 ID */
id: number;
/** 외부 URL (CDN 등, nullable) */
url: string | null;
/** API 서빙 URL (항상 존재) */
download_url: string;
/** 현재 로케일 대체 텍스트 */
alt_text_current?: string;
/** 대표 이미지 여부 */
is_thumbnail?: boolean;
/** 정렬 순서 */
sort_order?: number;
}
export interface ProductImageViewerProps {
/** 상품 이미지 배열 (API 응답 그대로) */
images: ProductImage[];
/** 커스텀 클래스 */
className?: string;
}
// ========== Helper ==========
/**
* 이미지 표시용 URL 반환 (url 우선, 없으면 download_url)
*/
const getImageSrc = (image: ProductImage): string => {
return image.url ?? image.download_url;
};
// ========== Main Component ==========
export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
images = [],
className = '',
}) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const { openGallery, galleryProps } = useImageGallery();
// 이미지를 ImageGallery용 형식으로 변환
const galleryImages: GalleryImage[] = useMemo(
() =>
images.map((img) => ({
src: getImageSrc(img),
title: img.alt_text_current ?? '',
thumbnail: getImageSrc(img),
downloadUrl: img.download_url,
filename: img.alt_text_current ?? `image-${img.id}`,
})),
[images],
);
// 이미지 없음
if (!images || images.length === 0) {
return (
<Div
className={`flex items-center justify-center bg-gray-100 dark:bg-gray-700 rounded-lg aspect-square ${className}`}
>
<Div className="text-center text-gray-400 dark:text-gray-500">
<Icon name="image" size="3x" className="mb-3 opacity-50" />
<Div className="text-sm">{t('shop.no_image')}</Div>
</Div>
</Div>
);
}
const currentImage = images[selectedIndex] ?? images[0];
return (
<Div className={className}>
{/* 메인 이미지 */}
<Div className="relative overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-700 aspect-square mb-3">
<Button
type="button"
className="w-full h-full cursor-zoom-in block"
onClick={() => openGallery(galleryImages, selectedIndex)}
aria-label={t('shop.view_image')}
>
<Img
src={getImageSrc(currentImage)}
alt={currentImage.alt_text_current ?? ''}
className="w-full h-full object-contain"
/>
</Button>
</Div>
{/* 썸네일 리스트 (2개 이상일 때만) */}
{images.length > 1 && (
<Div className="flex gap-2 overflow-x-auto pb-1">
{images.map((img, index) => (
<Button
key={img.id}
type="button"
className={`flex-shrink-0 w-16 h-16 rounded-md overflow-hidden border-2 transition-colors cursor-pointer ${
index === selectedIndex
? 'border-gray-900 dark:border-white'
: 'border-gray-200 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-400'
}`}
onClick={() => setSelectedIndex(index)}
aria-label={img.alt_text_current ?? `${t('shop.image')} ${index + 1}`}
>
<Img
src={getImageSrc(img)}
alt={img.alt_text_current ?? ''}
className="w-full h-full object-cover"
/>
</Button>
))}
</Div>
)}
{/* 라이트박스 */}
<ImageGallery {...galleryProps} />
</Div>
);
};
ProductImageViewer.displayName = 'ProductImageViewer';
export default ProductImageViewer;
@@ -0,0 +1,170 @@
/**
* QuantitySelector 컴포넌트
*
* 수량 선택을 위한 +/- 버튼 컴포넌트입니다.
* 상품 상세 페이지, 장바구니 등에서 사용됩니다.
*/
import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Input } from '../basic/Input';
import { Icon } from '../basic/Icon';
interface QuantitySelectorProps {
/** 현재 수량 */
value: number;
/** 최소 수량 */
min?: number;
/** 최대 수량 */
max?: number;
/** 수량 변경 콜백 */
onChange: (value: number) => void;
/** 컴포넌트 크기 */
size?: 'sm' | 'md' | 'lg';
/** 비활성화 여부 */
disabled?: boolean;
/** 추가 CSS 클래스 */
className?: string;
}
/**
* 수량 선택 컴포넌트
*
* @example
* ```tsx
* const [quantity, setQuantity] = useState(1);
*
* <QuantitySelector
* value={quantity}
* min={1}
* max={10}
* onChange={setQuantity}
* />
* ```
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "QuantitySelector",
* "props": {
* "value": "{{item.quantity}}",
* "min": 1,
* "max": "{{item.stock}}",
* "size": "sm"
* },
* "actions": [{
* "event": "onChange",
* "type": "change",
* "handler": "updateQuantity",
* "params": { "itemId": "{{item.id}}", "quantity": "{{$args[0]}}" }
* }]
* }
* ```
*/
const QuantitySelector: React.FC<QuantitySelectorProps> = ({
value,
min = 1,
max = 999,
onChange,
size = 'md',
disabled = false,
className = '',
}) => {
const sizeClasses = {
sm: {
container: 'h-8',
button: 'w-8 h-8 text-sm',
input: 'w-10 text-sm',
},
md: {
container: 'h-10',
button: 'w-10 h-10',
input: 'w-14',
},
lg: {
container: 'h-12',
button: 'w-12 h-12 text-lg',
input: 'w-16 text-lg',
},
};
const classes = sizeClasses[size];
const handleDecrease = () => {
if (value > min && !disabled) {
onChange(value - 1);
}
};
const handleIncrease = () => {
if (value < max && !disabled) {
onChange(value + 1);
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = parseInt(e.target.value, 10);
if (!isNaN(newValue)) {
const clampedValue = Math.max(min, Math.min(max, newValue));
onChange(clampedValue);
}
};
const handleInputBlur = (e: React.FocusEvent<HTMLInputElement>) => {
const newValue = parseInt(e.target.value, 10);
if (isNaN(newValue) || newValue < min) {
onChange(min);
} else if (newValue > max) {
onChange(max);
}
};
const isMinDisabled = disabled || value <= min;
const isMaxDisabled = disabled || value >= max;
return (
<Div
className={`inline-flex items-center border border-gray-300 dark:border-gray-600 rounded-lg ${classes.container} ${className}`}
>
{/* 감소 버튼 */}
<Button
type="button"
onClick={handleDecrease}
disabled={isMinDisabled}
className={`${classes.button} flex items-center justify-center text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-l-lg transition-colors`}
aria-label="수량 감소"
>
<Icon name="minus" className="w-4 h-4" />
</Button>
{/* 수량 입력 */}
<Input
type="number"
value={value}
onChange={handleInputChange}
onBlur={handleInputBlur}
min={min}
max={max}
disabled={disabled}
className={`${classes.input} text-center border-x border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none`}
aria-label="수량"
/>
{/* 증가 버튼 */}
<Button
type="button"
onClick={handleIncrease}
disabled={isMaxDisabled}
className={`${classes.button} flex items-center justify-center text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-r-lg transition-colors`}
aria-label="수량 증가"
>
<Icon name="plus" className="w-4 h-4" />
</Button>
</Div>
);
};
export default QuantitySelector;
@@ -0,0 +1,339 @@
/**
* RichTextEditor 컴포넌트
*
* 게시글 작성을 위한 리치 텍스트 에디터입니다.
* TipTap 또는 Quill 등의 외부 라이브러리를 래핑합니다.
*
* @note 실제 구현 시 TipTap, Quill, CKEditor 등 선택하여 래핑
*/
import React, { useEffect, useRef, useState } from 'react';
import { Div } from '../basic/Div';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:RichTextEditor')) ?? {
log: (...args: unknown[]) => console.log('[Comp:RichTextEditor]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:RichTextEditor]', ...args),
error: (...args: unknown[]) => console.error('[Comp:RichTextEditor]', ...args),
};
import { Button } from '../basic/Button';
import { Input } from '../basic/Input';
import { Textarea } from '../basic/Textarea';
import { H3 } from '../basic/H3';
import { Label } from '../basic/Label';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
interface RichTextEditorProps {
/** 필드 이름 */
name: string;
/** 초기 HTML 값 */
initialValue?: string;
/** 플레이스홀더 */
placeholder?: string;
/** 값 변경 콜백 */
onChange?: (html: string) => void;
/** 이미지 업로드 URL */
imageUploadUrl?: string;
/** 최소 높이 */
minHeight?: string;
/** 비활성화 여부 */
disabled?: boolean;
/** 추가 CSS 클래스 */
className?: string;
}
type FormatType =
| 'bold'
| 'italic'
| 'underline'
| 'strike'
| 'code'
| 'h1'
| 'h2'
| 'h3'
| 'bulletList'
| 'orderedList'
| 'blockquote'
| 'link'
| 'image';
/**
* 리치 텍스트 에디터 컴포넌트
*
* @example
* ```tsx
* <RichTextEditor
* name="content"
* initialValue={post?.content}
* placeholder="내용을 입력하세요..."
* onChange={(html) => setContent(html)}
* />
* ```
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "RichTextEditor",
* "props": {
* "name": "content",
* "placeholder": "$t:board.form.content_placeholder",
* "initialValue": "{{post.data?.content ?? ''}}"
* }
* }
* ```
*/
const RichTextEditor: React.FC<RichTextEditorProps> = ({
name,
initialValue = '',
placeholder,
onChange,
imageUploadUrl = '/api/upload/image',
minHeight = '300px',
disabled = false,
className = '',
}) => {
const editorRef = useRef<HTMLDivElement>(null);
const [content, setContent] = useState(initialValue);
const [showCodeView, setShowCodeView] = useState(false);
const [showLinkModal, setShowLinkModal] = useState(false);
const [linkUrl, setLinkUrl] = useState('');
// 에디터 초기화 (실제 구현 시 TipTap/Quill 초기화)
useEffect(() => {
// 초기값 설정 (dangerouslySetInnerHTML 대신 직접 설정)
if (editorRef.current && !editorRef.current.innerHTML) {
editorRef.current.innerHTML = initialValue;
}
}, [initialValue]);
// 값 변경 시 콜백 호출
useEffect(() => {
if (onChange) {
onChange(content);
}
}, [content, onChange]);
// 포맷 적용 (실제 구현 시 에디터 API 사용)
const applyFormat = (format: FormatType) => {
// TODO: 에디터 라이브러리의 포맷 API 호출
logger.log('Apply format:', format);
};
// 이미지 업로드
const handleImageUpload = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch(imageUploadUrl, {
method: 'POST',
body: formData,
credentials: 'include',
});
if (!response.ok) throw new Error('업로드 실패');
const data = await response.json();
// TODO: 에디터에 이미지 삽입
logger.log('Image uploaded:', data.url);
} catch (error) {
logger.error('이미지 업로드 오류:', error);
}
};
// 파일 선택 핸들러
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
handleImageUpload(file);
}
};
// 링크 삽입
const insertLink = () => {
if (linkUrl) {
// TODO: 에디터에 링크 삽입
logger.log('Insert link:', linkUrl);
setShowLinkModal(false);
setLinkUrl('');
}
};
const toolbarButtons: { format: FormatType; icon: React.ReactNode; title: string }[] = [
{ format: 'bold', icon: 'B', title: t('editor.toolbar.bold') },
{ format: 'italic', icon: 'I', title: t('editor.toolbar.italic') },
{ format: 'underline', icon: 'U', title: t('editor.toolbar.underline') },
{ format: 'strike', icon: 'S', title: t('editor.toolbar.strike') },
{ format: 'code', icon: '</>', title: t('editor.toolbar.code') },
];
const headingButtons: { format: FormatType; label: string }[] = [
{ format: 'h1', label: 'H1' },
{ format: 'h2', label: 'H2' },
{ format: 'h3', label: 'H3' },
];
const listButtons: { format: FormatType; icon: string; title: string }[] = [
{ format: 'bulletList', icon: '•', title: t('editor.toolbar.bullet_list') },
{ format: 'orderedList', icon: '1.', title: t('editor.toolbar.ordered_list') },
{ format: 'blockquote', icon: '❝', title: t('editor.toolbar.blockquote') },
];
return (
<Div className={`border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden ${className}`}>
{/* 툴바 */}
<Div className="flex flex-wrap items-center gap-1 p-2 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
{/* 텍스트 포맷 */}
<Div className="flex items-center gap-1 pr-2 border-r border-gray-200 dark:border-gray-700">
{toolbarButtons.map((btn) => (
<Button
key={btn.format}
type="button"
onClick={() => applyFormat(btn.format)}
disabled={disabled}
className="w-8 h-8 flex items-center justify-center text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded disabled:opacity-50"
title={btn.title}
>
{btn.icon}
</Button>
))}
</Div>
{/* 제목 */}
<Div className="flex items-center gap-1 pr-2 border-r border-gray-200 dark:border-gray-700">
{headingButtons.map((btn) => (
<Button
key={btn.format}
type="button"
onClick={() => applyFormat(btn.format)}
disabled={disabled}
className="px-2 h-8 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded disabled:opacity-50"
>
{btn.label}
</Button>
))}
</Div>
{/* 리스트 */}
<Div className="flex items-center gap-1 pr-2 border-r border-gray-200 dark:border-gray-700">
{listButtons.map((btn) => (
<Button
key={btn.format}
type="button"
onClick={() => applyFormat(btn.format)}
disabled={disabled}
className="w-8 h-8 flex items-center justify-center text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded disabled:opacity-50"
title={btn.title}
>
{btn.icon}
</Button>
))}
</Div>
{/* 미디어 */}
<Div className="flex items-center gap-1 pr-2 border-r border-gray-200 dark:border-gray-700">
<Button
type="button"
onClick={() => setShowLinkModal(true)}
disabled={disabled}
className="w-8 h-8 flex items-center justify-center text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded disabled:opacity-50"
title={t('editor.toolbar.link')}
>
🔗
</Button>
<Label className="w-8 h-8 flex items-center justify-center text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded cursor-pointer">
🖼
<Input
type="file"
accept="image/*"
onChange={handleFileSelect}
disabled={disabled}
className="hidden"
/>
</Label>
</Div>
{/* 코드 보기 토글 */}
<Button
type="button"
onClick={() => setShowCodeView(!showCodeView)}
disabled={disabled}
className={`px-2 h-8 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded disabled:opacity-50 ${
showCodeView ? 'bg-gray-200 dark:bg-gray-700' : ''
}`}
>
{'</>'}
{t('editor.toolbar.code_view')}
</Button>
</Div>
{/* 에디터 영역 */}
{showCodeView ? (
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
disabled={disabled}
className="w-full p-4 bg-gray-900 text-gray-100 font-mono text-sm focus:outline-none resize-none"
style={{ minHeight }}
/>
) : (
<Div
ref={editorRef}
contentEditable={!disabled}
onInput={(e) => setContent(e.currentTarget.innerHTML)}
className="p-4 bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none prose dark:prose-invert max-w-none"
style={{ minHeight }}
data-placeholder={placeholder}
/>
)}
{/* 숨겨진 input (폼 전송용) */}
<Input type="hidden" name={name} value={content} />
{/* 링크 모달 */}
{showLinkModal && (
<Div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<Div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-96">
<H3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
{t('editor.link_modal.title')}
</H3>
<Input
type="url"
value={linkUrl}
onChange={(e) => setLinkUrl(e.target.value)}
placeholder="https://example.com"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white mb-4"
/>
<Div className="flex justify-end gap-2">
<Button
type="button"
onClick={() => {
setShowLinkModal(false);
setLinkUrl('');
}}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
>
{t('common.cancel')}
</Button>
<Button
type="button"
onClick={insertLink}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
{t('editor.link_modal.insert')}
</Button>
</Div>
</Div>
</Div>
)}
</Div>
);
};
export default RichTextEditor;
@@ -0,0 +1,184 @@
import React, { useState, useEffect } from 'react';
import { Form } from '../basic/Form';
import { Input } from '../basic/Input';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
export interface SearchSuggestion {
id: string | number;
text: string;
}
export interface SearchBarProps {
name?: string;
placeholder?: string;
value?: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
onSubmit?: (e: React.FormEvent<HTMLFormElement>) => void;
showButton?: boolean; // true: 검색 버튼 표시, false: 버튼 숨김 (기본값: false)
suggestions?: SearchSuggestion[];
onSuggestionClick?: (suggestion: SearchSuggestion) => void;
showSuggestions?: boolean;
className?: string;
style?: React.CSSProperties;
}
/**
* SearchBar 집합 컴포넌트
*
* 검색 입력 필드와 선택적 버튼을 제공하는 검색 바 컴포넌트입니다.
* Enter 키를 누르면 항상 검색이 실행됩니다.
*
* 기본 컴포넌트 조합: Form + Input + Button + Icon + Div + Span
*
* @example
* // 레이아웃 JSON 사용 예시 (버튼 없음)
* {
* "name": "SearchBar",
* "props": {
* "placeholder": "검색어를 입력하세요",
* "value": "{{query.search}}",
* "showButton": false
* }
* }
*
* @example
* // 레이아웃 JSON 사용 예시 (버튼 있음)
* {
* "name": "SearchBar",
* "props": {
* "placeholder": "검색어를 입력하세요",
* "value": "{{query.search}}",
* "showButton": true
* }
* }
*/
export const SearchBar: React.FC<SearchBarProps> = ({
name = 'search',
placeholder,
value: controlledValue,
onChange,
onSubmit,
showButton = false,
suggestions = [],
onSuggestionClick,
showSuggestions = false,
className = '',
style,
}) => {
// props로 전달된 값이 없으면 다국어 키 사용
const resolvedPlaceholder = placeholder ?? t('common.search_placeholder');
const [internalValue, setInternalValue] = useState('');
const [isFocused, setIsFocused] = useState(false);
const containerRef = React.useRef<HTMLDivElement>(null);
const previousValueRef = React.useRef<string>('');
const value = controlledValue !== undefined ? controlledValue : internalValue;
const shouldShowSuggestions = showSuggestions && isFocused && suggestions.length > 0 && value.length > 0;
// controlledValue가 변경될 때 previousValueRef 동기화
useEffect(() => {
if (controlledValue !== undefined) {
previousValueRef.current = controlledValue;
}
}, [controlledValue]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInternalValue(newValue);
onChange?.(e);
// X 버튼으로 검색어를 지운 경우 감지
// 이전 값이 있었는데 새 값이 빈 문자열이고, nativeEvent가 없는 경우 = X 버튼 클릭
if (previousValueRef.current !== '' && newValue === '' && !(e.nativeEvent as any).inputType) {
// X 버튼 클릭: 자동으로 검색 초기화
setTimeout(() => {
const formElement = containerRef.current?.querySelector('form');
if (formElement) {
formElement.requestSubmit();
}
}, 0);
}
previousValueRef.current = newValue;
};
const handleSuggestionClick = (suggestion: SearchSuggestion) => {
setInternalValue(suggestion.text);
const syntheticEvent = {
target: { value: suggestion.text, name },
} as React.ChangeEvent<HTMLInputElement>;
onChange?.(syntheticEvent);
onSuggestionClick?.(suggestion);
setIsFocused(false);
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit?.(e);
};
return (
<Div ref={containerRef} className={`relative ${className}`} style={style}>
<Form onSubmit={handleSubmit} className="relative">
<Div className={`relative flex items-center ${showButton ? 'gap-2' : ''}`}>
{/* Input wrapper */}
<Div className="relative flex-1">
{/* 검색 아이콘 */}
<Div className="absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none">
<Icon name={IconName.Search} className="w-5 h-5 text-gray-400 dark:text-gray-500" />
</Div>
{/* 검색 입력 */}
<Input
type="search"
name={name}
value={value}
onChange={handleChange}
onFocus={() => setIsFocused(true)}
onBlur={() => setTimeout(() => setIsFocused(false), 200)}
placeholder={resolvedPlaceholder}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
/>
</Div>
{/* 검색 버튼 (showButton=true일 때만 표시) */}
{showButton && (
<Button
type="submit"
className="px-4 py-2 bg-gray-800 dark:bg-gray-600 text-white rounded-lg hover:bg-gray-900 dark:hover:bg-gray-500 transition-colors text-sm font-medium cursor-pointer h-[42px]"
>
{t('common.search')}
</Button>
)}
</Div>
</Form>
{/* 자동완성 제안 목록 */}
{shouldShowSuggestions && (
<Div className="absolute z-10 w-full mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-64 overflow-y-auto">
{suggestions.map((suggestion) => (
<Div
key={suggestion.id}
className="px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer border-b border-gray-100 dark:border-gray-700 last:border-b-0 transition-colors"
onClick={() => handleSuggestionClick(suggestion)}
>
<Div className="flex items-center gap-2">
<Icon name={IconName.Search} className="w-4 h-4 text-gray-400 dark:text-gray-500" />
<Span className="text-sm text-gray-700 dark:text-gray-300">{suggestion.text}</Span>
</Div>
</Div>
))}
</Div>
)}
</Div>
);
};
@@ -0,0 +1,198 @@
/**
* SocialLoginButtons 컴포넌트
*
* 소셜 로그인(OAuth) 버튼 그룹입니다.
* Google, Naver, Kakao 등의 소셜 로그인을 지원합니다.
*/
import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
/**
* 소셜 로그인 아이콘 SVG 컴포넌트
*/
const SocialIcon: React.FC<{ provider: string; className?: string }> = ({ provider, className = 'w-5 h-5' }) => {
switch (provider) {
case 'google':
return (
<svg className={className} viewBox="0 0 24 24">
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
</svg>
);
case 'naver':
return (
<svg className={className} viewBox="0 0 24 24">
<path fill="currentColor" d="M16.273 12.845L7.376 0H0v24h7.727V11.155L16.624 24H24V0h-7.727z"/>
</svg>
);
case 'kakao':
return (
<svg className={className} viewBox="0 0 24 24">
<path fill="currentColor" d="M12 3c5.799 0 10.5 3.664 10.5 8.185 0 4.52-4.701 8.184-10.5 8.184a13.5 13.5 0 0 1-1.727-.11l-4.408 2.883c-.501.265-.678.236-.472-.413l.892-3.678c-2.88-1.46-4.785-3.99-4.785-6.866C1.5 6.665 6.201 3 12 3zm5.519 8.625h-.634v2.916h-.97v-2.916h-.633v-.848h2.237v.848zm-3.294 2.916h-.97V10.77h.97v3.771zm-1.97 0h-.97v-2.77l-.658 1.53h-.629l-.665-1.53v2.77h-.97V10.77h1.13l.822 1.912.814-1.912h1.126v3.771zm-4.49 0h-.97V10.77h.97v3.771z"/>
</svg>
);
case 'facebook':
return (
<svg className={className} viewBox="0 0 24 24">
<path fill="currentColor" d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
</svg>
);
case 'apple':
return (
<svg className={className} viewBox="0 0 24 24">
<path fill="currentColor" d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"/>
</svg>
);
default:
return null;
}
};
/**
* G7Core 번역 함수
*/
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
type SocialProvider = 'google' | 'naver' | 'kakao' | 'facebook' | 'apple';
interface SocialLoginButtonsProps {
/** 표시할 소셜 로그인 제공자 목록 */
providers?: SocialProvider[];
/** 로그인/회원가입 모드 */
mode?: 'login' | 'register';
/** 버튼 스타일 */
variant?: 'full' | 'icon';
/** 추가 CSS 클래스 */
className?: string;
}
interface ProviderConfig {
id: SocialProvider;
name: string;
color: string;
textColor: string;
}
/**
* 소셜 로그인 제공자 설정
*/
const PROVIDER_CONFIGS: ProviderConfig[] = [
{
id: 'google',
name: 'Google',
color: 'bg-white dark:bg-gray-800',
textColor: 'text-gray-700 dark:text-gray-300',
},
{
id: 'naver',
name: '네이버',
color: 'bg-[#03C75A]',
textColor: 'text-white',
},
{
id: 'kakao',
name: '카카오',
color: 'bg-[#FEE500]',
textColor: 'text-[#000000]/85',
},
{
id: 'facebook',
name: 'Facebook',
color: 'bg-[#1877F2]',
textColor: 'text-white',
},
{
id: 'apple',
name: 'Apple',
color: 'bg-black dark:bg-white',
textColor: 'text-white dark:text-black',
},
];
/**
* 소셜 로그인 버튼 그룹
*
* @example
* ```tsx
* <SocialLoginButtons
* providers={['google', 'naver', 'kakao']}
* mode="login"
* />
* ```
*
* @example
* ```json
* // 레이아웃 JSON에서 사용
* {
* "type": "composite",
* "name": "SocialLoginButtons",
* "props": {
* "providers": ["google", "naver", "kakao"],
* "mode": "register"
* }
* }
* ```
*/
const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
providers = ['google', 'naver', 'kakao'],
mode = 'login',
variant = 'full',
className = '',
}) => {
const handleSocialLogin = (provider: SocialProvider) => {
// OAuth 인증 URL로 리다이렉트
const callbackUrl = encodeURIComponent(window.location.href);
window.location.href = `/api/auth/${provider}?redirect=${callbackUrl}`;
};
const getButtonText = (providerName: string): string => {
if (mode === 'register') {
return t('auth.social.register_with', { provider: providerName });
}
return t('auth.social.login_with', { provider: providerName });
};
const filteredProviders = PROVIDER_CONFIGS.filter((config) =>
providers.includes(config.id)
);
if (variant === 'icon') {
return (
<Div className={`flex justify-center gap-4 ${className}`}>
{filteredProviders.map((provider) => (
<Button
key={provider.id}
onClick={() => handleSocialLogin(provider.id)}
className={`w-12 h-12 flex items-center justify-center rounded-full ${provider.color} ${provider.textColor} border border-gray-200 dark:border-gray-700 hover:opacity-90 transition-opacity`}
aria-label={getButtonText(provider.name)}
>
<SocialIcon provider={provider.id} className="w-5 h-5" />
</Button>
))}
</Div>
);
}
return (
<Div className={`space-y-3 ${className}`}>
{filteredProviders.map((provider) => (
<Button
key={provider.id}
onClick={() => handleSocialLogin(provider.id)}
className={`w-full flex items-center justify-center gap-3 px-4 py-3 rounded-lg font-medium border border-gray-200 dark:border-gray-700 ${provider.color} ${provider.textColor} hover:opacity-90 transition-opacity`}
>
<SocialIcon provider={provider.id} className="w-5 h-5" />
<Span>{getButtonText(provider.name)}</Span>
</Button>
))}
</Div>
);
};
export default SocialLoginButtons;
@@ -0,0 +1,188 @@
import React, { useState, useEffect } from 'react';
import { Nav } from '../basic/Nav';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
export interface Tab {
id: string | number;
label: string;
iconName?: IconName;
disabled?: boolean;
badge?: string | number;
}
export interface TabNavigationProps {
tabs: Tab[];
activeTabId?: string | number;
onTabChange?: (tabId: string | number) => void;
variant?: 'default' | 'pills' | 'underline';
className?: string;
style?: React.CSSProperties;
/** 모바일에서 그리드 레이아웃 사용 (기본: true) */
mobileGrid?: boolean;
/** 모바일 그리드 컬럼 수 (기본: 3) */
mobileColumns?: number;
/** 숨길 탭 ID 목록 (동적 조건부 탭 노출용) */
hiddenTabIds?: (string | number)[];
}
/**
* TabNavigation 집합 컴포넌트
*
* 탭 네비게이션을 제공하는 컴포넌트입니다.
* 여러 탭을 전환할 수 있으며, 아이콘과 뱃지를 지원합니다.
* 모바일에서는 그리드 레이아웃으로 표시합니다.
*
* **주의**: 이 컴포넌트는 순수 네비게이션 UI만 제공하며,
* 실제 탭 컨텐츠는 부모 컴포넌트에서 activeTabId를 기반으로 조건부 렌더링해야 합니다.
*
* 기본 컴포넌트 조합: Nav + Button + Icon + Div + Span
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "TabNavigation",
* "props": {
* "activeTabId": 1,
* "mobileColumns": 3,
* "tabs": [
* {"id": 1, "label": "프로필", "iconName": "user"},
* {"id": 2, "label": "설정", "iconName": "cog", "badge": 3},
* {"id": 3, "label": "문의내역", "iconName": "comment"}
* ],
* "hiddenTabIds": "{{_global.modules?.['sirsoft-ecommerce']?.inquiry?.board_slug ? [] : ['inquiries']}}"
* }
* }
*/
export const TabNavigation: React.FC<TabNavigationProps> = ({
tabs,
activeTabId,
onTabChange,
variant = 'underline',
className = '',
style,
mobileGrid = true,
mobileColumns = 3,
hiddenTabIds = [],
}) => {
const [isMobile, setIsMobile] = useState(false);
// 모바일 감지 (768px 기준)
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768);
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
const handleTabClick = (tab: Tab) => {
if (!tab.disabled && tab.id !== activeTabId) {
onTabChange?.(tab.id);
}
};
const getTabClasses = (tab: Tab) => {
const isActive = tab.id === activeTabId;
const baseClasses = isMobile && mobileGrid
? 'flex flex-col items-center justify-center gap-3 pt-4 pb-2 font-medium text-sm transition-all'
: 'flex items-center gap-2 px-3 py-2 font-medium text-sm transition-all shrink-0 whitespace-nowrap';
if (tab.disabled) {
return `${baseClasses} opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-600`;
}
// 모바일 그리드 스타일
if (isMobile && mobileGrid) {
return isActive
? `${baseClasses} text-gray-900 dark:text-white bg-gray-100 dark:bg-gray-700 rounded-lg`
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg`;
}
switch (variant) {
case 'pills':
return isActive
? `${baseClasses} bg-blue-600 dark:bg-blue-500 text-white rounded-lg`
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg`;
case 'underline':
return isActive
? `${baseClasses} text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white`
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 border-b-2 border-transparent hover:border-gray-300 dark:hover:border-gray-600`;
case 'default':
default:
return isActive
? `${baseClasses} text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 border-b-2 border-blue-600 dark:border-blue-400`
: `${baseClasses} text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 border-b-2 border-transparent`;
}
};
// 모바일 그리드 컬럼 클래스
const getGridColumnsClass = () => {
switch (mobileColumns) {
case 2:
return 'grid-cols-2';
case 4:
return 'grid-cols-4';
case 3:
default:
return 'grid-cols-3';
}
};
const navClasses = isMobile && mobileGrid
? `grid ${getGridColumnsClass()} gap-1 p-1 bg-gray-50 dark:bg-gray-800 rounded-lg`
: variant === 'underline'
? 'flex gap-0 border-b border-gray-200 dark:border-gray-700'
: 'flex gap-2';
const renderTabButton = (tab: Tab) => (
<Button
key={tab.id}
type="button"
onClick={() => handleTabClick(tab)}
disabled={tab.disabled}
className={getTabClasses(tab)}
>
{tab.iconName && (
<Icon name={tab.iconName} size="sm"/>
)}
{isMobile && mobileGrid && tab.badge !== undefined ? (
<Div className="flex items-center gap-1">
<Span className="text-xs">{tab.label}</Span>
<Div className="flex items-center justify-center min-w-5 h-5 px-1.5 bg-red-500 text-white text-xs font-bold rounded-full">
<Span>{tab.badge}</Span>
</Div>
</Div>
) : (
<>
<Span className={isMobile && mobileGrid ? 'text-xs' : ''}>{tab.label}</Span>
{tab.badge !== undefined && (
<Div className="flex items-center justify-center min-w-5 h-5 px-1.5 bg-red-500 text-white text-xs font-bold rounded-full">
<Span>{tab.badge}</Span>
</Div>
)}
</>
)}
</Button>
);
const visibleTabs = hiddenTabIds.length > 0
? tabs.filter((tab) => !hiddenTabIds.includes(tab.id))
: tabs;
return (
<Div className={`relative ${className}`} style={style}>
<Nav className={navClasses}>
{visibleTabs.map((tab) => renderTabButton(tab))}
</Nav>
</Div>
);
};
@@ -0,0 +1,246 @@
import React, { useState, useEffect, useRef } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Span } from '../basic/Span';
/**
* 테마 모드 타입
*/
export type ThemeMode = 'auto' | 'light' | 'dark';
/**
* ThemeToggle Props
*/
export interface ThemeToggleProps {
/** 테마 변경 콜백 */
onThemeChange?: (theme: ThemeMode) => void;
/** 추가 CSS 클래스 */
className?: string;
/** 자동 모드 텍스트 (다국어 키 사용 권장) */
autoText?: string;
/** 라이트 모드 텍스트 (다국어 키 사용 권장) */
lightText?: string;
/** 다크 모드 텍스트 (다국어 키 사용 권장) */
darkText?: string;
}
/**
* ThemeToggle 컴포넌트
*
* 다크/라이트 모드 전환 버튼
* - 3가지 모드: 자동(시스템 설정 따름), 라이트, 다크
* - localStorage에 'g7_color_scheme' 키로 저장 (admin 템플릿과 동일)
* - 시스템 prefers-color-scheme 감지 지원
*
* @example
* ```json
* {
* "type": "composite",
* "name": "ThemeToggle",
* "props": {
* "autoText": "$t:common.theme.auto",
* "lightText": "$t:common.theme.light",
* "darkText": "$t:common.theme.dark"
* }
* }
* ```
*/
/**
* 실제 적용될 테마 결정 (auto인 경우 시스템 설정 반영)
*/
const getEffectiveTheme = (mode: ThemeMode): 'light' | 'dark' => {
if (mode === 'auto') {
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
}
return mode;
};
/**
* 테마 적용
*/
const applyTheme = (mode: ThemeMode) => {
const effectiveTheme = getEffectiveTheme(mode);
document.documentElement.setAttribute('data-theme', effectiveTheme);
// dark 클래스 토글 (Tailwind CSS dark: 모드 지원)
if (effectiveTheme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
};
/**
* 초기 테마 로드 및 적용 (즉시 실행)
* admin 템플릿과 동일한 localStorage 키 사용: 'g7_color_scheme'
*/
const getInitialTheme = (): ThemeMode => {
const savedTheme = localStorage.getItem('g7_color_scheme') as ThemeMode | null;
if (savedTheme && ['auto', 'light', 'dark'].includes(savedTheme)) {
return savedTheme;
}
return 'auto';
};
export const ThemeToggle: React.FC<ThemeToggleProps> = ({
onThemeChange,
className = '',
autoText = 'System',
lightText = 'Light',
darkText = 'Dark',
}) => {
// 초기 테마를 즉시 로드하고 적용
const initialTheme = getInitialTheme();
const [currentMode, setCurrentMode] = useState<ThemeMode>(initialTheme);
const [showMenu, setShowMenu] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
/**
* 컴포넌트 마운트 시 즉시 테마 적용
*/
useEffect(() => {
applyTheme(currentMode);
}, []);
/**
* 시스템 테마 변경 감지
*/
useEffect(() => {
if (currentMode !== 'auto') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
applyTheme('auto');
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [currentMode]);
/**
* 외부 클릭 감지
*/
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setShowMenu(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
/**
* 테마 변경 핸들러
* admin 템플릿과 동일한 localStorage 키 사용: 'g7_color_scheme'
*/
const handleThemeChange = (mode: ThemeMode) => {
setCurrentMode(mode);
localStorage.setItem('g7_color_scheme', mode);
applyTheme(mode);
setShowMenu(false);
onThemeChange?.(mode);
};
/**
* 현재 표시할 아이콘 결정
*/
const getCurrentIcon = (): IconName => {
const effectiveTheme = getEffectiveTheme(currentMode);
return effectiveTheme === 'dark' ? IconName.Moon : IconName.Sun;
};
return (
<Div ref={menuRef} className={`relative ${className}`}>
{/* 테마 토글 버튼 */}
<Button
onClick={() => setShowMenu(!showMenu)}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors text-gray-600 dark:text-gray-400"
aria-label="Toggle theme"
>
<Icon
name={getCurrentIcon()}
className="w-5 h-5"
/>
</Button>
{/* 테마 선택 드롭다운 */}
{showMenu && (
<Div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
<Div className="py-2">
{/* 자동 모드 */}
<Button
onClick={() => handleThemeChange('auto')}
className={`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${currentMode === 'auto' ? 'bg-gray-50 dark:bg-gray-700' : ''}
`}
>
<Icon
name={IconName.Settings}
className="w-5 h-5 text-gray-600 dark:text-gray-400"
/>
<Span className="flex-1 text-left text-gray-900 dark:text-white">{autoText}</Span>
{currentMode === 'auto' && (
<Icon
name={IconName.Check}
className="w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"
/>
)}
</Button>
{/* 라이트 모드 */}
<Button
onClick={() => handleThemeChange('light')}
className={`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${currentMode === 'light' ? 'bg-gray-50 dark:bg-gray-700' : ''}
`}
>
<Icon
name={IconName.Sun}
className="w-5 h-5 text-gray-600 dark:text-gray-400"
/>
<Span className="flex-1 text-left text-gray-900 dark:text-white">{lightText}</Span>
{currentMode === 'light' && (
<Icon
name={IconName.Check}
className="w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"
/>
)}
</Button>
{/* 다크 모드 */}
<Button
onClick={() => handleThemeChange('dark')}
className={`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${currentMode === 'dark' ? 'bg-gray-50 dark:bg-gray-700' : ''}
`}
>
<Icon
name={IconName.Moon}
className="w-5 h-5 text-gray-600 dark:text-gray-400"
/>
<Span className="flex-1 text-left text-gray-900 dark:text-white">{darkText}</Span>
{currentMode === 'dark' && (
<Icon
name={IconName.Check}
className="w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"
/>
)}
</Button>
</Div>
</Div>
)}
</Div>
);
};
export default ThemeToggle;
@@ -0,0 +1,256 @@
import React, { useEffect, useState, useCallback } from 'react';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
/**
* G7Core.t() 번역 함수 참조
* 런타임에 G7Core.t를 접근하여 테스트 환경에서도 모킹이 적용되도록 함
*/
const getTranslation = (key: string, params?: Record<string, string | number>) => {
const G7Core = (window as any).G7Core;
return G7Core?.t?.(key, params) ?? key;
};
export type ToastType = 'success' | 'error' | 'warning' | 'info';
export type ToastPosition =
| 'top-left'
| 'top-center'
| 'top-right'
| 'bottom-left'
| 'bottom-center'
| 'bottom-right';
export interface ToastItem {
id: string | number;
type: ToastType;
message: string;
/** 커스텀 아이콘 이름 (지정하지 않으면 타입별 기본 아이콘 사용) */
icon?: string;
/** 개별 토스트 자동 닫힘 시간 (ms) */
duration?: number;
}
export interface ToastProps {
/** 토스트 배열 (전역 상태 _global.toasts) */
toasts?: ToastItem[] | null;
/** 토스트 표시 위치 */
position?: ToastPosition;
/** 기본 자동 닫힘 시간 (ms, 기본 3000) */
duration?: number;
/** 토스트 제거 콜백 (전역 상태 업데이트용) */
onRemove?: (id: string | number) => void;
}
// 타입별 기본 아이콘 매핑
const defaultIconMap: Record<ToastType, IconName> = {
success: IconName.CheckCircle,
error: IconName.XCircle,
warning: IconName.ExclamationTriangle,
info: IconName.InfoCircle,
};
// 타입별 스타일 매핑
const typeStyleMap: Record<ToastType, { bg: string; text: string }> = {
success: {
bg: 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800',
text: 'text-green-800 dark:text-green-300',
},
error: {
bg: 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800',
text: 'text-red-800 dark:text-red-300',
},
warning: {
bg: 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800',
text: 'text-yellow-800 dark:text-yellow-300',
},
info: {
bg: 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800',
text: 'text-blue-800 dark:text-blue-300',
},
};
// position별 스타일 매핑
const positionClassMap: Record<ToastPosition, string> = {
'top-left': 'top-4 left-4',
'top-center': 'top-4 left-1/2 -translate-x-1/2',
'top-right': 'top-4 right-4',
'bottom-left': 'bottom-4 left-4',
'bottom-center': 'bottom-4 left-1/2 -translate-x-1/2',
'bottom-right': 'bottom-4 right-4',
};
/**
* Toast 컴포넌트
*
* 전역 상태(_global.toasts)를 구독하여 토스트 알림을 스택으로 표시하는 컴포넌트.
* ActionDispatcher의 toast 핸들러와 연동됩니다.
*
* 기능:
* - 다중 토스트 스택 지원
* - 타입별 스타일 (success, error, warning, info)
* - 커스텀 아이콘 지정 가능
* - 개별 토스트 자동 닫힘 시간 설정
* - 수동 닫기 버튼
*
* @example
* // 레이아웃 JSON 사용 예시 (_user_base.json)
* {
* "id": "global_toast",
* "type": "composite",
* "name": "Toast",
* "props": {
* "toasts": "{{_global.toasts}}",
* "position": "bottom-center",
* "duration": 3000
* }
* }
*
* @example
* // toast 핸들러 호출 예시 (레이아웃 JSON)
* {
* "handler": "toast",
* "params": {
* "type": "success",
* "message": "$t:common.save_success",
* "icon": "check",
* "duration": 5000
* }
* }
*/
export const Toast: React.FC<ToastProps> = ({
toasts,
position = 'bottom-center',
duration = 3000,
onRemove,
}) => {
// 내부적으로 표시할 토스트 상태 관리 (애니메이션용)
const [visibleToasts, setVisibleToasts] = useState<Map<string | number, boolean>>(new Map());
// 토스트 제거 핸들러
const handleRemove = useCallback((id: string | number) => {
// 먼저 숨김 애니메이션 시작
setVisibleToasts(prev => {
const next = new Map(prev);
next.set(id, false);
return next;
});
// 애니메이션 후 실제 제거
setTimeout(() => {
if (onRemove) {
onRemove(id);
} else {
// onRemove가 없으면 G7Core.state.update를 통해 전역 상태 업데이트
const G7Core = (window as any).G7Core;
if (G7Core?.state?.update) {
G7Core.state.update((prevState: Record<string, any>) => {
const currentToasts = Array.isArray(prevState.toasts) ? prevState.toasts : [];
return {
toasts: currentToasts.filter((t: ToastItem) => t.id !== id),
};
});
}
}
}, 300);
}, [onRemove]);
// 새 토스트가 추가되면 visible 상태 설정 및 자동 제거 타이머 설정
useEffect(() => {
if (!toasts || toasts.length === 0) return;
toasts.forEach(toast => {
// 이미 처리된 토스트는 건너뜀
if (visibleToasts.has(toast.id)) return;
// visible 상태 추가
setVisibleToasts(prev => {
const next = new Map(prev);
next.set(toast.id, true);
return next;
});
// 자동 제거 타이머 설정
const effectiveDuration = toast.duration || duration;
if (effectiveDuration > 0) {
setTimeout(() => {
handleRemove(toast.id);
}, effectiveDuration);
}
});
}, [toasts, duration, handleRemove, visibleToasts]);
// 토스트가 없으면 렌더링하지 않음
if (!toasts || toasts.length === 0) {
return null;
}
return (
<Div
className={`fixed z-[9999] flex flex-col gap-2 ${positionClassMap[position]}`}
aria-live="polite"
aria-atomic="true"
>
{toasts.map((toast) => (
<ToastItemComponent
key={toast.id}
toast={toast}
position={position}
isVisible={visibleToasts.get(toast.id) ?? true}
onClose={() => handleRemove(toast.id)}
/>
))}
</Div>
);
};
interface ToastItemComponentProps {
toast: ToastItem;
position: ToastPosition;
isVisible: boolean;
onClose: () => void;
}
const ToastItemComponent: React.FC<ToastItemComponentProps> = ({ toast, position, isVisible, onClose }) => {
const typeStyle = typeStyleMap[toast.type] || typeStyleMap.info;
// 아이콘 결정: 커스텀 아이콘 > 타입별 기본 아이콘
const iconName = toast.icon
? (toast.icon as IconName)
: defaultIconMap[toast.type];
// position에 따라 숨김 애니메이션 방향 결정 (top → 위로, bottom → 아래로)
const hideTranslate = position.startsWith('bottom') ? 'translate-y-2' : '-translate-y-2';
return (
<Div
className={`
flex items-center gap-3 p-4 rounded-lg border shadow-lg
min-w-[300px] max-w-md
transition-all duration-300
${typeStyle.bg}
${isVisible ? 'opacity-100 translate-y-0' : `opacity-0 ${hideTranslate}`}
`}
role="alert"
>
<Icon
name={iconName}
className={`w-5 h-5 flex-shrink-0 ${typeStyle.text}`}
/>
<Span className={`flex-1 text-sm font-medium ${typeStyle.text}`}>
{toast.message}
</Span>
<Button
onClick={onClose}
className={`flex-shrink-0 p-1 rounded hover:bg-black/10 dark:hover:bg-white/10 ${typeStyle.text} focus:outline-none`}
aria-label={getTranslation('common.close')}
>
<Icon name={IconName.Times} className="w-4 h-4" />
</Button>
</Div>
);
};
export default Toast;
@@ -0,0 +1,438 @@
/**
* UserInfo 컴포넌트
*
* 게시글 작성자 정보를 표시하고 드롭다운 메뉴를 제공하는 통합 컴포넌트입니다.
* - 작성자 이름, 서브텍스트 표시
* - 클릭 시 드롭다운 메뉴 (회원인 경우)
* - 비회원인 경우 배지 표시
* - 탈퇴한 사용자인 경우 "탈퇴한 사용자" 텍스트 표시
*
* ## Props 우선순위
* 명시적으로 전달한 props가 author에서 추출한 값보다 우선합니다.
* - 이름: text > name > author.name
* - 사용자 ID: userId > author.id
* - 비회원 여부: isGuest > author.is_guest
* - 탈퇴 여부: isWithdrawn || author.status === 'withdrawn'
*
* @example
* // 레이아웃 JSON에서 사용 (author 객체 전달 - 권장)
* {
* "type": "composite",
* "name": "UserInfo",
* "props": {
* "author": "{{post.author}}",
* "subText": "{{post.created_at | datetime}}"
* }
* }
*
* @example
* // author와 개별 props 혼합 사용 (개별 props가 우선)
* {
* "type": "composite",
* "name": "UserInfo",
* "props": {
* "author": "{{post.author}}",
* "name": "관리자",
* "subText": "{{post.created_at | datetime}}"
* }
* }
* // author.name이 "홍길동"이어도 "관리자"가 표시됨
*/
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
// G7Core 참조
const getG7Core = () => (window as any).G7Core;
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
/**
* 메뉴 항목 설정 인터페이스
*/
export interface MenuItemConfig {
/** 메뉴 항목 식별자 */
key: string;
/** 표시 텍스트 */
label: string;
/** 아이콘 이름 (선택) */
icon?: string;
/** 이동 경로 ({{userId}} 치환 지원) */
path?: string;
/** 커스텀 클릭 핸들러 (선택) */
onClick?: () => void;
/** 표시 여부 (기본: true) */
show?: boolean;
}
/**
* Author 객체 인터페이스
*/
export interface AuthorInfo {
/** 사용자 ID */
id?: string | number;
/** 사용자 UUID */
uuid?: string;
/** 사용자 이름 */
name?: string;
/** 아바타 URL */
avatar?: string;
/** 사용자 상태 */
status?: 'active' | 'inactive' | 'blocked' | 'withdrawn';
/** 비회원 여부 */
is_guest?: boolean;
}
export interface UserInfoProps {
/**
* 작성자 객체 (권장)
* API 응답의 author 객체를 그대로 전달하면 됩니다.
* 개별 props(name, userId 등)가 함께 전달되면 개별 props가 우선합니다.
*/
author?: AuthorInfo;
/**
* 사용자 이름 (author.name보다 우선)
*/
name?: string;
/**
* 사용자 ID (author.id보다 우선)
*/
userId?: string | number;
/**
* 표시할 서브 텍스트 (날짜, 시간 등)
*/
subText?: string;
/**
* 서브 텍스트의 title 속성 (tooltip용 원본 datetime)
*/
subTextTitle?: string;
/**
* 비회원 여부 (author.is_guest보다 우선)
* @default false
*/
isGuest?: boolean;
/**
* 탈퇴한 사용자 여부 (author.status === 'withdrawn'과 OR 조건)
* @default false
*/
isWithdrawn?: boolean;
/**
* 드롭다운 표시 여부
* @default true
*/
showDropdown?: boolean;
/**
* 프로필 클릭 가능 여부 (드롭다운이 없을 때)
* @default true
*/
clickable?: boolean;
/**
* 사용자 프로필 경로 패턴
* @default '/users/{userId}'
*/
profilePath?: string;
/**
* 추가 className
*/
className?: string;
/**
* 레이아웃 방향
* @default 'vertical'
*/
layout?: 'vertical' | 'horizontal';
/**
* 레이아웃 JSON에서 text 속성으로 전달되는 이름
* name보다 우선순위가 높음
*/
text?: string;
/**
* 이벤트 버블링 방지 여부
* @default false
*/
stopPropagation?: boolean;
// 메뉴 커스터마이징
/** 커스텀 메뉴 항목 (지정 시 기본 메뉴 대체) */
menuItems?: MenuItemConfig[];
/** 숨길 기본 메뉴 항목 키 배열 */
hideMenuItems?: string[];
/** 기본 메뉴에 추가할 항목 */
appendMenuItems?: MenuItemConfig[];
}
// 레이아웃별 컨테이너 클래스
const LAYOUT_CLASSES = {
horizontal: 'flex items-center gap-1.5',
vertical: 'flex flex-col items-start',
} as const;
// 기본 메뉴 항목 생성
const createDefaultMenuItems = (): MenuItemConfig[] => [
{
key: 'view_profile',
label: t('userinfo.view_profile'),
icon: 'user',
path: '/users/{{userId}}',
},
{
key: 'view_posts',
label: t('userinfo.view_posts'),
icon: 'file-lines',
path: '/users/{{userId}}/posts',
},
];
/**
* 서브텍스트 렌더링 컴포넌트
*/
const SubText: React.FC<{ text?: string; title?: string }> = ({ text, title }) => {
if (!text) return null;
return (
<Span className="text-sm text-gray-500 dark:text-gray-400" title={title}>
{text}
</Span>
);
};
/**
* UserInfo 컴포넌트
*/
export const UserInfo: React.FC<UserInfoProps> = ({
author,
name,
userId,
subText,
subTextTitle,
isGuest = false,
isWithdrawn = false,
showDropdown = true,
clickable = true,
profilePath = '/users/{userId}',
className = '',
layout = 'vertical',
text,
stopPropagation = false,
menuItems,
hideMenuItems = [],
appendMenuItems = [],
}) => {
// 명시적 props > author 추출값 순서로 결정
const actualUserId = userId ?? author?.uuid;
const actualIsGuest = isGuest || author?.is_guest || false;
const actualIsWithdrawn = isWithdrawn || author?.status === 'withdrawn';
// 이름 우선순위: text > name > author.name
// 탈퇴한 사용자는 "탈퇴한 사용자" 텍스트 표시
const actualName = actualIsWithdrawn
? t('userinfo.withdrawn_user')
: (text ?? name ?? author?.name ?? '');
// 드롭다운 상태
const [showMenu, setShowMenu] = useState(false);
const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
const containerRef = useRef<HTMLDivElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
// 프로필 경로 생성
const actualProfilePath = profilePath.replace('{userId}', String(actualUserId ?? ''));
// 컨테이너 클래스
const containerClass = `${LAYOUT_CLASSES[layout]} ${className}`;
// 메뉴 외부 클릭 시 닫기 + 스크롤/리사이즈 시 닫기
useEffect(() => {
if (!showMenu) return;
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Node;
const isInsideContainer = containerRef.current?.contains(target);
const isInsideDropdown = dropdownRef.current?.contains(target);
if (!isInsideContainer && !isInsideDropdown) {
setShowMenu(false);
}
};
const handleScrollOrResize = () => setShowMenu(false);
document.addEventListener('mousedown', handleClickOutside);
window.addEventListener('scroll', handleScrollOrResize, true);
window.addEventListener('resize', handleScrollOrResize);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
window.removeEventListener('scroll', handleScrollOrResize, true);
window.removeEventListener('resize', handleScrollOrResize);
};
}, [showMenu]);
// 최종 메뉴 항목 계산
const getMenuItems = useCallback((): MenuItemConfig[] => {
// 커스텀 메뉴가 지정된 경우 그대로 사용
if (menuItems && menuItems.length > 0) {
return menuItems.filter((item) => item.show !== false);
}
// 기본 메뉴에서 숨길 항목 제거
const defaultItems = createDefaultMenuItems();
let items = defaultItems.filter(
(item) => !hideMenuItems.includes(item.key) && item.show !== false
);
// 추가 항목 병합
if (appendMenuItems && appendMenuItems.length > 0) {
items = [...items, ...appendMenuItems.filter((item) => item.show !== false)];
}
return items;
}, [menuItems, hideMenuItems, appendMenuItems]);
// 드롭다운 위치 계산 (뷰포트 기준 fixed 위치 — Portal 사용)
const updateMenuPosition = useCallback(() => {
if (buttonRef.current) {
const buttonRect = buttonRef.current.getBoundingClientRect();
setMenuPosition({
top: buttonRect.bottom + 4,
left: buttonRect.left,
});
}
}, []);
// 메뉴 항목 클릭 핸들러
const handleMenuItemClick = useCallback((item: MenuItemConfig, e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
setShowMenu(false);
if (item.onClick) {
item.onClick();
} else if (item.path) {
const path = item.path.replace(/\{\{userId\}\}/g, String(actualUserId ?? ''));
const g7Core = getG7Core();
if (g7Core?.navigate) {
g7Core.navigate(path);
} else {
window.location.href = path;
}
}
}, [actualUserId]);
// 클릭 핸들러 (드롭다운 또는 프로필 이동)
const handleClick = useCallback((e: React.MouseEvent) => {
e.preventDefault();
if (stopPropagation) {
e.stopPropagation();
}
// 비회원이거나 userId가 없으면 아무 동작 안 함
if (actualIsGuest || !actualUserId) {
return;
}
// 드롭다운이 활성화된 경우
if (showDropdown) {
if (!showMenu) {
updateMenuPosition();
}
setShowMenu((prev) => !prev);
}
// 드롭다운이 비활성화되고 클릭 가능한 경우
else if (clickable) {
getG7Core()?.navigate?.(actualProfilePath);
}
}, [stopPropagation, actualIsGuest, actualUserId, showDropdown, showMenu, updateMenuPosition, clickable, actualProfilePath]);
// 비회원인 경우
if (actualIsGuest || !actualUserId) {
return (
<Div className={containerClass}>
<Div className="flex items-center gap-1.5 text-gray-400 dark:text-gray-500">
<Span>{actualName}</Span>
<Span className="text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded">
{t('userinfo.guest_badge')}
</Span>
</Div>
<SubText text={subText} title={subTextTitle} />
</Div>
);
}
// 탈퇴한 사용자인 경우
if (actualIsWithdrawn) {
return (
<Div className={containerClass}>
<Span className="text-gray-400 dark:text-gray-500 line-through">
{actualName}
</Span>
<SubText text={subText} title={subTextTitle} />
</Div>
);
}
// 회원인 경우
const finalMenuItems = getMenuItems();
// className에 text- 색상 클래스가 있으면 nameButtonClass의 기본 색상을 대체
const hasCustomColor = /\btext-\S+/.test(className);
const defaultColorClass = hasCustomColor ? '' : 'text-gray-900 dark:text-white';
const nameButtonClass = (showDropdown || clickable)
? `${defaultColorClass} hover:text-blue-600 dark:hover:text-blue-400 cursor-pointer font-medium`.trim()
: `${defaultColorClass} font-medium`.trim();
return (
<Div ref={containerRef} className={`relative inline-block ${className}`}>
<Div className={LAYOUT_CLASSES[layout]}>
<Button
ref={buttonRef}
onClick={handleClick}
className={nameButtonClass}
>
{actualName}
</Button>
<SubText text={subText} title={subTextTitle} />
</Div>
{/* 드롭다운 메뉴 - Portal로 document.body에 fixed 배치 (overflow-hidden 부모 회피) */}
{showDropdown && showMenu && finalMenuItems.length > 0 && createPortal(
<Div
ref={dropdownRef}
className="fixed w-40 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-[9999]"
style={{ top: menuPosition.top, left: menuPosition.left }}
data-testid="author-dropdown-menu"
>
{finalMenuItems.map((item) => (
<Button
key={item.key}
onClick={(e) => handleMenuItemClick(item, e)}
className="flex items-center justify-start gap-2 w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer"
data-testid={`menu-item-${item.key}`}
>
{item.icon && <Icon name={item.icon} className="w-4 h-4" />}
<Span>{item.label}</Span>
</Button>
))}
</Div>,
document.body
)}
</Div>
);
};
@@ -0,0 +1,172 @@
/**
* ExpandableContent 컴포넌트 테스트
*
* @description 콘텐츠 펼치기/접기 컴포넌트의 동작을 테스트합니다.
*/
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock basic 컴포넌트
vi.mock('../../basic/Div', () => ({
Div: React.forwardRef(({ children, className, style, ...props }: any, ref: any) => (
<div ref={ref} className={className} style={style} {...props}>{children}</div>
)),
}));
vi.mock('../../basic/Button', () => ({
Button: ({ children, onClick, className, type, ...props }: any) => (
<button onClick={onClick} className={className} type={type} {...props}>{children}</button>
),
}));
vi.mock('../../basic/Span', () => ({
Span: ({ children, className, ...props }: any) => (
<span className={className} {...props}>{children}</span>
),
}));
vi.mock('../../basic/Icon', () => ({
Icon: ({ name, size, ...props }: any) => (
<i data-testid={`icon-${name}`} data-size={size} {...props} />
),
}));
// Mock G7Core.t()
(window as any).G7Core = {
t: (key: string) => {
const translations: Record<string, string> = {
'sirsoft-ecommerce.shop.product.expand_detail': '상세정보 펼쳐보기',
'sirsoft-ecommerce.shop.product.collapse_detail': '상세정보 접기',
};
return translations[key] ?? key;
},
};
import { ExpandableContent } from '../ExpandableContent';
describe('ExpandableContent', () => {
beforeEach(() => {
// ResizeObserver mock
global.ResizeObserver = vi.fn().mockImplementation(() => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
}));
});
it('children을 렌더링합니다', () => {
render(
<ExpandableContent>
<p data-testid="content">테스트 콘텐츠</p>
</ExpandableContent>
);
expect(screen.getByTestId('content')).toBeInTheDocument();
expect(screen.getByText('테스트 콘텐츠')).toBeInTheDocument();
});
it('콘텐츠가 짧으면 버튼이 표시되지 않습니다', () => {
render(
<ExpandableContent maxHeight={500}>
<p>짧은 콘텐츠</p>
</ExpandableContent>
);
// scrollHeight가 0 (jsdom)이므로 needsExpand = false
expect(screen.queryByText('상세정보 펼쳐보기')).not.toBeInTheDocument();
});
it('기본 maxHeight가 500입니다', () => {
const { container } = render(
<ExpandableContent>
<p>콘텐츠</p>
</ExpandableContent>
);
// 컴포넌트가 렌더링되었는지 확인
expect(container.firstChild).toBeInTheDocument();
});
it('커스텀 className이 적용됩니다', () => {
const { container } = render(
<ExpandableContent className="custom-class">
<p>콘텐츠</p>
</ExpandableContent>
);
expect(container.firstChild).toHaveClass('custom-class');
});
it('커스텀 expandText/collapseText가 적용됩니다', () => {
// scrollHeight를 강제로 설정하여 needsExpand = true 시뮬레이션
const originalScrollHeight = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
'scrollHeight'
);
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
configurable: true,
get() {
return 1000;
},
});
render(
<ExpandableContent
maxHeight={100}
expandText="더 보기"
collapseText="줄이기"
>
<p>긴 콘텐츠</p>
</ExpandableContent>
);
expect(screen.getByText('더 보기')).toBeInTheDocument();
// 클릭하여 펼치기
fireEvent.click(screen.getByRole('button'));
expect(screen.getByText('줄이기')).toBeInTheDocument();
// 복원
if (originalScrollHeight) {
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', originalScrollHeight);
}
});
it('버튼 클릭 시 펼치기/접기 토글이 됩니다', () => {
const originalScrollHeight = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
'scrollHeight'
);
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
configurable: true,
get() {
return 1000;
},
});
render(
<ExpandableContent maxHeight={100}>
<p>긴 콘텐츠</p>
</ExpandableContent>
);
// 접힌 상태: chevron-down 아이콘
expect(screen.getByTestId('icon-chevron-down')).toBeInTheDocument();
// 펼치기
fireEvent.click(screen.getByRole('button'));
expect(screen.getByTestId('icon-chevron-up')).toBeInTheDocument();
// 다시 접기
fireEvent.click(screen.getByRole('button'));
expect(screen.getByTestId('icon-chevron-down')).toBeInTheDocument();
if (originalScrollHeight) {
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', originalScrollHeight);
}
});
});
@@ -0,0 +1,125 @@
/**
* FileUploader accept 검증 테스트
*
* useFileUploader의 파일 타입 검증 로직을 테스트합니다.
* - 파일 확장자 매칭 (.jpg, .png 등)
* - MIME 타입 와일드카드 매칭 (image/*, video/*)
* - 정확한 MIME 타입 매칭 (image/jpeg)
*
* @vitest-environment jsdom
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
// useFileUploader의 accept 검증 로직만 추출하여 테스트
function isFileAccepted(file: File, accept: string): boolean {
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
const acceptedTypes = accept.split(',').map((e) => e.trim().toLowerCase());
return acceptedTypes.some((accepted) => {
if (accepted.includes('/')) {
if (accepted.endsWith('/*')) {
const mimePrefix = accepted.slice(0, -2);
return file.type.toLowerCase().startsWith(mimePrefix + '/');
}
return file.type.toLowerCase() === accepted;
}
return ext === accepted;
});
}
describe('FileUploader accept 검증', () => {
describe('파일 확장자 매칭', () => {
it('.jpg 확장자 허용', () => {
const file = new File([''], 'photo.jpg', { type: 'image/jpeg' });
expect(isFileAccepted(file, '.jpg,.png')).toBe(true);
});
it('.pdf 확장자 허용', () => {
const file = new File([''], 'doc.pdf', { type: 'application/pdf' });
expect(isFileAccepted(file, '.jpg,.png,.pdf')).toBe(true);
});
it('.exe 확장자 거부', () => {
const file = new File([''], 'app.exe', { type: 'application/x-msdownload' });
expect(isFileAccepted(file, '.jpg,.png,.pdf')).toBe(false);
});
it('대소문자 무시', () => {
const file = new File([''], 'photo.JPG', { type: 'image/jpeg' });
expect(isFileAccepted(file, '.jpg,.png')).toBe(true);
});
});
describe('MIME 타입 와일드카드 매칭', () => {
it('image/* 와일드카드로 JPEG 허용', () => {
const file = new File([''], 'photo.jpg', { type: 'image/jpeg' });
expect(isFileAccepted(file, 'image/*')).toBe(true);
});
it('image/* 와일드카드로 PNG 허용', () => {
const file = new File([''], 'photo.png', { type: 'image/png' });
expect(isFileAccepted(file, 'image/*')).toBe(true);
});
it('image/* 와일드카드로 WebP 허용', () => {
const file = new File([''], 'photo.webp', { type: 'image/webp' });
expect(isFileAccepted(file, 'image/*')).toBe(true);
});
it('image/* 와일드카드로 GIF 허용', () => {
const file = new File([''], 'anim.gif', { type: 'image/gif' });
expect(isFileAccepted(file, 'image/*')).toBe(true);
});
it('image/* 와일드카드로 PDF 거부', () => {
const file = new File([''], 'doc.pdf', { type: 'application/pdf' });
expect(isFileAccepted(file, 'image/*')).toBe(false);
});
it('video/* 와일드카드로 MP4 허용', () => {
const file = new File([''], 'video.mp4', { type: 'video/mp4' });
expect(isFileAccepted(file, 'video/*')).toBe(true);
});
it('audio/* 와일드카드로 MP3 허용', () => {
const file = new File([''], 'song.mp3', { type: 'audio/mpeg' });
expect(isFileAccepted(file, 'audio/*')).toBe(true);
});
});
describe('정확한 MIME 타입 매칭', () => {
it('image/jpeg 정확한 매칭', () => {
const file = new File([''], 'photo.jpg', { type: 'image/jpeg' });
expect(isFileAccepted(file, 'image/jpeg')).toBe(true);
});
it('image/png과 image/jpeg 불일치', () => {
const file = new File([''], 'photo.png', { type: 'image/png' });
expect(isFileAccepted(file, 'image/jpeg')).toBe(false);
});
});
describe('혼합 accept 값', () => {
it('확장자 + MIME 와일드카드 혼합', () => {
const jpgFile = new File([''], 'photo.jpg', { type: 'image/jpeg' });
const pdfFile = new File([''], 'doc.pdf', { type: 'application/pdf' });
const zipFile = new File([''], 'archive.zip', { type: 'application/zip' });
const accept = 'image/*,.pdf';
expect(isFileAccepted(jpgFile, accept)).toBe(true);
expect(isFileAccepted(pdfFile, accept)).toBe(true);
expect(isFileAccepted(zipFile, accept)).toBe(false);
});
it('여러 MIME 와일드카드', () => {
const imgFile = new File([''], 'photo.jpg', { type: 'image/jpeg' });
const videoFile = new File([''], 'clip.mp4', { type: 'video/mp4' });
const pdfFile = new File([''], 'doc.pdf', { type: 'application/pdf' });
const accept = 'image/*,video/*';
expect(isFileAccepted(imgFile, accept)).toBe(true);
expect(isFileAccepted(videoFile, accept)).toBe(true);
expect(isFileAccepted(pdfFile, accept)).toBe(false);
});
});
});
@@ -0,0 +1,160 @@
/**
* FileUploader initialFiles 참조 안정성 테스트
*
* initialFiles 기본값이 매 렌더마다 새 배열을 생성하여
* useEffect 무한 루프를 발생시키는 버그의 회귀 방지 테스트입니다.
*
* 근본 원인: FileUploader.tsx에서 `initialFiles = []` 기본값이
* 매 렌더마다 새 참조를 생성 → useEffect [initialFiles] 의존성 변경 감지 →
* setExistingFiles([]) 호출 → 재렌더링 → 무한 루프
*
* 수정: EMPTY_FILES 모듈 상수 + useMemo 기반 참조 안정화
*
* @vitest-environment jsdom
*/
import { describe, it, expect } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useRef, useMemo } from 'react';
/**
* useFileUploader의 stableInitialFiles 패턴을 추출하여 테스트
* (실제 훅은 G7Core 의존성이 많아 순수 로직만 검증)
*/
interface Attachment {
id: number;
[key: string]: any;
}
function useStableInitialFiles(initialFiles: Attachment[]) {
const prevRef = useRef<Attachment[]>(initialFiles);
const stable = useMemo(() => {
const prev = prevRef.current;
if (prev === initialFiles) return prev;
if (prev.length !== initialFiles.length) {
prevRef.current = initialFiles;
return initialFiles;
}
if (prev.length === 0 && initialFiles.length === 0) return prev;
const changed = initialFiles.some((f, i) => f.id !== prev[i]?.id);
if (changed) {
prevRef.current = initialFiles;
return initialFiles;
}
return prev;
}, [initialFiles]);
return stable;
}
describe('FileUploader initialFiles 참조 안정성', () => {
describe('빈 배열 안정화', () => {
it('매 렌더마다 새 빈 배열 전달 시 동일 참조 유지', () => {
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: [] as Attachment[] } }
);
const firstRef = result.current;
// 새 빈 배열로 rerender
rerender({ files: [] });
expect(result.current).toBe(firstRef);
// 다시 새 빈 배열로 rerender
rerender({ files: [] });
expect(result.current).toBe(firstRef);
});
it('동일 참조 전달 시 그대로 반환', () => {
const STABLE: Attachment[] = [];
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: STABLE } }
);
const firstRef = result.current;
rerender({ files: STABLE });
expect(result.current).toBe(firstRef);
});
});
describe('실제 변경 감지', () => {
it('파일이 추가되면 새 참조 반환', () => {
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: [] as Attachment[] } }
);
const firstRef = result.current;
// 파일 추가
rerender({ files: [{ id: 1, name: 'test.jpg' }] });
expect(result.current).not.toBe(firstRef);
expect(result.current).toHaveLength(1);
});
it('파일 ID가 변경되면 새 참조 반환', () => {
const files1 = [{ id: 1, name: 'a.jpg' }, { id: 2, name: 'b.jpg' }];
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: files1 } }
);
const firstRef = result.current;
// 동일 길이지만 다른 ID
const files2 = [{ id: 1, name: 'a.jpg' }, { id: 3, name: 'c.jpg' }];
rerender({ files: files2 });
expect(result.current).not.toBe(firstRef);
});
it('동일 ID 배열은 새 참조여도 이전 참조 유지', () => {
const files1 = [{ id: 1, name: 'a.jpg' }, { id: 2, name: 'b.jpg' }];
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: files1 } }
);
const firstRef = result.current;
// 새 배열이지만 동일 ID 구성
const files2 = [{ id: 1, name: 'a.jpg' }, { id: 2, name: 'b.jpg' }];
rerender({ files: files2 });
expect(result.current).toBe(firstRef);
});
it('파일 개수가 줄어들면 새 참조 반환', () => {
const files1 = [{ id: 1 }, { id: 2 }] as Attachment[];
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: files1 } }
);
const firstRef = result.current;
rerender({ files: [{ id: 1 }] as Attachment[] });
expect(result.current).not.toBe(firstRef);
});
});
describe('무한 루프 방지 시나리오', () => {
it('100회 연속 새 빈 배열 전달에도 참조 안정 유지', () => {
const { result, rerender } = renderHook(
({ files }) => useStableInitialFiles(files),
{ initialProps: { files: [] as Attachment[] } }
);
const firstRef = result.current;
for (let i = 0; i < 100; i++) {
rerender({ files: [] }); // 매번 새 [] 참조
}
// 100회 후에도 동일 참조 — 무한 루프 방지 확인
expect(result.current).toBe(firstRef);
});
});
});
@@ -0,0 +1,210 @@
/**
* FileUploader 업로드 응답 파싱 테스트
*
* uploadSingleFile의 응답 파싱 로직과 null attachment 방어를 검증합니다.
* - 정상 응답: pendingFile 제거 + existingFile 추가
* - data 누락 응답: pendingFile을 에러 상태로 전환
*
* @vitest-environment jsdom
* @module composite/__tests__/FileUploaderUpload.test
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { act, renderHook } from '@testing-library/react';
import { useFileUploader } from '../FileUploader/useFileUploader';
import type { Attachment } from '../FileUploader/types';
// G7Core 모킹
// 주의: useFileUploader.ts가 모듈 스코프에서 G7Core = (window as any).G7Core를 캐싱하므로
// window.G7Core를 새 객체로 교체하면 참조가 끊어짐 → 기존 객체에 프로퍼티를 직접 추가해야 함
beforeEach(() => {
const listeners = new Map<string, Set<Function>>();
if (!(window as any).G7Core) {
(window as any).G7Core = {};
}
const g7 = (window as any).G7Core;
g7.componentEvent = {
on: vi.fn((event: string, callback: Function) => {
if (!listeners.has(event)) {
listeners.set(event, new Set());
}
listeners.get(event)!.add(callback);
return () => {
listeners.get(event)?.delete(callback);
};
}),
emit: vi.fn(async (event: string, data?: any) => {
const eventListeners = listeners.get(event);
if (!eventListeners) return [];
const results = [];
for (const listener of eventListeners) {
results.push(await listener(data));
}
return results;
}),
};
g7.createLogger = vi.fn(() => ({
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}));
});
// browser-image-compression 모킹
vi.mock('browser-image-compression', () => ({
default: vi.fn((file: File) => Promise.resolve(file)),
}));
// Node.js의 URL.createObjectURL은 jsdom 환경에서 Blob 인스턴스 불일치로 실패 → mock 필수
URL.createObjectURL = vi.fn(() => 'blob:mock-url');
URL.revokeObjectURL = vi.fn();
// 테스트 헬퍼: Attachment 생성
function createAttachment(overrides: Partial<Attachment> = {}): Attachment {
const id = overrides.id ?? Math.floor(Math.random() * 10000);
return {
id,
hash: `hash_${id}`,
original_filename: `image_${id}.jpg`,
mime_type: 'image/jpeg',
size: 1024,
size_formatted: '1 KB',
download_url: `/api/admin/attachments/${id}/download`,
order: 1,
is_image: true,
...overrides,
};
}
describe('FileUploader - 업로드 응답 파싱 (useFileUploader 훅 직접 테스트)', () => {
// 업로드 테스트에서만 api mock 설정
// 전체 컴포넌트 대신 훅만 테스트하여 DndContext/SortableThumbnailItem 등의
// 컴포넌트 트리 오버헤드 없이 업로드 로직(응답 파싱, 에러 처리)을 검증
const defaultEndpoints = {
upload: '/api/attachments',
delete: '/api/attachments/:id',
reorder: '/api/attachments/reorder',
};
// 안정적인 참조 — renderHook 콜백 내에서 매 렌더마다 새 [] 생성하면
// initialFiles 변경 감지 → setExistingFiles → 재렌더 → 무한 루프 발생
const STABLE_EMPTY_FILES: Attachment[] = [];
const STABLE_EMPTY_ROLE_IDS: number[] = [];
beforeEach(() => {
const g7 = (window as any).G7Core;
g7.api = {
delete: vi.fn().mockResolvedValue({}),
post: vi.fn().mockResolvedValue({ data: {} }),
// 인증 이미지 로딩은 테스트 대상이 아님 → 즉시 실패시켜 async 체인 방지
get: vi.fn(() => { throw new Error('test: skip auth image'); }),
};
});
afterEach(() => {
// api mock 정리 — 다른 테스트에 영향 방지
delete (window as any).G7Core.api;
});
it('uploadSingleFile이 올바른 응답을 파싱하여 pendingFile을 제거하고 existingFile에 추가한다', async () => {
const uploadedAttachment = createAttachment({ id: 100, original_filename: 'uploaded.jpg' });
// G7Core.api.post가 ResponseHelper 형식 응답 반환 (ApiClient가 Axios response.data를 반환)
(window as any).G7Core.api.post = vi.fn().mockResolvedValue({
success: true,
message: 'Upload success',
data: uploadedAttachment,
});
const { result } = renderHook(() =>
useFileUploader({
collection: 'test',
maxFiles: 5,
maxSize: 10,
maxConcurrentUploads: 3,
roleIds: STABLE_EMPTY_ROLE_IDS,
autoUpload: false,
initialFiles: STABLE_EMPTY_FILES,
confirmBeforeRemove: false,
endpoints: defaultEndpoints,
})
);
// 파일 추가 (FileList mock)
const testFile = new File(['test content'], 'test-image.png', { type: 'image/png' });
await act(async () => {
const fileList = { 0: testFile, length: 1, item: () => testFile } as unknown as FileList;
await result.current.handleFiles(fileList);
});
// pendingFile이 추가되었는지 확인
expect(result.current.pendingFiles).toHaveLength(1);
expect(result.current.pendingFiles[0].original_filename).toBe('test-image.png');
expect(result.current.pendingFiles[0].status).toBe('pending');
// 업로드 실행
await act(async () => {
await result.current.handleUploadAll();
});
// api.post가 호출되었는지 확인
expect((window as any).G7Core.api.post).toHaveBeenCalled();
// 업로드 완료 후: pendingFile 제거, existingFile에 추가
expect(result.current.pendingFiles).toHaveLength(0);
expect(result.current.existingFiles).toHaveLength(1);
expect(result.current.existingFiles[0].original_filename).toBe('uploaded.jpg');
expect(result.current.existingFiles[0].id).toBe(100);
});
it('uploadSingleFile 응답에 data가 없으면 pendingFile을 에러 상태로 전환한다', async () => {
// API 응답에 data 없음 → response?.data = undefined → attachment null
(window as any).G7Core.api.post = vi.fn().mockResolvedValue({
success: true,
message: 'Upload success',
// data 필드 누락
});
const onUploadError = vi.fn();
const { result } = renderHook(() =>
useFileUploader({
collection: 'test',
maxFiles: 5,
maxSize: 10,
maxConcurrentUploads: 3,
roleIds: STABLE_EMPTY_ROLE_IDS,
autoUpload: false,
initialFiles: STABLE_EMPTY_FILES,
confirmBeforeRemove: false,
onUploadError,
endpoints: defaultEndpoints,
})
);
// 파일 추가
const testFile = new File(['test'], 'invalid-response.png', { type: 'image/png' });
await act(async () => {
const fileList = { 0: testFile, length: 1, item: () => testFile } as unknown as FileList;
await result.current.handleFiles(fileList);
});
// 파일 추가 확인
expect(result.current.pendingFiles).toHaveLength(1);
// 업로드 실행
await act(async () => {
await result.current.handleUploadAll();
});
// 에러 콜백이 호출되어야 함 (업로드중 영구 잔류 대신 에러 상태)
expect(onUploadError).toHaveBeenCalled();
expect(onUploadError.mock.calls[0][0]).toContain('invalid-response.png');
// pendingFile이 에러 상태로 전환됨 (uploading 상태로 영구 잔류하지 않음)
expect(result.current.pendingFiles).toHaveLength(1);
expect(result.current.pendingFiles[0].status).toBe('error');
});
});
@@ -0,0 +1,136 @@
/**
* Header 컴포넌트 테스트
*
* @description 사이트 헤더 컴포넌트의 렌더링 및 동작을 테스트합니다.
*/
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
// G7Core mock
const mockG7Core = {
t: vi.fn((key: string, params?: Record<string, string | number>) => {
const translations: Record<string, string> = {
'nav.home': '홈',
'nav.popular': '인기글',
'nav.shop': '쇼핑',
'nav.cart': '장바구니',
'auth.login': '로그인',
'auth.register': '회원가입',
};
return translations[key] ?? key;
}),
};
// window.G7Core mock 설정
beforeEach(() => {
(window as any).G7Core = mockG7Core;
});
// Header 컴포넌트 mock (basic 컴포넌트 의존성 때문에)
const MockHeader: React.FC<{
logo?: string;
siteName?: string;
user?: { id: number; name: string } | null;
cartCount?: number;
boards?: { id: number; name: string; slug: string }[];
}> = ({ logo, siteName = '그누보드7', user, cartCount = 0, boards = [] }) => {
const t = (key: string) => mockG7Core.t(key);
return (
<header data-testid="header">
<a href="/" data-testid="logo-link">
{logo ? <img src={logo} alt={siteName} /> : <span>{siteName}</span>}
</a>
<nav data-testid="main-nav">
<a href="/">{t('nav.home')}</a>
<a href="/popular">{t('nav.popular')}</a>
<a href="/shop">{t('nav.shop')}</a>
{boards.map((board) => (
<a key={board.id} href={`/board/${board.slug}`}>
{board.name}
</a>
))}
</nav>
<div data-testid="user-area">
{user ? (
<span data-testid="user-name">{user.name}</span>
) : (
<>
<a href="/login">{t('auth.login')}</a>
<a href="/register">{t('auth.register')}</a>
</>
)}
</div>
{cartCount > 0 && (
<span data-testid="cart-count">{cartCount}</span>
)}
</header>
);
};
describe('Header 컴포넌트', () => {
describe('렌더링', () => {
it('기본 헤더가 렌더링되어야 함', () => {
render(<MockHeader />);
expect(screen.getByTestId('header')).toBeInTheDocument();
});
it('사이트 이름이 표시되어야 함', () => {
render(<MockHeader siteName="테스트 사이트" />);
expect(screen.getByText('테스트 사이트')).toBeInTheDocument();
});
it('로고 이미지가 있으면 이미지로 표시되어야 함', () => {
render(<MockHeader logo="/logo.png" siteName="테스트" />);
const img = screen.getByAltText('테스트');
expect(img).toHaveAttribute('src', '/logo.png');
});
});
describe('네비게이션', () => {
it('기본 메뉴 항목이 표시되어야 함', () => {
render(<MockHeader />);
expect(screen.getByText('홈')).toBeInTheDocument();
expect(screen.getByText('인기글')).toBeInTheDocument();
expect(screen.getByText('쇼핑')).toBeInTheDocument();
});
it('게시판 목록이 표시되어야 함', () => {
const boards = [
{ id: 1, name: '자유게시판', slug: 'free' },
{ id: 2, name: '질문답변', slug: 'qna' },
];
render(<MockHeader boards={boards} />);
expect(screen.getByText('자유게시판')).toBeInTheDocument();
expect(screen.getByText('질문답변')).toBeInTheDocument();
});
});
describe('사용자 상태', () => {
it('비로그인 시 로그인/회원가입 버튼이 표시되어야 함', () => {
render(<MockHeader user={null} />);
expect(screen.getByText('로그인')).toBeInTheDocument();
expect(screen.getByText('회원가입')).toBeInTheDocument();
});
it('로그인 시 사용자 이름이 표시되어야 함', () => {
const user = { id: 1, name: '홍길동' };
render(<MockHeader user={user} />);
expect(screen.getByTestId('user-name')).toHaveTextContent('홍길동');
});
});
describe('장바구니', () => {
it('장바구니에 아이템이 있으면 카운트가 표시되어야 함', () => {
render(<MockHeader cartCount={3} />);
expect(screen.getByTestId('cart-count')).toHaveTextContent('3');
});
it('장바구니가 비어있으면 카운트가 표시되지 않아야 함', () => {
render(<MockHeader cartCount={0} />);
expect(screen.queryByTestId('cart-count')).not.toBeInTheDocument();
});
});
});
Loaded 100 of 3967 files, more files were not shown because too many files have changed in this diff. Show more