v7.0.0-beta.2 release
This commit is contained in:
1 parent
6595fd0eb5
commit
fa8eba7a0d
1165 files changed
+107118
-762127
No files matched your search
+92
-2
@@ -1,8 +1,8 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
|
||||
import { render, screen, waitFor, cleanup } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, rmdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { CodeEditor } from '../composite/CodeEditor';
|
||||
import { LayoutFileList, LayoutFileItem } from '../composite/LayoutFileList';
|
||||
@@ -42,6 +42,67 @@ vi.mock('@monaco-editor/react', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const FIXTURES_DIR = join(__dirname, '__fixtures__');
|
||||
const FIXTURE_FILES = [
|
||||
{ size: 1, filename: 'test-1mb.json' },
|
||||
{ size: 5, filename: 'test-5mb.json' },
|
||||
{ size: 10, filename: 'test-10mb.json' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 대용량 JSON 데이터 생성 (generate-test-fixtures.ts와 동일 로직)
|
||||
*/
|
||||
const generateLargeJSON = (sizeInMB: number): string => {
|
||||
const targetSize = sizeInMB * 1024 * 1024;
|
||||
const baseObject = {
|
||||
id: 1,
|
||||
name: 'test-layout',
|
||||
version: '1.0.0',
|
||||
components: [] as any[],
|
||||
};
|
||||
|
||||
const sampleComponent = {
|
||||
id: 'component-0',
|
||||
type: 'div',
|
||||
className: 'container flex flex-col items-center justify-center p-4 m-2',
|
||||
children: [
|
||||
{ id: 'child-0-1', type: 'h1', className: 'text-2xl font-bold', content: 'Title Component' },
|
||||
{ id: 'child-0-2', type: 'p', className: 'text-base', content: 'Description text for the component' },
|
||||
],
|
||||
metadata: {
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
author: 'system',
|
||||
tags: ['component', 'layout', 'container', 'responsive'],
|
||||
},
|
||||
};
|
||||
|
||||
const sampleJSON = JSON.stringify({ components: [sampleComponent] }, null, 2);
|
||||
const componentSize = sampleJSON.length - JSON.stringify({ components: [] }, null, 2).length;
|
||||
const baseSize = JSON.stringify(baseObject).length;
|
||||
const componentsNeeded = Math.ceil((targetSize - baseSize) / componentSize * 1.1);
|
||||
|
||||
for (let i = 0; i < componentsNeeded; i++) {
|
||||
baseObject.components.push({
|
||||
id: `component-${i}`,
|
||||
type: 'div',
|
||||
className: 'container flex flex-col items-center justify-center p-4 m-2',
|
||||
children: [
|
||||
{ id: `child-${i}-1`, type: 'h1', className: 'text-2xl font-bold', content: `Title Component ${i}` },
|
||||
{ id: `child-${i}-2`, type: 'p', className: 'text-base', content: `Description text for the component ${i}` },
|
||||
],
|
||||
metadata: {
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
author: 'system',
|
||||
tags: ['component', 'layout', 'container', 'responsive'],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return JSON.stringify(baseObject, null, 2);
|
||||
};
|
||||
|
||||
/**
|
||||
* 픽스처 파일에서 테스트 데이터 로드
|
||||
*/
|
||||
@@ -77,6 +138,35 @@ const generateLargeVersionList = (count: number): VersionItem[] => {
|
||||
};
|
||||
|
||||
describe('레이아웃 에디터 성능 테스트', () => {
|
||||
beforeAll(() => {
|
||||
// fixture 디렉토리 생성
|
||||
if (!existsSync(FIXTURES_DIR)) {
|
||||
mkdirSync(FIXTURES_DIR, { recursive: true });
|
||||
}
|
||||
// fixture 파일 생성
|
||||
for (const { size, filename } of FIXTURE_FILES) {
|
||||
const filePath = join(FIXTURES_DIR, filename);
|
||||
if (!existsSync(filePath)) {
|
||||
const data = generateLargeJSON(size);
|
||||
writeFileSync(filePath, data, 'utf-8');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
// fixture 파일 삭제
|
||||
for (const { filename } of FIXTURE_FILES) {
|
||||
const filePath = join(FIXTURES_DIR, filename);
|
||||
if (existsSync(filePath)) {
|
||||
unlinkSync(filePath);
|
||||
}
|
||||
}
|
||||
// fixture 디렉토리 삭제 (비어있을 때만)
|
||||
if (existsSync(FIXTURES_DIR)) {
|
||||
try { rmdirSync(FIXTURES_DIR); } catch { /* 디렉토리가 비어있지 않으면 무시 */ }
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
-450007
File diff suppressed because it is too large.
Load diff
-45007
File diff suppressed because it is too large.
Load diff
-225007
File diff suppressed because it is too large.
Load diff
@@ -5,8 +5,8 @@ export interface FileInputProps extends Omit<React.InputHTMLAttributes<HTMLInput
|
||||
accept?: string;
|
||||
/** 최대 파일 크기 (MB) */
|
||||
maxSize?: number;
|
||||
/** 파일 선택 시 콜백 */
|
||||
onChange?: (file: File | null) => void;
|
||||
/** 파일 선택 시 콜백 ({ target: { value } } 패턴) */
|
||||
onChange?: (event: { target: { value: File | null; name: string } }) => void;
|
||||
/** 에러 발생 시 콜백 */
|
||||
onError?: (error: string) => void;
|
||||
/** 버튼 텍스트 */
|
||||
@@ -46,7 +46,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
|
||||
|
||||
if (!file) {
|
||||
setFileName('');
|
||||
onChange?.(null);
|
||||
onChange?.({ target: { value: null, name: '' } });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
|
||||
}
|
||||
|
||||
setFileName(file.name);
|
||||
onChange?.(file);
|
||||
onChange?.({ target: { value: file, name: file.name } });
|
||||
}, [maxSize, onChange, onError, inputRef]);
|
||||
|
||||
const handleClear = useCallback((e: React.MouseEvent) => {
|
||||
@@ -72,7 +72,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
|
||||
inputRef.current.value = '';
|
||||
}
|
||||
setFileName('');
|
||||
onChange?.(null);
|
||||
onChange?.({ target: { value: null, name: '' } });
|
||||
}, [onChange, inputRef]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import React, { useMemo, useState, useRef, useEffect } from 'react';
|
||||
import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Div } from './Div';
|
||||
import { Button } from './Button';
|
||||
import { Span } from './Span';
|
||||
import { Svg } from './Svg';
|
||||
import { Input } from './Input';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('Comp:Select')) ?? {
|
||||
@@ -22,6 +24,10 @@ export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectE
|
||||
error?: string;
|
||||
options?: SelectOption[] | string[];
|
||||
onChange?: (e: React.ChangeEvent<HTMLSelectElement> | { target: { value: string | number } }) => void;
|
||||
/** 드롭다운 내 검색 input 활성화 (engine-v1.40.0+) */
|
||||
searchable?: boolean;
|
||||
/** 검색 input placeholder */
|
||||
searchPlaceholder?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,11 +62,17 @@ export const Select: React.FC<SelectProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
searchable = false,
|
||||
searchPlaceholder,
|
||||
...props
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [dropdownPos, setDropdownPos] = useState<{ top?: number; bottom?: number; left: number; width: number } | null>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// options를 SelectOption[] 형식으로 정규화
|
||||
const normalizedOptions = useMemo((): SelectOption[] | null => {
|
||||
@@ -94,10 +106,79 @@ export const Select: React.FC<SelectProps> = ({
|
||||
return selected?.label || '';
|
||||
}, [normalizedOptions, value]);
|
||||
|
||||
// 외부 클릭 시 드롭다운 닫기
|
||||
// searchable 모드에서 검색어로 필터링된 옵션
|
||||
const visibleOptions = useMemo((): SelectOption[] | null => {
|
||||
if (!normalizedOptions) return null;
|
||||
if (!searchable || searchTerm.trim() === '') return normalizedOptions;
|
||||
const needle = searchTerm.trim().toLowerCase();
|
||||
return normalizedOptions.filter(opt =>
|
||||
opt.label.toLowerCase().includes(needle) ||
|
||||
String(opt.value).toLowerCase().includes(needle)
|
||||
);
|
||||
}, [normalizedOptions, searchable, searchTerm]);
|
||||
|
||||
// 드롭다운 열릴 때 검색어 초기화 및 input 포커스
|
||||
useEffect(() => {
|
||||
if (isOpen && searchable) {
|
||||
setSearchTerm('');
|
||||
// 다음 tick에 포커스 (DOM 렌더 이후)
|
||||
const timer = setTimeout(() => searchInputRef.current?.focus(), 0);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
if (!isOpen) {
|
||||
setSearchTerm('');
|
||||
}
|
||||
}, [isOpen, searchable]);
|
||||
|
||||
/**
|
||||
* 드롭다운 위치 계산 (버튼 기준 fixed positioning)
|
||||
* Modal 등 overflow:hidden 컨테이너 내부에서도 정상 표시
|
||||
*/
|
||||
const updateDropdownPos = useCallback(() => {
|
||||
if (!buttonRef.current) return;
|
||||
const rect = buttonRef.current.getBoundingClientRect();
|
||||
const spaceBelow = window.innerHeight - rect.bottom;
|
||||
const dropdownMaxH = 280; // max-h-60(240px) + search(~40px)
|
||||
// 아래 공간 부족 시 위로 열기
|
||||
const openUpward = spaceBelow < dropdownMaxH && rect.top > spaceBelow;
|
||||
if (openUpward) {
|
||||
setDropdownPos({
|
||||
bottom: window.innerHeight - rect.top + 4,
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
});
|
||||
} else {
|
||||
setDropdownPos({
|
||||
top: rect.bottom + 4,
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 드롭다운 열릴 때 위치 계산 + 스크롤/리사이즈 추적
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setDropdownPos(null);
|
||||
return;
|
||||
}
|
||||
updateDropdownPos();
|
||||
window.addEventListener('scroll', updateDropdownPos, true);
|
||||
window.addEventListener('resize', updateDropdownPos);
|
||||
return () => {
|
||||
window.removeEventListener('scroll', updateDropdownPos, true);
|
||||
window.removeEventListener('resize', updateDropdownPos);
|
||||
};
|
||||
}, [isOpen, updateDropdownPos]);
|
||||
|
||||
// 외부 클릭 시 드롭다운 닫기 (Portal 영역 포함)
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||
const target = event.target as Node;
|
||||
if (
|
||||
containerRef.current && !containerRef.current.contains(target) &&
|
||||
(!dropdownRef.current || !dropdownRef.current.contains(target))
|
||||
) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
@@ -190,13 +271,34 @@ export const Select: React.FC<SelectProps> = ({
|
||||
</Svg>
|
||||
</Button>
|
||||
|
||||
{isOpen && (
|
||||
{isOpen && dropdownPos && createPortal(
|
||||
<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"
|
||||
ref={dropdownRef}
|
||||
className="fixed z-[9999] bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 overflow-hidden"
|
||||
style={{ top: dropdownPos.top, bottom: dropdownPos.bottom, left: dropdownPos.left, width: dropdownPos.width }}
|
||||
role="listbox"
|
||||
>
|
||||
{searchable && (
|
||||
<Div className="p-2 border-b border-gray-200 dark:border-gray-600">
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}
|
||||
placeholder={searchPlaceholder ?? 'Search...'}
|
||||
className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-700 border-0 rounded-lg text-sm text-gray-700 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
|
||||
role="searchbox"
|
||||
aria-label={searchPlaceholder ?? 'Search'}
|
||||
/>
|
||||
</Div>
|
||||
)}
|
||||
<Div className="py-2 max-h-60 overflow-auto">
|
||||
{normalizedOptions.map((option) => {
|
||||
{visibleOptions && visibleOptions.length === 0 && (
|
||||
<Div className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 text-center">
|
||||
{searchTerm ? 'No results' : ''}
|
||||
</Div>
|
||||
)}
|
||||
{(visibleOptions ?? []).map((option) => {
|
||||
const isSelected = String(option.value) === String(value);
|
||||
return (
|
||||
<Button
|
||||
@@ -225,7 +327,8 @@ export const Select: React.FC<SelectProps> = ({
|
||||
);
|
||||
})}
|
||||
</Div>
|
||||
</Div>
|
||||
</Div>,
|
||||
document.body
|
||||
)}
|
||||
</Div>
|
||||
);
|
||||
|
||||
+5
-5
@@ -53,7 +53,7 @@ describe('FileInput 컴포넌트', () => {
|
||||
|
||||
fireEvent.change(fileInput);
|
||||
|
||||
expect(handleChange).toHaveBeenCalledWith(file);
|
||||
expect(handleChange).toHaveBeenCalledWith({ target: { value: file, name: 'test.zip' } });
|
||||
});
|
||||
|
||||
it('파일 선택 시 파일명이 표시된다', () => {
|
||||
@@ -114,7 +114,7 @@ describe('FileInput 컴포넌트', () => {
|
||||
fireEvent.change(fileInput);
|
||||
|
||||
expect(handleError).not.toHaveBeenCalled();
|
||||
expect(handleChange).toHaveBeenCalledWith(file);
|
||||
expect(handleChange).toHaveBeenCalledWith({ target: { value: file, name: 'small.zip' } });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -147,12 +147,12 @@ describe('FileInput 컴포넌트', () => {
|
||||
});
|
||||
|
||||
fireEvent.change(fileInput);
|
||||
expect(handleChange).toHaveBeenCalledWith(file);
|
||||
expect(handleChange).toHaveBeenCalledWith({ target: { value: file, name: 'test.zip' } });
|
||||
|
||||
const clearButton = screen.getByLabelText('Clear file');
|
||||
fireEvent.click(clearButton);
|
||||
|
||||
expect(handleChange).toHaveBeenLastCalledWith(null);
|
||||
expect(handleChange).toHaveBeenLastCalledWith({ target: { value: null, name: '' } });
|
||||
expect(screen.getByText('No file selected')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -216,7 +216,7 @@ describe('FileInput 컴포넌트', () => {
|
||||
|
||||
fireEvent.change(fileInput);
|
||||
|
||||
expect(handleChange).toHaveBeenCalledWith(null);
|
||||
expect(handleChange).toHaveBeenCalledWith({ target: { value: null, name: '' } });
|
||||
});
|
||||
});
|
||||
});
|
||||
+120
@@ -614,4 +614,124 @@ describe('Select 컴포넌트', () => {
|
||||
expect(select).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ========================================
|
||||
// searchable 모드 (engine-v1.40.0+)
|
||||
// ========================================
|
||||
describe('searchable 모드', () => {
|
||||
const timezoneOptions = [
|
||||
{ value: 'Asia/Seoul', label: '(UTC+09:00) Asia/Seoul' },
|
||||
{ value: 'Asia/Tokyo', label: '(UTC+09:00) Asia/Tokyo' },
|
||||
{ value: 'America/New_York', label: '(UTC-05:00) America/New_York' },
|
||||
{ value: 'Europe/London', label: '(UTC+00:00) Europe/London' },
|
||||
{ value: 'Pacific/Auckland', label: '(UTC+13:00) Pacific/Auckland' },
|
||||
];
|
||||
|
||||
it('searchable=false 기본값에서는 검색 input이 렌더링되지 않는다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
expect(screen.queryByRole('searchbox')).toBeNull();
|
||||
});
|
||||
|
||||
it('searchable=true 시 드롭다운 내 검색 input이 렌더링된다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} searchable />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
expect(screen.getByRole('searchbox')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('searchPlaceholder가 input placeholder로 적용된다', () => {
|
||||
render(
|
||||
<Select
|
||||
options={timezoneOptions}
|
||||
value="Asia/Seoul"
|
||||
onChange={() => {}}
|
||||
searchable
|
||||
searchPlaceholder="타임존 검색..."
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
const input = screen.getByRole('searchbox') as HTMLInputElement;
|
||||
expect(input.placeholder).toBe('타임존 검색...');
|
||||
});
|
||||
|
||||
it('검색어 입력 시 라벨 기준으로 옵션이 필터링된다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} searchable />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
|
||||
const input = screen.getByRole('searchbox');
|
||||
fireEvent.change(input, { target: { value: 'tokyo' } });
|
||||
|
||||
const visibleOptions = screen.getAllByRole('option');
|
||||
expect(visibleOptions.length).toBe(1);
|
||||
expect(visibleOptions[0].textContent).toContain('Asia/Tokyo');
|
||||
});
|
||||
|
||||
it('검색은 대소문자를 구분하지 않는다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} searchable />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'LONDON' } });
|
||||
|
||||
const visibleOptions = screen.getAllByRole('option');
|
||||
expect(visibleOptions.length).toBe(1);
|
||||
expect(visibleOptions[0].textContent).toContain('Europe/London');
|
||||
});
|
||||
|
||||
it('value 문자열에 대해서도 검색된다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} searchable />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'pacific' } });
|
||||
|
||||
const visibleOptions = screen.getAllByRole('option');
|
||||
expect(visibleOptions.length).toBe(1);
|
||||
expect(visibleOptions[0].textContent).toContain('Pacific/Auckland');
|
||||
});
|
||||
|
||||
it('검색 결과가 없으면 "No results" 메시지가 표시된다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} searchable />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'nonexistent-zzz' } });
|
||||
|
||||
expect(screen.queryAllByRole('option').length).toBe(0);
|
||||
expect(screen.getByText('No results')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('필터된 옵션 선택 시 onChange가 호출되고 드롭다운이 닫힌다', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={handleChange} searchable />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'tokyo' } });
|
||||
|
||||
const tokyoOption = screen.getAllByRole('option')[0];
|
||||
fireEvent.click(tokyoOption);
|
||||
|
||||
expect(handleChange).toHaveBeenCalledTimes(1);
|
||||
expect(handleChange).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ target: { value: 'Asia/Tokyo' } })
|
||||
);
|
||||
expect(screen.queryByRole('listbox')).toBeNull();
|
||||
});
|
||||
|
||||
it('드롭다운을 다시 열면 검색어가 초기화된다', () => {
|
||||
render(<Select options={timezoneOptions} value="Asia/Seoul" onChange={() => {}} searchable />);
|
||||
|
||||
// 첫 번째 열기 + 필터링
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'tokyo' } });
|
||||
expect(screen.getAllByRole('option').length).toBe(1);
|
||||
|
||||
// 닫기 (외부 클릭 대신 ESC)
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
expect(screen.queryByRole('listbox')).toBeNull();
|
||||
|
||||
// 다시 열기 — 검색어가 초기화되어 모든 옵션이 보여야 함
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
expect(screen.getAllByRole('option').length).toBe(timezoneOptions.length);
|
||||
const input = screen.getByRole('searchbox') as HTMLInputElement;
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -168,6 +168,8 @@ export interface DataGridFooterCell {
|
||||
}
|
||||
|
||||
export interface DataGridProps {
|
||||
/** DOM id (transition_overlay.target / overlay_target 으로 spinner mount 영역 지정용) */
|
||||
id?: string;
|
||||
columns: DataGridColumn[];
|
||||
data: any[];
|
||||
sortable?: boolean;
|
||||
@@ -556,6 +558,7 @@ const renderSubRowChildren = (
|
||||
* }
|
||||
*/
|
||||
export const DataGrid: React.FC<DataGridProps> = ({
|
||||
id,
|
||||
columns,
|
||||
data,
|
||||
sortable = true,
|
||||
@@ -1112,7 +1115,7 @@ export const DataGrid: React.FC<DataGridProps> = ({
|
||||
// 모바일 카드 뷰
|
||||
if (isMobileView) {
|
||||
return (
|
||||
<Div className={`w-full ${className}`} style={style}>
|
||||
<Div id={id} className={`w-full ${className}`} style={style}>
|
||||
{/* 컬럼 선택 메뉴 */}
|
||||
{showColumnSelector && (
|
||||
<Div className="mb-4 flex justify-end">
|
||||
@@ -1168,20 +1171,22 @@ export const DataGrid: React.FC<DataGridProps> = ({
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 카드 목록 */}
|
||||
{paginatedData && paginatedData.length > 0 ? (
|
||||
paginatedData.map((row, index) => (
|
||||
<Div key={row[idField] || index}>
|
||||
{cardRenderer
|
||||
? cardRenderer(row, displayColumns)
|
||||
: defaultCardRenderer(row, displayColumns)}
|
||||
{/* 카드 목록 — body wrapper 에 `${id}__body` 부여 (pagination 제외 영역) */}
|
||||
<Div id={id ? `${id}__body` : undefined}>
|
||||
{paginatedData && paginatedData.length > 0 ? (
|
||||
paginatedData.map((row, index) => (
|
||||
<Div key={row[idField] || index}>
|
||||
{cardRenderer
|
||||
? cardRenderer(row, displayColumns)
|
||||
: defaultCardRenderer(row, displayColumns)}
|
||||
</Div>
|
||||
))
|
||||
) : (
|
||||
<Div className="text-center py-8 text-gray-500 dark:text-gray-400">
|
||||
{resolvedEmptyMessage}
|
||||
</Div>
|
||||
))
|
||||
) : (
|
||||
<Div className="text-center py-8 text-gray-500 dark:text-gray-400">
|
||||
{resolvedEmptyMessage}
|
||||
</Div>
|
||||
)}
|
||||
)}
|
||||
</Div>
|
||||
|
||||
{/* 푸터 (모바일 카드 뷰) - v1.19.0+ */}
|
||||
{footerCells && footerCells.length > 0 && paginatedData && paginatedData.length > 0 && (
|
||||
@@ -1229,7 +1234,7 @@ export const DataGrid: React.FC<DataGridProps> = ({
|
||||
|
||||
// 데스크톱 테이블 뷰
|
||||
return (
|
||||
<Div className={`w-full ${className}`} style={style}>
|
||||
<Div id={id} className={`w-full ${className}`} style={style}>
|
||||
{/* 컬럼 선택 메뉴 */}
|
||||
{showColumnSelector && (
|
||||
<Div className="mb-4 flex justify-end">
|
||||
@@ -1285,8 +1290,8 @@ export const DataGrid: React.FC<DataGridProps> = ({
|
||||
</Div>
|
||||
)}
|
||||
|
||||
{/* 테이블 */}
|
||||
<Div className="overflow-x-auto border border-gray-200 dark:border-gray-700 rounded-lg">
|
||||
{/* 테이블 — body wrapper 에 `${id}__body` 부여 (pagination 제외 영역) */}
|
||||
<Div id={id ? `${id}__body` : undefined} className="overflow-x-auto border border-gray-200 dark:border-gray-700 rounded-lg">
|
||||
<Table className="w-full">
|
||||
<Thead className="bg-gray-50 dark:bg-gray-700">
|
||||
<Tr>
|
||||
|
||||
+38
-15
@@ -147,6 +147,8 @@ export function useFileUploader(options: UseFileUploaderOptions): UseFileUploade
|
||||
const galleryKeyRef = useRef(0);
|
||||
// 인증된 이미지 URL 캐시 (기존 첨부파일용)
|
||||
const [authenticatedImageUrls, setAuthenticatedImageUrls] = useState<Map<number, string>>(new Map());
|
||||
// ref로 URL 캐시 추적 (stale closure 방지 — cleanup/has 체크에서 항상 최신 참조)
|
||||
const authenticatedImageUrlsRef = useRef<Map<number, string>>(new Map());
|
||||
|
||||
// onFilesChange를 ref로 관리하여 useEffect 의존성에서 제거
|
||||
// (Form 자동 바인딩이 매 렌더링마다 새 함수 참조를 생성하므로
|
||||
@@ -651,35 +653,56 @@ export function useFileUploader(options: UseFileUploaderOptions): UseFileUploade
|
||||
|
||||
// 기존 첨부파일 인증된 이미지 URL 로드 (갤러리용)
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const loadAuthenticatedUrls = async () => {
|
||||
const existingImageFiles = existingFiles.filter((f) => f.mime_type?.startsWith('image/') ?? false);
|
||||
// is_image 필드 사용 (imageFiles 필터와 일치)
|
||||
const existingImageFiles = existingFiles.filter((f) => f.is_image);
|
||||
|
||||
// existingFiles에서 제거된 파일의 URL 정리
|
||||
const currentIds = new Set(existingImageFiles.map((f) => f.id));
|
||||
for (const [id, url] of authenticatedImageUrlsRef.current) {
|
||||
if (!currentIds.has(id)) {
|
||||
URL.revokeObjectURL(url);
|
||||
authenticatedImageUrlsRef.current.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of existingImageFiles) {
|
||||
if (!authenticatedImageUrls.has(file.id)) {
|
||||
try {
|
||||
const blob = await G7Core.api.get(file.download_url, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
if (blob) {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
setAuthenticatedImageUrls((prev) => new Map(prev).set(file.id, objectUrl));
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to load authenticated image:', error);
|
||||
if (cancelled) break;
|
||||
// ref 기반 has 체크 (stale closure 방지)
|
||||
if (authenticatedImageUrlsRef.current.has(file.id)) continue;
|
||||
|
||||
try {
|
||||
const blob = await G7Core.api.get(file.download_url, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
if (!cancelled && blob) {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
authenticatedImageUrlsRef.current.set(file.id, objectUrl);
|
||||
setAuthenticatedImageUrls(new Map(authenticatedImageUrlsRef.current));
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to load authenticated image:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadAuthenticatedUrls();
|
||||
|
||||
// 클린업: 컴포넌트 언마운트 시 URL 해제
|
||||
return () => {
|
||||
authenticatedImageUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
cancelled = true;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [existingFiles]);
|
||||
|
||||
// 언마운트 시에만 모든 인증된 이미지 URL 해제
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
authenticatedImageUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
authenticatedImageUrlsRef.current.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 파일 다운로드 실행
|
||||
const handleDownload = useCallback(async (item: Attachment) => {
|
||||
const { executeImageDownload } = await import('../ImageGallery');
|
||||
|
||||
@@ -44,7 +44,6 @@ export interface HtmlContentProps {
|
||||
* @example
|
||||
* // HTML 렌더링 (기본값)
|
||||
* <HtmlContent content="<p>안녕하세요</p>" />
|
||||
* <HtmlContent content="<p>안녕하세요</p>" isHtml={true} />
|
||||
*
|
||||
* // 일반 텍스트 렌더링
|
||||
* <HtmlContent
|
||||
@@ -95,41 +94,57 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
|
||||
);
|
||||
}
|
||||
|
||||
// isHtml=true: HTML 렌더링 (기존 로직)
|
||||
// 기본 DOMPurify 설정
|
||||
// 기본 DOMPurify 설정 (FORBID 방식: 위험 태그/속성만 차단, 나머지 허용)
|
||||
const defaultConfig: any = {
|
||||
ALLOWED_TAGS: [
|
||||
'p', 'br', 'strong', 'em', 'u', 's', 'strike', 'del', 'ins',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
||||
'ul', 'ol', 'li',
|
||||
'a', 'img',
|
||||
'blockquote', 'code', 'pre',
|
||||
'table', 'thead', 'tbody', 'tr', 'th', 'td',
|
||||
'div', 'span',
|
||||
FORBID_TAGS: [
|
||||
// 스크립트 실행
|
||||
'script', 'noscript',
|
||||
// 외부 콘텐츠 삽입
|
||||
'iframe', 'frame', 'frameset', 'object', 'embed', 'applet', 'portal',
|
||||
// 폼 요소 (피싱 방지)
|
||||
'form', 'input', 'textarea', 'select', 'button',
|
||||
// 메타/스타일 조작
|
||||
'style', 'link', 'meta', 'base',
|
||||
// 구조 태그 주입
|
||||
'body', 'head', 'html', 'title',
|
||||
// SVG/MathML (XSS 벡터)
|
||||
'svg', 'math',
|
||||
// 미디어 이벤트 핸들러 (onerror, onloadstart)
|
||||
'audio', 'video', 'source', 'track', 'canvas',
|
||||
// UI 오버레이/이벤트
|
||||
'details', 'dialog',
|
||||
// HTML 파서 혼란/sanitizer 우회
|
||||
'plaintext', 'xmp', 'listing',
|
||||
// 레거시/비표준
|
||||
'marquee', 'noframes', 'noembed', 'template', 'slot',
|
||||
],
|
||||
ALLOWED_ATTR: [
|
||||
'href', 'target', 'rel', 'title', 'alt', 'src', 'width', 'height',
|
||||
'class', 'style', 'id', 'data-*',
|
||||
FORBID_ATTR: [
|
||||
'onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur',
|
||||
'ontoggle', 'oncanplay', 'onloadstart',
|
||||
'formaction', 'xlink:href', 'action',
|
||||
],
|
||||
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 config = purifyConfig
|
||||
? {
|
||||
...defaultConfig,
|
||||
...purifyConfig,
|
||||
// 보안 기본값은 항상 유지 (사용자 설정으로 덮어쓰기 방지)
|
||||
FORBID_TAGS: [...defaultConfig.FORBID_TAGS, ...(purifyConfig.FORBID_TAGS || [])],
|
||||
FORBID_ATTR: [...defaultConfig.FORBID_ATTR, ...(purifyConfig.FORBID_ATTR || [])],
|
||||
}
|
||||
: 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">`;
|
||||
}
|
||||
@@ -137,7 +152,7 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
|
||||
return match;
|
||||
}
|
||||
);
|
||||
}, [actualContent, purifyConfig, defaultConfig]);
|
||||
}, [actualContent, purifyConfig]);
|
||||
|
||||
// 컨테이너 클래스 조합
|
||||
const containerClasses = `
|
||||
@@ -147,19 +162,20 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
|
||||
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
|
||||
[&_table]:w-full [&_table]:border-collapse [&_table]:border [&_table]:border-gray-300
|
||||
dark:[&_table]:border-gray-600
|
||||
[&_th]:border [&_th]:border-gray-300 [&_th]:px-4 [&_th]:py-2 [&_th]:bg-gray-100 [&_th]:text-left
|
||||
dark:[&_th]:border-gray-600 dark:[&_th]:bg-gray-800
|
||||
[&_td]:border [&_td]:border-gray-300 [&_td]:px-4 [&_td]:py-2
|
||||
dark:[&_td]:border-gray-600
|
||||
[&_tr:hover]:bg-gray-50 dark:[&_tr:hover]:bg-gray-700/50
|
||||
after:content-[''] after:block after:clear-both
|
||||
${className}
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
@@ -169,4 +185,4 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
|
||||
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
|
||||
/>
|
||||
);
|
||||
};
|
||||
};
|
||||
+271
-50
@@ -1,9 +1,10 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
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';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Input } from '../basic/Input';
|
||||
|
||||
/**
|
||||
* 알림 아이템 인터페이스
|
||||
@@ -15,6 +16,7 @@ export interface NotificationItem {
|
||||
time: string;
|
||||
read?: boolean;
|
||||
iconName?: IconName;
|
||||
data?: Record<string, unknown>;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
@@ -24,19 +26,48 @@ export interface NotificationItem {
|
||||
export interface NotificationCenterProps {
|
||||
/** 알림 목록 */
|
||||
notifications?: NotificationItem[];
|
||||
/** 서버 기반 미읽음 알림 수 */
|
||||
unreadCount?: number;
|
||||
/** 추가 로드 가능 여부 */
|
||||
hasMore?: boolean;
|
||||
/** 로딩 상태 */
|
||||
loading?: boolean;
|
||||
/** 알림 제목 텍스트 */
|
||||
titleText?: string;
|
||||
/** 알림 없음 텍스트 */
|
||||
emptyText?: string;
|
||||
/** 알림 클릭 핸들러 */
|
||||
onNotificationClick?: (id: string | number) => void;
|
||||
/** "모두 읽음" 버튼 텍스트 */
|
||||
markAllReadText?: string;
|
||||
/** "모두 삭제" 버튼 텍스트 */
|
||||
deleteAllText?: string;
|
||||
/** "미읽음만" 체크박스 텍스트 */
|
||||
unreadOnlyText?: string;
|
||||
/** "미읽음만" 체크박스 상태 */
|
||||
unreadOnly?: boolean;
|
||||
/** 알림 클릭 핸들러 (알림 전체 객체 전달) */
|
||||
onNotificationClick?: (notification: NotificationItem) => void;
|
||||
/** 드롭다운 닫힐 때 (뷰포트에 들어온 미읽음 알림 ID 목록) */
|
||||
onClose?: (visibleUnreadIds: (string | number)[]) => void;
|
||||
/** 추가 로드 요청 */
|
||||
onLoadMore?: () => void;
|
||||
/** 모두 읽음 처리 요청 */
|
||||
onMarkAllRead?: () => void;
|
||||
/** 모두 삭제 요청 */
|
||||
onDeleteAll?: () => void;
|
||||
/** 개별 알림 삭제 요청 (알림 전체 객체 전달) */
|
||||
onDelete?: (notification: NotificationItem) => void;
|
||||
/** "미읽음만" 체크박스 토글 */
|
||||
onUnreadOnlyToggle?: (checked: boolean) => void;
|
||||
/** 드롭다운 정렬 방향 — "right"(기본): 우측 정렬되어 좌측으로 확장 / "left": 좌측 정렬되어 우측으로 확장 */
|
||||
dropdownAlign?: 'left' | 'right';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* NotificationCenter 컴포넌트
|
||||
*
|
||||
* 알림 센터 - 알림 목록 표시 및 관리
|
||||
* 알림 센터 - 알림 목록 표시, 무한스크롤, 읽음 추적
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
@@ -44,6 +75,8 @@ export interface NotificationCenterProps {
|
||||
* notifications={[
|
||||
* { id: 1, title: '새 댓글', message: '게시물에 댓글이 달렸습니다', time: '5분 전' }
|
||||
* ]}
|
||||
* unreadCount={5}
|
||||
* hasMore={true}
|
||||
* titleText="Notifications"
|
||||
* emptyText="No notifications"
|
||||
* />
|
||||
@@ -51,97 +84,285 @@ export interface NotificationCenterProps {
|
||||
*/
|
||||
export const NotificationCenter: React.FC<NotificationCenterProps> = ({
|
||||
notifications = [],
|
||||
unreadCount = 0,
|
||||
hasMore = false,
|
||||
loading = false,
|
||||
titleText = 'Notifications',
|
||||
emptyText = 'No notifications',
|
||||
markAllReadText = 'Mark all as read',
|
||||
deleteAllText = 'Delete all',
|
||||
unreadOnlyText = 'Unread only',
|
||||
unreadOnly = false,
|
||||
onNotificationClick,
|
||||
onClose,
|
||||
onLoadMore,
|
||||
onMarkAllRead,
|
||||
onDeleteAll,
|
||||
onDelete,
|
||||
onUnreadOnlyToggle,
|
||||
dropdownAlign = 'right',
|
||||
className = '',
|
||||
}) => {
|
||||
const [showNotifications, setShowNotifications] = useState(false);
|
||||
const notificationRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.read).length;
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
const visibleUnreadIdsRef = useRef<Set<string | number>>(new Set());
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지
|
||||
* 무한스크롤 — IntersectionObserver
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!sentinelRef.current || !scrollRef.current || !hasMore || loading || !showNotifications) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
onLoadMore?.();
|
||||
}
|
||||
},
|
||||
{ root: scrollRef.current, threshold: 0.1 }
|
||||
);
|
||||
|
||||
observer.observe(sentinelRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, [hasMore, loading, showNotifications, onLoadMore, notifications.length]);
|
||||
|
||||
/**
|
||||
* 뷰포트 내 미읽음 알림 추적 — IntersectionObserver
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!scrollRef.current || !showNotifications) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
const id = entry.target.getAttribute('data-notification-id');
|
||||
const isUnread = entry.target.getAttribute('data-unread') === 'true';
|
||||
if (id && isUnread && entry.isIntersecting) {
|
||||
visibleUnreadIdsRef.current.add(id);
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
root: scrollRef.current,
|
||||
threshold: 0.5,
|
||||
}
|
||||
);
|
||||
|
||||
const items = scrollRef.current.querySelectorAll('[data-notification-id]');
|
||||
items.forEach((item) => observer.observe(item));
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [showNotifications, notifications]);
|
||||
|
||||
/**
|
||||
* 드롭다운 닫기 — 뷰포트에 들어온 미읽음 알림 ID 전달
|
||||
*/
|
||||
const handleClose = useCallback(() => {
|
||||
if (showNotifications) {
|
||||
const ids = Array.from(visibleUnreadIdsRef.current);
|
||||
if (ids.length > 0) {
|
||||
onClose?.(ids);
|
||||
}
|
||||
visibleUnreadIdsRef.current.clear();
|
||||
setShowNotifications(false);
|
||||
}
|
||||
}, [showNotifications, onClose]);
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지 — 드롭다운이 열려 있을 때만 리스너 등록
|
||||
* (stale closure 방지: showNotifications 변경 시 리스너 재등록)
|
||||
* 주의: handleClose가 useCallback으로 선언된 이후에 위치해야 TDZ 위반 방지
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!showNotifications) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
notificationRef.current &&
|
||||
!notificationRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setShowNotifications(false);
|
||||
handleClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
}, [showNotifications, handleClose]);
|
||||
|
||||
/**
|
||||
* 드롭다운 토글
|
||||
*/
|
||||
const handleToggle = useCallback(() => {
|
||||
if (showNotifications) {
|
||||
handleClose();
|
||||
} else {
|
||||
setShowNotifications(true);
|
||||
}
|
||||
}, [showNotifications, handleClose]);
|
||||
|
||||
/**
|
||||
* 뱃지에 표시할 카운트
|
||||
*/
|
||||
const displayCount = unreadCount > 0 ? unreadCount : notifications.filter((n) => !n.read).length;
|
||||
|
||||
return (
|
||||
<Div ref={notificationRef} className={`relative ${className}`}>
|
||||
<Button
|
||||
onClick={() => setShowNotifications(!showNotifications)}
|
||||
className="relative p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
|
||||
onClick={handleToggle}
|
||||
className="relative p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors cursor-pointer"
|
||||
aria-label={titleText}
|
||||
>
|
||||
<Icon name={IconName.Bell} className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
{unreadCount > 0 && (
|
||||
{displayCount > 0 && (
|
||||
<Span className="absolute top-0 right-0 flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-red-500 rounded-full">
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
{displayCount > 99 ? '99+' : displayCount}
|
||||
</Span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* 알림 드롭다운 */}
|
||||
{showNotifications && (
|
||||
<Div className="absolute right-0 mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
|
||||
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<Span className="font-semibold text-gray-900 dark:text-white">{titleText}</Span>
|
||||
<Div className={`absolute ${dropdownAlign === 'left' ? 'left-0' : 'right-0'} mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50`}>
|
||||
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between gap-2">
|
||||
<Div className="flex items-center gap-3 min-w-0">
|
||||
<Span className="font-semibold text-gray-900 dark:text-white">{titleText}</Span>
|
||||
{onUnreadOnlyToggle && (
|
||||
<Div
|
||||
className="flex items-center gap-1.5 cursor-pointer select-none"
|
||||
onClick={() => onUnreadOnlyToggle(!unreadOnly)}
|
||||
>
|
||||
<Input
|
||||
type="checkbox"
|
||||
checked={unreadOnly}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
e.stopPropagation();
|
||||
onUnreadOnlyToggle(e.target.checked);
|
||||
}}
|
||||
onClick={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500 cursor-pointer"
|
||||
/>
|
||||
<Span className="text-xs text-gray-600 dark:text-gray-400">{unreadOnlyText}</Span>
|
||||
</Div>
|
||||
)}
|
||||
</Div>
|
||||
<Div className="flex items-center gap-3 flex-shrink-0">
|
||||
{onMarkAllRead && displayCount > 0 && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
onMarkAllRead();
|
||||
visibleUnreadIdsRef.current.clear();
|
||||
}}
|
||||
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 hover:underline cursor-pointer"
|
||||
>
|
||||
{markAllReadText}
|
||||
</Button>
|
||||
)}
|
||||
{onDeleteAll && notifications.length > 0 && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
// 드롭다운은 닫지 않음 — 확인 모달이 닫히면 다시 자연스럽게 노출되어야 하고,
|
||||
// 사용자가 모달 취소 시에도 컨텍스트 유지 (PO 요구)
|
||||
onDeleteAll();
|
||||
}}
|
||||
className="text-xs text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300 hover:underline cursor-pointer"
|
||||
>
|
||||
{deleteAllText}
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
<Div className="max-h-96 overflow-y-auto">
|
||||
{notifications.length === 0 ? (
|
||||
<Div ref={scrollRef} className="max-h-96 overflow-y-auto">
|
||||
{notifications.length === 0 && !loading ? (
|
||||
<Div className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
|
||||
<Span>{emptyText}</Span>
|
||||
</Div>
|
||||
) : (
|
||||
notifications.map((notification) => (
|
||||
<Button
|
||||
key={notification.id}
|
||||
onClick={() => {
|
||||
notification.onClick?.();
|
||||
onNotificationClick?.(notification.id);
|
||||
setShowNotifications(false);
|
||||
}}
|
||||
className={`
|
||||
w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 border-b border-gray-100 dark:border-gray-700 transition-colors
|
||||
${!notification.read ? 'bg-blue-50 dark:bg-gray-700' : ''}
|
||||
`}
|
||||
>
|
||||
<Div className="flex items-start gap-3">
|
||||
{notification.iconName && (
|
||||
<Icon
|
||||
name={notification.iconName}
|
||||
className="w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5"
|
||||
/>
|
||||
)}
|
||||
<Div className="flex-1">
|
||||
<Div className="font-semibold text-gray-900 dark:text-white text-sm">
|
||||
{notification.title}
|
||||
<>
|
||||
{notifications.map((notification) => {
|
||||
const isUnread = !notification.read;
|
||||
return (
|
||||
<Div
|
||||
key={notification.id}
|
||||
data-notification-id={notification.id}
|
||||
data-unread={isUnread ? 'true' : 'false'}
|
||||
onClick={() => {
|
||||
notification.onClick?.();
|
||||
onNotificationClick?.(notification);
|
||||
setShowNotifications(false);
|
||||
}}
|
||||
className={`group flex items-start gap-3 px-4 py-3 text-left border-b border-gray-100 dark:border-gray-700 transition-colors cursor-pointer ${
|
||||
isUnread
|
||||
? 'bg-blue-50/70 dark:bg-blue-900/20 hover:bg-blue-50 dark:hover:bg-blue-900/30'
|
||||
: 'bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700/50 opacity-70'
|
||||
}`}
|
||||
>
|
||||
{notification.iconName && (
|
||||
<Icon
|
||||
name={notification.iconName}
|
||||
className={`w-5 h-5 mt-0.5 flex-shrink-0 ${
|
||||
isUnread ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400 dark:text-gray-500'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
<Div className="flex-1 min-w-0">
|
||||
<Div
|
||||
className={`text-sm truncate ${
|
||||
isUnread
|
||||
? 'font-semibold text-gray-900 dark:text-white'
|
||||
: 'font-normal text-gray-600 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{notification.title}
|
||||
</Div>
|
||||
<Div
|
||||
className={`text-sm mt-1 line-clamp-2 ${
|
||||
isUnread ? 'text-gray-700 dark:text-gray-300' : 'text-gray-500 dark:text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{notification.message}
|
||||
</Div>
|
||||
<Div className="text-gray-400 dark:text-gray-500 text-xs mt-1 font-mono">
|
||||
{notification.time}
|
||||
</Div>
|
||||
</Div>
|
||||
<Div className="text-gray-600 dark:text-gray-300 text-sm mt-1">
|
||||
{notification.message}
|
||||
</Div>
|
||||
<Div className="text-gray-400 dark:text-gray-500 text-xs mt-1">
|
||||
{notification.time}
|
||||
<Div className="flex flex-col items-center gap-2 flex-shrink-0">
|
||||
{isUnread && (
|
||||
<Span className="w-2 h-2 bg-blue-500 rounded-full mt-1.5" />
|
||||
)}
|
||||
{onDelete && (
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDelete(notification);
|
||||
}}
|
||||
className="p-1 text-gray-400 dark:text-gray-500 hover:text-red-600 dark:hover:text-red-400 rounded hover:bg-red-50 dark:hover:bg-red-900/20 cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
aria-label="Delete notification"
|
||||
>
|
||||
<Icon name={IconName.Trash} className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
{!notification.read && (
|
||||
<Span className="w-2 h-2 bg-blue-500 rounded-full mt-1.5" />
|
||||
);
|
||||
})}
|
||||
{/* 무한스크롤 sentinel */}
|
||||
{hasMore && (
|
||||
<Div ref={sentinelRef} className="px-4 py-3 text-center">
|
||||
{loading ? (
|
||||
<Span className="text-sm text-gray-400 dark:text-gray-500">...</Span>
|
||||
) : (
|
||||
<Span className="text-sm text-gray-400 dark:text-gray-500" />
|
||||
)}
|
||||
</Div>
|
||||
</Button>
|
||||
))
|
||||
)}
|
||||
{loading && !hasMore && notifications.length > 0 && (
|
||||
<Div className="px-4 py-2 text-center">
|
||||
<Span className="text-sm text-gray-400 dark:text-gray-500">...</Span>
|
||||
</Div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Div>
|
||||
</Div>
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* 페이지 로딩 컴포넌트 Props (엔진에서 전달)
|
||||
*
|
||||
* @since engine-v1.29.0
|
||||
*/
|
||||
export interface PageLoadingProps {
|
||||
options?: {
|
||||
text?: string;
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -5,6 +5,7 @@ import { Icon } from '../basic/Icon';
|
||||
import { IconName } from '../basic/IconTypes';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Span } from '../basic/Span';
|
||||
import { Select } from '../basic/Select';
|
||||
|
||||
export interface Tab {
|
||||
id: string | number;
|
||||
@@ -21,6 +22,8 @@ export interface TabNavigationProps {
|
||||
variant?: 'default' | 'pills' | 'underline';
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
/** 모바일 전환 임계값 (px). 기본값 768 — G7 ResponsiveContext mobile 프리셋과 동일 */
|
||||
mobileBreakpoint?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,10 +32,14 @@ export interface TabNavigationProps {
|
||||
* 탭 네비게이션을 제공하는 컴포넌트입니다.
|
||||
* 여러 탭을 전환할 수 있으며, 아이콘과 뱃지를 지원합니다.
|
||||
*
|
||||
* 반응형: G7Core.useResponsive() hook으로 화면 너비를 구독하여
|
||||
* mobileBreakpoint(기본 768px) 미만일 때 Select 드롭다운으로 자동 전환됩니다.
|
||||
* Tailwind hidden md:flex 분기를 사용하지 않으므로 위지윅 편집기의 디바이스 미리보기와도 호환됩니다.
|
||||
*
|
||||
* **주의**: 이 컴포넌트는 순수 네비게이션 UI만 제공하며,
|
||||
* 실제 탭 컨텐츠는 부모 컴포넌트에서 activeTabId를 기반으로 조건부 렌더링해야 합니다.
|
||||
*
|
||||
* 기본 컴포넌트 조합: Nav + Button + Icon + Div + Span
|
||||
* 기본 컴포넌트 조합: Nav + Button + Icon + Div + Span + Select
|
||||
*
|
||||
* @example
|
||||
* // 레이아웃 JSON 사용 예시
|
||||
@@ -46,16 +53,6 @@ export interface TabNavigationProps {
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* // 부모 컴포넌트에서 컨텐츠 렌더링 예시:
|
||||
* const [activeTab, setActiveTab] = useState(1);
|
||||
* return (
|
||||
* <>
|
||||
* <TabNavigation tabs={tabs} activeTabId={activeTab} onTabChange={setActiveTab} />
|
||||
* {activeTab === 1 && <ProfileContent />}
|
||||
* {activeTab === 2 && <SettingsContent />}
|
||||
* </>
|
||||
* );
|
||||
*/
|
||||
export const TabNavigation: React.FC<TabNavigationProps> = ({
|
||||
tabs,
|
||||
@@ -64,13 +61,55 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
|
||||
variant = 'default',
|
||||
className = '',
|
||||
style,
|
||||
mobileBreakpoint = 768,
|
||||
}) => {
|
||||
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준)
|
||||
const G7Core = (window as any).G7Core;
|
||||
const useResponsive = G7Core?.useResponsive;
|
||||
const responsiveValue = useResponsive?.();
|
||||
const isMobile = responsiveValue
|
||||
? responsiveValue.width < mobileBreakpoint
|
||||
: typeof window !== 'undefined' && window.innerWidth < mobileBreakpoint;
|
||||
|
||||
const handleTabClick = (tab: Tab) => {
|
||||
if (!tab.disabled && tab.id !== activeTabId) {
|
||||
onTabChange?.(tab.id);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectChange = (
|
||||
e: React.ChangeEvent<HTMLSelectElement> | { target: { value: string | number } }
|
||||
) => {
|
||||
const selectedId = e.target.value;
|
||||
const numericId = Number(selectedId);
|
||||
const finalId =
|
||||
typeof selectedId === 'string' && selectedId !== '' && !Number.isNaN(numericId)
|
||||
? numericId
|
||||
: selectedId;
|
||||
const selectedTab = tabs.find((tab) => String(tab.id) === String(finalId));
|
||||
if (selectedTab) {
|
||||
handleTabClick(selectedTab);
|
||||
}
|
||||
};
|
||||
|
||||
// 모바일: Select 드롭다운 단일 렌더
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Div className={className} style={style}>
|
||||
<Select
|
||||
value={activeTabId !== undefined ? String(activeTabId) : ''}
|
||||
onChange={handleSelectChange}
|
||||
options={tabs.map((tab) => ({
|
||||
value: String(tab.id),
|
||||
label: tab.badge !== undefined ? `${tab.label} (${tab.badge})` : tab.label,
|
||||
disabled: tab.disabled,
|
||||
}))}
|
||||
className="w-full"
|
||||
/>
|
||||
</Div>
|
||||
);
|
||||
}
|
||||
|
||||
const getTabClasses = (tab: Tab) => {
|
||||
const isActive = tab.id === activeTabId;
|
||||
const baseClasses = 'flex items-center gap-2 px-4 py-2 font-medium text-sm transition-all';
|
||||
@@ -103,6 +142,7 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
|
||||
? 'flex gap-0 border-b border-gray-200 dark:border-gray-700'
|
||||
: 'flex gap-2';
|
||||
|
||||
// 데스크톱: 탭 버튼 단일 렌더
|
||||
return (
|
||||
<Nav
|
||||
className={`${navClasses} ${className}`}
|
||||
|
||||
+41
-30
@@ -70,6 +70,8 @@ export interface TabNavigationScrollProps {
|
||||
* - 내부 상태로 활성 탭 관리 (React useState)
|
||||
* - scrollToSectionHandler를 사용하여 자동 스크롤
|
||||
* - 탭 클릭 시 즉시 UI 업데이트 + 스크롤 이동
|
||||
* - 반응형: G7Core.useResponsive() hook으로 화면 너비를 구독하여 768px 미만 시
|
||||
* Select 드롭다운으로 자동 전환 (Tailwind hidden md:flex 분기 미사용 — 위지윅 미리보기 호환)
|
||||
*
|
||||
* @example
|
||||
* ```json
|
||||
@@ -104,6 +106,14 @@ export const TabNavigationScroll: React.FC<TabNavigationScrollProps> = ({
|
||||
activeTabId ?? (tabs.length > 0 ? tabs[0].id : '')
|
||||
);
|
||||
|
||||
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준)
|
||||
const G7Core = (window as any).G7Core;
|
||||
const useResponsive = G7Core?.useResponsive;
|
||||
const responsiveValue = useResponsive?.();
|
||||
const isMobile = responsiveValue
|
||||
? responsiveValue.width < 768
|
||||
: typeof window !== 'undefined' && window.innerWidth < 768;
|
||||
|
||||
// Scroll Spy 일시 중지를 위한 ref
|
||||
const isScrollingRef = useRef(false);
|
||||
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
@@ -321,39 +331,40 @@ export const TabNavigationScroll: React.FC<TabNavigationScrollProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 데스크톱: 탭 버튼 (md 이상) */}
|
||||
<Div className={`hidden md:flex ${className}`} style={style}>
|
||||
{tabs.map((tab) => (
|
||||
<Button
|
||||
key={tab.id}
|
||||
className={activeTab === tab.id ? activeClassName : inactiveClassName}
|
||||
disabled={tab.disabled}
|
||||
onClick={() => handleTabClick(tab)}
|
||||
>
|
||||
{tab.iconName && (
|
||||
<Icon name={tab.iconName} size="sm" />
|
||||
)}
|
||||
<Span>{tab.label}</Span>
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
|
||||
{/* 모바일: Select 박스 (md 미만) */}
|
||||
<Div className="md:hidden bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
|
||||
// 모바일: Select 드롭다운 단일 렌더
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
|
||||
<Select
|
||||
value={String(activeTab)}
|
||||
onChange={handleSelectChange}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<option key={tab.id} value={String(tab.id)} disabled={tab.disabled}>
|
||||
{tab.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
options={tabs.map((tab) => ({
|
||||
value: String(tab.id),
|
||||
label: tab.label,
|
||||
disabled: tab.disabled,
|
||||
}))}
|
||||
className="w-full"
|
||||
/>
|
||||
</Div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// 데스크톱: 탭 버튼 단일 렌더
|
||||
return (
|
||||
<Div className={className} style={style}>
|
||||
{tabs.map((tab) => (
|
||||
<Button
|
||||
key={tab.id}
|
||||
className={activeTab === tab.id ? activeClassName : inactiveClassName}
|
||||
disabled={tab.disabled}
|
||||
onClick={() => handleTabClick(tab)}
|
||||
>
|
||||
{tab.iconName && (
|
||||
<Icon name={tab.iconName} size="sm" />
|
||||
)}
|
||||
<Span>{tab.label}</Span>
|
||||
</Button>
|
||||
))}
|
||||
</Div>
|
||||
);
|
||||
};
|
||||
+115
-3
@@ -1,17 +1,62 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TabNavigation, Tab } from '../TabNavigation';
|
||||
import { IconName } from '../../basic/IconTypes';
|
||||
|
||||
/**
|
||||
* window.G7Core.useResponsive mock
|
||||
*
|
||||
* 기본값은 데스크톱 (1024px). 모바일 케이스는 `mockUseResponsive.mockReturnValueOnce({...})`로 개별 오버라이드.
|
||||
*/
|
||||
const mockUseResponsive = vi.fn(() => ({
|
||||
width: 1024,
|
||||
isMobile: false,
|
||||
isTablet: false,
|
||||
isDesktop: true,
|
||||
matchedPreset: 'desktop' as const,
|
||||
}));
|
||||
|
||||
const setMobile = () => {
|
||||
mockUseResponsive.mockReturnValue({
|
||||
width: 375,
|
||||
isMobile: true,
|
||||
isTablet: false,
|
||||
isDesktop: false,
|
||||
matchedPreset: 'mobile' as const,
|
||||
});
|
||||
};
|
||||
|
||||
describe('TabNavigation', () => {
|
||||
let originalG7Core: any;
|
||||
|
||||
beforeEach(() => {
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = {
|
||||
...originalG7Core,
|
||||
useResponsive: mockUseResponsive,
|
||||
};
|
||||
mockUseResponsive.mockReturnValue({
|
||||
width: 1024,
|
||||
isMobile: false,
|
||||
isTablet: false,
|
||||
isDesktop: true,
|
||||
matchedPreset: 'desktop' as const,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(window as any).G7Core = originalG7Core;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const mockTabs: Tab[] = [
|
||||
{ id: 1, label: '프로필' },
|
||||
{ id: 2, label: '설정' },
|
||||
{ id: 3, label: '알림' },
|
||||
];
|
||||
|
||||
describe('기본 렌더링', () => {
|
||||
it('모든 탭을 렌더링해야 함', () => {
|
||||
describe('데스크톱 렌더링', () => {
|
||||
it('모든 탭을 Nav 안의 버튼으로 렌더링해야 함', () => {
|
||||
render(<TabNavigation tabs={mockTabs} />);
|
||||
|
||||
expect(screen.getByText('프로필')).toBeInTheDocument();
|
||||
@@ -25,6 +70,14 @@ describe('TabNavigation', () => {
|
||||
const nav = container.querySelector('nav');
|
||||
expect(nav).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Select 드롭다운은 렌더링되지 않아야 함', () => {
|
||||
const { container } = render(<TabNavigation tabs={mockTabs} />);
|
||||
|
||||
// 데스크톱 분기에서는 native select도, custom Select trigger도 없어야 함
|
||||
const selects = container.querySelectorAll('select');
|
||||
expect(selects.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('활성 탭', () => {
|
||||
@@ -209,6 +262,65 @@ describe('TabNavigation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('모바일 (useResponsive isMobile=true)', () => {
|
||||
beforeEach(() => {
|
||||
setMobile();
|
||||
});
|
||||
|
||||
it('Nav 대신 Select 드롭다운만 렌더링해야 함', () => {
|
||||
const { container } = render(
|
||||
<TabNavigation tabs={mockTabs} activeTabId={1} />
|
||||
);
|
||||
|
||||
// Nav 없음, Select 있음
|
||||
expect(container.querySelector('nav')).not.toBeInTheDocument();
|
||||
// custom Select는 trigger button 1개와 dropdown div를 가짐
|
||||
const triggerButton = container.querySelector('button');
|
||||
expect(triggerButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('현재 활성 탭의 label을 Select trigger에 표시해야 함', () => {
|
||||
render(<TabNavigation tabs={mockTabs} activeTabId={2} />);
|
||||
|
||||
// 데스크톱 Nav가 없으므로 라벨 충돌 없음
|
||||
expect(screen.getByText('설정')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('뱃지가 있는 탭은 label과 함께 뱃지 수를 병기해야 함', () => {
|
||||
const tabsWithBadge: Tab[] = [
|
||||
{ id: 1, label: '알림', badge: 5 },
|
||||
];
|
||||
render(<TabNavigation tabs={tabsWithBadge} activeTabId={1} />);
|
||||
|
||||
expect(screen.getByText('알림 (5)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Select trigger 클릭 후 옵션 선택 시 onTabChange가 호출되어야 함', () => {
|
||||
const handleTabChange = vi.fn();
|
||||
const { container } = render(
|
||||
<TabNavigation
|
||||
tabs={mockTabs}
|
||||
activeTabId={1}
|
||||
onTabChange={handleTabChange}
|
||||
/>
|
||||
);
|
||||
|
||||
// Select trigger 열기
|
||||
const triggerButton = container.querySelector('button');
|
||||
fireEvent.mouseDown(document.body);
|
||||
fireEvent.click(triggerButton!);
|
||||
|
||||
// 옵션 클릭 (custom dropdown 내부)
|
||||
const settingsOption = screen.getAllByText('설정').find(
|
||||
(el) => el.closest('button') !== triggerButton
|
||||
);
|
||||
if (settingsOption) {
|
||||
fireEvent.click(settingsOption.closest('button')!);
|
||||
expect(handleTabChange).toHaveBeenCalledWith(2);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('복합 시나리오', () => {
|
||||
it('아이콘, 뱃지, 비활성화를 모두 함께 사용할 수 있어야 함', () => {
|
||||
const complexTabs: Tab[] = [
|
||||
|
||||
+79
-17
@@ -4,6 +4,28 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { TabNavigationScroll, Tab } from '../TabNavigationScroll';
|
||||
import * as scrollHandler from '../../../handlers/scrollToSectionHandler';
|
||||
|
||||
/**
|
||||
* window.G7Core.useResponsive mock — 기본값은 데스크톱 (1024px).
|
||||
* 모바일 케이스는 setMobile() 호출.
|
||||
*/
|
||||
const mockUseResponsive = vi.fn(() => ({
|
||||
width: 1024,
|
||||
isMobile: false,
|
||||
isTablet: false,
|
||||
isDesktop: true,
|
||||
matchedPreset: 'desktop' as const,
|
||||
}));
|
||||
|
||||
const setMobile = () => {
|
||||
mockUseResponsive.mockReturnValue({
|
||||
width: 375,
|
||||
isMobile: true,
|
||||
isTablet: false,
|
||||
isDesktop: false,
|
||||
matchedPreset: 'mobile' as const,
|
||||
});
|
||||
};
|
||||
|
||||
describe('TabNavigationScroll', () => {
|
||||
const mockTabs: Tab[] = [
|
||||
{ id: 'basic', label: '기본정보' },
|
||||
@@ -11,6 +33,8 @@ describe('TabNavigationScroll', () => {
|
||||
{ id: 'permissions', label: '권한설정' },
|
||||
];
|
||||
|
||||
let originalG7Core: any;
|
||||
|
||||
// IntersectionObserver Mock
|
||||
let observerCallback: IntersectionObserverCallback;
|
||||
let mockObserverInstance: {
|
||||
@@ -20,6 +44,20 @@ describe('TabNavigationScroll', () => {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// G7Core.useResponsive mock — 기본 데스크톱
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = {
|
||||
...originalG7Core,
|
||||
useResponsive: mockUseResponsive,
|
||||
};
|
||||
mockUseResponsive.mockReturnValue({
|
||||
width: 1024,
|
||||
isMobile: false,
|
||||
isTablet: false,
|
||||
isDesktop: true,
|
||||
matchedPreset: 'desktop' as const,
|
||||
});
|
||||
|
||||
// scrollToSectionHandler mock
|
||||
vi.spyOn(scrollHandler, 'scrollToSectionHandler').mockImplementation(async () => {});
|
||||
|
||||
@@ -54,31 +92,16 @@ describe('TabNavigationScroll', () => {
|
||||
return { id } as HTMLElement;
|
||||
});
|
||||
|
||||
// matchMedia mock - md(768px) 이상으로 설정하여 데스크톱 뷰 표시
|
||||
// 참고: hidden md:flex 클래스는 Tailwind CSS 클래스이므로 실제 CSS가 적용되지 않음
|
||||
// 테스트 환경에서는 버튼이 표시되도록 해야 함
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: query.includes('min-width: 768px'),
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(window as any).G7Core = originalG7Core;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/**
|
||||
* 헬퍼 함수: 데스크톱 뷰의 탭 버튼을 찾습니다.
|
||||
* 컴포넌트는 데스크톱과 모바일 뷰를 모두 렌더링하므로 버튼만 선택해야 합니다.
|
||||
* 단일 분기 렌더(useResponsive 기반)이므로 데스크톱 모드에서는 Nav 안의 버튼만 존재합니다.
|
||||
*/
|
||||
const getTabButton = (text: string): HTMLButtonElement | null => {
|
||||
const buttons = screen.getAllByRole('button');
|
||||
@@ -576,6 +599,45 @@ describe('TabNavigationScroll', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('모바일 (useResponsive isMobile=true)', () => {
|
||||
beforeEach(() => {
|
||||
setMobile();
|
||||
});
|
||||
|
||||
it('데스크톱 Nav 버튼 대신 Select 드롭다운만 렌더링해야 함', () => {
|
||||
const { container } = render(<TabNavigationScroll tabs={mockTabs} />);
|
||||
|
||||
// 데스크톱 분기의 탭 버튼들이 없어야 함 — Select trigger 1개만 존재
|
||||
const buttons = container.querySelectorAll('button');
|
||||
expect(buttons.length).toBe(1);
|
||||
});
|
||||
|
||||
it('현재 활성 탭의 label을 Select trigger에 표시해야 함', () => {
|
||||
render(<TabNavigationScroll tabs={mockTabs} activeTabId="list" />);
|
||||
|
||||
expect(screen.getByText('목록설정')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Select trigger 클릭 → 옵션 선택 시 scrollToSectionHandler가 호출되어야 함', () => {
|
||||
const { container } = render(<TabNavigationScroll tabs={mockTabs} />);
|
||||
|
||||
// Select trigger 열기
|
||||
const trigger = container.querySelector('button');
|
||||
fireEvent.click(trigger!);
|
||||
|
||||
// 옵션 클릭 (custom Select dropdown 내부)
|
||||
const options = screen.getAllByText('목록설정');
|
||||
const optionButton = options
|
||||
.map((el) => el.closest('button'))
|
||||
.find((btn) => btn !== trigger);
|
||||
|
||||
if (optionButton) {
|
||||
fireEvent.click(optionButton);
|
||||
expect(scrollHandler.scrollToSectionHandler).toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('복합 시나리오', () => {
|
||||
it('개별 설정, 공통 설정, 기본값을 모두 함께 사용할 수 있어야 함', () => {
|
||||
const onTabChange = vi.fn();
|
||||
|
||||
@@ -123,6 +123,9 @@ export type { ColumnSelectorProps, ColumnItem } from './ColumnSelector';
|
||||
export { PageTransitionIndicator } from './PageTransitionIndicator';
|
||||
export type { PageTransitionIndicatorProps } from './PageTransitionIndicator';
|
||||
|
||||
export { default as PageLoading } from './PageLoading';
|
||||
export type { PageLoadingProps } from './PageLoading';
|
||||
|
||||
export { Toggle } from './Toggle';
|
||||
export type { ToggleProps } from './Toggle';
|
||||
|
||||
|
||||
Reference in new issue
Block a user