v7.0.0-beta.2 release

This commit is contained in:
HeuJung committed 2026-04-20 20:37:49 +09:00
1 parent 6595fd0eb5
commit fa8eba7a0d
1165 files changed
+107118 -762127

No files matched your search

@@ -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>
);
@@ -0,0 +1,737 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import { Select } from '../Select';
describe('Select 컴포넌트', () => {
describe('기본 렌더링 (children 모드)', () => {
it('select 요소가 렌더링된다', () => {
const { container } = render(
<Select>
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
it('option 요소가 렌더링된다', () => {
render(
<Select>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
expect(screen.getByText('옵션 1')).toBeTruthy();
expect(screen.getByText('옵션 2')).toBeTruthy();
});
it('기본 선택 옵션이 표시된다', () => {
const { container } = render(
<Select defaultValue="2">
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe('2');
});
});
describe('이벤트 핸들링 (children 모드)', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Select onChange={handleChange}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.change(select, { target: { value: '2' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(
<Select onFocus={handleFocus}>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.focus(select);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(
<Select onBlur={handleBlur}>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.blur(select);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
});
describe('value 및 제어 컴포넌트 (children 모드)', () => {
it('value prop이 적용된다', () => {
const { container } = render(
<Select value="2" onChange={() => {}}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
<option value="3">옵션 3</option>
</Select>
);
const select = container.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe('2');
});
it('제어 컴포넌트로 작동한다', () => {
const TestComponent = () => {
const [value, setValue] = React.useState('1');
return (
<Select value={value} onChange={(e) => setValue(String(e.target.value))}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
};
const { container } = render(<TestComponent />);
const select = container.querySelector('select')!;
expect((select as HTMLSelectElement).value).toBe('1');
fireEvent.change(select, { target: { value: '2' } });
expect((select as HTMLSelectElement).value).toBe('2');
});
});
describe('HTML 속성 (children 모드)', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(
<Select disabled>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.disabled).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(
<Select required>
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(
<Select name="category">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.name).toBe('category');
});
it('id 속성이 적용된다', () => {
const { container } = render(
<Select id="category-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.id).toBe('category-select');
});
it('multiple 속성이 적용된다', () => {
const { container } = render(
<Select multiple>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.multiple).toBe(true);
});
it('size 속성이 적용된다', () => {
const { container } = render(
<Select size={3}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.size).toBe(3);
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(
<Select label="카테고리 선택">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(
<Select error="카테고리를 선택해주세요">
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
});
describe('사용자 정의 Props (children 모드)', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Select className="custom-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.className).toContain('custom-select');
});
it('aria-label이 적용된다', () => {
const { container } = render(
<Select aria-label="카테고리 선택">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.getAttribute('aria-label')).toBe('카테고리 선택');
});
it('data 속성이 적용된다', () => {
const { container } = render(
<Select data-testid="test-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.getAttribute('data-testid')).toBe('test-select');
});
});
describe('optgroup 지원', () => {
it('optgroup이 렌더링된다', () => {
render(
<Select>
<optgroup label="그룹 1">
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</optgroup>
<optgroup label="그룹 2">
<option value="3">옵션 3</option>
<option value="4">옵션 4</option>
</optgroup>
</Select>
);
expect(screen.getByText('옵션 1')).toBeTruthy();
expect(screen.getByText('옵션 3')).toBeTruthy();
});
});
describe('복합 Props (children 모드)', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Select
name="category"
value="2"
onChange={handleChange}
required
className="custom-select"
aria-label="카테고리 선택"
>
<option value="">선택하세요</option>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
<option value="3">옵션 3</option>
</Select>
);
const select = container.querySelector('select')!;
expect(select.name).toBe('category');
expect((select as HTMLSelectElement).value).toBe('2');
expect(select.required).toBe(true);
expect(select.className).toContain('custom-select');
expect(select.getAttribute('aria-label')).toBe('카테고리 선택');
fireEvent.change(select, { target: { value: '3' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
// ========================================
// 커스텀 드롭다운 모드 (options prop 사용)
// ========================================
describe('커스텀 드롭다운 렌더링 (options 모드)', () => {
const options = [
{ value: '', label: '전체' },
{ value: 'name', label: '이름' },
{ value: 'email', label: '이메일' },
];
it('options prop으로 커스텀 드롭다운이 렌더링된다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
// 버튼이 렌더링되어야 함 (select가 아닌 button)
const button = screen.getByRole('button');
expect(button).toBeTruthy();
});
it('선택된 옵션의 라벨이 버튼에 표시된다', () => {
render(<Select options={options} value="name" onChange={() => {}} />);
expect(screen.getByText('이름')).toBeTruthy();
});
it('빈 값일 때 해당 옵션의 라벨이 표시된다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
expect(screen.getByText('전체')).toBeTruthy();
});
it('버튼 클릭 시 드롭다운이 열린다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 드롭다운 메뉴가 열림 (listbox)
const listbox = screen.getByRole('listbox');
expect(listbox).toBeTruthy();
// 모든 옵션이 표시됨 (옵션은 role="option"으로 찾음)
const optionElements = screen.getAllByRole('option');
expect(optionElements.length).toBe(3);
});
it('옵션 클릭 시 onChange가 호출되고 드롭다운이 닫힌다', () => {
const handleChange = vi.fn();
render(<Select options={options} value="" onChange={handleChange} />);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
// 옵션 선택
const nameOption = screen.getAllByRole('option').find(
opt => opt.textContent?.includes('이름')
);
fireEvent.click(nameOption!);
// onChange가 호출됨 (synthetic event 형식)
expect(handleChange).toHaveBeenCalledTimes(1);
expect(handleChange).toHaveBeenCalledWith(
expect.objectContaining({
target: { value: 'name' },
type: 'change',
})
);
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
it('선택된 옵션에 체크마크가 표시된다', () => {
render(<Select options={options} value="email" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 선택된 옵션 찾기
const selectedOption = screen.getAllByRole('option').find(
opt => opt.getAttribute('aria-selected') === 'true'
);
expect(selectedOption).toBeTruthy();
expect(selectedOption?.textContent).toContain('이메일');
});
it('disabled 상태에서 클릭이 작동하지 않는다', () => {
render(<Select options={options} value="" onChange={() => {}} disabled />);
const button = screen.getByRole('button');
expect(button).toHaveProperty('disabled', true);
fireEvent.click(button);
// 드롭다운이 열리지 않음
expect(screen.queryByRole('listbox')).toBeNull();
});
it('외부 클릭 시 드롭다운이 닫힌다', () => {
render(
<div>
<Select options={options} value="" onChange={() => {}} />
<div data-testid="outside">외부 영역</div>
</div>
);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByRole('listbox')).toBeTruthy();
// 외부 클릭
const outside = screen.getByTestId('outside');
fireEvent.mouseDown(outside);
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
it('ESC 키로 드롭다운이 닫힌다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByRole('listbox')).toBeTruthy();
// ESC 키 입력
fireEvent.keyDown(document, { key: 'Escape' });
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
});
describe('커스텀 드롭다운 스타일 (options 모드)', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
it('기본 스타일이 적용된다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.className).toContain('bg-gray-100');
expect(button.className).toContain('rounded-xl');
});
it('커스텀 className이 적용된다', () => {
render(
<Select
options={options}
value="1"
onChange={() => {}}
className="bg-blue-100 custom-class"
/>
);
const button = screen.getByRole('button');
expect(button.className).toContain('bg-blue-100');
expect(button.className).toContain('custom-class');
});
it('드롭다운 메뉴가 둥근 모서리를 가진다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const listbox = screen.getByRole('listbox');
expect(listbox.className).toContain('rounded-2xl');
expect(listbox.className).toContain('shadow-lg');
});
});
describe('string[] options 지원', () => {
it('string 배열을 옵션으로 변환한다', () => {
render(<Select options={['ko', 'en']} value="ko" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 로케일 이름으로 변환됨 (role="option"으로 찾음)
const optionElements = screen.getAllByRole('option');
const labels = optionElements.map(opt => opt.textContent);
expect(labels).toContain('한국어');
expect(labels).toContain('English');
});
it('알 수 없는 로케일은 그대로 표시된다', () => {
render(<Select options={['unknown']} value="unknown" onChange={() => {}} />);
expect(screen.getByText('unknown')).toBeTruthy();
});
});
describe('disabled 옵션 지원', () => {
it('disabled 옵션이 비활성화된다', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2', disabled: true },
];
const handleChange = vi.fn();
render(<Select options={options} value="1" onChange={handleChange} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const disabledOption = screen.getAllByRole('option').find(
opt => opt.textContent?.includes('옵션 2')
);
expect(disabledOption).toHaveProperty('disabled', true);
// 클릭해도 onChange가 호출되지 않음
fireEvent.click(disabledOption!);
expect(handleChange).not.toHaveBeenCalled();
});
});
describe('접근성 (options 모드)', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
it('aria-haspopup 속성이 있다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.getAttribute('aria-haspopup')).toBe('listbox');
});
it('aria-expanded가 열림 상태를 반영한다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.getAttribute('aria-expanded')).toBe('false');
fireEvent.click(button);
expect(button.getAttribute('aria-expanded')).toBe('true');
});
it('옵션에 role="option"이 있다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const optionElements = screen.getAllByRole('option');
expect(optionElements.length).toBe(2);
});
it('선택된 옵션에 aria-selected="true"가 있다', () => {
render(<Select options={options} value="2" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const selectedOption = screen.getAllByRole('option').find(
opt => opt.getAttribute('aria-selected') === 'true'
);
expect(selectedOption?.textContent).toContain('옵션 2');
});
});
describe('제어 컴포넌트 (options 모드)', () => {
it('value 변경에 따라 표시가 업데이트된다', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
const TestComponent = () => {
const [value, setValue] = React.useState('1');
return (
<div>
<Select
options={options}
value={value}
onChange={(e) => setValue(String(e.target.value))}
/>
<button onClick={() => setValue('2')}>변경</button>
</div>
);
};
render(<TestComponent />);
// 초기값 확인
expect(screen.getByText('옵션 1')).toBeTruthy();
// 외부에서 값 변경
fireEvent.click(screen.getByText('변경'));
// 표시가 업데이트됨
expect(screen.getByText('옵션 2')).toBeTruthy();
});
});
describe('빈 options 처리', () => {
it('빈 배열일 때도 렌더링된다', () => {
render(<Select options={[]} value="" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button).toBeTruthy();
});
it('options가 배열이 아닐 때 기본 select로 폴백된다', () => {
// @ts-expect-error - 의도적으로 잘못된 타입 전달
const { container } = render(<Select options="invalid" />);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
});
// ========================================
// 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('');
});
});
});
@@ -142,6 +142,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());
// 대기 파일 변경 시 콜백
useEffect(() => {
@@ -674,35 +676,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) {
console.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) {
console.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');
@@ -33,6 +33,9 @@ import { ThemeToggle } from './ThemeToggle';
// Avatar 컴포넌트 import
import { Avatar } from './Avatar';
// NotificationCenter 컴포넌트 import
import { NotificationCenter, type NotificationItem } from './NotificationCenter';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
@@ -84,6 +87,40 @@ interface HeaderProps {
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
// ===== 알림센터 드롭다운 Props =====
/** 알림 목록 (NotificationCenter에 전달) */
notifications?: NotificationItem[];
/** 더 불러올 페이지 존재 여부 */
notificationHasMore?: boolean;
/** 알림 로딩 상태 */
notificationLoading?: boolean;
/** "안 읽은 알림만" 필터 상태 */
notificationUnreadOnly?: boolean;
/** 알림 드롭다운 제목 */
notificationTitleText?: string;
/** 알림 없음 텍스트 */
notificationEmptyText?: string;
/** "모두 읽음" 텍스트 */
notificationMarkAllReadText?: string;
/** "모두 삭제" 텍스트 */
notificationDeleteAllText?: string;
/** "안 읽은 알림만" 체크박스 텍스트 */
notificationUnreadOnlyText?: string;
/** 알림 드롭다운 닫힐 때 (뷰포트에 보인 미읽음 ID 배열 전달) */
onNotificationClose?: (visibleUnreadIds: (string | number)[]) => void;
/** 개별 알림 클릭 */
onNotificationClick?: (notification: NotificationItem) => void;
/** 무한 스크롤: 추가 로드 */
onNotificationLoadMore?: () => void;
/** "모두 읽음" 처리 */
onNotificationMarkAllRead?: () => void;
/** "모두 삭제" 요청 (모달 오픈) */
onNotificationDeleteAll?: () => void;
/** 개별 알림 삭제 */
onNotificationDelete?: (notification: NotificationItem) => void;
/** "안 읽은 알림만" 체크박스 토글 */
onNotificationUnreadOnlyToggle?: (checked: boolean) => void;
}
/**
@@ -120,6 +157,23 @@ const Header: React.FC<HeaderProps> = ({
currentLocale = 'ko',
shopBase = '/shop',
className = '',
// 알림센터
notifications = [],
notificationHasMore = false,
notificationLoading = false,
notificationUnreadOnly = false,
notificationTitleText,
notificationEmptyText,
notificationMarkAllReadText,
notificationDeleteAllText,
notificationUnreadOnlyText,
onNotificationClose,
onNotificationClick,
onNotificationLoadMore,
onNotificationMarkAllRead,
onNotificationDeleteAll,
onNotificationDelete,
onNotificationUnreadOnlyToggle,
}) => {
const [searchQuery, setSearchQuery] = useState('');
const [showUserMenu, setShowUserMenu] = useState(false);
@@ -129,6 +183,14 @@ const Header: React.FC<HeaderProps> = ({
const userMenuRef = useRef<HTMLDivElement>(null);
const moreButtonRef = useRef<HTMLDivElement>(null);
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준 — 위지윅 overrideWidth 호환)
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;
// 경로 변경 감지 (SPA 네비게이션 대응)
useEffect(() => {
const handlePopState = () => setCurrentPath(window.location.pathname);
@@ -228,22 +290,24 @@ const Header: React.FC<HeaderProps> = ({
)}
</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>
{/* 검색바 (데스크톱 전용) */}
{!isMobile && (
<Form onSubmit={handleSearch} className="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">
@@ -254,15 +318,29 @@ const Header: React.FC<HeaderProps> = ({
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>
{/* 알림센터 드롭다운 — 로그인 사용자에게만 노출 */}
{user?.uuid && (
<NotificationCenter
notifications={notifications}
unreadCount={notificationCount}
hasMore={notificationHasMore}
loading={notificationLoading}
unreadOnly={notificationUnreadOnly}
titleText={notificationTitleText ?? t('mypage.notifications.title')}
emptyText={notificationEmptyText ?? t('mypage.notifications.empty')}
markAllReadText={notificationMarkAllReadText ?? t('mypage.notifications.mark_all_read')}
deleteAllText={notificationDeleteAllText ?? t('mypage.notifications.delete_all')}
unreadOnlyText={notificationUnreadOnlyText ?? t('mypage.notifications.unread_only')}
onClose={onNotificationClose}
onNotificationClick={onNotificationClick}
onLoadMore={onNotificationLoadMore}
onMarkAllRead={onNotificationMarkAllRead}
onDeleteAll={onNotificationDeleteAll}
onDelete={onNotificationDelete}
onUnreadOnlyToggle={onNotificationUnreadOnlyToggle}
dropdownAlign="right"
/>
)}
{/* 장바구니 */}
<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">
@@ -391,19 +469,22 @@ const Header: React.FC<HeaderProps> = ({
</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>
{/* 모바일 햄버거 메뉴 (모바일 전용) */}
{isMobile && (
<Button
onClick={onMobileMenuOpen}
className="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">
{/* 탭 네비게이션 (데스크톱 전용) */}
{!isMobile && (
<Nav className="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))}>
@@ -481,6 +562,7 @@ const Header: React.FC<HeaderProps> = ({
</Div>
</Div>
</Nav>
)}
</HeaderBasic>
);
};
@@ -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', 'mark',
'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, ' ');
@@ -88,6 +88,15 @@ const MobileNav: React.FC<MobileNavProps> = ({
}) => {
const drawerRef = useRef<HTMLDivElement>(null);
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준 — 위지윅 overrideWidth 호환)
const G7Core = (window as any).G7Core;
const useResponsive = G7Core?.useResponsive;
const responsiveValue = useResponsive?.();
// lg 미만(< 1024px)에서만 드로어 노출 — 데스크톱은 Header의 탭 nav 사용
const isPortable = responsiveValue
? responsiveValue.width < 1024
: typeof window !== 'undefined' && window.innerWidth < 1024;
// ESC 키로 닫기
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
@@ -115,10 +124,12 @@ const MobileNav: React.FC<MobileNavProps> = ({
};
if (!isOpen) return null;
// 데스크톱(lg+)에서는 모바일 드로어 자체를 노출하지 않음 (위지윅 overrideWidth 호환)
if (!isPortable) return null;
return (
<Div
className="fixed inset-0 z-50 lg:hidden"
className="fixed inset-0 z-50"
onClick={handleOverlayClick}
>
{/* 오버레이 */}
@@ -0,0 +1,374 @@
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';
/**
* 알림 아이템 인터페이스
*/
export interface NotificationItem {
id: string | number;
title: string;
message: string;
time: string;
read?: boolean;
iconName?: IconName;
data?: Record<string, unknown>;
onClick?: () => void;
}
/**
* NotificationCenter Props
*/
export interface NotificationCenterProps {
/** 알림 목록 */
notifications?: NotificationItem[];
/** 서버 기반 미읽음 알림 수 */
unreadCount?: number;
/** 추가 로드 가능 여부 */
hasMore?: boolean;
/** 로딩 상태 */
loading?: boolean;
/** 알림 제목 텍스트 */
titleText?: string;
/** 알림 없음 텍스트 */
emptyText?: string;
/** "모두 읽음" 버튼 텍스트 */
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 컴포넌트 (User)
*
* 알림 센터 - 알림 목록 표시, 무한스크롤, 읽음 추적.
* sirsoft-admin_basic의 NotificationCenter와 동일 API/동작을 제공한다.
*
* @example
* ```tsx
* <NotificationCenter
* notifications={[
* { id: 1, title: '새 댓글', message: '게시물에 댓글이 달렸습니다', time: '5분 전' }
* ]}
* unreadCount={5}
* hasMore={true}
* titleText="알림"
* emptyText="알림이 없습니다."
* />
* ```
*/
export const NotificationCenter: React.FC<NotificationCenterProps> = ({
notifications = [],
unreadCount = 0,
hasMore = false,
loading = false,
titleText = '알림',
emptyText = '알림이 없습니다.',
markAllReadText = '모두 읽음',
deleteAllText = '모두 삭제',
unreadOnlyText = '안 읽은 알림만',
unreadOnly = false,
onNotificationClick,
onClose,
onLoadMore,
onMarkAllRead,
onDeleteAll,
onDelete,
onUnreadOnlyToggle,
dropdownAlign = 'right',
className = '',
}) => {
const [showNotifications, setShowNotifications] = useState(false);
const notificationRef = useRef<HTMLDivElement>(null);
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)
) {
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={handleToggle}
className="relative p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
aria-label={titleText}
>
<Icon name={IconName.Bell} className="w-5 h-5" />
{displayCount > 0 && (
<Span className="absolute -top-1 -right-1 w-5 h-5 flex items-center justify-center text-xs font-bold text-white bg-red-500 rounded-full">
{displayCount > 99 ? '99+' : displayCount}
</Span>
)}
</Button>
{/* 알림 드롭다운 */}
{showNotifications && (
<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 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) => {
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="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>
);
})}
{/* 무한스크롤 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>
)}
{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>
)}
</Div>
);
};
export default NotificationCenter;
@@ -422,29 +422,30 @@ function renderChildren(
children: LayoutComponent[] | undefined,
animClass: string,
iterCount: number,
width: number,
): (React.ReactElement | null)[] {
if (!children || children.length === 0) return [];
const filtered = filterChildren(children);
return filtered.map((child, i) =>
renderSkeletonNode(child, animClass, iterCount, i)
renderSkeletonNode(child, animClass, iterCount, i, width)
);
}
/**
* 현재 뷰포트에 맞는 className 결정
*
* responsive 속성이 있으면 현재 window 크기에 따라 적절한 className 선택.
* responsive 속성이 있으면 호출자가 전달한 viewport width 기준으로 적절한 className 선택.
* - desktop (lg, 1024px+): responsive.desktop.props.className
* - tablet (md, 768px+): responsive.tablet.props.className
* - 기본: props.className
*
* @param width G7Core.useResponsive()로 구독한 viewport width (overrideWidth 반영)
*/
function resolveClassName(component: LayoutComponent): string {
function resolveClassName(component: LayoutComponent, width: number): 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;
}
@@ -456,18 +457,19 @@ function resolveClassName(component: LayoutComponent): string {
}
/**
* Tailwind 반응형 display 클래스를 현재 뷰포트 기준으로 해석
* Tailwind 반응형 display 클래스를 viewport 기준으로 해석
*
* 레이아웃 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 결정
* 2. Tailwind cascade 규칙 적용: base → sm → md → lg → xl → 2xl 순서로 width에 맞는 display 결정
* 3. hidden이면 컴포넌트 숨김, 아니면 해석된 display 클래스 + 나머지 클래스 반환
*
* @param width G7Core.useResponsive()로 구독한 viewport width (overrideWidth 반영)
*/
function resolveResponsiveDisplay(className: string): { visible: boolean; className: string } {
const width = typeof window !== 'undefined' ? window.innerWidth : 1024;
function resolveResponsiveDisplay(className: string, width: number): { visible: boolean; className: string } {
const tokens = className.split(/\s+/).filter(Boolean);
const displayEntries: Array<{ breakpoint: number; display: string }> = [];
@@ -560,10 +562,11 @@ function renderSkeletonNode(
animClass: string,
iterCount: number,
index: number,
width: number,
): React.ReactElement | null {
const { name, children, iteration } = component;
// 1. responsive 속성에서 뷰포트에 맞는 className 선택
const rawClassName = resolveClassName(component);
const rawClassName = resolveClassName(component, width);
// 1.5. Flex/Grid 레이아웃 props → Tailwind 클래스 병합
const layoutClasses = resolveLayoutProps(component);
const mergedClassName = layoutClasses
@@ -572,7 +575,7 @@ function renderSkeletonNode(
// 2. {{...}} 표현식 해석 (삼항 → true 분기)
const exprResolved = resolveExpressions(mergedClassName);
// 3. Tailwind 반응형 display 클래스 해석 (hidden lg:grid → grid at desktop)
const responsive = resolveResponsiveDisplay(exprResolved);
const responsive = resolveResponsiveDisplay(exprResolved, width);
if (!name) return null;
@@ -591,6 +594,7 @@ function renderSkeletonNode(
animClass,
iterCount,
i,
width,
)
))}
</React.Fragment>
@@ -620,7 +624,7 @@ function renderSkeletonNode(
}
// 자식 렌더링 (조건부 분기 필터링 적용)
const renderedChildren = renderChildren(children, animClass, iterCount);
const renderedChildren = renderChildren(children, animClass, iterCount, width);
const hasContent = renderedChildren.length > 0 && renderedChildren.some(c => c !== null);
// 모든 자식이 필터링됨 (로딩/에러 wrapper 등) → 컨테이너 자체 스킵
@@ -686,7 +690,7 @@ function renderSkeletonNode(
if (name === 'Button') {
if (children && children.length > 0) {
const sanitized = sanitizeClassName(className, name);
const renderedChildren = renderChildren(children, animClass, iterCount);
const renderedChildren = renderChildren(children, animClass, iterCount, width);
const hasContent = renderedChildren.length > 0 && renderedChildren.some(c => c !== null);
if (!hasContent) return null;
// 원본 className에 border/rounded가 있으면 실제 버튼 형태 → 스켈레톤 경계 추가
@@ -712,7 +716,7 @@ function renderSkeletonNode(
if (children && children.length > 0) {
return (
<div key={index} className={sanitizedLeafClass}>
{renderChildren(children, animClass, iterCount)}
{renderChildren(children, animClass, iterCount, width)}
</div>
);
}
@@ -740,6 +744,14 @@ function renderSkeletonNode(
export const PageSkeleton: React.FC<PageSkeletonProps> = ({ components, options }) => {
const animClass = getAnimationClass(options.animation);
// G7Core.useResponsive를 통해 viewport width 구독 (G7 표준 — 위지윅 overrideWidth 호환)
const G7Core = (window as any).G7Core;
const useResponsive = G7Core?.useResponsive;
const responsiveValue = useResponsive?.();
const width = responsiveValue
? responsiveValue.width
: (typeof window !== 'undefined' ? window.innerWidth : 1024);
return (
<div
className="w-full"
@@ -747,7 +759,7 @@ export const PageSkeleton: React.FC<PageSkeletonProps> = ({ components, options
aria-busy="true"
aria-label="Loading..."
>
{renderChildren(components, animClass, options.iteration_count)}
{renderChildren(components, animClass, options.iteration_count, width)}
</div>
);
};
@@ -1,10 +1,11 @@
import React, { useState, useEffect } from 'react';
import React from 'react';
import { Nav } from '../basic/Nav';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import { Select } from '../basic/Select';
export interface Tab {
id: string | number;
@@ -21,12 +22,10 @@ export interface TabNavigationProps {
variant?: 'default' | 'pills' | 'underline';
className?: string;
style?: React.CSSProperties;
/** 모바일에서 그리드 레이아웃 사용 (기본: true) */
mobileGrid?: boolean;
/** 모바일 그리드 컬럼 수 (기본: 3) */
mobileColumns?: number;
/** 숨길 탭 ID 목록 (동적 조건부 탭 노출용) */
hiddenTabIds?: (string | number)[];
/** 모바일 전환 임계값 (px). 기본값 768 — G7 ResponsiveContext mobile 프리셋과 동일 */
mobileBreakpoint?: number;
}
/**
@@ -34,12 +33,15 @@ 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 사용 예시
@@ -47,7 +49,6 @@ export interface TabNavigationProps {
* "name": "TabNavigation",
* "props": {
* "activeTabId": 1,
* "mobileColumns": 3,
* "tabs": [
* {"id": 1, "label": "프로필", "iconName": "user"},
* {"id": 2, "label": "설정", "iconName": "cog", "badge": 3},
@@ -64,22 +65,16 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
variant = 'underline',
className = '',
style,
mobileGrid = true,
mobileColumns = 3,
hiddenTabIds = [],
mobileBreakpoint = 768,
}) => {
const [isMobile, setIsMobile] = useState(false);
// 모바일 감지 (768px 기준)
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768);
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
// 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) {
@@ -87,23 +82,52 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
}
};
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);
}
};
const visibleTabs = hiddenTabIds.length > 0
? tabs.filter((tab) => !hiddenTabIds.includes(tab.id))
: tabs;
// 모바일: Select 드롭다운 단일 렌더
if (isMobile) {
return (
<Div className={`relative ${className}`} style={style}>
<Select
value={activeTabId !== undefined ? String(activeTabId) : ''}
onChange={handleSelectChange}
options={visibleTabs.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 = 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';
const baseClasses =
'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
@@ -123,65 +147,36 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
}
};
// 모바일 그리드 컬럼 클래스
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'
const navClasses =
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))}
{visibleTabs.map((tab) => (
<Button
key={tab.id}
type="button"
onClick={() => handleTabClick(tab)}
disabled={tab.disabled}
className={getTabClasses(tab)}
>
{tab.iconName && (
<Icon name={tab.iconName} size="sm" />
)}
<Span>{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>
))}
</Nav>
</Div>
);
@@ -0,0 +1,240 @@
/**
* NotificationCenter 컴포넌트 테스트 (sirsoft-basic)
*
* @description 알림센터 드롭다운의 핵심 동작 검증
* 주요 회귀:
* - 알림 카드는 Button이 아닌 Div (button-in-button HTML 무효 회피)
* - 외부 클릭 useEffect 의존성에 [showNotifications, handleClose] 포함
* - useEffect는 handleClose(useCallback) 정의 이후 위치 → TDZ 회피
* - 콜백은 notification 객체 전체를 인자로 전달 (id가 아님)
*/
import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import { NotificationCenter, type NotificationItem } from '../NotificationCenter';
// IntersectionObserver 폴리필
beforeEach(() => {
cleanup();
(window as any).IntersectionObserver = class {
observe() {}
unobserve() {}
disconnect() {}
};
});
const mockNotifications: NotificationItem[] = [
{
id: 1,
title: '새 댓글',
message: '게시물에 댓글이 달렸습니다',
time: '2026-04-10 10:00:00',
read: false,
},
{
id: 2,
title: '시스템 알림',
message: '시스템 점검이 완료되었습니다',
time: '2026-04-10 09:00:00',
read: true,
},
];
describe('NotificationCenter (sirsoft-basic)', () => {
describe('기본 렌더링', () => {
it('Bell 트리거 버튼이 렌더링됨', () => {
render(<NotificationCenter />);
expect(screen.getByLabelText('알림')).toBeInTheDocument();
});
it('unreadCount가 0보다 크면 배지가 표시됨', () => {
render(<NotificationCenter unreadCount={5} />);
expect(screen.getByText('5')).toBeInTheDocument();
});
it('unreadCount가 99 초과 시 99+로 표시됨', () => {
render(<NotificationCenter unreadCount={150} />);
expect(screen.getByText('99+')).toBeInTheDocument();
});
it('unreadCount가 0이면 배지가 표시되지 않음', () => {
const { container } = render(<NotificationCenter unreadCount={0} notifications={[]} />);
// 배지는 .bg-red-500 클래스를 가지는 Span
expect(container.querySelector('.bg-red-500')).not.toBeInTheDocument();
});
});
describe('드롭다운 토글', () => {
it('Bell 클릭 시 드롭다운이 열림', () => {
render(<NotificationCenter notifications={mockNotifications} titleText="알림" />);
fireEvent.click(screen.getByLabelText('알림'));
expect(screen.getByText('새 댓글')).toBeInTheDocument();
expect(screen.getByText('시스템 알림')).toBeInTheDocument();
});
it('알림이 비어있을 때 emptyText가 표시됨', () => {
render(<NotificationCenter notifications={[]} emptyText="알림이 없습니다." />);
fireEvent.click(screen.getByLabelText('알림'));
expect(screen.getByText('알림이 없습니다.')).toBeInTheDocument();
});
it('드롭다운 외부 클릭 시 닫힘 (외부 클릭 의존성 회귀)', () => {
const { container } = render(
<div>
<NotificationCenter notifications={mockNotifications} />
<div data-testid="outside">바깥</div>
</div>
);
fireEvent.click(screen.getByLabelText('알림'));
expect(screen.getByText('새 댓글')).toBeInTheDocument();
fireEvent.mouseDown(screen.getByTestId('outside'));
expect(screen.queryByText('새 댓글')).not.toBeInTheDocument();
});
});
describe('button-in-button 회귀 — 알림 카드는 Div', () => {
it('알림 카드가 button 태그가 아닌 div 태그여야 함', () => {
const { container } = render(<NotificationCenter notifications={mockNotifications} />);
fireEvent.click(screen.getByLabelText('알림'));
const titleEl = screen.getByText('새 댓글');
// 가장 가까운 알림 카드 컨테이너 (data-notification-id 속성을 가진 요소)
const card = titleEl.closest('[data-notification-id]');
expect(card).not.toBeNull();
expect(card!.tagName.toLowerCase()).toBe('div');
});
});
describe('이벤트 핸들러', () => {
it('알림 클릭 시 onNotificationClick 콜백에 객체 전체가 전달됨', () => {
const handler = vi.fn();
render(
<NotificationCenter
notifications={mockNotifications}
onNotificationClick={handler}
/>
);
fireEvent.click(screen.getByLabelText('알림'));
const card = screen.getByText('새 댓글').closest('[data-notification-id]');
fireEvent.click(card!);
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({ id: 1, title: '새 댓글' })
);
});
it('개별 삭제 버튼 클릭 시 onDelete가 호출되고 카드 클릭 이벤트는 전파되지 않음', () => {
const onDelete = vi.fn();
const onClick = vi.fn();
const { container } = render(
<NotificationCenter
notifications={mockNotifications}
onDelete={onDelete}
onNotificationClick={onClick}
/>
);
fireEvent.click(screen.getByLabelText('알림'));
const deleteBtn = container.querySelector('[aria-label="Delete notification"]');
expect(deleteBtn).not.toBeNull();
fireEvent.click(deleteBtn!);
expect(onDelete).toHaveBeenCalledTimes(1);
expect(onDelete).toHaveBeenCalledWith(
expect.objectContaining({ id: 1 })
);
// stopPropagation 검증: 카드 클릭 핸들러는 호출되지 않아야 함
expect(onClick).not.toHaveBeenCalled();
});
it('"모두 읽음" 버튼은 displayCount > 0 일 때만 표시되고 onMarkAllRead 호출', () => {
const onMarkAllRead = vi.fn();
render(
<NotificationCenter
notifications={mockNotifications}
unreadCount={2}
onMarkAllRead={onMarkAllRead}
markAllReadText="모두 읽음"
/>
);
fireEvent.click(screen.getByLabelText('알림'));
fireEvent.click(screen.getByText('모두 읽음'));
expect(onMarkAllRead).toHaveBeenCalledTimes(1);
});
it('"모두 삭제" 버튼은 notifications.length > 0 일 때만 표시되고 onDeleteAll 호출', () => {
const onDeleteAll = vi.fn();
render(
<NotificationCenter
notifications={mockNotifications}
onDeleteAll={onDeleteAll}
deleteAllText="모두 삭제"
/>
);
fireEvent.click(screen.getByLabelText('알림'));
fireEvent.click(screen.getByText('모두 삭제'));
expect(onDeleteAll).toHaveBeenCalledTimes(1);
});
it('"안 읽은 알림만" 체크박스 토글 시 onUnreadOnlyToggle 호출', () => {
const onUnreadOnlyToggle = vi.fn();
render(
<NotificationCenter
notifications={mockNotifications}
unreadOnly={false}
onUnreadOnlyToggle={onUnreadOnlyToggle}
unreadOnlyText="안 읽은 알림만"
/>
);
fireEvent.click(screen.getByLabelText('알림'));
const checkbox = screen.getByRole('checkbox') as HTMLInputElement;
fireEvent.click(checkbox);
expect(onUnreadOnlyToggle).toHaveBeenCalled();
expect(onUnreadOnlyToggle).toHaveBeenLastCalledWith(true);
});
});
describe('dropdownAlign prop', () => {
it('기본값은 right (right-0 클래스)', () => {
const { container } = render(<NotificationCenter notifications={mockNotifications} />);
fireEvent.click(screen.getByLabelText('알림'));
expect(container.querySelector('.right-0')).not.toBeNull();
});
it('left 지정 시 left-0 클래스', () => {
const { container } = render(
<NotificationCenter notifications={mockNotifications} dropdownAlign="left" />
);
fireEvent.click(screen.getByLabelText('알림'));
expect(container.querySelector('.left-0')).not.toBeNull();
});
});
describe('읽음/미읽음 시각 구분', () => {
it('미읽음 알림에는 파란 점이 있음', () => {
const { container } = render(
<NotificationCenter notifications={mockNotifications} />
);
fireEvent.click(screen.getByLabelText('알림'));
const blueDots = container.querySelectorAll('.bg-blue-500.rounded-full');
// 미읽음 1건만 점 표시
expect(blueDots.length).toBe(1);
});
it('미읽음 카드에는 파란 배경 클래스가 적용됨', () => {
render(<NotificationCenter notifications={mockNotifications} />);
fireEvent.click(screen.getByLabelText('알림'));
const unread = screen.getByText('새 댓글').closest('[data-notification-id]');
expect(unread?.className).toMatch(/bg-blue-50/);
});
it('읽음 카드에는 opacity-70 클래스가 적용됨', () => {
render(<NotificationCenter notifications={mockNotifications} />);
fireEvent.click(screen.getByLabelText('알림'));
const read = screen.getByText('시스템 알림').closest('[data-notification-id]');
expect(read?.className).toMatch(/opacity-70/);
});
});
});
@@ -2,47 +2,30 @@
* TabNavigation 컴포넌트 테스트
*
* @description 탭 네비게이션 컴포넌트의 동작을 테스트합니다.
* 주요 검증: 탭 렌더링, 탭 전환, 뱃지 표시, hiddenTabIds, disabled 상태
* 주요 검증: 탭 렌더링, 탭 전환, 뱃지 표시, hiddenTabIds, disabled, 반응형 분기 (G7Core.useResponsive)
*/
import React, { useState } from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import type { Tab } from '../TabNavigation';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { TabNavigation, type Tab } from '../TabNavigation';
// basic 컴포넌트 의존성을 제거한 Mock TabNavigation
const MockTabNavigation: React.FC<{
tabs: Tab[];
activeTabId?: string | number;
onTabChange?: (tabId: string | number) => void;
mobileGrid?: boolean;
hiddenTabIds?: (string | number)[];
}> = ({ tabs, activeTabId, onTabChange, mobileGrid = true, hiddenTabIds = [] }) => {
const visibleTabs = hiddenTabIds.length > 0
? tabs.filter((tab) => !hiddenTabIds.includes(tab.id))
: tabs;
const mockUseResponsive = vi.fn(() => ({
width: 1024,
isMobile: false,
isTablet: false,
isDesktop: true,
matchedPreset: 'desktop' as const,
}));
return (
<nav data-testid="tab-navigation">
{visibleTabs.map((tab) => (
<button
key={tab.id}
data-testid={`tab-${tab.id}`}
onClick={() => !tab.disabled && onTabChange?.(tab.id)}
disabled={tab.disabled}
aria-selected={tab.id === activeTabId}
>
<span data-testid={`tab-label-${tab.id}`}>{tab.label}</span>
{mobileGrid && tab.badge !== undefined && (
<span data-testid={`tab-badge-${tab.id}`}>{tab.badge}</span>
)}
{!mobileGrid && tab.badge !== undefined && (
<span data-testid={`tab-badge-${tab.id}`}>{tab.badge}</span>
)}
</button>
))}
</nav>
);
const setMobile = () => {
mockUseResponsive.mockReturnValue({
width: 375,
isMobile: true,
isTablet: false,
isDesktop: false,
matchedPreset: 'mobile' as const,
});
};
const defaultTabs: Tab[] = [
@@ -52,50 +35,72 @@ const defaultTabs: Tab[] = [
];
describe('TabNavigation 컴포넌트', () => {
describe('렌더링', () => {
it('모든 탭이 렌더링되어야 함', () => {
render(<MockTabNavigation tabs={defaultTabs} activeTabId="detail" />);
let originalG7Core: any;
expect(screen.getByTestId('tab-detail')).toBeInTheDocument();
expect(screen.getByTestId('tab-reviews')).toBeInTheDocument();
expect(screen.getByTestId('tab-qna')).toBeInTheDocument();
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();
});
describe('데스크톱 렌더링', () => {
it('Nav 안의 버튼으로 모든 탭이 렌더링되어야 함', () => {
const { container } = render(
<TabNavigation tabs={defaultTabs} activeTabId="detail" />
);
expect(container.querySelector('nav')).toBeInTheDocument();
expect(screen.getByText('상세정보')).toBeInTheDocument();
expect(screen.getByText('리뷰')).toBeInTheDocument();
expect(screen.getByText('문의')).toBeInTheDocument();
});
it('탭 라벨이 표시되어야 함', () => {
render(<MockTabNavigation tabs={defaultTabs} activeTabId="detail" />);
it('Select 드롭다운은 렌더링되지 않아야 함', () => {
const { container } = render(
<TabNavigation tabs={defaultTabs} activeTabId="detail" />
);
expect(screen.getByTestId('tab-label-detail')).toHaveTextContent('상세정보');
expect(screen.getByTestId('tab-label-reviews')).toHaveTextContent('리뷰');
expect(screen.getByTestId('tab-label-qna')).toHaveTextContent('문의');
const selects = container.querySelectorAll('select');
expect(selects.length).toBe(0);
});
it('활성 탭이 aria-selected=true 이어야 함', () => {
render(<MockTabNavigation tabs={defaultTabs} activeTabId="reviews" />);
it('활성 탭이 활성화 스타일을 가져야 함', () => {
render(
<TabNavigation tabs={defaultTabs} activeTabId="reviews" variant="underline" />
);
expect(screen.getByTestId('tab-reviews')).toHaveAttribute('aria-selected', 'true');
expect(screen.getByTestId('tab-detail')).toHaveAttribute('aria-selected', 'false');
const activeButton = screen.getByText('리뷰').closest('button');
expect(activeButton).toHaveClass('border-b-2');
});
});
describe('뱃지(badge)', () => {
it('badge가 있는 탭에 뱃지가 표시되어야 함', () => {
render(<MockTabNavigation tabs={defaultTabs} activeTabId="detail" />);
it('뱃지가 표시되어야 함', () => {
render(<TabNavigation tabs={defaultTabs} activeTabId="detail" />);
expect(screen.getByTestId('tab-badge-reviews')).toHaveTextContent('12');
expect(screen.getByTestId('tab-badge-qna')).toHaveTextContent('3');
});
it('badge가 없는 탭에는 뱃지가 렌더링되지 않아야 함', () => {
render(<MockTabNavigation tabs={defaultTabs} activeTabId="detail" />);
expect(screen.queryByTestId('tab-badge-detail')).not.toBeInTheDocument();
expect(screen.getByText('12')).toBeInTheDocument();
expect(screen.getByText('3')).toBeInTheDocument();
});
it('badge 값이 0일 때도 표시되어야 함', () => {
const tabs: Tab[] = [{ id: 'qna', label: '문의', badge: 0 }];
render(<MockTabNavigation tabs={tabs} activeTabId="qna" />);
render(<TabNavigation tabs={tabs} activeTabId="qna" />);
expect(screen.getByTestId('tab-badge-qna')).toHaveTextContent('0');
expect(screen.getByText('0')).toBeInTheDocument();
});
});
@@ -103,10 +108,14 @@ describe('TabNavigation 컴포넌트', () => {
it('탭 클릭 시 onTabChange가 호출되어야 함', () => {
const onTabChange = vi.fn();
render(
<MockTabNavigation tabs={defaultTabs} activeTabId="detail" onTabChange={onTabChange} />,
<TabNavigation
tabs={defaultTabs}
activeTabId="detail"
onTabChange={onTabChange}
/>
);
fireEvent.click(screen.getByTestId('tab-reviews'));
fireEvent.click(screen.getByText('리뷰').closest('button')!);
expect(onTabChange).toHaveBeenCalledWith('reviews');
});
@@ -114,19 +123,21 @@ describe('TabNavigation 컴포넌트', () => {
const Wrapper = () => {
const [activeTabId, setActiveTabId] = useState<string | number>('detail');
return (
<MockTabNavigation
<TabNavigation
tabs={defaultTabs}
activeTabId={activeTabId}
onTabChange={setActiveTabId}
variant="underline"
/>
);
};
render(<Wrapper />);
expect(screen.getByTestId('tab-detail')).toHaveAttribute('aria-selected', 'true');
fireEvent.click(screen.getByTestId('tab-reviews'));
expect(screen.getByTestId('tab-reviews')).toHaveAttribute('aria-selected', 'true');
expect(screen.getByTestId('tab-detail')).toHaveAttribute('aria-selected', 'false');
expect(screen.getByText('상세정보').closest('button')).toHaveClass('border-b-2');
fireEvent.click(screen.getByText('리뷰').closest('button')!);
expect(screen.getByText('리뷰').closest('button')).toHaveClass('border-b-2');
});
});
@@ -138,44 +149,91 @@ describe('TabNavigation 컴포넌트', () => {
{ id: 'reviews', label: '리뷰', disabled: true },
];
render(
<MockTabNavigation tabs={tabs} activeTabId="detail" onTabChange={onTabChange} />,
<TabNavigation
tabs={tabs}
activeTabId="detail"
onTabChange={onTabChange}
/>
);
fireEvent.click(screen.getByTestId('tab-reviews'));
fireEvent.click(screen.getByText('리뷰').closest('button')!);
expect(onTabChange).not.toHaveBeenCalled();
});
it('disabled 탭은 disabled 속성이 있어야 함', () => {
const tabs: Tab[] = [{ id: 'reviews', label: '리뷰', disabled: true }];
render(<MockTabNavigation tabs={tabs} activeTabId="detail" />);
render(<TabNavigation tabs={tabs} activeTabId="detail" />);
expect(screen.getByTestId('tab-reviews')).toBeDisabled();
expect(screen.getByText('리뷰').closest('button')).toBeDisabled();
});
});
describe('hiddenTabIds', () => {
it('hiddenTabIds에 포함된 탭은 렌더링되지 않아야 함', () => {
render(
<MockTabNavigation
<TabNavigation
tabs={defaultTabs}
activeTabId="detail"
hiddenTabIds={['qna']}
/>,
/>
);
expect(screen.getByTestId('tab-detail')).toBeInTheDocument();
expect(screen.getByTestId('tab-reviews')).toBeInTheDocument();
expect(screen.queryByTestId('tab-qna')).not.toBeInTheDocument();
expect(screen.getByText('상세정보')).toBeInTheDocument();
expect(screen.getByText('리뷰')).toBeInTheDocument();
expect(screen.queryByText('문의')).not.toBeInTheDocument();
});
it('hiddenTabIds가 빈 배열이면 모든 탭이 표시되어야 함', () => {
render(
<MockTabNavigation tabs={defaultTabs} activeTabId="detail" hiddenTabIds={[]} />,
<TabNavigation tabs={defaultTabs} activeTabId="detail" hiddenTabIds={[]} />
);
expect(screen.getByTestId('tab-detail')).toBeInTheDocument();
expect(screen.getByTestId('tab-reviews')).toBeInTheDocument();
expect(screen.getByTestId('tab-qna')).toBeInTheDocument();
expect(screen.getByText('상세정보')).toBeInTheDocument();
expect(screen.getByText('리뷰')).toBeInTheDocument();
expect(screen.getByText('문의')).toBeInTheDocument();
});
});
describe('모바일 (useResponsive isMobile=true)', () => {
beforeEach(() => {
setMobile();
});
it('Nav 대신 Select 드롭다운만 렌더링해야 함', () => {
const { container } = render(
<TabNavigation tabs={defaultTabs} activeTabId="detail" />
);
expect(container.querySelector('nav')).not.toBeInTheDocument();
// custom Select trigger button이 존재해야 함
const trigger = container.querySelector('button');
expect(trigger).toBeInTheDocument();
});
it('현재 활성 탭의 label을 Select trigger에 표시해야 함', () => {
render(<TabNavigation tabs={defaultTabs} activeTabId="detail" />);
expect(screen.getByText('상세정보')).toBeInTheDocument();
});
it('뱃지가 있는 탭은 label과 함께 뱃지 수를 병기해야 함', () => {
render(<TabNavigation tabs={defaultTabs} activeTabId="reviews" />);
expect(screen.getByText('리뷰 (12)')).toBeInTheDocument();
});
it('hiddenTabIds가 모바일에서도 적용되어야 함', () => {
render(
<TabNavigation
tabs={defaultTabs}
activeTabId="detail"
hiddenTabIds={['qna']}
/>
);
// 활성 라벨은 보이지만 숨김 처리된 항목은 보이지 않음 (Select 닫힌 상태)
expect(screen.getByText('상세정보')).toBeInTheDocument();
expect(screen.queryByText('문의')).not.toBeInTheDocument();
});
});
});
@@ -9,6 +9,8 @@
export { default as Header } from './Header';
export { default as Footer } from './Footer';
export { default as MobileNav } from './MobileNav';
export { NotificationCenter } from './NotificationCenter';
export type { NotificationCenterProps, NotificationItem } from './NotificationCenter';
// 상품 관련 컴포넌트
export { default as ProductCard } from './ProductCard';
@@ -63,6 +65,7 @@ export const compositeComponents = {
Header: () => import('./Header'),
Footer: () => import('./Footer'),
MobileNav: () => import('./MobileNav'),
NotificationCenter: () => import('./NotificationCenter'),
// 상품
ProductCard: () => import('./ProductCard'),