v7.0.0-beta.1 release

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

No files matched your search

@@ -0,0 +1,450 @@
# Changelog
이 프로젝트의 모든 주요 변경사항을 기록합니다.
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.0-beta.1] - 2026-04-01
### Changed
- 오픈 베타 릴리즈
## [0.2.34] - 2026-03-31
### Added
- 템플릿 업데이트 모달 — "수정 유지" 선택 시 수정된 레이아웃 목록 패널 표시 (이름, 변화량, 수정 일시) (_modal_update.json, _tab_admin.json, _tab_user.json, lang)
### Changed
- 사용자 관리 국가 입력항목 및 표시 숨김 처리 (admin_user_list.json, admin_user_form.json, admin_user_detail.json)
### Fixed
- 관리자 검색 페이지에서 다른 페이지로 이동 후 돌아올 때 이전 검색어가 Input에 유지되던 문제 수정 — `_global` 상태를 `_local`로 전환, `init_actions`로 URL 쿼리 기준 초기화 (admin_user_list.json, admin_module_list.json, admin_plugin_list.json, admin_role_list.json, admin_schedule_list.json, admin_template_list.json, _tab_user.json, _tab_admin.json)
## [0.2.33] - 2026-03-30
### Added
- 관리자 로그인 화면 개선 — 비밀번호 찾기/재설정 플로우 레이아웃 추가, 테마 Segmented Control, 언어 셀렉트 확대 (admin_login.json, admin_forgot_password.json, admin_reset_password.json, lang, passwordResetHandlers)
- 활동 로그 이력 조회 관리자 레이아웃 및 다국어 추가 (admin_activity_logs.json, _partial_activity_log_detail.json)
- 환경설정 드라이버 탭 검색엔진 설정 UI 및 다국어 추가 (_tab_drivers.json, lang)
### Fixed
- DynamicFieldList/MultilingualInput stale closure 수정 — 디바운스 병합 시 이전 키 변경 유실 방지 (DynamicFieldList.tsx, MultilingualInput.tsx)
- FileUploader onRemove 시 form 데이터 동기화 누락 수정 — 환경설정 로고 삭제 시 폼 데이터 미반영 (_tab_general.json)
- 사용자 관리에서 관리자/슈퍼관리자 삭제 시 토스트 메시지 및 어빌리티 처리 — 삭제 불가 사용자 UI 반영 (admin_user_list.json)
### Removed
- 게시판 사용자 알림 설정 확장 파일 제거 (extensions/)
## [0.2.32] - 2026-03-30
### Fixed
- 레이아웃 편집 버전 히스토리 복원 후 에디터 content 미갱신 수정 — onSuccess에서 `refetchDataSource` 후 `_global.editorContent`를 명시적으로 갱신하여 stale 에디터 내용이 DB를 덮어쓰는 문제 방지 (_modal_version_history.json)
- 버전 히스토리 복원 버튼 `sequence` 핸들러 문법 수정 — top-level `actions` → `params.actions` (_modal_version_history.json)
### Removed
- 작동 불가한 "템플릿 업데이트 변경 내역 확인" 버튼 및 모달 삭제 (admin_template_layout_edit.json, _modal_template_changelog.json)
## [0.2.31] - 2026-03-30
### Changed
- 환경설정 드라이버 탭 저장 버튼 비활성화 조건을 `_global.settings.drivers` 참조에서 `_local.originalDrivers` (API 원본값) 참조로 변경 — `window.G7Config`에서 drivers 설정 미노출 대응 (admin_settings.json initLocal 맵 확장)
## [0.2.30] - 2026-03-30
### Fixed
- 다크모드 전수 조사 및 수정 — TSX 컴포넌트 약 26건, CSS 5건의 누락된 `dark:` variant 추가
- PermissionTree, FileUploader, DynamicFieldList, SectionLayout, TagInput, SortableMenuItem, Accordion, ColumnSelector, IconSelect, LanguageSelector, MultilingualInput, Toggle 등
- ui-elements.css: Select SVG 아이콘 다크모드 밝은 색상 추가, 폼 Input 6개 클래스 `dark:bg-gray-800` → `dark:bg-gray-700` (카드 배경과 구분)
- Select 컴포넌트 다크모드 텍스트 색상 누락 수정 — 커스텀 `bg-*` className 사용 시 텍스트 색상 자동 보충 로직 추가 (`hasTextColor` 검사 → `text-gray-700 dark:text-gray-200` 보충)
- safelist에 다크모드 클래스 패밀리 46개 추가 (amber, emerald, teal, cyan 등)
## [0.2.29] - 2026-03-30
### Fixed
- FileUploader 상품 수정 시 이미지 순서 유실 버그 3건 수정 — customOrder 상태 도입으로 기존/신규 파일 간 드래그 순서 보존, handleDragEnd에서 customOrder 기반 정렬, 업로드 완료 즉시 pending ID→hash 교체 (useFileUploader.ts)
- FileUploader 상품 복사 모드 지원 — hash 기반 이미지 식별, id 없는 이미지 서버 삭제 스킵, 복사 모드 삭제 후 재출현 방지 (useFileUploader.ts, FileList.tsx, types.ts)
- FileUploader onReorder 콜백 추가 — 드래그 순서 변경 및 업로드 완료 시 부모에게 정렬된 파일 목록 전달 (useFileUploader.ts, FileUploader.tsx, types.ts)
- FileUploader 대표이미지 식별 hash 기반 전환 — primaryFileId에 hash 우선 사용 (FileList.tsx, types.ts)
- FileUploader 업로드 응답 ResponseHelper 이중 래핑 대응 — response.data.data ?? response.data 패턴 (useFileUploader.ts)
- FileUploader mime_type null 방어 코드 추가 — optional chaining으로 startsWith 에러 방지 (useFileUploader.ts, SortableThumbnailItem.tsx, FileList.tsx, utils.ts)
## [0.2.28] - 2026-03-30
### Fixed
- DynamicFieldList 입력 시 포커스 아웃 수정 — itemIdKey가 없는 아이템에 자동 ID 부여로 setState 라운드트립 후에도 React key 안정성 유지 (DynamicFieldList.tsx)
## [0.2.27] - 2026-03-29
### Fixed
- FileUploader mime_type null 방어 코드 추가 — optional chaining으로 startsWith 에러 방지 (useFileUploader.ts, SortableThumbnailItem.tsx, FileList.tsx, utils.ts)
- FileUploader 대표이미지 식별 hash 기반 전환 — primaryFileId 비교/이벤트에 hash 우선 사용, 복사 모드(id 없는 이미지) 삭제 시 서버 API 호출 스킵 (useFileUploader.ts, FileList.tsx, types.ts)
- FileUploader 복사 모드 이미지 삭제 후 재출현 버그 수정 — deletedIdsRef에 hash 추가 추적, initialFiles 동기화 시 hash 기반 필터링 (useFileUploader.ts)
## [0.2.26] - 2026-03-28
### Changed
- 레이아웃 편집기 CodeEditor, 레이아웃 설명, 파일 설명 바인딩에 `raw:` 접두사 적용 — 사용자 입력 데이터 내 `$t:` 패턴 번역 방지 (admin_template_layout_edit.json) (#225)
## [0.2.25] - 2026-03-28
### Added
- 활동 로그 기간 검색 프리셋 버튼 추가 — 오늘, 1주일, 1개월, 3개월, 6개월, 1년 빠른 선택 (주문관리와 동일 UX) (_partial_filter.json) (#225)
- `setDateRange` 핸들러 추가 — 날짜 프리셋별 시작일/종료일 자동 계산, datetime-local 형식 반환 (setDateRangeHandler.ts) (#225)
- 삭제 모달 스피너 추가 — 개별/일괄 삭제 진행 중 삭제 버튼에 스피너 아이콘 표시 (admin_activity_log_list.json) (#225)
### Changed
- 활동 로그 기간 필터를 date에서 datetime-local로 변경 — 시/분/초 지정 가능 (_partial_filter.json) (#225)
## [0.2.24] - 2026-03-28
### Changed
- 활동 로그 행위자 필터를 텍스트 Input에서 SearchableDropdown으로 변경 — UUID 기반 사용자 검색, API `/api/admin/users/search` 연동 (_partial_filter.json, admin_activity_log_list.json) (#225)
- 활동 로그 DataGrid 행위자 컬럼을 ActionMenu로 변경 — 회원 정보 보기, 해당 행위자로 검색 기능 추가 (_partial_datagrid.json) (#225)
- 활동 로그 양방향(한글/영어) 검색 지원 — 액션/설명 검색 시 번역 라벨 역추적으로 원본 키도 함께 검색 (ActivityLogRepository.php) (#225)
## [0.2.23] - 2026-03-28
### Added
- 활동 로그 이력 조회 메뉴 및 목록 페이지 신설 — 필터(검색어, 로그 타입, 날짜 범위), DataGrid(확장 행으로 변경 내역 표시), 서버 사이드 페이지네이션, 단건/일괄 삭제 기능 (admin_activity_log_list.json, _partial_filter.json, _partial_datagrid.json) (#225)
- 활동 로그 다국어 키 추가 — 페이지 제목, 필터 레이블, 테이블 컬럼, 상세 정보, 삭제 확인 메시지 등 (ko/admin.json, en/admin.json) (#225)
- 활동 로그 목록 레이아웃 렌더링 테스트 추가 — 필터 UI, DataGrid 렌더링, 빈 상태, abilities 기반 삭제 버튼 제어 (admin-activity-log-list.test.tsx) (#225)
- 대시보드 활동 로그 레이아웃 렌더링 테스트 추가 (admin-dashboard-activity-log.test.tsx) (#225)
### Changed
- 활동 로그 필터 전면 재구현 — 검색 키워드 대상 드롭다운(전체/액션/설명/IP주소), 로그 타입 체크박스(전체/관리자/사용자/시스템), 행위자 필터, 기간 필터, filter-row/filter-label CSS 패턴 (_partial_filter.json, admin_activity_log_list.json) (#225)
- DataGrid `expandConditionField` prop 추가 — 행별 조건부 확장 아이콘 표시 지원, `has_changes` 필드 기반 변경 이력 있는 행만 확장 가능 (DataGrid.tsx) (#225)
- 활동 로그 DataGrid에 IP 주소 컬럼 추가, selectable 항상 활성화, expandConditionField 적용 (_partial_datagrid.json) (#225)
- 활동 로그 일괄 삭제 버튼 `if` 조건 → `disabled` 속성으로 변경 (admin_activity_log_list.json) (#225)
- 대시보드 "시스템 알림" 카드 숨김 처리 — `if: "false"` 추가, dashboard_alerts 데이터소스 `auto_fetch: false` 변경 (admin_dashboard.json) (#225)
- 대시보드 "최근 활동"이 사용자 가입 이력 대신 ActivityLog 전체를 표시하도록 변경 (admin_dashboard.json) (#225)
## [0.2.22] - 2026-03-28
### Fixed
- 대시보드 모듈 상태 배지가 항상 "비활성화"로 표시되는 버그 수정 — `module.is_active` (미존재 필드) → `module.status === 'active'` (admin_dashboard.json) (#225)
- 대시보드 확장 카드 아이콘을 사이드바 메뉴 아이콘과 일치 — 모듈: cube, 플러그인: puzzle-piece, 템플릿: palette (admin_dashboard.json) (#225)
- 대시보드 "더보기" 버튼 actions 형식을 배열 형식(`type: "click"`)으로 수정 — onClick 객체 형식에서 navigate 무반응 해결 (admin_dashboard.json) (#225)
### Added
- 대시보드 플러그인/템플릿 상태 카드 추가 — 모듈 카드와 동일 구조, 각 확장 타입별 아이콘 표시 (cube/puzzle-piece/palette) (admin_dashboard.json) (#225)
- 대시보드 확장 카드 "더보기" 버튼 추가 — 각 카드에서 해당 관리 페이지로 이동 (admin_dashboard.json) (#225)
- IconTypes.ts에 Palette 아이콘 추가 — 템플릿 관리 메뉴 아이콘(`fa-palette`) 지원 (IconTypes.ts) (#225)
- 대시보드 확장 상태 카드 레이아웃 렌더링 테스트 추가 (admin-dashboard-extension-status.test.tsx) (#225)
### Changed
- 대시보드 하단 그리드를 2열에서 3열로 변경 — 확장 카드 3개 (모듈/플러그인/템플릿) + 알림 카드 별도 행 (admin_dashboard.json) (#225)
## [0.2.21] - 2026-03-28
### Fixed
- FileUploader 업로드 후 'uploading' 항목 영구 잔류 버그 수정 — `response.data?.data` 이중 접근을 `response?.data`로 수정 (ApiClient가 Axios response.data를 이미 언래핑하므로), attachment null 시 에러 상태 전환 방어 로직 추가 (useFileUploader.ts) (#225)
### Added
- FileUploader 업로드 응답 파싱 테스트 추가 — renderHook 기반 훅 직접 테스트로 정상 파싱 및 null 응답 방어 검증 (FileUploader.test.tsx) (#225)
## [0.2.20] - 2026-03-27
### Added
- SortableMenuList 크로스 depth DnD 지원 — 중첩 SortableContext → flattened tree 방식 리팩토링, 단일 SortableContext로 depth 간 이동 가능
- AdminSidebar 부모 메뉴 클릭/토글 분리 — URL 있는 부모 메뉴 텍스트 클릭 시 네비게이션, chevron 클릭 시 하위 메뉴 토글
### Fixed
- SortableMenuList 드롭 위치 방향 판단 버그 수정 — flat 배열 인덱스 비교로 드래그 방향 판단, 위로 드래그 시 over 앞에 삽입
## [0.2.19] - 2026-03-27
### Changed
- Toast 기본 위치를 top-right → bottom-center로 변경 — 우측 상단 버튼과의 겹침 해소 (#148)
- Toast 숨김 애니메이션 방향을 position에 따라 분기 처리 (bottom → 아래로, top → 위로)
## [0.2.18] - 2026-03-24
### Added
- TabNavigationScroll에 스크롤 컨테이너 지정 기능 추가 — 특정 엘리먼트 내에서 스크롤이 발생하는 레이아웃(예: 게시판 설정 탭)에서 올바른 섹션 감지와 스크롤 이동을 지원
- TabNavigationScroll 스크롤 컨테이너 관련 테스트 추가
### Fixed
- UserProfile.tsx: User 인터페이스에 uuid 필드 누락 수정 (TS2339 빌드 오류)
## [0.2.17] - 2026-03-23
### Changed
- 사용자 목록: DataGrid row.id → row.uuid 참조 전환
- 사용자 상세/수정: UUID 읽기전용 필드 추가, user.id → user.uuid 전환
- UserProfile.tsx: 네비게이션 경로 user.id → user.uuid 전환
- ColumnSelector.tsx: localStorage 키 user.id → user.uuid 전환
- FilterVisibilitySelector.tsx: localStorage 키 user.id → user.uuid 전환
## [0.2.16] - 2026-03-23
### Added
- Hr (수평선) basic 컴포넌트 추가 — HTML `<hr>` 래퍼, className 지원
## [0.2.15] - 2026-03-22
### Added
- Textarea 크기 변형 CSS 클래스 추가 — `textarea-sm` (80px), `textarea-md` (128px), `textarea-lg` (192px)
- safelist에 `min-h` spacing 클래스 추가 — `min-h-10` ~ `min-h-64`
## [0.2.14] - 2026-03-21
### Added
- common.json 다국어 키 추가 — download, downloading, send, sending (ko/en)
## [0.2.13] - 2026-03-20
### Added
- Tfoot 기본 컴포넌트 추가 — HTML `<tfoot>` 래퍼, components.json 등록
- DataGrid footerRow 기능 — `footerCells`, `footerClassName`, `footerCardChildren` props 추가, PC(테이블)/모바일(카드) 합계 행 지원
### Changed
- DataGrid 조건부 렌더링을 엔진에 위임 — 자체 구현 `evaluateCondition` 제거, `condition` 속성은 엔진의 `evaluateRenderCondition`이 네이티브 처리 (engine-v1.21.1)
- DataGrid `mapConditionToIf` 워크어라운드 제거 — 엔진 `condition` 지원으로 불필요
## [0.2.12] - 2026-03-19
### Added
- 상품 리뷰 관리 화면 지원 (이커머스 모듈 연동)
- 리뷰 목록: 상태 배지, 답변 여부 배지, 포토리뷰 이미지 썸네일 표시
- 판매자 답변 등록·수정·삭제 모달
- 리뷰 일괄 상태 변경 및 일괄 삭제
- 이미지 미리보기 모달
### Fixed
- 역할 목록 페이지네이션 경로 수정 — `roles.pagination.total` 등 올바른 응답 경로 사용
- 역할 폼 신규 생성 시 `is_active` Toggle 값이 `false`로 저장되지 않는 버그 수정 — `init_actions`에서 Toggle 초기값 `true` 설정
## [0.2.11] - 2026-03-16
### Added
- CategoryTree 컴포넌트 추가 — 계층형 카테고리 트리 선택/해제 UI
### Fixed
- DataGrid `cellChildren`/`subRowChildren` 내부 액션에서 `setState(target: "local")`이 globalStateUpdater 경로로 실행되어 Form 자동 바인딩의 stale 값에 덮어쓰이는 버그 수정 — `componentContext`를 `renderCellChildren`/`renderSubRowChildren`에 전달하여 컴포넌트 setState 경로 사용
### Changed
- 라이선스 프로그램 명칭 정비
## [0.2.9] - 2026-03-14
### Fixed
- FormField 컴포넌트에 `error` prop 전달 시 자식 Input/Select/Textarea에 적색 테두리가 자동 적용되도록 수정
- `form-field-error` CSS 자손 선택자 추가 — FormField 에러 상태에서 `.input`, `input[type]`, `select`, `textarea` 요소에 `border-red-500` 적용
## [0.2.8] - 2026-03-14
### Fixed
- CodeEditor onChange를 `{ target: { value } }` 패턴으로 수정 — 엔진 isCustomComponentEvent 경로로 정상 처리
- 레이아웃 편집기 CodeEditor onChange에서 `$args[0]` → `$event.target.value` 수정 — 객체가 상태에 저장되는 버그
- 레이아웃 편집기 CodeEditor onChange에 debounce 300ms 추가 — 매 키 입력마다 전역 상태 갱신 방지
## [0.2.7] - 2026-03-14
### Added
- 역할 리스트에서 활성/비활성 상태 직접 토글 기능 (Toggle 컴포넌트, abilities 기반 비활성화)
- 역할 생성 폼에 `identifier` 입력 필드 추가 — 수정 모드에서는 비활성화
- 역할 토글/identifier 관련 다국어 키 추가 (ko/en)
- 역할 리스트 확장 출처 뱃지 개선 — extension_type별 구분 (코어/모듈/플러그인) + 로케일 확장명 표시
### Fixed
- PermissionTree 확장 타입 뱃지가 코어 권한에도 "모듈"로 표시되는 버그 수정 — API의 `extension_type` 필드 직접 활용
## [0.2.6] - 2026-03-13
### Added
- 환경설정 > 고급 디버그 모드 활성화 시 개발 대시보드(`/dev`) 바로가기 버튼 추가
- `dev_dashboard` 다국어 키 추가 (ko/en)
- Admin 푸터 copyright 클릭 → 코어 라이선스 모달, 버전 클릭 → Changelog 모달 기능
- 코어 라이선스/Changelog 모달 partial 추가 (`_modal_license.json`, `_modal_changelog.json`)
- 확장 상세 모달에서 라이선스 클릭 시 전문 모달 표시 (모듈/플러그인/템플릿)
- Pre 기본 컴포넌트 추가
- 라이선스/Changelog 관련 다국어 키 추가 (ko/en)
- TemplateResource에 `license` 필드 추가
- `_admin_base.json`에 버전 동적 바인딩 (`appConfig.version`)
## [0.2.5] - 2026-03-13
### Fixed
- 확장 수동 설치 모달에서 설치 실패 시 상세 에러 사유(`errors.error`) 미표시 → `whitespace-pre-line` P 요소 추가
## [0.2.4] - 2026-03-13
### Added
- 확장 수동 설치 모달 3개(모듈/플러그인/템플릿)에 `contentType: "multipart/form-data"` 적용 — ZIP 파일 업로드 시 FormData 전송
## [0.2.3] - 2026-03-13
### Changed
- 확장 업데이트 모달 changelog source를 동적으로 전환 — `source=bundled` 하드코딩 → `source={{row.update_source ?? 'bundled'}}` (모듈/플러그인/템플릿 4개 레이아웃)
### Fixed
- 코어 업데이트 결과 모달에서 from/to 버전 파라미터가 전달되지 않는 버그 수정 — `params.params` → `params.query`
## [0.2.2] - 2026-03-13
### Changed
- 확장 수동 설치 모달 3개(모듈/플러그인/템플릿) UI 통일 — TabNavigation underline, 에러 배너, 필드별 적색 테두리, download/spinner 아이콘
- 확장 목록 PageHeader에서 새로고침 버튼 제거, 업데이트 확인 버튼으로 통일
### Fixed
- 수동 설치 모달에서 `condition` 속성 사용으로 탭 콘텐츠가 모두 노출되던 문제 수정 — `if` 속성으로 전환
## [0.2.1] - 2026-03-08
### Changed
- 레이아웃 JSON의 `permissions.can_*` / `permissions?.can_*` 바인딩을 `abilities.can_*` / `abilities?.can_*`로 변경 (코어 표준화)
- 모듈/플러그인 상세 모달의 `defined_permissions` 키를 원래 이름 `permissions`로 원복
## [0.2.0] - 2026-03-05
### Changed
- 업데이트 모달 changelog 버전 헤더를 Badge 스타일로 개선 (모듈/플러그인/템플릿 공통)
- 버전 번호와 날짜를 분리 표시하여 중간 버전 시각적 구분 강화
## [0.1.9] - 2026-03-05
### Added
- 코어 메일 템플릿 관리 탭 및 발송 이력 탭 레이아웃
- 게시판/이커머스 메일 템플릿 관리 레이아웃
## [0.1.8] - 2026-03-02
### Changed
- 저작권 연도를 config/app.php SSoT 기반 동적 참조로 전환
- AdminFooter copyright prop 기본값 2025 → 2026 변경
- _admin_base.json copyright prop 동적 바인딩 전환 (`_global.appConfig.releaseYear`)
- components.json copyright default 값 2026으로 갱신
## [0.1.7] - 2026-02-26
### Added
- 확장 Changelog 시스템 구현 (CHANGELOG.md 파싱 및 관리화면 표시)
- 상세 모달에 변경 내역(Changelog) 섹션 추가 (모듈/플러그인/템플릿)
- 업데이트 모달에 인라인 변경사항 표시 추가
- Changelog API 엔드포인트 3개 추가 (modules/plugins/templates)
- 다국어 키 추가 (changelog, update_changelog_title 등)
### Fixed
- 미설치 확장의 변경 내역 미표시 버그 수정 (active → _bundled 폴백)
### Changed
- 업데이트/상세 모달 changelog 카드 간격 개선 (구분선 추가)
## [0.1.6] - 2026-02-26
### Fixed
- 업데이트 모달 '개발자' 필드에 vendor 대신 업데이트 소스가 표시되던 버그 수정
- vendor 행과 update_source 행을 분리하여 2개 행으로 표시
## [0.1.5] - 2026-02-25
### Changed
- 모듈/플러그인 업데이트 뱃지 색상 amber → red로 변경
- 모듈/플러그인 목록에 업데이트 버튼 추가
## [0.1.4] - 2026-02-25
### Fixed
- 확장 업데이트 버전 표시 버그 수정 (latest_version null fallback)
- iteration 컨텍스트 $t: → $t:defer: 수정 (7개 파일)
### Added
- 모듈/플러그인 레이아웃에 version_available 표시 추가
- 다국어 modules.version_available 키 추가
## [0.1.3] - 2026-02-25
### Fixed
- 모듈/플러그인 업데이트 체크 apiCall에 auth_required 누락 수정 (401 오류 해결)
## [0.1.2] - 2026-02-25
### Added
- 모듈 레이아웃 admin/user 분기 등록 기능
- 레이아웃 이름 포맷 통일 (DOT 포맷 지원)
### Changed
- LayoutResolverService 오버라이드 version_constraint 검사 추가
- 고아 오버라이드 레코드 자동 정리
## [0.1.1] - 2026-02-24
### Changed
- 버전 체계 조정 (정식 출시 전 0.x 체계로 변경)
## [0.1.0] - 2026-02-23
### Added
- 관리자 기본 템플릿 초기 구현
- 템플릿 구조 (template.json, routes.json, _base.json)
- 기본 컴포넌트 세트 (Basic 27개, Composite 7개)
- 사이드바 네비게이션: 접기/펼치기, 계층형 메뉴, 활성 상태 표시
- 상단바: 사용자 정보, 알림 벨, 다크 모드 전환 토글
- 대시보드 레이아웃: 시스템 정보, 통계 위젯
- 사용자/역할/권한 관리 화면
- 메뉴 관리 화면 (드래그 앤 드롭 순서 변경)
- 모듈/플러그인/템플릿 관리 화면 (설치/업데이트/상세 모달)
- 환경설정 탭 레이아웃 (사이트 정보, SEO, 메일, 보안)
- 일정 관리 캘린더 화면
- 시스템 정보 화면
- CRUD 화면 표준 레이아웃 (목록/생성/수정/상세)
- 모달 기반 상세 보기/수정 기능
- 토스트 알림 시스템
- 확인 다이얼로그 (삭제 확인 등)
- 에러 페이지 (403, 404, 500, 503)
- 다국어 지원 (ko, en)
- 다크 모드 지원
- 반응형 레이아웃 (데스크톱/태블릿/모바일)
@@ -0,0 +1,47 @@
프로그램 명칭 : 그누보드7용 Admin Basic 템플릿 (sirsoft-admin_basic)
저작자 : (주)에스아이알소프트
----- MIT 라이선스 (한국어 번역) --------------------------------------------------------
MIT 라이선스
Copyright (c) 2026 (주)에스아이알소프트
이 소프트웨어와 관련 문서 파일(이하 "소프트웨어")의 복사본을 취득하는 모든 사람에게
소프트웨어를 제한 없이 사용, 복사, 수정, 병합, 출판, 배포, 서브라이선스 허여 및/또는
판매할 수 있는 권리를 무상으로 부여합니다. 다만, 소프트웨어를 제공받은 사람은 다음
조건을 따라야 합니다:
위 저작권 고지와 본 허가 고지는 소프트웨어의 모든 복사본 또는 상당 부분에 포함되어야
합니다.
소프트웨어는 "있는 그대로" 제공되며, 명시적이든 묵시적이든 어떠한 종류의 보증도 하지
않습니다. 여기에는 상품성, 특정 목적에의 적합성 및 비침해에 대한 보증이 포함되나 이에
국한되지 않습니다. 어떠한 경우에도 저작자 또는 저작권자는 소프트웨어나 소프트웨어의
사용 또는 기타 거래로 인해 발생하는 계약, 불법행위 또는 기타 청구, 손해 또는 기타
책임에 대해 책임을 지지 않습니다.
----- MIT License (English Original) --------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2026 SIRSOFT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,181 @@
/**
* @file AdminSidebar.test.tsx
* @description AdminSidebar 컴포넌트 테스트
*
* 테스트 대상:
* - URL 있는 부모 메뉴: 텍스트 클릭 → 네비게이션, chevron 클릭 → 토글
* - URL 없는 부모 메뉴: 전체 클릭 → 토글 (기존 동작)
* - URL 있는 리프 메뉴: 클릭 → 네비게이션
* - collapsed 모드 동작
*/
import React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { AdminSidebar, MenuItem } from '../../src/components/composite/AdminSidebar';
// G7Core mock
const mockDispatch = vi.fn();
const mockNavigationOnComplete = vi.fn();
beforeEach(() => {
mockNavigationOnComplete.mockImplementation(() => {});
(window as any).G7Core = {
dispatch: mockDispatch,
locale: { current: () => 'ko' },
state: { subscribe: () => () => {} },
t: (key: string) => key,
navigation: { onComplete: mockNavigationOnComplete },
style: { mergeClasses: (...args: string[]) => args.filter(Boolean).join(' ') },
};
});
afterEach(() => {
vi.clearAllMocks();
delete (window as any).G7Core;
});
const createMenu = (): MenuItem[] => [
{
id: 1,
name: { ko: '대시보드', en: 'Dashboard' },
slug: 'dashboard',
url: '/admin/dashboard',
icon: 'fas fa-tachometer-alt',
},
{
id: 2,
name: { ko: '이커머스', en: 'Ecommerce' },
slug: 'ecommerce',
url: '/admin/ecommerce',
icon: 'fas fa-shopping-cart',
children: [
{
id: 21,
name: { ko: '상품 관리', en: 'Products' },
slug: 'products',
url: '/admin/ecommerce/products',
icon: 'fas fa-box',
},
{
id: 22,
name: { ko: '주문 관리', en: 'Orders' },
slug: 'orders',
url: '/admin/ecommerce/orders',
icon: 'fas fa-list',
},
],
},
{
id: 3,
name: { ko: '콘텐츠', en: 'Content' },
slug: 'content',
icon: 'fas fa-file-alt',
children: [
{
id: 31,
name: { ko: '게시판', en: 'Boards' },
slug: 'boards',
url: '/admin/boards',
},
],
},
];
describe('AdminSidebar', () => {
describe('URL 있는 부모 메뉴 (클릭/토글 분리)', () => {
it('텍스트/아이콘 영역 클릭 시 네비게이션이 실행된다', () => {
render(<AdminSidebar menu={createMenu()} currentLocale="ko" />);
// "이커머스" 텍스트를 포함하는 버튼 클릭
const ecommerceLabel = screen.getByText('이커머스');
const navButton = ecommerceLabel.closest('button');
expect(navButton).toBeTruthy();
fireEvent.click(navButton!);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({
handler: 'navigate',
params: { path: '/admin/ecommerce' },
})
);
});
it('chevron 버튼 클릭 시 토글만 발생하고 네비게이션은 발생하지 않는다', () => {
render(<AdminSidebar menu={createMenu()} currentLocale="ko" />);
// chevron 버튼 찾기 (aria-label로 식별)
const ecommerceChevron = screen.getByLabelText('common.expand');
expect(ecommerceChevron).toBeTruthy();
mockDispatch.mockClear();
fireEvent.click(ecommerceChevron);
// navigate가 호출되지 않아야 함
expect(mockDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ handler: 'navigate' })
);
// 자식 메뉴가 표시되어야 함
expect(screen.getByText('상품 관리')).toBeTruthy();
});
});
describe('URL 없는 부모 메뉴 (전체 클릭 = 토글)', () => {
it('전체 영역 클릭 시 하위 메뉴가 토글된다', () => {
render(<AdminSidebar menu={createMenu()} currentLocale="ko" />);
// "콘텐츠" 메뉴 클릭 (URL 없음 → 전체가 토글 버튼)
const contentButton = screen.getByText('콘텐츠').closest('button');
expect(contentButton).toBeTruthy();
fireEvent.click(contentButton!);
// 자식 메뉴가 표시되어야 함
expect(screen.getByText('게시판')).toBeTruthy();
// navigate는 호출되지 않아야 함
expect(mockDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ handler: 'navigate' })
);
});
});
describe('리프 메뉴 (자식 없음 + URL 있음)', () => {
it('클릭 시 네비게이션이 실행된다', () => {
render(<AdminSidebar menu={createMenu()} currentLocale="ko" />);
// 대시보드 클릭
const dashboardButton = screen.getByText('대시보드').closest('button');
expect(dashboardButton).toBeTruthy();
fireEvent.click(dashboardButton!);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({
handler: 'navigate',
params: { path: '/admin/dashboard' },
})
);
});
});
describe('collapsed 모드', () => {
it('collapsed 시 텍스트 라벨이 표시되지 않는다', () => {
render(<AdminSidebar menu={createMenu()} collapsed={true} currentLocale="ko" />);
// 텍스트 라벨이 보이지 않아야 함
expect(screen.queryByText('대시보드')).toBeNull();
expect(screen.queryByText('이커머스')).toBeNull();
});
it('collapsed 시 chevron 버튼이 표시되지 않는다', () => {
render(<AdminSidebar menu={createMenu()} collapsed={true} currentLocale="ko" />);
// chevron 버튼 (aria-label)이 없어야 함
expect(screen.queryByLabelText('common.expand')).toBeNull();
expect(screen.queryByLabelText('common.collapse')).toBeNull();
});
});
});
@@ -0,0 +1,211 @@
/**
* @file DynamicFieldList.test.tsx
* @description DynamicFieldList 아이템 ID 정규화 및 포커스 안정성 테스트
*
* 테스트 대상:
* - itemIdKey가 없는 아이템에 자동 ID 부여
* - onChange 콜백에 ID가 포함된 아이템 전달
* - 값 변경 시 ID 안정성 유지 (리마운트 방지)
*/
import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { DynamicFieldList } from '../../src/components/composite/DynamicFieldList/DynamicFieldList';
import type { DynamicFieldColumn } from '../../src/components/composite/DynamicFieldList/types';
// G7Core 모킹
(window as any).G7Core = {
locale: {
all: () => ['ko', 'en'],
current: () => 'ko',
},
form: null,
};
const basicColumns: DynamicFieldColumn[] = [
{ key: 'name', type: 'input', label: '항목명' },
{ key: 'content', type: 'input', label: '내용' },
];
describe('DynamicFieldList ID 정규화', () => {
it('itemIdKey가 없는 아이템에 자동으로 _id를 부여한다', () => {
const onChange = vi.fn();
const items = [
{ name: '항목1', content: '내용1' },
{ name: '항목2', content: '내용2' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
enableDrag={false}
/>
);
// 항목이 렌더링되는지 확인
const inputs = screen.getAllByRole('textbox');
expect(inputs.length).toBeGreaterThanOrEqual(2);
});
it('이미 _id가 있는 아이템은 변경하지 않는다', () => {
const onChange = vi.fn();
const items = [
{ _id: 'existing_1', name: '항목1', content: '내용1' },
{ _id: 'existing_2', name: '항목2', content: '내용2' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
enableDrag={false}
/>
);
const inputs = screen.getAllByRole('textbox');
expect(inputs.length).toBeGreaterThanOrEqual(2);
});
it('값 변경 시 onChange에 _id가 포함된 아이템이 전달된다', () => {
const onChange = vi.fn();
const items = [
{ name: '항목1', content: '내용1' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
enableDrag={false}
/>
);
// 첫 번째 input에 값 입력
const inputs = screen.getAllByRole('textbox');
fireEvent.change(inputs[0], { target: { value: '수정됨' } });
// onChange가 호출되었는지 확인
expect(onChange).toHaveBeenCalled();
// 전달된 아이템에 _id가 포함되어 있는지 확인
const updatedItems = onChange.mock.calls[0][0];
expect(updatedItems[0]).toHaveProperty('_id');
expect(typeof updatedItems[0]._id).toBe('string');
expect(updatedItems[0]._id.length).toBeGreaterThan(0);
});
it('값 변경 전후로 _id가 동일하게 유지된다', () => {
const onChange = vi.fn();
const items = [
{ _id: 'stable_id_1', name: '항목1', content: '내용1' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
enableDrag={false}
/>
);
const inputs = screen.getAllByRole('textbox');
fireEvent.change(inputs[0], { target: { value: '수정됨' } });
expect(onChange).toHaveBeenCalled();
const updatedItems = onChange.mock.calls[0][0];
expect(updatedItems[0]._id).toBe('stable_id_1');
});
it('커스텀 itemIdKey를 사용할 때도 정규화가 동작한다', () => {
const onChange = vi.fn();
const items = [
{ name: '항목1', content: '내용1' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
itemIdKey="key"
enableDrag={false}
/>
);
const inputs = screen.getAllByRole('textbox');
fireEvent.change(inputs[0], { target: { value: '수정됨' } });
expect(onChange).toHaveBeenCalled();
const updatedItems = onChange.mock.calls[0][0];
// itemIdKey가 'key'이므로 key 필드에 ID가 부여됨
expect(updatedItems[0]).toHaveProperty('key');
expect(typeof updatedItems[0].key).toBe('string');
});
it('항목 추가 시 새 아이템에 _id가 부여된다', () => {
const onChange = vi.fn();
const items = [
{ _id: 'existing_1', name: '항목1', content: '내용1' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
enableDrag={false}
addLabel="항목 추가"
/>
);
// 추가 버튼 클릭
const addButton = screen.getByText('항목 추가');
fireEvent.click(addButton);
expect(onChange).toHaveBeenCalled();
const updatedItems = onChange.mock.calls[0][0];
expect(updatedItems).toHaveLength(2);
// 기존 아이템 ID 유지
expect(updatedItems[0]._id).toBe('existing_1');
// 새 아이템에 ID 부여
expect(updatedItems[1]).toHaveProperty('_id');
expect(typeof updatedItems[1]._id).toBe('string');
});
it('항목 삭제 시 나머지 아이템의 _id가 유지된다', () => {
const onChange = vi.fn();
const items = [
{ _id: 'id_1', name: '항목1', content: '내용1' },
{ _id: 'id_2', name: '항목2', content: '내용2' },
{ _id: 'id_3', name: '항목3', content: '내용3' },
];
render(
<DynamicFieldList
items={items}
columns={basicColumns}
onChange={onChange}
enableDrag={false}
minItems={0}
/>
);
// 삭제 버튼 클릭 (첫 번째 항목)
const removeButtons = screen.getAllByTitle(/삭제|제거|remove/i);
if (removeButtons.length > 0) {
fireEvent.click(removeButtons[0]);
expect(onChange).toHaveBeenCalled();
const updatedItems = onChange.mock.calls[0][0];
expect(updatedItems).toHaveLength(2);
expect(updatedItems[0]._id).toBe('id_2');
expect(updatedItems[1]._id).toBe('id_3');
}
});
});
@@ -0,0 +1,354 @@
/**
* @file SortableMenuList.test.tsx
* @description SortableMenuList 헬퍼 함수 테스트 — flattened tree + 크로스 depth 이동 + 순환 참조 방지
*
* 테스트 대상:
* - flattenTree: 트리 → 평탄 배열 변환 (확장 상태 반영)
* - removeItemFromTree: 트리에서 아이템 제거
* - insertItemIntoParent: 특정 부모 아래 index 기반 삽입
* - reorderInParent: 같은 부모 내 순서 변경
* - collectDescendantIds: 자손 ID 수집 (순환 참조 방지)
* - generateOrderData: 트리 → API 전송용 order 데이터
* - MenuOrderData 인터페이스 (moved_items optional)
*/
import { describe, it, expect } from 'vitest';
import {
MenuItem,
MenuOrderData,
flattenTree,
findItemById,
collectDescendantIds,
removeItemFromTree,
insertItemIntoParent,
reorderInParent,
generateOrderData,
} from '../../src/components/composite/SortableMenuList';
// 테스트용 메뉴 데이터 생성 헬퍼
function createMenuItem(overrides: Partial<MenuItem> & { id: number }): MenuItem {
return {
name: `Menu ${overrides.id}`,
slug: `menu-${overrides.id}`,
url: `/menu-${overrides.id}`,
icon: 'fas fa-folder',
order: 1,
is_active: true,
parent_id: null,
module_id: null,
children: [],
...overrides,
};
}
// 공통 샘플 트리
const sampleTree: MenuItem[] = [
createMenuItem({
id: 1,
children: [
createMenuItem({ id: 11, parent_id: 1 }),
createMenuItem({ id: 12, parent_id: 1 }),
],
}),
createMenuItem({
id: 2,
children: [
createMenuItem({ id: 21, parent_id: 2 }),
],
}),
createMenuItem({ id: 3 }),
];
describe('SortableMenuList 헬퍼 함수', () => {
describe('flattenTree', () => {
it('확장 없이 최상위만 반환한다', () => {
const result = flattenTree(sampleTree, new Set());
expect(result).toHaveLength(3);
expect(result.map((f) => f.item.id)).toEqual([1, 2, 3]);
expect(result.every((f) => f.depth === 0)).toBe(true);
});
it('확장된 노드의 자식을 포함한다', () => {
const result = flattenTree(sampleTree, new Set([1]));
expect(result).toHaveLength(5);
expect(result.map((f) => f.item.id)).toEqual([1, 11, 12, 2, 3]);
expect(result[1].depth).toBe(1);
expect(result[1].parentId).toBe(1);
});
it('모든 노드 확장 시 전체 트리를 반환한다', () => {
const result = flattenTree(sampleTree, new Set([1, 2]));
expect(result).toHaveLength(6);
expect(result.map((f) => f.item.id)).toEqual([1, 11, 12, 2, 21, 3]);
});
it('3단계 트리를 올바르게 평탄화한다', () => {
const deepTree: MenuItem[] = [
createMenuItem({
id: 1,
children: [
createMenuItem({
id: 11,
parent_id: 1,
children: [
createMenuItem({ id: 111, parent_id: 11 }),
],
}),
],
}),
];
const result = flattenTree(deepTree, new Set([1, 11]));
expect(result).toHaveLength(3);
expect(result[2].depth).toBe(2);
expect(result[2].parentId).toBe(11);
});
});
describe('findItemById', () => {
it('최상위 아이템을 찾는다', () => {
const found = findItemById(sampleTree, 2);
expect(found).toBeTruthy();
expect(found!.id).toBe(2);
});
it('자식 아이템을 찾는다', () => {
const found = findItemById(sampleTree, 21);
expect(found).toBeTruthy();
expect(found!.id).toBe(21);
});
it('존재하지 않는 ID는 null을 반환한다', () => {
expect(findItemById(sampleTree, 999)).toBeNull();
});
});
describe('removeItemFromTree', () => {
it('최상위 아이템을 제거한다', () => {
const result = removeItemFromTree(sampleTree, 3);
expect(result).toHaveLength(2);
expect(result.find((i) => i.id === 3)).toBeUndefined();
});
it('자식 아이템을 제거한다', () => {
const result = removeItemFromTree(sampleTree, 12);
const parent = result.find((i) => i.id === 1)!;
expect(parent.children).toHaveLength(1);
expect(parent.children[0].id).toBe(11);
});
});
describe('insertItemIntoParent', () => {
it('최상위에 아이템을 삽입한다 (index 기반)', () => {
const newItem = createMenuItem({ id: 99 });
const result = insertItemIntoParent(sampleTree, newItem, null, 1);
expect(result).toHaveLength(4);
expect(result[1].id).toBe(99);
});
it('자식 레벨에 아이템을 삽입한다', () => {
const newItem = createMenuItem({ id: 99, parent_id: 1 });
const result = insertItemIntoParent(sampleTree, newItem, 1, 1);
const parent = result.find((i) => i.id === 1)!;
expect(parent.children).toHaveLength(3);
expect(parent.children[1].id).toBe(99);
});
it('끝에 삽입한다 (index = children.length)', () => {
const newItem = createMenuItem({ id: 99, parent_id: 2 });
const result = insertItemIntoParent(sampleTree, newItem, 2, 1);
const parent = result.find((i) => i.id === 2)!;
expect(parent.children).toHaveLength(2);
expect(parent.children[1].id).toBe(99);
});
});
describe('reorderInParent', () => {
it('최상위에서 순서를 변경한다', () => {
const result = reorderInParent(sampleTree, null, 3, 1);
expect(result[0].id).toBe(3);
expect(result[1].id).toBe(1);
expect(result[2].id).toBe(2);
});
it('자식 레벨에서 순서를 변경한다', () => {
const result = reorderInParent(sampleTree, 1, 12, 11);
const parent = result.find((i) => i.id === 1)!;
expect(parent.children[0].id).toBe(12);
expect(parent.children[1].id).toBe(11);
});
});
describe('collectDescendantIds', () => {
it('직계 자식 ID를 수집한다', () => {
const item = sampleTree[0]; // id: 1, children: [11, 12]
const ids = collectDescendantIds(item);
expect(ids).toContain(11);
expect(ids).toContain(12);
});
it('3단계 자손까지 수집한다', () => {
const deepTree = createMenuItem({
id: 1,
children: [
createMenuItem({
id: 11,
parent_id: 1,
children: [
createMenuItem({ id: 111, parent_id: 11 }),
],
}),
],
});
const ids = collectDescendantIds(deepTree);
expect(ids).toEqual([11, 111]);
});
it('자식이 없으면 빈 배열을 반환한다', () => {
const item = createMenuItem({ id: 3 });
expect(collectDescendantIds(item)).toEqual([]);
});
});
describe('순환 참조 방지', () => {
it('부모를 자식 아래로 이동 시 자손 ID에 포함되어 차단', () => {
const parent = sampleTree[0]; // id: 1, children: [11, 12]
const descendantIds = collectDescendantIds(parent);
expect(descendantIds.includes(11)).toBe(true);
});
it('같은 depth 형제로 이동은 허용 (자손이 아님)', () => {
const item2 = sampleTree[1]; // id: 2
const descendantIds = collectDescendantIds(item2);
expect(descendantIds.includes(3)).toBe(false);
});
});
describe('generateOrderData', () => {
it('parent_menus와 child_menus를 올바르게 생성한다', () => {
const orderData = generateOrderData(sampleTree);
expect(orderData.parent_menus).toEqual([
{ id: 1, order: 1 },
{ id: 2, order: 2 },
{ id: 3, order: 3 },
]);
expect(orderData.child_menus[1]).toEqual([
{ id: 11, order: 1 },
{ id: 12, order: 2 },
]);
expect(orderData.child_menus[2]).toEqual([
{ id: 21, order: 1 },
]);
});
it('자식이 없는 최상위 메뉴는 child_menus에 포함되지 않는다', () => {
const orderData = generateOrderData(sampleTree);
expect(orderData.child_menus[3]).toBeUndefined();
});
it('3단계 자식도 child_menus에 포함된다 (재귀)', () => {
const deepTree: MenuItem[] = [
createMenuItem({
id: 1,
children: [
createMenuItem({
id: 11,
parent_id: 1,
children: [
createMenuItem({ id: 111, parent_id: 11 }),
createMenuItem({ id: 112, parent_id: 11 }),
],
}),
],
}),
];
const orderData = generateOrderData(deepTree);
expect(orderData.child_menus[11]).toEqual([
{ id: 111, order: 1 },
{ id: 112, order: 2 },
]);
});
});
describe('크로스 depth 이동 시나리오', () => {
it('자식→최상위 이동 (아래→위 드래그): over 앞에 삽입', () => {
// 시나리오: id:11 (parent:1의 자식) → 최상위 id:2 앞으로 이동
// flat 배열: [1(idx0), 11(idx1), 12(idx2), 2(idx3), 3(idx4)] (모두 확장)
// active(11) flatIdx=1, over(2) flatIdx=3 → activeIdx < overIdx → 아래로 드래그 → over 뒤 삽입
const activeItem = sampleTree[0].children[0]; // id: 11, parent_id: 1
let newItems = removeItemFromTree(sampleTree, activeItem.id);
// 아래로 드래그 (activeIdx < overIdx) → over 뒤에 삽입
const overIndex = newItems.findIndex((i) => i.id === 2);
const movedItem = { ...activeItem, parent_id: null };
newItems = insertItemIntoParent(newItems, movedItem, null, overIndex + 1);
const orderData = generateOrderData(newItems);
orderData.moved_items = [{ id: activeItem.id, new_parent_id: null }];
expect(newItems.map((i) => i.id)).toEqual([1, 2, 11, 3]);
const parent1 = newItems.find((i) => i.id === 1)!;
expect(parent1.children.map((c) => c.id)).toEqual([12]);
expect(orderData.moved_items).toEqual([{ id: 11, new_parent_id: null }]);
});
it('자식→최상위 이동 (위로 드래그): over 앞에 삽입', () => {
// 시나리오: id:21 (parent:2의 자식) → 최상위 id:2 앞으로 이동
// flat 배열: [1(idx0), 2(idx1), 21(idx2), 3(idx3)] (id:2만 확장)
// active(21) flatIdx=2, over(2) flatIdx=1 → activeIdx > overIdx → 위로 드래그 → over 앞 삽입
const activeItem = sampleTree[1].children[0]; // id: 21, parent_id: 2
let newItems = removeItemFromTree(sampleTree, activeItem.id);
// 위로 드래그 (activeIdx > overIdx) → over 앞에 삽입 (insertIndex += 0)
const overIndex = newItems.findIndex((i) => i.id === 2);
const movedItem = { ...activeItem, parent_id: null };
newItems = insertItemIntoParent(newItems, movedItem, null, overIndex);
expect(newItems.map((i) => i.id)).toEqual([1, 21, 2, 3]);
const parent2 = newItems.find((i) => i.id === 2)!;
expect(parent2.children).toHaveLength(0);
});
it('최상위→자식 이동: remove + insert + moved_items 생성', () => {
const activeItem = sampleTree[2]; // id: 3, parent_id: null
let newItems = removeItemFromTree(sampleTree, activeItem.id);
// over(id:21)의 위치: parent(2).children에서 index 0 → 뒤에 삽입 = index 1
const overParent = findItemById(newItems, 2)!;
const overIndex = overParent.children.findIndex((c) => c.id === 21);
const movedItem = { ...activeItem, parent_id: 2 };
newItems = insertItemIntoParent(newItems, movedItem, 2, overIndex + 1);
const orderData = generateOrderData(newItems);
orderData.moved_items = [{ id: activeItem.id, new_parent_id: 2 }];
expect(newItems.map((i) => i.id)).toEqual([1, 2]);
const parent2 = newItems.find((i) => i.id === 2)!;
expect(parent2.children.map((c) => c.id)).toEqual([21, 3]);
expect(orderData.moved_items).toEqual([{ id: 3, new_parent_id: 2 }]);
});
});
describe('MenuOrderData 인터페이스', () => {
it('moved_items는 optional이다', () => {
const data: MenuOrderData = {
parent_menus: [{ id: 1, order: 1 }],
child_menus: {},
};
expect(data.moved_items).toBeUndefined();
});
it('moved_items를 포함할 수 있다', () => {
const data: MenuOrderData = {
parent_menus: [{ id: 1, order: 1 }],
child_menus: {},
moved_items: [{ id: 5, new_parent_id: null }],
};
expect(data.moved_items).toHaveLength(1);
expect(data.moved_items![0].new_parent_id).toBeNull();
});
});
});
@@ -0,0 +1,536 @@
/**
* @file admin-activity-log-list.test.tsx
* @description 활동 로그 목록 레이아웃 렌더링 테스트
*
* 테스트 대상:
* - 데이터 로드 시 DataGrid에 로그 항목 렌더링
* - 빈 데이터 시 빈 상태 표시
* - 필터 UI 렌더링 (검색, 로그 타입 체크박스, 날짜)
* - 페이지네이션 렌더링
* - abilities 기반 삭제 버튼 제어
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h1 className={className}>{children || text}</h1>
);
const TestButton: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
type?: string;
disabled?: boolean | string;
'data-testid'?: string;
}> = ({ className, children, text, type, disabled, 'data-testid': testId }) => (
<button className={className} type={type as any} disabled={!!disabled} data-testid={testId}>{children || text}</button>
);
const TestInput: React.FC<{
className?: string;
type?: string;
name?: string;
value?: string;
placeholder?: string;
'data-testid'?: string;
}> = ({ className, type, name, value, placeholder, 'data-testid': testId }) => (
<input className={className} type={type} name={name} defaultValue={value} placeholder={placeholder} data-testid={testId || `input-${name}`} />
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={className} data-icon={name} data-testid={`icon-${name}`} />
);
const TestSelect: React.FC<{
name?: string;
className?: string;
value?: string;
options?: Array<{ value: string; label: string }>;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ name, className, value, options, children, 'data-testid': testId }) => (
<select className={className} name={name} defaultValue={value} data-testid={testId || `select-${name}`}>
{(options ?? []).map(opt => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
{children}
</select>
);
const TestCheckbox: React.FC<{
name?: string;
label?: string;
value?: string;
checked?: boolean | string;
className?: string;
}> = ({ name, label, value, checked, className }) => (
<label className={className} data-testid={`checkbox-${name}`}>
<input type="checkbox" name={name} value={value} defaultChecked={!!checked} />
{label}
</label>
);
const TestDataGrid: React.FC<{
data?: any[];
columns?: any[];
loading?: boolean | string;
selectable?: boolean | string;
expandable?: boolean;
pagination?: boolean;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ data, columns, loading, selectable, expandable, pagination, children, 'data-testid': testId }) => (
<div data-testid={testId || 'datagrid'} data-loading={String(!!loading)} data-selectable={String(!!selectable)}>
{(data ?? []).map((item, i) => (
<div key={item.id || i} data-testid="datagrid-row">
{(columns ?? []).map((col: any) => (
<span key={col.field} data-testid={`cell-${col.field}`}>
{item[col.field]}
</span>
))}
</div>
))}
{(!data || data.length === 0) && <div data-testid="datagrid-empty">No data</div>}
{children}
</div>
);
const TestModal: React.FC<{
id?: string;
title?: string;
size?: string;
children?: React.ReactNode;
}> = ({ id, title, size, children }) => (
<div data-testid={`modal-${id}`} data-title={title}>{children}</div>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Select: { component: TestSelect, metadata: { name: 'Select', type: 'composite' } },
Checkbox: { component: TestCheckbox, metadata: { name: 'Checkbox', type: 'composite' } },
DataGrid: { component: TestDataGrid, metadata: { name: 'DataGrid', type: 'composite' } },
Modal: { component: TestModal, metadata: { name: 'Modal', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 활동 로그 목록 레이아웃 (단순화 — 핵심 구조만)
function createActivityLogListLayout() {
return {
data_sources: [
{
id: 'activityLogs',
type: 'api',
endpoint: '/api/admin/activity-logs',
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
params: {
page: '{{query.page || 1}}',
per_page: '{{query.per_page || 20}}',
},
},
],
components: [
{
id: 'page_header',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'page-header' },
children: [
{
type: 'basic',
name: 'H1',
text: '활동 로그',
props: { 'data-testid': 'page-title' },
},
],
},
{
id: 'filter_section',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'filter-section' },
children: [
{
type: 'composite',
name: 'Select',
props: {
name: 'searchType',
'data-testid': 'select-searchType',
options: [
{ value: 'all', label: '전체' },
{ value: 'action', label: '액션' },
{ value: 'description', label: '설명' },
{ value: 'ip_address', label: 'IP주소' },
],
},
},
{
type: 'basic',
name: 'Input',
props: {
type: 'text',
name: 'search',
placeholder: '검색어를 입력하세요...',
'data-testid': 'search-input',
},
},
{
type: 'composite',
name: 'Select',
props: {
name: 'createdBy',
'data-testid': 'actor-searchable-dropdown',
options: [],
},
},
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'date-preset-buttons' },
children: [
{ type: 'basic', name: 'Button', text: '오늘', props: { type: 'button', 'data-testid': 'preset-today' } },
{ type: 'basic', name: 'Button', text: '1주일', props: { type: 'button', 'data-testid': 'preset-week' } },
{ type: 'basic', name: 'Button', text: '1개월', props: { type: 'button', 'data-testid': 'preset-month' } },
{ type: 'basic', name: 'Button', text: '3개월', props: { type: 'button', 'data-testid': 'preset-3months' } },
{ type: 'basic', name: 'Button', text: '6개월', props: { type: 'button', 'data-testid': 'preset-6months' } },
{ type: 'basic', name: 'Button', text: '1년', props: { type: 'button', 'data-testid': 'preset-1year' } },
],
},
{
type: 'basic',
name: 'Input',
props: {
type: 'datetime-local',
name: 'dateFrom',
step: '1',
'data-testid': 'date-from',
},
},
{
type: 'basic',
name: 'Input',
props: {
type: 'datetime-local',
name: 'dateTo',
step: '1',
'data-testid': 'date-to',
},
},
{
type: 'basic',
name: 'Button',
text: '검색',
props: { 'data-testid': 'search-button' },
},
{
type: 'basic',
name: 'Button',
text: '초기화',
props: { 'data-testid': 'reset-button' },
},
],
},
{
id: 'activity_log_datagrid',
type: 'composite',
name: 'DataGrid',
props: {
data: '{{activityLogs?.data?.data}}',
pagination: true,
serverSidePagination: true,
selectable: true,
loading: '{{activityLogs?.loading}}',
expandable: true,
expandConditionField: 'has_changes',
'data-testid': 'activity-log-datagrid',
columns: [
{ field: 'number', header: '#' },
{ field: 'log_type_label', header: '타입' },
{ field: 'action_label', header: '액션' },
{ field: 'localized_description', header: '설명' },
{ field: 'loggable_type_display', header: '대상' },
{ field: 'actor_name', header: '행위자' },
{ field: 'ip_address', header: 'IP 주소' },
{ field: 'created_at', header: '일시' },
],
},
},
{
id: 'bulk_delete_button',
type: 'basic',
name: 'Button',
props: {
'data-testid': 'bulk-delete-button',
disabled: '{{activityLogs?.data?.abilities?.can_delete !== true}}',
},
text: '선택 삭제',
},
],
};
}
describe('활동 로그 목록 - 필터 UI 렌더링', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(() => {
const registry = setupTestRegistry();
const layout = createActivityLogListLayout();
testUtils = createLayoutTest(layout, { componentRegistry: registry });
});
afterEach(() => {
testUtils.cleanup();
});
it('검색 타입 드롭다운, 검색 입력, 행위자, 날짜 필터가 렌더링됨', async () => {
testUtils.mockApi('activityLogs', {
response: { data: { data: [], pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0 } } },
});
await testUtils.render();
const filterSection = screen.queryByTestId('filter-section');
expect(filterSection).not.toBeNull();
// 검색 타입 드롭다운
const searchTypeSelect = screen.queryByTestId('select-searchType');
expect(searchTypeSelect).not.toBeNull();
const searchInput = screen.queryByTestId('search-input');
expect(searchInput).not.toBeNull();
// 행위자 검색 드롭다운
const actorDropdown = screen.queryByTestId('actor-searchable-dropdown');
expect(actorDropdown).not.toBeNull();
// 날짜 프리셋 버튼
const presetButtons = screen.queryByTestId('date-preset-buttons');
expect(presetButtons).not.toBeNull();
expect(screen.queryByTestId('preset-today')).not.toBeNull();
expect(screen.queryByTestId('preset-week')).not.toBeNull();
expect(screen.queryByTestId('preset-month')).not.toBeNull();
// 날짜 필터 (datetime-local)
const dateFrom = screen.queryByTestId('date-from');
expect(dateFrom).not.toBeNull();
expect(dateFrom?.getAttribute('type')).toBe('datetime-local');
const dateTo = screen.queryByTestId('date-to');
expect(dateTo).not.toBeNull();
expect(dateTo?.getAttribute('type')).toBe('datetime-local');
// 버튼
const searchButton = screen.queryByTestId('search-button');
expect(searchButton).not.toBeNull();
const resetButton = screen.queryByTestId('reset-button');
expect(resetButton).not.toBeNull();
});
});
describe('활동 로그 목록 - DataGrid 렌더링', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(() => {
const registry = setupTestRegistry();
const layout = createActivityLogListLayout();
testUtils = createLayoutTest(layout, { componentRegistry: registry });
});
afterEach(() => {
testUtils.cleanup();
});
it('데이터 로드 시 DataGrid에 로그 항목 렌더링됨', async () => {
// mockApi response는 데이터소스에 직접 저장됨
// 레이아웃에서 activityLogs?.data?.data로 접근하므로 response.data 안에 중첩 필요
testUtils.mockApi('activityLogs', {
response: {
data: {
data: [
{
id: 1,
number: 2,
log_type: 'admin',
log_type_label: '관리자',
action: 'user.update',
action_label: '수정',
localized_description: '사용자 정보를 수정했습니다',
loggable_type_display: 'User',
actor_name: '홍길동',
created_at: '2026-03-28 14:30:00',
},
{
id: 2,
number: 1,
log_type: 'user',
log_type_label: '사용자',
action: 'auth.login',
action_label: '로그인',
localized_description: '로그인했습니다',
loggable_type_display: null,
actor_name: '김철수',
created_at: '2026-03-28 14:00:00',
},
],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 2 },
abilities: { can_delete: false },
},
},
});
await testUtils.render();
const rows = screen.queryAllByTestId('datagrid-row');
expect(rows.length).toBe(2);
});
it('빈 데이터 시 빈 상태 표시', async () => {
testUtils.mockApi('activityLogs', {
response: {
data: {
data: [],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0 },
abilities: { can_delete: false },
},
},
});
await testUtils.render();
const rows = screen.queryAllByTestId('datagrid-row');
expect(rows.length).toBe(0);
const emptyState = screen.queryByTestId('datagrid-empty');
expect(emptyState).not.toBeNull();
});
it('삭제 권한 있을 때 일괄 삭제 버튼 활성화', async () => {
testUtils.mockApi('activityLogs', {
response: {
data: {
data: [
{
id: 1,
number: 1,
log_type: 'admin',
log_type_label: '관리자',
action_label: '수정',
localized_description: '테스트',
actor_name: '관리자',
created_at: '2026-03-28',
},
],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 1 },
abilities: { can_delete: true },
},
},
});
await testUtils.render();
const bulkDeleteButton = screen.queryByTestId('bulk-delete-button');
expect(bulkDeleteButton).not.toBeNull();
});
it('삭제 권한 없을 때 일괄 삭제 버튼 비활성화', async () => {
testUtils.mockApi('activityLogs', {
response: {
data: {
data: [
{
id: 1,
number: 1,
log_type: 'admin',
log_type_label: '관리자',
action_label: '수정',
localized_description: '테스트',
actor_name: '관리자',
created_at: '2026-03-28',
},
],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 1 },
abilities: { can_delete: false },
},
},
});
await testUtils.render();
const bulkDeleteButton = screen.queryByTestId('bulk-delete-button');
expect(bulkDeleteButton).not.toBeNull();
expect(bulkDeleteButton?.getAttribute('disabled')).not.toBeNull();
});
it('DataGrid에 selectable이 항상 활성화됨', async () => {
testUtils.mockApi('activityLogs', {
response: {
data: {
data: [],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0 },
abilities: { can_delete: false },
},
},
});
await testUtils.render();
const datagrid = screen.queryByTestId('activity-log-datagrid');
expect(datagrid).not.toBeNull();
// selectable이 항상 true로 설정됨 (권한과 무관하게 체크박스 표시)
expect(datagrid?.getAttribute('data-selectable')).toBe('true');
});
});
@@ -0,0 +1,275 @@
/**
* @file admin-dashboard-activity-log.test.tsx
* @description 대시보드 활동 로그 관련 렌더링 테스트
*
* 테스트 대상:
* - 시스템 알림 카드가 if="false"로 숨김 처리됨
* - 최근 활동 카드가 ActivityLog 데이터로 렌더링됨
* - 활동 항목에 title, description, time 표시
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestH2: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h2 className={className}>{children || text}</h2>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={className} data-icon={name} data-testid={`icon-${name}`} />
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
H2: { component: TestH2, metadata: { name: 'H2', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 시스템 알림 카드 레이아웃 (if="false"로 숨김)
function createSystemAlertsLayout() {
return {
data_sources: [
{
id: 'dashboard_alerts',
type: 'api',
endpoint: '/api/admin/dashboard/alerts',
method: 'GET',
auto_fetch: false,
auth_required: true,
loading_strategy: 'background',
fallback: { data: [] },
},
],
components: [
{
id: 'system_alerts_card',
if: 'false',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'system-alerts-card' },
children: [
{
id: 'alerts_title',
type: 'basic',
name: 'H2',
text: '시스템 알림',
},
],
},
],
};
}
// 최근 활동 카드 레이아웃
function createRecentActivityLayout() {
return {
data_sources: [
{
id: 'dashboard_activities',
type: 'api',
endpoint: '/api/admin/dashboard/activities',
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
fallback: { data: [] },
},
],
components: [
{
id: 'recent_activity_card',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'recent-activity-card' },
children: [
{
id: 'recent_activity_title',
type: 'basic',
name: 'H2',
text: '최근 활동',
props: { 'data-testid': 'activity-title' },
},
{
id: 'activity_list',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'activity-list' },
children: [
{
id: 'activity_item',
type: 'basic',
name: 'Div',
props: { 'data-testid': 'activity-item' },
iteration: {
source: 'dashboard_activities?.data',
item_var: 'activity',
},
children: [
{
id: 'activity_item_title',
type: 'basic',
name: 'Span',
text: '{{activity.title}}',
},
{
id: 'activity_item_desc',
type: 'basic',
name: 'Span',
text: '{{activity.description}}',
},
{
id: 'activity_item_time',
type: 'basic',
name: 'Span',
text: '{{activity.time}}',
},
],
},
],
},
],
},
],
};
}
describe('대시보드 - 시스템 알림 카드 숨김', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(() => {
const registry = setupTestRegistry();
const layout = createSystemAlertsLayout();
testUtils = createLayoutTest(layout, { componentRegistry: registry });
});
afterEach(() => {
testUtils.cleanup();
});
it('시스템 알림 카드가 if="false"로 숨김 처리되어 렌더링되지 않음', async () => {
await testUtils.render();
const alertsCard = screen.queryByTestId('system-alerts-card');
expect(alertsCard).toBeNull();
});
});
describe('대시보드 - 최근 활동 카드', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(() => {
const registry = setupTestRegistry();
const layout = createRecentActivityLayout();
testUtils = createLayoutTest(layout, { componentRegistry: registry });
});
afterEach(() => {
testUtils.cleanup();
});
it('최근 활동 카드가 렌더링됨', async () => {
testUtils.mockApi('dashboard_activities', {
response: {
data: [],
},
});
await testUtils.render();
const activityCard = screen.queryByTestId('recent-activity-card');
expect(activityCard).not.toBeNull();
});
it('ActivityLog 데이터가 활동 항목으로 렌더링됨', async () => {
testUtils.mockApi('dashboard_activities', {
response: {
data: [
{
type: 'admin',
icon: 'pen-to-square',
icon_color: 'blue',
title: '사용자 정보를 수정했습니다',
description: '홍길동',
time: '10분 전',
timestamp: '2026-03-28 14:30:00',
},
{
type: 'user',
icon: 'right-to-bracket',
icon_color: 'green',
title: '로그인했습니다',
description: '김철수',
time: '30분 전',
timestamp: '2026-03-28 14:00:00',
},
],
},
});
await testUtils.render();
const items = screen.queryAllByTestId('activity-item');
expect(items.length).toBe(2);
});
it('활동 데이터 없을 때 빈 상태 표시', async () => {
testUtils.mockApi('dashboard_activities', {
response: {
data: [],
},
});
await testUtils.render();
const items = screen.queryAllByTestId('activity-item');
expect(items.length).toBe(0);
});
});
@@ -0,0 +1,448 @@
/**
* @file admin-dashboard-extension-status.test.tsx
* @description 대시보드 확장 상태 카드 렌더링 테스트
*
* 테스트 대상:
* - 모듈 상태 카드: status === 'active' 기반 활성/비활성 배지 표시
* - 플러그인 상태 카드: 동일 패턴
* - 템플릿 상태 카드: 동일 패턴
* - 각 카드 헤더에 아이콘 및 "더보기" 버튼 존재
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
className?: string;
disabled?: boolean;
type?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
onClick?: () => void;
}> = ({ className, disabled, type, children, text, 'data-testid': testId, onClick }) => (
<button className={className} disabled={disabled} type={type as any} data-testid={testId} onClick={onClick}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestH2: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h2 className={className}>{children || text}</h2>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={className} data-icon={name} data-testid={`icon-${name}`} />
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
H2: { component: TestH2, metadata: { name: 'H2', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 모듈 상태 카드만 추출한 레이아웃
function createExtensionCardLayout(
cardId: string,
dataSourceId: string,
endpoint: string,
iconName: string,
itemVar: string,
titleKey: string,
subtitleKey: string,
activeKey: string,
inactiveKey: string,
morePath: string,
permission: string
) {
return {
data_sources: [
{
id: dataSourceId,
type: 'api',
endpoint,
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
params: { per_page: '5' },
fallback: {
data: { data: [], current_page: 1, last_page: 1, per_page: 5, total: 0 },
},
},
],
components: [
{
id: cardId,
permissions: [permission],
type: 'basic',
name: 'Div',
children: [
{
id: `${cardId}_header`,
type: 'basic',
name: 'Div',
props: { className: 'flex items-center justify-between mb-4' },
children: [
{
id: `${cardId}_header_left`,
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2' },
children: [
{
id: `${cardId}_header_icon`,
type: 'basic',
name: 'Icon',
props: { name: iconName },
},
{
id: `${cardId}_header_text`,
type: 'basic',
name: 'Div',
children: [
{
id: `${cardId}_title`,
type: 'basic',
name: 'H2',
text: titleKey,
},
{
id: `${cardId}_subtitle`,
type: 'basic',
name: 'P',
text: subtitleKey,
},
],
},
],
},
{
id: `${cardId}_more_btn`,
type: 'basic',
name: 'Button',
props: { type: 'button' },
text: '더보기',
actions: {
onClick: [{ handler: 'navigate', params: { path: morePath } }],
},
},
],
},
{
id: `${cardId}_list`,
type: 'basic',
name: 'Div',
children: [
{
id: `${cardId}_item`,
type: 'basic',
name: 'Div',
props: { className: 'flex items-center justify-between py-2' },
iteration: {
source: `${dataSourceId}?.data?.data`,
item_var: itemVar,
},
children: [
{
id: `${cardId}_info`,
type: 'basic',
name: 'Div',
children: [
{
id: `${cardId}_name`,
type: 'basic',
name: 'P',
text: `{{${itemVar}.name}}`,
},
{
id: `${cardId}_version`,
type: 'basic',
name: 'P',
text: `v{{${itemVar}.version}}`,
},
],
},
{
id: `${cardId}_badge`,
type: 'basic',
name: 'Span',
props: {
className: `{{${itemVar}.status === 'active' ? 'badge-active' : 'badge-inactive'}}`,
},
text: `{{${itemVar}.status === 'active' ? '${activeKey}' : '${inactiveKey}'}}`,
},
],
},
],
},
],
},
],
};
}
describe('대시보드 확장 상태 카드', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('모듈 상태 카드', () => {
const layout = createExtensionCardLayout(
'module_status_card',
'dashboard_modules',
'/api/admin/modules/installed',
'cube',
'module',
'모듈 상태',
'설치된 모듈들의 현재 상태',
'활성화',
'비활성화',
'/admin/modules',
'core.modules.read'
);
it('활성 모듈은 활성화 배지로 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_modules', {
response: {
data: {
data: [
{ name: '게시판', version: '0.7.0', status: 'active' },
{ name: '이커머스', version: '0.16.1', status: 'inactive' },
],
},
},
});
await testUtils.render();
const badges = document.querySelectorAll('[class*="badge-"]');
expect(badges.length).toBe(2);
expect(badges[0].className).toContain('badge-active');
expect(badges[0].textContent).toBe('활성화');
expect(badges[1].className).toContain('badge-inactive');
expect(badges[1].textContent).toBe('비활성화');
testUtils.cleanup();
});
it('cubes 아이콘이 헤더에 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_modules', {
response: { data: { data: [] } },
});
await testUtils.render();
expect(screen.getByTestId('icon-cube')).toBeInTheDocument();
testUtils.cleanup();
});
it('더보기 버튼이 존재한다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_modules', {
response: { data: { data: [] } },
});
await testUtils.render();
expect(screen.getByText('더보기')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('플러그인 상태 카드', () => {
const layout = createExtensionCardLayout(
'plugin_status_card',
'dashboard_plugins',
'/api/admin/plugins/installed',
'puzzle-piece',
'plugin',
'플러그인 상태',
'설치된 플러그인들의 현재 상태',
'활성화',
'비활성화',
'/admin/plugins',
'core.plugins.read'
);
it('활성 플러그인은 활성화 배지로 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_plugins', {
response: {
data: {
data: [
{ name: '결제', version: '1.0.0', status: 'active' },
],
},
},
});
await testUtils.render();
const badges = document.querySelectorAll('[class*="badge-"]');
expect(badges.length).toBe(1);
expect(badges[0].className).toContain('badge-active');
expect(badges[0].textContent).toBe('활성화');
testUtils.cleanup();
});
it('plug 아이콘이 헤더에 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_plugins', {
response: { data: { data: [] } },
});
await testUtils.render();
expect(screen.getByTestId('icon-puzzle-piece')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('템플릿 상태 카드', () => {
const layout = createExtensionCardLayout(
'template_status_card',
'dashboard_templates',
'/api/admin/templates',
'palette',
'template',
'템플릿 상태',
'설치된 템플릿들의 현재 상태',
'활성화',
'비활성화',
'/admin/templates/admin',
'core.templates.read'
);
it('활성 템플릿은 활성화 배지로 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_templates', {
response: {
data: {
data: [
{ name: 'Admin Basic', version: '0.2.21', status: 'active' },
{ name: 'User Basic', version: '0.1.0', status: 'active' },
],
},
},
});
await testUtils.render();
const badges = document.querySelectorAll('[class*="badge-"]');
expect(badges.length).toBe(2);
expect(badges[0].className).toContain('badge-active');
expect(badges[1].className).toContain('badge-active');
testUtils.cleanup();
});
it('puzzle-piece 아이콘이 헤더에 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
testUtils.mockApi('dashboard_templates', {
response: { data: { data: [] } },
});
await testUtils.render();
expect(screen.getByTestId('icon-palette')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('모듈 상태 버그 수정 검증 (is_active → status)', () => {
/**
* 이전 버그: module.is_active 참조 시 undefined → 항상 비활성화 표시
* 수정: module.status === 'active' 사용
*/
const layout = createExtensionCardLayout(
'module_status_card',
'dashboard_modules',
'/api/admin/modules/installed',
'cube',
'module',
'모듈 상태',
'설치된 모듈들의 현재 상태',
'활성화',
'비활성화',
'/admin/modules',
'core.modules.read'
);
it('status=active 모듈은 is_active 없이도 활성화로 표시된다', async () => {
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
// is_active 필드 없이 status만 있는 API 응답 (실제 ModuleResource 출력)
testUtils.mockApi('dashboard_modules', {
response: {
data: {
data: [
{ name: '게시판', version: '0.7.0', status: 'active' },
{ name: '이커머스', version: '0.16.1', status: 'active' },
],
},
},
});
await testUtils.render();
const badges = document.querySelectorAll('[class*="badge-"]');
expect(badges.length).toBe(2);
// 이전에는 모두 badge-inactive였음 (is_active가 undefined)
expect(badges[0].className).toContain('badge-active');
expect(badges[1].className).toContain('badge-active');
expect(badges[0].textContent).toBe('활성화');
expect(badges[1].textContent).toBe('활성화');
testUtils.cleanup();
});
});
});
@@ -0,0 +1,564 @@
/**
* @file admin-extension-list-abilities.test.tsx
* @description 모듈/플러그인/템플릿 관리 페이지 abilities 기반 버튼 비활성화 렌더링 테스트
*
* 테스트 대상:
* - collection-level abilities (can_install, can_activate, can_uninstall)
* - per-row abilities 표현식 패턴 (row.abilities.can_install !== true)
* - 페이지 레벨 버튼: 업데이트 확인, 수동 설치
* - per-row 버튼: 설치, 업데이트, 활성화/비활성화 토글
* - ActionMenu 항목: 레이아웃 갱신, 삭제 (status + abilities 복합 조건)
*
* 참고: 실제 레이아웃에서 `row`는 DataGrid iteration 컨텍스트로 제공되지만,
* 테스트에서는 `_local.row`로 시뮬레이션하여 표현식 패턴을 검증합니다.
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
type?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button className={className} disabled={disabled} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={className} data-icon={name} />
);
const TestPageHeader: React.FC<{
title?: string;
description?: string;
children?: React.ReactNode;
}> = ({ title, description, children }) => (
<div data-testid="page-header">
{title && <h1>{title}</h1>}
{description && <p>{description}</p>}
{children}
</div>
);
const TestToggle: React.FC<{
disabled?: boolean;
checked?: boolean;
'data-testid'?: string;
}> = ({ disabled, checked, 'data-testid': testId }) => (
<input
type="checkbox"
checked={checked}
disabled={disabled}
data-testid={testId}
readOnly
/>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
PageHeader: { component: TestPageHeader, metadata: { name: 'PageHeader', type: 'composite' } },
Toggle: { component: TestToggle, metadata: { name: 'Toggle', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
/**
* 페이지 레벨 버튼 테스트 레이아웃
* - collection-level abilities: modules?.data?.abilities?.can_install
* - isCheckingUpdates 상태와 OR 조건
*/
const pageLevelLayout = {
version: '1.0.0',
layout_name: 'test_page_level_abilities',
data_sources: [
{
id: 'modules',
type: 'api',
endpoint: '/api/admin/modules',
method: 'GET',
auto_fetch: true,
auth_required: true,
fallback: {
data: {
data: [],
abilities: { can_install: false, can_activate: false, can_uninstall: false },
},
},
},
],
state: {
isCheckingUpdates: false,
},
components: [
{
id: 'page_content',
type: 'basic',
name: 'Div',
children: [
{
id: 'check_updates_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{_local.isCheckingUpdates || modules?.data?.abilities?.can_install !== true}}',
'data-testid': 'check-updates-button',
},
text: '업데이트 확인',
},
{
id: 'manual_install_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{modules?.data?.abilities?.can_install !== true}}',
className: 'disabled:opacity-50 disabled:cursor-not-allowed',
'data-testid': 'manual-install-button',
},
text: '수동 설치',
},
],
},
],
};
/**
* per-row 버튼 테스트 레이아웃
* 실제 레이아웃에서 `row`는 DataGrid iteration 컨텍스트이지만,
* 테스트에서는 _local.row로 시뮬레이션하여 동일한 표현식 패턴 검증
*/
const rowLevelLayout = {
version: '1.0.0',
layout_name: 'test_row_level_abilities',
data_sources: [],
state: {
row: {
status: 'active',
abilities: { can_install: false, can_activate: false, can_uninstall: false },
},
},
components: [
{
id: 'row_content',
type: 'basic',
name: 'Div',
children: [
{
id: 'row_install_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{_local.row.abilities?.can_install !== true}}',
className: 'disabled:opacity-50 disabled:cursor-not-allowed',
'data-testid': 'row-install-button',
},
text: '설치',
},
{
id: 'row_update_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{_local.row.abilities?.can_install !== true}}',
className: 'disabled:opacity-50 disabled:cursor-not-allowed',
'data-testid': 'row-update-button',
},
text: '업데이트',
},
{
id: 'row_toggle',
type: 'basic',
name: 'Toggle',
props: {
disabled: '{{_local.row.abilities?.can_activate !== true}}',
'data-testid': 'row-toggle',
},
},
{
id: 'action_refresh_layouts',
type: 'basic',
name: 'Button',
props: {
disabled: "{{_local.row.status != 'active' || _local.row.abilities?.can_activate !== true}}",
'data-testid': 'action-refresh-layouts',
},
text: '레이아웃 갱신',
},
{
id: 'action_uninstall',
type: 'basic',
name: 'Button',
props: {
disabled: "{{_local.row.status == 'uninstalled' || _local.row.status == 'uninstalling' || _local.row.status == 'installing' || _local.row.abilities?.can_uninstall !== true}}",
'data-testid': 'action-uninstall',
},
text: '삭제',
},
],
},
],
};
// Mock API 응답 생성 헬퍼
function createModulesResponse(
collectionAbilities: { can_install: boolean; can_activate: boolean; can_uninstall: boolean },
) {
return {
success: true,
data: {
data: [
{
id: 'sirsoft-ecommerce',
name: { ko: '전자상거래', en: 'E-Commerce' },
status: 'active',
abilities: collectionAbilities,
},
],
abilities: collectionAbilities,
current_page: 1,
last_page: 1,
per_page: 12,
total: 1,
},
};
}
describe('모듈/플러그인/템플릿 관리 - abilities 기반 버튼 비활성화', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('페이지 레벨 버튼 - collection abilities', () => {
it('모든 권한 있음 → 업데이트 확인, 수동 설치 버튼 활성화', async () => {
const testUtils = createLayoutTest(pageLevelLayout);
testUtils.mockApi('modules', {
response: createModulesResponse(
{ can_install: true, can_activate: true, can_uninstall: true },
),
});
await testUtils.render();
const checkUpdatesBtn = screen.getByTestId('check-updates-button');
const manualInstallBtn = screen.getByTestId('manual-install-button');
expect(checkUpdatesBtn).not.toBeDisabled();
expect(manualInstallBtn).not.toBeDisabled();
testUtils.cleanup();
});
it('can_install=false → 업데이트 확인, 수동 설치 버튼 비활성화', async () => {
const testUtils = createLayoutTest(pageLevelLayout);
testUtils.mockApi('modules', {
response: createModulesResponse(
{ can_install: false, can_activate: true, can_uninstall: true },
),
});
await testUtils.render();
const checkUpdatesBtn = screen.getByTestId('check-updates-button');
const manualInstallBtn = screen.getByTestId('manual-install-button');
expect(checkUpdatesBtn).toBeDisabled();
expect(manualInstallBtn).toBeDisabled();
testUtils.cleanup();
});
it('isCheckingUpdates=true → 업데이트 확인 버튼 비활성화 (can_install=true여도)', async () => {
// isCheckingUpdates를 true로 시작하는 별도 레이아웃
const layoutWithChecking = {
...pageLevelLayout,
layout_name: 'test_page_level_checking',
state: { isCheckingUpdates: true },
};
const testUtils = createLayoutTest(layoutWithChecking);
testUtils.mockApi('modules', {
response: createModulesResponse(
{ can_install: true, can_activate: true, can_uninstall: true },
),
});
await testUtils.render();
const checkUpdatesBtn = screen.getByTestId('check-updates-button');
expect(checkUpdatesBtn).toBeDisabled();
// 수동 설치는 isCheckingUpdates와 무관하게 can_install만 체크
const manualInstallBtn = screen.getByTestId('manual-install-button');
expect(manualInstallBtn).not.toBeDisabled();
testUtils.cleanup();
});
});
describe('per-row 버튼 - row abilities', () => {
it('모든 권한 있음 → 설치, 업데이트, 토글 활성화', async () => {
const layoutWithFullAbilities = {
...rowLevelLayout,
layout_name: 'test_row_full_abilities',
state: {
row: {
status: 'active',
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layoutWithFullAbilities);
await testUtils.render();
expect(screen.getByTestId('row-install-button')).not.toBeDisabled();
expect(screen.getByTestId('row-update-button')).not.toBeDisabled();
expect(screen.getByTestId('row-toggle')).not.toBeDisabled();
testUtils.cleanup();
});
it('can_install=false → 설치, 업데이트 버튼 비활성화', async () => {
const layoutNoInstall = {
...rowLevelLayout,
layout_name: 'test_row_no_install',
state: {
row: {
status: 'active',
abilities: { can_install: false, can_activate: true, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layoutNoInstall);
await testUtils.render();
expect(screen.getByTestId('row-install-button')).toBeDisabled();
expect(screen.getByTestId('row-update-button')).toBeDisabled();
// 토글은 can_activate=true이므로 활성화
expect(screen.getByTestId('row-toggle')).not.toBeDisabled();
testUtils.cleanup();
});
it('can_activate=false → 토글 비활성화', async () => {
const layoutNoActivate = {
...rowLevelLayout,
layout_name: 'test_row_no_activate',
state: {
row: {
status: 'active',
abilities: { can_install: true, can_activate: false, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layoutNoActivate);
await testUtils.render();
expect(screen.getByTestId('row-toggle')).toBeDisabled();
// 설치 버튼은 can_install=true이므로 활성화
expect(screen.getByTestId('row-install-button')).not.toBeDisabled();
testUtils.cleanup();
});
});
describe('ActionMenu 항목 - status + abilities 복합 조건', () => {
it('active + 모든 권한 → 레이아웃 갱신 활성화', async () => {
const layout = {
...rowLevelLayout,
layout_name: 'test_action_active_full',
state: {
row: {
status: 'active',
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
expect(screen.getByTestId('action-refresh-layouts')).not.toBeDisabled();
testUtils.cleanup();
});
it('inactive + can_activate=false → 레이아웃 갱신 비활성화', async () => {
const layout = {
...rowLevelLayout,
layout_name: 'test_action_inactive_no_activate',
state: {
row: {
status: 'inactive',
abilities: { can_install: true, can_activate: false, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
// inactive != 'active' → true, OR 연산으로 이미 disabled
expect(screen.getByTestId('action-refresh-layouts')).toBeDisabled();
testUtils.cleanup();
});
it('active + can_activate=false → 레이아웃 갱신 비활성화 (status는 OK지만 권한 부족)', async () => {
const layout = {
...rowLevelLayout,
layout_name: 'test_action_active_no_activate',
state: {
row: {
status: 'active',
abilities: { can_install: true, can_activate: false, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
expect(screen.getByTestId('action-refresh-layouts')).toBeDisabled();
testUtils.cleanup();
});
it('inactive + can_uninstall=false → 삭제 비활성화', async () => {
const layout = {
...rowLevelLayout,
layout_name: 'test_action_no_uninstall',
state: {
row: {
status: 'inactive',
abilities: { can_install: true, can_activate: true, can_uninstall: false },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
expect(screen.getByTestId('action-uninstall')).toBeDisabled();
testUtils.cleanup();
});
it('inactive + can_uninstall=true → 삭제 활성화', async () => {
const layout = {
...rowLevelLayout,
layout_name: 'test_action_uninstall_ok',
state: {
row: {
status: 'inactive',
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
expect(screen.getByTestId('action-uninstall')).not.toBeDisabled();
testUtils.cleanup();
});
it('uninstalled 상태 → can_uninstall=true여도 삭제 비활성화', async () => {
const layout = {
...rowLevelLayout,
layout_name: 'test_action_uninstalled',
state: {
row: {
status: 'uninstalled',
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
expect(screen.getByTestId('action-uninstall')).toBeDisabled();
testUtils.cleanup();
});
});
describe('모든 권한 없는 사용자 (읽기 전용)', () => {
it('페이지 레벨 + per-row 모든 버튼 비활성화', async () => {
const noAbilities = { can_install: false, can_activate: false, can_uninstall: false };
// 페이지 레벨
const pageLevelTest = createLayoutTest(pageLevelLayout);
pageLevelTest.mockApi('modules', {
response: createModulesResponse(noAbilities),
});
await pageLevelTest.render();
expect(screen.getByTestId('check-updates-button')).toBeDisabled();
expect(screen.getByTestId('manual-install-button')).toBeDisabled();
pageLevelTest.cleanup();
// per-row 레벨
const rowLayout = {
...rowLevelLayout,
layout_name: 'test_readonly_row',
state: {
row: { status: 'active', abilities: noAbilities },
},
};
const rowLevelTest = createLayoutTest(rowLayout);
await rowLevelTest.render();
expect(screen.getByTestId('row-install-button')).toBeDisabled();
expect(screen.getByTestId('row-update-button')).toBeDisabled();
expect(screen.getByTestId('row-toggle')).toBeDisabled();
expect(screen.getByTestId('action-refresh-layouts')).toBeDisabled();
expect(screen.getByTestId('action-uninstall')).toBeDisabled();
rowLevelTest.cleanup();
});
});
});
@@ -0,0 +1,466 @@
/**
* @file admin-forgot-password.test.tsx
* @description 관리자 비밀번호 찾기 레이아웃 렌더링 테스트
*
* 테스트 대상:
* - 초기 상태에서 폼이 표시되고 성공 메시지가 숨겨지는지
* - 성공 상태에서 폼이 숨겨지고 성공 메시지가 표시되는지
* - 로그인으로 돌아가기 링크가 /admin/login으로 네비게이션하는지
* - 제출 중 상태에서 스피너와 처리 중 텍스트가 표시되는지
* - 에러 시 이메일 입력 필드에 빨간 테두리 + 하단 에러 메시지 표시
*/
import React from 'react';
import { describe, it, expect, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<any> = ({ className, children, type, disabled, 'data-testid': testId }) => (
<button className={className} type={type} disabled={disabled} data-testid={testId}>{children}</button>
);
const TestInput: React.FC<any> = ({ className, type, name, placeholder, disabled, required, 'data-testid': testId, ...rest }) => (
<input className={className} type={type} name={name} placeholder={placeholder} disabled={disabled} required={required} data-testid={testId} readOnly {...rest} />
);
const TestForm: React.FC<any> = ({ className, children }) => <form className={className}>{children}</form>;
const TestLabel: React.FC<any> = ({ className, children }) => <label className={className}>{children}</label>;
const TestSelect: React.FC<any> = ({ className, 'data-testid': testId }) => <select className={className} data-testid={testId} readOnly />;
const TestH1: React.FC<any> = ({ className, children }) => <h1 className={className}>{children}</h1>;
const TestP: React.FC<any> = ({ className, children, 'data-testid': testId }) => <p className={className} data-testid={testId}>{children}</p>;
const TestSpan: React.FC<any> = ({ className, children }) => <span className={className}>{children}</span>;
const TestIcon: React.FC<any> = ({ name, size, color }) => <i data-icon={name} data-size={size} className={color} />;
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Form: { component: TestForm, metadata: { name: 'Form', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Select: { component: TestSelect, metadata: { name: 'Select', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 비밀번호 찾기 레이아웃 (핵심 부분)
const forgotPasswordLayout = {
version: '1.0.0',
layout_name: 'test_admin_forgot_password',
state: {
isSubmitting: false,
success: false,
forgotError: null,
forgotErrors: null,
},
components: [
{
id: 'forgot_card',
type: 'basic',
name: 'Div',
props: { className: 'bg-white dark:bg-gray-800 rounded-lg shadow-md p-8' },
children: [
{
id: 'forgot_header',
type: 'basic',
name: 'Div',
props: { className: 'text-center mb-8' },
children: [
{
id: 'forgot_lock_icon_wrapper',
type: 'basic',
name: 'Div',
props: { className: 'w-16 h-16 mx-auto mb-4 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center' },
children: [
{ id: 'forgot_lock_icon', type: 'basic', name: 'Icon', props: { name: 'lock', size: 'xl', color: 'text-blue-600 dark:text-blue-400' } },
],
},
{
id: 'forgot_title',
type: 'basic',
name: 'H1',
props: { className: 'text-2xl font-bold text-gray-900 dark:text-white mb-2' },
text: '비밀번호 찾기',
},
{
id: 'forgot_subtitle',
type: 'basic',
name: 'P',
if: '{{!_local.success}}',
props: { className: 'text-sm text-gray-600 dark:text-gray-400' },
text: '가입 시 사용한 이메일을 입력하시면 비밀번호 재설정 링크를 보내드립니다.',
},
],
},
{
id: 'forgot_success_message',
type: 'basic',
name: 'Div',
if: '{{_local.success}}',
props: { className: 'mb-6 p-4 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-lg' },
children: [
{
id: 'forgot_success_text',
type: 'basic',
name: 'P',
props: { className: 'text-green-700 dark:text-green-300 text-sm text-center' },
text: '비밀번호 재설정 링크가 이메일로 발송되었습니다.',
},
],
},
{
id: 'forgot_error_message',
type: 'basic',
name: 'Div',
if: '{{_local.forgotError && !_local.forgotErrors}}',
props: { className: 'p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg', 'data-testid': 'general-error' },
children: [
{
id: 'forgot_error_text',
type: 'basic',
name: 'P',
props: { className: 'text-red-700 dark:text-red-300 text-sm text-center' },
text: '{{_local.forgotError}}',
},
],
},
{
id: 'forgot_form',
type: 'basic',
name: 'Form',
if: '{{!_local.success}}',
props: { className: 'space-y-6' },
children: [
{
id: 'forgot_email_field',
type: 'basic',
name: 'Div',
children: [
{
id: 'forgot_email_label',
type: 'basic',
name: 'Label',
props: { className: 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2' },
text: '이메일',
},
{
id: 'forgot_email_input',
type: 'basic',
name: 'Input',
props: {
type: 'email',
name: 'email',
placeholder: '이메일 주소를 입력하세요',
required: true,
disabled: '{{_local.isSubmitting ?? false}}',
className: "{{_local.forgotErrors?.email ? 'w-full px-4 py-3 border border-red-500 dark:border-red-500 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:border-red-500 focus:ring-red-500' : 'w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-blue-500'}}",
'data-testid': 'email-input',
},
},
{
id: 'forgot_email_error',
type: 'basic',
name: 'P',
if: '{{_local.forgotErrors?.email}}',
props: { className: 'mt-2 text-sm text-red-600 dark:text-red-400', 'data-testid': 'email-error' },
text: "{{Array.isArray(_local.forgotErrors?.email) ? _local.forgotErrors.email[0] : _local.forgotErrors?.email}}",
},
],
},
{
id: 'forgot_submit_button',
type: 'basic',
name: 'Button',
props: {
type: 'submit',
className: 'w-full px-4 py-3 rounded-lg font-medium bg-blue-600 text-white',
disabled: '{{_local.isSubmitting ?? false}}',
'data-testid': 'submit-button',
},
children: [
{
id: 'forgot_submit_spinner',
type: 'basic',
name: 'Div',
if: '{{_local.isSubmitting}}',
props: { className: 'w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin', 'data-testid': 'spinner' },
},
{
id: 'forgot_submit_text',
type: 'basic',
name: 'Span',
if: '{{!_local.isSubmitting}}',
text: '재설정 링크 발송',
},
{
id: 'forgot_submit_processing',
type: 'basic',
name: 'Span',
if: '{{_local.isSubmitting}}',
text: '처리 중...',
},
],
},
],
},
{
id: 'forgot_back_to_login',
type: 'basic',
name: 'Div',
props: { className: 'mt-6 text-center' },
children: [
{
id: 'forgot_back_link',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: 'text-sm text-blue-600',
'data-testid': 'back-to-login',
},
actions: [
{ type: 'click', handler: 'navigate', params: { path: '/admin/login' } },
],
text: '← 로그인으로 돌아가기',
},
],
},
],
},
],
};
describe('관리자 비밀번호 찾기 레이아웃', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
describe('초기 상태 (success = false)', () => {
it('폼이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('email-input')).toBeInTheDocument();
expect(screen.getByTestId('submit-button')).toBeInTheDocument();
});
it('제목과 부제목이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호 찾기')).toBeInTheDocument();
expect(screen.getByText('가입 시 사용한 이메일을 입력하시면 비밀번호 재설정 링크를 보내드립니다.')).toBeInTheDocument();
});
it('성공 메시지는 숨겨져 있다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByText('비밀번호 재설정 링크가 이메일로 발송되었습니다.')).toBeNull();
});
it('로그인으로 돌아가기 링크가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
const backLink = screen.getByTestId('back-to-login');
expect(backLink).toBeInTheDocument();
expect(screen.getByText('← 로그인으로 돌아가기')).toBeInTheDocument();
});
it('제출 버튼에 재설정 링크 발송 텍스트가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('재설정 링크 발송')).toBeInTheDocument();
});
it('스피너가 숨겨져 있다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('spinner')).toBeNull();
});
it('에러 메시지가 숨겨져 있다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('general-error')).toBeNull();
expect(screen.queryByTestId('email-error')).toBeNull();
});
it('이메일 입력 필드에 기본 테두리가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(forgotPasswordLayout, { componentRegistry: registry });
await testUtils.render();
const emailInput = screen.getByTestId('email-input');
expect(emailInput.className).toContain('border-gray-300');
expect(emailInput.className).not.toContain('border-red-500');
});
});
describe('성공 상태 (success = true)', () => {
const successLayout = {
...forgotPasswordLayout,
layout_name: 'test_admin_forgot_password_success',
state: { isSubmitting: false, success: true, forgotError: null, forgotErrors: null },
};
it('성공 메시지가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(successLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호 재설정 링크가 이메일로 발송되었습니다.')).toBeInTheDocument();
});
it('폼이 숨겨진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(successLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('email-input')).toBeNull();
expect(screen.queryByTestId('submit-button')).toBeNull();
});
it('부제목이 숨겨진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(successLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByText('가입 시 사용한 이메일을 입력하시면 비밀번호 재설정 링크를 보내드립니다.')).toBeNull();
});
});
describe('제출 중 상태 (isSubmitting = true)', () => {
const submittingLayout = {
...forgotPasswordLayout,
layout_name: 'test_admin_forgot_password_submitting',
state: { isSubmitting: true, success: false, forgotError: null, forgotErrors: null },
};
it('스피너가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(submittingLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('spinner')).toBeInTheDocument();
});
it('처리 중 텍스트가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(submittingLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('처리 중...')).toBeInTheDocument();
});
it('재설정 링크 발송 텍스트가 숨겨진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(submittingLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByText('재설정 링크 발송')).toBeNull();
});
});
describe('필드 에러 상태 (forgotErrors.email 존재)', () => {
const errorLayout = {
...forgotPasswordLayout,
layout_name: 'test_admin_forgot_password_field_error',
state: {
isSubmitting: false,
success: false,
forgotError: 'The given data was invalid.',
forgotErrors: { email: ['이메일 주소를 찾을 수 없습니다.'] },
},
};
it('이메일 입력 필드에 빨간 테두리가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
const emailInput = screen.getByTestId('email-input');
expect(emailInput.className).toContain('border-red-500');
expect(emailInput.className).not.toContain('border-gray-300');
});
it('이메일 필드 아래 에러 메시지가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
const emailError = screen.getByTestId('email-error');
expect(emailError).toBeInTheDocument();
expect(emailError.textContent).toBe('이메일 주소를 찾을 수 없습니다.');
});
it('일반 에러 배너는 숨겨진다 (필드 에러가 있으므로)', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('general-error')).toBeNull();
});
});
describe('일반 에러 상태 (forgotError만, forgotErrors 없음)', () => {
const generalErrorLayout = {
...forgotPasswordLayout,
layout_name: 'test_admin_forgot_password_general_error',
state: {
isSubmitting: false,
success: false,
forgotError: '서버 오류가 발생했습니다.',
forgotErrors: null,
},
};
it('일반 에러 배너가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(generalErrorLayout, { componentRegistry: registry });
await testUtils.render();
const generalError = screen.getByTestId('general-error');
expect(generalError).toBeInTheDocument();
expect(screen.getByText('서버 오류가 발생했습니다.')).toBeInTheDocument();
});
it('이메일 필드 에러는 숨겨진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(generalErrorLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('email-error')).toBeNull();
});
it('이메일 입력 필드에 기본 테두리가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(generalErrorLayout, { componentRegistry: registry });
await testUtils.render();
const emailInput = screen.getByTestId('email-input');
expect(emailInput.className).toContain('border-gray-300');
});
});
});
@@ -0,0 +1,338 @@
/**
* @file admin-login-improvements.test.tsx
* @description 관리자 로그인 화면 개선 테스트
*
* 테스트 대상:
* - 비밀번호 찾기 링크가 Button + navigate 핸들러로 구현되었는지
* - 언어 셀렉트박스가 w-full 클래스를 사용하는지
* - 테마 Segmented Control이 3개 버튼으로 구성되었는지
* - 테마 버튼이 _global.theme에 따라 활성 스타일을 적용하는지
*/
import React from 'react';
import { describe, it, expect, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 기본 컴포넌트
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId, ...rest }) => (
<div className={className} data-testid={testId} {...rest}>{children}</div>
);
const TestButton: React.FC<any> = ({ className, children, type, title, disabled, 'data-testid': testId }) => (
<button className={className} type={type} title={title} disabled={disabled} data-testid={testId}>{children}</button>
);
const TestSelect: React.FC<any> = ({ className, value, 'data-testid': testId }) => (
<select className={className} value={value} readOnly data-testid={testId} />
);
const TestInput: React.FC<any> = ({ className, type, name, 'data-testid': testId, ...rest }) => (
<input className={className} type={type} name={name} data-testid={testId} readOnly {...rest} />
);
const TestSpan: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children}</span>
);
const TestH1: React.FC<any> = ({ className, children }) => (
<h1 className={className}>{children}</h1>
);
const TestP: React.FC<any> = ({ className, children }) => (
<p className={className}>{children}</p>
);
const TestForm: React.FC<any> = ({ className, children }) => (
<form className={className}>{children}</form>
);
const TestLabel: React.FC<any> = ({ className, children }) => (
<label className={className}>{children}</label>
);
const TestIcon: React.FC<any> = ({ name, size, color }) => (
<i data-icon={name} data-size={size} className={color} />
);
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Select: { component: TestSelect, metadata: { name: 'Select', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
H2: { component: TestH1, metadata: { name: 'H2', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Form: { component: TestForm, metadata: { name: 'Form', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 로그인 페이지 하단 영역만 추출 (비밀번호 찾기 링크 + 언어 셀렉터 + 테마 컨트롤)
const loginBottomLayout = {
version: '1.0.0',
layout_name: 'test_admin_login_bottom',
state: {
isLoggingIn: false,
},
components: [
{
comment: '비밀번호 찾기 링크',
id: 'login_forgot_password',
type: 'basic',
name: 'Div',
props: { className: 'flex items-center justify-end' },
children: [
{
id: 'login_forgot_link',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: 'text-sm text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors duration-200 cursor-pointer',
'data-testid': 'forgot-link',
},
actions: [
{
type: 'click',
handler: 'navigate',
params: { path: '/admin/forgot-password' },
},
],
text: '비밀번호를 잊으셨나요?',
},
],
},
{
id: 'language_selector_container',
type: 'basic',
name: 'Div',
props: { className: 'mt-6' },
children: [
{
id: 'language_selector',
type: 'basic',
name: 'Select',
props: {
className: 'block w-full px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm',
'data-testid': 'language-select',
},
},
],
},
{
id: 'theme_selector_container',
type: 'basic',
name: 'Div',
props: { className: 'mt-4 flex justify-center' },
children: [
{
id: 'theme_segmented_control',
type: 'basic',
name: 'Div',
props: {
className: 'inline-flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1 gap-1',
'data-testid': 'theme-segmented-control',
},
children: [
{
id: 'theme_light_button',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: "{{_global.theme === 'light' ? 'p-2 rounded-md bg-white dark:bg-gray-700 shadow-sm text-blue-600 dark:text-blue-400 transition-all duration-200' : 'p-2 rounded-md text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-all duration-200'}}",
title: 'Light',
'data-testid': 'theme-light',
},
children: [
{ id: 'icon_light', type: 'basic', name: 'Icon', props: { name: 'sun', size: 'sm' } },
],
},
{
id: 'theme_dark_button',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: "{{_global.theme === 'dark' ? 'p-2 rounded-md bg-white dark:bg-gray-700 shadow-sm text-blue-600 dark:text-blue-400 transition-all duration-200' : 'p-2 rounded-md text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-all duration-200'}}",
title: 'Dark',
'data-testid': 'theme-dark',
},
children: [
{ id: 'icon_dark', type: 'basic', name: 'Icon', props: { name: 'moon', size: 'sm' } },
],
},
{
id: 'theme_auto_button',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: "{{_global.theme === 'auto' || !_global.theme ? 'p-2 rounded-md bg-white dark:bg-gray-700 shadow-sm text-blue-600 dark:text-blue-400 transition-all duration-200' : 'p-2 rounded-md text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-all duration-200'}}",
title: 'Auto',
'data-testid': 'theme-auto',
},
children: [
{ id: 'icon_auto', type: 'basic', name: 'Icon', props: { name: 'desktop', size: 'sm' } },
],
},
],
},
],
},
],
};
describe('관리자 로그인 화면 개선', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
describe('비밀번호 찾기 링크', () => {
it('Button 컴포넌트로 렌더링된다 (A 태그 아님)', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
const forgotLink = screen.getByTestId('forgot-link');
expect(forgotLink.tagName).toBe('BUTTON');
});
it('비밀번호를 잊으셨나요? 텍스트가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호를 잊으셨나요?')).toBeInTheDocument();
});
});
describe('언어 셀렉트박스', () => {
it('w-full 클래스가 적용된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
const select = screen.getByTestId('language-select');
expect(select.className).toContain('w-full');
});
it('rounded-lg 클래스가 적용된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
const select = screen.getByTestId('language-select');
expect(select.className).toContain('rounded-lg');
});
});
describe('테마 Segmented Control', () => {
it('3개 테마 버튼이 렌더링된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('theme-light')).toBeInTheDocument();
expect(screen.getByTestId('theme-dark')).toBeInTheDocument();
expect(screen.getByTestId('theme-auto')).toBeInTheDocument();
});
it('pill 컨테이너가 inline-flex + rounded-lg 스타일을 가진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
const control = screen.getByTestId('theme-segmented-control');
expect(control.className).toContain('inline-flex');
expect(control.className).toContain('rounded-lg');
expect(control.className).toContain('bg-gray-100');
});
it('각 버튼에 접근성 title이 있다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('theme-light')).toHaveAttribute('title', 'Light');
expect(screen.getByTestId('theme-dark')).toHaveAttribute('title', 'Dark');
expect(screen.getByTestId('theme-auto')).toHaveAttribute('title', 'Auto');
});
it('_global.theme 미설정 시 auto 버튼이 활성 스타일을 가진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
// _global.theme 미설정 → auto 버튼이 활성
const autoBtn = screen.getByTestId('theme-auto');
expect(autoBtn.className).toContain('shadow-sm');
expect(autoBtn.className).toContain('text-blue-600');
// light, dark 버튼은 비활성 스타일
const lightBtn = screen.getByTestId('theme-light');
expect(lightBtn.className).toContain('text-gray-500');
});
it('_global.theme = light 시 light 버튼만 활성 스타일을 가진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, {
componentRegistry: registry,
initialState: { _global: { theme: 'light' } },
});
await testUtils.render();
const lightBtn = screen.getByTestId('theme-light');
expect(lightBtn.className).toContain('shadow-sm');
expect(lightBtn.className).toContain('text-blue-600');
const darkBtn = screen.getByTestId('theme-dark');
expect(darkBtn.className).toContain('text-gray-500');
const autoBtn = screen.getByTestId('theme-auto');
expect(autoBtn.className).toContain('text-gray-500');
});
it('_global.theme = dark 시 dark 버튼만 활성 스타일을 가진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, {
componentRegistry: registry,
initialState: { _global: { theme: 'dark' } },
});
await testUtils.render();
const darkBtn = screen.getByTestId('theme-dark');
expect(darkBtn.className).toContain('shadow-sm');
expect(darkBtn.className).toContain('text-blue-600');
const lightBtn = screen.getByTestId('theme-light');
expect(lightBtn.className).toContain('text-gray-500');
});
it('아이콘만 표시된다 (텍스트 없음)', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(loginBottomLayout, { componentRegistry: registry });
await testUtils.render();
// sun, moon, desktop 아이콘 확인
const sunIcon = document.querySelector('[data-icon="sun"]');
const moonIcon = document.querySelector('[data-icon="moon"]');
const desktopIcon = document.querySelector('[data-icon="desktop"]');
expect(sunIcon).not.toBeNull();
expect(moonIcon).not.toBeNull();
expect(desktopIcon).not.toBeNull();
});
});
});
@@ -0,0 +1,389 @@
/**
* @file admin-mail-send-log-abilities.test.tsx
* @description 메일 발송 이력 관리 페이지 abilities 기반 권한 제어 렌더링 테스트
*
* 테스트 대상:
* - collection-level abilities (can_delete) → 일괄 삭제 버튼 disabled
* - DataGrid selectable 조건 (can_delete)
* - per-row abilities → 삭제 rowAction disabledField
* - errorHandling 403 데이터소스 설정 존재 여부
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen, waitFor } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
type?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button className={className} disabled={disabled} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
/**
* collection-level abilities 테스트 레이아웃
* - bulk_action_bar: 선택 시에만 표시 (if 조건), 삭제 버튼은 can_delete로 disabled
* - selectable → 체크박스 표시 여부 제어
*/
const collectionAbilitiesLayout = {
version: '1.0.0',
layout_name: 'test_mail_send_log_collection_abilities',
data_sources: [
{
id: 'mailSendLogs',
type: 'api',
endpoint: '/api/admin/mail-send-logs',
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
fallback: {
data: {
data: {
data: [],
abilities: { can_delete: false },
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0 },
},
},
},
errorHandling: {
'403': {
handler: 'showErrorPage',
params: { target: 'content' },
},
},
},
],
state: {},
components: [
{
id: 'page_content',
type: 'basic',
name: 'Div',
children: [
{
id: 'bulk_action_bar',
type: 'basic',
name: 'Div',
props: {
'data-testid': 'bulk-action-bar',
},
children: [
{
type: 'basic',
name: 'Span',
props: {
'data-testid': 'selected-count',
},
text: '{{(_global.selectedIds_admin_mail_send_logs ?? []).length}}건 선택됨',
},
{
id: 'bulk_delete_button',
type: 'basic',
name: 'Button',
props: {
type: 'button',
disabled: '{{(_global.selectedIds_admin_mail_send_logs ?? []).length === 0 || mailSendLogs?.data?.abilities?.can_delete !== true}}',
'data-testid': 'bulk-delete-button',
},
text: '선택 삭제',
},
],
},
{
id: 'selectable_indicator',
type: 'basic',
name: 'Span',
props: {
'data-testid': 'selectable-indicator',
},
text: '{{mailSendLogs?.data?.abilities?.can_delete === true ? "selectable" : "not-selectable"}}',
},
],
},
],
};
/**
* per-row abilities 테스트 레이아웃
* DataGrid의 row context를 _local.row로 시뮬레이션
*/
const rowAbilitiesLayout = {
version: '1.0.0',
layout_name: 'test_mail_send_log_row_abilities',
data_sources: [],
state: {
row: {
id: 1,
abilities: { can_delete: false },
},
},
components: [
{
id: 'row_content',
type: 'basic',
name: 'Div',
children: [
{
id: 'row_delete_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{_local.row.abilities?.can_delete !== true}}',
'data-testid': 'row-delete-button',
},
text: '삭제',
},
],
},
],
};
// Mock API 응답 생성 헬퍼
// 테스트 유틸리티는 API 응답에서 data 필드를 추출하여 dataContext에 저장
// 실제 엔진에서는 mailSendLogs = { loading, data: <api_data>, error } 형태
// 테스트 유틸리티에서는 mailSendLogs = <api_data> 형태로 저장
// 레이아웃에서 mailSendLogs?.data?.abilities로 접근하므로
// 테스트 mock에서도 data 안에 중첩된 data/abilities가 있어야 함
function createMailSendLogsResponse(canDelete: boolean) {
return {
data: {
data: [
{
id: 1,
recipient_email: 'test@example.com',
recipient_name: '테스트',
subject: '테스트 메일',
status: 'sent',
sent_at: '2026-03-10 10:00:00',
abilities: { can_delete: canDelete },
},
],
abilities: { can_delete: canDelete },
pagination: {
current_page: 1,
last_page: 1,
per_page: 20,
total: 1,
},
},
};
}
describe('메일 발송 이력 관리 - abilities 기반 권한 제어', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('collection-level abilities - can_delete', () => {
it('can_delete=true → selectable 활성화 표시', async () => {
const testUtils = createLayoutTest(collectionAbilitiesLayout);
testUtils.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(true),
});
await testUtils.render();
// progressive 로딩 후 API 응답이 반영될 때까지 대기
await waitFor(() => {
const indicator = screen.getByTestId('selectable-indicator');
expect(indicator.textContent).toBe('selectable');
});
testUtils.cleanup();
});
it('can_delete=false → selectable 비활성화 표시', async () => {
const testUtils = createLayoutTest(collectionAbilitiesLayout);
testUtils.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(false),
});
await testUtils.render();
const indicator = screen.getByTestId('selectable-indicator');
expect(indicator.textContent).toBe('not-selectable');
testUtils.cleanup();
});
it('bulk_action_bar 상시 표시 + 선택 개수 표시', async () => {
const testUtils = createLayoutTest(collectionAbilitiesLayout);
testUtils.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(true),
});
await testUtils.render();
// 선택 항목 없어도 bulk_action_bar 항상 표시
expect(screen.getByTestId('bulk-action-bar')).toBeTruthy();
// 선택 개수 0 표시
const selectedCount = screen.getByTestId('selected-count');
expect(selectedCount.textContent).toContain('0');
testUtils.cleanup();
});
it('선택 항목 없음 → 일괄 삭제 버튼 비활성화', async () => {
const testUtils = createLayoutTest(collectionAbilitiesLayout);
testUtils.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(true),
});
await testUtils.render();
// can_delete=true여도 선택 항목 없으면 disabled
await waitFor(() => {
const bulkDeleteBtn = screen.getByTestId('bulk-delete-button');
expect(bulkDeleteBtn).toBeDisabled();
});
testUtils.cleanup();
});
it('can_delete=true + 선택 항목 있음 → 일괄 삭제 버튼 활성화', async () => {
const testUtils = createLayoutTest(collectionAbilitiesLayout);
testUtils.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(true),
});
testUtils.setState('selectedIds_admin_mail_send_logs', [1], 'global');
await testUtils.render();
// progressive 로딩 후 API 응답이 반영될 때까지 대기
await waitFor(() => {
const bulkDeleteBtn = screen.getByTestId('bulk-delete-button');
expect(bulkDeleteBtn).not.toBeDisabled();
});
testUtils.cleanup();
});
it('can_delete=false + 선택 항목 있음 → 일괄 삭제 버튼 비활성화', async () => {
const testUtils = createLayoutTest(collectionAbilitiesLayout);
testUtils.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(false),
});
testUtils.setState('selectedIds_admin_mail_send_logs', [1], 'global');
await testUtils.render();
const bulkDeleteBtn = screen.getByTestId('bulk-delete-button');
expect(bulkDeleteBtn).toBeDisabled();
testUtils.cleanup();
});
});
describe('per-row abilities - can_delete', () => {
it('can_delete=true → 행 삭제 버튼 활성화', async () => {
const layout = {
...rowAbilitiesLayout,
layout_name: 'test_row_can_delete',
state: {
row: {
id: 1,
abilities: { can_delete: true },
},
},
};
const testUtils = createLayoutTest(layout);
await testUtils.render();
expect(screen.getByTestId('row-delete-button')).not.toBeDisabled();
testUtils.cleanup();
});
it('can_delete=false → 행 삭제 버튼 비활성화', async () => {
const testUtils = createLayoutTest(rowAbilitiesLayout);
await testUtils.render();
expect(screen.getByTestId('row-delete-button')).toBeDisabled();
testUtils.cleanup();
});
});
describe('errorHandling 설정 검증', () => {
it('데이터소스에 403 errorHandling이 설정되어 있음', () => {
const dataSource = collectionAbilitiesLayout.data_sources[0];
expect(dataSource.errorHandling).toBeDefined();
expect(dataSource.errorHandling['403']).toBeDefined();
expect(dataSource.errorHandling['403'].handler).toBe('showErrorPage');
expect(dataSource.errorHandling['403'].params.target).toBe('content');
});
});
describe('읽기 전용 사용자 (삭제 권한 없음)', () => {
it('collection + row 모든 삭제 관련 기능 비활성화', async () => {
// collection-level
const collectionTest = createLayoutTest(collectionAbilitiesLayout);
collectionTest.mockApi('mail_send_logs', {
response: createMailSendLogsResponse(false),
});
await collectionTest.render();
const indicator = screen.getByTestId('selectable-indicator');
expect(indicator.textContent).toBe('not-selectable');
collectionTest.cleanup();
// row-level
const rowTest = createLayoutTest(rowAbilitiesLayout);
await rowTest.render();
expect(screen.getByTestId('row-delete-button')).toBeDisabled();
rowTest.cleanup();
});
});
});
@@ -0,0 +1,916 @@
/**
* @file admin-mail-send-log-list.test.tsx
* @description 메일 발송 이력 독립 관리자 메뉴 레이아웃 테스트
*
* 테스트 대상:
* - templates/.../admin_mail_send_log_list.json
* - templates/.../partials/admin_mail_send_log_list/_partial_filter.json
* - templates/.../partials/admin_mail_send_log_list/_partial_datagrid.json
*
* 검증 항목:
* - 레이아웃 구조 (extends, permissions, data_sources)
* - 필터 UI (searchType Select + 검색바 + 체크박스 필터 + 검색/초기화 버튼)
* - DataGrid 컬럼 정의 (수신자, 제목, 템플릿, 모듈, 상태, 발송일시)
* - 정렬/페이지크기 Select 및 Pagination 컴포넌트
* - URL 쿼리 기반 필터/정렬/페이지네이션
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// ==============================
// 테스트용 컴포넌트 정의
// ==============================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, onClick, 'data-testid': testId }) => (
<button type={type as any} className={className} disabled={disabled} onClick={onClick} data-testid={testId}>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestLabel: React.FC<{
className?: string;
children?: React.ReactNode;
}> = ({ className, children }) => (
<label className={className}>{children}</label>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h1 className={className}>{children || text}</h1>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={`icon-${name} ${className || ''}`} data-icon={name} />
);
const TestInput: React.FC<{
type?: string;
name?: string;
placeholder?: string;
className?: string;
value?: string;
checked?: boolean;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
'data-testid'?: string;
}> = ({ type, name, placeholder, className, value, checked, onChange, onKeyDown, 'data-testid': testId }) => (
<input
type={type}
name={name}
placeholder={placeholder}
className={className}
value={value}
checked={checked}
onChange={onChange}
onKeyDown={onKeyDown}
data-testid={testId}
/>
);
const TestSelect: React.FC<{
name?: string;
className?: string;
options?: Array<{ label: string; value: string }>;
value?: string;
onChange?: (e: React.ChangeEvent<HTMLSelectElement>) => void;
}> = ({ name, className, options, value, onChange }) => (
<div data-testid={`select-${name}`}>
<select name={name} className={className} value={value} onChange={onChange}>
{options?.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
</div>
);
const TestDataGrid: React.FC<{
data?: any[];
columns?: any[];
loading?: boolean;
selectable?: boolean;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ data, columns, loading, 'data-testid': testId }) => (
<div data-testid={testId || 'datagrid'} data-loading={loading} data-columns={columns?.length} data-rows={data?.length}>
{columns?.map((col: any) => (
<span key={col.field} data-testid={`col-${col.field}`}>{col.header}</span>
))}
</div>
);
const TestPagination: React.FC<{
currentPage?: number;
totalPages?: number;
onPageChange?: (page: number) => void;
}> = ({ currentPage, totalPages }) => (
<div data-testid="pagination" data-current={currentPage} data-total={totalPages}>
Pagination
</div>
);
const TestPageHeader: React.FC<{
title?: string;
children?: React.ReactNode;
}> = ({ title, children }) => (
<div data-testid="page-header">{title}{children}</div>
);
// ==============================
// 레지스트리 설정
// ==============================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Select: { component: TestSelect, metadata: { name: 'Select', type: 'composite' } },
DataGrid: { component: TestDataGrid, metadata: { name: 'DataGrid', type: 'composite' } },
Pagination: { component: TestPagination, metadata: { name: 'Pagination', type: 'composite' } },
PageHeader: { component: TestPageHeader, metadata: { name: 'PageHeader', type: 'composite' } },
};
return registry;
}
// ==============================
// 테스트용 레이아웃 (admin_mail_send_log_list.json 기반)
// ==============================
const mailSendLogListLayout = {
version: '1.0.0',
layout_name: 'admin_mail_send_log_list',
permissions: ['core.mail-send-logs.read'],
state: {
filter: {
searchType: 'all',
search: '',
modules: [],
statuses: [],
},
},
data_sources: [
{
id: 'mailSendLogs',
type: 'api',
endpoint: '/api/admin/mail-send-logs',
method: 'GET',
auto_fetch: true,
auth_required: true,
loading_strategy: 'progressive',
params: {
page: '{{query.page || 1}}',
per_page: '{{query.per_page || 20}}',
search: '{{query.search}}',
search_type: '{{query.search_type}}',
'module[]': "{{query['module[]']}}",
'status[]': "{{query['status[]']}}",
sort_by: "{{query.sort_by || 'sent_at'}}",
sort_order: "{{query.sort_order || 'desc'}}",
},
},
],
init_actions: [
{
handler: 'setState',
params: {
target: 'global',
_local: {
filter: {
searchType: "{{query.search_type || 'all'}}",
search: "{{query.search || ''}}",
modules: "{{query['module[]'] || []}}",
statuses: "{{query['status[]'] || []}}",
},
},
},
},
],
named_actions: {
searchMailSendLogs: {
handler: 'navigate',
params: {
path: '/admin/mail-send-logs',
replace: true,
query: {
page: 1,
search: '{{_local.filter.search || undefined}}',
search_type: "{{_local.filter.searchType !== 'all' ? _local.filter.searchType : undefined}}",
'module[]': '{{_local.filter.modules?.length > 0 ? _local.filter.modules : undefined}}',
'status[]': '{{_local.filter.statuses?.length > 0 ? _local.filter.statuses : undefined}}',
},
},
},
},
components: [
{
id: 'mail_send_log_list_content',
type: 'basic',
name: 'Div',
props: { className: 'p-6 bg-gray-50 dark:bg-gray-900 min-h-screen' },
children: [
// page_header
{
id: 'page_header',
type: 'basic',
name: 'Div',
children: [
{
type: 'basic',
name: 'Div',
children: [
{ type: 'basic', name: 'H1', props: { className: 'page-title' }, text: '$t:admin.mail_send_log.page_title' },
{ type: 'basic', name: 'P', text: '$t:admin.mail_send_log.page_description' },
],
},
],
},
// filter section
{
id: 'filter_section',
type: 'basic',
name: 'Div',
props: { className: 'card' },
children: [
// search_row (searchType Select + search Input)
{
id: 'search_row',
type: 'basic',
name: 'Div',
props: { className: 'mb-4' },
children: [
{
type: 'basic',
name: 'Div',
children: [
{
type: 'composite',
name: 'Select',
props: {
name: 'searchType',
value: "{{_local.filter.searchType || 'all'}}",
options: [
{ value: 'all', label: '$t:admin.mail_send_log.filter.search_type_all' },
{ value: 'recipient_email', label: '$t:admin.mail_send_log.filter.search_type_recipient_email' },
{ value: 'recipient_name', label: '$t:admin.mail_send_log.filter.search_type_recipient_name' },
{ value: 'subject', label: '$t:admin.mail_send_log.filter.search_type_subject' },
],
},
actions: [
{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.searchType': '{{$event.target.value}}' } },
],
},
{
type: 'basic',
name: 'Div',
children: [
{ type: 'basic', name: 'Icon', props: { name: 'fa-solid fa-search' } },
{
type: 'basic',
name: 'Input',
props: {
name: 'search',
type: 'text',
placeholder: '$t:admin.mail_send_log.filter.search_placeholder',
className: 'input w-full pl-10',
value: "{{_local.filter.search || ''}}",
},
actions: [
{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.search': '{{$event.target.value}}' } },
{ type: 'keydown', key: 'Enter', actionRef: 'searchMailSendLogs' },
],
},
],
},
],
},
],
},
// filter_grid (checkbox filters)
{
id: 'filter_grid',
type: 'basic',
name: 'Div',
props: { className: 'flex flex-col' },
children: [
// module filter row
{
id: 'module_filter',
type: 'basic',
name: 'Div',
props: { className: 'filter-row' },
children: [
{ type: 'basic', name: 'Span', props: { className: 'filter-label w-32' }, text: '$t:admin.mail_send_log.filter.module_label' },
{
type: 'basic',
name: 'Div',
children: [
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: '{{!_local.filter.modules || _local.filter.modules.length === 0}}' }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.modules': '{{[]}}' } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.module_all' },
]},
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: "{{(_local.filter.modules || []).includes('core')}}" }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.modules': "{{$event.target.checked ? [...(_local.filter.modules || []).filter(m => m !== 'core'), 'core'] : (_local.filter.modules || []).filter(m => m !== 'core')}}" } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.module_core' },
]},
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: "{{(_local.filter.modules || []).includes('sirsoft-board')}}" }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.modules': "{{$event.target.checked ? [...(_local.filter.modules || []).filter(m => m !== 'sirsoft-board'), 'sirsoft-board'] : (_local.filter.modules || []).filter(m => m !== 'sirsoft-board')}}" } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.module_board' },
]},
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: "{{(_local.filter.modules || []).includes('sirsoft-ecommerce')}}" }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.modules': "{{$event.target.checked ? [...(_local.filter.modules || []).filter(m => m !== 'sirsoft-ecommerce'), 'sirsoft-ecommerce'] : (_local.filter.modules || []).filter(m => m !== 'sirsoft-ecommerce')}}" } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.module_ecommerce' },
]},
],
},
],
},
// status filter row
{
id: 'status_filter',
type: 'basic',
name: 'Div',
props: { className: 'filter-row' },
children: [
{ type: 'basic', name: 'Span', props: { className: 'filter-label w-32' }, text: '$t:admin.mail_send_log.filter.status_label' },
{
type: 'basic',
name: 'Div',
children: [
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: '{{!_local.filter.statuses || _local.filter.statuses.length === 0}}' }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.statuses': '{{[]}}' } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.status_all' },
]},
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: "{{(_local.filter.statuses || []).includes('sent')}}" }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.statuses': "{{$event.target.checked ? [...(_local.filter.statuses || []).filter(s => s !== 'sent'), 'sent'] : (_local.filter.statuses || []).filter(s => s !== 'sent')}}" } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.status_sent' },
]},
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: "{{(_local.filter.statuses || []).includes('failed')}}" }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.statuses': "{{$event.target.checked ? [...(_local.filter.statuses || []).filter(s => s !== 'failed'), 'failed'] : (_local.filter.statuses || []).filter(s => s !== 'failed')}}" } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.status_failed' },
]},
{ type: 'basic', name: 'Label', children: [
{ type: 'basic', name: 'Input', props: { type: 'checkbox', className: 'checkbox', checked: "{{(_local.filter.statuses || []).includes('skipped')}}" }, actions: [{ type: 'change', handler: 'setState', params: { target: 'local', 'filter.statuses': "{{$event.target.checked ? [...(_local.filter.statuses || []).filter(s => s !== 'skipped'), 'skipped'] : (_local.filter.statuses || []).filter(s => s !== 'skipped')}}" } }] },
{ type: 'basic', name: 'Span', text: '$t:admin.mail_send_log.filter.status_skipped' },
]},
],
},
],
},
],
},
// filter_actions (검색 + 초기화 버튼)
{
id: 'filter_actions',
type: 'basic',
name: 'Div',
props: { className: 'flex justify-center gap-3 mt-6' },
children: [
{
type: 'basic',
name: 'Button',
props: { type: 'button', className: 'btn btn-primary px-6' },
text: '$t:admin.mail_send_log.filter.search_button',
actions: [{ type: 'click', actionRef: 'searchMailSendLogs' }],
},
{
type: 'basic',
name: 'Button',
props: { type: 'button', className: 'btn btn-secondary px-6' },
text: '$t:admin.mail_send_log.filter.reset_button',
actions: [{
type: 'click',
handler: 'sequence',
actions: [
{ handler: 'setState', params: { target: 'local', filter: { searchType: 'all', search: '', modules: [], statuses: [] } } },
{ handler: 'navigate', params: { path: '/admin/mail-send-logs' } },
],
}],
},
],
},
],
},
// data_table_section
{
id: 'data_table_section',
type: 'basic',
name: 'Div',
children: [
{
id: 'table_header_bar',
type: 'basic',
name: 'Div',
children: [
{
type: 'basic',
name: 'Span',
text: '$t:admin.mail_send_log.pagination.total|count={{mailSendLogs?.data?.pagination?.total || 0}}',
},
{
type: 'basic',
name: 'Div',
children: [
{
type: 'composite',
name: 'Select',
props: {
name: 'sortBy',
className: 'w-32 px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm',
value: "{{query.sort_by ? (query.sort_by + '_' + (query.sort_order || 'desc')) : 'sent_at_desc'}}",
options: [
{ value: 'sent_at_desc', label: '$t:admin.mail_send_log.sort.sent_at_desc' },
{ value: 'sent_at_asc', label: '$t:admin.mail_send_log.sort.sent_at_asc' },
{ value: 'recipient_email_asc', label: '$t:admin.mail_send_log.sort.recipient_email_asc' },
{ value: 'subject_asc', label: '$t:admin.mail_send_log.sort.subject_asc' },
],
},
},
{
type: 'composite',
name: 'Select',
props: {
name: 'perPage',
value: "{{query.per_page || '20'}}",
options: [
{ value: '10', label: '10' },
{ value: '20', label: '20' },
{ value: '50', label: '50' },
{ value: '100', label: '100' },
],
},
},
],
},
],
},
{
id: 'mail_send_log_datagrid',
type: 'composite',
name: 'DataGrid',
props: {
data: '{{mailSendLogs?.data?.data}}',
idField: 'id',
selectable: false,
loading: '{{mailSendLogs?.loading}}',
columns: [
{ field: 'recipient', header: '$t:admin.mail_send_log.table.column.recipient', width: '200px' },
{ field: 'subject', header: '$t:admin.mail_send_log.table.column.subject', width: '250px' },
{ field: 'template_type', header: '$t:admin.mail_send_log.table.column.template_type', width: '120px' },
{ field: 'module', header: '$t:admin.mail_send_log.table.column.module', width: '120px' },
{ field: 'status', header: '$t:admin.mail_send_log.table.column.status', sortable: true, width: '100px' },
{ field: 'sent_at', header: '$t:admin.mail_send_log.table.column.sent_at', sortable: true, width: '160px' },
],
},
},
{
id: 'pagination_section',
type: 'basic',
name: 'Div',
children: [
{
type: 'composite',
name: 'Pagination',
props: {
currentPage: '{{mailSendLogs?.data?.pagination?.current_page || 1}}',
totalPages: '{{mailSendLogs?.data?.pagination?.last_page || 1}}',
},
},
],
},
],
},
],
},
],
};
// ==============================
// 테스트
// ==============================
describe('메일 발송 이력 독립 관리자 메뉴', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
testUtils = createLayoutTest(mailSendLogListLayout, {
auth: {
isAuthenticated: true,
user: { id: 1, name: 'Admin', role: 'super_admin' },
authType: 'admin',
},
locale: 'ko',
componentRegistry: registry,
});
});
afterEach(() => {
testUtils.cleanup();
});
// ========================================================================
// 레이아웃 구조 검증
// ========================================================================
describe('레이아웃 구조 검증', () => {
it('레이아웃 이름이 admin_mail_send_log_list이다', () => {
const info = testUtils.getLayoutInfo();
expect(info.name).toBe('admin_mail_send_log_list');
});
it('권한이 core.mail-send-logs.read로 설정되어 있다', () => {
expect(mailSendLogListLayout.permissions).toEqual(['core.mail-send-logs.read']);
});
it('데이터 소스가 1개 정의되어 있다 (mailSendLogs)', () => {
const dataSources = testUtils.getDataSources();
const ids = dataSources.map((ds: any) => ds.id);
expect(ids).toContain('mailSendLogs');
expect(dataSources).toHaveLength(1);
});
it('데이터 소스 params에 정렬/검색 타입 파라미터가 포함되어 있다', () => {
const dataSources = testUtils.getDataSources();
const ds = dataSources.find((d: any) => d.id === 'mailSendLogs');
expect(ds.params.sort_by).toBeDefined();
expect(ds.params.sort_order).toBeDefined();
expect(ds.params.search_type).toBeDefined();
expect(ds.params['module[]']).toBeDefined();
expect(ds.params['status[]']).toBeDefined();
});
it('state 정의에 필터가 배열/기본값으로 설정되어 있다', () => {
expect(mailSendLogListLayout.state.filter).toEqual({
searchType: 'all',
search: '',
modules: [],
statuses: [],
});
});
});
// ========================================================================
// named_actions 검증
// ========================================================================
describe('named_actions 검증', () => {
it('searchMailSendLogs가 navigate 핸들러로 정의되어 있다', () => {
const namedActions = mailSendLogListLayout.named_actions;
expect(namedActions.searchMailSendLogs).toBeDefined();
expect(namedActions.searchMailSendLogs.handler).toBe('navigate');
expect(namedActions.searchMailSendLogs.params.path).toBe('/admin/mail-send-logs');
expect(namedActions.searchMailSendLogs.params.replace).toBe(true);
});
it('searchMailSendLogs가 배열 필터를 쿼리로 전달한다', () => {
const query = mailSendLogListLayout.named_actions.searchMailSendLogs.params.query;
expect(query.page).toBe(1);
expect(query.search).toBeDefined();
expect(query.search_type).toBeDefined();
expect(query['module[]']).toBeDefined();
expect(query['status[]']).toBeDefined();
});
});
// ========================================================================
// 필터 UI 검증 (searchType Select + 체크박스 필터 + 검색/초기화 버튼)
// ========================================================================
describe('필터 UI 검증', () => {
it('필터 섹션이 card 클래스를 가진다', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
expect(filterSection.id).toBe('filter_section');
expect(filterSection.props.className).toBe('card');
});
it('searchType Select가 4개 옵션을 가진다 (전체/수신자이메일/수신자이름/제목)', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const searchRow = filterSection.children[0]; // search_row
const searchTypeSelect = searchRow.children[0].children[0]; // Select (searchType)
expect(searchTypeSelect.name).toBe('Select');
expect(searchTypeSelect.props.name).toBe('searchType');
expect(searchTypeSelect.props.options).toHaveLength(4);
expect(searchTypeSelect.props.options[0].value).toBe('all');
expect(searchTypeSelect.props.options[1].value).toBe('recipient_email');
expect(searchTypeSelect.props.options[2].value).toBe('recipient_name');
expect(searchTypeSelect.props.options[3].value).toBe('subject');
});
it('검색 입력란이 input w-full pl-10 클래스를 가진다', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const searchRow = filterSection.children[0]; // search_row
const searchInputContainer = searchRow.children[0].children[1]; // Div (relative flex-1)
const searchInput = searchInputContainer.children[1]; // Input
expect(searchInput.name).toBe('Input');
expect(searchInput.props.className).toBe('input w-full pl-10');
});
it('검색 입력란에서 Enter 키 입력 시 actionRef로 searchMailSendLogs가 호출된다 (conditional/namedAction 핸들러 사용 금지)', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const searchRow = filterSection.children[0]; // search_row
const searchInputContainer = searchRow.children[0].children[1]; // Div (relative flex-1)
const searchInput = searchInputContainer.children[1]; // Input
const keydownAction = searchInput.actions.find((a: any) => a.type === 'keydown');
expect(keydownAction).toBeDefined();
// key 속성 + actionRef 패턴 사용 (admin_user_list 표준)
expect(keydownAction.key).toBe('Enter');
expect(keydownAction.actionRef).toBe('searchMailSendLogs');
// 비표준 핸들러 사용 금지 확인
expect(keydownAction.handler).toBeUndefined();
});
it('모듈 필터 행에 라벨과 4개 체크박스 옵션이 있다', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterGrid = filterSection.children[1]; // filter_grid
const moduleFilter = filterGrid.children[0]; // module_filter
expect(moduleFilter.id).toBe('module_filter');
// 라벨
expect(moduleFilter.children[0].text).toBe('$t:admin.mail_send_log.filter.module_label');
// 체크박스 옵션 4개 (전체 + core + board + ecommerce)
const checkboxContainer = moduleFilter.children[1];
expect(checkboxContainer.children).toHaveLength(4);
});
it('모듈 필터 체크박스가 checkbox 타입이다 (radio가 아님)', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterGrid = filterSection.children[1];
const moduleFilter = filterGrid.children[0];
const coreCheckbox = moduleFilter.children[1].children[1].children[0]; // core checkbox Input
expect(coreCheckbox.props.type).toBe('checkbox');
expect(coreCheckbox.props.className).toBe('checkbox');
});
it('상태 필터 행에 라벨과 4개 체크박스 옵션이 있다', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterGrid = filterSection.children[1]; // filter_grid
const statusFilter = filterGrid.children[1]; // status_filter
expect(statusFilter.id).toBe('status_filter');
expect(statusFilter.children[0].text).toBe('$t:admin.mail_send_log.filter.status_label');
const checkboxContainer = statusFilter.children[1];
expect(checkboxContainer.children).toHaveLength(4);
});
it('상태 필터 체크박스가 checkbox 타입이다 (radio가 아님)', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterGrid = filterSection.children[1];
const statusFilter = filterGrid.children[1];
const sentCheckbox = statusFilter.children[1].children[1].children[0]; // sent checkbox Input
expect(sentCheckbox.props.type).toBe('checkbox');
});
it('모듈 체크박스 change 시 setState만 실행 (즉시 검색 안 함)', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterGrid = filterSection.children[1];
const moduleFilter = filterGrid.children[0];
const coreCheckbox = moduleFilter.children[1].children[1].children[0]; // core checkbox Input
const changeAction = coreCheckbox.actions[0];
expect(changeAction.type).toBe('change');
expect(changeAction.handler).toBe('setState');
});
it('검색 버튼이 btn btn-primary이고 actionRef로 searchMailSendLogs를 호출한다', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterActions = filterSection.children[2]; // filter_actions
expect(filterActions.id).toBe('filter_actions');
const searchButton = filterActions.children[0];
expect(searchButton.props.className).toBe('btn btn-primary px-6');
expect(searchButton.actions[0].actionRef).toBe('searchMailSendLogs');
// 비표준 handler 사용 금지 확인
expect(searchButton.actions[0].handler).toBeUndefined();
});
it('초기화 버튼이 btn btn-secondary이고 sequence로 setState + navigate를 실행한다', () => {
const filterSection = mailSendLogListLayout.components[0].children[1];
const filterActions = filterSection.children[2]; // filter_actions
const resetButton = filterActions.children[1];
expect(resetButton.props.className).toBe('btn btn-secondary px-6');
expect(resetButton.text).toBe('$t:admin.mail_send_log.filter.reset_button');
const clickAction = resetButton.actions[0];
expect(clickAction.handler).toBe('sequence');
expect(clickAction.actions[0].handler).toBe('setState');
// 초기화 시 배열로 리셋
expect(clickAction.actions[0].params.filter.modules).toEqual([]);
expect(clickAction.actions[0].params.filter.statuses).toEqual([]);
expect(clickAction.actions[0].params.filter.searchType).toBe('all');
expect(clickAction.actions[1].handler).toBe('navigate');
expect(clickAction.actions[1].params.path).toBe('/admin/mail-send-logs');
});
it('필터 상태를 변경할 수 있다', async () => {
testUtils.mockApi('mailSendLogs', {
response: {
data: {
data: [],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0, from: null, to: null, has_more_pages: false },
},
},
});
await testUtils.render();
testUtils.setState('filter.modules', ['core'], 'local');
expect(testUtils.getState()._local.filter.modules).toEqual(['core']);
testUtils.setState('filter.statuses', ['sent', 'failed'], 'local');
expect(testUtils.getState()._local.filter.statuses).toEqual(['sent', 'failed']);
testUtils.setState('filter.searchType', 'recipient_email', 'local');
expect(testUtils.getState()._local.filter.searchType).toBe('recipient_email');
testUtils.setState('filter.search', 'test@example.com', 'local');
expect(testUtils.getState()._local.filter.search).toBe('test@example.com');
});
});
// ========================================================================
// DataGrid 구조 검증
// ========================================================================
describe('DataGrid 구조 검증', () => {
it('DataGrid가 selectable: false로 설정되어 있다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const datagrid = dataSection.children[1];
expect(datagrid.name).toBe('DataGrid');
expect(datagrid.props.selectable).toBe(false);
});
it('DataGrid에 6개 컬럼이 정의되어 있다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const datagrid = dataSection.children[1];
expect(datagrid.props.columns).toHaveLength(6);
});
it('DataGrid 컬럼이 올바른 필드를 가진다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const datagrid = dataSection.children[1];
const fields = datagrid.props.columns.map((c: any) => c.field);
expect(fields).toEqual(['recipient', 'subject', 'template_type', 'module', 'status', 'sent_at']);
});
it('status와 sent_at 컬럼이 sortable이다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const datagrid = dataSection.children[1];
const statusCol = datagrid.props.columns.find((c: any) => c.field === 'status');
const sentAtCol = datagrid.props.columns.find((c: any) => c.field === 'sent_at');
expect(statusCol.sortable).toBe(true);
expect(sentAtCol.sortable).toBe(true);
});
it('DataGrid 데이터가 mailSendLogs?.data?.data에 바인딩된다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const datagrid = dataSection.children[1];
expect(datagrid.props.data).toBe('{{mailSendLogs?.data?.data}}');
});
});
// ========================================================================
// 정렬/페이지크기 Select 검증
// ========================================================================
describe('정렬/페이지크기 Select 검증', () => {
it('정렬 Select에 4개 옵션이 있다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const headerBar = dataSection.children[0];
const sortSelect = headerBar.children[1].children[0];
expect(sortSelect.props.name).toBe('sortBy');
expect(sortSelect.props.options).toHaveLength(4);
});
it('정렬 Select가 w-32 클래스를 가진다 (배송정책과 일치)', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const headerBar = dataSection.children[0];
const sortSelect = headerBar.children[1].children[0];
expect(sortSelect.props.className).toContain('w-32');
});
it('페이지크기 Select에 4개 옵션이 있다 (10/20/50/100)', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const headerBar = dataSection.children[0];
const perPageSelect = headerBar.children[1].children[1];
expect(perPageSelect.props.name).toBe('perPage');
const values = perPageSelect.props.options.map((o: any) => o.value);
expect(values).toEqual(['10', '20', '50', '100']);
});
});
// ========================================================================
// Pagination 검증
// ========================================================================
describe('Pagination 검증', () => {
it('Pagination 컴포넌트가 mailSendLogs pagination에 바인딩된다', () => {
const dataSection = mailSendLogListLayout.components[0].children[2];
const paginationSection = dataSection.children[2];
const pagination = paginationSection.children[0];
expect(pagination.name).toBe('Pagination');
expect(pagination.props.currentPage).toBe('{{mailSendLogs?.data?.pagination?.current_page || 1}}');
expect(pagination.props.totalPages).toBe('{{mailSendLogs?.data?.pagination?.last_page || 1}}');
});
});
// ========================================================================
// 렌더링 테스트
// ========================================================================
describe('렌더링 테스트', () => {
it('빈 데이터로 렌더링이 성공한다', async () => {
testUtils.mockApi('mailSendLogs', {
response: {
data: {
data: [],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0, from: null, to: null, has_more_pages: false },
},
},
});
await testUtils.render();
expect(true).toBe(true);
});
it('데이터가 있을 때 렌더링이 성공한다', async () => {
testUtils.mockApi('mailSendLogs', {
response: {
data: {
data: [
{
id: 1,
number: 1,
recipient_email: 'test@example.com',
recipient_name: '테스트',
subject: '테스트 메일',
template_type: 'welcome',
module: 'core',
status: 'sent',
sent_at: '2026-03-05 12:00:00',
},
],
pagination: { current_page: 1, last_page: 1, per_page: 20, total: 1, from: 1, to: 1, has_more_pages: false },
},
},
});
await testUtils.render();
expect(true).toBe(true);
});
});
});
@@ -0,0 +1,349 @@
/**
* @file admin-mail-template-list.test.tsx
* @description 환경설정 메일 템플릿 탭 레이아웃 테스트
*
* 테스트 대상:
* - templates/.../partials/admin_settings/_tab_mail_templates.json
* - templates/.../partials/admin_settings/_modal_mail_template_form.json
*
* 검증 항목:
* - 검색 UI 렌더링 (검색 타입 Select, 검색 Input, 검색/초기화 버튼)
* - 페이지네이션 표시 조건
* - 편집 전용 모달 구조
* - 빈 목록 메시지 표시
* - 데이터 경로 (mailTemplates?.data?.data)
*/
import * as fs from 'fs';
import * as path from 'path';
import { describe, it, expect } from 'vitest';
// ==============================
// 실제 레이아웃 JSON 로드
// ==============================
const tabLayoutPath = path.resolve(
__dirname,
'../../layouts/partials/admin_settings/_tab_mail_templates.json'
);
const tabLayout = JSON.parse(fs.readFileSync(tabLayoutPath, 'utf-8'));
const formModalPath = path.resolve(
__dirname,
'../../layouts/partials/admin_settings/_modal_mail_template_form.json'
);
const formModalLayout = JSON.parse(fs.readFileSync(formModalPath, 'utf-8'));
// ==============================
// 헬퍼 함수: 컴포넌트 탐색
// ==============================
function findById(node: any, id: string): any {
if (node.id === id) return node;
const children = node.children ?? [];
for (const child of children) {
const found = findById(child, id);
if (found) return found;
}
return null;
}
function findAllByName(node: any, name: string): any[] {
const results: any[] = [];
if (node.name === name) results.push(node);
const children = node.children ?? [];
for (const child of children) {
results.push(...findAllByName(child, name));
}
return results;
}
// ==============================
// 테스트
// ==============================
describe('환경설정 메일 템플릿 탭 - 검색/페이지네이션/편집', () => {
describe('탭 레이아웃 구조 검증', () => {
it('탭 루트에 if 조건이 mail_templates 탭 확인이다', () => {
expect(tabLayout.if).toBe("{{(_global.activeSettingsTab || query.tab || 'general') === 'mail_templates'}}");
});
it('헤더 영역이 존재한다', () => {
expect(findById(tabLayout, 'mail_templates_header')).not.toBeNull();
});
it('검색 영역이 존재한다', () => {
expect(findById(tabLayout, 'mail_templates_search')).not.toBeNull();
});
it('정보 영역이 존재한다 (총 건수, 페이지당)', () => {
expect(findById(tabLayout, 'mail_templates_info')).not.toBeNull();
});
it('카드 목록이 존재한다', () => {
expect(findById(tabLayout, 'mail_templates_list')).not.toBeNull();
});
it('빈 목록 메시지가 존재한다', () => {
const empty = findById(tabLayout, 'mail_templates_empty');
expect(empty).not.toBeNull();
expect(empty.if).toBe('{{(mailTemplates?.data?.data ?? []).length === 0}}');
});
it('페이지네이션이 항상 표시된다', () => {
const pagination = findById(tabLayout, 'mail_templates_pagination');
expect(pagination).not.toBeNull();
expect(pagination.if).toBeUndefined();
});
});
describe('헤더 영역 검증', () => {
it('헤더에 새 템플릿 버튼이 없다 (등록 기능 제거됨)', () => {
const header = findById(tabLayout, 'mail_templates_header');
const buttons = findAllByName(header, 'Button');
const createButtons = buttons.filter((b: any) =>
b.actions?.some((a: any) => a.handler === 'sequence' &&
a.actions?.some((sa: any) => sa.handler === 'openModal'))
);
expect(createButtons.length).toBe(0);
});
});
describe('검색 영역 검증', () => {
it('검색 타입 Select가 3개 옵션을 가진다 (전체/제목/본문)', () => {
const search = findById(tabLayout, 'mail_templates_search');
const selects = findAllByName(search, 'Select');
expect(selects.length).toBeGreaterThanOrEqual(1);
const options = selects[0].props.options;
expect(options).toHaveLength(3);
expect(options.map((o: any) => o.value)).toEqual(['all', 'subject', 'body']);
});
it('검색 Input이 존재하고 로컬 상태에 바인딩된다', () => {
const search = findById(tabLayout, 'mail_templates_search');
const inputs = findAllByName(search, 'Input');
expect(inputs.length).toBeGreaterThanOrEqual(1);
expect(inputs[0].props.value).toBe("{{_local.mailTemplateFilter?.search || ''}}");
});
it('검색 Input에서 Enter 키 시 navigate(replace:true)로 URL 쿼리 업데이트', () => {
const search = findById(tabLayout, 'mail_templates_search');
const inputs = findAllByName(search, 'Input');
const keydownAction = inputs[0].actions.find((a: any) => a.type === 'keydown');
expect(keydownAction).toBeDefined();
expect(keydownAction.key).toBe('Enter');
expect(keydownAction.handler).toBe('navigate');
expect(keydownAction.params.replace).toBe(true);
expect(keydownAction.params.query.page).toBe(1);
expect(keydownAction.params.query.tab).toBe('mail_templates');
});
it('검색 버튼 클릭 시 navigate(replace:true)로 URL 쿼리 업데이트', () => {
const search = findById(tabLayout, 'mail_templates_search');
const buttons = findAllByName(search, 'Button');
const clickAction = buttons[0].actions[0];
expect(clickAction.handler).toBe('navigate');
expect(clickAction.params.replace).toBe(true);
expect(clickAction.params.query.page).toBe(1);
expect(clickAction.params.query.tab).toBe('mail_templates');
});
it('초기화 버튼이 필터를 기본값으로 리셋하고 navigate로 쿼리 정리', () => {
const search = findById(tabLayout, 'mail_templates_search');
const buttons = findAllByName(search, 'Button');
const resetBtn = buttons[1];
const clickAction = resetBtn.actions[0];
expect(clickAction.handler).toBe('sequence');
const setStateAction = clickAction.actions.find((a: any) => a.handler === 'setState');
expect(setStateAction.params.mailTemplateFilter.search).toBe('');
expect(setStateAction.params.mailTemplateFilter.searchType).toBe('all');
const navigateAction = clickAction.actions.find((a: any) => a.handler === 'navigate');
expect(navigateAction.params.replace).toBe(true);
expect(navigateAction.params.query.tab).toBe('mail_templates');
});
});
describe('카드 목록 검증', () => {
it('iteration source가 mailTemplates?.data?.data 경로를 사용한다', () => {
const card = findById(tabLayout, 'template_card');
expect(card).not.toBeNull();
expect(card.iteration.source).toBe('{{mailTemplates?.data?.data ?? []}}');
expect(card.iteration.item_var).toBe('tpl');
expect(card.iteration.index_var).toBe('tplIdx');
});
it('삭제 버튼이 없다 (삭제 기능 제거됨)', () => {
const deleteBtn = findById(tabLayout, 'btn_delete_{{tplIdx}}');
expect(deleteBtn).toBeNull();
});
it('기본값 복원 버튼에 if 조건이 있다 (is_default=false만)', () => {
const resetBtn = findById(tabLayout, 'btn_reset_{{tplIdx}}');
expect(resetBtn).not.toBeNull();
expect(resetBtn.if).toBe('{{!tpl.is_default}}');
});
it('편집 버튼이 modal_mail_template_form을 연다', () => {
const editBtn = findById(tabLayout, 'btn_edit_{{tplIdx}}');
expect(editBtn).not.toBeNull();
const clickAction = editBtn.actions[0];
const openModal = clickAction.actions.find((a: any) => a.handler === 'openModal');
expect(openModal.target).toBe('modal_mail_template_form');
});
it('편집 버튼이 editingTemplate에 tpl 데이터를 설정한다', () => {
const editBtn = findById(tabLayout, 'btn_edit_{{tplIdx}}');
const clickAction = editBtn.actions[0];
const setState = clickAction.actions.find((a: any) => a.handler === 'setState');
expect(setState.params.editingTemplate).toBe('{{tpl}}');
expect(setState.params.templateErrors).toBeNull();
expect(setState.params.isSaving).toBe(false);
});
});
describe('페이지네이션 검증', () => {
it('Pagination 컴포넌트가 올바른 props를 가진다', () => {
const paginationSection = findById(tabLayout, 'mail_templates_pagination');
const paginations = findAllByName(paginationSection, 'Pagination');
expect(paginations.length).toBe(1);
const pagination = paginations[0];
expect(pagination.props.currentPage).toBe('{{mailTemplates?.data?.pagination?.current_page || 1}}');
expect(pagination.props.totalPages).toBe('{{mailTemplates?.data?.pagination?.last_page || 1}}');
});
it('onPageChange 이벤트가 navigate(replace:true, mergeQuery:true)를 호출한다', () => {
const paginationSection = findById(tabLayout, 'mail_templates_pagination');
const paginations = findAllByName(paginationSection, 'Pagination');
const pageChangeAction = paginations[0].actions.find((a: any) => a.event === 'onPageChange');
expect(pageChangeAction.handler).toBe('navigate');
expect(pageChangeAction.params.replace).toBe(true);
expect(pageChangeAction.params.mergeQuery).toBe(true);
expect(pageChangeAction.params.query.page).toBe('{{$args[0]}}');
});
});
describe('편집 전용 모달 레이아웃 검증', () => {
it('모달 ID가 modal_mail_template_form이다', () => {
expect(formModalLayout.id).toBe('modal_mail_template_form');
});
it('모달이 xl 사이즈이다', () => {
expect(formModalLayout.props.size).toBe('xl');
});
it('모달 타이틀이 편집 전용이다', () => {
expect(formModalLayout.props.title).toContain('edit_modal.title');
});
it('type 입력 필드가 없다 (생성 모드 제거)', () => {
const typeInput = findById(formModalLayout, 'type_input_section');
expect(typeInput).toBeNull();
});
it('type 표시 섹션이 항상 표시된다 (조건 없음)', () => {
const typeDisplay = findById(formModalLayout, 'type_display_section');
expect(typeDisplay).not.toBeNull();
expect(typeDisplay.if).toBeUndefined();
});
it('한국어/영어 탭이 있다', () => {
const buttons = findAllByName(formModalLayout, 'Button');
const langButtons = buttons.filter((b: any) =>
b.text === '한국어' || b.text === 'English'
);
expect(langButtons.length).toBe(2);
});
it('한국어/영어 제목 입력 필드가 있다 (탭별 조건부)', () => {
const subjectKo = findById(formModalLayout, 'subject_ko');
const subjectEn = findById(formModalLayout, 'subject_en');
expect(subjectKo).not.toBeNull();
expect(subjectEn).not.toBeNull();
expect(subjectKo.if).toContain("=== 'ko'");
expect(subjectEn.if).toContain("=== 'en'");
});
it('한국어/영어 본문 HtmlEditor가 있다 (탭별 조건부)', () => {
const bodyKo = findById(formModalLayout, 'body_ko');
const bodyEn = findById(formModalLayout, 'body_en');
expect(bodyKo).not.toBeNull();
expect(bodyEn).not.toBeNull();
const editorsKo = findAllByName(bodyKo, 'HtmlEditor');
const editorsEn = findAllByName(bodyEn, 'HtmlEditor');
expect(editorsKo.length).toBe(1);
expect(editorsEn.length).toBe(1);
});
it('활성화 토글이 있다', () => {
const toggle = findById(formModalLayout, 'is_active_toggle');
expect(toggle).not.toBeNull();
const toggles = findAllByName(toggle, 'Toggle');
expect(toggles.length).toBe(1);
expect(toggles[0].props.checked).toBe('{{$parent._local.editingTemplate?.is_active ?? true}}');
});
it('변수 정보 섹션이 조건부 표시된다', () => {
const variablesInfo = findById(formModalLayout, 'variables_info');
expect(variablesInfo).not.toBeNull();
expect(variablesInfo.if).toBe('{{($parent._local.editingTemplate?.variables ?? []).length > 0}}');
});
it('검증 에러 배너가 조건부 표시된다', () => {
const errorBanner = findById(formModalLayout, 'validation_error_banner');
expect(errorBanner).not.toBeNull();
expect(errorBanner.if).toBe('{{$parent._local.templateErrors}}');
});
it('저장 버튼이 PUT 메서드로 편집 API를 호출한다', () => {
const saveBtn = findById(formModalLayout, 'btn_save');
expect(saveBtn).not.toBeNull();
const clickAction = saveBtn.actions[0];
expect(clickAction.handler).toBe('sequence');
const apiCallAction = clickAction.actions.find((a: any) => a.handler === 'apiCall');
expect(apiCallAction).toBeDefined();
expect(apiCallAction.target).toContain('editingTemplate');
expect(apiCallAction.params.method).toBe('PUT');
});
it('저장 성공 시 모달 닫기 + navigate로 목록 새로고침', () => {
const saveBtn = findById(formModalLayout, 'btn_save');
const apiCallAction = saveBtn.actions[0].actions.find((a: any) => a.handler === 'apiCall');
const onSuccess = apiCallAction.onSuccess;
const closeModal = onSuccess.find((a: any) => a.handler === 'closeModal');
expect(closeModal).toBeDefined();
expect(closeModal.target).toBe('modal_mail_template_form');
const navigateAction = onSuccess.find((a: any) => a.handler === 'navigate');
expect(navigateAction).toBeDefined();
expect(navigateAction.params.replace).toBe(true);
expect(navigateAction.params.mergeQuery).toBe(true);
});
it('저장 실패 시 에러 상태가 설정된다', () => {
const saveBtn = findById(formModalLayout, 'btn_save');
const apiCallAction = saveBtn.actions[0].actions.find((a: any) => a.handler === 'apiCall');
const onError = apiCallAction.onError;
const setStateAction = onError.find((a: any) => a.handler === 'setState');
expect(setStateAction).toBeDefined();
expect(setStateAction.params.templateErrors).toBe('{{error.errors}}');
expect(setStateAction.params.isSaving).toBe(false);
});
it('취소 버튼이 modal_mail_template_form을 닫는다', () => {
const cancelBtn = findById(formModalLayout, 'btn_cancel');
expect(cancelBtn).not.toBeNull();
const clickAction = cancelBtn.actions[0];
expect(clickAction.handler).toBe('closeModal');
expect(clickAction.target).toBe('modal_mail_template_form');
});
});
});
@@ -0,0 +1,477 @@
/**
* @file admin-manual-install-modal.test.tsx
* @description 확장 수동 설치 모달 레이아웃 테스트
*
* 테스트 대상:
* - templates/.../partials/admin_module_list/_modal_manual_install.json
* - templates/.../partials/admin_plugin_list/_modal_manual_install.json
* - templates/.../partials/admin_template_list/_modal_manual_install.json
*
* 검증 항목:
* - 3개 모달 구조 동일성 (TabNavigation underline, 에러 배너, 필드 에러)
* - if 조건 기반 탭 콘텐츠 전환 (file_upload / github)
* - 에러 배너 조건부 렌더링
* - 필드별 에러 표시 (적색 테두리)
* - 설치 버튼 disabled 조건
* - 설치 중 스피너 표시
* - errors.error 상세 에러 메시지 표시
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
import fs from 'fs';
import path from 'path';
// ==============================
// 테스트용 컴포넌트 정의
// ==============================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, onClick, 'data-testid': testId }) => (
<button
type={type as any}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
data-disabled={disabled ? 'true' : 'false'}
>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
size?: string;
}> = ({ name, className }) => (
<i className={`icon-${name} ${className || ''}`} data-testid={`icon-${name}`} data-icon={name} />
);
const TestLabel: React.FC<{
htmlFor?: string;
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ htmlFor, className, children, text }) => (
<label htmlFor={htmlFor} className={className}>
{children || text}
</label>
);
const TestInput: React.FC<{
type?: string;
value?: string;
placeholder?: string;
className?: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
'data-testid'?: string;
}> = ({ type, value, placeholder, className, onChange, 'data-testid': testId }) => (
<input
type={type}
value={value}
placeholder={placeholder}
className={className}
onChange={onChange}
data-testid={testId}
/>
);
const TestFileInput: React.FC<{
accept?: string;
className?: string;
buttonText?: string;
placeholder?: string;
onChange?: (e: any) => void;
}> = ({ accept, className, buttonText, placeholder }) => (
<div data-testid="file-input" className={className} data-accept={accept}>
<span>{buttonText}</span>
<span>{placeholder}</span>
</div>
);
const TestTabNavigation: React.FC<{
tabs?: Array<{ id: string; label: string; iconName?: string }>;
activeTabId?: string;
variant?: string;
onTabChange?: (tabId: string) => void;
children?: React.ReactNode;
}> = ({ tabs, activeTabId, variant, children }) => (
<div data-testid="tab-navigation" data-variant={variant} data-active-tab={activeTabId}>
{tabs?.map((tab) => (
<button key={tab.id} data-testid={`tab-${tab.id}`} data-active={tab.id === activeTabId ? 'true' : 'false'}>
{tab.label}
</button>
))}
{children}
</div>
);
const TestModal: React.FC<{
id?: string;
isOpen?: boolean;
title?: string;
size?: string;
children?: React.ReactNode;
}> = ({ id, isOpen, title, size, children }) => (
isOpen ? (
<div data-testid={`modal-${id}`} role="dialog" data-size={size}>
<h2>{title}</h2>
{children}
</div>
) : null
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// ==============================
// 레지스트리 설정
// ==============================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
FileInput: { component: TestFileInput, metadata: { name: 'FileInput', type: 'basic' } },
TabNavigation: { component: TestTabNavigation, metadata: { name: 'TabNavigation', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
Modal: { component: TestModal, metadata: { name: 'Modal', type: 'composite' } },
};
return registry;
}
// ==============================
// JSON 파일 로드 헬퍼
// ==============================
function loadModalJson(extensionType: 'module' | 'plugin' | 'template'): any {
const basePath = path.resolve(
__dirname,
'../../layouts/partials'
);
const filePath = path.join(basePath, `admin_${extensionType}_list`, '_modal_manual_install.json');
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
// ==============================
// 3개 모달 JSON 구조 동일성 테스트
// ==============================
describe('수동 설치 모달 3개 구조 동일성 검증', () => {
it('3개 모달 모두 TabNavigation variant="underline" 사용', () => {
const types = ['module', 'plugin', 'template'] as const;
for (const type of types) {
const json = loadModalJson(type);
const tabNav = json.children.find((c: any) => c.name === 'TabNavigation');
expect(tabNav, `${type}: TabNavigation이 존재해야 함`).toBeDefined();
expect(tabNav.props.variant, `${type}: variant가 underline이어야 함`).toBe('underline');
}
});
it('3개 모달 모두 동일한 탭 구조 (file_upload, github)', () => {
const types = ['module', 'plugin', 'template'] as const;
for (const type of types) {
const json = loadModalJson(type);
const tabNav = json.children.find((c: any) => c.name === 'TabNavigation');
const tabIds = tabNav.props.tabs.map((t: any) => t.id);
expect(tabIds, `${type}: 탭 ID가 동일해야 함`).toEqual(['file_upload', 'github']);
}
});
it('3개 모달 모두 에러 배너(if 조건) 포함', () => {
const types = ['module', 'plugin', 'template'] as const;
const errorStateKeys: Record<string, string> = {
module: 'moduleInstallError',
plugin: 'pluginInstallError',
template: 'templateInstallError',
};
for (const type of types) {
const json = loadModalJson(type);
const errorBanner = json.children.find(
(c: any) => c.if && c.if.includes(errorStateKeys[type])
);
expect(errorBanner, `${type}: 에러 배너가 존재해야 함`).toBeDefined();
expect(errorBanner.props.className).toContain('bg-red-50');
}
});
it('3개 모달 모두 condition 속성 미사용 (if만 사용)', () => {
const types = ['module', 'plugin', 'template'] as const;
for (const type of types) {
const json = loadModalJson(type);
const jsonStr = JSON.stringify(json);
expect(jsonStr).not.toContain('"condition"');
}
});
it('3개 모달 모두 설치 버튼에 download/spinner 아이콘 포함', () => {
const types = ['module', 'plugin', 'template'] as const;
for (const type of types) {
const json = loadModalJson(type);
const jsonStr = JSON.stringify(json);
expect(jsonStr, `${type}: download 아이콘 존재`).toContain('"download"');
expect(jsonStr, `${type}: spinner 아이콘 존재`).toContain('"spinner"');
}
});
it('3개 모달 모두 FileInput 컴포넌트 사용', () => {
const types = ['module', 'plugin', 'template'] as const;
for (const type of types) {
const json = loadModalJson(type);
const jsonStr = JSON.stringify(json);
expect(jsonStr, `${type}: FileInput 사용`).toContain('"FileInput"');
}
});
it('3개 모달 모두 FileInput onChange에서 $event.target.value 패턴 사용', () => {
const types = ['module', 'plugin', 'template'] as const;
const uploadFileKeys: Record<string, string> = {
module: 'moduleUploadFile',
plugin: 'pluginUploadFile',
template: 'templateUploadFile',
};
for (const type of types) {
const json = loadModalJson(type);
const jsonStr = JSON.stringify(json);
const key = uploadFileKeys[type];
// raw value가 아닌 $event.target.value 패턴 사용 확인
expect(jsonStr, `${type}: ${key}이 $event.target.value 패턴 사용`)
.toContain(`"${key}":"{{$event.target.value}}"`);
expect(jsonStr, `${type}: fileName이 $event.target.value?.name 패턴 사용`)
.toContain('{{$event.target.value?.name}}');
}
});
it('3개 모달 모두 errors.error 상세 에러 메시지 표시 P 요소 포함', () => {
const types = ['module', 'plugin', 'template'] as const;
const errorsStateKeys: Record<string, string> = {
module: 'moduleInstallErrors',
plugin: 'pluginInstallErrors',
template: 'templateInstallErrors',
};
for (const type of types) {
const json = loadModalJson(type);
const jsonStr = JSON.stringify(json);
const key = errorsStateKeys[type];
// errors.error 상세 메시지를 표시하는 P 요소가 존재해야 함
expect(jsonStr, `${type}: ${key}?.error if 조건 존재`).toContain(`_global.${key}?.error`);
expect(jsonStr, `${type}: ${key}.error 텍스트 바인딩 존재`).toContain(`_global.${key}.error`);
}
});
it('3개 모달 모두 필드별 에러 표시(text-red-500) 포함', () => {
const types = ['module', 'plugin', 'template'] as const;
for (const type of types) {
const json = loadModalJson(type);
const jsonStr = JSON.stringify(json);
// 파일 에러 + URL 에러 모두 적색 텍스트
const redErrorCount = (jsonStr.match(/text-red-500 dark:text-red-400 text-xs/g) || []).length;
expect(redErrorCount, `${type}: 필드 에러 2개(file, github_url)`).toBeGreaterThanOrEqual(2);
}
});
});
// ==============================
// 모듈 수동 설치 모달 렌더링 테스트
// ==============================
// Partial JSON의 children을 직접 components로 렌더링 (모달 wrapper 없이)
describe('모듈 수동 설치 모달 렌더링 테스트', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
/**
* partial JSON의 children을 일반 레이아웃 components로 변환하여 렌더링.
* 모달 open/close 메커니즘 없이 콘텐츠만 검증.
*/
const createContentLayout = (globalOverrides: Record<string, any> = {}) => {
const modalJson = loadModalJson('module');
return {
version: '1.0.0',
layout_name: 'module_manual_install_content_test',
initGlobal: {
moduleInstallTab: null,
moduleUploadFile: null,
moduleUploadFileName: null,
moduleGithubUrl: null,
isModuleManualInstalling: false,
moduleInstallError: null,
moduleInstallErrors: null,
...globalOverrides,
},
components: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'modal-content' },
children: modalJson.children,
},
],
};
};
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
testUtils?.cleanup();
});
it('초기 렌더링 시 파일 업로드 탭이 활성화됨', async () => {
testUtils = createLayoutTest(createContentLayout(), { componentRegistry: registry });
await testUtils.render();
// TabNavigation이 렌더링됨
const tabNav = screen.getByTestId('tab-navigation');
expect(tabNav).toBeInTheDocument();
expect(tabNav.getAttribute('data-variant')).toBe('underline');
// FileInput이 보여야 함 (file_upload 탭이 기본)
expect(screen.getByTestId('file-input')).toBeInTheDocument();
});
it('에러 배너는 moduleInstallError가 없으면 렌더링되지 않음', async () => {
testUtils = createLayoutTest(createContentLayout(), { componentRegistry: registry });
await testUtils.render();
// 에러 아이콘(triangle-exclamation)이 없어야 함
expect(screen.queryByTestId('icon-triangle-exclamation')).not.toBeInTheDocument();
});
it('moduleInstallError가 있으면 에러 배너가 렌더링됨', async () => {
testUtils = createLayoutTest(
createContentLayout({ moduleInstallError: '설치에 실패했습니다.' }),
{ componentRegistry: registry }
);
await testUtils.render();
// 에러 아이콘이 보여야 함
expect(screen.getByTestId('icon-triangle-exclamation')).toBeInTheDocument();
});
it('moduleInstallErrors?.file이 있으면 파일 필드에 적색 테두리 적용', async () => {
testUtils = createLayoutTest(
createContentLayout({
moduleInstallErrors: { file: ['ZIP 파일만 업로드 가능합니다.'] },
}),
{ componentRegistry: registry }
);
await testUtils.render();
const fileInput = screen.getByTestId('file-input');
expect(fileInput.className).toContain('border-red-500');
});
it('설치 중(isModuleManualInstalling=true)일 때 spinner 표시, download 숨김', async () => {
testUtils = createLayoutTest(
createContentLayout({
isModuleManualInstalling: true,
moduleUploadFile: { name: 'test.zip' },
}),
{ componentRegistry: registry }
);
await testUtils.render();
// spinner가 보이고 download는 안 보여야 함
expect(screen.getByTestId('icon-spinner')).toBeInTheDocument();
expect(screen.queryByTestId('icon-download')).not.toBeInTheDocument();
});
it('moduleInstallErrors?.error가 있으면 상세 에러 메시지가 표시됨', async () => {
testUtils = createLayoutTest(
createContentLayout({
moduleInstallError: '설치에 실패했습니다.',
moduleInstallErrors: { error: '필수 의존성 sirsoft-ecommerce (module)이 충족되지 않았습니다.' },
}),
{ componentRegistry: registry }
);
await testUtils.render();
// 에러 배너가 보여야 함
expect(screen.getByTestId('icon-triangle-exclamation')).toBeInTheDocument();
// 상세 에러 메시지가 표시되어야 함
expect(screen.getByText('필수 의존성 sirsoft-ecommerce (module)이 충족되지 않았습니다.')).toBeInTheDocument();
// 일반 메시지도 함께 표시됨
expect(screen.getByText('설치에 실패했습니다.')).toBeInTheDocument();
});
it('moduleInstallErrors?.error가 없으면 상세 에러 메시지 P 요소가 렌더링되지 않음', async () => {
testUtils = createLayoutTest(
createContentLayout({
moduleInstallError: '설치에 실패했습니다.',
moduleInstallErrors: { file: ['ZIP 파일만 업로드 가능합니다.'] },
}),
{ componentRegistry: registry }
);
await testUtils.render();
// 일반 에러는 표시
expect(screen.getByText('설치에 실패했습니다.')).toBeInTheDocument();
// errors.error가 없으므로 상세 메시지는 미표시
expect(screen.queryByText('필수 의존성')).not.toBeInTheDocument();
});
it('설치 중이 아닐 때 download 아이콘 표시, spinner 숨김', async () => {
testUtils = createLayoutTest(
createContentLayout({ moduleUploadFile: { name: 'test.zip' } }),
{ componentRegistry: registry }
);
await testUtils.render();
expect(screen.getByTestId('icon-download')).toBeInTheDocument();
expect(screen.queryByTestId('icon-spinner')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,406 @@
/**
* @file admin-menu-list-abilities.test.tsx
* @description 메뉴 관리 페이지 abilities 기반 UI 비활성화 렌더링 테스트
*
* 테스트 대상:
* - abilities.can_create=false → 메뉴 추가 버튼 disabled
* - abilities.can_update=false → SortableMenuList enableDrag=false, toggleDisabled=true
* - abilities.can_delete=false → 삭제 버튼 disabled
* - abilities.can_update=false → 편집 버튼 disabled
* - 모든 abilities=true → 모든 UI 활성 상태
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
className?: string;
disabled?: boolean;
children?: React.ReactNode;
text?: string;
onClick?: () => void;
'data-testid'?: string;
}> = ({ className, disabled, children, text, onClick, 'data-testid': testId }) => (
<button className={className} disabled={disabled} onClick={onClick} data-testid={testId}>
{children || text}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestH3: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h3 className={className}>{children || text}</h3>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={className} data-icon={name} />
);
const TestPageHeader: React.FC<{
title?: string;
description?: string;
children?: React.ReactNode;
}> = ({ title, description, children }) => (
<div data-testid="page-header">
{title && <h1>{title}</h1>}
{description && <p>{description}</p>}
{children}
</div>
);
const TestSortableMenuList: React.FC<{
items?: any[];
selectedId?: number | null;
enableDrag?: boolean;
toggleDisabled?: boolean;
className?: string;
'data-testid'?: string;
}> = ({ items, enableDrag, toggleDisabled, 'data-testid': testId }) => (
<div
data-testid={testId || 'sortable-menu-list'}
data-enable-drag={String(enableDrag ?? true)}
data-toggle-disabled={String(toggleDisabled ?? false)}
data-items-count={String((items ?? []).length)}
/>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
PageHeader: { component: TestPageHeader, metadata: { name: 'PageHeader', type: 'composite' } },
SortableMenuList: { component: TestSortableMenuList, metadata: { name: 'SortableMenuList', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 메뉴 추가 버튼 + SortableMenuList가 포함된 간략화 레이아웃
const menuListLayout = {
version: '1.0.0',
layout_name: 'test_admin_menu_list',
data_sources: [
{
id: 'menus',
type: 'api',
endpoint: '/api/admin/menus',
method: 'GET',
auto_fetch: true,
auth_required: true,
params: { with_children: true, hierarchical: true },
fallback: { data: [] },
},
],
state: {
selectedMenuId: null,
selectedMenu: null,
panelMode: 'view',
},
components: [
{
id: 'menu_list_content',
type: 'basic',
name: 'Div',
children: [
{
id: 'page_header',
type: 'composite',
name: 'PageHeader',
props: {
title: '메뉴 관리',
},
children: [
{
id: 'add_menu_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{!(menus?.data?.abilities?.can_create)}}',
className: 'flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed',
'data-testid': 'add-menu-button',
},
children: [
{
type: 'basic',
name: 'Span',
text: '메뉴 추가',
},
],
},
],
},
{
id: 'main_grid',
type: 'basic',
name: 'Div',
children: [
{
id: 'sortable_menu_list',
type: 'composite',
name: 'SortableMenuList',
props: {
items: '{{menus?.data?.data ?? []}}',
selectedId: '{{_global.selectedMenuId}}',
enableDrag: '{{menus?.data?.abilities?.can_update ?? false}}',
toggleDisabled: '{{!(menus?.data?.abilities?.can_update ?? false)}}',
'data-testid': 'sortable-menu-list',
},
},
],
},
],
},
],
};
// 편집/삭제 버튼이 포함된 뷰 패널 레이아웃
const viewPanelLayout = {
version: '1.0.0',
layout_name: 'test_admin_menu_view_panel',
data_sources: [
{
id: 'menus',
type: 'api',
endpoint: '/api/admin/menus',
method: 'GET',
auto_fetch: true,
auth_required: true,
fallback: { data: [] },
},
],
state: {
selectedMenuId: 1,
selectedMenu: { id: 1, name: '테스트', extension_type: null },
panelMode: 'view',
},
components: [
{
id: 'view_panel',
type: 'basic',
name: 'Div',
children: [
{
id: 'edit_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{!(menus?.data?.abilities?.can_update)}}',
className: 'border disabled:opacity-50 disabled:cursor-not-allowed',
'data-testid': 'edit-button',
},
text: '편집',
},
{
id: 'delete_button',
type: 'basic',
name: 'Button',
if: "{{_global.selectedMenu?.extension_type !== 'core'}}",
props: {
disabled: '{{!(menus?.data?.abilities?.can_delete)}}',
className: 'text-red-600 disabled:opacity-50 disabled:cursor-not-allowed',
'data-testid': 'delete-button',
},
text: '삭제',
},
],
},
],
};
// Mock API 응답 생성 헬퍼
function createMenusResponse(abilities: { can_create: boolean; can_update: boolean; can_delete: boolean }) {
return {
success: true,
data: {
data: [
{ id: 1, name: '대시보드', slug: 'dashboard', url: '/admin', icon: 'home', is_active: true },
],
abilities,
},
};
}
describe('메뉴 관리 페이지 - abilities 기반 UI 비활성화', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('모든 권한이 있는 사용자 (abilities 모두 true)', () => {
it('메뉴 추가 버튼이 활성화됨', async () => {
const testUtils = createLayoutTest(menuListLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: true, can_update: true, can_delete: true }),
});
await testUtils.render();
const addButton = screen.getByTestId('add-menu-button');
expect(addButton).not.toBeDisabled();
testUtils.cleanup();
});
it('SortableMenuList에 enableDrag=true, toggleDisabled=false 전달', async () => {
const testUtils = createLayoutTest(menuListLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: true, can_update: true, can_delete: true }),
});
await testUtils.render();
const menuList = screen.getByTestId('sortable-menu-list');
expect(menuList.getAttribute('data-enable-drag')).toBe('true');
expect(menuList.getAttribute('data-toggle-disabled')).toBe('false');
testUtils.cleanup();
});
it('편집/삭제 버튼이 활성화됨', async () => {
const testUtils = createLayoutTest(viewPanelLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: true, can_update: true, can_delete: true }),
});
await testUtils.render();
const editButton = screen.getByTestId('edit-button');
const deleteButton = screen.getByTestId('delete-button');
expect(editButton).not.toBeDisabled();
expect(deleteButton).not.toBeDisabled();
testUtils.cleanup();
});
});
describe('읽기 전용 사용자 (abilities 모두 false)', () => {
it('메뉴 추가 버튼이 비활성화됨', async () => {
const testUtils = createLayoutTest(menuListLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: false, can_update: false, can_delete: false }),
});
await testUtils.render();
const addButton = screen.getByTestId('add-menu-button');
expect(addButton).toBeDisabled();
testUtils.cleanup();
});
it('SortableMenuList에 enableDrag=false, toggleDisabled=true 전달', async () => {
const testUtils = createLayoutTest(menuListLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: false, can_update: false, can_delete: false }),
});
await testUtils.render();
const menuList = screen.getByTestId('sortable-menu-list');
expect(menuList.getAttribute('data-enable-drag')).toBe('false');
expect(menuList.getAttribute('data-toggle-disabled')).toBe('true');
testUtils.cleanup();
});
it('편집 버튼이 비활성화됨', async () => {
const testUtils = createLayoutTest(viewPanelLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: false, can_update: false, can_delete: false }),
});
await testUtils.render();
const editButton = screen.getByTestId('edit-button');
expect(editButton).toBeDisabled();
testUtils.cleanup();
});
it('삭제 버튼이 비활성화됨', async () => {
const testUtils = createLayoutTest(viewPanelLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: false, can_update: false, can_delete: false }),
});
await testUtils.render();
const deleteButton = screen.getByTestId('delete-button');
expect(deleteButton).toBeDisabled();
testUtils.cleanup();
});
});
describe('부분 권한 사용자 (can_create만 true)', () => {
it('메뉴 추가 버튼은 활성화, 편집/삭제는 비활성화', async () => {
const testUtils = createLayoutTest(viewPanelLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: true, can_update: false, can_delete: false }),
});
await testUtils.render();
const editButton = screen.getByTestId('edit-button');
const deleteButton = screen.getByTestId('delete-button');
expect(editButton).toBeDisabled();
expect(deleteButton).toBeDisabled();
testUtils.cleanup();
});
it('드래그 비활성화, 토글 비활성화', async () => {
const testUtils = createLayoutTest(menuListLayout);
testUtils.mockApi('menus', {
response: createMenusResponse({ can_create: true, can_update: false, can_delete: false }),
});
await testUtils.render();
const addButton = screen.getByTestId('add-menu-button');
expect(addButton).not.toBeDisabled();
const menuList = screen.getByTestId('sortable-menu-list');
expect(menuList.getAttribute('data-enable-drag')).toBe('false');
expect(menuList.getAttribute('data-toggle-disabled')).toBe('true');
testUtils.cleanup();
});
});
});
@@ -0,0 +1,919 @@
/**
* @file admin-module-update.test.tsx
* @description 모듈 업데이트 UI 레이아웃 테스트
*
* 테스트 대상:
* - admin_module_list.json: updating 배지, 업데이트 확인 버튼, 행별 업데이트 버튼
* - partials/admin_module_list/_modal_update.json: 업데이트 확인 모달
*
* 검증 항목:
* - updating 상태 배지 렌더링
* - update_available 배지 렌더링
* - "업데이트 확인" 상단 버튼 존재 + 아이콘 전환
* - 행별 업데이트 버튼 조건부 렌더링
* - 모달 구조: 버전 정보, update_source, changelog 링크, 확인/취소 버튼
* - 모달 버튼 disabled 상태 (업데이트 진행 중)
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// ==============================
// 테스트용 컴포넌트 정의
// ==============================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, onClick, 'data-testid': testId }) => (
<button
type={type as any}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={`icon-${name} ${className || ''}`} data-testid={`icon-${name}`} data-icon={name} data-size={size} />
);
const TestA: React.FC<{
href?: string;
target?: string;
className?: string;
children?: React.ReactNode;
}> = ({ href, target, className, children }) => (
<a href={href} target={target} className={className} data-testid="link">{children}</a>
);
const TestModal: React.FC<{
id?: string;
isOpen?: boolean;
title?: string;
size?: string;
children?: React.ReactNode;
}> = ({ id, isOpen, title, size, children }) => (
isOpen ? (
<div data-testid={`modal-${id}`} role="dialog" data-size={size}>
<h2>{title}</h2>
{children}
</div>
) : null
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// ==============================
// 레지스트리 설정
// ==============================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
A: { component: TestA, metadata: { name: 'A', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
Modal: { component: TestModal, metadata: { name: 'Modal', type: 'composite' } },
};
return registry;
}
// ==============================
// 공통 번역 키
// ==============================
const translations = {
admin: {
modules: {
update_available: '업데이트 필요',
version_available: '(v{{version}} 사용 가능)',
updating: '업데이트 중...',
update_success: '모듈이 성공적으로 업데이트되었습니다.',
check_updates_success: '업데이트 확인 완료 ({{count}}개 업데이트 가능)',
check_updates_no_updates: '모든 모듈이 최신 상태입니다.',
status: {
active: '활성화',
inactive: '비활성화',
not_installed: '미설치',
installing: '설치 중',
uninstalling: '제거 중',
updating: '업데이트 중',
},
actions: {
update: '업데이트',
check_updates: '업데이트 확인',
},
modals: {
update_title: '모듈 업데이트 확인',
update_confirm: '{{name}} 모듈을 업데이트하시겠습니까?',
update_version_info: '{{from}} → {{to}}',
update_source_github: 'GitHub에서 다운로드',
update_source_bundled: '선탑재 패키지에서 설치',
view_changelog: '변경사항 보기',
field_version: '버전',
field_vendor: '개발자',
},
},
},
common: {
cancel: '취소',
},
};
// ==============================
// 0. 레이아웃 JSON auth_required 검증
// ==============================
describe('모듈 업데이트 - check-updates auth_required 검증', () => {
it('check-updates apiCall에 auth_required: true가 설정되어 있다', async () => {
const fs = await import('fs');
const path = await import('path');
const layoutPath = path.resolve(__dirname, '../../layouts/admin_module_list.json');
const layoutJson = JSON.parse(fs.readFileSync(layoutPath, 'utf-8'));
// sequence 내부의 apiCall 중 check-updates 찾기
function findCheckUpdatesApiCall(actions: any[]): any {
for (const action of actions) {
if (action.handler === 'apiCall' && action.target?.includes('check-updates')) {
return action;
}
if (action.handler === 'sequence' && action.actions) {
const found = findCheckUpdatesApiCall(action.actions);
if (found) return found;
}
}
return null;
}
// 컴포넌트 트리에서 actions를 가진 요소 탐색
function findActionsInComponents(components: any[]): any[] {
const allActions: any[] = [];
for (const comp of components) {
if (comp.actions) {
for (const actionGroup of comp.actions) {
if (actionGroup.handler === 'sequence' && actionGroup.actions) {
allActions.push(...actionGroup.actions);
} else {
allActions.push(actionGroup);
}
}
}
if (comp.children) {
allActions.push(...findActionsInComponents(comp.children));
}
}
return allActions;
}
// slots.content 또는 components에서 탐색
const components = layoutJson.slots?.content ?? layoutJson.components ?? [];
const allActions = findActionsInComponents(components);
const checkUpdatesAction = findCheckUpdatesApiCall(allActions);
expect(checkUpdatesAction).not.toBeNull();
expect(checkUpdatesAction.auth_required).toBe(true);
});
});
// ==============================
// 1. 상태 배지 테스트
// ==============================
describe('모듈 업데이트 - 상태 배지', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
function createBadgeLayout(row: Record<string, any>) {
return {
version: '1.0.0',
layout_name: 'module_update_badge_test',
initGlobal: { row },
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{
type: 'basic',
name: 'Span',
if: "{{_global.row.status == 'updating'}}",
props: {
className: 'px-2 py-0.5 text-xs bg-purple-100 dark:bg-purple-900 text-purple-600 dark:text-purple-400 rounded',
},
text: '$t:admin.modules.status.updating',
},
{
type: 'basic',
name: 'Span',
if: "{{_global.row.update_available && _global.row.status != 'updating' && _global.row.status != 'uninstalled'}}",
props: {
className: 'px-2 py-0.5 text-xs bg-amber-100 dark:bg-amber-900 text-amber-600 dark:text-amber-400 rounded',
},
text: '$t:admin.modules.update_available',
},
{
type: 'basic',
name: 'Span',
if: "{{_global.row.update_available && _global.row.latest_version && _global.row.status != 'updating' && _global.row.status != 'uninstalled'}}",
props: {
className: 'text-xs text-gray-500 dark:text-gray-400',
},
text: "$t:admin.modules.version_available|version={{_global.row.latest_version ?? ''}}",
},
],
},
],
};
}
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
it('updating 상태일 때 보라색 배지가 표시된다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'updating', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
const badges = screen.getAllByText('업데이트 중');
expect(badges.length).toBeGreaterThanOrEqual(1);
const badge = badges[0];
expect(badge.className).toContain('bg-purple-100');
expect(badge.className).toContain('dark:bg-purple-900');
});
it('update_available일 때 (updating 아닌) 황색 배지가 표시된다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
const badges = screen.getAllByText('업데이트 필요');
expect(badges.length).toBeGreaterThanOrEqual(1);
const badge = badges[0];
expect(badge.className).toContain('bg-amber-100');
});
it('update_available=false일 때 업데이트 배지가 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: false }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByText('업데이트 필요')).toBeNull();
expect(screen.queryByText('업데이트 중')).toBeNull();
});
it('uninstalled 상태에서는 update_available이어도 배지가 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'uninstalled', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByText('업데이트 필요')).toBeNull();
});
it('update_available이고 latest_version이 있으면 버전 정보가 표시된다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: true, latest_version: '2.0.0' }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.getByText('(v2.0.0 사용 가능)')).toBeTruthy();
});
it('update_available이지만 latest_version이 null이면 버전 정보가 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: true, latest_version: null }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByText(/사용 가능/)).toBeNull();
});
});
// ==============================
// 2. 업데이트 확인 버튼 테스트
// ==============================
describe('모듈 업데이트 - 업데이트 확인 버튼', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
const checkUpdatesButtonLayout = {
version: '1.0.0',
layout_name: 'module_check_updates_button_test',
initGlobal: {
isCheckingUpdates: false,
},
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{
id: 'check_updates_button',
type: 'basic',
name: 'Button',
props: {
className: 'flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed',
disabled: '{{_global.isCheckingUpdates}}',
type: 'button',
'data-testid': 'check-updates-btn',
},
children: [
{
type: 'basic',
name: 'Icon',
if: '{{!_global.isCheckingUpdates}}',
props: { name: 'refresh', size: 'sm' },
},
{
type: 'basic',
name: 'Icon',
if: '{{_global.isCheckingUpdates}}',
props: { name: 'spinner', size: 'sm', className: 'animate-spin' },
},
{
type: 'basic',
name: 'Span',
text: '$t:admin.modules.actions.check_updates',
},
],
},
],
},
],
};
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
it('업데이트 확인 버튼이 렌더링된다', async () => {
testUtils = createLayoutTest(checkUpdatesButtonLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
});
await testUtils.render();
expect(screen.getByText('업데이트 확인')).toBeTruthy();
});
it('로딩 중이 아닐 때 refresh 아이콘이 표시된다', async () => {
testUtils = createLayoutTest(checkUpdatesButtonLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
});
await testUtils.render();
expect(screen.getByTestId('icon-refresh')).toBeTruthy();
expect(screen.queryByTestId('icon-spinner')).toBeNull();
});
it('isCheckingUpdates=true일 때 spinner 아이콘이 표시되고 버튼이 disabled된다', async () => {
const loadingLayout = {
...checkUpdatesButtonLayout,
initGlobal: { isCheckingUpdates: true },
};
testUtils = createLayoutTest(loadingLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
});
await testUtils.render();
expect(screen.getByTestId('icon-spinner')).toBeTruthy();
expect(screen.queryByTestId('icon-refresh')).toBeNull();
const btn = screen.getByTestId('check-updates-btn');
expect(btn).toHaveProperty('disabled', true);
});
});
// ==============================
// 3. 행별 업데이트 버튼 테스트
// ==============================
describe('모듈 업데이트 - 행별 업데이트 버튼', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
function createRowButtonLayout(row: Record<string, any>) {
return {
version: '1.0.0',
layout_name: 'module_row_update_button_test',
initGlobal: { row },
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{
id: 'update_button',
type: 'basic',
name: 'Button',
if: "{{_global.row.update_available && _global.row.status != 'updating' && _global.row.status != 'uninstalled'}}",
props: {
className: 'flex items-center gap-1.5 px-3 py-1.5 text-sm bg-amber-500 text-white rounded-lg',
type: 'button',
'data-testid': 'row-update-btn',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'arrow-up-circle', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: '$t:admin.modules.actions.update',
},
],
},
],
},
],
};
}
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
it('update_available && active 상태에서 업데이트 버튼이 표시된다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'active', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.getByTestId('row-update-btn')).toBeTruthy();
expect(screen.getByText('업데이트')).toBeTruthy();
expect(screen.getByTestId('icon-arrow-up-circle')).toBeTruthy();
});
it('update_available=false일 때 업데이트 버튼이 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'active', update_available: false }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByTestId('row-update-btn')).toBeNull();
});
it('updating 상태에서는 업데이트 버튼이 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'updating', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByTestId('row-update-btn')).toBeNull();
});
it('uninstalled 상태에서는 업데이트 버튼이 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'uninstalled', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByTestId('row-update-btn')).toBeNull();
});
});
// ==============================
// 4. 업데이트 모달 테스트
// ==============================
describe('모듈 업데이트 - 업데이트 모달', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
const updateModalLayout = {
version: '1.0.0',
layout_name: 'module_update_modal_test',
initGlobal: {
selectedModule: {
identifier: 'sirsoft-board',
name: '게시판',
version: '1.0.0',
latest_version: '1.1.0',
update_source: 'github',
github_changelog_url: 'https://github.com/gnuboard/sirsoft-board/releases',
},
isModuleUpdating: false,
},
modals: [
{
id: 'module_update_modal',
type: 'composite',
name: 'Modal',
props: {
title: '$t:admin.modules.modals.update_title',
size: 'small',
},
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'py-2' },
children: [
{
type: 'basic',
name: 'P',
props: { className: 'text-gray-700 dark:text-gray-300' },
text: "$t:admin.modules.modals.update_confirm|name={{_global.selectedModule.name ?? ''}}",
},
{
type: 'basic',
name: 'Div',
props: { className: 'mt-3 p-3 bg-gray-50 dark:bg-gray-800 border rounded-lg space-y-2' },
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2 text-sm' },
children: [
{
type: 'basic',
name: 'Span',
props: { className: 'text-gray-500' },
text: '$t:admin.modules.modals.field_version',
},
{
type: 'basic',
name: 'Span',
props: { className: 'font-medium text-gray-900 dark:text-white' },
text: "$t:admin.modules.modals.update_version_info|from={{_global.selectedModule.version ?? ''}}|to={{_global.selectedModule.latest_version ?? ''}}",
},
],
},
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2 text-sm' },
children: [
{
type: 'basic',
name: 'Span',
props: { className: 'text-gray-500' },
text: '$t:admin.modules.modals.field_vendor',
},
{
type: 'basic',
name: 'Span',
props: { className: 'text-gray-700' },
text: "{{_global.selectedModule.update_source === 'github' ? '$t:admin.modules.modals.update_source_github' : '$t:admin.modules.modals.update_source_bundled'}}",
},
],
},
],
},
{
type: 'basic',
name: 'Div',
if: '{{_global.selectedModule.github_changelog_url}}',
props: { className: 'mt-3' },
children: [
{
type: 'basic',
name: 'A',
props: {
href: '{{_global.selectedModule.github_changelog_url}}',
target: '_blank',
className: 'inline-flex items-center gap-1.5 text-sm text-blue-600',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'external-link', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: '$t:admin.modules.modals.view_changelog',
},
],
},
],
},
],
},
{
type: 'basic',
name: 'Div',
props: { className: 'flex justify-end gap-3 mt-6' },
children: [
{
type: 'basic',
name: 'Button',
props: {
className: 'px-4 py-2 bg-white dark:bg-gray-800 border rounded-lg disabled:opacity-50',
disabled: '{{_global.isModuleUpdating}}',
'data-testid': 'cancel-btn',
},
children: [
{ type: 'basic', name: 'Span', text: '$t:common.cancel' },
],
},
{
type: 'basic',
name: 'Button',
props: {
className: 'flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg disabled:opacity-50',
disabled: '{{_global.isModuleUpdating}}',
'data-testid': 'confirm-update-btn',
},
children: [
{
type: 'basic',
name: 'Icon',
if: '{{_global.isModuleUpdating}}',
props: { name: 'spinner', className: 'w-4 h-4 animate-spin' },
},
{
type: 'basic',
name: 'Span',
text: "{{_global.isModuleUpdating ? '$t:admin.modules.updating' : '$t:admin.modules.actions.update'}}",
},
],
},
],
},
],
},
],
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{ type: 'basic', name: 'Span', text: '모듈 관리 페이지' },
],
},
],
};
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
describe('레이아웃 구조 검증', () => {
it('레이아웃 정보가 올바르게 로드된다', () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
const info = testUtils.getLayoutInfo();
expect(info.name).toBe('module_update_modal_test');
expect(info.version).toBe('1.0.0');
});
it('초기 전역 상태가 올바르게 설정된다', () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
const state = testUtils.getState();
expect(state._global.selectedModule).toEqual({
identifier: 'sirsoft-board',
name: '게시판',
version: '1.0.0',
latest_version: '1.1.0',
update_source: 'github',
github_changelog_url: 'https://github.com/gnuboard/sirsoft-board/releases',
});
expect(state._global.isModuleUpdating).toBe(false);
});
it('모달 크기가 small로 설정되어 있다', () => {
const modal = updateModalLayout.modals[0];
expect(modal.props.size).toBe('small');
});
});
describe('모달 열기/닫기', () => {
it('업데이트 모달을 열고 닫을 수 있다', async () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
await testUtils.render();
testUtils.openModal('module_update_modal');
expect(testUtils.getModalStack()).toContain('module_update_modal');
testUtils.closeModal();
expect(testUtils.getModalStack()).not.toContain('module_update_modal');
});
});
describe('모달 콘텐츠 구조 검증', () => {
it('모달 타이틀이 업데이트 확인으로 설정되어 있다', () => {
const modal = updateModalLayout.modals[0];
expect(modal.props.title).toBe('$t:admin.modules.modals.update_title');
});
it('모달에 업데이트 확인 메시지가 포함되어 있다', () => {
const modal = updateModalLayout.modals[0];
// children[0] = py-2 Div > children[0] = P (confirm message)
const confirmP = modal.children[0].children[0];
expect(confirmP.text).toContain('$t:admin.modules.modals.update_confirm');
expect(confirmP.text).toContain('_global.selectedModule.name');
});
it('모달에 버전 정보가 포함되어 있다 (from → to)', () => {
const modal = updateModalLayout.modals[0];
// children[0] > children[1] = version info Div > children[0] = version row Div > children[1] = Span
const versionRow = modal.children[0].children[1].children[0];
const versionLabel = versionRow.children[0];
const versionValue = versionRow.children[1];
expect(versionLabel.text).toBe('$t:admin.modules.modals.field_version');
expect(versionValue.text).toContain('$t:admin.modules.modals.update_version_info');
expect(versionValue.text).toContain('_global.selectedModule.version');
expect(versionValue.text).toContain('_global.selectedModule.latest_version');
});
it('모달에 update_source 표시가 포함되어 있다', () => {
const modal = updateModalLayout.modals[0];
// children[0] > children[1] = info Div > children[1] = vendor row
const vendorRow = modal.children[0].children[1].children[1];
const vendorLabel = vendorRow.children[0];
const vendorValue = vendorRow.children[1];
expect(vendorLabel.text).toBe('$t:admin.modules.modals.field_vendor');
expect(vendorValue.text).toContain('update_source_github');
});
it('모달에 changelog 링크가 조건부로 포함되어 있다', () => {
const modal = updateModalLayout.modals[0];
// children[0] > children[2] = changelog Div (if 조건)
const changelogDiv = modal.children[0].children[2];
expect(changelogDiv.if).toBe('{{_global.selectedModule.github_changelog_url}}');
const linkA = changelogDiv.children[0];
expect(linkA.name).toBe('A');
expect(linkA.props.target).toBe('_blank');
expect(linkA.props.href).toContain('_global.selectedModule.github_changelog_url');
});
it('changelog URL이 없으면 조건에 의해 렌더링되지 않는다', () => {
// github_changelog_url이 null이면 if 조건이 falsy
const noChangelogState = { ...updateModalLayout.initGlobal.selectedModule, github_changelog_url: null };
expect(noChangelogState.github_changelog_url).toBeNull();
// if="{{_global.selectedModule.github_changelog_url}}" → null은 falsy
const modal = updateModalLayout.modals[0];
const changelogDiv = modal.children[0].children[2];
expect(changelogDiv.if).toBe('{{_global.selectedModule.github_changelog_url}}');
});
});
describe('버튼 구조 및 상태 검증', () => {
it('취소/확인 버튼이 모달에 정의되어 있다', () => {
const modal = updateModalLayout.modals[0];
// children[1] = 버튼 영역 Div > children = [cancel, confirm]
const buttonsDiv = modal.children[1];
expect(buttonsDiv.children).toHaveLength(2);
const cancelBtn = buttonsDiv.children[0];
const confirmBtn = buttonsDiv.children[1];
// 취소 버튼
expect(cancelBtn.name).toBe('Button');
expect(cancelBtn.props.disabled).toBe('{{_global.isModuleUpdating}}');
expect(cancelBtn.children[0].text).toBe('$t:common.cancel');
// 확인 버튼
expect(confirmBtn.name).toBe('Button');
expect(confirmBtn.props.disabled).toBe('{{_global.isModuleUpdating}}');
});
it('확인 버튼에 스피너 조건부 렌더링이 설정되어 있다', () => {
const modal = updateModalLayout.modals[0];
const confirmBtn = modal.children[1].children[1];
// spinner Icon (if: isModuleUpdating)
const spinnerIcon = confirmBtn.children[0];
expect(spinnerIcon.name).toBe('Icon');
expect(spinnerIcon.if).toBe('{{_global.isModuleUpdating}}');
expect(spinnerIcon.props.name).toBe('spinner');
// 텍스트 (ternary: updating → '업데이트 중...' / '업데이트')
const textSpan = confirmBtn.children[1];
expect(textSpan.text).toContain('_global.isModuleUpdating');
expect(textSpan.text).toContain('$t:admin.modules.updating');
expect(textSpan.text).toContain('$t:admin.modules.actions.update');
});
it('isModuleUpdating 상태가 올바르게 변경될 수 있다', async () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
await testUtils.render();
// 초기값 false
let state = testUtils.getState();
expect(state._global.isModuleUpdating).toBe(false);
// true로 변경
testUtils.setState('isModuleUpdating', true, 'global');
state = testUtils.getState();
expect(state._global.isModuleUpdating).toBe(true);
// 완료 후 false로 복원
testUtils.setState('isModuleUpdating', false, 'global');
testUtils.setState('selectedModule', null, 'global');
state = testUtils.getState();
expect(state._global.isModuleUpdating).toBe(false);
expect(state._global.selectedModule).toBeNull();
});
});
});
@@ -0,0 +1,905 @@
/**
* @file admin-plugin-update.test.tsx
* @description 플러그인 업데이트 UI 레이아웃 테스트
*
* 테스트 대상:
* - admin_plugin_list.json: updating 배지, 업데이트 확인 버튼, 행별 업데이트 버튼
* - partials/admin_plugin_list/_modal_update.json: 업데이트 확인 모달
*
* 검증 항목:
* - updating 상태 배지 렌더링
* - update_available 배지 렌더링
* - "업데이트 확인" 상단 버튼 존재 + 아이콘 전환
* - 행별 업데이트 버튼 조건부 렌더링
* - 모달 구조: 버전 정보, update_source, changelog 링크, 확인/취소 버튼
* - 모달 버튼 disabled 상태 (업데이트 진행 중)
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// ==============================
// 테스트용 컴포넌트 정의
// ==============================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, onClick, 'data-testid': testId }) => (
<button
type={type as any}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={`icon-${name} ${className || ''}`} data-testid={`icon-${name}`} data-icon={name} data-size={size} />
);
const TestA: React.FC<{
href?: string;
target?: string;
className?: string;
children?: React.ReactNode;
}> = ({ href, target, className, children }) => (
<a href={href} target={target} className={className} data-testid="link">{children}</a>
);
const TestModal: React.FC<{
id?: string;
isOpen?: boolean;
title?: string;
size?: string;
children?: React.ReactNode;
}> = ({ id, isOpen, title, size, children }) => (
isOpen ? (
<div data-testid={`modal-${id}`} role="dialog" data-size={size}>
<h2>{title}</h2>
{children}
</div>
) : null
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// ==============================
// 레지스트리 설정
// ==============================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
A: { component: TestA, metadata: { name: 'A', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
Modal: { component: TestModal, metadata: { name: 'Modal', type: 'composite' } },
};
return registry;
}
// ==============================
// 공통 번역 키
// ==============================
const translations = {
admin: {
plugins: {
update_available: '업데이트 필요',
version_available: '(v{{version}} 사용 가능)',
updating: '업데이트 중...',
update_success: '플러그인이 성공적으로 업데이트되었습니다.',
check_updates_success: '업데이트 확인 완료 ({{count}}개 업데이트 가능)',
check_updates_no_updates: '모든 플러그인이 최신 상태입니다.',
status: {
active: '활성화',
inactive: '비활성화',
not_installed: '미설치',
installing: '설치 중',
uninstalling: '제거 중',
updating: '업데이트 중',
},
actions: {
update: '업데이트',
check_updates: '업데이트 확인',
},
modals: {
update_title: '플러그인 업데이트 확인',
update_confirm: '{{name}} 플러그인을 업데이트하시겠습니까?',
update_version_info: '{{from}} → {{to}}',
update_source_github: 'GitHub에서 다운로드',
update_source_bundled: '선탑재 패키지에서 설치',
view_changelog: '변경사항 보기',
field_version: '버전',
field_vendor: '개발자',
},
},
},
common: {
cancel: '취소',
},
};
// ==============================
// 0. 레이아웃 JSON auth_required 검증
// ==============================
describe('플러그인 업데이트 - check-updates auth_required 검증', () => {
it('check-updates apiCall에 auth_required: true가 설정되어 있다', async () => {
const fs = await import('fs');
const path = await import('path');
const layoutPath = path.resolve(__dirname, '../../layouts/admin_plugin_list.json');
const layoutJson = JSON.parse(fs.readFileSync(layoutPath, 'utf-8'));
// sequence 내부의 apiCall 중 check-updates 찾기
function findCheckUpdatesApiCall(actions: any[]): any {
for (const action of actions) {
if (action.handler === 'apiCall' && action.target?.includes('check-updates')) {
return action;
}
if (action.handler === 'sequence' && action.actions) {
const found = findCheckUpdatesApiCall(action.actions);
if (found) return found;
}
}
return null;
}
// 컴포넌트 트리에서 actions를 가진 요소 탐색
function findActionsInComponents(components: any[]): any[] {
const allActions: any[] = [];
for (const comp of components) {
if (comp.actions) {
for (const actionGroup of comp.actions) {
if (actionGroup.handler === 'sequence' && actionGroup.actions) {
allActions.push(...actionGroup.actions);
} else {
allActions.push(actionGroup);
}
}
}
if (comp.children) {
allActions.push(...findActionsInComponents(comp.children));
}
}
return allActions;
}
// slots.content 또는 components에서 탐색
const components = layoutJson.slots?.content ?? layoutJson.components ?? [];
const allActions = findActionsInComponents(components);
const checkUpdatesAction = findCheckUpdatesApiCall(allActions);
expect(checkUpdatesAction).not.toBeNull();
expect(checkUpdatesAction.auth_required).toBe(true);
});
});
// ==============================
// 1. 상태 배지 테스트
// ==============================
describe('플러그인 업데이트 - 상태 배지', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
function createBadgeLayout(row: Record<string, any>) {
return {
version: '1.0.0',
layout_name: 'plugin_update_badge_test',
initGlobal: { row },
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{
type: 'basic',
name: 'Span',
if: "{{_global.row.status == 'updating'}}",
props: {
className: 'px-2 py-0.5 text-xs bg-purple-100 dark:bg-purple-900 text-purple-600 dark:text-purple-400 rounded',
},
text: '$t:admin.plugins.status.updating',
},
{
type: 'basic',
name: 'Span',
if: "{{_global.row.update_available && _global.row.status != 'updating' && _global.row.status != 'uninstalled'}}",
props: {
className: 'px-2 py-0.5 text-xs bg-amber-100 dark:bg-amber-900 text-amber-600 dark:text-amber-400 rounded',
},
text: '$t:admin.plugins.update_available',
},
{
type: 'basic',
name: 'Span',
if: "{{_global.row.update_available && _global.row.latest_version && _global.row.status != 'updating' && _global.row.status != 'uninstalled'}}",
props: {
className: 'text-xs text-gray-500 dark:text-gray-400',
},
text: "$t:admin.plugins.version_available|version={{_global.row.latest_version ?? ''}}",
},
],
},
],
};
}
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
it('updating 상태일 때 보라색 배지가 표시된다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'updating', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
const badges = screen.getAllByText('업데이트 중');
expect(badges.length).toBeGreaterThanOrEqual(1);
const badge = badges[0];
expect(badge.className).toContain('bg-purple-100');
expect(badge.className).toContain('dark:bg-purple-900');
});
it('update_available일 때 (updating 아닌) 황색 배지가 표시된다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
const badges = screen.getAllByText('업데이트 필요');
expect(badges.length).toBeGreaterThanOrEqual(1);
const badge = badges[0];
expect(badge.className).toContain('bg-amber-100');
});
it('update_available=false일 때 업데이트 배지가 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: false }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByText('업데이트 필요')).toBeNull();
expect(screen.queryByText('업데이트 중')).toBeNull();
});
it('uninstalled 상태에서는 update_available이어도 배지가 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'uninstalled', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByText('업데이트 필요')).toBeNull();
});
it('update_available이고 latest_version이 있으면 버전 정보가 표시된다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: true, latest_version: '2.0.0' }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.getByText('(v2.0.0 사용 가능)')).toBeTruthy();
});
it('update_available이지만 latest_version이 null이면 버전 정보가 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createBadgeLayout({ status: 'active', update_available: true, latest_version: null }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByText(/사용 가능/)).toBeNull();
});
});
// ==============================
// 2. 업데이트 확인 버튼 테스트
// ==============================
describe('플러그인 업데이트 - 업데이트 확인 버튼', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
const checkUpdatesButtonLayout = {
version: '1.0.0',
layout_name: 'plugin_check_updates_button_test',
initGlobal: {
isCheckingUpdates: false,
},
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{
id: 'check_updates_button',
type: 'basic',
name: 'Button',
props: {
className: 'flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed',
disabled: '{{_global.isCheckingUpdates}}',
type: 'button',
'data-testid': 'check-updates-btn',
},
children: [
{
type: 'basic',
name: 'Icon',
if: '{{!_global.isCheckingUpdates}}',
props: { name: 'refresh', size: 'sm' },
},
{
type: 'basic',
name: 'Icon',
if: '{{_global.isCheckingUpdates}}',
props: { name: 'spinner', size: 'sm', className: 'animate-spin' },
},
{
type: 'basic',
name: 'Span',
text: '$t:admin.plugins.actions.check_updates',
},
],
},
],
},
],
};
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
it('업데이트 확인 버튼이 렌더링된다', async () => {
testUtils = createLayoutTest(checkUpdatesButtonLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
});
await testUtils.render();
expect(screen.getByText('업데이트 확인')).toBeTruthy();
});
it('로딩 중이 아닐 때 refresh 아이콘이 표시된다', async () => {
testUtils = createLayoutTest(checkUpdatesButtonLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
});
await testUtils.render();
expect(screen.getByTestId('icon-refresh')).toBeTruthy();
expect(screen.queryByTestId('icon-spinner')).toBeNull();
});
it('isCheckingUpdates=true일 때 spinner 아이콘이 표시되고 버튼이 disabled된다', async () => {
const loadingLayout = {
...checkUpdatesButtonLayout,
initGlobal: { isCheckingUpdates: true },
};
testUtils = createLayoutTest(loadingLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
});
await testUtils.render();
expect(screen.getByTestId('icon-spinner')).toBeTruthy();
expect(screen.queryByTestId('icon-refresh')).toBeNull();
const btn = screen.getByTestId('check-updates-btn');
expect(btn).toHaveProperty('disabled', true);
});
});
// ==============================
// 3. 행별 업데이트 버튼 테스트
// ==============================
describe('플러그인 업데이트 - 행별 업데이트 버튼', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
function createRowButtonLayout(row: Record<string, any>) {
return {
version: '1.0.0',
layout_name: 'plugin_row_update_button_test',
initGlobal: { row },
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{
id: 'update_button',
type: 'basic',
name: 'Button',
if: "{{_global.row.update_available && _global.row.status != 'updating' && _global.row.status != 'uninstalled'}}",
props: {
className: 'flex items-center gap-1.5 px-3 py-1.5 text-sm bg-amber-500 text-white rounded-lg',
type: 'button',
'data-testid': 'row-update-btn',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'arrow-up-circle', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: '$t:admin.plugins.actions.update',
},
],
},
],
},
],
};
}
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
it('update_available && active 상태에서 업데이트 버튼이 표시된다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'active', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.getByTestId('row-update-btn')).toBeTruthy();
expect(screen.getByText('업데이트')).toBeTruthy();
expect(screen.getByTestId('icon-arrow-up-circle')).toBeTruthy();
});
it('update_available=false일 때 업데이트 버튼이 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'active', update_available: false }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByTestId('row-update-btn')).toBeNull();
});
it('updating 상태에서는 업데이트 버튼이 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'updating', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByTestId('row-update-btn')).toBeNull();
});
it('uninstalled 상태에서는 업데이트 버튼이 표시되지 않는다', async () => {
testUtils = createLayoutTest(
createRowButtonLayout({ status: 'uninstalled', update_available: true }),
{ translations, locale: 'ko', componentRegistry: registry },
);
await testUtils.render();
expect(screen.queryByTestId('row-update-btn')).toBeNull();
});
});
// ==============================
// 4. 업데이트 모달 테스트
// ==============================
describe('플러그인 업데이트 - 업데이트 모달', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
const updateModalLayout = {
version: '1.0.0',
layout_name: 'plugin_update_modal_test',
initGlobal: {
selectedPlugin: {
identifier: 'sirsoft-payment',
name: '결제 플러그인',
version: '1.0.0',
latest_version: '1.1.0',
update_source: 'github',
github_changelog_url: 'https://github.com/gnuboard/sirsoft-payment/releases',
},
isPluginUpdating: false,
},
modals: [
{
id: 'plugin_update_modal',
type: 'composite',
name: 'Modal',
props: {
title: '$t:admin.plugins.modals.update_title',
size: 'small',
},
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'py-2' },
children: [
{
type: 'basic',
name: 'P',
props: { className: 'text-gray-700 dark:text-gray-300' },
text: "$t:admin.plugins.modals.update_confirm|name={{_global.selectedPlugin.name ?? ''}}",
},
{
type: 'basic',
name: 'Div',
props: { className: 'mt-3 p-3 bg-gray-50 dark:bg-gray-800 border rounded-lg space-y-2' },
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2 text-sm' },
children: [
{
type: 'basic',
name: 'Span',
props: { className: 'text-gray-500' },
text: '$t:admin.plugins.modals.field_version',
},
{
type: 'basic',
name: 'Span',
props: { className: 'font-medium text-gray-900 dark:text-white' },
text: "$t:admin.plugins.modals.update_version_info|from={{_global.selectedPlugin.version ?? ''}}|to={{_global.selectedPlugin.latest_version ?? ''}}",
},
],
},
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2 text-sm' },
children: [
{
type: 'basic',
name: 'Span',
props: { className: 'text-gray-500' },
text: '$t:admin.plugins.modals.field_vendor',
},
{
type: 'basic',
name: 'Span',
props: { className: 'text-gray-700' },
text: "{{_global.selectedPlugin.update_source === 'github' ? '$t:admin.plugins.modals.update_source_github' : '$t:admin.plugins.modals.update_source_bundled'}}",
},
],
},
],
},
{
type: 'basic',
name: 'Div',
if: '{{_global.selectedPlugin.github_changelog_url}}',
props: { className: 'mt-3' },
children: [
{
type: 'basic',
name: 'A',
props: {
href: '{{_global.selectedPlugin.github_changelog_url}}',
target: '_blank',
className: 'inline-flex items-center gap-1.5 text-sm text-blue-600',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'external-link', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: '$t:admin.plugins.modals.view_changelog',
},
],
},
],
},
],
},
{
type: 'basic',
name: 'Div',
props: { className: 'flex justify-end gap-3 mt-6' },
children: [
{
type: 'basic',
name: 'Button',
props: {
className: 'px-4 py-2 bg-white dark:bg-gray-800 border rounded-lg disabled:opacity-50',
disabled: '{{_global.isPluginUpdating}}',
'data-testid': 'cancel-btn',
},
children: [
{ type: 'basic', name: 'Span', text: '$t:common.cancel' },
],
},
{
type: 'basic',
name: 'Button',
props: {
className: 'flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg disabled:opacity-50',
disabled: '{{_global.isPluginUpdating}}',
'data-testid': 'confirm-update-btn',
},
children: [
{
type: 'basic',
name: 'Icon',
if: '{{_global.isPluginUpdating}}',
props: { name: 'spinner', className: 'w-4 h-4 animate-spin' },
},
{
type: 'basic',
name: 'Span',
text: "{{_global.isPluginUpdating ? '$t:admin.plugins.updating' : '$t:admin.plugins.actions.update'}}",
},
],
},
],
},
],
},
],
components: [
{
id: 'main-content',
type: 'basic',
name: 'Div',
children: [
{ type: 'basic', name: 'Span', text: '플러그인 관리 페이지' },
],
},
],
};
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
});
describe('레이아웃 구조 검증', () => {
it('레이아웃 정보가 올바르게 로드된다', () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
const info = testUtils.getLayoutInfo();
expect(info.name).toBe('plugin_update_modal_test');
expect(info.version).toBe('1.0.0');
});
it('초기 전역 상태가 올바르게 설정된다', () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
const state = testUtils.getState();
expect(state._global.selectedPlugin).toEqual({
identifier: 'sirsoft-payment',
name: '결제 플러그인',
version: '1.0.0',
latest_version: '1.1.0',
update_source: 'github',
github_changelog_url: 'https://github.com/gnuboard/sirsoft-payment/releases',
});
expect(state._global.isPluginUpdating).toBe(false);
});
it('모달 크기가 small로 설정되어 있다', () => {
const modal = updateModalLayout.modals[0];
expect(modal.props.size).toBe('small');
});
});
describe('모달 열기/닫기', () => {
it('업데이트 모달을 열고 닫을 수 있다', async () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
await testUtils.render();
testUtils.openModal('plugin_update_modal');
expect(testUtils.getModalStack()).toContain('plugin_update_modal');
testUtils.closeModal();
expect(testUtils.getModalStack()).not.toContain('plugin_update_modal');
});
});
describe('모달 콘텐츠 구조 검증', () => {
it('모달 타이틀이 업데이트 확인으로 설정되어 있다', () => {
const modal = updateModalLayout.modals[0];
expect(modal.props.title).toBe('$t:admin.plugins.modals.update_title');
});
it('모달에 업데이트 확인 메시지가 포함되어 있다', () => {
const modal = updateModalLayout.modals[0];
const confirmP = modal.children[0].children[0];
expect(confirmP.text).toContain('$t:admin.plugins.modals.update_confirm');
expect(confirmP.text).toContain('_global.selectedPlugin.name');
});
it('모달에 버전 정보가 포함되어 있다 (from → to)', () => {
const modal = updateModalLayout.modals[0];
const versionRow = modal.children[0].children[1].children[0];
const versionLabel = versionRow.children[0];
const versionValue = versionRow.children[1];
expect(versionLabel.text).toBe('$t:admin.plugins.modals.field_version');
expect(versionValue.text).toContain('$t:admin.plugins.modals.update_version_info');
expect(versionValue.text).toContain('_global.selectedPlugin.version');
expect(versionValue.text).toContain('_global.selectedPlugin.latest_version');
});
it('모달에 update_source 표시가 포함되어 있다', () => {
const modal = updateModalLayout.modals[0];
const vendorRow = modal.children[0].children[1].children[1];
const vendorLabel = vendorRow.children[0];
const vendorValue = vendorRow.children[1];
expect(vendorLabel.text).toBe('$t:admin.plugins.modals.field_vendor');
expect(vendorValue.text).toContain('update_source_github');
});
it('모달에 changelog 링크가 조건부로 포함되어 있다', () => {
const modal = updateModalLayout.modals[0];
const changelogDiv = modal.children[0].children[2];
expect(changelogDiv.if).toBe('{{_global.selectedPlugin.github_changelog_url}}');
const linkA = changelogDiv.children[0];
expect(linkA.name).toBe('A');
expect(linkA.props.target).toBe('_blank');
expect(linkA.props.href).toContain('_global.selectedPlugin.github_changelog_url');
});
it('changelog URL이 없으면 조건에 의해 렌더링되지 않는다', () => {
const noChangelogState = { ...updateModalLayout.initGlobal.selectedPlugin, github_changelog_url: null };
expect(noChangelogState.github_changelog_url).toBeNull();
const modal = updateModalLayout.modals[0];
const changelogDiv = modal.children[0].children[2];
expect(changelogDiv.if).toBe('{{_global.selectedPlugin.github_changelog_url}}');
});
});
describe('버튼 구조 및 상태 검증', () => {
it('취소/확인 버튼이 모달에 정의되어 있다', () => {
const modal = updateModalLayout.modals[0];
const buttonsDiv = modal.children[1];
expect(buttonsDiv.children).toHaveLength(2);
const cancelBtn = buttonsDiv.children[0];
const confirmBtn = buttonsDiv.children[1];
expect(cancelBtn.name).toBe('Button');
expect(cancelBtn.props.disabled).toBe('{{_global.isPluginUpdating}}');
expect(cancelBtn.children[0].text).toBe('$t:common.cancel');
expect(confirmBtn.name).toBe('Button');
expect(confirmBtn.props.disabled).toBe('{{_global.isPluginUpdating}}');
});
it('확인 버튼에 스피너 조건부 렌더링이 설정되어 있다', () => {
const modal = updateModalLayout.modals[0];
const confirmBtn = modal.children[1].children[1];
const spinnerIcon = confirmBtn.children[0];
expect(spinnerIcon.name).toBe('Icon');
expect(spinnerIcon.if).toBe('{{_global.isPluginUpdating}}');
expect(spinnerIcon.props.name).toBe('spinner');
const textSpan = confirmBtn.children[1];
expect(textSpan.text).toContain('_global.isPluginUpdating');
expect(textSpan.text).toContain('$t:admin.plugins.updating');
expect(textSpan.text).toContain('$t:admin.plugins.actions.update');
});
it('isPluginUpdating 상태가 올바르게 변경될 수 있다', async () => {
testUtils = createLayoutTest(updateModalLayout, {
translations,
locale: 'ko',
componentRegistry: registry,
includeModals: true,
});
await testUtils.render();
let state = testUtils.getState();
expect(state._global.isPluginUpdating).toBe(false);
testUtils.setState('isPluginUpdating', true, 'global');
state = testUtils.getState();
expect(state._global.isPluginUpdating).toBe(true);
testUtils.setState('isPluginUpdating', false, 'global');
testUtils.setState('selectedPlugin', null, 'global');
state = testUtils.getState();
expect(state._global.isPluginUpdating).toBe(false);
expect(state._global.selectedPlugin).toBeNull();
});
});
});
@@ -0,0 +1,547 @@
/**
* @file admin-reset-password.test.tsx
* @description 관리자 비밀번호 재설정 레이아웃 렌더링 테스트
*
* 테스트 대상:
* - 토큰 유효 시 비밀번호 재설정 폼이 표시되는지
* - 토큰 에러 시 경고 메시지와 비밀번호 찾기 링크가 표시되는지
* - 성공 시 성공 메시지와 로그인 버튼이 표시되는지
* - 제출 중 상태에서 스피너가 표시되는지
*/
import React from 'react';
import { describe, it, expect, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<any> = ({ className, children, type, disabled, 'data-testid': testId }) => (
<button className={className} type={type} disabled={disabled} data-testid={testId}>{children}</button>
);
const TestInput: React.FC<any> = ({ className, type, name, placeholder, disabled, required, 'data-testid': testId, ...rest }) => (
<input className={className} type={type} name={name} placeholder={placeholder} disabled={disabled} required={required} data-testid={testId} readOnly {...rest} />
);
const TestForm: React.FC<any> = ({ className, children }) => <form className={className}>{children}</form>;
const TestLabel: React.FC<any> = ({ className, children }) => <label className={className}>{children}</label>;
const TestSelect: React.FC<any> = ({ className, 'data-testid': testId }) => <select className={className} data-testid={testId} readOnly />;
const TestH1: React.FC<any> = ({ className, children }) => <h1 className={className}>{children}</h1>;
const TestP: React.FC<any> = ({ className, children, 'data-testid': testId }) => <p className={className} data-testid={testId}>{children}</p>;
const TestSpan: React.FC<any> = ({ className, children }) => <span className={className}>{children}</span>;
const TestIcon: React.FC<any> = ({ name, size, color }) => <i data-icon={name} data-size={size} className={color} />;
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Form: { component: TestForm, metadata: { name: 'Form', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Select: { component: TestSelect, metadata: { name: 'Select', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 비밀번호 재설정 레이아웃 — 정상 상태 (토큰 유효)
const resetPasswordLayout = {
version: '1.0.0',
layout_name: 'test_admin_reset_password',
state: {
isSubmitting: false,
success: false,
tokenError: false,
tokenValid: true,
resetError: null,
resetErrors: null,
},
components: [
{
id: 'reset_card',
type: 'basic',
name: 'Div',
props: { className: 'bg-white dark:bg-gray-800 rounded-lg shadow-md p-8' },
children: [
{
id: 'reset_header',
type: 'basic',
name: 'Div',
props: { className: 'text-center mb-8' },
children: [
{
id: 'reset_icon_wrapper',
type: 'basic',
name: 'Div',
if: '{{!_local.tokenError}}',
props: { className: 'w-16 h-16 mx-auto mb-4 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center' },
children: [
{ id: 'reset_lock_icon', type: 'basic', name: 'Icon', props: { name: 'lock', size: 'xl', color: 'text-blue-600 dark:text-blue-400' } },
],
},
{
id: 'reset_warning_icon_wrapper',
type: 'basic',
name: 'Div',
if: '{{_local.tokenError}}',
props: { className: 'w-16 h-16 mx-auto mb-4 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center' },
children: [
{ id: 'reset_warning_icon', type: 'basic', name: 'Icon', props: { name: 'triangle-exclamation', size: 'xl', color: 'text-red-600 dark:text-red-400' } },
],
},
{
id: 'reset_title',
type: 'basic',
name: 'H1',
if: '{{!_local.tokenError}}',
props: { className: 'text-2xl font-bold text-gray-900 dark:text-white mb-2' },
text: '비밀번호 재설정',
},
{
id: 'reset_title_invalid',
type: 'basic',
name: 'H1',
if: '{{_local.tokenError}}',
props: { className: 'text-2xl font-bold text-gray-900 dark:text-white mb-2' },
text: '유효하지 않은 링크',
},
{
id: 'reset_subtitle',
type: 'basic',
name: 'P',
if: '{{!_local.tokenError && !_local.success}}',
props: { className: 'text-sm text-gray-600 dark:text-gray-400' },
text: '새로운 비밀번호를 입력해주세요.',
},
],
},
{
id: 'reset_token_error',
type: 'basic',
name: 'Div',
if: '{{_local.tokenError}}',
props: { className: 'text-center' },
children: [
{
id: 'reset_token_error_text',
type: 'basic',
name: 'P',
props: { className: 'text-gray-600 dark:text-gray-400 mb-6' },
text: '비밀번호 재설정 링크가 만료되었거나 유효하지 않습니다.',
},
{
id: 'reset_token_error_button',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: 'w-full px-4 py-3 rounded-lg font-medium bg-blue-600 text-white',
'data-testid': 'go-to-forgot',
},
actions: [
{ type: 'click', handler: 'navigate', params: { path: '/admin/forgot-password' } },
],
text: '비밀번호 찾기로 이동',
},
],
},
{
id: 'reset_success',
type: 'basic',
name: 'Div',
if: '{{_local.success && !_local.tokenError}}',
props: { className: 'text-center' },
children: [
{
id: 'reset_success_icon_wrapper',
type: 'basic',
name: 'Div',
props: { className: 'mb-4 p-4 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-lg' },
children: [
{
id: 'reset_success_text',
type: 'basic',
name: 'P',
props: { className: 'text-green-700 dark:text-green-300 text-sm' },
text: '비밀번호가 성공적으로 변경되었습니다.',
},
],
},
{
id: 'reset_success_login_button',
type: 'basic',
name: 'Button',
props: {
type: 'button',
className: 'w-full px-4 py-3 rounded-lg font-medium bg-blue-600 text-white',
'data-testid': 'go-to-login',
},
actions: [
{ type: 'click', handler: 'navigate', params: { path: '/admin/login' } },
],
text: '로그인하기',
},
],
},
{
id: 'reset_form',
type: 'basic',
name: 'Form',
if: '{{!_local.tokenError && !_local.success}}',
props: { className: 'space-y-6' },
children: [
{
id: 'reset_password_field',
type: 'basic',
name: 'Div',
children: [
{
id: 'reset_password_label',
type: 'basic',
name: 'Label',
props: { className: 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2' },
text: '새 비밀번호',
},
{
id: 'reset_password_input',
type: 'basic',
name: 'Input',
props: {
type: 'password',
name: 'password',
className: "{{_local.resetErrors?.password ? 'w-full px-4 py-3 border border-red-500 rounded-lg' : 'w-full px-4 py-3 border border-gray-300 rounded-lg'}}",
required: true,
disabled: '{{_local.isSubmitting ?? false}}',
'data-testid': 'password-input',
},
},
{
id: 'reset_password_error',
type: 'basic',
name: 'P',
if: '{{_local.resetErrors?.password}}',
props: { className: 'mt-2 text-sm text-red-600 dark:text-red-400', 'data-testid': 'password-error' },
text: "{{Array.isArray(_local.resetErrors?.password) ? _local.resetErrors.password[0] : _local.resetErrors?.password}}",
},
],
},
{
id: 'reset_password_confirm_field',
type: 'basic',
name: 'Div',
children: [
{
id: 'reset_password_confirm_label',
type: 'basic',
name: 'Label',
props: { className: 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2' },
text: '비밀번호 확인',
},
{
id: 'reset_password_confirm_input',
type: 'basic',
name: 'Input',
props: {
type: 'password',
name: 'password_confirmation',
className: "{{_local.resetErrors?.password_confirmation ? 'w-full px-4 py-3 border border-red-500 rounded-lg' : 'w-full px-4 py-3 border border-gray-300 rounded-lg'}}",
required: true,
disabled: '{{_local.isSubmitting ?? false}}',
'data-testid': 'password-confirm-input',
},
},
{
id: 'reset_password_confirm_error',
type: 'basic',
name: 'P',
if: '{{_local.resetErrors?.password_confirmation}}',
props: { className: 'mt-2 text-sm text-red-600 dark:text-red-400', 'data-testid': 'password-confirm-error' },
text: "{{Array.isArray(_local.resetErrors?.password_confirmation) ? _local.resetErrors.password_confirmation[0] : _local.resetErrors?.password_confirmation}}",
},
],
},
{
id: 'reset_submit_button',
type: 'basic',
name: 'Button',
props: {
type: 'submit',
className: 'w-full px-4 py-3 rounded-lg font-medium bg-blue-600 text-white',
disabled: '{{_local.isSubmitting ?? false}}',
'data-testid': 'submit-button',
},
children: [
{
id: 'reset_submit_spinner',
type: 'basic',
name: 'Div',
if: '{{_local.isSubmitting}}',
props: { className: 'w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin', 'data-testid': 'spinner' },
},
{
id: 'reset_submit_text',
type: 'basic',
name: 'Span',
if: '{{!_local.isSubmitting}}',
text: '비밀번호 변경',
},
{
id: 'reset_submit_processing',
type: 'basic',
name: 'Span',
if: '{{_local.isSubmitting}}',
text: '처리 중...',
},
],
},
],
},
],
},
],
};
describe('관리자 비밀번호 재설정 레이아웃', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
describe('정상 상태 (토큰 유효, 폼 표시)', () => {
it('비밀번호 입력 필드가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('password-input')).toBeInTheDocument();
expect(screen.getByTestId('password-confirm-input')).toBeInTheDocument();
});
it('제목과 부제목이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호 재설정')).toBeInTheDocument();
expect(screen.getByText('새로운 비밀번호를 입력해주세요.')).toBeInTheDocument();
});
it('lock 아이콘이 표시된다 (warning 아이콘 아님)', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(document.querySelector('[data-icon="lock"]')).not.toBeNull();
expect(document.querySelector('[data-icon="triangle-exclamation"]')).toBeNull();
});
it('비밀번호 변경 버튼이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호 변경')).toBeInTheDocument();
});
it('토큰 에러 메시지가 숨겨져 있다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByText('비밀번호 재설정 링크가 만료되었거나 유효하지 않습니다.')).toBeNull();
});
it('password 타입 input이 사용된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
const pwInput = screen.getByTestId('password-input');
expect(pwInput).toHaveAttribute('type', 'password');
const confirmInput = screen.getByTestId('password-confirm-input');
expect(confirmInput).toHaveAttribute('type', 'password');
});
});
describe('토큰 에러 상태', () => {
const tokenErrorLayout = {
...resetPasswordLayout,
layout_name: 'test_admin_reset_password_token_error',
state: { isSubmitting: false, success: false, tokenError: true, tokenValid: false, resetError: null, resetErrors: null },
};
it('경고 아이콘이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(tokenErrorLayout, { componentRegistry: registry });
await testUtils.render();
expect(document.querySelector('[data-icon="triangle-exclamation"]')).not.toBeNull();
expect(document.querySelector('[data-icon="lock"]')).toBeNull();
});
it('유효하지 않은 링크 제목이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(tokenErrorLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('유효하지 않은 링크')).toBeInTheDocument();
expect(screen.queryByText('비밀번호 재설정')).toBeNull();
});
it('에러 메시지와 비밀번호 찾기로 이동 버튼이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(tokenErrorLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호 재설정 링크가 만료되었거나 유효하지 않습니다.')).toBeInTheDocument();
expect(screen.getByTestId('go-to-forgot')).toBeInTheDocument();
expect(screen.getByText('비밀번호 찾기로 이동')).toBeInTheDocument();
});
it('폼이 숨겨진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(tokenErrorLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('password-input')).toBeNull();
expect(screen.queryByTestId('submit-button')).toBeNull();
});
});
describe('성공 상태', () => {
const successLayout = {
...resetPasswordLayout,
layout_name: 'test_admin_reset_password_success',
state: { isSubmitting: false, success: true, tokenError: false, tokenValid: true, resetError: null, resetErrors: null },
};
it('성공 메시지가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(successLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('비밀번호가 성공적으로 변경되었습니다.')).toBeInTheDocument();
});
it('로그인하기 버튼이 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(successLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('go-to-login')).toBeInTheDocument();
expect(screen.getByText('로그인하기')).toBeInTheDocument();
});
it('폼이 숨겨진다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(successLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('password-input')).toBeNull();
});
});
describe('제출 중 상태', () => {
const submittingLayout = {
...resetPasswordLayout,
layout_name: 'test_admin_reset_password_submitting',
state: { isSubmitting: true, success: false, tokenError: false, tokenValid: true, resetError: null, resetErrors: null },
};
it('스피너가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(submittingLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('spinner')).toBeInTheDocument();
});
it('처리 중 텍스트가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(submittingLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('처리 중...')).toBeInTheDocument();
expect(screen.queryByText('비밀번호 변경')).toBeNull();
});
});
describe('필드 에러 상태 (resetErrors 존재)', () => {
const errorLayout = {
...resetPasswordLayout,
layout_name: 'test_admin_reset_password_field_error',
state: {
isSubmitting: false,
success: false,
tokenError: false,
tokenValid: true,
resetError: 'The given data was invalid.',
resetErrors: {
password: ['비밀번호는 8자 이상이어야 합니다.'],
password_confirmation: ['비밀번호 확인이 일치하지 않습니다.'],
},
},
};
it('비밀번호 입력 필드에 빨간 테두리가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
const pwInput = screen.getByTestId('password-input');
expect(pwInput.className).toContain('border-red-500');
expect(pwInput.className).not.toContain('border-gray-300');
});
it('비밀번호 필드 아래 에러 메시지가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
const pwError = screen.getByTestId('password-error');
expect(pwError).toBeInTheDocument();
expect(pwError.textContent).toBe('비밀번호는 8자 이상이어야 합니다.');
});
it('비밀번호 확인 입력 필드에 빨간 테두리가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
const confirmInput = screen.getByTestId('password-confirm-input');
expect(confirmInput.className).toContain('border-red-500');
});
it('비밀번호 확인 필드 아래 에러 메시지가 표시된다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(errorLayout, { componentRegistry: registry });
await testUtils.render();
const confirmError = screen.getByTestId('password-confirm-error');
expect(confirmError).toBeInTheDocument();
expect(confirmError.textContent).toBe('비밀번호 확인이 일치하지 않습니다.');
});
});
describe('초기 상태에서 에러 요소 미표시', () => {
it('에러 메시지와 빨간 테두리가 없다', async () => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(resetPasswordLayout, { componentRegistry: registry });
await testUtils.render();
expect(screen.queryByTestId('password-error')).toBeNull();
expect(screen.queryByTestId('password-confirm-error')).toBeNull();
const pwInput = screen.getByTestId('password-input');
expect(pwInput.className).toContain('border-gray-300');
expect(pwInput.className).not.toContain('border-red-500');
});
});
});
@@ -0,0 +1,207 @@
/**
* @file admin-role-form-identifier.test.tsx
* @description 역할 생성/수정 폼 - identifier 필드 렌더링 테스트
*
* 테스트 대상:
* - identifier Input 필드가 렌더링되는지
* - 생성 모드에서 identifier가 활성화(editable)되는지
* - 수정 모드에서 identifier가 비활성화(disabled)되는지
* - 힌트 텍스트가 모드에 따라 올바르게 표시되는지
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestLabel: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<label className={className}>{children || text}</label>
);
const TestInput: React.FC<{
name?: string;
type?: string;
placeholder?: string;
maxLength?: number;
disabled?: boolean;
error?: string;
value?: string;
'data-testid'?: string;
}> = ({ name, type, placeholder, disabled, value, 'data-testid': testId }) => (
<input
name={name}
type={type}
placeholder={placeholder}
disabled={disabled}
value={value ?? ''}
data-testid={testId || `input-${name}`}
readOnly
/>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 테스트용 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// identifier 필드만 포함한 최소 레이아웃 JSON
const identifierFieldLayout = {
version: '1.0.0',
layout_name: 'admin_role_form_identifier_test',
slots: {
content: [
{
id: 'identifier_field',
type: 'basic',
name: 'Div',
props: {
className: 'space-y-1',
},
children: [
{
type: 'basic',
name: 'Label',
props: {
className: 'block text-sm font-medium text-gray-700',
},
text: 'Identifier',
},
{
id: 'identifier_input',
type: 'basic',
name: 'Input',
props: {
name: 'identifier',
type: 'text',
placeholder: 'e.g. content_manager',
maxLength: 100,
disabled: '{{!!route?.id}}',
},
},
{
type: 'basic',
name: 'Span',
if: '{{!route?.id}}',
props: {
className: 'text-gray-500 text-xs mt-1',
},
text: 'Only lowercase letters, numbers, and underscores allowed.',
},
{
type: 'basic',
name: 'Span',
if: '{{!!route?.id}}',
props: {
className: 'text-gray-500 text-xs mt-1',
},
text: 'Identifier cannot be changed after creation.',
},
],
},
],
},
};
describe('admin_role_form - identifier 필드 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
(registry as any).registry = {};
});
it('생성 모드에서 identifier Input이 활성화 상태로 렌더링된다', async () => {
const testUtils = createLayoutTest(identifierFieldLayout, {
componentRegistry: registry,
routeParams: {},
});
await testUtils.render();
const input = screen.getByTestId('input-identifier');
expect(input).toBeInTheDocument();
expect(input).not.toBeDisabled();
testUtils.cleanup();
});
it('수정 모드에서 identifier Input이 비활성화 상태로 렌더링된다', async () => {
const testUtils = createLayoutTest(identifierFieldLayout, {
componentRegistry: registry,
routeParams: { id: '5' },
});
await testUtils.render();
const input = screen.getByTestId('input-identifier');
expect(input).toBeInTheDocument();
expect(input).toBeDisabled();
testUtils.cleanup();
});
it('생성 모드에서 생성 힌트 텍스트가 표시된다', async () => {
const testUtils = createLayoutTest(identifierFieldLayout, {
componentRegistry: registry,
routeParams: {},
});
await testUtils.render();
expect(screen.getByText('Only lowercase letters, numbers, and underscores allowed.')).toBeInTheDocument();
testUtils.cleanup();
});
it('수정 모드에서 수정 불가 힌트 텍스트가 표시된다', async () => {
const testUtils = createLayoutTest(identifierFieldLayout, {
componentRegistry: registry,
routeParams: { id: '5' },
});
await testUtils.render();
expect(screen.getByText('Identifier cannot be changed after creation.')).toBeInTheDocument();
testUtils.cleanup();
});
});
@@ -0,0 +1,253 @@
/**
* @file admin-role-list-badges.test.tsx
* @description 역할 목록 - extension_type별 뱃지 렌더링 테스트
*
* 테스트 대상:
* - core 역할: shield 아이콘 + "시스템" 뱃지 (회색)
* - module 역할: cube 아이콘 + 확장명 뱃지 (파란색)
* - plugin 역할: plug 아이콘 + 확장명 뱃지 (보라색)
* - user-created 역할(null): 뱃지 없음
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
'data-testid'?: string;
}> = ({ name, size, 'data-testid': testId }) => (
<i data-testid={testId || `icon-${name}`} data-icon={name} data-size={size} />
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 테스트용 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 이름 셀의 뱃지 부분만 추출한 최소 레이아웃
function createBadgeTestLayout(row: Record<string, any>) {
return {
version: '1.0.0',
layout_name: 'admin_role_list_badge_test',
initGlobal: {
row,
},
slots: {
content: [
{
id: 'name_cell',
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-2' },
children: [
{
type: 'basic',
name: 'Span',
props: { className: 'font-medium' },
text: '{{_global.row.name}}',
},
{
id: 'badge_core',
type: 'basic',
name: 'Div',
if: "{{_global.row.extension_type === 'core'}}",
props: {
className: 'inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'shield', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: 'System',
},
],
},
{
id: 'badge_module',
type: 'basic',
name: 'Div',
if: "{{_global.row.extension_type === 'module'}}",
props: {
className: 'inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'cube', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: "{{_global.row.extension_name ?? 'Module'}}",
},
],
},
{
id: 'badge_plugin',
type: 'basic',
name: 'Div',
if: "{{_global.row.extension_type === 'plugin'}}",
props: {
className: 'inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700',
},
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'plug', size: 'sm' },
},
{
type: 'basic',
name: 'Span',
text: "{{_global.row.extension_name ?? 'Plugin'}}",
},
],
},
],
},
],
},
};
}
describe('admin_role_list - extension_type별 뱃지 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
(registry as any).registry = {};
});
it('core 역할: shield 아이콘 + "System" 뱃지가 렌더링된다', async () => {
const layout = createBadgeTestLayout({
name: 'Admin',
extension_type: 'core',
extension_identifier: 'core',
extension_name: null,
});
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('Admin')).toBeInTheDocument();
expect(screen.getByTestId('icon-shield')).toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
testUtils.cleanup();
});
it('module 역할: cube 아이콘 + 확장명 뱃지가 렌더링된다', async () => {
const layout = createBadgeTestLayout({
name: 'Board Manager',
extension_type: 'module',
extension_identifier: 'sirsoft-board',
extension_name: '게시판',
});
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('Board Manager')).toBeInTheDocument();
expect(screen.getByTestId('icon-cube')).toBeInTheDocument();
expect(screen.getByText('게시판')).toBeInTheDocument();
testUtils.cleanup();
});
it('plugin 역할: plug 아이콘 + 확장명 뱃지가 렌더링된다', async () => {
const layout = createBadgeTestLayout({
name: 'Payment Admin',
extension_type: 'plugin',
extension_identifier: 'sirsoft-payment',
extension_name: '토스페이먼츠',
});
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('Payment Admin')).toBeInTheDocument();
expect(screen.getByTestId('icon-plug')).toBeInTheDocument();
expect(screen.getByText('토스페이먼츠')).toBeInTheDocument();
testUtils.cleanup();
});
it('user-created 역할(null): 뱃지가 렌더링되지 않는다', async () => {
const layout = createBadgeTestLayout({
name: 'Custom Role',
extension_type: null,
extension_identifier: null,
extension_name: null,
});
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByText('Custom Role')).toBeInTheDocument();
expect(screen.queryByTestId('icon-shield')).not.toBeInTheDocument();
expect(screen.queryByTestId('icon-cube')).not.toBeInTheDocument();
expect(screen.queryByTestId('icon-plug')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('module 역할에 extension_name이 없으면 폴백 "Module" 텍스트가 표시된다', async () => {
const layout = createBadgeTestLayout({
name: 'Unknown Module Role',
extension_type: 'module',
extension_identifier: 'unknown-module',
extension_name: null,
});
const testUtils = createLayoutTest(layout, { componentRegistry: registry });
await testUtils.render();
expect(screen.getByTestId('icon-cube')).toBeInTheDocument();
expect(screen.getByText('Module')).toBeInTheDocument();
testUtils.cleanup();
});
});
@@ -0,0 +1,246 @@
/**
* @file admin-settings-logo-remove.test.tsx
* @description 환경설정 사이트 로고 파일 상태 변경 시 form 동기화 및 hasChanges 활성화 테스트
*
* 테스트 대상:
* - FileUploader onRemove 시 setState로 _local.form.general.site_logo에서 해당 항목 필터링
* - FileUploader onFilesChange 시 hasChanges = true 설정
* - FileUploader onUploadComplete 시 form.general.site_logo에 업로드된 파일 추가 + hasChanges = true
* - onRemove 시 hasChanges = true 설정
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트
const TestDiv: React.FC<{ children?: React.ReactNode; 'data-testid'?: string }> = ({ children, 'data-testid': testId }) => (
<div data-testid={testId}>{children}</div>
);
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
const TestFileUploader: React.FC<{
collection?: string;
initialFiles?: any[];
onRemove?: (id: number) => void;
onFilesChange?: (files: any[]) => void;
onUploadComplete?: (files: any[]) => void;
'data-testid'?: string;
}> = ({ 'data-testid': testId }) => (
<div data-testid={testId || 'file-uploader'} />
);
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
FileUploader: { component: TestFileUploader, metadata: { name: 'FileUploader', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 테스트용 로고 데이터
const LOGO_1 = { id: 101, hash: 'abc123', original_filename: 'logo1.png', mime_type: 'image/png', size: 1000 };
const LOGO_2 = { id: 202, hash: 'def456', original_filename: 'logo2.png', mime_type: 'image/png', size: 2000 };
const UPLOADED_LOGO = { id: 303, hash: 'ghi789', original_filename: 'new_logo.png', mime_type: 'image/png', size: 3000 };
// 프로덕션 레이아웃과 동일한 액션 패턴
const settingsLogoLayout = {
version: '1.0.0',
layout_name: 'test_settings_logo',
components: [
{
id: 'site_logo_uploader',
type: 'composite',
name: 'FileUploader',
props: {
collection: 'site_logo',
initialFiles: '{{_local.form?.general?.site_logo ?? []}}',
'data-testid': 'file-uploader',
},
actions: [
{
event: 'onFilesChange',
type: 'change',
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
},
},
{
event: 'onUploadComplete',
type: 'change',
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
'form.general.site_logo': "{{[...(_local.form?.general?.site_logo ?? []), ...$args[0]]}}",
},
},
{
event: 'onRemove',
type: 'change',
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
'form.general.site_logo': "{{(_local.form?.general?.site_logo ?? []).filter(item => item.id !== $args[0])}}",
},
},
],
},
],
};
describe('환경설정 사이트 로고 파일 상태 변경', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
(registry as any).registry = {};
});
describe('onRemove - 로고 삭제 시 form 동기화', () => {
it('로고 2개 중 1개 삭제 시 나머지 1개만 form에 남아야 한다', async () => {
const testUtils = createLayoutTest(settingsLogoLayout, {
componentRegistry: registry,
});
testUtils.setState('form', {
general: { site_logo: [LOGO_1, LOGO_2] },
}, 'local');
await testUtils.render();
await testUtils.triggerAction({
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
'form.general.site_logo': [LOGO_2],
},
});
const state = testUtils.getState();
expect(state._local.form.general.site_logo).toHaveLength(1);
expect(state._local.form.general.site_logo[0].id).toBe(202);
testUtils.cleanup();
});
it('모든 로고 삭제 시 빈 배열이어야 한다', async () => {
const testUtils = createLayoutTest(settingsLogoLayout, {
componentRegistry: registry,
});
testUtils.setState('form', {
general: { site_logo: [LOGO_1] },
}, 'local');
await testUtils.render();
await testUtils.triggerAction({
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
'form.general.site_logo': [],
},
});
const state = testUtils.getState();
expect(state._local.form.general.site_logo).toEqual([]);
testUtils.cleanup();
});
it('삭제 시 hasChanges가 true로 설정되어야 한다', async () => {
const testUtils = createLayoutTest(settingsLogoLayout, {
componentRegistry: registry,
});
testUtils.setState('form', {
general: { site_logo: [LOGO_1] },
}, 'local');
testUtils.setState('hasChanges', false, 'local');
await testUtils.render();
await testUtils.triggerAction({
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
'form.general.site_logo': [],
},
});
const state = testUtils.getState();
expect(state._local.hasChanges).toBe(true);
testUtils.cleanup();
});
});
describe('onFilesChange - 파일 선택 시 hasChanges 활성화', () => {
it('파일 선택 시 hasChanges가 true로 설정되어야 한다', async () => {
const testUtils = createLayoutTest(settingsLogoLayout, {
componentRegistry: registry,
});
testUtils.setState('hasChanges', false, 'local');
await testUtils.render();
await testUtils.triggerAction({
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
},
});
const state = testUtils.getState();
expect(state._local.hasChanges).toBe(true);
testUtils.cleanup();
});
});
describe('onUploadComplete - 업로드 완료 시 form 동기화', () => {
it('업로드 완료 시 form.general.site_logo에 새 파일이 추가되어야 한다', async () => {
const testUtils = createLayoutTest(settingsLogoLayout, {
componentRegistry: registry,
});
testUtils.setState('form', {
general: { site_logo: [LOGO_1] },
}, 'local');
await testUtils.render();
await testUtils.triggerAction({
handler: 'setState',
params: {
target: 'local',
hasChanges: true,
'form.general.site_logo': [LOGO_1, UPLOADED_LOGO],
},
});
const state = testUtils.getState();
expect(state._local.form.general.site_logo).toHaveLength(2);
expect(state._local.form.general.site_logo[1].id).toBe(303);
expect(state._local.hasChanges).toBe(true);
testUtils.cleanup();
});
});
});
@@ -0,0 +1,375 @@
/**
* @file admin-settings-readonly.test.tsx
* @description 환경설정 읽기 전용 UI 제어 렌더링 테스트
*
* 테스트 대상:
* - can_update: true → footer_buttons 표시, readonly 배너 미표시, Input 활성
* - can_update: false → footer_buttons 숨김, readonly 배너 표시, Input disabled
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
className?: string;
disabled?: boolean;
type?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, disabled, type, children, text, 'data-testid': testId }) => (
<button className={className} disabled={disabled} type={type as any} data-testid={testId}>
{children || text}
</button>
);
const TestInput: React.FC<{
className?: string;
disabled?: boolean;
type?: string;
name?: string;
placeholder?: string;
'data-testid'?: string;
}> = ({ className, disabled, type, name, placeholder, 'data-testid': testId }) => (
<input
className={className}
disabled={disabled}
type={type}
name={name}
placeholder={placeholder}
data-testid={testId || name}
/>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={className} data-icon={name} data-testid={`icon-${name}`} />
);
const TestPageHeader: React.FC<{
title?: string;
description?: string;
children?: React.ReactNode;
}> = ({ title, description, children }) => (
<div data-testid="page-header">
{title && <h1>{title}</h1>}
{description && <p>{description}</p>}
{children}
</div>
);
const TestTabNavigation: React.FC<{
tabs?: any[];
activeTabId?: string;
variant?: string;
children?: React.ReactNode;
}> = ({ tabs, activeTabId, children }) => (
<div data-testid="tab-navigation" data-active-tab={activeTabId}>
{children}
</div>
);
const TestLabel: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<label className={className}>{children || text}</label>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
PageHeader: { component: TestPageHeader, metadata: { name: 'PageHeader', type: 'composite' } },
TabNavigation: { component: TestTabNavigation, metadata: { name: 'TabNavigation', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// Mock API 응답 생성 헬퍼
function createSettingsResponse(abilities: { can_update: boolean }) {
return {
success: true,
data: {
general: { site_name: 'Test Site' },
abilities,
},
};
}
// 인라인 표현식 (프로덕션에서는 _computed.isReadOnly가 _local.form.abilities 경로 사용,
// 테스트에서는 initLocal 미지원으로 데이터소스 직접 참조)
const IS_READONLY = '{{!!settings?.data && !(settings?.data?.abilities?.can_update ?? false)}}';
const IS_NOT_READONLY = '{{!!settings?.data && (settings?.data?.abilities?.can_update ?? false)}}';
// 환경설정 간략화 레이아웃 (배너 + general 탭 Input + footer)
const settingsLayout = {
version: '1.0.0',
layout_name: 'test_admin_settings',
data_sources: [
{
id: 'settings',
type: 'api',
endpoint: '/api/admin/settings',
method: 'GET',
auto_fetch: true,
auth_required: true,
fallback: { data: [] },
},
],
components: [
{
id: 'settings_content',
type: 'basic',
name: 'Div',
children: [
{
id: 'readonly_banner',
type: 'basic',
name: 'Div',
if: IS_READONLY,
props: {
className: 'bg-yellow-50',
'data-testid': 'readonly-banner',
},
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-3' },
children: [
{
type: 'basic',
name: 'Icon',
props: { name: 'lock' },
},
{
type: 'basic',
name: 'P',
text: '이 설정은 읽기 전용입니다.',
},
],
},
],
},
{
id: 'field_site_name',
type: 'basic',
name: 'Div',
children: [
{
type: 'basic',
name: 'Label',
text: '사이트 이름',
},
{
type: 'basic',
name: 'Input',
props: {
type: 'text',
name: 'general.site_name',
disabled: IS_READONLY,
'data-testid': 'input-site-name',
},
},
],
},
{
id: 'footer_buttons',
type: 'basic',
name: 'Div',
if: IS_NOT_READONLY,
props: {
'data-testid': 'footer-buttons',
},
children: [
{
type: 'basic',
name: 'Button',
props: {
type: 'submit',
'data-testid': 'btn-save',
},
text: '저장',
},
{
type: 'basic',
name: 'Button',
props: {
type: 'button',
'data-testid': 'btn-cancel',
},
text: '취소',
},
],
},
],
},
],
};
describe('admin-settings 읽기 전용 UI 제어', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
(registry as any).registry = {};
});
describe('can_update: true (수정 가능)', () => {
it('readonly 배너가 표시되지 않아야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: createSettingsResponse({ can_update: true }),
});
await testUtils.render();
expect(screen.queryByTestId('readonly-banner')).toBeNull();
testUtils.cleanup();
});
it('footer 저장/취소 버튼이 표시되어야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: createSettingsResponse({ can_update: true }),
});
await testUtils.render();
expect(screen.getByTestId('footer-buttons')).toBeTruthy();
expect(screen.getByTestId('btn-save')).toBeTruthy();
expect(screen.getByTestId('btn-cancel')).toBeTruthy();
testUtils.cleanup();
});
it('Input이 활성 상태여야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: createSettingsResponse({ can_update: true }),
});
await testUtils.render();
const input = screen.getByTestId('input-site-name') as HTMLInputElement;
expect(input.disabled).toBe(false);
testUtils.cleanup();
});
});
describe('can_update: false (읽기 전용)', () => {
it('readonly 배너가 표시되어야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: createSettingsResponse({ can_update: false }),
});
await testUtils.render();
expect(screen.getByTestId('readonly-banner')).toBeTruthy();
testUtils.cleanup();
});
it('footer 저장/취소 버튼이 숨겨져야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: createSettingsResponse({ can_update: false }),
});
await testUtils.render();
expect(screen.queryByTestId('footer-buttons')).toBeNull();
expect(screen.queryByTestId('btn-save')).toBeNull();
testUtils.cleanup();
});
it('Input이 disabled 상태여야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: createSettingsResponse({ can_update: false }),
});
await testUtils.render();
const input = screen.getByTestId('input-site-name') as HTMLInputElement;
expect(input.disabled).toBe(true);
testUtils.cleanup();
});
});
describe('abilities 미포함 (하위 호환)', () => {
it('abilities가 없으면 읽기 전용으로 처리되어야 한다', async () => {
const testUtils = createLayoutTest(settingsLayout);
testUtils.mockApi('settings', {
response: {
success: true,
data: {
general: { site_name: 'Test Site' },
// abilities 없음
},
},
});
await testUtils.render();
// abilities 없으면 can_update가 false이므로 읽기 전용
expect(screen.getByTestId('readonly-banner')).toBeTruthy();
expect(screen.queryByTestId('footer-buttons')).toBeNull();
testUtils.cleanup();
});
});
});
@@ -0,0 +1,555 @@
/**
* @file admin-settings-test-mail.test.tsx
* @description 환경설정 메일 탭 테스트 메일 기능 레이아웃 테스트
*
* 테스트 대상:
* - templates/.../partials/admin_settings/_tab_mail.json
*
* 검증 항목:
* - apiCall body에 to_email 파라미터 사용 (email 아닌)
* - 테스트 결과 인라인 표시 (testMailResult 상태)
* - 메일러 드라이버 옵션 (Sendmail/Log 미포함)
* - 버튼 disabled 상태 (발송 중)
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// ==============================
// 테스트용 컴포넌트 정의
// ==============================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, onClick, 'data-testid': testId }) => (
<button
type={type as any}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestH3: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h3 className={className}>{children || text}</h3>
);
const TestIcon: React.FC<{
name?: string;
className?: string;
}> = ({ name, className }) => (
<i className={`icon-${name} ${className || ''}`} data-testid={`icon-${name}`} data-icon={name} />
);
const TestLabel: React.FC<{
htmlFor?: string;
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ htmlFor, className, children, text }) => (
<label htmlFor={htmlFor} className={className}>
{children || text}
</label>
);
const TestInput: React.FC<{
type?: string;
name?: string;
placeholder?: string;
className?: string;
value?: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
'data-testid'?: string;
}> = ({ type, name, placeholder, className, value, onChange, 'data-testid': testId }) => (
<input
type={type}
name={name}
placeholder={placeholder}
className={className}
value={value}
onChange={onChange}
data-testid={testId}
/>
);
const TestSelect: React.FC<{
name?: string;
className?: string;
placeholder?: string;
options?: Array<{ label: string; value: string }>;
value?: string;
error?: string;
onChange?: (e: React.ChangeEvent<HTMLSelectElement>) => void;
}> = ({ name, className, options, value, error, onChange }) => (
<div data-testid={`select-${name}`}>
<select name={name} className={className} value={value} onChange={onChange}>
{options?.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
{error && <span className="error">{error}</span>}
</div>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// ==============================
// 레지스트리 설정
// ==============================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
Select: { component: TestSelect, metadata: { name: 'Select', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ==============================
// _tab_mail.json에서 핵심 부분 추출한 테스트용 레이아웃
// ==============================
const testMailLayout = {
version: '1.0.0',
layout_name: 'admin_settings_test_mail',
initLocal: {
form: { mail: { test_email: '' } },
isSendingTest: false,
testMailResult: null,
testMailResultMessage: null,
},
components: [
{
id: 'mail_settings',
type: 'basic',
name: 'Div',
children: [
{
id: 'field_mailer',
type: 'basic',
name: 'Div',
children: [
{
type: 'composite',
name: 'Select',
props: {
name: 'mail.mailer',
className: 'w-full',
options: [
{ label: 'SMTP', value: 'smtp' },
{ label: 'Mailgun', value: 'mailgun' },
{ label: 'SES (Amazon)', value: 'ses' },
],
},
},
],
},
{
id: 'test_mail_section',
type: 'basic',
name: 'Div',
children: [
{
type: 'basic',
name: 'Div',
props: { className: 'flex items-center gap-3' },
children: [
{
type: 'basic',
name: 'Input',
props: {
type: 'email',
name: 'mail.test_email',
placeholder: 'test@example.com',
},
},
{
id: 'test_mail_button',
type: 'basic',
name: 'Button',
props: {
disabled: '{{_local.isSendingTest}}',
'data-testid': 'test-mail-button',
},
actions: [
{
type: 'click',
handler: 'sequence',
actions: [
{
handler: 'setState',
params: {
target: 'local',
isSendingTest: true,
testMailResult: null,
testMailResultMessage: null,
},
},
{
handler: 'apiCall',
auth_required: true,
target: '/api/admin/settings/test-mail',
params: {
method: 'POST',
body: {
to_email: "{{_local.form?.mail?.test_email || ''}}",
},
},
onSuccess: [
{
handler: 'setState',
params: {
target: 'local',
isSendingTest: false,
testMailResult: 'success',
testMailResultMessage: '테스트 메일이 발송되었습니다.',
},
},
],
onError: [
{
handler: 'setState',
params: {
target: 'local',
isSendingTest: false,
testMailResult: 'error',
testMailResultMessage: '테스트 메일 발송에 실패했습니다.',
},
},
],
},
],
},
],
children: [
{
type: 'basic',
name: 'Icon',
if: '{{_local.isSendingTest}}',
props: { name: 'spinner', className: 'w-4 h-4 animate-spin' },
},
{
type: 'basic',
name: 'Icon',
if: '{{!_local.isSendingTest}}',
props: { name: 'paper-plane', className: 'w-4 h-4' },
},
{
type: 'basic',
name: 'Span',
text: '테스트 발송',
},
],
},
],
},
{
id: 'test_mail_result',
type: 'basic',
name: 'Div',
if: '{{_local.testMailResult}}',
props: {
className: "{{_local.testMailResult === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}}",
'data-testid': 'test-mail-result',
},
children: [
{
type: 'basic',
name: 'Icon',
if: "{{_local.testMailResult === 'success'}}",
props: { name: 'check-circle' },
},
{
type: 'basic',
name: 'Icon',
if: "{{_local.testMailResult === 'error'}}",
props: { name: 'exclamation-circle' },
},
{
type: 'basic',
name: 'Span',
text: "{{_local.testMailResultMessage ?? ''}}",
},
],
},
],
},
],
},
],
};
// ==============================
// 테스트
// ==============================
describe('환경설정 메일 탭 - 테스트 메일 기능', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
testUtils = createLayoutTest(testMailLayout, {
auth: {
isAuthenticated: true,
user: { id: 1, name: 'Admin', role: 'super_admin' },
authType: 'admin',
},
locale: 'ko',
componentRegistry: registry,
});
});
afterEach(() => {
testUtils.cleanup();
});
describe('레이아웃 구조 검증', () => {
it('레이아웃 정보가 올바르게 로드된다', () => {
const info = testUtils.getLayoutInfo();
expect(info.name).toBe('admin_settings_test_mail');
});
it('초기 로컬 상태가 올바르게 설정된다', () => {
const state = testUtils.getState();
expect(state._local.isSendingTest).toBe(false);
expect(state._local.testMailResult).toBeNull();
expect(state._local.testMailResultMessage).toBeNull();
});
});
describe('메일러 드라이버 옵션 검증', () => {
it('Select 옵션에 SMTP, Mailgun, SES만 포함된다', () => {
const mailerSelect = testMailLayout.components[0].children[0].children[0];
expect(mailerSelect.name).toBe('Select');
const options = mailerSelect.props.options;
const values = options.map((opt: any) => opt.value);
expect(values).toContain('smtp');
expect(values).toContain('mailgun');
expect(values).toContain('ses');
expect(values).not.toContain('sendmail');
expect(values).not.toContain('log');
});
it('SES 옵션 라벨이 "SES (Amazon)"이다', () => {
const mailerSelect = testMailLayout.components[0].children[0].children[0];
const sesOption = mailerSelect.props.options.find((opt: any) => opt.value === 'ses');
expect(sesOption.label).toBe('SES (Amazon)');
});
it('드라이버 옵션이 정확히 3개이다', () => {
const mailerSelect = testMailLayout.components[0].children[0].children[0];
expect(mailerSelect.props.options).toHaveLength(3);
});
});
describe('테스트 메일 apiCall 파라미터 검증', () => {
it('apiCall body에 to_email 파라미터를 사용한다 (email 아닌)', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
expect(button.id).toBe('test_mail_button');
const sequence = button.actions[0];
expect(sequence.handler).toBe('sequence');
const apiCall = sequence.actions[1];
expect(apiCall.handler).toBe('apiCall');
expect(apiCall.target).toBe('/api/admin/settings/test-mail');
expect(apiCall.params.method).toBe('POST');
// 핵심 검증: to_email 사용
expect(apiCall.params.body).toHaveProperty('to_email');
expect(apiCall.params.body).not.toHaveProperty('email');
});
it('apiCall에 auth_required가 true로 설정되어 있다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
const apiCall = button.actions[0].actions[1];
expect(apiCall.auth_required).toBe(true);
});
});
describe('테스트 메일 발송 상태 관리', () => {
it('발송 시작 시 isSendingTest이 true, 결과가 초기화된다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
const setStateAction = button.actions[0].actions[0];
expect(setStateAction.handler).toBe('setState');
expect(setStateAction.params.isSendingTest).toBe(true);
expect(setStateAction.params.testMailResult).toBeNull();
expect(setStateAction.params.testMailResultMessage).toBeNull();
});
it('발송 성공 시 testMailResult이 success로 설정된다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
const apiCall = button.actions[0].actions[1];
const onSuccess = apiCall.onSuccess[0];
expect(onSuccess.handler).toBe('setState');
expect(onSuccess.params.isSendingTest).toBe(false);
expect(onSuccess.params.testMailResult).toBe('success');
expect(onSuccess.params.testMailResultMessage).toBeTruthy();
});
it('발송 실패 시 testMailResult이 error로 설정된다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
const apiCall = button.actions[0].actions[1];
const onError = apiCall.onError[0];
expect(onError.handler).toBe('setState');
expect(onError.params.isSendingTest).toBe(false);
expect(onError.params.testMailResult).toBe('error');
expect(onError.params.testMailResultMessage).toBeTruthy();
});
});
describe('테스트 결과 인라인 표시', () => {
it('초기에는 결과 영역이 숨겨진다 (testMailResult이 null)', async () => {
await testUtils.render();
const state = testUtils.getState();
expect(state._local.testMailResult).toBeNull();
});
it('testMailResult이 success이면 결과 영역이 표시된다', async () => {
await testUtils.render();
testUtils.setState('testMailResult', 'success', 'local');
testUtils.setState('testMailResultMessage', '테스트 메일이 발송되었습니다.', 'local');
await testUtils.rerender();
const state = testUtils.getState();
expect(state._local.testMailResult).toBe('success');
expect(state._local.testMailResultMessage).toBe('테스트 메일이 발송되었습니다.');
});
it('testMailResult이 error이면 오류 메시지가 표시된다', async () => {
await testUtils.render();
testUtils.setState('testMailResult', 'error', 'local');
testUtils.setState('testMailResultMessage', '테스트 메일 발송에 실패했습니다.', 'local');
await testUtils.rerender();
const state = testUtils.getState();
expect(state._local.testMailResult).toBe('error');
expect(state._local.testMailResultMessage).toBe('테스트 메일 발송에 실패했습니다.');
});
it('결과 영역의 if 조건이 testMailResult 존재 여부이다', () => {
const resultDiv = testMailLayout.components[0].children[1].children[1];
expect(resultDiv.id).toBe('test_mail_result');
expect(resultDiv.if).toBe('{{_local.testMailResult}}');
});
it('성공 시 check-circle 아이콘, 실패 시 exclamation-circle 아이콘이 표시된다', () => {
const resultDiv = testMailLayout.components[0].children[1].children[1];
const successIcon = resultDiv.children[0];
expect(successIcon.name).toBe('Icon');
expect(successIcon.if).toBe("{{_local.testMailResult === 'success'}}");
expect(successIcon.props.name).toBe('check-circle');
const errorIcon = resultDiv.children[1];
expect(errorIcon.name).toBe('Icon');
expect(errorIcon.if).toBe("{{_local.testMailResult === 'error'}}");
expect(errorIcon.props.name).toBe('exclamation-circle');
});
it('결과 메시지가 Span으로 표시된다', () => {
const resultDiv = testMailLayout.components[0].children[1].children[1];
const messageSpan = resultDiv.children[2];
expect(messageSpan.name).toBe('Span');
expect(messageSpan.text).toBe("{{_local.testMailResultMessage ?? ''}}");
});
});
describe('버튼 상태 관리', () => {
it('발송 중 버튼이 disabled 된다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
expect(button.props.disabled).toBe('{{_local.isSendingTest}}');
});
it('isSendingTest 상태를 변경할 수 있다', async () => {
await testUtils.render();
testUtils.setState('isSendingTest', true, 'local');
expect(testUtils.getState()._local.isSendingTest).toBe(true);
testUtils.setState('isSendingTest', false, 'local');
expect(testUtils.getState()._local.isSendingTest).toBe(false);
});
it('발송 중 spinner 아이콘이 표시된다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
const spinnerIcon = button.children[0];
expect(spinnerIcon.name).toBe('Icon');
expect(spinnerIcon.if).toBe('{{_local.isSendingTest}}');
expect(spinnerIcon.props.name).toBe('spinner');
});
it('대기 중 paper-plane 아이콘이 표시된다', () => {
const button = testMailLayout.components[0].children[1].children[0].children[1];
const planeIcon = button.children[1];
expect(planeIcon.name).toBe('Icon');
expect(planeIcon.if).toBe('{{!_local.isSendingTest}}');
expect(planeIcon.props.name).toBe('paper-plane');
});
});
});
@@ -0,0 +1,287 @@
/**
* @file admin-template-layout-edit.test.tsx
* @description 템플릿 레이아웃 편집 페이지 테스트
*
* 테스트 대상:
* - admin_template_layout_edit.json: 미리보기 버튼 액션 구조
* - partials/admin_template_layout_edit/_modal_template_changelog.json: CHANGELOG 모달
* - 어빌리티 기반 조건부 렌더링 (저장 버튼)
*
* 검증 항목:
* - 미리보기 버튼이 sequence → apiCall → openWindow 패턴 사용
* - CHANGELOG 버튼이 sequence → setState → openModal → apiCall 패턴 사용
* - CHANGELOG 모달 JSON 구조 (로딩, 빈 상태, 데이터 표시)
* - 저장 버튼에 can_update 어빌리티 조건 존재
* - modals 섹션에 CHANGELOG 모달 partial 등록
*/
import { describe, it, expect } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
// ==============================
// 레이아웃 JSON 파일 로드
// ==============================
const LAYOUTS_BASE = path.resolve(__dirname, '../../layouts');
function loadLayout(relativePath: string): any {
const fullPath = path.resolve(LAYOUTS_BASE, relativePath);
return JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
}
const layoutEditJson = loadLayout('admin_template_layout_edit.json');
const changelogModalJson = loadLayout('partials/admin_template_layout_edit/_modal_template_changelog.json');
// ==============================
// 헬퍼: JSON 구조 내 컴포넌트 검색
// ==============================
function findAllComponents(node: any, predicate: (n: any) => boolean): any[] {
const results: any[] = [];
if (!node) return results;
if (predicate(node)) {
results.push(node);
}
if (Array.isArray(node.children)) {
for (const child of node.children) {
results.push(...findAllComponents(child, predicate));
}
}
if (Array.isArray(node.slots?.content)) {
for (const child of node.slots.content) {
results.push(...findAllComponents(child, predicate));
}
}
return results;
}
function findComponent(root: any, predicate: (n: any) => boolean): any | null {
const results = findAllComponents(root, predicate);
return results.length > 0 ? results[0] : null;
}
// ==============================
// 미리보기 버튼 테스트
// ==============================
describe('미리보기 버튼', () => {
it('sequence → apiCall → openWindow 패턴을 사용한다', () => {
// 미리보기 버튼 찾기 (preview 엔드포인트를 호출하는 버튼)
const previewButton = findComponent(layoutEditJson, (n) => {
if (!n.actions) return false;
return n.actions.some((a: any) =>
a.handler === 'sequence' &&
JSON.stringify(a.params?.actions ?? []).includes('/preview')
);
});
expect(previewButton).not.toBeNull();
const sequenceAction = previewButton.actions.find(
(a: any) => a.handler === 'sequence'
);
expect(sequenceAction).toBeDefined();
const actions = sequenceAction.params.actions;
expect(actions).toBeDefined();
expect(actions.length).toBeGreaterThanOrEqual(1);
// apiCall 액션 찾기
const apiCallAction = actions.find((a: any) => a.handler === 'apiCall');
expect(apiCallAction).toBeDefined();
expect(apiCallAction.params.method).toBe('POST');
expect(apiCallAction.target).toContain('/preview');
expect(apiCallAction.auth_required).toBe(true);
// onSuccess에 openWindow 존재
expect(apiCallAction.onSuccess).toBeDefined();
const openWindowAction = apiCallAction.onSuccess.find(
(a: any) => a.handler === 'openWindow'
);
expect(openWindowAction).toBeDefined();
expect(openWindowAction.params.path).toContain('response.data.token');
});
it('apiCall body에 editorContent를 전달한다', () => {
const previewButton = findComponent(layoutEditJson, (n) => {
if (!n.actions) return false;
return n.actions.some((a: any) =>
JSON.stringify(a.params?.actions ?? []).includes('/preview')
);
});
const sequenceAction = previewButton.actions.find(
(a: any) => a.handler === 'sequence'
);
const apiCallAction = sequenceAction.params.actions.find(
(a: any) => a.handler === 'apiCall'
);
expect(apiCallAction.params.body).toBeDefined();
expect(JSON.stringify(apiCallAction.params.body)).toContain('editorContent');
});
it('type: "button" prop이 설정되어 있다', () => {
const previewButton = findComponent(layoutEditJson, (n) => {
if (!n.actions) return false;
return n.actions.some((a: any) =>
JSON.stringify(a.params?.actions ?? []).includes('/preview')
);
});
expect(previewButton.props?.type).toBe('button');
});
});
// ==============================
// CHANGELOG 버튼 테스트
// ==============================
describe('CHANGELOG 버튼', () => {
it('sequence → setState → openModal → apiCall 패턴을 사용한다', () => {
// CHANGELOG 버튼 찾기 (template_changelog_modal을 여는 버튼)
const changelogButton = findComponent(layoutEditJson, (n) => {
if (!n.actions) return false;
return n.actions.some((a: any) =>
JSON.stringify(a).includes('template_changelog_modal')
);
});
expect(changelogButton).not.toBeNull();
expect(changelogButton.name).toBe('Button');
const sequenceAction = changelogButton.actions.find(
(a: any) => a.handler === 'sequence'
);
expect(sequenceAction).toBeDefined();
const actions = sequenceAction.params.actions;
// setState (loading 상태 설정)
const setStateAction = actions.find((a: any) => a.handler === 'setState');
expect(setStateAction).toBeDefined();
expect(setStateAction.params.loadingChangelog).toBe(true);
// openModal
const openModalAction = actions.find((a: any) => a.handler === 'openModal');
expect(openModalAction).toBeDefined();
expect(openModalAction.target).toBe('template_changelog_modal');
// apiCall (changelog 조회)
const apiCallAction = actions.find((a: any) => a.handler === 'apiCall');
expect(apiCallAction).toBeDefined();
expect(apiCallAction.params.method).toBe('GET');
expect(apiCallAction.target).toContain('/changelog');
expect(apiCallAction.auth_required).toBe(true);
});
it('apiCall onSuccess에서 templateChangelog와 loadingChangelog를 설정한다', () => {
const changelogButton = findComponent(layoutEditJson, (n) => {
if (!n.actions) return false;
return n.actions.some((a: any) =>
JSON.stringify(a).includes('template_changelog_modal')
);
});
const sequenceAction = changelogButton.actions.find(
(a: any) => a.handler === 'sequence'
);
const apiCallAction = sequenceAction.params.actions.find(
(a: any) => a.handler === 'apiCall'
);
const onSuccessSetState = apiCallAction.onSuccess.find(
(a: any) => a.handler === 'setState'
);
expect(onSuccessSetState).toBeDefined();
expect(onSuccessSetState.params).toHaveProperty('templateChangelog');
expect(onSuccessSetState.params.loadingChangelog).toBe(false);
});
});
// ==============================
// CHANGELOG 모달 JSON 구조 테스트
// ==============================
describe('CHANGELOG 모달 구조', () => {
it('올바른 모달 ID와 구조를 가진다', () => {
expect(changelogModalJson.id).toBe('template_changelog_modal');
expect(changelogModalJson.type).toBe('composite');
expect(changelogModalJson.name).toBe('Modal');
expect(changelogModalJson.props.size).toBe('lg');
});
it('로딩 상태를 표시하는 조건부 영역이 있다', () => {
const loadingDiv = changelogModalJson.children.find(
(c: any) => c.if && c.if.includes('loadingChangelog') && !c.if.includes('!')
);
expect(loadingDiv).toBeDefined();
});
it('빈 상태를 표시하는 조건부 영역이 있다', () => {
const emptyDiv = changelogModalJson.children.find(
(c: any) => c.if && c.if.includes('templateChangelog.length === 0')
);
expect(emptyDiv).toBeDefined();
});
it('changelog 목록을 반복 렌더링하는 영역이 있다', () => {
const listDiv = changelogModalJson.children.find(
(c: any) => c.if && c.if.includes('templateChangelog.length > 0')
);
expect(listDiv).toBeDefined();
// iteration이 존재하는 자식 확인
const iterationChild = findComponent(listDiv, (n) => n.iteration?.source?.includes('templateChangelog'));
expect(iterationChild).not.toBeNull();
});
it('is_partial 메타데이터가 설정되어 있다', () => {
expect(changelogModalJson.meta?.is_partial).toBe(true);
});
});
// ==============================
// modals 섹션 테스트
// ==============================
describe('modals 섹션', () => {
it('template_changelog 모달 partial이 등록되어 있다', () => {
expect(layoutEditJson.modals).toBeDefined();
expect(Array.isArray(layoutEditJson.modals)).toBe(true);
const changelogModal = layoutEditJson.modals.find(
(m: any) => m.partial?.includes('_modal_template_changelog')
);
expect(changelogModal).toBeDefined();
});
it('version_history 모달 partial도 등록되어 있다', () => {
const versionModal = layoutEditJson.modals.find(
(m: any) => m.partial?.includes('_modal_version_history')
);
expect(versionModal).toBeDefined();
});
});
// ==============================
// 어빌리티 기반 조건부 렌더링 테스트
// ==============================
describe('어빌리티 기반 조건부 렌더링', () => {
it('저장 버튼에 can_update 조건이 있다', () => {
// 저장 버튼: apiCall로 PUT 요청하는 버튼 or save 관련 텍스트
const saveButton = findComponent(layoutEditJson, (n) => {
return n.if && n.if.includes('can_update');
});
expect(saveButton).not.toBeNull();
expect(saveButton.if).toContain('abilities');
expect(saveButton.if).toContain('can_update');
});
});
@@ -0,0 +1,208 @@
/**
* @file admin-user-delete-modal.test.tsx
* @description 사용자 삭제 모달 레이아웃 테스트
*
* 테스트 대상:
* - templates/.../layouts/admin_user_list.json (삭제 모달 부분)
*
* 검증 항목:
* - 삭제 모달 데이터 전달: setState(_global.modal_data) -> openModal 패턴
* - apiCall target에 _global.modal_data.id가 포함되는지 확인
* - 삭제 버튼 스피너/disabled 상태 (규정: modal-usage.md 위험 작업 버튼 로딩 상태)
* - 취소 버튼도 삭제 중 비활성화
* - onError 시 isDeleting 복원
*/
import { describe, it, expect } from 'vitest';
// ==============================
// 테스트
// ==============================
describe('사용자 삭제 모달 레이아웃 테스트', () => {
describe('모달 데이터 전달 패턴', () => {
it('삭제 모달은 setState(_global.modal_data) -> openModal 패턴을 사용해야 한다', () => {
// admin_user_list.json의 switch > delete 케이스 구조 검증
// 이 테스트는 레이아웃 JSON 구조를 직접 검증
const layout = require('../../layouts/admin_user_list.json');
// body > named_actions 또는 body 내 switch 구조에서 delete 케이스를 찾기
const bodyStr = JSON.stringify(layout);
// setState + target: global + modal_data 패턴이 존재해야 함
expect(bodyStr).toContain('"handler":"setState"');
expect(bodyStr).toContain('"target":"global"');
expect(bodyStr).toContain('"modal_data"');
// openModal이 onSuccess 내에 있어야 함 (setState 이후)
expect(bodyStr).toContain('"handler":"openModal"');
expect(bodyStr).toContain('"target":"delete_confirm_modal"');
// 잘못된 패턴 (openModal의 params.data로 직접 전달)이 없어야 함
expect(bodyStr).not.toContain('"handler":"openModal","target":"delete_confirm_modal","params"');
});
it('apiCall target에 _global.modal_data.id를 사용해야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const bodyStr = JSON.stringify(layout);
// 올바른 패턴: _global.modal_data.uuid
expect(bodyStr).toContain('/api/admin/users/{{_global.modal_data.uuid}}');
// 잘못된 패턴: modal_data.uuid (global 접두사 없음)
expect(bodyStr).not.toMatch(/\/api\/admin\/users\/\{\{modal_data\.uuid\}\}/);
});
});
describe('삭제 버튼 스피너/disabled 상태', () => {
it('삭제 모달에 isDeleting 로딩 상태가 구현되어 있어야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const bodyStr = JSON.stringify(layout);
// _global.isDeleting 상태 사용
expect(bodyStr).toContain('_global.isDeleting');
// sequence 핸들러로 setState -> apiCall 순서
expect(bodyStr).toContain('"handler":"sequence"');
});
it('삭제/취소 버튼 모두 isDeleting 시 disabled여야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
expect(deleteModal).toBeDefined();
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const buttons = footerDiv.children;
// 취소 버튼 (첫 번째)
expect(buttons[0].props.disabled).toBe('{{_global.isDeleting}}');
// 삭제 버튼 (두 번째)
expect(buttons[1].props.disabled).toBe('{{_global.isDeleting}}');
});
it('삭제 버튼에 스피너 아이콘과 텍스트 삼항연산자가 있어야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const deleteButton = footerDiv.children[1]; // 삭제 버튼
// 스피너 Icon 존재
const spinnerIcon = deleteButton.children.find(
(c: any) => c.name === 'Icon' && c.props?.name === 'spinner'
);
expect(spinnerIcon).toBeDefined();
expect(spinnerIcon.if).toBe('{{_global.isDeleting}}');
expect(spinnerIcon.props.className).toContain('animate-spin');
// 텍스트 삼항 연산자
const textSpan = deleteButton.children.find((c: any) => c.name === 'Span');
expect(textSpan).toBeDefined();
expect(textSpan.text).toContain('_global.isDeleting');
expect(textSpan.text).toContain('$t:common.deleting');
expect(textSpan.text).toContain('$t:common.delete');
});
it('삭제 버튼 className에 flex items-center gap-2가 있어야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const deleteButton = footerDiv.children[1];
expect(deleteButton.props.className).toContain('flex items-center gap-2');
expect(deleteButton.props.className).toContain('disabled:opacity-50');
expect(deleteButton.props.className).toContain('disabled:cursor-not-allowed');
});
});
describe('onSuccess/onError 핸들러 구조', () => {
it('onSuccess에 closeModal, setState(false), refetchDataSource, toast가 있어야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const deleteButton = footerDiv.children[1];
// sequence > apiCall 추출
const sequenceAction = deleteButton.actions[0];
expect(sequenceAction.handler).toBe('sequence');
const apiCallAction = sequenceAction.actions.find((a: any) => a.handler === 'apiCall');
expect(apiCallAction).toBeDefined();
// onSuccess 핸들러 순서 검증 (setState → refetchDataSource → toast → closeModal)
const onSuccess = apiCallAction.onSuccess;
expect(onSuccess).toHaveLength(4);
expect(onSuccess[0].handler).toBe('setState');
expect(onSuccess[0].params.isDeleting).toBe(false);
expect(onSuccess[1].handler).toBe('refetchDataSource');
expect(onSuccess[1].params.dataSourceId).toBe('users');
expect(onSuccess[2].handler).toBe('toast');
expect(onSuccess[3].handler).toBe('closeModal');
});
it('onError에 setState(false)와 toast(error)가 있어야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const deleteButton = footerDiv.children[1];
const sequenceAction = deleteButton.actions[0];
const apiCallAction = sequenceAction.actions.find((a: any) => a.handler === 'apiCall');
// onError 핸들러 검증
const onError = apiCallAction.onError;
expect(onError).toBeDefined();
expect(onError).toHaveLength(2);
expect(onError[0].handler).toBe('setState');
expect(onError[0].params.isDeleting).toBe(false);
expect(onError[1].handler).toBe('toast');
expect(onError[1].params.type).toBe('error');
});
it('onError toast 메시지는 {{error.message}}를 사용해야 한다 ($error 아님)', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const deleteButton = footerDiv.children[1];
const sequenceAction = deleteButton.actions[0];
const apiCallAction = sequenceAction.actions.find((a: any) => a.handler === 'apiCall');
const onError = apiCallAction.onError;
const toastAction = onError.find((a: any) => a.handler === 'toast');
// 올바른 패턴: {{error.message}} ($ 접두사 없음)
expect(toastAction.params.message).toBe('{{error.message}}');
// 금지 패턴: {{$error.message}} — ActionDispatcher는 error 키 사용
expect(toastAction.params.message).not.toContain('$error');
});
});
describe('삭제 버튼 스타일 규정 준수', () => {
it('취소 버튼에 disabled:opacity-50 disabled:cursor-not-allowed가 있어야 한다', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const cancelButton = footerDiv.children[0];
expect(cancelButton.props.className).toContain('disabled:opacity-50');
expect(cancelButton.props.className).toContain('disabled:cursor-not-allowed');
});
it('삭제 버튼은 bg-red-600 스타일이어야 한다 (위험 작업)', () => {
const layout = require('../../layouts/admin_user_list.json');
const modals = layout.modals;
const deleteModal = modals.find((m: any) => m.id === 'delete_confirm_modal');
const footerDiv = deleteModal.children[deleteModal.children.length - 1];
const deleteButton = footerDiv.children[1];
expect(deleteButton.props.className).toContain('bg-red-600');
});
});
});
@@ -0,0 +1,406 @@
/**
* @file admin-user-form-roles.test.tsx
* @description 사용자 등록/수정 폼 - 역할 TagInput 렌더링 테스트
*
* 테스트 대상:
* - 역할 필드가 TagInput으로 렌더링되는지
* - options가 roles API 데이터에서 {value: id, label: name} 형태로 매핑되는지
* - 생성/수정 모드에서 value가 올바르게 바인딩되는지
* - onChange 시 _local.form.role_ids가 정수 배열로 업데이트되는지
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
// 테스트용 컴포넌트 정의
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestLabel: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<label className={className}>{children || text}</label>
);
const TestTagInput: React.FC<{
name?: string;
value?: (string | number)[];
options?: Array<{ value: string | number; label: string }>;
placeholder?: string;
noOptionsMessage?: string;
className?: string;
defaultVariant?: string;
onChange?: (event: any) => void;
'data-testid'?: string;
}> = ({ name, value, options, placeholder, noOptionsMessage, className, defaultVariant, onChange, 'data-testid': testId }) => (
<div
data-testid={testId || `taginput-${name}`}
data-name={name}
data-value={JSON.stringify(value ?? [])}
data-options={JSON.stringify(options ?? [])}
data-placeholder={placeholder}
data-no-options-message={noOptionsMessage}
data-variant={defaultVariant}
className={className}
>
{(value ?? []).map((v: any) => {
const opt = (options ?? []).find((o: any) => o.value === v);
return <span key={v} data-testid={`tag-${v}`}>{opt?.label ?? v}</span>;
})}
{placeholder && (value ?? []).length === 0 && <span data-testid="placeholder">{placeholder}</span>}
</div>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
TagInput: { component: TestTagInput, metadata: { name: 'TagInput', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 테스트용 역할 데이터
const mockRolesData = [
{ id: 1, identifier: 'super_admin', name: '슈퍼 관리자', is_system: true, is_active: true },
{ id: 2, identifier: 'admin', name: '관리자', is_system: true, is_active: true },
{ id: 3, identifier: 'manager', name: '매니저', is_system: false, is_active: true },
];
// 역할 TagInput이 포함된 레이아웃 JSON (생성 모드)
const createModeLayout = {
version: '1.0.0',
layout_name: 'test_user_form_create',
data_sources: [
{
id: 'roles',
type: 'api',
endpoint: '/api/admin/roles/active',
method: 'GET',
auto_fetch: true,
auth_required: true,
fallback: { data: [] },
},
],
components: [
{
id: 'field_roles',
type: 'basic',
name: 'Div',
props: { className: 'md:col-span-2' },
children: [
{
type: 'basic',
name: 'Label',
props: { className: 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2' },
text: '역할',
},
{
type: 'composite',
name: 'TagInput',
props: {
name: 'role_ids',
value: '{{_local.form?.role_ids ?? _local.form?.roles?.map(r => r.id) ?? []}}',
options: '{{(roles?.data ?? []).map(r => ({value: r.id, label: r.name}))}}',
placeholder: '역할을 선택하세요',
noOptionsMessage: '선택 가능한 역할이 없습니다',
className: 'w-full',
defaultVariant: 'blue',
},
actions: [
{
type: 'change',
handler: 'setState',
params: {
target: 'local',
form: {
role_ids: '{{$event.target.value}}',
},
},
},
],
},
],
},
],
};
// 수정 모드 레이아웃 (initLocal 시뮬레이션)
const editModeLayout = {
...createModeLayout,
layout_name: 'test_user_form_edit',
};
describe('사용자 폼 - 역할 TagInput 테스트', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
describe('생성 모드', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
it('역할 TagInput이 렌더링된다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
// 라벨이 렌더링되는지 확인
expect(screen.getByText('역할')).toBeInTheDocument();
});
it('roles API 데이터가 options로 매핑된다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
initialData: {
roles: { data: mockRolesData },
},
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
// TagInput의 options가 {value: id, label: name} 형태로 매핑되는지 확인
const tagInput = screen.getByTestId('taginput-role_ids');
const options = JSON.parse(tagInput.getAttribute('data-options') || '[]');
expect(options).toEqual([
{ value: 1, label: '슈퍼 관리자' },
{ value: 2, label: '관리자' },
{ value: 3, label: '매니저' },
]);
});
it('생성 모드에서 초기 value는 빈 배열이다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
initialData: {
roles: { data: mockRolesData },
},
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
const tagInput = screen.getByTestId('taginput-role_ids');
const value = JSON.parse(tagInput.getAttribute('data-value') || '[]');
expect(value).toEqual([]);
});
it('역할 선택 시 _local.form.role_ids가 업데이트된다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
initialData: {
roles: { data: mockRolesData },
},
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
// setState를 통해 role_ids 설정 (TagInput onChange 시뮬레이션)
testUtils.setState('form.role_ids', [1, 3], 'local');
const state = testUtils.getState();
expect(state._local.form.role_ids).toEqual([1, 3]);
});
});
describe('수정 모드', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
it('기존 역할이 value로 표시된다', async () => {
testUtils = createLayoutTest(editModeLayout, {
translations: {},
componentRegistry: registry,
initialData: {
roles: { data: mockRolesData },
},
initialState: {
_local: {
form: {
roles: [
{ id: 1, identifier: 'super_admin', name: '슈퍼 관리자' },
{ id: 2, identifier: 'admin', name: '관리자' },
],
},
},
},
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
// roles 객체 배열에서 id가 추출되어 value로 사용되는지 확인
const tagInput = screen.getByTestId('taginput-role_ids');
const value = JSON.parse(tagInput.getAttribute('data-value') || '[]');
expect(value).toEqual([1, 2]);
});
it('role_ids가 이미 있으면 roles보다 우선된다', async () => {
testUtils = createLayoutTest(editModeLayout, {
translations: {},
componentRegistry: registry,
initialData: {
roles: { data: mockRolesData },
},
initialState: {
_local: {
form: {
role_ids: [3],
roles: [
{ id: 1, identifier: 'super_admin', name: '슈퍼 관리자' },
],
},
},
},
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
// role_ids가 roles보다 우선되는지 확인
const tagInput = screen.getByTestId('taginput-role_ids');
const value = JSON.parse(tagInput.getAttribute('data-value') || '[]');
expect(value).toEqual([3]);
});
it('모든 역할 해제 시 빈 배열이 된다', async () => {
testUtils = createLayoutTest(editModeLayout, {
translations: {},
componentRegistry: registry,
initialData: {
roles: { data: mockRolesData },
},
initialState: {
_local: {
form: {
role_ids: [1, 2],
},
},
},
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
// 모든 역할 해제
testUtils.setState('form.role_ids', [], 'local');
const state = testUtils.getState();
expect(state._local.form.role_ids).toEqual([]);
});
});
describe('엣지 케이스', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
it('roles 데이터가 없을 때 빈 options로 렌더링된다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
});
testUtils.mockApi('roles', {
response: { data: [] },
});
await testUtils.render();
const tagInput = screen.getByTestId('taginput-role_ids');
const options = JSON.parse(tagInput.getAttribute('data-options') || '[]');
expect(options).toEqual([]);
});
it('placeholder가 올바르게 표시된다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
const tagInput = screen.getByTestId('taginput-role_ids');
expect(tagInput.getAttribute('data-placeholder')).toBe('역할을 선택하세요');
});
it('defaultVariant가 blue로 설정된다', async () => {
testUtils = createLayoutTest(createModeLayout, {
translations: {},
componentRegistry: registry,
});
testUtils.mockApi('roles', {
response: { data: mockRolesData },
});
await testUtils.render();
const tagInput = screen.getByTestId('taginput-role_ids');
expect(tagInput.getAttribute('data-variant')).toBe('blue');
});
});
});
@@ -0,0 +1,816 @@
/**
* @file core-update.test.tsx
* @description 코어 업데이트 관련 레이아웃 테스트
*
* 테스트 대상:
* - errors/maintenance.json (Admin): 관리자 maintenance 페이지
* - errors/maintenance.json (User): 사용자 maintenance 페이지
* - partials/admin_settings/_modal_core_update_result.json: 업데이트 확인 결과 모달
* - partials/admin_settings/_modal_core_changelog.json: 코어 변경사항 모달
* - partials/admin_settings/_modal_core_update_guide.json: 업데이트 터미널 안내 모달
*
* 검증 항목:
* - maintenance 레이아웃 JSON 구조 (extends, meta, slots)
* - 업데이트 결과 모달 구조 (버전 정보, 업데이트 가능/불가 섹션, 액션)
* - 변경사항 모달 구조 (3단 iteration: entry → category → items)
* - 업데이트 안내 모달 구조 (경고, 터미널 명령어)
* - 실제 렌더링 검증 (createLayoutTest 활용)
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
import * as fs from 'fs';
import * as path from 'path';
// ==============================
// 레이아웃 JSON 파일 로드 헬퍼
// ==============================
const ADMIN_PARTIALS_BASE = path.resolve(
__dirname,
'../../layouts/partials',
);
const ADMIN_LAYOUTS_BASE = path.resolve(
__dirname,
'../../layouts',
);
const USER_LAYOUTS_BASE = path.resolve(
__dirname,
'../../../sirsoft-basic/layouts',
);
function loadAdminLayout(relativePath: string): any {
const fullPath = path.resolve(ADMIN_LAYOUTS_BASE, relativePath);
return JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
}
function loadUserLayout(relativePath: string): any {
const fullPath = path.resolve(USER_LAYOUTS_BASE, relativePath);
return JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
}
function loadPartial(relativePath: string): any {
const fullPath = path.resolve(ADMIN_PARTIALS_BASE, relativePath);
return JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
}
// ==============================
// 테스트용 컴포넌트 정의
// ==============================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
disabled?: boolean;
children?: React.ReactNode;
onClick?: () => void;
'data-testid'?: string;
}> = ({ type, className, disabled, children, onClick, 'data-testid': testId }) => (
<button
type={type as any}
className={className}
disabled={disabled}
onClick={onClick}
data-testid={testId}
>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<span className={className}>{children || text}</span>
);
const TestP: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<p className={className}>{children || text}</p>
);
const TestH1: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<h1 className={className}>{children || text}</h1>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={`icon-${name} ${className || ''}`} data-testid={`icon-${name}`} data-icon={name} data-size={size} />
);
const TestUl: React.FC<{
className?: string;
children?: React.ReactNode;
}> = ({ className, children }) => (
<ul className={className}>{children}</ul>
);
const TestLi: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
}> = ({ className, children, text }) => (
<li className={className}>{children || text}</li>
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// ==============================
// 레지스트리 설정
// ==============================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
H1: { component: TestH1, metadata: { name: 'H1', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
Ul: { component: TestUl, metadata: { name: 'Ul', type: 'basic' } },
Li: { component: TestLi, metadata: { name: 'Li', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// ==============================
// 모달 children $parent._local → _local 변환 헬퍼
// (모달 children을 테스트에서 직접 렌더링 시 $parent._local 컨텍스트가 없으므로 변환 필요)
// ==============================
function replaceParentLocalRefs(obj: any): any {
if (typeof obj === 'string') {
return obj.replace(/\$parent\._local/g, '_local');
}
if (Array.isArray(obj)) {
return obj.map(replaceParentLocalRefs);
}
if (obj && typeof obj === 'object') {
const result: any = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = replaceParentLocalRefs(value);
}
return result;
}
return obj;
}
// ==============================
// JSON 트리 탐색 헬퍼
// ==============================
function findInTree(nodes: any[], predicate: (node: any) => boolean): any | undefined {
for (const node of nodes) {
if (predicate(node)) return node;
if (node.children) {
const found = findInTree(node.children, predicate);
if (found) return found;
}
}
return undefined;
}
function findAllInTree(nodes: any[], predicate: (node: any) => boolean): any[] {
const results: any[] = [];
for (const node of nodes) {
if (predicate(node)) results.push(node);
if (node.children) {
results.push(...findAllInTree(node.children, predicate));
}
}
return results;
}
// ==============================
// 샘플 데이터
// ==============================
const sampleChangelog = [
{
version: '1.1.0',
date: '2026-03-05',
categories: [
{
name: 'Added',
items: ['코어 업데이트 기능 추가', '유지보수 모드 지원'],
},
{
name: 'Fixed',
items: ['설정 저장 버그 수정'],
},
],
},
];
const multiVersionChangelog = [
{
version: '1.2.0',
date: '2026-03-07',
categories: [
{
name: 'Added',
items: ['신규 기능 X 추가'],
},
],
},
{
version: '1.1.0',
date: '2026-03-05',
categories: [
{
name: 'Changed',
items: ['기존 기능 Y 변경'],
},
{
name: 'Fixed',
items: ['버그 Z 수정', '버그 W 수정'],
},
],
},
];
const translations = {
admin: {
settings: {
info: {
update_result_title: '업데이트 확인 결과',
current_version: '현재 버전',
latest_version: '최신 버전',
update_available_message: '새로운 업데이트가 있습니다.',
no_update_message: '현재 최신 버전을 사용 중입니다.',
view_changelog: '변경사항 보기',
how_to_update: '업데이트 방법',
changelog_title: '변경사항',
no_changelog: '변경사항 정보가 없습니다.',
update_guide_title: '업데이트 방법',
update_guide_warning: '서버 터미널에서 실행하세요.',
update_guide_desc: '아래 명령어를 실행하여 업데이트합니다.',
update_guide_note: '업데이트 전 백업을 권장합니다.',
},
},
},
errors: {
maintenance: {
title: '시스템 점검 중',
message: '현재 시스템 업데이트가 진행 중입니다.',
description: '잠시 후 다시 접속해 주세요.',
},
},
error: {
maintenance: {
title: '시스템 점검 중',
description: '잠시 후 다시 접속해 주세요.',
back_to_home: '홈으로 돌아가기',
},
},
};
// ============================================================
// 1. JSON 구조 검증 테스트
// ============================================================
describe('코어 업데이트 레이아웃 JSON 구조', () => {
describe('Admin Maintenance 레이아웃', () => {
let layout: any;
beforeEach(() => {
layout = loadAdminLayout('errors/maintenance.json');
});
it('_admin_base를 상속한다', () => {
expect(layout.extends).toBe('_admin_base');
});
it('meta에 에러 레이아웃 플래그와 503 코드를 갖는다', () => {
expect(layout.meta.is_error_layout).toBe(true);
expect(layout.meta.error_code).toBe(503);
});
it('i18n 제목을 $t:errors.maintenance.title로 설정한다', () => {
expect(layout.meta.title).toBe('$t:errors.maintenance.title');
});
it('content 슬롯에 maintenance 컨테이너가 있다', () => {
expect(layout.slots.content).toHaveLength(1);
expect(layout.slots.content[0].id).toBe('maintenance_container');
});
it('spinning gear 아이콘이 포함되어 있다', () => {
const icon = findInTree(layout.slots.content, (n: any) => n.name === 'Icon');
expect(icon).toBeDefined();
expect(icon.props.name).toBe('gear');
expect(icon.props.className).toContain('animate-spin');
});
it('제목, 메시지, 설명 텍스트가 i18n 키를 사용한다', () => {
const h1 = findInTree(layout.slots.content, (n: any) => n.name === 'H1');
expect(h1.text).toBe('$t:errors.maintenance.title');
const pNodes = findAllInTree(layout.slots.content, (n: any) => n.name === 'P');
expect(pNodes.length).toBeGreaterThanOrEqual(2);
expect(pNodes[0].text).toBe('$t:errors.maintenance.message');
expect(pNodes[1].text).toBe('$t:errors.maintenance.description');
});
});
describe('User Maintenance 레이아웃', () => {
let layout: any;
beforeEach(() => {
layout = loadUserLayout('errors/maintenance.json');
});
it('_user_base를 상속한다', () => {
expect(layout.extends).toBe('_user_base');
});
it('meta에 에러 레이아웃 플래그를 갖는다', () => {
expect(layout.meta.is_error_layout).toBe(true);
});
it('error. 네임스페이스의 i18n 키를 사용한다', () => {
expect(layout.meta.title).toBe('$t:error.maintenance.title');
});
it('홈으로 돌아가기 버튼이 포함되어 있다', () => {
const button = findInTree(layout.slots.content, (n: any) => n.name === 'Button');
expect(button).toBeDefined();
expect(button.actions).toBeDefined();
const navigateAction = button.actions.find((a: any) => a.handler === 'navigate');
expect(navigateAction).toBeDefined();
expect(navigateAction.params.path).toBe('/');
});
it('spinning gear 아이콘이 포함되어 있다', () => {
const icon = findInTree(layout.slots.content, (n: any) => n.name === 'Icon' && n.props?.name === 'gear');
expect(icon).toBeDefined();
expect(icon.props.className).toContain('animate-spin');
});
});
describe('코어 업데이트 결과 모달', () => {
let modal: any;
beforeEach(() => {
modal = loadPartial('admin_settings/_modal_core_update_result.json');
});
it('모달 ID가 core_update_result_modal이다', () => {
expect(modal.id).toBe('core_update_result_modal');
});
it('모달 사이즈가 md이다', () => {
expect(modal.props.size).toBe('md');
});
it('현재 버전과 최신 버전 표시 영역이 있다', () => {
const spans = findAllInTree(modal.children, (n: any) => n.name === 'Span');
const currentVersionText = spans.find((s: any) => s.text === '$t:admin.settings.info.current_version');
const latestVersionText = spans.find((s: any) => s.text === '$t:admin.settings.info.latest_version');
expect(currentVersionText).toBeDefined();
expect(latestVersionText).toBeDefined();
});
it('업데이트 가능 섹션이 if 조건으로 제어된다', () => {
const updateSection = findInTree(modal.children, (n: any) => n.id === 'update_available_section');
expect(updateSection).toBeDefined();
expect(updateSection.if).toBe('{{$parent._local.coreUpdateInfo?.update_available}}');
});
it('업데이트 없음 섹션이 if 조건으로 제어된다', () => {
const noUpdateSection = findInTree(modal.children, (n: any) => n.id === 'no_update_section');
expect(noUpdateSection).toBeDefined();
expect(noUpdateSection.if).toBe('{{!$parent._local.coreUpdateInfo?.update_available}}');
});
it('변경사항 보기 버튼에 changelog API 호출 액션이 있다 (closeModal 없이 직접 apiCall)', () => {
const buttons = findAllInTree(modal.children, (n: any) => n.name === 'Button');
const viewChangelogBtn = buttons.find((b: any) => b.text === '$t:admin.settings.info.view_changelog');
expect(viewChangelogBtn).toBeDefined();
// closeModal 없이 직접 apiCall (child 모달을 result 모달 위에 겹쳐서 열기)
const apiCallAction = viewChangelogBtn.actions[0];
expect(apiCallAction.handler).toBe('apiCall');
expect(apiCallAction.target).toBe('/api/admin/core-update/changelog');
expect(apiCallAction.params.method).toBe('GET');
// onSuccess에서 openModal로 changelog 모달 열기
const openModalInSuccess = apiCallAction.onSuccess.find((a: any) => a.handler === 'openModal');
expect(openModalInSuccess).toBeDefined();
expect(openModalInSuccess.target).toBe('core_changelog_modal');
});
it('업데이트 방법 버튼에 openModal 액션이 있다 (closeModal 없이 직접 openModal)', () => {
const buttons = findAllInTree(modal.children, (n: any) => n.name === 'Button');
const howToUpdateBtn = buttons.find((b: any) => b.text === '$t:admin.settings.info.how_to_update');
expect(howToUpdateBtn).toBeDefined();
// closeModal 없이 직접 openModal (child 모달을 result 모달 위에 겹쳐서 열기)
const openModalAction = howToUpdateBtn.actions[0];
expect(openModalAction.handler).toBe('openModal');
expect(openModalAction.target).toBe('core_update_guide_modal');
});
});
describe('업데이트 확인 버튼 (정보 탭)', () => {
let tabInfo: any;
beforeEach(() => {
tabInfo = loadPartial('admin_settings/_tab_info.json');
});
it('업데이트 확인 성공 시 openModal이 target 형식을 사용한다', () => {
// 업데이트 확인 버튼 찾기: sequence → apiCall → onSuccess → openModal
const allButtons = findAllInTree(
Array.isArray(tabInfo) ? tabInfo : [tabInfo],
(n: any) => n.name === 'Button',
);
// apiCall target이 /api/admin/core-update/check인 sequence를 가진 버튼 찾기
const checkUpdateBtn = allButtons.find((btn: any) => {
const action = btn.actions?.[0];
if (action?.handler !== 'sequence') return false;
return action.actions?.some(
(a: any) => a.handler === 'apiCall' && a.target === '/api/admin/core-update/check',
);
});
expect(checkUpdateBtn).toBeDefined();
const sequenceAction = checkUpdateBtn.actions[0];
const apiCallAction = sequenceAction.actions.find((a: any) => a.handler === 'apiCall');
// onSuccess의 openModal이 target 형식을 사용하는지 검증
const openModalInSuccess = apiCallAction.onSuccess.find(
(a: any) => a.handler === 'openModal',
);
expect(openModalInSuccess).toBeDefined();
expect(openModalInSuccess.target).toBe('core_update_result_modal');
// params.id 형식이 아닌 target 형식이어야 함 (params.id는 모달 ID가 undefined로 전달됨)
expect(openModalInSuccess.params?.id).toBeUndefined();
});
});
describe('코어 변경사항 모달', () => {
let modal: any;
beforeEach(() => {
modal = loadPartial('admin_settings/_modal_core_changelog.json');
});
it('모달 ID가 core_changelog_modal이다', () => {
expect(modal.id).toBe('core_changelog_modal');
});
it('모달 사이즈가 lg이다', () => {
expect(modal.props.size).toBe('lg');
});
it('빈 상태 메시지가 if 조건으로 제어된다', () => {
const emptyDiv = findInTree(modal.children, (n: any) =>
n.if === '{{!$parent._local.coreChangelog || $parent._local.coreChangelog.length === 0}}'
);
expect(emptyDiv).toBeDefined();
expect(emptyDiv.text).toBe('$t:admin.settings.info.no_changelog');
});
it('3단 iteration 구조를 갖는다 (entry → category → items)', () => {
// 1단: coreChangelog entries ($parent._local 경로 사용 - 모달 컨텍스트)
const entryIteration = findInTree(modal.children, (n: any) =>
n.iteration?.source === '$parent._local.coreChangelog'
);
expect(entryIteration).toBeDefined();
expect(entryIteration.iteration.item_var).toBe('entry');
// 2단: categories
const categoryIteration = findInTree(entryIteration.children, (n: any) =>
n.iteration?.source === 'entry.categories'
);
expect(categoryIteration).toBeDefined();
expect(categoryIteration.iteration.item_var).toBe('category');
// 3단: items
const itemIteration = findInTree(categoryIteration.children, (n: any) =>
n.iteration?.source === 'category.items'
);
expect(itemIteration).toBeDefined();
expect(itemIteration.iteration.item_var).toBe('changeItem');
expect(itemIteration.text).toBe('{{changeItem}}');
});
it('버전과 날짜 표시 영역이 있다', () => {
const entryIteration = findInTree(modal.children, (n: any) =>
n.iteration?.source === '$parent._local.coreChangelog'
);
const versionSpan = findInTree(entryIteration.children, (n: any) =>
n.text === 'v{{entry.version}}'
);
expect(versionSpan).toBeDefined();
const dateSpan = findInTree(entryIteration.children, (n: any) =>
n.text === '{{entry.date}}'
);
expect(dateSpan).toBeDefined();
expect(dateSpan.if).toBe('{{entry.date}}');
});
});
describe('코어 업데이트 안내 모달', () => {
let modal: any;
beforeEach(() => {
modal = loadPartial('admin_settings/_modal_core_update_guide.json');
});
it('모달 ID가 core_update_guide_modal이다', () => {
expect(modal.id).toBe('core_update_guide_modal');
});
it('모달 사이즈가 md이다', () => {
expect(modal.props.size).toBe('md');
});
it('경고 아이콘(triangle-exclamation)이 포함되어 있다', () => {
const icon = findInTree(modal.children, (n: any) =>
n.name === 'Icon' && n.props?.name === 'triangle-exclamation'
);
expect(icon).toBeDefined();
});
it('터미널 명령어 표시 영역이 있다', () => {
const commandText = findInTree(modal.children, (n: any) =>
n.text === '$ php artisan core:update'
);
expect(commandText).toBeDefined();
expect(commandText.props.className).toContain('font-mono');
});
it('노란색 경고 배경이 있다', () => {
const warningDiv = findInTree(modal.children, (n: any) =>
n.props?.className?.includes('bg-yellow-50')
);
expect(warningDiv).toBeDefined();
});
});
});
// ============================================================
// 2. 렌더링 검증 테스트
// ============================================================
describe('코어 업데이트 레이아웃 렌더링', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
afterEach(() => {
(registry as any).registry = {};
});
describe('Admin Maintenance 페이지 렌더링', () => {
it('제목, 메시지, 설명이 렌더링된다', async () => {
const layout = loadAdminLayout('errors/maintenance.json');
const contentLayout = {
version: '1.0.0',
layout_name: 'maintenance_test',
slots: {
content: layout.slots.content,
},
};
const testUtils = createLayoutTest(contentLayout, {
translations,
});
await testUtils.render();
expect(screen.getByText('시스템 점검 중')).toBeInTheDocument();
expect(screen.getByText('현재 시스템 업데이트가 진행 중입니다.')).toBeInTheDocument();
expect(screen.getByText('잠시 후 다시 접속해 주세요.')).toBeInTheDocument();
testUtils.cleanup();
});
it('spinning gear 아이콘이 렌더링된다', async () => {
const layout = loadAdminLayout('errors/maintenance.json');
const contentLayout = {
version: '1.0.0',
layout_name: 'maintenance_icon_test',
slots: {
content: layout.slots.content,
},
};
const testUtils = createLayoutTest(contentLayout, {
translations,
});
await testUtils.render();
const icon = screen.getByTestId('icon-gear');
expect(icon).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('업데이트 확인 결과 모달 렌더링', () => {
it('업데이트가 있을 때 업데이트 가능 섹션이 표시된다', async () => {
const modal = loadPartial('admin_settings/_modal_core_update_result.json');
const layout = {
version: '1.0.0',
layout_name: 'update_result_test',
initLocal: {
coreUpdateInfo: {
update_available: true,
current_version: '1.0.0',
latest_version: '1.1.0',
},
},
slots: {
content: replaceParentLocalRefs(modal.children),
},
};
const testUtils = createLayoutTest(layout, {
translations,
});
await testUtils.render();
expect(screen.getByText('1.0.0')).toBeInTheDocument();
expect(screen.getByText('1.1.0')).toBeInTheDocument();
expect(screen.getByText('새로운 업데이트가 있습니다.')).toBeInTheDocument();
testUtils.cleanup();
});
it('업데이트가 없을 때 최신 버전 메시지가 표시된다', async () => {
const modal = loadPartial('admin_settings/_modal_core_update_result.json');
const layout = {
version: '1.0.0',
layout_name: 'no_update_test',
initLocal: {
coreUpdateInfo: {
update_available: false,
current_version: '1.1.0',
latest_version: '1.1.0',
},
},
slots: {
content: replaceParentLocalRefs(modal.children),
},
};
const testUtils = createLayoutTest(layout, {
translations,
});
await testUtils.render();
expect(screen.getByText('현재 최신 버전을 사용 중입니다.')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('변경사항 모달 렌더링', () => {
it('changelog 데이터가 없을 때 빈 상태 메시지가 표시된다', async () => {
const modal = loadPartial('admin_settings/_modal_core_changelog.json');
const layout = {
version: '1.0.0',
layout_name: 'changelog_empty_test',
initLocal: {
coreChangelog: [],
},
slots: {
content: replaceParentLocalRefs(modal.children),
},
};
const testUtils = createLayoutTest(layout, {
translations,
});
await testUtils.render();
expect(screen.getByText('변경사항 정보가 없습니다.')).toBeInTheDocument();
testUtils.cleanup();
});
it('changelog 데이터로 버전별 변경사항이 렌더링된다', async () => {
const modal = loadPartial('admin_settings/_modal_core_changelog.json');
const layout = {
version: '1.0.0',
layout_name: 'changelog_render_test',
initLocal: {
coreChangelog: sampleChangelog,
},
slots: {
content: replaceParentLocalRefs(modal.children),
},
};
const testUtils = createLayoutTest(layout, {
translations,
});
await testUtils.render();
expect(screen.getByText('v1.1.0')).toBeInTheDocument();
expect(screen.getByText('2026-03-05')).toBeInTheDocument();
expect(screen.getByText('Added')).toBeInTheDocument();
expect(screen.getByText('코어 업데이트 기능 추가')).toBeInTheDocument();
expect(screen.getByText('유지보수 모드 지원')).toBeInTheDocument();
expect(screen.getByText('Fixed')).toBeInTheDocument();
expect(screen.getByText('설정 저장 버그 수정')).toBeInTheDocument();
testUtils.cleanup();
});
it('여러 버전의 changelog가 모두 렌더링된다', async () => {
const modal = loadPartial('admin_settings/_modal_core_changelog.json');
const layout = {
version: '1.0.0',
layout_name: 'changelog_multi_test',
initLocal: {
coreChangelog: multiVersionChangelog,
},
slots: {
content: replaceParentLocalRefs(modal.children),
},
};
const testUtils = createLayoutTest(layout, {
translations,
});
await testUtils.render();
expect(screen.getByText('v1.2.0')).toBeInTheDocument();
expect(screen.getByText('v1.1.0')).toBeInTheDocument();
expect(screen.getByText('신규 기능 X 추가')).toBeInTheDocument();
expect(screen.getByText('기존 기능 Y 변경')).toBeInTheDocument();
expect(screen.getByText('버그 Z 수정')).toBeInTheDocument();
expect(screen.getByText('버그 W 수정')).toBeInTheDocument();
testUtils.cleanup();
});
});
describe('업데이트 안내 모달 렌더링', () => {
it('경고 메시지와 터미널 명령어가 렌더링된다', async () => {
const modal = loadPartial('admin_settings/_modal_core_update_guide.json');
const layout = {
version: '1.0.0',
layout_name: 'update_guide_test',
slots: {
content: modal.children,
},
};
const testUtils = createLayoutTest(layout, {
translations,
});
await testUtils.render();
expect(screen.getByText('서버 터미널에서 실행하세요.')).toBeInTheDocument();
expect(screen.getByText('$ php artisan core:update')).toBeInTheDocument();
expect(screen.getByTestId('icon-triangle-exclamation')).toBeInTheDocument();
testUtils.cleanup();
});
});
});
@@ -0,0 +1,227 @@
/**
* @file formfield-error-border.test.tsx
* @description FormField 컴포넌트 에러 시 적색 테두리 자동 적용 테스트
*
* 테스트 대상:
* - FormField에 error prop이 있을 때 form-field-error 클래스가 적용되는지
* - FormField에 error prop이 없을 때 form-field-error 클래스가 없는지
* - 유효성 검증 실패 시 에러 메시지가 표시되는지
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
import { FormField } from '../../src/components/composite/FormField';
// 테스트용 기본 컴포넌트
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestLabel: React.FC<{
className?: string;
children?: React.ReactNode;
}> = ({ className, children }) => (
<label className={className}>{children}</label>
);
const TestInput: React.FC<{
type?: string;
name?: string;
className?: string;
value?: string;
'data-testid'?: string;
}> = ({ type, name, className, value, 'data-testid': testId }) => (
<input type={type} name={name} className={className} value={value ?? ''} readOnly data-testid={testId || `input-${name}`} />
);
const TestFragment: React.FC<{
children?: React.ReactNode;
}> = ({ children }) => <>{children}</>;
// 컴포넌트 레지스트리 설정
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
FormField: { component: FormField, metadata: { name: 'FormField', type: 'composite' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
return registry;
}
// 에러가 있는 폼 레이아웃
const layoutWithErrors = {
version: '1.0.0',
layout_name: 'test_formfield_error',
state: {
form: { name: '' },
errors: { name: ['쿠폰명은 필수입니다.'] },
},
components: [
{
id: 'field_with_error',
type: 'composite',
name: 'FormField',
props: {
label: '쿠폰명',
required: true,
error: "{{_local.errors?.name?.[0] ?? ''}}",
'data-testid': 'formfield-with-error',
},
children: [
{
type: 'basic',
name: 'Input',
props: {
name: 'name',
className: 'input w-full',
'data-testid': 'input-name',
},
},
],
},
{
id: 'field_without_error',
type: 'composite',
name: 'FormField',
props: {
label: '설명',
error: "{{_local.errors?.description?.[0] ?? ''}}",
'data-testid': 'formfield-without-error',
},
children: [
{
type: 'basic',
name: 'Input',
props: {
name: 'description',
className: 'input w-full',
'data-testid': 'input-description',
},
},
],
},
],
};
// 에러가 없는 폼 레이아웃
const layoutWithoutErrors = {
version: '1.0.0',
layout_name: 'test_formfield_no_error',
state: {
form: { name: '테스트 쿠폰' },
errors: null,
},
components: [
{
id: 'field_normal',
type: 'composite',
name: 'FormField',
props: {
label: '쿠폰명',
required: true,
error: "{{_local.errors?.name?.[0] ?? ''}}",
'data-testid': 'formfield-normal',
},
children: [
{
type: 'basic',
name: 'Input',
props: {
name: 'name',
className: 'input w-full',
'data-testid': 'input-name-normal',
},
},
],
},
],
};
describe('FormField 에러 시 적색 테두리 자동 적용', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
afterEach(() => {
testUtils?.cleanup();
});
describe('에러가 있는 필드', () => {
beforeEach(() => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(layoutWithErrors, { componentRegistry: registry });
});
it('에러가 있는 FormField에 form-field-error 클래스가 적용된다', async () => {
await testUtils.render();
// form-field-error 클래스가 존재하는지 확인
const container = document.querySelector('.form-field-error');
expect(container).not.toBeNull();
});
it('에러 메시지 텍스트가 표시된다', async () => {
await testUtils.render();
const errorText = screen.getByText('쿠폰명은 필수입니다.');
expect(errorText).toBeInTheDocument();
});
it('에러가 없는 FormField에는 form-field-error 클래스가 없다', async () => {
await testUtils.render();
// input-description의 부모 FormField에는 form-field-error가 없어야 함
const descriptionInput = screen.getByTestId('input-description');
const parentDiv = descriptionInput.closest('.form-field-error');
expect(parentDiv).toBeNull();
});
});
describe('에러가 없는 필드', () => {
beforeEach(() => {
const registry = setupTestRegistry();
testUtils = createLayoutTest(layoutWithoutErrors, { componentRegistry: registry });
});
it('에러가 null일 때 form-field-error 클래스가 적용되지 않는다', async () => {
await testUtils.render();
const errorContainer = document.querySelector('.form-field-error');
expect(errorContainer).toBeNull();
});
it('에러 메시지가 표시되지 않는다', async () => {
await testUtils.render();
const errorText = screen.queryByText('쿠폰명은 필수입니다.');
expect(errorText).toBeNull();
});
});
describe('에러 유무에 따른 클래스 차이', () => {
it('에러가 있는 레이아웃과 없는 레이아웃의 form-field-error 클래스 적용이 다르다', async () => {
// 에러 있는 레이아웃
const registry1 = setupTestRegistry();
const utils1 = createLayoutTest(layoutWithErrors, { componentRegistry: registry1 });
await utils1.render();
expect(document.querySelector('.form-field-error')).not.toBeNull();
utils1.cleanup();
// 에러 없는 레이아웃
const registry2 = setupTestRegistry();
const utils2 = createLayoutTest(layoutWithoutErrors, { componentRegistry: registry2 });
testUtils = utils2;
await utils2.render();
expect(document.querySelector('.form-field-error')).toBeNull();
});
});
});
@@ -0,0 +1,107 @@
/**
* 코어 템플릿 관리 필터 named_actions 검증 테스트
*
* @description
* - 사용자관리: named_actions.searchUsers 정의 및 4개 actionRef 검증
* - 스케줄관리: named_actions.searchSchedules 정의 및 2개 actionRef 검증
*
* @vitest-environment jsdom
*/
import { describe, it, expect } from 'vitest';
// 사용자관리 (단일 파일)
import userList from '../../layouts/admin_user_list.json';
// 스케줄관리 (메인 + 파샬)
import scheduleList from '../../layouts/admin_schedule_list.json';
import scheduleTab from '../../layouts/partials/admin_schedule_list/_tab_schedules.json';
/** JSON 전체에서 actionRef를 가진 액션을 찾는 유틸리티 */
function findActionRefs(obj: any, refName: string, results: any[] = []): any[] {
if (!obj) return results;
if (typeof obj === 'object') {
if (obj.actionRef === refName) {
results.push(obj);
}
for (const key of Object.keys(obj)) {
findActionRefs(obj[key], refName, results);
}
}
return results;
}
// ============================================
// 사용자관리
// ============================================
describe('사용자관리 named_actions 검증', () => {
it('레이아웃에 named_actions.searchUsers가 정의되어 있어야 함', () => {
const namedActions = (userList as any).named_actions;
expect(namedActions).toBeDefined();
expect(namedActions.searchUsers).toBeDefined();
});
it('searchUsers가 올바른 navigate 핸들러를 가져야 함', () => {
const action = (userList as any).named_actions.searchUsers;
expect(action.handler).toBe('navigate');
expect(action.params.path).toBe('/admin/users');
expect(action.params.mergeQuery).toBe(true);
expect(action.params.query['filters[0][operator]']).toBe('like');
});
it('Desktop + Mobile Enter keypress가 actionRef로 searchUsers를 참조해야 함', () => {
const refs = findActionRefs(userList, 'searchUsers');
const enterRefs = refs.filter((r: any) => r.type === 'keypress' && r.key === 'Enter');
expect(enterRefs.length).toBe(2); // desktop + mobile
});
it('Desktop + Mobile 검색 버튼 click이 actionRef로 searchUsers를 참조해야 함', () => {
const refs = findActionRefs(userList, 'searchUsers');
const clickRefs = refs.filter((r: any) => r.type === 'click');
expect(clickRefs.length).toBe(2); // desktop + mobile
});
it('총 4개의 actionRef가 searchUsers를 참조해야 함', () => {
const refs = findActionRefs(userList, 'searchUsers');
expect(refs.length).toBe(4);
});
});
// ============================================
// 스케줄관리
// ============================================
describe('스케줄관리 named_actions 검증', () => {
it('메인 레이아웃에 named_actions.searchSchedules가 정의되어 있어야 함', () => {
const namedActions = (scheduleList as any).named_actions;
expect(namedActions).toBeDefined();
expect(namedActions.searchSchedules).toBeDefined();
});
it('searchSchedules가 올바른 navigate 핸들러를 가져야 함', () => {
const action = (scheduleList as any).named_actions.searchSchedules;
expect(action.handler).toBe('navigate');
expect(action.params.path).toBe('/admin/schedules');
expect(action.params.mergeQuery).toBe(true);
expect(action.params.query.page).toBe(1);
expect(action.params.query.search).toBeDefined();
});
it('파샬 탭에서 Enter keypress가 actionRef로 searchSchedules를 참조해야 함', () => {
const refs = findActionRefs(scheduleTab, 'searchSchedules');
const enterRef = refs.find((r: any) => r.type === 'keypress' && r.key === 'Enter');
expect(enterRef).toBeDefined();
});
it('파샬 탭에서 검색 버튼 click이 actionRef로 searchSchedules를 참조해야 함', () => {
const refs = findActionRefs(scheduleTab, 'searchSchedules');
const clickRef = refs.find((r: any) => r.type === 'click');
expect(clickRef).toBeDefined();
});
it('총 2개의 actionRef가 searchSchedules를 참조해야 함', () => {
const refs = findActionRefs(scheduleTab, 'searchSchedules');
expect(refs.length).toBe(2);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
/*! tailwindcss v4.1.17 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-scroll-snap-strictness:proximity;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-red-900:oklch(39.6% .141 25.723);--color-red-950:oklch(25.8% .092 26.042);--color-orange-50:oklch(98% .016 73.684);--color-orange-100:oklch(95.4% .038 75.164);--color-orange-200:oklch(90.1% .076 70.697);--color-orange-300:oklch(83.7% .128 66.29);--color-orange-400:oklch(75% .183 55.934);--color-orange-500:oklch(70.5% .213 47.604);--color-orange-600:oklch(64.6% .222 41.116);--color-orange-700:oklch(55.3% .195 38.402);--color-orange-800:oklch(47% .157 37.304);--color-orange-900:oklch(40.8% .123 38.172);--color-orange-950:oklch(26.6% .079 36.259);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-900:oklch(41.4% .112 45.904);--color-amber-950:oklch(27.9% .077 45.635);--color-yellow-50:oklch(98.7% .026 102.212);--color-yellow-100:oklch(97.3% .071 103.193);--color-yellow-200:oklch(94.5% .129 101.54);--color-yellow-300:oklch(90.5% .182 98.111);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-500:oklch(79.5% .184 86.047);--color-yellow-600:oklch(68.1% .162 75.834);--color-yellow-700:oklch(55.4% .135 66.442);--color-yellow-800:oklch(47.6% .114 61.907);--color-yellow-900:oklch(42.1% .095 57.708);--color-yellow-950:oklch(28.6% .066 53.813);--color-lime-50:oklch(98.6% .031 120.757);--color-lime-100:oklch(96.7% .067 122.328);--color-lime-200:oklch(93.8% .127 124.321);--color-lime-300:oklch(89.7% .196 126.665);--color-lime-400:oklch(84.1% .238 128.85);--color-lime-500:oklch(76.8% .233 130.85);--color-lime-600:oklch(64.8% .2 131.684);--color-lime-700:oklch(53.2% .157 131.589);--color-lime-800:oklch(45.3% .124 130.933);--color-lime-900:oklch(40.5% .101 131.063);--color-lime-950:oklch(27.4% .072 132.109);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-300:oklch(87.1% .15 154.449);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--Line truncated
@@ -0,0 +1,2 @@
export * from './src/index'
export {}
@@ -0,0 +1,309 @@
var SirsoftAdminBasic=(function(Q,c,m,fr){"use strict";function Jf(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const _=Jf(m),Rf=()=>window.G7Core,oe=m.forwardRef(({children:e,variant:t="primary",size:n="md",className:a="",...r},o)=>{const s="inline-flex items-center justify-center",i=Rf()?.style?.mergeClasses?.(s,a)??`${s} ${a}`;return c.jsx("button",{ref:o,className:i,...r,children:e})});oe.displayName="Button";const Vi=m.forwardRef(({accept:e,maxSize:t,onChange:n,onError:a,buttonText:r="Browse",placeholder:o="No file selected",className:s="",disabled:i,...l},f)=>{const u=m.useRef(null),d=f||u,[g,h]=m.useState(""),b=m.useCallback(()=>{!i&&d.current&&d.current.click()},[i,d]),p=m.useCallback(v=>{const O=v.target.files?.[0]||null;if(!O){h(""),n?.(null);return}if(t&&O.size>t*1024*1024){const k=`File size exceeds ${t}MB limit`;a?.(k),d.current&&(d.current.value=""),h("");return}h(O.name),n?.(O)},[t,n,a,d]),x=m.useCallback(v=>{v.stopPropagation(),d.current&&(d.current.value=""),h(""),n?.(null)},[n,d]);return c.jsxs("div",{className:`flex items-center gap-2 ${s}`,children:[c.jsx("input",{ref:d,type:"file",accept:e,onChange:p,disabled:i,className:"hidden",...l}),c.jsx("button",{type:"button",onClick:b,disabled:i,className:"px-4 py-2 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed",children:r}),c.jsx("span",{className:"flex-1 text-sm text-gray-600 dark:text-gray-400 truncate",children:g||o}),g&&!i&&c.jsx("button",{type:"button",onClick:x,className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":"Clear file",children:c.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})});Vi.displayName="FileInput";const gt=m.forwardRef(({label:e,error:t,className:n="",onChange:a,onKeyPress:r,value:o,defaultValue:s,type:i="text",checked:l,defaultChecked:f,...u},d)=>{const g=i==="radio"||i==="checkbox",h=m.useRef(!1),b=m.useRef(null);m.useImperativeHandle(d,()=>b.current);const[p,x]=m.useState(o??s??"");m.useEffect(()=>{if(!g&&!h.current&&o!==void 0){if(b.current&&document.activeElement===b.current)return;x(o)}},[o,g]);const v=m.useCallback(()=>{h.current=!0},[]),O=m.useCallback(w=>{if(h.current=!1,a){const I=w.target.value;x(I);const L=new Event("change",{bubbles:!0});Object.defineProperty(L,"target",{writable:!1,value:{value:I}}),Object.defineProperty(L,"currentTarget",{writable:!1,value:{value:I}}),a(L)}},[a]),k=m.useCallback(w=>{const I=w.target.value;x(I),!h.current&&a&&a(w)},[a]),C=m.useCallback(w=>{h.current||r&&r(w)},[r]),{loadingactions:N,formdata:E,...S}=u;if(g)return c.jsx("input",{ref:b,type:i,className:n,onChange:a,checked:l,defaultChecked:f,value:o,...S});const y=o!==void 0?{value:p}:{defaultValue:s};return c.jsx("input",{ref:b,type:i,className:n,onChange:k,onKeyPress:C,onCompositionStart:v,onCompositionEnd:O,...y,...S})});gt.displayName="Input";const vr=({label:e,error:t,className:n="",onChange:a,value:r,defaultValue:o,...s})=>{const i=m.useRef(!1),l=m.useRef(null),[f,u]=m.useState(r??o??"");m.useEffect(()=>{!i.current&&r!==void 0&&u(r)},[r]);const d=m.useCallback(()=>{i.current=!0},[]),g=m.useCallback(O=>{if(i.current=!1,a){const k=O.target.value;u(k);const C=new Event("change",{bubbles:!0});Object.defineProperty(C,"target",{writable:!1,value:{value:k}}),Object.defineProperty(C,"currentTarget",{writable:!1,value:{value:k}}),a(C)}},[a]),h=m.useCallback(O=>{const k=O.target.value;u(k),!i.current&&a&&a(O)},[a]),{loadingactions:b,formdata:p,...x}=s,v=r!==void 0?{value:f}:{defaultValue:o};return c.jsx("textarea",{ref:l,className:n,onChange:h,onCompositionStart:d,onCompositionEnd:g,...v,...x})},$t=({children:e,className:t="",...n})=>c.jsx("label",{className:t,...n,children:e}),D=m.forwardRef(({children:e,className:t="",...n},a)=>c.jsx("div",{ref:a,className:t,...n,children:e})),Z=({children:e,className:t="",...n})=>c.jsx("span",{className:t,...n,children:e}),ut=({children:e,className:t="",...n})=>c.jsx("p",{className:t,...n,children:e}),ar=({className:e="",alt:t="",...n})=>c.jsx("img",{className:e,alt:t,...n}),Ao=({children:e,className:t="",...n})=>c.jsx("h1",{className:t,...n,children:e}),Er=({children:e,className:t="",...n})=>c.jsx("h2",{className:t,...n,children:e}),Vr=({children:e,className:t="",...n})=>c.jsx("h3",{className:t,...n,children:e}),Hi=({children:e,className:t="",...n})=>c.jsx("h4",{className:t,...n,children:e}),Io=({children:e,className:t="",...n})=>c.jsx("ul",{className:t,.Line truncated
inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium
${ee?"bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300":"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"}
`,children:[c.jsx(ne,{name:"globe",className:"w-3 h-3"}),A($),ee&&c.jsx(Z,{className:"text-red-500 dark:text-red-400",children:"*"}),!ee&&c.jsx(oe,{type:"button",className:"ml-0.5 p-0.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",onClick:()=>M($),disabled:l,children:c.jsx(ne,{name:"xmark",className:"w-3 h-3"})})]}),ee&&q&&U()]}),n==="textarea"?c.jsx(vr,{name:`${g}[${$}]`,value:k[$]||"",onChange:re=>P($,re.target.value),placeholder:X,required:i&&ee,disabled:l,maxLength:f,rows:u,className:`${R} resize-vertical`}):c.jsx(gt,{type:"text",name:`${g}[${$}]`,value:k[$]||"",onChange:re=>P($,re.target.value),placeholder:X,required:i&&ee,disabled:l,maxLength:f,className:R})]},$)},[g,k,P,s,i,l,f,u,n,A,v,M,U,p]),G=m.useCallback($=>{const J=`w-full px-3 py-2 border ${p?"border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500":"border-gray-200 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500"} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2`,R=`${s}${s?" (":""}${A($)}${s?")":""}`;return c.jsx(D,{children:n==="textarea"?c.jsx(vr,{name:`${g}[${$}]`,value:k[$]||"",onChange:ee=>P($,ee.target.value),placeholder:R,required:i&&$===v,disabled:l,maxLength:f,rows:u,className:`${J} resize-vertical`}):c.jsx(gt,{type:"text",name:`${g}[${$}]`,value:k[$]||"",onChange:ee=>P($,ee.target.value),placeholder:R,required:i&&$===v,disabled:l,maxLength:f,className:J})},$)},[g,k,P,s,i,l,f,u,n,v,A]),H=()=>c.jsx(D,{className:d,children:c.jsx(D,{className:"space-y-4",children:S.map(($,q)=>Y($,q===0))})}),B=()=>c.jsxs(D,{className:d,children:[c.jsxs(D,{className:"flex items-center gap-2 mb-3",children:[S.map($=>c.jsxs(oe,{type:"button",className:`
inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all
${w===$?$===v?"bg-blue-500 text-white dark:bg-blue-600 dark:text-white shadow-md scale-105":"bg-gray-500 text-white dark:bg-gray-600 dark:text-white shadow-md scale-105":$===v?"bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/50":"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600"}
`,onClick:()=>I($),children:[c.jsx(ne,{name:"globe",className:"w-3 h-3"}),h?c.jsxs(c.Fragment,{children:[c.jsx(Z,{className:"hidden md:inline",children:A($)}),c.jsx(Z,{className:"inline md:hidden",children:$.toUpperCase()})]}):A($),$===v&&c.jsx(Z,{className:"text-red-500 dark:text-red-400",children:"*"}),j($)&&w!==$&&c.jsx(ne,{name:"check",className:"w-3 h-3 text-green-500 dark:text-green-400"}),$!==v&&c.jsx(oe,{type:"button",className:"ml-0.5 p-0.5 rounded-full hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors",onClick:q=>{q.stopPropagation(),M($)},disabled:l,children:c.jsx(ne,{name:"xmark",className:"w-3 h-3"})})]},$)),U()]}),S.map($=>c.jsx(D,{className:w===$?"block":"hidden",children:G($)},$))]}),z=()=>{const $=p?"border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500":"border-gray-200 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500";return c.jsx(D,{className:d,children:c.jsxs(D,{className:"flex items-center gap-1",children:[c.jsx(D,{className:"flex items-center shrink-0",children:S.map(q=>c.jsxs(oe,{type:"button",className:`
px-2 py-1.5 text-xs font-medium border-y border-l first:rounded-l last:rounded-r last:border-r transition-colors
${w===q?"bg-blue-500 text-white border-blue-500 dark:bg-blue-600 dark:border-blue-600":"bg-white text-gray-600 border-gray-200 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700"}
`,onClick:()=>I(q),title:A(q),children:[q.toUpperCase(),q===v&&c.jsx(Z,{className:"text-red-400 ml-0.5",children:"*"})]},q))}),c.jsx(D,{className:"flex-1 min-w-0",children:n==="textarea"?c.jsx(vr,{name:`${g}[${w}]`,value:k[w]||"",onChange:q=>P(w,q.target.value),placeholder:s,required:i&&w===v,disabled:l,maxLength:f,rows:u,className:`w-full px-2 py-1.5 border ${$} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-sm`}):c.jsx(gt,{type:"text",name:`${g}[${w}]`,value:k[w]||"",onChange:q=>P(w,q.target.value),placeholder:s,required:i&&w===v,disabled:l,maxLength:f,className:`w-full px-2 py-1.5 border ${$} rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-sm`})})]})})};return c.jsxs(D,{className:l?"opacity-50 cursor-not-allowed":void 0,children:[a==="compact"?z():a==="tabs"?B():H(),p&&b&&c.jsx(Z,{className:"text-xs text-red-500 dark:text-red-400 mt-1 block",children:b})]})};Uo.displayName="MultilingualInput";const gg=()=>window.G7Core,Vo=({checked:e,value:t,onChange:n,disabled:a=!1,label:r,description:o,size:s="md",className:i="",name:l})=>{const[f,u]=m.useState(()=>e??t??!1);m.useEffect(()=>{u(e??t??!1)},[e,t]);const d=p=>{const x=p.target.checked;u(x),n&&!a&&n(p)},h={sm:{track:"w-9 h-5",thumb:"after:h-4 after:w-4"},md:{track:"w-11 h-6",thumb:"after:h-5 after:w-5"},lg:{track:"w-14 h-7",thumb:"after:h-6 after:w-6"}}[s],b=()=>{if(!a){const p=!f;if(u(p),n){const x=gg();x?.createChangeEvent&&n(x.createChangeEvent({checked:p,name:l}))}}};return c.jsxs("div",{className:`inline-flex flex-wrap items-start gap-x-2 w-auto ${i}`,children:[c.jsxs("div",{className:`relative inline-flex items-center flex-shrink-0 ${a?"cursor-not-allowed opacity-50":"cursor-pointer"}`,onClick:p=>{p.preventDefault(),p.stopPropagation(),b()},children:[c.jsx("input",{type:"checkbox",id:l,name:l,checked:f,onChange:d,disabled:a,className:"sr-only peer",tabIndex:-1}),c.jsx("div",{className:`
relative ${h.track}
bg-gray-200 dark:bg-gray-700
rounded-full
peer
peer-focus:outline-none
peer-focus:ring-4
peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800
peer-checked:bg-blue-600 dark:peer-checked:bg-blue-500
after:content-['']
after:absolute
after:top-0.5
after:left-0.5
after:bg-white
after:border-gray-300 dark:after:border-gray-600
after:border
after:rounded-full
${h.thumb}
after:transition-all
peer-checked:after:translate-x-full
peer-checked:after:border-white
transition-colors
`})]}),r&&c.jsx("span",{className:`text-sm font-medium text-gray-900 dark:text-white ${a?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,onClick:b,children:r}),o&&c.jsx("p",{className:"w-full mt-1 text-xs text-gray-500 dark:text-gray-400",children:o})]})},fa=({status:e,label:t,showIcon:n=!0,iconName:a,className:r="",style:o})=>{const s={success:"bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800",warning:"bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800",error:"bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800",info:"bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800",pending:"bg-gray-50 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-200 dark:border-gray-600",default:"bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-200 dark:border-gray-600"},i={success:de.CheckCircle,warning:de.ExclamationTriangle,error:de.XCircle,info:de.InfoCircle,pending:de.Clock,default:de.QuestionCircle},l={success:"성공",warning:"경고",error:"오류",info:"정보",pending:"대기 중",default:"기본"},f=a||i[e],u=t||l[e],d=s[e];return c.jsxs(Z,{className:`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border ${d} ${r}`,style:o,children:[n&&c.jsx(ne,{name:f,className:"w-4 h-4"}),c.jsx(Z,{children:u})]})},Bi={blue:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",green:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300",red:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300",gray:"bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300",yellow:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300",purple:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300",orange:"bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300",teal:"bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-300",cyan:"bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-300"},Wi={sm:"px-1.5 py-0.5 text-[10px]",md:"px-2 py-0.5 text-xs",lg:"px-2.5 py-1 text-sm"},Yi=({color:e="gray",text:t,size:n="md",className:a="",style:r,children:o})=>{const s=Bi[e]||Bi.gray,i=Wi[n]||Wi.md;return c.jsxs(Z,{className:`inline-flex items-center rounded-full font-medium ${i} ${s} ${a}`,style:r,children:[t,o]})};/*! @license DOMPurify 3.1.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.7/LICENSE */const{entries:qi,setPrototypeOf:Ki,isFrozen:hg,getPrototypeOf:pg,getOwnPropertyDescriptor:bg}=Object;let{freeze:Nt,seal:zt,create:Xi}=Object,{apply:Ho,construct:jo}=typeof Reflect<"u"&&Reflect;Nt||(Nt=function(t){return t}),zt||(zt=function(t){return t}),Ho||(Ho=function(t,n,a){return t.apply(n,a)}),jo||(jo=function(t,n){return new t(...n)});const ga=Ft(Array.prototype.forEach),Zi=Ft(Array.prototype.pop),mn=Ft(Array.prototype.push),ha=Ft(String.prototype.toLowerCase),zo=Ft(String.prototype.toString),Qi=Ft(String.prototype.match),vn=Ft(String.prototype.replace),mg=Ft(String.prototype.indexOf),vg=Ft(String.prototype.trim),Zt=Ft(Object.prototype.hasOwnProperty),Ot=Ft(RegExp.prototype.test),yn=yg(TypeError);function Ft(e){return function(t){for(var n=arguments.length,a=new Array(n>1?n-1:0),r=1;r<n;r++)a[r-1]=arguments[r];return Ho(e,t,a)}}function yg(e){return function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];return jo(e,n)}}function Ue(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ha;Ki&&Ki(e,null);let a=t.length;for(;a--;){let r=t[a];if(typeof r=="string"){const o=n(r);o!==r&&(hg(t)||(t[a]=o),r=o)}e[r]=!0}return e}function xg(e){for(let t=0;t<e.length;t++)Zt(e,t)||(e[t]=null);return e}function Nr(e){const t=Xi(null);for(const[n,a]of qi(e))Zt(e,n)&&(Array.isArray(a)?t[n]=xg(a):a&&typeof a=="object"&&a.constructor===Object?t[n]=Nr(a):t[n]=a);return t}function xn(e,t){for(;e!==null;){const a=bg(e,t);if(a){if(a.get)return Ft(a.get);if(typeof a.value=="function")return Ft(a.value)}e=pg(e)}function n(){return null}return n}const Ji=Nt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","stri Line truncated
`+ke),le&&ga([F,T,P],Kt=>{ke=vn(ke,Kt," ")}),C&&We?C.createHTML(ke):ke},t.setConfig=function(){let we=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};it(we),ce=!0},t.clearConfig=function(){_e=null,ce=!1},t.isValidAttribute=function(we,K,se){_e||it({});const W=me(we),ie=me(K);return Ur(W,ie,se)},t.addHook=function(we,K){typeof K=="function"&&(L[we]=L[we]||[],mn(L[we],K))},t.removeHook=function(we){if(L[we])return Zi(L[we])},t.removeHooks=function(we){L[we]&&(L[we]=[])},t.removeAllHooks=function(){L={}},t}var Dg=ol();const qo=({content:e,text:t,isHtml:n=!0,className:a="",purifyConfig:r})=>{const o=t??e??"";if(!o||o.trim()==="")return null;if(!n){const f=`
whitespace-pre-wrap
text-gray-900 dark:text-gray-100
font-sans
${a}
`.trim().replace(/\s+/g," ");return c.jsx(D,{className:f,children:o})}const s={ALLOWED_TAGS:["p","br","strong","em","u","s","strike","del","ins","h1","h2","h3","h4","h5","h6","ul","ol","li","a","img","blockquote","code","pre","table","thead","tbody","tr","th","td","div","span"],ALLOWED_ATTR:["href","target","rel","title","alt","src","width","height","class","style","id","data-*"],ALLOW_DATA_ATTR:!0,ADD_ATTR:["target"],SAFE_FOR_TEMPLATES:!0},i=m.useMemo(()=>{const f=r||s;return Dg.sanitize(o,f).replace(/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi,(d,g,h,b)=>(h.startsWith("http://")||h.startsWith("https://"))&&!d.includes("rel=")?`<a ${g}href="${h}"${b} rel="noopener noreferrer">`:d)},[o,r,s]),l=`
prose dark:prose-invert max-w-none
prose-p:my-2
prose-headings:font-bold prose-headings:mt-6 prose-headings:mb-4
prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg
prose-a:text-blue-600 dark:prose-a:text-blue-400
prose-a:no-underline hover:prose-a:underline
prose-img:rounded-lg prose-img:shadow-md
prose-blockquote:border-l-4 prose-blockquote:border-gray-300 dark:prose-blockquote:border-gray-600
prose-blockquote:pl-4 prose-blockquote:italic
prose-code:bg-gray-100 dark:prose-code:bg-gray-800
prose-code:px-1 prose-code:py-0.5 prose-code:rounded
prose-pre:bg-gray-100 dark:prose-pre:bg-gray-800
prose-pre:p-4 prose-pre:rounded-lg prose-pre:overflow-x-auto
prose-table:border prose-table:border-gray-300 dark:prose-table:border-gray-600
prose-th:bg-gray-100 dark:prose-th:bg-gray-800
prose-th:border prose-th:border-gray-300 dark:prose-th:border-gray-600
prose-th:px-4 prose-th:py-2
prose-td:border prose-td:border-gray-300 dark:prose-td:border-gray-600
prose-td:px-4 prose-td:py-2
${a}
`.trim().replace(/\s+/g," ");return c.jsx(D,{className:l,dangerouslySetInnerHTML:{__html:i}})},ba=window.G7Core?.createLogger?.("Comp:DataGrid")??{log:(...e)=>console.log("[Comp:DataGrid]",...e),warn:(...e)=>console.warn("[Comp:DataGrid]",...e),error:(...e)=>console.error("[Comp:DataGrid]",...e)},kn=(e,t)=>window.G7Core?.t?.(e,t)??e,Ko={Div:D,Span:Z,Button:oe,Icon:ne,Checkbox:Xt,P:ut,A:Hr,Label:$t,Input:gt,H1:Ao,H2:Er,H3:Vr,H4:Hi,Img:ar,Select:pn,Textarea:vr,Table:_o,Thead:Po,Tbody:$o,Tfoot:Fo,Tr:yr,Th:jr,Td:Lt,MultilingualInput:Uo,Toggle:Vo,StatusBadge:fa,Badge:Yi,HtmlContent:qo,ActionMenu:bn},Xo=e=>{if(e==null)return"";if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>Xo(t)).join(", ");if(typeof e=="object"){if(m.isValidElement(e))return e;if(Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return ba.warn("객체를 문자열로 변환할 수 없습니다:",e),"[Object]"}}return String(e)},sl=(e,t)=>{if(!e)return!0;const n=e.match(/^\{\{(.+)\}\}$/);if(!n)return!0;const a=n[1].trim();try{return!!new Function("row",`return ${a}`)(t)}catch(r){return ba.warn("subRow 조건 평가 실패:",e,r),!0}},Cn=(e,t,n,a="",r)=>{const o=window.G7Core;if(o?.renderItemChildren){const s={row:t,value:n,$value:n};return o.renderItemChildren(e,s,Ko,a,r?{componentContext:r}:void 0)}return ba.warn("G7Core.renderItemChildren을 사용할 수 없습니다."),null},Zo=(e,t,n="",a)=>{const r=window.G7Core;if(r?.renderItemChildren){const o={row:t,$value:t};return r.renderItemChildren(e,o,Ko,n,a?{componentContext:a}:void 0)}return ba.warn("G7Core.renderItemChildren을 사용할 수 없습니다."),null},_g=({columns:e,data:t,sortable:n=!0,pagination:a=!1,pageSize:r=10,onRowClick:o,className:s="",style:i,sortField:l,sortDirection:f,onSortChange:u,selectable:d=!1,selectedIds:g=[],onSelectionChange:h,idField:b="id",showColumnSelector:p=!1,visibleColumns:x,onColumnVisibilityChange:v,responsiveBreakpoint:O=768,cardRenderer:k,rowActions:C,onRowAction:N,alwaysShowPagination:E=!1,serverSidePagination:S=!1,serverCurrentPage:y,serverTotalPages:w,onPageChange:I,prevText:L,nextText:F,columnSelectorText:T,emptyMessage:P,actionsColumnHeader:V,requiredText:M,selectedCountText:A,showFirstLast:j=!0,expandable:U=!1,expandedRowIds:Y,onExpandChange:G,expandChildren:H,expandedRowRender:B,expandColumnWidth:z="48px",expandIconExpanded:$=de.ChevronDown,expandIconCollapsed:q=de.ChevronRight,expandConditionField:J,dynamicColumns:R,dynamicColumnsInsertAfter:ee,expandContext:X,__componentContext:re,subRowChildren:le,subRowCondition:ve,subRowClassName:he="px-6 py-2 bg-gray-50 dark:bg-gray-750",subRowRender:ce,footerCells:ye,footerClassName:pe="bg-gray-50 dark:bg-gray-800/50 font-medium",footerCardChildren:Le})=>{const We=L||void 0,He=F||void 0,te=T??kn("common.column_selector"),Ae=P??kn("common.no_data"),De=V??kn("common.actions"),Oe=M??kn("common.required"),Fe=A??kn("common.selected_count"),Ze=window.G7Core,Qe=Ze?.useControllableState,ze=Ze?.shallowArrayEqual,[ae,ue]=Qe?Qe(l,null,W=>{W!==null&&u?.(W,fe)}):[l??null,()=>{}],[fe,ge]=Qe?Qe(f,"asc",W=>{ae!==null&&u?.(ae,W)}):[f??"asc",()=>{}],[Ce,Ie]=m.useState(1),[be,Pe]=Qe?Qe(Y,[],G,{isEqual:ze}):[Y??[],()=>{}],[Te,Re]=m.useState(!1),Ge=m.useRef(null),rt=Ze?.useResponsive,qe=rt?.(),me=qe?qe.width<O:typeof window<"u"&&window.innerWidth<O,_e=m.useMemo(()=>{if(!R||!Array.isArray(R)||R.length===0)return e;if(ee){const W=e.findIndex(ie=>ie.field===ee);if(W!==-1)return[...e.slice(0,W+1),...R,...e.slice(W+1)]}return[...e,...R]},[e,R,ee]),[Be,st]=m.useState(()=>x&&x.length>0?x:e.filter(W=>!W.hidden).map(W=>W.field));m.useEffect(()=>{x&&x.length>0&&st(x)},[x]);const it=m.useRef("");m.useEffect(()=>{const W=e.map(ie=>ie.field).join(",");it.current&&W!==it.current&&(!x||x.length===0)&&st(e.filter(ie=>!ie.hidden).map(ie=>ie.field)),it.current=W},[e,x]);const et=m.useRef([]),at=m.useRef(null);m.useEffect(()=>{if(R&&R.length>0){const W=R.map($e=>$e.field);if(at.current===null&&(at.current=x!==void 0&&x.length>0,at.current)){et.current=W;return}const ie=et.current,xe=W.filter($e=>!ie.includes($e));if(xe.length>0){const $e=xe.filter(ke=>!Be.includes(ke));if($e.length>0){const ke=[...Be,...$e];st(ke),v?.(ke)}}et.current=W}},[R]),m.useEffect(()=>{S||Ie(1)},[t,S]),m.useEffect(()=>{const W=ie=>{Ge.current&&!Ge.current.contains(ie.target)&&Re(!1)};return Te&&document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[Te]);const vt=m.useMemo(()=>!p&&(!x||x.length===0)?_e.filter(W=>!W.hidden):_e.filter(W=>Be.includes(W.field)),[_e,Be,p,x]),nt=m.useMemo(()=>!ae||!n||!t?t||[]:[...t].sort((W,ie)=>{const xe=W[ae],$e=ie[ae];if(xe===$e)return 0;const ke=xe>$e?1:-1;return fe==="asc"?ke:-ke}),[t,ae,fe,n]),Ye=m.useMemo(()=>{if(S||!a)return nt;const W=(Ce-1)*r,ie=W+r;return nt.slice(W,ie)},[nt,Ce,r,a,S]),At=S?y||1:Ce,ot=S?w||1:Math.ceil((nt?.length||0)/r),Ht=m.useCallback(W=>{S&&I?I(W):Ie(W)},[S,I]),dr=W=>{if(!n||e.find($e=>$e. Line truncated
px-4 py-2 rounded-md font-medium transition-colors
focus:outline-none focus:ring-2 focus:ring-offset-2
disabled:opacity-50 disabled:cursor-not-allowed
${d[g.variant||"primary"]}
`,children:[g.iconName&&c.jsx(ne,{name:g.iconName,className:"w-4 h-4 mr-2 inline-block"}),g.label]},h))})]})},ts=(e,t)=>window.G7Core?.t?.(e,t)??e,hl=({isOpen:e,onClose:t,title:n,message:a,confirmText:r,cancelText:o,onConfirm:s,onCancel:i,confirmButtonVariant:l="primary",cancelButtonVariant:f="secondary",width:u="500px",closeOnOverlay:d=!0,isLoading:g=!1,loadingText:h})=>{const b=r??ts("common.confirm"),p=o??ts("common.cancel"),x=h??ts("common.loading"),v=()=>{s()},O=()=>{g||(i?.(),t())},k=()=>{g||t()},C={primary:"bg-blue-600 text-white hover:bg-blue-700",secondary:"bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600",danger:"bg-red-600 text-white hover:bg-red-700",ghost:"bg-transparent text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"};return c.jsxs(ma,{isOpen:e,onClose:k,title:n,width:u,children:[c.jsx(D,{className:"py-2",children:typeof a=="string"?c.jsx(ut,{className:"text-gray-700 dark:text-gray-300",children:a}):a}),c.jsxs(D,{className:"flex justify-end gap-3 mt-6",children:[c.jsx(oe,{onClick:O,disabled:g,className:"px-4 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed",children:c.jsx(Z,{children:p})}),c.jsxs(oe,{onClick:v,disabled:g,className:`flex items-center gap-2 px-4 py-2 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed ${C[l]}`,children:[g&&c.jsx(ne,{name:de.Spinner,className:"w-4 h-4 animate-spin"}),c.jsx(Z,{children:g?x:b})]})]})]})},t0=(e,t)=>window.G7Core?.t?.(e,t)??e,r0=({isOpen:e,onClose:t,title:n,message:a,confirmText:r,onConfirm:o,confirmButtonVariant:s="primary",width:i="500px",closeOnOverlay:l=!0})=>{const d=[{label:r??t0("common.confirm"),onClick:()=>{o?.(),t()},variant:s}],g=typeof a=="string"?c.jsx(ut,{className:"text-gray-700 dark:text-gray-300",children:a}):a;return c.jsx(gl,{isOpen:e,onClose:t,title:n,content:g,actions:d,width:i,closeOnOverlay:l})},n0=(e,t)=>window.G7Core?.t?.(e,t)??e,a0={success:de.CheckCircle,error:de.XCircle,warning:de.ExclamationTriangle,info:de.InfoCircle},pl={success:{bg:"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800",text:"text-green-800 dark:text-green-300"},error:{bg:"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800",text:"text-red-800 dark:text-red-300"},warning:{bg:"bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800",text:"text-yellow-800 dark:text-yellow-300"},info:{bg:"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800",text:"text-blue-800 dark:text-blue-300"}},o0={"top-left":"top-4 left-4","top-center":"top-4 left-1/2 -translate-x-1/2","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-center":"bottom-4 left-1/2 -translate-x-1/2","bottom-right":"bottom-4 right-4"},s0=({toasts:e,position:t="bottom-center",duration:n=3e3,onRemove:a})=>{const[r,o]=m.useState(new Map),s=m.useCallback(i=>{o(l=>{const f=new Map(l);return f.set(i,!1),f}),setTimeout(()=>{if(a)a(i);else{const l=window.G7Core;l?.state?.update&&l.state.update(f=>({toasts:(Array.isArray(f.toasts)?f.toasts:[]).filter(d=>d.id!==i)}))}},300)},[a]);return m.useEffect(()=>{!e||e.length===0||e.forEach(i=>{if(r.has(i.id))return;o(f=>{const u=new Map(f);return u.set(i.id,!0),u});const l=i.duration||n;l>0&&setTimeout(()=>{s(i.id)},l)})},[e,n,s,r]),!e||e.length===0?null:c.jsx(D,{className:`fixed z-[9999] flex flex-col gap-2 ${o0[t]}`,"aria-live":"polite","aria-atomic":"true",children:e.map(i=>c.jsx(i0,{toast:i,position:t,isVisible:r.get(i.id)??!0,onClose:()=>s(i.id)},i.id))})},i0=({toast:e,position:t,isVisible:n,onClose:a})=>{const r=pl[e.type]||pl.info,o=e.icon?e.icon:a0[e.type],s=t.startsWith("bottom")?"translate-y-2":"-translate-y-2";return c.jsxs(D,{className:`
flex items-center gap-3 p-4 rounded-lg border shadow-lg
min-w-[300px] max-w-md
transition-all duration-300
${r.bg}
${n?"opacity-100 translate-y-0":`opacity-0 ${s}`}
`,role:"alert",children:[c.jsx(ne,{name:o,className:`w-5 h-5 flex-shrink-0 ${r.text}`}),c.jsx(Z,{className:`flex-1 text-sm font-medium ${r.text}`,children:e.message}),c.jsx(oe,{onClick:a,className:`flex-shrink-0 p-1 rounded hover:bg-black/10 dark:hover:bg-white/10 ${r.text} focus:outline-none`,"aria-label":n0("common.close_notification"),children:c.jsx(ne,{name:de.Times,className:"w-4 h-4"})})]})},bl=({items:e,separator:t=c.jsx(ne,{name:de.ChevronRight,className:"w-4 h-4 text-gray-400 dark:text-gray-500"}),showHome:n=!1,homeHref:a="/",maxItems:r,className:o=""})=>{let i=n?[{label:"Home",href:a},...e]:e,l=i,f=!1;if(r&&i.length>r){f=!0;const u=i.slice(0,1),d=i.slice(-(r-2));l=[...u,...d]}return c.jsx(ua,{className:`flex items-center space-x-2 text-sm ${o}`,"aria-label":"Breadcrumb",children:c.jsx(D,{className:"flex items-center space-x-2",children:l.map((u,d)=>{const g=d===l.length-1,h=d===0;return c.jsxs(m.Fragment,{children:[f&&h&&c.jsxs(c.Fragment,{children:[c.jsx(ml,{item:u,isLast:!1}),c.jsx(Z,{className:"text-gray-400 dark:text-gray-500","aria-hidden":"true",children:t}),c.jsx(Z,{className:"text-gray-500 dark:text-gray-400",children:"..."}),l.length>1&&c.jsx(Z,{className:"text-gray-400 dark:text-gray-500","aria-hidden":"true",children:t})]}),(!f||!h)&&c.jsxs(c.Fragment,{children:[c.jsx(ml,{item:u,isLast:g}),!g&&c.jsx(Z,{className:"text-gray-400 dark:text-gray-500","aria-hidden":"true",children:t})]})]},d)})})})},ml=({item:e,isLast:t})=>t||!e.href&&!e.onClick?c.jsx(Z,{className:"font-medium text-gray-900 dark:text-white","aria-current":t?"page":void 0,children:e.label}):e.onClick?c.jsx(Hr,{href:"#",onClick:n=>{n.preventDefault(),e.onClick?.()},className:"text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors",children:e.label}):c.jsx(Hr,{href:e.href,className:"text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors",children:e.label}),l0=({title:e,description:t,iconName:n,illustrationSrc:a,illustrationAlt:r="Empty state illustration",actions:o=[],className:s=""})=>{const i={primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600 focus:ring-gray-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",ghost:"bg-transparent text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-gray-500"};return c.jsxs(D,{className:`flex flex-col items-center justify-center p-8 text-center ${s}`,role:"status","aria-live":"polite",children:[a?c.jsx(ar,{src:a,alt:r,className:"w-48 h-48 mb-6 object-contain"}):n?c.jsx(D,{className:"mb-6 p-4 rounded-full bg-gray-100 dark:bg-gray-700",children:c.jsx(ne,{name:n,className:"w-12 h-12 text-gray-400 dark:text-gray-500"})}):null,c.jsx(Er,{className:"text-xl font-semibold text-gray-900 dark:text-white mb-2",children:e}),t&&c.jsx(ut,{className:"text-gray-600 dark:text-gray-400 mb-6 max-w-md",children:t}),o.length>0&&c.jsx(D,{className:"flex flex-wrap gap-3 justify-center",children:o.map((l,f)=>c.jsxs(oe,{onClick:l.onClick,className:`
px-4 py-2 rounded-md font-medium transition-colors
focus:outline-none focus:ring-2 focus:ring-offset-2
${i[l.variant||"primary"]}
`,children:[l.iconName&&c.jsx(ne,{name:l.iconName,className:"w-4 h-4 mr-2 inline-block"}),l.label]},f))})]})},c0=(e,t)=>window.G7Core?.t?.(e,t)??e,u0=({id:e,size:t="md",color:n="text-blue-600",fullscreen:a=!1,text:r,className:o=""})=>{const s={sm:"w-4 h-4 border-2",md:"w-8 h-8 border-2",lg:"w-12 h-12 border-3",xl:"w-16 h-16 border-4"},i={sm:"text-xs",md:"text-sm",lg:"text-base",xl:"text-lg"},l=c.jsxs(D,{className:`flex flex-col items-center justify-center gap-3 ${o}`,children:[c.jsx(D,{className:`
${s[t]}
border-gray-200 dark:border-gray-700 border-t-current
rounded-full animate-spin
${n}
`,role:"status","aria-label":c0("common.loading")}),r&&c.jsx(Z,{className:`${i[t]} ${n} font-medium`,children:r})]});return a?c.jsx(D,{id:e,className:"fixed inset-0 z-50 flex items-center justify-center bg-white dark:bg-gray-900 bg-opacity-90 dark:bg-opacity-90","aria-live":"polite","aria-busy":"true",children:l}):c.jsx(D,{id:e,className:"flex items-center justify-center p-4","aria-live":"polite","aria-busy":"true",children:l})},lt=({className:e="",children:t,style:n,...a})=>c.jsx("i",{className:e,style:n,...a,children:t}),Gr=()=>window.G7Core,rs=(e,t)=>window.G7Core?.t?.(e,t)??e,d0=({logo:e,logoAlt:t="Logo",menu:n=[],collapsed:a=!1,onToggleCollapse:r,className:o="",currentLocale:s})=>{const[i,l]=m.useState(new Set),[f,u]=m.useState(s||Gr()?.locale?.current?.()||"ko"),[d,g]=m.useState(window.location.pathname),h=m.useMemo(()=>{const S=[],y=w=>{for(const I of w)I.url&&S.push(I.url),I.children&&y(I.children)};return y(n),S},[n]),b=m.useCallback(S=>{let y=null;for(const w of h)(S===w||S.startsWith(w+"/"))&&(!y||w.length>y.length)&&(y=w);return y},[h]);m.useEffect(()=>{const S=Gr();return S?.state?.subscribe?S.state.subscribe(w=>{const I=w?._global?.locale||S?.locale?.current?.()||"ko";u(I);const L=w?._global?.currentPath||window.location.pathname;g(L)}):void 0},[]),m.useEffect(()=>{const S=()=>{g(window.location.pathname)};return window.addEventListener("popstate",S),()=>window.removeEventListener("popstate",S)},[]),m.useEffect(()=>{s&&u(s)},[s]);const p=(S,y)=>!S||typeof y!="string"?!1:y===S?!0:y.startsWith(S+"/")?b(y)===S:!1,x=(S,y)=>{const w=new Set,I=L=>{for(const F of L)if(F.children&&F.children.length>0){if(I(F.children)||p(F.url,y))return w.add(F.id),!0}else if(p(F.url,y))return!0;return!1};return I(S),w};m.useEffect(()=>{if(n.length>0&&d){const S=x(n,d);S.size>0&&l(y=>new Set([...y,...S]))}},[d,n]);const v=S=>p(S,d),O=S=>S.children?S.children.some(y=>v(y.url)||O(y)):!1,k=S=>{l(y=>{const w=new Set(y);return w.has(S)?w.delete(S):w.add(S),w})},C=S=>typeof S=="string"?S:S[f]||S.en||Object.values(S)[0]||"",N=(S,y)=>{Gr()?.dispatch?(S.preventDefault(),Gr().navigation?.onComplete(()=>{Gr().dispatch({handler:"setState",params:{target:"global",sidebarOpen:!1}})}),Gr().dispatch({handler:"navigate",params:{path:y}})):window.location.href=y},E=(S,y=0)=>{const w=S.children&&S.children.length>0,I=i.has(S.id),L=y*16+16,F=C(S.name),T=v(S.url),P=O(S),V="w-full flex items-center justify-between px-4 py-3 transition-colors",M="bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 border-l-4 border-blue-500",A="text-blue-600 dark:text-blue-400",j="text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700";return c.jsxs(D,{children:[w&&S.url?c.jsxs(D,{className:`
${V}
${T?M:P?A:j}
${a?"justify-center":""}
`,style:{paddingLeft:a?void 0:`${L}px`},children:[c.jsxs(oe,{onClick:Y=>N(Y,S.url),className:"flex items-center justify-start flex-1 min-w-0",children:[S.icon&&c.jsx(lt,{className:`${S.icon} ${a?"":"mr-3"} w-5 h-5 flex items-center justify-center`}),!a&&c.jsx(Z,{className:"truncate",children:F})]}),!a&&c.jsxs(D,{className:"flex items-center gap-1",children:[S.module_id&&c.jsx(lt,{className:"fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60",title:"모듈 메뉴"}),c.jsx(oe,{onClick:()=>k(S.id),className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600","aria-label":rs(I?"common.collapse":"common.expand"),children:c.jsx(lt,{className:`fas fa-chevron-down w-4 h-4 transition-transform ${I?"rotate-180":""}`})})]})]}):w?c.jsxs(oe,{onClick:()=>k(S.id),className:`
${V}
${P?A:j}
${a?"justify-center":""}
`,style:{paddingLeft:a?void 0:`${L}px`},children:[c.jsxs(D,{className:"flex items-center",children:[S.icon&&c.jsx(lt,{className:`${S.icon} ${a?"":"mr-3"} w-5 h-5 flex items-center justify-center`}),!a&&c.jsx(Z,{children:F})]}),!a&&c.jsxs(D,{className:"flex items-center gap-1",children:[S.module_id&&c.jsx(lt,{className:"fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60",title:"모듈 메뉴"}),c.jsx(lt,{className:`fas fa-chevron-down w-4 h-4 transition-transform ${I?"rotate-180":""}`})]})]}):S.url?c.jsxs(oe,{onClick:Y=>N(Y,S.url),className:`
${V}
${T?M:j}
${a?"justify-center":""}
text-left
`,style:{paddingLeft:a?void 0:`${L}px`},children:[c.jsxs(D,{className:"flex items-center",children:[S.icon&&c.jsx(lt,{className:`${S.icon} ${a?"":"mr-3"} w-5 h-5 flex items-center justify-center`}),!a&&c.jsx(Z,{children:F})]}),!a&&S.module_id&&c.jsx(lt,{className:"fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60",title:"모듈 메뉴"})]}):c.jsxs(oe,{className:`
${V}
text-gray-400 dark:text-gray-500 cursor-default
${a?"justify-center":""}
text-left
`,style:{paddingLeft:a?void 0:`${L}px`},children:[c.jsxs(D,{className:"flex items-center",children:[S.icon&&c.jsx(lt,{className:`${S.icon} ${a?"":"mr-3"} w-5 h-5 flex items-center justify-center`}),!a&&c.jsx(Z,{children:F})]}),!a&&S.module_id&&c.jsx(lt,{className:"fas fa-cube w-3 h-3 mr-2 text-gray-400 dark:text-gray-500 opacity-60",title:"모듈 메뉴"})]}),w&&!a&&I&&c.jsx(D,{className:"bg-gray-50 dark:bg-gray-900",children:S.children.map(Y=>E(Y,y+1))})]},S.id)};return c.jsxs(D,{className:o,children:[(e||r)&&c.jsxs(D,{className:"flex items-center justify-between px-4 py-4 border-b border-gray-200 dark:border-gray-700",children:[e&&!a&&c.jsx(ar,{src:e,alt:t,className:"h-8"}),r&&c.jsx(oe,{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors","aria-label":rs(a?"common.expand_sidebar":"common.collapse_sidebar"),children:c.jsx(lt,{className:`${a?"fas fa-chevron-right":"fas fa-chevron-left"} w-5 h-5 text-gray-600 dark:text-gray-400`})})]}),c.jsx(D,{children:n.map(S=>E(S))})]})},Sn=(e,t)=>window.G7Core?.t?.(e,t)??e,f0=({user:e={name:"",email:""},notifications:t=[],onNotificationClick:n,onProfileClick:a,onLogoutClick:r,className:o=""})=>{const[s,i]=m.useState(!1),[l,f]=m.useState(!1),u=m.useRef(null),d=m.useRef(null),g=t.filter(h=>!h.read).length;return m.useEffect(()=>{const h=b=>{u.current&&!u.current.contains(b.target)&&i(!1),d.current&&!d.current.contains(b.target)&&f(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]),c.jsxs(D,{className:`
bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 flex items-center justify-end gap-4
${o}
`,children:[c.jsxs(D,{ref:u,className:"relative",children:[c.jsxs(oe,{onClick:()=>i(!s),className:"relative p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-colors","aria-label":Sn("common.notifications"),children:[c.jsx(ne,{name:de.Bell,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),g>0&&c.jsx(Z,{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",children:g>9?"9+":g})]}),s&&c.jsxs(D,{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",children:[c.jsx(D,{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:c.jsx(Z,{className:"font-semibold text-gray-900 dark:text-white",children:Sn("common.notifications")})}),c.jsx(D,{className:"max-h-96 overflow-y-auto",children:t.length===0?c.jsx(D,{className:"px-4 py-8 text-center text-gray-500 dark:text-gray-400",children:c.jsx(Z,{children:Sn("common.no_notifications")})}):t.map(h=>c.jsx(oe,{onClick:()=>{h.onClick?.(),n?.(h.id),i(!1)},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
${h.read?"":"bg-blue-50 dark:bg-blue-900/20"}
`,children:c.jsxs(D,{className:"flex items-start gap-3",children:[h.iconName&&c.jsx(ne,{name:h.iconName,className:"w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5"}),c.jsxs(D,{className:"flex-1",children:[c.jsx(D,{className:"font-semibold text-gray-900 dark:text-white text-sm",children:h.title}),c.jsx(D,{className:"text-gray-600 dark:text-gray-400 text-sm mt-1",children:h.message}),c.jsx(D,{className:"text-gray-400 dark:text-gray-500 text-xs mt-1",children:h.time})]}),!h.read&&c.jsx(Z,{className:"w-2 h-2 bg-blue-500 rounded-full mt-1.5"})]})},h.id))})]})]}),c.jsxs(D,{ref:d,className:"relative",children:[c.jsxs(oe,{onClick:()=>f(!l),className:"flex items-center gap-3 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:[e.avatar?c.jsx(ar,{src:e.avatar,alt:e.name,className:"w-8 h-8 rounded-full object-cover"}):c.jsx(D,{className:"w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center",children:c.jsx(ne,{name:de.User,className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),c.jsxs(D,{className:"hidden md:block text-left",children:[c.jsx(D,{className:"font-semibold text-gray-900 dark:text-white text-sm",children:e.name}),e.role&&c.jsx(D,{className:"text-gray-500 dark:text-gray-400 text-xs",children:e.role})]}),c.jsx(ne,{name:de.ChevronDown,className:"w-4 h-4 text-gray-600 dark:text-gray-400"})]}),l&&c.jsxs(D,{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50",children:[c.jsxs(D,{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:[c.jsx(D,{className:"font-semibold text-gray-900 dark:text-white",children:e.name}),c.jsx(D,{className:"text-gray-500 dark:text-gray-400 text-sm",children:e.email})]}),c.jsxs(D,{className:"py-2",children:[c.jsxs(oe,{onClick:()=>{a?.(),f(!1)},className:"w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors text-gray-900 dark:text-white",children:[c.jsx(ne,{name:de.User,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{children:Sn("common.profile_settings")})]}),c.jsxs(oe,{onClick:()=>{r?.(),f(!1)},className:"w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 text-red-600 dark:text-red-400 transition-colors",children:[c.jsx(ne,{name:de.ArrowRight,className:"w-5 h-5"}),c.jsx(Z,{children:Sn("common.logout")})]})]})]})]})]})},g0=({notifications:e=[],titleText:t="Notifications",emptyText:n="No notifications",onNotificationClick:a,className:r=""})=>{const[o,s]=m.useState(!1),i=m.useRef(null),l=e.filter(f=>!f.read).length;return m.useEffect(()=>{const f=u=>{i.current&&!i.current.contains(u.target)&&s(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[]),c.jsxs(D,{ref:i,className:`relative ${r}`,children:[c.jsxs(oe,{onClick:()=>s(!o),className:"relative p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors","aria-label":t,children:[c.jsx(ne,{name:de.Bell,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),l>0&&c.jsx(Z,{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",children:l>9?"9+":l})]}),o&&c.jsxs(D,{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",children:[c.jsx(D,{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:c.jsx(Z,{className:"font-semibold text-gray-900 dark:text-white",children:t})}),c.jsx(D,{className:"max-h-96 overflow-y-auto",children:e.length===0?c.jsx(D,{className:"px-4 py-8 text-center text-gray-500 dark:text-gray-400",children:c.jsx(Z,{children:n})}):e.map(f=>c.jsx(oe,{onClick:()=>{f.onClick?.(),a?.(f.id),s(!1)},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
${f.read?"":"bg-blue-50 dark:bg-gray-700"}
`,children:c.jsxs(D,{className:"flex items-start gap-3",children:[f.iconName&&c.jsx(ne,{name:f.iconName,className:"w-5 h-5 text-gray-600 dark:text-gray-400 mt-0.5"}),c.jsxs(D,{className:"flex-1",children:[c.jsx(D,{className:"font-semibold text-gray-900 dark:text-white text-sm",children:f.title}),c.jsx(D,{className:"text-gray-600 dark:text-gray-300 text-sm mt-1",children:f.message}),c.jsx(D,{className:"text-gray-400 dark:text-gray-500 text-xs mt-1",children:f.time})]}),!f.read&&c.jsx(Z,{className:"w-2 h-2 bg-blue-500 rounded-full mt-1.5"})]})},f.id))})]})]})},va=window.G7Core?.createLogger?.("Comp:LanguageSelector")??{log:(...e)=>console.log("[Comp:LanguageSelector]",...e),warn:(...e)=>console.warn("[Comp:LanguageSelector]",...e),error:(...e)=>console.error("[Comp:LanguageSelector]",...e)},vl=e=>({ko:"한국어",en:"English",ja:"日本語",zh:"中文",es:"Español",fr:"Français",de:"Deutsch"})[e]||e,yl=({availableLocales:e=["ko","en"],languageText:t="Language",apiEndpoint:n="/api/admin/users/me/language",onLanguageChange:a,className:r="",inline:o=!1})=>{const[s,i]=m.useState(!1),[l,f]=m.useState(!1),[u,d]=m.useState(()=>localStorage.getItem("g7_locale")||"ko"),g=m.useRef(null);m.useEffect(()=>{if(o)return;const x=v=>{g.current&&!g.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[o]);const h=()=>{const v=`; ${document.cookie}`.split("; XSRF-TOKEN=");return v.length===2?decodeURIComponent(v.pop()?.split(";").shift()||""):null},b=()=>localStorage.getItem("auth_token"),p=async x=>{if(!(l||x===u))try{f(!0);const v=h(),O=b();try{const k=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json",Accept:"application/json",...v&&{"X-XSRF-TOKEN":v},...O&&{Authorization:`Bearer ${O}`}},credentials:"include",body:JSON.stringify({language:x})});k.ok||va.warn("언어 설정 저장 실패 (UI는 변경됨):",k.statusText)}catch(k){va.warn("언어 설정 API 호출 실패 (UI는 변경됨):",k)}d(x),i(!1),a?.(x),window.__templateApp?await window.__templateApp.changeLocale(x):(va.warn("TemplateApp not found, reloading page"),window.location.reload())}catch(v){va.error("언어 변경 오류:",v)}finally{f(!1)}};return o?c.jsxs(D,{className:`${r}`,children:[c.jsxs(oe,{onClick:()=>i(!s),disabled:l,className:"w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors",children:[c.jsx(ne,{name:de.Globe,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{className:"text-gray-900 dark:text-white flex-1",children:t}),c.jsx(Z,{className:"px-2 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded",children:u.toUpperCase()}),c.jsx(ne,{name:de.ChevronDown,className:`w-4 h-4 text-gray-400 dark:text-gray-500 transition-transform ${s?"rotate-180":""}`})]}),s&&c.jsx(D,{className:"px-4 py-2 flex flex-wrap gap-2",children:e.map(x=>c.jsx(oe,{onClick:()=>p(x),disabled:l,className:`
px-3 py-1.5 text-sm font-medium rounded-md transition-colors
${u===x?"bg-blue-600 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600"}
${l?"opacity-50 cursor-not-allowed":""}
`,children:vl(x)},x))})]}):c.jsxs(D,{ref:g,className:`relative ${r}`,children:[c.jsx(oe,{onClick:()=>i(!s),className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors","aria-label":t,children:c.jsx(ne,{name:de.Globe,className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),s&&c.jsx(D,{className:"absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50",children:c.jsx(D,{className:"py-2",children:e.map(x=>c.jsxs(oe,{onClick:()=>p(x),disabled:l,className:`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${u===x?"bg-gray-50 dark:bg-gray-700":""}
${l?"opacity-50 cursor-not-allowed":""}
`,children:[c.jsx(Z,{className:"text-gray-900 dark:text-white flex-1",children:vl(x)}),u===x&&c.jsx(ne,{name:de.Check,className:"w-4 h-4 text-blue-600 dark:text-blue-400"})]},x))})})]})},xl=window.G7Core?.createLogger?.("Comp:UserProfile")??{log:(...e)=>console.log("[Comp:UserProfile]",...e),warn:(...e)=>console.warn("[Comp:UserProfile]",...e),error:(...e)=>console.error("[Comp:UserProfile]",...e)},h0=({user:e={name:"",email:""},profileText:t="Profile Settings",logoutText:n="Logout",languageText:a="Language",availableLocales:r=["ko","en"],onProfileClick:o,onLogoutClick:s,className:i="",logoutEndpoint:l="/api/admin/auth/logout",redirectPath:f="/admin/login"})=>{const[u,d]=m.useState(!1),[g,h]=m.useState(!1),b=m.useRef(null);m.useEffect(()=>{const O=k=>{b.current&&!b.current.contains(k.target)&&d(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const p=()=>{const k=`; ${document.cookie}`.split("; XSRF-TOKEN=");return k.length===2?decodeURIComponent(k.pop()?.split(";").shift()||""):null},x=()=>localStorage.getItem("auth_token"),v=async()=>{if(!g)try{if(h(!0),d(!1),s){s();return}const O=p(),k=x(),C=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...O&&{"X-XSRF-TOKEN":O},...k&&{Authorization:`Bearer ${k}`}},credentials:"include"});C.ok?(localStorage.removeItem("auth_token"),window.location.href=f):(xl.error("로그아웃 실패:",C.statusText),localStorage.removeItem("auth_token"),window.location.href=f)}catch(O){xl.error("로그아웃 오류:",O),localStorage.removeItem("auth_token"),window.location.href=f}finally{h(!1)}};return c.jsxs(D,{ref:b,className:`relative ${i}`,children:[c.jsxs(oe,{onClick:()=>d(!u),className:"flex items-center gap-2 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors w-full",children:[e.avatar?c.jsx(ar,{src:e.avatar,alt:e.name,className:"w-8 h-8 rounded-full object-cover"}):c.jsx(D,{className:"w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center",children:c.jsx(ne,{name:de.User,className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),c.jsxs(D,{className:"flex-1 text-left",children:[c.jsx(D,{className:"font-semibold text-gray-900 dark:text-white text-sm",children:e.name}),e.role&&c.jsx(D,{className:"text-gray-500 dark:text-gray-400 text-xs",children:e.role})]}),c.jsx(ne,{name:de.ChevronDown,className:"w-4 h-4 text-gray-600 dark:text-gray-400"})]}),u&&c.jsxs(D,{className:"absolute bottom-full left-0 mb-2 w-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50",children:[c.jsxs(D,{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors",onClick:()=>{d(!1),window.G7Core?.dispatch({handler:"navigate",params:{path:`/admin/users/${e.uuid}`}})},children:[c.jsx(D,{className:"font-semibold text-gray-900 dark:text-white",children:e.name}),c.jsx(D,{className:"text-gray-500 dark:text-gray-400 text-sm",children:e.email})]}),r.length>1&&c.jsx(D,{className:"border-b border-gray-200 dark:border-gray-700",children:c.jsx(yl,{availableLocales:r,languageText:a,inline:!0,onLanguageChange:()=>d(!1)})}),c.jsxs(D,{className:"py-2",children:[c.jsxs(oe,{onClick:()=>{d(!1),o?o():window.G7Core?.dispatch({handler:"navigate",params:{path:`/admin/users/${e.uuid}/edit`}})},className:"w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center justify-start gap-3 transition-colors",children:[c.jsx(ne,{name:de.User,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{className:"text-gray-900 dark:text-white",children:t})]}),c.jsxs(oe,{onClick:v,disabled:g,className:"w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center justify-start gap-3 text-red-600 dark:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[c.jsx(ne,{name:de.ArrowRight,className:"w-5 h-5"}),c.jsx(Z,{children:g?"Logging out...":n})]})]})]})]})},p0=({copyright:e="© 2026 G7",version:t,quickLinks:n=[],className:a="",changelogModalId:r,copyrightModalId:o})=>{const s=m.useCallback(()=>{r&&window.G7Core?.dispatch?.({handler:"sequence",actions:[{handler:"apiCall",auth_required:!0,target:"/api/admin/changelog",params:{method:"GET"},onSuccess:[{handler:"setState",params:{target:"global",coreChangelogContent:"{{response.data.content}}"}},{handler:"openModal",target:r}],onError:[{handler:"openModal",target:r}]}]})},[r]),i=m.useCallback(()=>{o&&window.G7Core?.dispatch?.({handler:"sequence",actions:[{handler:"apiCall",auth_required:!0,target:"/api/admin/license",params:{method:"GET"},onSuccess:[{handler:"setState",params:{target:"global",coreLicenseContent:"{{response.data.content}}"}},{handler:"openModal",target:o}],onError:[{handler:"openModal",target:o}]}]})},[o]);return c.jsx(D,{className:`
bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-6 py-4
${a}
`,children:c.jsxs(D,{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[c.jsxs(D,{className:"flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400",children:[c.jsx(Z,{className:o?"cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 transition-colors":"",onClick:o?i:void 0,children:e}),t&&c.jsxs(c.Fragment,{children:[c.jsx(Z,{className:"hidden md:inline",children:"•"}),c.jsxs(Z,{className:`flex items-center gap-2 ${r?"cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 transition-colors":""}`,onClick:r?s:void 0,children:[c.jsx(ne,{name:de.Tag,className:"w-4 h-4"}),c.jsxs(Z,{children:["v",t]})]})]})]}),n.length>0&&c.jsx(D,{className:"flex items-center gap-4",children:n.map(l=>c.jsxs(Hr,{href:l.url,className:"flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors",children:[l.iconName&&c.jsx(ne,{name:l.iconName,className:"w-4 h-4"}),c.jsx(Z,{children:l.label})]},l.id))})]})})},b0=({title:e,description:t,breadcrumbItems:n,tabs:a,onTabChange:r,actions:o,className:s="",children:i})=>{const l=(f="secondary")=>`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${{primary:"bg-blue-600 text-white hover:bg-blue-700",secondary:"bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600",danger:"bg-red-600 text-white hover:bg-red-700",ghost:"p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"}[f]}`;return c.jsxs(D,{className:s,children:[n&&n.length>0&&c.jsx(D,{className:"mb-4",children:c.jsx(bl,{items:n})}),c.jsxs(D,{className:"flex items-center justify-between mb-6",children:[c.jsxs(D,{children:[c.jsx(Ao,{className:"text-xl sm:text-2xl font-semibold text-gray-900 dark:text-white",children:e}),t&&c.jsx(ut,{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:t})]}),i?c.jsx(D,{className:"flex items-center gap-2",children:i}):o&&o.length>0?c.jsx(D,{className:"flex items-center gap-2",children:o.map(f=>c.jsxs(oe,{onClick:f.onClick,disabled:f.disabled,className:l(f.variant),children:[f.iconName&&c.jsx(ne,{name:f.iconName,className:"w-5 h-5"}),f.variant!=="ghost"&&f.label&&c.jsx(D,{children:f.label})]},f.id))}):null]}),a&&a.length>0&&c.jsx(D,{className:"flex gap-6 border-b border-gray-200 dark:border-gray-700 mb-6",children:a.map(f=>c.jsxs(oe,{onClick:()=>r?.(f.value),className:`
px-1 py-3 border-b-2 transition-colors font-medium flex items-center gap-2 -mb-px
${f.active?"border-blue-600 text-blue-600 dark:text-blue-400":"border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"}
`,children:[c.jsx(D,{children:f.label}),f.badge!==void 0&&c.jsx(D,{className:`
px-2 py-0.5 rounded-full text-xs font-semibold
${f.active?"bg-blue-100 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400":"bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400"}
`,children:f.badge})]},f.id))})]})},xr=(e,t)=>window.G7Core?.t?.(e,t)??e,m0=({image:e,imageAlt:t,vendor:n,name:a,version:r,status:o,updateAvailable:s=!1,latestVersion:i,dependencies:l=[],showLayoutEditButton:f=!1,actions:u=[],onLayoutEditClick:d,className:g=""})=>{const h=p=>({active:"success",inactive:"default",pending:"pending",error:"error"})[p],b=p=>({active:xr("common.status_active"),inactive:xr("common.status_inactive"),pending:xr("common.status_pending"),error:xr("common.status_error")})[p];return c.jsxs(D,{className:`
bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden hover:shadow-lg transition-shadow
${g}
`,children:[e&&c.jsxs(D,{className:"relative",children:[c.jsx(ar,{src:e,alt:t||xr("common.template_preview",{vendor:n,name:a}),className:"w-full h-48 object-cover"}),c.jsx(D,{className:"absolute top-3 right-3",children:c.jsx(fa,{status:h(o),label:b(o),showIcon:!0})}),s&&c.jsx(D,{className:"absolute top-3 left-3",children:c.jsxs(Z,{className:"flex items-center gap-1 px-2 py-1 bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-400 border border-yellow-200 dark:border-yellow-800 rounded-md text-xs font-semibold",children:[c.jsx(ne,{name:de.ExclamationTriangle,className:"w-3 h-3"}),c.jsx(Z,{children:xr("common.update_available")})]})})]}),c.jsxs(D,{className:"p-4",children:[c.jsxs(D,{className:"flex items-start justify-between mb-3",children:[c.jsxs(D,{className:"flex-1",children:[c.jsxs(Vr,{className:"text-lg font-bold text-gray-900 dark:text-white",children:[n,"/",a]}),c.jsxs(D,{className:"flex items-center gap-2 mt-1 text-sm text-gray-600 dark:text-gray-400",children:[c.jsxs(Z,{children:["v",r]}),s&&i&&c.jsxs(c.Fragment,{children:[c.jsx(Z,{children:"→"}),c.jsxs(Z,{className:"text-yellow-600 dark:text-yellow-400 font-semibold",children:["v",i]})]})]}),!e&&c.jsx(D,{className:"mt-2",children:c.jsx(fa,{status:h(o),label:b(o),showIcon:!0})})]}),u.length>0&&c.jsx(bn,{items:u,triggerIconName:de.EllipsisVertical,position:"left"})]}),l.length>0&&c.jsxs(D,{className:"mb-3",children:[c.jsxs(ut,{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:[xr("common.dependencies"),":"]}),c.jsx(D,{className:"flex flex-wrap gap-1",children:l.map((p,x)=>c.jsx(Z,{className:"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-xs rounded",children:p},x))})]}),f&&d&&c.jsxs(oe,{onClick:d,className:"w-full px-4 py-2 bg-blue-600 dark:bg-blue-500 text-white rounded-md hover:bg-blue-700 dark:hover:bg-blue-600 transition-colors flex items-center justify-center gap-2 font-medium",children:[c.jsx(ne,{name:de.Edit,className:"w-4 h-4"}),c.jsx(Z,{children:xr("common.edit_layout")})]})]})]})},wl=({type:e,message:t,dismissible:n=!1,onDismiss:a,className:r=""})=>{const s={info:{bgColor:"bg-blue-100 dark:bg-blue-900",borderColor:"border-blue-400 dark:border-blue-600",textColor:"text-blue-800 dark:text-blue-200",iconColor:"text-blue-600 dark:text-blue-400",icon:de.InfoCircle},success:{bgColor:"bg-green-100 dark:bg-green-900",borderColor:"border-green-400 dark:border-green-600",textColor:"text-green-800 dark:text-green-200",iconColor:"text-green-600 dark:text-green-400",icon:de.CheckCircle},warning:{bgColor:"bg-yellow-100 dark:bg-yellow-900",borderColor:"border-yellow-400 dark:border-yellow-600",textColor:"text-yellow-800 dark:text-yellow-200",iconColor:"text-yellow-600 dark:text-yellow-400",icon:de.ExclamationTriangle},error:{bgColor:"bg-red-100 dark:bg-red-900",borderColor:"border-red-400 dark:border-red-600",textColor:"text-red-800 dark:text-red-200",iconColor:"text-red-600 dark:text-red-400",icon:de.TimesCircle}}[e],i=`
flex items-start gap-3 p-4 rounded-lg border
${s.bgColor}
${s.borderColor}
${r}
`.trim().replace(/\s+/g," ");return c.jsxs(D,{className:i,role:"alert","aria-live":"polite",children:[c.jsx(ne,{name:s.icon,className:`${s.iconColor} flex-shrink-0 mt-0.5`,ariaLabel:`${e} icon`}),c.jsx(ut,{className:`flex-1 ${s.textColor} text-sm`,children:t}),n&&c.jsx(oe,{onClick:a,className:`${s.textColor} hover:opacity-70 flex-shrink-0 bg-transparent border-0 p-0 cursor-pointer`,"aria-label":"Close alert",children:c.jsx(ne,{name:de.Times,className:s.iconColor,ariaLabel:"Close"})})]})},v0=({layoutName:e,onBack:t,onPreview:n,onSave:a,isSaving:r=!1,className:o=""})=>{const s=`
flex items-center justify-between gap-4 p-4 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700
${o}
`.trim().replace(/\s+/g," ");return c.jsxs(D,{className:s,children:[c.jsxs(D,{className:"flex items-center gap-3",children:[c.jsx(oe,{onClick:t,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors bg-transparent border-0 cursor-pointer","aria-label":"뒤로가기",children:c.jsx(ne,{name:de.ArrowLeft,className:"text-gray-700 dark:text-gray-300",ariaLabel:"뒤로가기"})}),c.jsx(Er,{className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:e})]}),c.jsxs(D,{className:"flex items-center gap-2",children:[c.jsx(oe,{onClick:n,className:"px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors border-0 cursor-pointer","aria-label":"미리보기",children:c.jsxs(D,{className:"flex items-center gap-2",children:[c.jsx(ne,{name:de.Eye,className:"text-gray-700 dark:text-gray-300",ariaLabel:"미리보기 아이콘"}),c.jsx("span",{children:"미리보기"})]})}),c.jsx(oe,{onClick:a,disabled:r,className:`
px-4 py-2 rounded-lg transition-colors border-0 cursor-pointer
${r?"bg-blue-400 dark:bg-blue-600 cursor-not-allowed":"bg-blue-600 dark:bg-blue-500 hover:bg-blue-700 dark:hover:bg-blue-600"}
text-white
`.trim().replace(/\s+/g," "),"aria-label":r?"저장 중...":"저장",children:c.jsxs(D,{className:"flex items-center gap-2",children:[c.jsx(ne,{name:r?de.Spinner:de.Save,className:`text-white ${r?"animate-spin":""}`,ariaLabel:r?"저장 중 아이콘":"저장 아이콘"}),c.jsx("span",{children:r?"저장 중...":"저장"})]})})]})]})},y0=({files:e,selectedId:t,onSelect:n,className:a=""})=>{const r=i=>{try{const l=new Date(i);if(isNaN(l.getTime()))return i;const f=l.getFullYear(),u=String(l.getMonth()+1).padStart(2,"0"),d=String(l.getDate()).padStart(2,"0"),g=String(l.getHours()).padStart(2,"0"),h=String(l.getMinutes()).padStart(2,"0");return`${f}-${u}-${d} ${g}:${h}`}catch{return i}},o=i=>{n(i)},s=`
w-full
${a}
`.trim().replace(/\s+/g," ");return c.jsx(D,{className:s,children:e.length===0?c.jsx(D,{className:"p-4 text-center text-gray-500 dark:text-gray-400",children:"파일이 없습니다."}):c.jsx(Io,{className:"divide-y divide-gray-200 dark:divide-gray-700",role:"listbox","aria-label":"레이아웃 파일 목록",children:e.map(i=>{const l=i.id===t,f=`
flex items-center justify-between p-4 cursor-pointer
transition-colors duration-150
${l?"bg-blue-100 dark:bg-blue-900 border-l-4 border-blue-500":"hover:bg-gray-100 dark:hover:bg-gray-800"}
`.trim().replace(/\s+/g," "),u=`
font-medium
${l?"text-blue-900 dark:text-blue-100":"text-gray-900 dark:text-gray-100"}
`.trim().replace(/\s+/g," "),d=`
text-sm
${l?"text-blue-700 dark:text-blue-300":"text-gray-500 dark:text-gray-400"}
`.trim().replace(/\s+/g," ");return c.jsx(Lo,{className:f,onClick:()=>o(i.id),role:"option","aria-selected":l,tabIndex:0,onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),o(i.id))},children:c.jsxs(D,{className:"flex flex-col gap-1",children:[c.jsx(Z,{className:u,children:i.name}),c.jsx(Z,{className:d,children:r(i.updated_at)})]})},i.id)})})})};function kl(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,a=Array(t);n<t;n++)a[n]=e[n];return a}function x0(e){if(Array.isArray(e))return e}function w0(e,t,n){return(t=M0(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function k0(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var a,r,o,s,i=[],l=!0,f=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(a=o.call(n)).done)&&(i.push(a.value),i.length!==t);l=!0);}catch(u){f=!0,r=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(f)throw r}}return i}}function C0(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Cl(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,a)}return n}function Sl(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Cl(Object(n),!0).forEach(function(a){w0(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cl(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}function S0(e,t){if(e==null)return{};var n,a,r=E0(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function E0(e,t){if(e==null)return{};var n={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.indexOf(a)!==-1)continue;n[a]=e[a]}return n}function N0(e,t){return x0(e)||k0(e,t)||T0(e,t)||C0()}function O0(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function M0(e){var t=O0(e,"string");return typeof t=="symbol"?t:t+""}function T0(e,t){if(e){if(typeof e=="string")return kl(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?kl(e,t):void 0}}function A0(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function El(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,a)}return n}function Nl(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?El(Object(n),!0).forEach(function(a){A0(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):El(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}function I0(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(a){return t.reduceRight(function(r,o){return o(r)},a)}}function En(e){return function t(){for(var n=this,a=arguments.length,r=new Array(a),o=0;o<a;o++)r[o]=arguments[o];return r.length>=e.length?e.apply(this,r):function(){for(var s=arguments.length,i=new Array(s),l=0;l<s;l++)i[l]=arguments[l];return t.apply(n,[].concat(r,i))}}}function ya(e){return{}.toString.call(e).includes("Object")}function L0(e){return!Object.keys(e).length}function Nn(e){return typeof e=="function"}function D0(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function _0(e,t){return ya(t)||wr("changeType"),Object.keys(t).some(function(n){return!D0(e,n)})&&wr("changeField"),t}function P0(e){Nn(e)||wr("selectorType")}function $0(e){Nn(e)||ya(e)||wr("handlerType"),ya(e)&&Object.values(e).some(function(t){return!Nn(t)})&&wr("handlersType")}function F0(e){e||wr("initialIsRequired"),ya(e)||wr("initialType"),L0(e)&&wr("initialContent")}function U0(e,t){throw new Error(e[t]||e.default)}var V0={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},wr=En(U0)(V0),xa={changes:_0,selector:P0,handler:$0,initial:F0};function H0(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};xa.initial(e),xa.handler(t);var n={current:e},a=En(G0)(n,t),r=En(z0)(n),o=En(xa.changes)(e),s=En(j0)(n);function i(){var f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(u){return u};return xa.selector(f),f(n.current)}function l(f){I0(a,r,o,s)(f)}return[i,l]}function j0(e,t){return Nn(t)?t(e.current):t}function z0(e,t){return e.current=Nl(Nl({},e.current),t),t}function G0(e,t,n){return Nn(t)?t(e.current):Object.keys(n).forEach(function(a){var r;return(r=t[a])===null||r===void 0?void 0:r.call(t,e.current[a])}),n}var B0={create:H0},W0={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.54.0/min/vs"}};function Y0(e){return function t(){for(var n=this,a=arguments.length,r=new Array(a),o=0;o<a;o++)r[o]=arguments[o];return r.length>=e.length?e.apply(this,r):function(){for(var s=arguments.length,i=new Array(s),l=0;l<s;l++)i[l]=arguments[l]; Line truncated
You are using deprecated way of configuration.
Instead of using
monaco.config({ urls: { monacoBase: '...' } })
use
monaco.config({ paths: { vs: '...' } })
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
`},Ml=Y0(Z0)(Ol),Q0={config:K0},J0=function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];return function(r){return n.reduceRight(function(o,s){return s(o)},r)}};function Tl(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Tl(e[n],t[n]))}),Sl(Sl({},e),t)}var R0={type:"cancelation",msg:"operation is manually canceled"};function ns(e){var t=!1,n=new Promise(function(a,r){e.then(function(o){return t?r(R0):a(o)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var eh=["monaco"],th=B0.create({config:W0,isInitialized:!1,resolve:null,reject:null,monaco:null}),Al=N0(th,2),On=Al[0],wa=Al[1];function rh(e){var t=Q0.config(e),n=t.monaco,a=S0(t,eh);wa(function(r){return{config:Tl(r.config,a),monaco:n}})}function nh(){var e=On(function(t){var n=t.monaco,a=t.isInitialized,r=t.resolve;return{monaco:n,isInitialized:a,resolve:r}});if(!e.isInitialized){if(wa({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),ns(as);if(window.monaco&&window.monaco.editor)return Il(window.monaco),e.resolve(window.monaco),ns(as);J0(ah,sh)(ih)}return ns(as)}function ah(e){return document.body.appendChild(e)}function oh(e){var t=document.createElement("script");return e&&(t.src=e),t}function sh(e){var t=On(function(a){var r=a.config,o=a.reject;return{config:r,reject:o}}),n=oh("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function ih(){var e=On(function(n){var a=n.config,r=n.resolve,o=n.reject;return{config:a,resolve:r,reject:o}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){var a=n.m;Il(a),e.resolve(a)},function(n){e.reject(n)})}function Il(e){On().monaco||wa({monaco:e})}function lh(){return On(function(e){var t=e.monaco;return t})}var as=new Promise(function(e,t){return wa({resolve:e,reject:t})}),Ll={config:rh,init:nh,__getMonacoInstance:lh},ch={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},os=ch,uh={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},dh=uh;function fh({children:e}){return m.createElement("div",{style:dh.container},e)}var gh=fh,hh=gh;function ph({width:e,height:t,isEditorReady:n,loading:a,_ref:r,className:o,wrapperProps:s}){return m.createElement("section",{style:{...os.wrapper,width:e,height:t},...s},!n&&m.createElement(hh,null,a),m.createElement("div",{ref:r,style:{...os.fullWidth,...!n&&os.hide},className:o}))}var bh=ph,Dl=m.memo(bh);function mh(e){m.useEffect(e,[])}var _l=mh;function vh(e,t,n=!0){let a=m.useRef(!0);m.useEffect(a.current||!n?()=>{a.current=!1}:e,t)}var Ut=vh;function Mn(){}function Br(e,t,n,a){return yh(e,a)||xh(e,t,n,a)}function yh(e,t){return e.editor.getModel(Pl(e,t))}function xh(e,t,n,a){return e.editor.createModel(t,n,a?Pl(e,a):void 0)}function Pl(e,t){return e.Uri.parse(t)}function wh({original:e,modified:t,language:n,originalLanguage:a,modifiedLanguage:r,originalModelPath:o,modifiedModelPath:s,keepCurrentOriginalModel:i=!1,keepCurrentModifiedModel:l=!1,theme:f="light",loading:u="Loading...",options:d={},height:g="100%",width:h="100%",className:b,wrapperProps:p={},beforeMount:x=Mn,onMount:v=Mn}){let[O,k]=m.useState(!1),[C,N]=m.useState(!0),E=m.useRef(null),S=m.useRef(null),y=m.useRef(null),w=m.useRef(v),I=m.useRef(x),L=m.useRef(!1);_l(()=>{let V=Ll.init();return V.then(M=>(S.current=M)&&N(!1)).catch(M=>M?.type!=="cancelation"&&console.error("Monaco initialization: error:",M)),()=>E.current?P():V.cancel()}),Ut(()=>{if(E.current&&S.current){let V=E.current.getOriginalEditor(),M=Br(S.current,e||"",a||n||"text",o||"");M!==V.getModel()&&V.setModel(M)}},[o],O),Ut(()=>{if(E.current&&S.current){let V=E.current.getModifiedEditor(),M=Br(S.current,t||"",r||n||"text",s||"");M!==V.getModel()&&V.setModel(M)}},[s],O),Ut(()=>{let V=E.current.getModifiedEditor();V.getOption(S.current.editor.EditorOption.readOnly)?V.setValue(t||""):t!==V.getValue()&&(V.executeEdits("",[{range:V.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),V.pushUndoStop())},[t],O),Ut(()=>{E.current?.getModel()?.original.setValue(e||"")},[e],O),Ut(()=>{let{original:V,modified:M}=E.current.getModel();S.current.editor.setModelLanguage(V,a||n||"text"),S.current.editor.setModelLanguage(M,r||n||"text")},[n,a,r],O),Ut(()=>{S.current?.editor.setTheme(f)},[f],O),Ut(()=>{E.current?.updateOptions(d)},[d],O);let F=m.useCallback(()=>{if(!S.current)return;I.current(S.current);let V=Br(S.current,e||"",a||n||"text",o||""),M=Br(S.current,t||"",r||n||"text",s||"");E.current?.setModel({original:V,modified:M})},[n,t,r,e,a,o,s]),T=m.useCallback(()=>{!L.current&&y.current&&(E.current=S.current.editor.createDiffEditor(y.current,{automaticLayout:!0,...d}),F(),S.current?.editor.setTheme(f),k(!0),L.current=!0)},[d,f,F]);m.useEffect(()=>{O&&w.current(E.current,S.current)},[O]),m.useEffect(()=>{!C&&!O&&T()},[C,O,T]);function P(){let V=E.current?.getModel();i||V?.original?.disp Line truncated
p-3 rounded-lg border cursor-pointer transition-colors
${o?"border-blue-500 bg-blue-50 dark:bg-blue-900/20":"border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500"}
`,onClick:()=>n?.(r.id),children:c.jsxs(D,{className:"flex justify-between items-start",children:[c.jsxs(D,{className:"flex-1",children:[c.jsxs(Z,{className:"font-semibold text-gray-900 dark:text-gray-100",children:["버전 ",r.version]}),c.jsx(Z,{className:"ml-2 text-sm text-gray-500 dark:text-gray-400",children:a(r.created_at)})]}),c.jsxs(D,{className:"flex gap-3 text-sm",children:[c.jsxs(Z,{className:"text-green-600 dark:text-green-400",children:["+",r.changes_summary.added]}),c.jsxs(Z,{className:"text-red-600 dark:text-red-400",children:["-",r.changes_summary.removed]})]})]})},r.id)})})},Ah=({layoutId:e,versions:t,onRestore:n})=>{const[a,r]=m.useState(),o=l=>{r(l)},s=()=>{a!==void 0&&n(a)},i=a===void 0;return c.jsxs(D,{className:"space-y-4",role:"region","aria-label":"레이아웃 히스토리 패널",children:[c.jsx(D,{className:"border border-gray-300 dark:border-gray-600 rounded-lg p-4",children:c.jsx($l,{versions:t,selectedId:a,onSelect:o})}),c.jsx(D,{className:"flex justify-end",children:c.jsx(oe,{variant:"primary",disabled:i,onClick:s,"aria-label":"선택한 버전으로 복원",children:"복원"})})]})},Ih=({emailLabel:e="Email",passwordLabel:t="Password",submitButtonText:n="Sign In",processingText:a="Processing...",emailPlaceholder:r="Email",passwordPlaceholder:o="Password",forgotPasswordText:s="Forgot your password?",forgotPasswordUrl:i="/admin/password/reset",emailRequiredError:l="Please enter your email.",emailInvalidError:f="Please enter a valid email address.",passwordRequiredError:u="Please enter your password.",onSubmit:d,loadingActions:g={},isLoading:h=!1,disabled:b=!1,apiError:p="",className:x="",style:v})=>{const[O,k]=m.useState(""),[C,N]=m.useState(""),[E,S]=m.useState({}),y=p,w=Object.values(g).some(P=>P===!0),I=h||w,L=b||I,F=()=>{const P={},V=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return!O||O.trim()===""?P.email=l:V.test(O)||(P.email=f),(!C||C.trim()==="")&&(P.password=u),S(P),Object.keys(P).length===0},T=async P=>{if(!F()){P.preventDefault();return}S({}),d?await d(P):P.preventDefault()};return c.jsx(D,{className:`w-full ${x}`,style:v,children:c.jsxs(Do,{onSubmit:T,className:"space-y-6",noValidate:!0,children:[y&&c.jsx(D,{className:"p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800",children:c.jsx(ut,{className:"text-sm text-red-600 dark:text-red-400",children:y})}),c.jsxs(D,{children:[c.jsx($t,{htmlFor:"email",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:e}),c.jsx(gt,{id:"email",name:"email",type:"email",value:O,onChange:P=>k(P.target.value),placeholder:r,disabled:L,className:`
w-full px-4 py-3 rounded-lg border
${E.email?"border-red-500 focus:border-red-500 focus:ring-red-500":"border-gray-300 dark:border-gray-600 focus:border-blue-500 focus:ring-blue-500"}
bg-white dark:bg-gray-800
text-gray-900 dark:text-white
placeholder-gray-400 dark:placeholder-gray-500
focus:outline-none focus:ring-2
disabled:opacity-50 disabled:cursor-not-allowed
transition-colors duration-200
`}),E.email&&c.jsx(ut,{className:"mt-2 text-sm text-red-600 dark:text-red-400",children:E.email})]}),c.jsxs(D,{children:[c.jsx($t,{htmlFor:"password",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:t}),c.jsx(gt,{id:"password",name:"password",type:"password",value:C,onChange:P=>N(P.target.value),placeholder:o,disabled:L,className:`
w-full px-4 py-3 rounded-lg border
${E.password?"border-red-500 focus:border-red-500 focus:ring-red-500":"border-gray-300 dark:border-gray-600 focus:border-blue-500 focus:ring-blue-500"}
bg-white dark:bg-gray-800
text-gray-900 dark:text-white
placeholder-gray-400 dark:placeholder-gray-500
focus:outline-none focus:ring-2
disabled:opacity-50 disabled:cursor-not-allowed
transition-colors duration-200
`}),E.password&&c.jsx(ut,{className:"mt-2 text-sm text-red-600 dark:text-red-400",children:E.password})]}),i&&c.jsx(D,{className:"flex items-center justify-end",children:c.jsx(Hr,{href:i,className:"text-sm text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors duration-200",children:s})}),c.jsx(oe,{type:"submit",disabled:L,className:`
w-full px-4 py-3 rounded-lg font-medium
bg-blue-600 hover:bg-blue-700
dark:bg-blue-500 dark:hover:bg-blue-600
text-white
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
dark:focus:ring-offset-gray-900
disabled:opacity-50 disabled:cursor-not-allowed
transition-colors duration-200
flex items-center justify-center
`,children:I?c.jsxs(c.Fragment,{children:[c.jsxs(gr,{className:"animate-spin -ml-1 mr-3 h-5 w-5 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),a]}):n})]})})},Fl=e=>e==="auto"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e,ss=e=>{const t=Fl(e);document.documentElement.setAttribute("data-theme",t),t==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},Lh=()=>{const e=localStorage.getItem("g7_color_scheme");return e&&["auto","light","dark"].includes(e)?e:"auto"},Dh=({onThemeChange:e,className:t="",autoText:n="System",lightText:a="Light",darkText:r="Dark"})=>{const o=Lh(),[s,i]=m.useState(o),[l,f]=m.useState(!1),u=m.useRef(null);m.useEffect(()=>{ss(s)},[]),m.useEffect(()=>{if(s!=="auto")return;const h=window.matchMedia("(prefers-color-scheme: dark)"),b=()=>{ss("auto")};return h.addEventListener("change",b),()=>h.removeEventListener("change",b)},[s]),m.useEffect(()=>{const h=b=>{u.current&&!u.current.contains(b.target)&&f(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const d=h=>{i(h),localStorage.setItem("g7_color_scheme",h),ss(h),f(!1),e?.(h)},g=()=>Fl(s)==="dark"?de.Moon:de.Sun;return c.jsxs(D,{ref:u,className:`relative ${t}`,children:[c.jsx(oe,{onClick:()=>f(!l),className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors","aria-label":"Toggle theme",children:c.jsx(ne,{name:g(),className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),l&&c.jsx(D,{className:"absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50",children:c.jsxs(D,{className:"py-2",children:[c.jsxs(oe,{onClick:()=>d("auto"),className:`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${s==="auto"?"bg-gray-50 dark:bg-gray-700":""}
`,children:[c.jsx(ne,{name:de.Settings,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{className:"flex-1 text-left text-gray-900 dark:text-white",children:n}),s==="auto"&&c.jsx(ne,{name:de.Check,className:"w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"})]}),c.jsxs(oe,{onClick:()=>d("light"),className:`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${s==="light"?"bg-gray-50 dark:bg-gray-700":""}
`,children:[c.jsx(ne,{name:de.Sun,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{className:"flex-1 text-left text-gray-900 dark:text-white",children:a}),s==="light"&&c.jsx(ne,{name:de.Check,className:"w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"})]}),c.jsxs(oe,{onClick:()=>d("dark"),className:`
w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors
${s==="dark"?"bg-gray-50 dark:bg-gray-700":""}
`,children:[c.jsx(ne,{name:de.Moon,className:"w-5 h-5 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{className:"flex-1 text-left text-gray-900 dark:text-white",children:r}),s==="dark"&&c.jsx(ne,{name:de.Check,className:"w-4 h-4 text-blue-600 dark:text-blue-400 ml-auto"})]})]})})]})},Ul=window.G7Core?.createLogger?.("Comp:ColumnSelector")??{log:(...e)=>console.log("[Comp:ColumnSelector]",...e),warn:(...e)=>console.warn("[Comp:ColumnSelector]",...e),error:(...e)=>console.error("[Comp:ColumnSelector]",...e)},Vl=(e,t)=>window.G7Core?.t?.(e,t)??e,_h=()=>window.G7Core,Ph=({id:e,columns:t,visibleColumns:n,onColumnVisibilityChange:a,triggerLabel:r,triggerIconName:o=de.Sliders,position:s="right",className:i="",style:l,requiredText:f,menuTitle:u,menuDescription:d,defaultColumns:g,triggerClassName:h,labelClassName:b,dynamicColumns:p,dynamicColumnsInsertAfter:x})=>{const v=r??Vl("common.column_selector"),O=f??Vl("common.required"),k=m.useMemo(()=>{if(!p||!Array.isArray(p)||p.length===0)return t;if(x){const z=t.findIndex($=>$.field===x);if(z!==-1)return[...t.slice(0,z+1),...p,...t.slice(z+1)]}return[...t,...p]},[t,p,x]),[C,N]=m.useState(!1),E=m.useRef(null),S=m.useRef(null),[y,w]=m.useState(!1),[I,L]=m.useState(s),F=m.useMemo(()=>{try{const z=window.G7Core?.AuthManager?.getInstance();return z?z.getUser()?.uuid:void 0}catch{return}},[]),T=e?`g7_columns_${e}${F!==void 0?`_${F}`:""}`:null,P=()=>{if(!T)return null;try{const z=localStorage.getItem(T);if(z){const $=JSON.parse(z);if(Array.isArray($)&&$.length>0)return $}}catch(z){Ul.warn("Failed to load from localStorage:",z)}return null},V=z=>{if(T)try{localStorage.setItem(T,JSON.stringify(z))}catch($){Ul.warn("Failed to save to localStorage:",$)}},M=()=>{const z=P();return z||(n&&n.length>0?n:g&&g.length>0?g:k.filter($=>$.visible!==!1).map($=>$.field))},[A,j]=m.useState(M);m.useEffect(()=>{y||(a&&A.length>0&&a(A),w(!0))},[y,a,A]),m.useEffect(()=>{y&&n&&n.length>0&&(P()||j(n))},[n,y]);const U=m.useRef([]),Y=m.useRef(null);m.useEffect(()=>{if(y&&p&&p.length>0){const z=p.map(J=>J.field);if(Y.current===null){const J=P();if(Y.current=J!==null,J!==null){U.current=z;return}}const $=U.current,q=z.filter(J=>!$.includes(J));if(q.length>0){const J=n&&n.length>0?n:A,R=q.filter(ee=>!J.includes(ee));if(R.length>0){const ee=[...J,...R];j(ee),V(ee),a?.(ee)}}U.current=z}},[p,y]);const G=n&&n.length>0?n:A;m.useEffect(()=>{const z=$=>{E.current&&!E.current.contains($.target)&&N(!1)};return C&&document.addEventListener("mousedown",z),()=>{document.removeEventListener("mousedown",z)}},[C]),m.useEffect(()=>{if(C&&S.current&&E.current){const z=S.current.getBoundingClientRect(),$=E.current.getBoundingClientRect(),q=window.innerWidth,J=z.width||256;s==="right"?$.right-J<0?L("left"):L("right"):$.left+J>q?L("right"):L("left")}},[C,s]);const H=z=>{if(k.find(J=>J.field===z)?.required)return;const q=G.includes(z)?G.filter(J=>J!==z):[...G,z];j(q),V(q),a?.(q)},B=I==="left"?"left-0":"right-0";return c.jsxs(D,{ref:E,className:`relative inline-block ${i}`,style:l,children:[c.jsxs(oe,{onClick:()=>N(!C),className:_h()?.style?.mergeClasses?.("flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",h)??`flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors ${h??""}`,children:[c.jsx(ne,{name:o,className:"w-5 h-5"}),v&&c.jsx(Z,{className:`${b||"hidden sm:inline"} text-sm`,children:v})]}),C&&c.jsxs(D,{ref:S,className:`absolute ${B} z-50 mt-2 w-64 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg`,children:[(u||d)&&c.jsxs(D,{className:"px-4 pt-3 pb-2 border-b border-gray-200 dark:border-gray-700",children:[u&&c.jsx(Z,{className:"block text-sm font-medium text-gray-900 dark:text-white",children:u}),d&&c.jsx(Z,{className:"block text-xs text-gray-500 dark:text-gray-400 mt-1",children:d})]}),c.jsx(D,{className:"p-2 max-h-64 overflow-y-auto",children:k.map(z=>{const $=G.includes(z.field),q=z.required===!0;return c.jsxs(D,{onClick:()=>!q&&H(z.field),className:`flex items-center gap-2 px-3 py-2 rounded hover:bg-gray-50 dark:hover:bg-gray-700 ${q?"cursor-default":"cursor-pointer"}`,children:[c.jsx(Xt,{checked:$,disabled:q,readOnly:!0,className:"h-4 w-4 text-blue-600 rounded border-gray-300 dark:border-gray-600 pointer-events-none"}),c.jsx(Z,{className:"text-sm text-gray-700 dark:text-gray-300",children:z.header}),q&&O&&c.jsx(Z,{className:"ml-auto text-xs text-gray-400 dark:text-gray-500",children:O})]},z.field)})})]})]})},$h=window.G7Core?.createLogger?.("Comp:PageTransition")??{log:(...e)=>console.log("[Comp:PageTransition]",...e),warn:(...e)=>console.warn("[Comp:PageTransition]",...e),error:(...e)=>console.error("[Comp:PageTransition]",...e)},Fh=({className:e="",style:t})=>{const[n,a]=m.useState(!1);return m.useEffect(()=>{const r=window.G7Core?.Trans Line truncated
@keyframes loading {
0% {
transform: translateX(-100%);
}
50% {
transform: translateX(300%);
}
100% {
transform: translateX(-100%);
}
}
`})]}):null};function Or(e){"@babel/helpers - typeof";return Or=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Or(e)}function Uh(e,t){if(Or(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(Or(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Hl(e){var t=Uh(e,"string");return Or(t)=="symbol"?t:t+""}function Tn(e,t,n){return(t=Hl(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jl(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,a)}return n}function Ee(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?jl(Object(n),!0).forEach(function(a){Tn(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jl(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}function Vh(e){if(Array.isArray(e))return e}function Hh(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var a,r,o,s,i=[],l=!0,f=!1;try{if(o=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;l=!1}else for(;!(l=(a=o.call(n)).done)&&(i.push(a.value),i.length!==t);l=!0);}catch(u){f=!0,r=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(f)throw r}}return i}}function is(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,a=Array(t);n<t;n++)a[n]=e[n];return a}function zl(e,t){if(e){if(typeof e=="string")return is(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?is(e,t):void 0}}function jh(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hr(e,t){return Vh(e)||Hh(e,t)||zl(e,t)||jh()}function zh(e,t){if(e==null)return{};var n={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.indexOf(a)!==-1)continue;n[a]=e[a]}return n}function or(e,t){if(e==null)return{};var n,a,r=zh(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}var Gh=["defaultInputValue","defaultMenuIsOpen","defaultValue","inputValue","menuIsOpen","onChange","onInputChange","onMenuClose","onMenuOpen","value"];function Gl(e){var t=e.defaultInputValue,n=t===void 0?"":t,a=e.defaultMenuIsOpen,r=a===void 0?!1:a,o=e.defaultValue,s=o===void 0?null:o,i=e.inputValue,l=e.menuIsOpen,f=e.onChange,u=e.onInputChange,d=e.onMenuClose,g=e.onMenuOpen,h=e.value,b=or(e,Gh),p=m.useState(i!==void 0?i:n),x=hr(p,2),v=x[0],O=x[1],k=m.useState(l!==void 0?l:r),C=hr(k,2),N=C[0],E=C[1],S=m.useState(h!==void 0?h:s),y=hr(S,2),w=y[0],I=y[1],L=m.useCallback(function(j,U){typeof f=="function"&&f(j,U),I(j)},[f]),F=m.useCallback(function(j,U){var Y;typeof u=="function"&&(Y=u(j,U)),O(Y!==void 0?Y:j)},[u]),T=m.useCallback(function(){typeof g=="function"&&g(),E(!0)},[g]),P=m.useCallback(function(){typeof d=="function"&&d(),E(!1)},[d]),V=i!==void 0?i:v,M=l!==void 0?l:N,A=h!==void 0?h:w;return Ee(Ee({},b),{},{inputValue:V,menuIsOpen:M,onChange:L,onInputChange:F,onMenuClose:P,onMenuOpen:T,value:A})}function Me(){return Me=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)({}).hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},Me.apply(null,arguments)}function Bh(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Bl(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,Hl(a.key),a)}}function Wh(e,t,n){return t&&Bl(e.prototype,t),n&&Bl(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function ls(e,t){return ls=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},ls(e,t)}function Yh(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ls(e,t)}function Ca(e){return Ca=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Ca(e)}function Wl(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Wl=function(){return!!e})()}function qh(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Kh(e,t){if(t&&(Or(t)=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return qh(e)}function Xh(e){var t=Wl();return function(){var n,a=Ca(e);if(t){var r=Ca(this).constructor;n=Reflect.construct(a,arguments,r)}else n=a.apply(this,arguments);return Kh(this,n)}}function Zh(e){if(Array.isArray(e))return is(e)}function Qh(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Jh(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Wr(e){return Zh(e)||Qh(e)||zl(e)||Jh()}function Rh(e){if(e.sheet)return e.sheet;for(var t=0;t<document.styleSheets.length;t++)if(document.styleSheets[t].ownerNode===e)return document.styleSheets[t]}function ep(e){var t=document.createElement("style");return t.setAttribute("data-emotion",e.key),e.nonce!==void 0&&t.setAttribute("nonce",e.nonce),t.appendChild(document.createTextNode("")),t.setAttribute("data-s",""),t}var tp=(function(){function e(n){var a=this;this._insertTag=function(r){var o;a.tags.length===0?a.insertionPoint?o=a.insertionPoint.nextSibling:a.prepend?o=a.container.firstChild:o=a.before:o=a.tags[a.tags.length-1].nextSibling,a.container.insertBefore(r,o),a.tags.push(r)},this.isSpeedy=n.speedy===void 0?!0:n.speedy,this.tags=[],this.ctr=0,this.nonce=n.nonce,this.key=n.key,this.container=n.container,this.prepend=n.prepend,this.insertionPoint=n.insertionPoint,this.before=null}var t=e.prototype;return t.hydrate=function(a){a.forEach(this._insertTag)},t.insert=function(a){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(ep(this));var r=this.tags[this.tags.length-1];if(this.isSpeedy){var o=Rh(r);try{o.insertRule(a,o.cssRules.length)}catch{}}else r.appendChild(document.createTextNode(a));this.ctr++},t.flush=function(){this.tags.forEach(function(a){var r;return(r=a.parentNode)==null?void 0:r.removeChild(a)}),this.tags=[],this.ctr=0},e})(),kt="-ms-",Sa="-moz-",Ke="-webkit-",Yl="comm",cs="rule",us="decl",rp="@import",ql="@keyframes",np="@layer",ap=Math.abs,Ea=String.fromCharCode,op=Object.assign;function sp(e,t){return yt(e,0)^45?(((t<<2^yt(e,0))<<2^yt(e,1))<<2^yt(e,2))<<2^yt(e,3):0}function Kl(e){return e.trim()}function ip(e,t){return(e=t.exec(e))?e[0]:e}function Xe(e,t,n){return e.replace(t,n)}function ds(e,t){return e.indexOf(t)}function yt(e,t){return e.charCodeAt(t)|0}function An(e,t,n){return e.slice(t,n)}function sr(e){return e.length}function fs(e){return e.length}function Na(e,t){return t.push(e),e}function lp(e,t){return e.map(t).join("")}var Oa=1,Yr=1,Xl=0,Dt=0,dt=0,qr="";function Ma(e,t,n,a,r,o,s){return{value:e,root:t,parent:n,type:a,props:r,children:o,line:Oa,column:Yr,length:s,return:""}}function In(e,t){return op(Ma("",null,null,"",null,null,0),e,{length:-e.length},t)}function cp(){return dt}function up(){return dt=Dt>0?yt(qr,--Dt):0,Yr--,dt===10&&(Yr=1,Oa--),dt}function Vt(){return dt=Dt<Xl?yt(qr,Dt++):0,Yr++,dt===10&&(Yr=1,Oa++),dt}function ir(){return yt(qr,Dt)}function Ta(){return Dt}function Ln(e,t){return An(qr,e,t)}function Dn(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function Zl(e){return Oa=Yr=1,Xl=sr(qr=e),Dt=0,[]}function Ql(e){return qr="",e}function Aa(e){return Kl(Ln(Dt-1,gs(e===91?e+2:e===40?e+1:e)))}function dp(e){for(;(dt=ir())&&dt<33;)Vt();return Dn(e)>2||Dn(dt)>3?"":" "}function fp(e,t){for(;--t&&Vt()&&!(dt<48||dt>102||dt>57&&dt<65||dt>70&&dt<97););return Ln(e,Ta()+(t<6&&ir()==32&&Vt()==32))}function gs(e){for(;Vt();)switch(dt){case e:return Dt;case 34:case 39:e!==34&&e!==39&&gs(dt);break;case 40:e===41&&gs(e);break;case 92:Vt();break}return Dt}function gp(e,t){for(;Vt()&&e+dt!==57;)if(e+dt===84&&ir()===47)break;return"/*"+Ln(t,Dt-1)+"*"+Ea(e===47?e:Vt())}function hp(e){for(;!Dn(ir());)Vt();return Ln(e,Dt)}function pp(e){return Ql(Ia("",null,null,null,[""],e=Zl(e),0,[0],e))}function Ia(e,t,n,a,r,o,s,i,l){for(var f=0,u=0,d=s,g=0,h=0,b=0,p=1,x=1,v=1,O=0,k="",C=r,N=o,E=a,S=k;x;)switch(b=O,O=Vt()){case 40:if(b!=108&&yt(S,d-1)==58){ds(S+=Xe(Aa(O),"&","&\f"),"&\f")!=-1&&(v=-1);break}case 34:case 39:case 91:S+=Aa(O);break;case 9:case 10:case 13:case 32:S+=dp(b);break;case 92:S+=fp(Ta()-1,7);continue;case 47:switch(ir()){case 42:case 47:Na(bp(gp(Vt(),Ta()),t,n),l);break;default:S+="/"}break;case 123*p:i[f++]=sr(S)*v;case 125*p:case 59:case 0:switch(O){case 0:case 125:x=0;case 59+u:v==-1&&(S=Xe(S,/\f/g,"")),h>0&&sr(S)-d&&Na(h>32?Rl(S+";",a,n,d-1):Rl(Xe(S," ","")+";",a,n,d-2),l);break;case 59:S+=";";default:if(Na(E=Jl(S,t,n,f,u,r,i,k,C=[],N=[],d),o),O===123)if(u===0)Ia(S,t,E,E,C,o,d,i,N);else switch(g===99&&yt(S,3)===110?100:g){case 100:case 108:case 109:case 115:Ia(e,E,E,a&&Na(Jl(e,E,E,0,0,r,i,k,r,C=[],d),N),r,N,d,i,a?C:N);break;default:Ia(S,E,E,E,[""],N,0,i,N)}}f=u=h=0,p=v=1,k=S="",d=s;break;case 58:d=1+sr(S),h=b;default:if(p<1){if(O==123)--p;else if(O==125&&p++==0&&up()==125)continue}switch(S+=Ea(O),O*p){case 38:v=u>0?1:(S+="\f",-1);break;case 44:i[f++]=(sr(S)-1)*v,v=1;break;case 64:ir()===45&&(S+=Aa(Vt())),g=ir(),u=d=sr(k=S+=hp(Ta())),O++;break;case 45:b===45&&sr(S)==2&&(p=0)}}return o}function Jl(e,t,n,a,r,o,s,i,l,f,u){for(var d=r-1,g=r===0?o:[""],h=fs(g),b=0,p=0,x=0;b<a;++b)for(var v=0,O=An(e,d+1,d=ap(p=s[b])),k=e;v<h;++v)(k=Kl(p>0?g[v]+" "+O:Xe(O,/&\f/g,g[v])))&&(l[x++]=k);retu Line truncated
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var rc;function Tp(){if(rc)return Je;rc=1;var e=typeof Symbol=="function"&&Symbol.for,t=e?Symbol.for("react.element"):60103,n=e?Symbol.for("react.portal"):60106,a=e?Symbol.for("react.fragment"):60107,r=e?Symbol.for("react.strict_mode"):60108,o=e?Symbol.for("react.profiler"):60114,s=e?Symbol.for("react.provider"):60109,i=e?Symbol.for("react.context"):60110,l=e?Symbol.for("react.async_mode"):60111,f=e?Symbol.for("react.concurrent_mode"):60111,u=e?Symbol.for("react.forward_ref"):60112,d=e?Symbol.for("react.suspense"):60113,g=e?Symbol.for("react.suspense_list"):60120,h=e?Symbol.for("react.memo"):60115,b=e?Symbol.for("react.lazy"):60116,p=e?Symbol.for("react.block"):60121,x=e?Symbol.for("react.fundamental"):60117,v=e?Symbol.for("react.responder"):60118,O=e?Symbol.for("react.scope"):60119;function k(N){if(typeof N=="object"&&N!==null){var E=N.$$typeof;switch(E){case t:switch(N=N.type,N){case l:case f:case a:case o:case r:case d:return N;default:switch(N=N&&N.$$typeof,N){case i:case u:case b:case h:case s:return N;default:return E}}case n:return E}}}function C(N){return k(N)===f}return Je.AsyncMode=l,Je.ConcurrentMode=f,Je.ContextConsumer=i,Je.ContextProvider=s,Je.Element=t,Je.ForwardRef=u,Je.Fragment=a,Je.Lazy=b,Je.Memo=h,Je.Portal=n,Je.Profiler=o,Je.StrictMode=r,Je.Suspense=d,Je.isAsyncMode=function(N){return C(N)||k(N)===l},Je.isConcurrentMode=C,Je.isContextConsumer=function(N){return k(N)===i},Je.isContextProvider=function(N){return k(N)===s},Je.isElement=function(N){return typeof N=="object"&&N!==null&&N.$$typeof===t},Je.isForwardRef=function(N){return k(N)===u},Je.isFragment=function(N){return k(N)===a},Je.isLazy=function(N){return k(N)===b},Je.isMemo=function(N){return k(N)===h},Je.isPortal=function(N){return k(N)===n},Je.isProfiler=function(N){return k(N)===o},Je.isStrictMode=function(N){return k(N)===r},Je.isSuspense=function(N){return k(N)===d},Je.isValidElementType=function(N){return typeof N=="string"||typeof N=="function"||N===a||N===f||N===o||N===r||N===d||N===g||typeof N=="object"&&N!==null&&(N.$$typeof===b||N.$$typeof===h||N.$$typeof===s||N.$$typeof===i||N.$$typeof===u||N.$$typeof===x||N.$$typeof===v||N.$$typeof===O||N.$$typeof===p)},Je.typeOf=k,Je}var nc;function Ap(){return nc||(nc=1,hs.exports=Tp()),hs.exports}var ps,ac;function Ip(){if(ac)return ps;ac=1;var e=Ap(),t={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},a={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},r={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},o={};o[e.ForwardRef]=a,o[e.Memo]=r;function s(b){return e.isMemo(b)?r:o[b.$$typeof]||t}var i=Object.defineProperty,l=Object.getOwnPropertyNames,f=Object.getOwnPropertySymbols,u=Object.getOwnPropertyDescriptor,d=Object.getPrototypeOf,g=Object.prototype;function h(b,p,x){if(typeof p!="string"){if(g){var v=d(p);v&&v!==g&&h(b,v,x)}var O=l(p);f&&(O=O.concat(f(p)));for(var k=s(b),C=s(p),N=0;N<O.length;++N){var E=O[N];if(!n[E]&&!(x&&x[E])&&!(C&&C[E])&&!(k&&k[E])){var S=u(p,E);try{i(b,E,S)}catch{}}}}return b}return ps=h,ps}Ip();var Lp=!0;function Dp(e,t,n){var a="";return n.split(" ").forEach(function(r){e[r]!==void 0?t.push(e[r]+";"):r&&(a+=r+" ")}),a}var oc=function(t,n,a){var r=t.key+"-"+n.name;(a===!1||Lp===!1)&&t.registered[r]===void 0&&(t.registered[r]=n.styles)},_p=function(t,n,a){oc(t,n,a);var r=t.key+"-"+n.name;if(t.inserted[n.name]===void 0){var o=n;do t.insert(n===o?"."+r:"",o,t.sheet,!0),o=o.next;while(o!==void 0)}};function Pp(e){for(var t=0,n,a=0,r=e.length;r>=4;++a,r-=4)n=e.charCodeAt(a)&255|(e.charCodeAt(++a)&255)<<8|(e.charCodeAt(++a)&255)<<16|(e.charCodeAt(++a)&255)<<24,n=(n&65535)*1540483477+((n>>>16)*59797<<16),n^=n>>>24,t=(n&65535)*1540483477+((n>>>16)*59797<<16)^(t&65535)*1540483477+((t>>>16)*59797<<16);switch(r){case 3:t^=(e.charCodeAt(a+2)&255)<<16;case 2:t^=(e.charCodeAt(a+1)&255)<<8;case 1:t^=e.charCodeAt(a)&255,t=(t&65535)*1540483477+((t>>>16)*59797<<16)}return t^=t>>>13,t=(t&65535)*1540483477+((t>>>16)*59797<<16),((t^t>>>15)>>>0).toString(36)}var $p={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},Fp=/[A-Z]|^ms/g,Up=/_EMO_([^_]+?)_([^]*?)_EMO_/g,sc=function(t){return t.charCodeAt(1)===45},ic=functioLine truncated
0%, 80%, 100% { opacity: 0; }
40% { opacity: 1; }
`]))),nm=function(t,n){var a=t.isFocused,r=t.size,o=t.theme,s=o.colors,i=o.spacing.baseUnit;return Ee({label:"loadingIndicator",display:"flex",transition:"color 150ms",alignSelf:"center",fontSize:r,lineHeight:1,marginRight:r,textAlign:"center",verticalAlign:"middle"},n?{}:{color:a?s.neutral60:s.neutral20,padding:i*2})},Ns=function(t){var n=t.delay,a=t.offset;return Se("span",{css:ys({animation:"".concat(rm," 1s ease-in-out ").concat(n,"ms infinite;"),backgroundColor:"currentColor",borderRadius:"1em",display:"inline-block",marginLeft:a?"1em":void 0,height:"1em",verticalAlign:"top",width:"1em"},"","")})},am=function(t){var n=t.innerProps,a=t.isRtl,r=t.size,o=r===void 0?4:r,s=or(t,Kb);return Se("div",Me({},ct(Ee(Ee({},s),{},{innerProps:n,isRtl:a,size:o}),"loadingIndicator",{indicator:!0,"loading-indicator":!0}),n),Se(Ns,{delay:0,offset:a}),Se(Ns,{delay:160,offset:!0}),Se(Ns,{delay:320,offset:!a}))},om=function(t,n){var a=t.isDisabled,r=t.isFocused,o=t.theme,s=o.colors,i=o.borderRadius,l=o.spacing;return Ee({label:"control",alignItems:"center",cursor:"default",display:"flex",flexWrap:"wrap",justifyContent:"space-between",minHeight:l.controlHeight,outline:"0 !important",position:"relative",transition:"all 100ms"},n?{}:{backgroundColor:a?s.neutral5:s.neutral0,borderColor:a?s.neutral10:r?s.primary:s.neutral20,borderRadius:i,borderStyle:"solid",borderWidth:1,boxShadow:r?"0 0 0 1px ".concat(s.primary):void 0,"&:hover":{borderColor:r?s.primary:s.neutral30}})},sm=function(t){var n=t.children,a=t.isDisabled,r=t.isFocused,o=t.innerRef,s=t.innerProps,i=t.menuIsOpen;return Se("div",Me({ref:o},ct(t,"control",{control:!0,"control--is-disabled":a,"control--is-focused":r,"control--menu-is-open":i}),s,{"aria-disabled":a||void 0}),n)},im=sm,lm=["data"],cm=function(t,n){var a=t.theme.spacing;return n?{}:{paddingBottom:a.baseUnit*2,paddingTop:a.baseUnit*2}},um=function(t){var n=t.children,a=t.cx,r=t.getStyles,o=t.getClassNames,s=t.Heading,i=t.headingProps,l=t.innerProps,f=t.label,u=t.theme,d=t.selectProps;return Se("div",Me({},ct(t,"group",{group:!0}),l),Se(s,Me({},i,{selectProps:d,theme:u,getStyles:r,getClassNames:o,cx:a}),f),Se("div",null,n))},dm=function(t,n){var a=t.theme,r=a.colors,o=a.spacing;return Ee({label:"group",cursor:"default",display:"block"},n?{}:{color:r.neutral40,fontSize:"75%",fontWeight:500,marginBottom:"0.25em",paddingLeft:o.baseUnit*3,paddingRight:o.baseUnit*3,textTransform:"uppercase"})},fm=function(t){var n=wc(t);n.data;var a=or(n,lm);return Se("div",Me({},ct(t,"groupHeading",{"group-heading":!0}),a))},gm=um,hm=["innerRef","isDisabled","isHidden","inputClassName"],pm=function(t,n){var a=t.isDisabled,r=t.value,o=t.theme,s=o.spacing,i=o.colors;return Ee(Ee({visibility:a?"hidden":"visible",transform:r?"translateZ(0)":""},bm),n?{}:{margin:s.baseUnit/2,paddingBottom:s.baseUnit/2,paddingTop:s.baseUnit/2,color:i.neutral80})},Dc={gridArea:"1 / 2",font:"inherit",minWidth:"2px",border:0,margin:0,outline:0,padding:0},bm={flex:"1 1 auto",display:"inline-grid",gridArea:"1 / 1 / 2 / 3",gridTemplateColumns:"0 min-content","&:after":Ee({content:'attr(data-value) " "',visibility:"hidden",whiteSpace:"pre"},Dc)},mm=function(t){return Ee({label:"input",color:"inherit",background:0,opacity:t?0:1,width:"100%"},Dc)},vm=function(t){var n=t.cx,a=t.value,r=wc(t),o=r.innerRef,s=r.isDisabled,i=r.isHidden,l=r.inputClassName,f=or(r,hm);return Se("div",Me({},ct(t,"input",{"input-container":!0}),{"data-value":a||""}),Se("input",Me({className:n({input:!0},l),ref:o,style:mm(i),disabled:s},f)))},ym=vm,xm=function(t,n){var a=t.theme,r=a.spacing,o=a.borderRadius,s=a.colors;return Ee({label:"multiValue",display:"flex",minWidth:0},n?{}:{backgroundColor:s.neutral10,borderRadius:o/2,margin:r.baseUnit/2})},wm=function(t,n){var a=t.theme,r=a.borderRadius,o=a.colors,s=t.cropWithEllipsis;return Ee({overflow:"hidden",textOverflow:s||s===void 0?"ellipsis":void 0,whiteSpace:"nowrap"},n?{}:{borderRadius:r/2,color:o.neutral80,fontSize:"85%",padding:3,paddingLeft:6})},km=function(t,n){var a=t.theme,r=a.spacing,o=a.borderRadius,s=a.colors,i=t.isFocused;return Ee({alignItems:"center",display:"flex"},n?{}:{borderRadius:o/2,backgroundColor:i?s.dangerLight:void 0,paddingLeft:r.baseUnit,paddingRight:r.baseUnit,":hover":{backgroundColor:s.dangerLight,color:s.danger}})},_c=function(t){var n=t.children,a=t.innerProps;return Se("div",a,n)},Cm=_c,Sm=_c;function Em(e){var t=e.children,n=e.innerProps;return Se("div",Me({role:"button"},n),t||Se(Es,{size:14}))}var Nm=function(t){var n=t.children,a=t.components,r=t.data,o=t.innerProps,s=t.isDisabled,i=t.removeProps,l=t.selectProps,f=a.Container,u=a.Label,d=a.Remove;return Se(f,{data:r,innerProps:Ee(Ee({},ct(t,"multiValue",{"multi-value":!0,"multi-value--is-disabled":s})),o),selectProps:l},Se(u,{data:r,innerProps:Ee({},ct(t,"multiValueLabel",{"multi-value__label":!0})),selectProps:l},n),Se(d,{data:r,innerProps:Ee(Ee({},ct(t,"multiValueRemove",{"multi-value__remove":!0})),{},{"aria-label":"Remove ".concat(n||"option")},i),s Line truncated
px-4 py-2.5 bg-gray-100 dark:bg-gray-700
border-0 rounded-xl
text-gray-700 dark:text-gray-200 font-medium
focus:ring-2 focus:ring-blue-500 focus:outline-none
flex items-center justify-between gap-2
text-left cursor-pointer
disabled:opacity-50 disabled:cursor-not-allowed
min-w-[200px]
`,"aria-haspopup":"listbox","aria-expanded":g,children:[c.jsxs(D,{className:"flex items-center gap-2",children:[f,c.jsx(Z,{className:"truncate",children:N})]}),c.jsx(gr,{className:`w-4 h-4 flex-shrink-0 transition-transform duration-200 ${g?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),g&&c.jsxs(D,{className:"absolute z-50 w-full mt-2 bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 overflow-hidden min-w-[280px]",role:"listbox",children:[c.jsx(D,{className:"p-3 border-b border-gray-200 dark:border-gray-700",children:c.jsx("input",{id:O,type:"text",value:b,onChange:S,placeholder:r,className:"w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none"})}),c.jsxs(D,{className:"max-h-80 overflow-auto",children:[I&&c.jsx(D,{className:"px-4 py-6 text-center text-gray-500 dark:text-gray-400",children:i}),L&&c.jsx(D,{className:"px-4 py-6 text-center text-gray-500 dark:text-gray-400",children:s}),F&&c.jsx(D,{className:"py-2",children:C.map(T=>{const P=w(T.value);return c.jsxs(oe,{type:"button",onClick:()=>!T.disabled&&y(T.value),disabled:T.disabled,className:`
w-full px-4 py-3 text-left
flex items-start gap-3
hover:bg-gray-100 dark:hover:bg-gray-700
transition-colors
${T.disabled?"opacity-50 cursor-not-allowed":"cursor-pointer"}
`,role:"option","aria-selected":P,children:[c.jsx(D,{className:"w-5 h-5 flex-shrink-0 mt-0.5",children:P&&c.jsx(gr,{className:"w-5 h-5 text-blue-600 dark:text-blue-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),c.jsxs(D,{className:"flex-1 min-w-0",children:[c.jsx(D,{className:`font-medium ${P?"text-blue-600 dark:text-blue-400":"text-gray-900 dark:text-white"}`,children:T.label}),T.description&&c.jsx(D,{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:T.description})]})]},T.value)})})]})]})]})},Fn={container:{base:"tag-select",disabled:"opacity-50 cursor-not-allowed"},tag:"tag",tagRemove:"tag-remove",placeholder:"tag-select-placeholder"},_v=({options:e=[],value:t=[],onChange:n,placeholder:a="No items selected",disabled:r=!1,className:o=""})=>{const s=m.useCallback(u=>e.find(g=>String(g.value)===String(u))?.label||String(u),[e]),i=m.useCallback(u=>{if(r)return;const d=t.filter(g=>String(g)!==String(u));n?.(d)},[t,n,r]),l=m.useMemo(()=>t.map(u=>({value:u,label:s(u)})),[t,s]),f=`${Fn.container.base} ${r?Fn.container.disabled:""} ${o}`.trim();return c.jsx(D,{className:f,children:l.length===0?c.jsx(Z,{className:Fn.placeholder,children:a}):l.map(u=>c.jsxs(Z,{className:Fn.tag,children:[u.label,!r&&c.jsx(Z,{className:Fn.tagRemove,onClick:()=>i(u.value),role:"button","aria-label":`Remove ${u.label}`,children:c.jsx(gr,{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},u.value))})};function Pv(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return m.useMemo(()=>a=>{t.forEach(r=>r(a))},t)}const Ya=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Qr(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Fs(e){return"nodeType"in e}function Mt(e){var t,n;return e?Qr(e)?e:Fs(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Us(e){const{Document:t}=Mt(e);return e instanceof t}function Un(e){return Qr(e)?!1:e instanceof Mt(e).HTMLElement}function gu(e){return e instanceof Mt(e).SVGElement}function Jr(e){return e?Qr(e)?e.document:Fs(e)?Us(e)?e:Un(e)||gu(e)?e.ownerDocument:document:document:document}const Qt=Ya?m.useLayoutEffect:m.useEffect;function qa(e){const t=m.useRef(e);return Qt(()=>{t.current=e}),m.useCallback(function(){for(var n=arguments.length,a=new Array(n),r=0;r<n;r++)a[r]=arguments[r];return t.current==null?void 0:t.current(...a)},[])}function $v(){const e=m.useRef(null),t=m.useCallback((a,r)=>{e.current=setInterval(a,r)},[]),n=m.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Vn(e,t){t===void 0&&(t=[e]);const n=m.useRef(e);return Qt(()=>{n.current!==e&&(n.current=e)},t),n}function Hn(e,t){const n=m.useRef();return m.useMemo(()=>{const a=e(n.current);return n.current=a,a},[...t])}function Ka(e){const t=qa(e),n=m.useRef(null),a=m.useCallback(r=>{r!==n.current&&t?.(r,n.current),n.current=r},[]);return[n,a]}function Xa(e){const t=m.useRef();return m.useEffect(()=>{t.current=e},[e]),t.current}let Vs={};function jn(e,t){return m.useMemo(()=>{if(t)return t;const n=Vs[e]==null?0:Vs[e]+1;return Vs[e]=n,e+"-"+n},[e,t])}function hu(e){return function(t){for(var n=arguments.length,a=new Array(n>1?n-1:0),r=1;r<n;r++)a[r-1]=arguments[r];return a.reduce((o,s)=>{const i=Object.entries(s);for(const[l,f]of i){const u=o[l];u!=null&&(o[l]=u+e*f)}return o},{...t})}}const Rr=hu(1),zn=hu(-1);function Fv(e){return"clientX"in e&&"clientY"in e}function Za(e){if(!e)return!1;const{KeyboardEvent:t}=Mt(e.target);return t&&e instanceof t}function Uv(e){if(!e)return!1;const{TouchEvent:t}=Mt(e.target);return t&&e instanceof t}function Qa(e){if(Uv(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return Fv(e)?{x:e.clientX,y:e.clientY}:null}const cr=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[cr.Translate.toString(e),cr.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:a}=e;return t+" "+n+"ms "+a}}}),pu="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Vv(e){return e.matches(pu)?e:e.querySelector(pu)}const Hv={display:"none"};function jv(e){let{id:t,value:n}=e;return m.createElement("div",{id:t,style:Hv},n)}function zv(e){le Line truncated
To pick up a draggable item, press the space bar.
While dragging, use the arrow keys to move the item.
Press space again to drop the item in its new position, or press escape to cancel.
`},qv={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function Kv(e){let{announcements:t=qv,container:n,hiddenTextDescribedById:a,screenReaderInstructions:r=Yv}=e;const{announce:o,announcement:s}=Gv(),i=jn("DndLiveRegion"),[l,f]=m.useState(!1);if(m.useEffect(()=>{f(!0)},[]),Bv(m.useMemo(()=>({onDragStart(d){let{active:g}=d;o(t.onDragStart({active:g}))},onDragMove(d){let{active:g,over:h}=d;t.onDragMove&&o(t.onDragMove({active:g,over:h}))},onDragOver(d){let{active:g,over:h}=d;o(t.onDragOver({active:g,over:h}))},onDragEnd(d){let{active:g,over:h}=d;o(t.onDragEnd({active:g,over:h}))},onDragCancel(d){let{active:g,over:h}=d;o(t.onDragCancel({active:g,over:h}))}}),[o,t])),!l)return null;const u=m.createElement(m.Fragment,null,m.createElement(jv,{id:a,value:r.draggable}),m.createElement(zv,{id:i,announcement:s}));return n?fr.createPortal(u,n):u}var ft;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ft||(ft={}));function Ja(){}function en(e,t){return m.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Hs(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return m.useMemo(()=>[...t].filter(a=>a!=null),[...t])}const Jt=Object.freeze({x:0,y:0});function mu(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function Xv(e,t){const n=Qa(e);if(!n)return"0 0";const a={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return a.x+"% "+a.y+"%"}function vu(e,t){let{data:{value:n}}=e,{data:{value:a}}=t;return n-a}function Zv(e,t){let{data:{value:n}}=e,{data:{value:a}}=t;return a-n}function yu(e){let{left:t,top:n,height:a,width:r}=e;return[{x:t,y:n},{x:t+r,y:n},{x:t,y:n+a},{x:t+r,y:n+a}]}function xu(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function wu(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}const js=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:a}=e;const r=wu(t,t.left,t.top),o=[];for(const s of a){const{id:i}=s,l=n.get(i);if(l){const f=mu(wu(l),r);o.push({id:i,data:{droppableContainer:s,value:f}})}}return o.sort(vu)},Qv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:a}=e;const r=yu(t),o=[];for(const s of a){const{id:i}=s,l=n.get(i);if(l){const f=yu(l),u=r.reduce((g,h,b)=>g+mu(f[b],h),0),d=Number((u/4).toFixed(4));o.push({id:i,data:{droppableContainer:s,value:d}})}}return o.sort(vu)};function Jv(e,t){const n=Math.max(t.top,e.top),a=Math.max(t.left,e.left),r=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),s=r-a,i=o-n;if(a<r&&n<o){const l=t.width*t.height,f=e.width*e.height,u=s*i,d=u/(l+f-u);return Number(d.toFixed(4))}return 0}const Rv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:a}=e;const r=[];for(const o of a){const{id:s}=o,i=n.get(s);if(i){const l=Jv(i,t);l>0&&r.push({id:s,data:{droppableContainer:o,value:l}})}}return r.sort(Zv)};function ey(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function ku(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Jt}function ty(e){return function(n){for(var a=arguments.length,r=new Array(a>1?a-1:0),o=1;o<a;o++)r[o-1]=arguments[o];return r.reduce((s,i)=>({...s,top:s.top+e*i.y,bottom:s.bottom+e*i.y,left:s.left+e*i.x,right:s.right+e*i.x}),{...n})}}const ry=ty(1);function Cu(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function ny(e,t,n){const a=Cu(t);if(!a)return e;const{scaleX:r,scaleY:o,x:s,y:i}=a,l=e.left-s-(1-r)*parseFloat(n),f=e.top-i-(1-o)*parseFloat(n.slice(n.indexOf(" ")+1)),u=r?e.width/r:e.width,d=o?e.height/o:e.height;return{width:u,height:d,top:f,right:l+u,bottom:f+d,left:l}}const ay={ignoreTransform:!1};function tn(e,t){t===void 0&&(t=ay);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:f,transformOrigin:u}=Mt(e).getComputedStyle(e);f&&(n=ny(n,f,u))}const{top:a,left:r,width:o,height:s,bottom:i,right:l}=n;return{top:a,left:r,width:o,height:s,bottom:i,right:l}}function Su(e){return tn(e,{ignoreTransform:!0})}function oy(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function sy(e,t){return t===void 0&&(t=Mt(e).getComputedStyle(e)),t.posit Line truncated
w-full flex items-center justify-between px-3 py-2
bg-white dark:bg-gray-800
border border-gray-300 dark:border-gray-600 rounded-lg
text-left text-sm
${i?"opacity-50 cursor-not-allowed":"hover:border-gray-400 dark:hover:border-gray-500"}
focus:outline-none focus:ring-2 focus:ring-blue-500
`,children:[c.jsx(D,{className:"flex items-center gap-2",children:b?c.jsxs(c.Fragment,{children:[c.jsx(ne,{name:b.faIcon,className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),c.jsx(Z,{className:"text-gray-900 dark:text-white",children:b.label})]}):c.jsx(Z,{className:"text-gray-500 dark:text-gray-400",children:a})}),c.jsx(ne,{name:"chevron-down",className:`w-4 h-4 text-gray-400 dark:text-gray-500 transition-transform ${f?"rotate-180":""}`})]}),l&&c.jsx("input",{type:"hidden",name:l,value:e||""}),f&&c.jsxs(D,{className:"absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-72 overflow-hidden",children:[c.jsx(D,{className:"p-2 border-b border-gray-200 dark:border-gray-700",children:c.jsx(gt,{type:"text",value:d,onChange:v=>g(v.target.value),placeholder:r,className:"w-full px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white",autoFocus:!0})}),c.jsx(D,{className:"max-h-56 overflow-y-auto",children:p.length>0?p.map(v=>c.jsxs(oe,{type:"button",onClick:()=>x(v),className:`
w-full flex items-center gap-3 px-3 py-2 text-left text-sm
${b?.faIcon===v.faIcon?"bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300":"text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"}
`,children:[c.jsx(ne,{name:v.faIcon,className:"w-4 h-4"}),c.jsx(Z,{children:v.label}),b?.faIcon===v.faIcon&&c.jsx(ne,{name:"check",className:"w-4 h-4 ml-auto text-blue-600"})]},v.value)):c.jsx(D,{className:"px-3 py-4 text-sm text-gray-500 dark:text-gray-400 text-center",children:o})})]})]})},ei=({defaultOpen:e=!1,isOpen:t,onToggle:n,className:a="",style:r,children:o,disabled:s=!1})=>{const[i,l]=m.useState(e),f=t!==void 0,u=f?t:i,d=m.useRef(null),[g,h]=m.useState(e?void 0:0),b=()=>{if(s)return;const x=!u;f||l(x),n?.(x)};m.useEffect(()=>{if(d.current)if(u){h(d.current.scrollHeight);const x=setTimeout(()=>{h(void 0)},300);return()=>clearTimeout(x)}else h(d.current.scrollHeight),requestAnimationFrame(()=>{h(0)})},[u]);const p={};if(m.Children.forEach(o,x=>{if(m.isValidElement(x)){const v=x.props?.slot;v==="trigger"?p.trigger=x:v==="content"&&(p.content=x)}}),!p.trigger&&!p.content){const x=m.Children.toArray(o);x.length>=2?(p.trigger=x[0],p.content=x.slice(1)):x.length===1&&(p.content=x[0])}return c.jsxs(D,{className:`border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden ${a}`,style:r,children:[c.jsxs(oe,{type:"button",onClick:b,disabled:s,className:`w-full flex items-center justify-between p-3 text-left bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${s?"opacity-50 cursor-not-allowed":""} ${u?"border-b border-gray-200 dark:border-gray-700":""}`,"aria-expanded":u,children:[c.jsx(D,{className:"flex-1",children:p.trigger}),!p.trigger&&c.jsx("svg",{className:`w-5 h-5 text-gray-500 dark:text-gray-400 transition-transform duration-200 ${u?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),c.jsx(D,{ref:d,className:"overflow-hidden transition-all duration-300 ease-in-out",style:{height:g!==void 0?`${g}px`:"auto"},children:c.jsx(D,{className:"bg-white dark:bg-gray-800",children:p.content})})]})},Qn=window.G7Core,ld=Qn?.useControllableState,Ex=(e,t)=>window.G7Core?.t?.(e,t)??e,Nx={"":"common.scope_type_all_desc",self:"common.scope_type_self_desc",role:"common.scope_type_role_desc"},Ox=({options:e,value:t,onChange:n,disabled:a=!1})=>{const[r,o]=m.useState(!1),[s,i]=m.useState({}),l=m.useRef(null),f=e.find(d=>d.value===t)??e[0];m.useEffect(()=>{if(!r)return;const d=h=>{l.current&&!l.current.contains(h.target)&&o(!1)},g=()=>{if(!l.current)return;const h=l.current.getBoundingClientRect();i({position:"fixed",top:h.bottom+4,right:window.innerWidth-h.right,zIndex:9999})};return document.addEventListener("mousedown",d),window.addEventListener("scroll",g,!0),window.addEventListener("resize",g),()=>{document.removeEventListener("mousedown",d),window.removeEventListener("scroll",g,!0),window.removeEventListener("resize",g)}},[r]);const u=m.useCallback(()=>{if(a||!l.current)return;const d=l.current.getBoundingClientRect();i({position:"fixed",top:d.bottom+4,right:window.innerWidth-d.right,zIndex:9999}),o(g=>!g)},[a]);return c.jsxs(D,{ref:l,className:"relative flex-shrink-0",children:[c.jsxs(D,{role:"button",tabIndex:0,onClick:d=>{d.stopPropagation(),d.preventDefault(),u()},onMouseDown:d=>d.stopPropagation(),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.stopPropagation(),d.preventDefault(),u()),d.key==="Escape"&&o(!1)},className:`flex items-center gap-1 text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 cursor-pointer select-none ${a?"opacity-50 cursor-not-allowed":"hover:border-blue-400 dark:hover:border-blue-500"}`,children:[c.jsx(Z,{children:f?.label??""}),c.jsx(ne,{name:de.ChevronDown,className:"w-3 h-3 text-gray-400 dark:text-gray-500"})]}),r&&c.jsx(D,{style:s,className:"w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg py-1",children:e.map(d=>{const g=d.value??"",h=Nx[g],b=h?Ex(h):"",p=d.value===t;return c.jsxs(D,{role:"option","aria-selected":p,onClick:x=>{x.stopPropagation(),x.preventDefault(),n(d.value),o(!1)},onMouseDown:x=>x.stopPropagation(),className:`px-3 py-2 cursor-pointer transition-colors ${p?"bg-blue-50 dark:bg-blue-900/30":"hover:bg-gray-50 dark:hover:bg-gray-700/50"}`,children:[c.jsxs(D,{className:"flex items-center justify-between",children:[c.jsx(Z,{className:`text-xs font-medium ${p?"text-blue-700 dark:text-blue-300":"text-gray-900 dark:text-white"}`,children:d.label}),p&&c.jsx(ne,{name:de.Check,className:"w-3.5 h-3.5 text-blue-600 dark:text-blue-400"})]}),b&&c.jsx(Z,{className:"block text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:b})]},g||"__null__")})})]})},Mx=(e,t)=>{if(e.length!==t.length)return!1;const n=[...e].sort((r,o)=>r.id-o.id),a=[...t].sort((r,o)=>r.id-o.id);return n.every((r,o)=>r.id===a[o].id&&r.scope_type===a[o].scope_type)},Tx=({data:e=[],value:t=[],onChange:n,scopeOptions:a=[],className:r="",disabled:o=!1,desktopColumns:s=2,installedModules:i=[],installedPl Line truncated
let scriptImported = false
self.addEventListener('message', async (e) => {
const { file, id, imageCompressionLibUrl, options } = e.data
options.onProgress = (progress) => self.postMessage({ progress, id })
try {
if (!scriptImported) {
// console.log('[worker] importScripts', imageCompressionLibUrl)
self.importScripts(imageCompressionLibUrl)
scriptImported = true
}
// console.log('[worker] self', self)
const compressedFile = await imageCompression(file, options)
self.postMessage({ file: compressedFile, id })
} catch (e) {
// console.error('[worker] error', e)
self.postMessage({ error: e.message + '\\n' + e.stack, id })
}
})
`;let Ii;function Y1(e,t){return new Promise(((n,a)=>{Ii||(Ii=(function(s){const i=[];return i.push(s),URL.createObjectURL(new Blob(i))})(W1));const r=new Worker(Ii);r.addEventListener("message",(function(s){if(t.signal&&t.signal.aborted)r.terminate();else if(s.data.progress===void 0){if(s.data.error)return a(new Error(s.data.error)),void r.terminate();n(s.data.file),r.terminate()}else t.onProgress(s.data.progress)})),r.addEventListener("error",a),t.signal&&t.signal.addEventListener("abort",(()=>{a(t.signal.reason),r.terminate()})),r.postMessage({file:e,imageCompressionLibUrl:t.libURL,options:{...t,onProgress:void 0,signal:void 0}})}))}function Et(e,t){return new Promise((function(n,a){let r,o,s,i,l,f;if(r={...t},s=0,{onProgress:i}=r,r.maxSizeMB=r.maxSizeMB||Number.POSITIVE_INFINITY,l=typeof r.useWebWorker!="boolean"||r.useWebWorker,delete r.useWebWorker,r.onProgress=h=>{s=h,typeof i=="function"&&i(s)},!(e instanceof Blob||e instanceof B1))return a(new Error("The file given is not an instance of Blob or File"));if(!/^image/.test(e.type))return a(new Error("The file given is not an image"));if(f=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,!l||typeof Worker!="function"||f)return Lf(e,r).then(function(h){try{return o=h,g.call(this)}catch(b){return a(b)}}.bind(this),a);var u=function(){try{return g.call(this)}catch(h){return a(h)}}.bind(this),d=function(h){try{return Lf(e,r).then((function(b){try{return o=b,u()}catch(p){return a(p)}}),a)}catch(b){return a(b)}};try{return r.libURL=r.libURL||"https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js",Y1(e,r).then((function(h){try{return o=h,u()}catch{return d()}}),d)}catch{d()}function g(){try{o.name=e.name,o.lastModified=e.lastModified}catch{}try{r.preserveExif&&e.type==="image/jpeg"&&(!r.fileType||r.fileType&&r.fileType===e.type)&&(o=wf(e,o))}catch{}return n(o)}}))}Et.getDataUrlFromFile=Ef,Et.getFilefromDataUrl=Ai,Et.loadImage=Nf,Et.drawImageInCanvas=Mf,Et.drawFileInCanvas=Co,Et.canvasToFile=So,Et.getExifOrientation=Tf,Et.handleMaxWidthOrHeight=Af,Et.followExifOrientation=If,Et.cleanupCanvasMemory=ur,Et.isAutoOrientationInBrowser=fn,Et.approximateBelowMaximumCanvasSizeOfBrowser=Of,Et.copyExifWithoutOrientation=wf,Et.getBrowserName=$r,Et.version="2.0.2";const q1=window.G7Core,Li=e=>{const t=["B","KB","MB","GB"];let n=0,a=e;for(;a>=1024&&n<t.length-1;)a/=1024,n++;return`${a.toFixed(2)} ${t[n]}`},K1=e=>{if(e&&typeof e=="object"){const t=e;if(t.response?.data?.message)return t.response.data.message;if(t.response?.data?.errors){const n=Object.values(t.response.data.errors)[0];if(Array.isArray(n)&&n[0])return n[0]}if(t.message)return t.message}return e instanceof Error?e.message:"업로드 실패"},X1=e=>e?e.startsWith("image/")?"fa-file-image":e.startsWith("video/")?"fa-file-video":e.startsWith("audio/")?"fa-file-audio":e==="application/pdf"?"fa-file-pdf":e.includes("word")||e.includes("document")?"fa-file-word":e.includes("excel")||e.includes("spreadsheet")?"fa-file-excel":e.includes("zip")||e.includes("compressed")?"fa-file-zipper":"fa-file":"fa-file",wt=(e,t)=>q1?.t?.(e,t)??e,Df=window.G7Core?.createLogger?.("Comp:FileUploader")??{log:(...e)=>console.log("[Comp:FileUploader]",...e),warn:(...e)=>console.warn("[Comp:FileUploader]",...e),error:(...e)=>console.error("[Comp:FileUploader]",...e)},Fr=window.G7Core;function Z1(e){const{attachmentableType:t,attachmentableId:n,collection:a,maxFiles:r,maxSize:o,maxConcurrentUploads:s,accept:i,imageCompression:l,roleIds:f,autoUpload:u,initialFiles:d,endpoints:g,onFilesChange:h,onUploadComplete:b,onUploadError:p,onRemove:x,onReorder:v,uploadTriggerEvent:O,confirmBeforeRemove:k,uploadParams:C}=e,[N,E]=m.useState(d),[S,y]=m.useState([]),[w,I]=m.useState(!1),L=m.useRef(null),F=m.useRef(0),T=m.useRef(new Set),P=m.useRef(new Map),[V,M]=m.useState(!1),[A,j]=m.useState(null),[U,Y]=m.useState(!1),G=m.useRef(!1),[H,B]=m.useState([]),[z,$]=m.useState(!1),[q,J]=m.useState(0),R=m.useRef(0),[ee,X]=m.useState(new Map),re=m.useRef(h);re.current=h,m.useEffect(()=>{re.current?.(S)},[S]),m.useEffect(()=>{if(G.current)return;const ae=d.filter(ge=>!T.current.has(ge.id)&&(!ge.hash||!T.current.has(ge.hash))),ue=new Set(ae.map(ge=>ge.id)),fe=Array.from(P.current.values()).filter(ge=>!ue.has(ge.id)&&!T.current.has(ge.id));E([...ae,...fe])},[d]);const le=m.useCallback(async ae=>{const ue={maxSizeMB:l?.maxSizeMB??1,maxWidthOrHeight:l?.maxWidthOrHeight??1920,useWebWorker:!0};return await Et(ae,ue)},[l]),ve=m.useCallback(async ae=>{const ue=N.length+S.length,fe=r-ue,ge=Array.from(ae).slice(0,fe);for(const Ce of ge){if(Ce.size>o*1024*1024){p?.(`[${Ce.name}] 파일 크기(${Li(Ce.size)})가 최대 허용 크기(${o}MB)를 초과합니다.`,Ce);continue}if(i){const be="."+Ce.name.split(".").pop()?.toLowerCase();if(!i.split(",").map(Te=>Te.trim().toLowerCase()).includes(be)){p?.(`[${Ce.name}] 허용되지 않는 파일 형식입니다. (허용: ${i})`,Ce);continue}}const Ie={id:`pending-${Date.now()}Line truncated
relative border-2 border-dashed rounded-lg transition-colors
${l?"opacity-60 cursor-not-allowed":""}
${e&&!l?"border-blue-500 bg-blue-50 dark:bg-blue-900/20":"border-gray-300 dark:border-gray-600"}
`,onDragOver:d=>{d.preventDefault(),u&&a(!0)},onDragLeave:()=>a(!1),onDrop:d=>{d.preventDefault(),a(!1),u&&n(d.dataTransfer.files)},children:[c.jsx("input",{ref:r,type:"file",multiple:!0,accept:o,onChange:d=>d.target.files&&!l&&n(d.target.files),className:"hidden",disabled:l}),!f&&c.jsxs(D,{className:`p-8 text-center transition-colors ${l?"cursor-not-allowed":"cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50"}`,onClick:()=>!l&&r.current?.click(),children:[c.jsx(lt,{className:"fa-solid fa-cloud-arrow-up text-4xl text-gray-400 dark:text-gray-500 mb-4"}),c.jsx(ut,{className:"text-sm text-gray-600 dark:text-gray-400",children:wt("attachment.drop_or_click")}),c.jsxs(ut,{className:"text-xs text-gray-500 dark:text-gray-500 mt-2",children:[wt("attachment.upload_limit",{maxFiles:s,maxSize:i}),o&&` (${o})`]})]}),f]})},J1=window.G7Core,R1=window.G7Core?.createLogger?.("Comp:SortableThumbnail")??{log:(...e)=>console.log("[Comp:SortableThumbnail]",...e),warn:(...e)=>console.warn("[Comp:SortableThumbnail]",...e),error:(...e)=>console.error("[Comp:SortableThumbnail]",...e)},ek=({file:e,onRemove:t,onRetry:n,onImageClick:a,onDownload:r,isPrimary:o,onPrimaryClick:s,disabled:i})=>{const{attributes:l,listeners:f,setNodeRef:u,transform:d,transition:g,isDragging:h}=lo({id:"hash"in e?e.hash:e.id}),b={transform:cr.Transform.toString(d),transition:g,opacity:h?.5:1},p="status"in e&&e.status!==void 0,x=p?e.status:"done",v=x==="uploading",O=x==="compressing",k=x==="error",C=p?e.progress:100,N=p?e.preview:void 0,E=p?e.mime_type?.startsWith("image/")??!1:e.is_image,[S,y]=m.useState(void 0),w=!p&&E?e.download_url:void 0;m.useEffect(()=>{if(!w){y(void 0);return}let L=!0,F;return(async()=>{try{const P=await J1.api.get(w,{responseType:"blob"});L&&P&&(F=URL.createObjectURL(P),y(F))}catch(P){R1.error("Failed to load authenticated image:",P)}})(),()=>{L=!1,F&&URL.revokeObjectURL(F)}},[w]);const I=S;return c.jsxs(D,{ref:u,style:b,className:"relative group bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:[c.jsxs(D,{className:`aspect-square w-full flex items-center justify-center bg-gray-50 dark:bg-gray-900 relative ${E||!p?"cursor-pointer":""}`,onClick:()=>{v||O||(E&&a?a():!p&&r&&r())},children:[N||I?c.jsx(ar,{src:N||I,alt:e.original_filename,className:"w-full h-full object-cover"}):c.jsx(lt,{className:`fa-solid ${X1(e.mime_type)} text-4xl text-gray-400 dark:text-gray-500`}),(v||O)&&c.jsxs(D,{className:"absolute inset-0 bg-black/50 flex flex-col items-center justify-center",children:[c.jsx(D,{className:"w-3/4 h-2 bg-gray-700 rounded-full overflow-hidden",children:c.jsx(D,{className:"h-full bg-blue-500 transition-all",style:{width:`${C}%`}})}),c.jsxs(Z,{className:"text-white text-xs mt-1",children:[C,"%"]})]}),k&&c.jsx(D,{className:"absolute inset-0 bg-red-500/50 flex items-center justify-center",children:c.jsx(lt,{className:"fa-solid fa-exclamation-triangle text-2xl text-white"})}),s&&c.jsx(oe,{type:"button",onClick:L=>{L.stopPropagation(),s()},className:`absolute top-1.5 left-1.5 z-10 p-1 rounded-full transition-colors ${o?"bg-yellow-500 text-white":"bg-gray-800/50 text-gray-300 hover:bg-yellow-500 hover:text-white opacity-0 group-hover:opacity-100"}`,title:wt(o?"attachment.primary_image":"attachment.set_as_primary"),children:c.jsx(lt,{className:"fa-solid fa-star text-xs"})}),c.jsxs(D,{className:`absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors flex items-start justify-end p-1 gap-1 opacity-0 group-hover:opacity-100 ${i?"hidden":""}`,children:[c.jsx(oe,{type:"button",...l,...f,className:"p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-gray-600 dark:text-gray-300 hover:bg-white cursor-grab active:cursor-grabbing",title:wt("attachment.drag_to_reorder"),onClick:L=>L.stopPropagation(),children:c.jsx(lt,{className:"fa-solid fa-grip-vertical text-sm"})}),!p&&r&&c.jsx(oe,{type:"button",onClick:L=>{L.stopPropagation(),r()},className:"p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-blue-500 hover:bg-white",title:wt("common.download"),children:c.jsx(lt,{className:"fa-solid fa-download text-sm"})}),k&&n&&c.jsx(oe,{type:"button",onClick:L=>{L.stopPropagation(),n()},className:"p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-orange-500 hover:bg-white",title:wt("common.retry"),children:c.jsx(lt,{className:"fa-solid fa-arrow-rotate-right text-sm"})}),c.jsx(oe,{type:"button",onClick:L=>{L.stopPropagation(),t()},disabled:v||O,className:"p-1.5 bg-white/90 dark:bg-gray-800/90 rounded text-red-500 hover:bg-white disabled:opacity-50",title:wt("common.delete"),children:c.jsx(lt,{className:"fa-solid fa-times text-sm"})})]})]}),c.jsxs(D,{className:`p-2 ${!p&&r?"cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700":""}`,onClick:()=>{!p&&r&&r()},children:[c.jsx(ut,{className:"text-xs font-medium text-gray-900 dark:text-white truncate",title:e.original_filename,children:e.original_filename}),c.jsx(ut,{className:"text-xs text-gray-500 dark:text-gray-400",children:e.siz Line truncated
${b.radio}
text-blue-600
bg-gray-100 dark:bg-gray-700
border-gray-300 dark:border-gray-600
focus:ring-blue-500 dark:focus:ring-blue-600
focus:ring-2
dark:ring-offset-gray-800
${O?"cursor-not-allowed":"cursor-pointer"}
`}),c.jsx(Z,{className:`
${b.label}
font-medium
text-gray-900 dark:text-gray-300
`,children:x.label})]},x.value)})}),f&&c.jsx(Z,{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:f})]})},gn=()=>window.G7Core,Eo=(e,t)=>gn()?.t?.(e,t)??e,nk=()=>gn()?.locale?.supported?.()??["ko","en"],ak=()=>gn()?.locale?.current?.()??"ko",Pf=e=>{const t=Eo(`common.language_${e}`);return t===`common.language_${e}`?{ko:"한국어",en:"English",ja:"日本語",zh:"中文"}[e]||e.toUpperCase():t},ok=({content:e="",value:t,onChange:n,multilingual:a=!1,isHtml:r=!1,onIsHtmlChange:o,rows:s=15,placeholder:i="",label:l,showHtmlModeToggle:f=!0,contentClassName:u="",purifyConfig:d,className:g="",name:h="content",htmlFieldName:b="content_mode",readOnly:p=!1})=>{const x=m.useMemo(()=>nk(),[]),v=m.useMemo(()=>ak(),[]),[O,k]=m.useState(v),[C,N]=m.useState(r),[E,S]=m.useState(e),[y,w]=m.useState(t??{}),[I,L]=m.useState(!1);m.useEffect(()=>{N(r)},[r]),m.useEffect(()=>{a||S(e)},[e,a]),m.useEffect(()=>{a&&t&&w(t)},[t,a]);const F=m.useCallback(U=>{const Y=U.target.value;if(S(Y),n){const G=gn()?.createChangeEvent?.({value:Y,name:h,type:"textarea"})??{target:{name:h,value:Y}};n(G)}},[n,h]),T=m.useCallback((U,Y)=>{const G={...y,[U]:Y};if(w(G),n){const H=gn()?.createChangeEvent?.({value:G,name:h,type:"multilingual"})??{target:{name:h,value:G}};n(H)}},[n,h,y]),P=m.useCallback(U=>{const Y=U.target.checked;if(N(Y),Y||L(!1),o){const G=gn()?.createChangeEvent?.({checked:Y,name:b,type:"checkbox"})??{target:{name:b,checked:Y}};o(G)}},[o,b]),V=m.useCallback(()=>{L(U=>!U)},[]),M=a?y[O]??"":E,A=m.useCallback(U=>!!y[U]?.trim(),[y]),j=()=>c.jsx(D,{className:"flex items-center gap-2 mb-3",children:x.map(U=>{const Y=U===v,G=O===U;return c.jsxs(oe,{type:"button",className:`
inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all
${G?Y?"bg-blue-500 text-white dark:bg-blue-600 dark:text-white shadow-md scale-105":"bg-gray-500 text-white dark:bg-gray-600 dark:text-white shadow-md scale-105":Y?"bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/50":"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600"}
`,onClick:()=>k(U),children:[c.jsx(ne,{name:"globe",className:"w-3 h-3"}),c.jsx(Z,{children:Pf(U)}),Y&&c.jsx(Z,{className:"text-red-500",children:"*"}),A(U)&&!G&&c.jsx(ne,{name:"check",className:"w-3 h-3 text-green-500 dark:text-green-400"})]},U)})});return c.jsxs(D,{className:`space-y-2 ${g}`,children:[c.jsxs(D,{className:"flex items-center justify-between",children:[l&&c.jsx($t,{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:l}),c.jsxs(D,{className:"flex items-center gap-3",children:[C&&!p&&c.jsx(oe,{type:"button",onClick:V,className:`px-3 py-1.5 text-xs font-bold rounded-lg focus:outline-none focus:ring-2 ${I?"text-gray-700 dark:text-gray-200 bg-gray-200 dark:bg-gray-600 border border-gray-300 dark:border-gray-500 hover:bg-gray-300 dark:hover:bg-gray-500 focus:ring-gray-400 dark:focus:ring-gray-500":"text-blue-600 dark:text-blue-400 bg-white dark:bg-gray-700 border border-blue-300 dark:border-blue-600 hover:bg-blue-50 dark:hover:bg-gray-600 focus:ring-blue-500 dark:focus:ring-blue-600"}`,children:Eo(I?"common.preview_off":"common.preview")}),f&&c.jsxs($t,{className:"flex items-center gap-2 p-2 cursor-pointer",children:[c.jsx(gt,{type:"checkbox",name:b,checked:C,onChange:P,disabled:p,className:"w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"}),c.jsx(D,{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:Eo("common.html_mode")})]})]})]}),a&&j(),!I&&(a?x.map(U=>c.jsx(D,{className:O===U?"block":"hidden",children:c.jsx(vr,{name:`${h}[${U}]`,value:y[U]??"",onChange:Y=>T(U,Y.target.value),placeholder:`${i} (${Pf(U)})`,rows:s,readOnly:p,className:`block w-full rounded-lg border px-3 py-2 text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 disabled:opacity-50 disabled:cursor-not-allowed ${C?"font-mono bg-white dark:bg-gray-800 border-blue-300 dark:border-blue-600 text-gray-800 dark:text-gray-200 focus:border-blue-500 focus:ring-blue-500":"bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-blue-500"}`})},U)):c.jsx(vr,{name:h,value:E,onChange:F,placeholder:i,rows:s,readOnly:p,className:`block w-full rounded-lg border px-3 py-2 text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 disabled:opacity-50 disabled:cursor-not-allowed ${C?"font-mono bg-white dark:bg-gray-800 border-blue-300 dark:border-blue-600 text-gray-800 dark:text-gray-200 focus:border-blue-500 focus:ring-blue-500":"bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-blue-500"}`})),I&&c.jsx(D,{className:"p-4 bg-gray-50 dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 min-h-[400px]",children:c.jsx(qo,{content:M,isHtml:!0,className:u||"prose dark:prose-invert max-w-none text-gray-900 dark:text-gray-100",purifyConfig:d})})]})},$f="g7_dismissed_warnings";function Ff(){try{const e=sessionStorage.getItem($f);return e?JSON.parse(e):[]}catch{return[]}}function sk(e){try{const t=Ff();t.includes(e)||(t.push(e),sessionStorage.setItem($f,JSON.stringify(t)))}catch{}}function ik(e){switch(e){case"error":return"error";case"warning":return"warning";case"info":default:return"info"}}const lk=({warnings:e,className:t=""})=>{const[n,a]=m.useState([]);m.useEffect(()=>{a(Ff())},[]);const r=m.useCallback(s=>{sk(s),a(i=>[...i,s])},[]);if(!e||e.length===0)return null;const o=e.filter(s=>!n.includes(s.id));return o.length===0?null:c.jsx(D,{className:`space-y-2 ${t}`.trim(),children:o.map(s=>c.jsx(wl,{type:ik(s.level),message:s.message,dismissible:!0,onDismiss:()=>r(s.id)},s.id))})},Uf=window.G7Core?.createLogger?.("Comp:FilterVisibility")??{log:(...e)=>console.log("[Comp:FilterVisibility]",...e),warn:(...e)=>console.warn("[Comp:FilterVisibility]",...e),error:(...e)=>console.error("[Comp:FilterVisibility]",...e)},ck=({id:e,visibleFilters:t,defaultFilters:n=[],onFilterVisibilityChange:a})=>{const[r,o]=m.useState(!1),s=m.useRef(!0),i=m.useMemo(()=>{try{const g=window.G7Core?.AuthManager?.getInstance();return g?g.getUser()?.uuid:void 0}catch{return}},[]),l=m.useMemo(()=>`g7_filters_${e}${i!==void 0?`_${i}`:""}`,[e,i]),f=m.useCallback(()=>{try{const g=localStorage.getItem(l);if(g){const h=JSON.parse(g);if(Array.isArray(h))return h}}catch(g){Uf.warn("Failed to load from localStorage:",g)}return null},[l]),u=m.useCallback(g=>{try{localStorage.setItem(l,JSON.stringify(g))}catch(h){Uf.warn("Failed to save to localStorage:",h)}},[l]),d=m.useCallback(()=>{const g=f();return g||(t&&t.length>0?t:n)},[f,t,n]);return m.useEffect(()=>{if(!r){const g=d();a&&g.length>0&&a(g),o(!0)}},[r,a,d]),m.useEffect(()=>{if(r&&t&&t.length>0){if(s.current){s.current=!1;return}u(t)}},[r,t,u]),null},uk=window.G7Core?.createLogger?.("Comp:SlotContainer")??{log:(...e)=>console.log Line truncated
w-full px-4 py-2.5
bg-gray-100 dark:bg-gray-700
border-0 rounded-xl
text-gray-700 dark:text-gray-200 font-medium
focus:ring-2 focus:ring-blue-500 focus:outline-none
flex items-center justify-between gap-2
text-left cursor-pointer
disabled:opacity-50 disabled:cursor-not-allowed
`,"aria-haspopup":"listbox","aria-expanded":u,children:[c.jsx(D,{className:"flex-1 min-w-0",children:O()}),c.jsx(gr,{className:`w-4 h-4 flex-shrink-0 transition-transform duration-200 ${u?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),u&&c.jsx(D,{className:"absolute z-50 w-full mt-2 bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 overflow-hidden",role:"listbox",children:c.jsx(D,{className:"overflow-auto",style:{maxHeight:s},children:e.length===0?c.jsx(D,{className:"px-4 py-6 text-center text-gray-500 dark:text-gray-400",children:Vf("common.no_options")}):e.map((C,N)=>{const E=String(C.value)===String(t);return c.jsx(oe,{type:"button",onClick:()=>!C.disabled&&x(C.value),disabled:C.disabled,className:`
w-full px-4 py-3 text-left
hover:bg-gray-100 dark:hover:bg-gray-700
transition-colors
${E?"bg-blue-50 dark:bg-blue-900/20":""}
${C.disabled?"opacity-50 cursor-not-allowed":"cursor-pointer"}
`,role:"option","aria-selected":E,"data-item-value":C.value,"data-item-index":N,"data-item-selected":E,children:f?.item?Hf(f.item,{item:C,index:N,isSelected:E},`item-${N}`):i||k(C,E)},C.value)})})})]})};function gk(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}const hk=({value:e,checked:t=!1,icon:n,label:a,variant:r="blue",customColor:o,className:s="",style:i,onChange:l})=>{const[f,u]=m.useState(!1),d="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium border cursor-pointer transition-all";if(o){const p=gk(o),x=document.documentElement.classList.contains("dark");let v;return t?v={backgroundColor:o,color:"#ffffff",borderColor:o,opacity:f?.85:1}:v=p?{backgroundColor:`rgba(${p.r}, ${p.g}, ${p.b}, ${f?x?.25:.12:x?.15:.06})`,color:o,borderColor:`rgba(${p.r}, ${p.g}, ${p.b}, ${x?.3:.2})`}:{},c.jsxs($t,{className:`${d} ${s}`,style:{...v,...i},onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),children:[c.jsx(gt,{type:"checkbox",value:e,checked:t,onChange:O=>{l?.(O)},className:"hidden"}),n&&c.jsx(ne,{name:n,className:"w-4 h-4"}),c.jsx(D,{children:a})]})}const b=t?{green:"bg-green-600 dark:bg-green-600 text-white dark:text-white border-green-700 dark:border-green-500 hover:bg-green-700 dark:hover:bg-green-500",orange:"bg-orange-600 dark:bg-orange-600 text-white dark:text-white border-orange-700 dark:border-orange-500 hover:bg-orange-700 dark:hover:bg-orange-500",yellow:"bg-yellow-600 dark:bg-yellow-600 text-white dark:text-white border-yellow-700 dark:border-yellow-500 hover:bg-yellow-700 dark:hover:bg-yellow-500",gray:"bg-gray-600 dark:bg-gray-500 text-white dark:text-white border-gray-700 dark:border-gray-400 hover:bg-gray-700 dark:hover:bg-gray-400",blue:"bg-blue-600 dark:bg-blue-600 text-white dark:text-white border-blue-700 dark:border-blue-500 hover:bg-blue-700 dark:hover:bg-blue-500"}[r]:{green:"bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 border-green-200 dark:border-green-800 hover:bg-green-100 dark:hover:bg-green-900/30",orange:"bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-200 dark:border-orange-800 hover:bg-orange-100 dark:hover:bg-orange-900/30",yellow:"bg-yellow-50 dark:bg-yellow-900/20 text-yellow-600 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800 hover:bg-yellow-100 dark:hover:bg-yellow-900/30",gray:"bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-600",blue:"bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800 hover:bg-blue-100 dark:hover:bg-blue-900/30"}[r];return c.jsxs($t,{className:`${d} ${b} ${s}`,style:i,children:[c.jsx(gt,{type:"checkbox",value:e,checked:t,onChange:p=>{l?.(p)},className:"hidden"}),n&&c.jsx(ne,{name:n,className:"w-4 h-4"}),c.jsx(D,{children:a})]})},pk=({label:e,icon:t,iconPosition:n="left",position:a="right",className:r="",style:o,children:s})=>{const[i,l]=m.useState(!1),[f,u]=m.useState({top:0,left:0}),d=m.useRef(null),g=m.useRef(null),h=m.useCallback(()=>{if(!d.current)return;const p=d.current.getBoundingClientRect(),x=224;let v=a==="right"?p.right-x:p.left;const O=p.bottom+8;v<8&&(v=8),v+x>window.innerWidth-8&&(v=window.innerWidth-x-8),u({top:O,left:v})},[a]);m.useEffect(()=>{i&&h()},[i,h]),m.useEffect(()=>{if(!i)return;const p=()=>{l(!1)};return window.addEventListener("scroll",p,!0),window.addEventListener("resize",p),()=>{window.removeEventListener("scroll",p,!0),window.removeEventListener("resize",p)}},[i]),m.useEffect(()=>{const p=x=>{const v=x.target,O=d.current?.contains(v),k=g.current?.contains(v);!O&&!k&&l(!1)};return i&&document.addEventListener("mousedown",p),()=>{document.removeEventListener("mousedown",p)}},[i]);const b=i?fr.createPortal(c.jsx("div",{ref:g,className:"fixed z-[9999] w-56 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg overflow-hidden",style:{top:f.top,left:f.left},onClick:()=>l(!1),children:s}),document.body):null;return c.jsxs(D,{className:`relative inline-block ${r}`,style:o,children:[c.jsxs(oe,{ref:d,onClick:()=>l(!i),className:"flex items-center gap-2",children:[n==="left"&&t&&c.jsx(ne,{name:t,className:"w-4 h-4"}),e&&c.jsx(Z,{className:"text-sm font-medium",children:e}),n==="right"&&t&&c.jsx(ne,{name:t,className:"w-4 h-4"})]}),b]})},bk=({label:e,icon:t,variant:n="default",disabled:a=!1,divider:r=!1,className:o="",style:s,onClick:i})=>{if(r)return c.jsx(D,{className:"h-px bg-gray-200 dark:bg-gray-700 my-1",style:s});const l=n==="danger"?"text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20":"text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700",f=a?"opacity-50 cursor-not-allowed":"cursor-pointer",u=()=>{!a&&i&&i()};return c.jsxs(D,{onClick:u,className:`flex items-center gap-3 px-4 py-3 transition-colors ${l} ${f} ${o}`,styl Line truncated
//# sourceMappingURL=components.iife.js.map
@@ -0,0 +1 @@
{"version":3,"file":"components.iife.js","sources":["../../src/components/basic/Button.tsx","../../src/components/basic/FileInput.tsx","../../src/components/basic/Input.tsx","../../src/components/basic/Textarea.tsx","../../src/components/basic/Label.tsx","../../src/components/basic/Div.tsx","../../src/components/basic/Span.tsx","../../src/components/basic/P.tsx","../../src/components/basic/Img.tsx","../../src/components/basic/H1.tsx","../../src/components/basic/H2.tsx","../../src/components/basic/H3.tsx","../../src/components/basic/H4.tsx","../../src/components/basic/Ul.tsx","../../src/components/basic/Ol.tsx","../../src/components/basic/Li.tsx","../../src/components/basic/A.tsx","../../src/components/basic/Form.tsx","../../src/components/basic/Svg.tsx","../../src/components/basic/Select.tsx","../../src/components/basic/Option.tsx","../../src/components/basic/Optgroup.tsx","../../src/components/basic/Checkbox.tsx","../../src/components/basic/Table.tsx","../../src/components/basic/Thead.tsx","../../src/components/basic/Tbody.tsx","../../src/components/basic/Tfoot.tsx","../../src/components/basic/Tr.tsx","../../src/components/basic/Th.tsx","../../src/components/basic/Td.tsx","../../src/components/basic/Nav.tsx","../../src/components/basic/Section.tsx","../../src/components/basic/Icon.tsx","../../src/components/basic/Code.tsx","../../src/components/basic/Pre.tsx","../../src/components/basic/Fragment.tsx","../../src/components/basic/Hr.tsx","../../src/components/basic/IconTypes.ts","../../src/components/composite/Card.tsx","../../src/components/composite/ActionMenu.tsx","../../src/components/composite/Pagination.tsx","../../src/components/composite/MultilingualInput.tsx","../../src/components/composite/Toggle.tsx","../../src/components/composite/StatusBadge.tsx","../../src/components/composite/Badge.tsx","../../node_modules/dompurify/dist/purify.es.mjs","../../src/components/composite/HtmlContent.tsx","../../src/components/composite/DataGrid.tsx","../../src/components/composite/CardGrid.tsx","../../src/components/composite/Modal.tsx","../../src/components/composite/Dropdown.tsx","../../src/components/composite/ProductCard.tsx","../../src/components/composite/StatCard.tsx","../../src/components/composite/SearchBar.tsx","../../src/components/composite/FilterGroup.tsx","../../src/components/composite/TabNavigation.tsx","../../src/handlers/scrollToSectionHandler.ts","../../src/components/composite/TabNavigationScroll.tsx","../../src/components/composite/IconButton.tsx","../../src/components/composite/Dialog.tsx","../../src/components/composite/ConfirmDialog.tsx","../../src/components/composite/AlertDialog.tsx","../../src/components/composite/Toast.tsx","../../src/components/composite/Breadcrumb.tsx","../../src/components/composite/EmptyState.tsx","../../src/components/composite/LoadingSpinner.tsx","../../src/components/basic/I.tsx","../../src/components/composite/AdminSidebar.tsx","../../src/components/composite/AdminHeader.tsx","../../src/components/composite/NotificationCenter.tsx","../../src/components/composite/LanguageSelector.tsx","../../src/components/composite/UserProfile.tsx","../../src/components/composite/AdminFooter.tsx","../../src/components/composite/PageHeader.tsx","../../src/components/composite/TemplateCard.tsx","../../src/components/composite/Alert.tsx","../../src/components/composite/LayoutEditorHeader.tsx","../../src/components/composite/LayoutFileList.tsx","../../node_modules/@monaco-editor/loader/lib/es/_virtual/_rollupPluginBabelHelpers.js","../../node_modules/state-local/lib/es/state-local.js","../../node_modules/@monaco-editor/loader/lib/es/config/index.js","../../node_modules/@monaco-editor/loader/lib/es/utils/curry.js","../../node_modules/@monaco-editor/loader/lib/es/utils/isObject.js","../../node_modules/@monaco-editor/loader/lib/es/validators/index.js","../../node_modules/@monaco-editor/loader/lib/es/utils/compose.js","../../node_modules/@monaco-editor/loader/lib/es/utils/deepMerge.js","../../node_modules/@monaco-editor/loader/lib/es/utils/makeCancelable.js","../../node_modules/@monaco-editor/loader/lib/es/loader/index.js","../../node_modules/@monaco-editor/react/dist/index.mjs","../../src/components/composite/CodeEditor.tsx","../../src/components/composite/VersionList.tsx","../../src/components/composite/LayoutHistoryPanel.tsx","../../src/components/composite/LoginForm.tsx","../../src/components/composite/ThemeToggle.tsx","../../src/components/composite/ColumnSelector.tsx","../../src/components/composite/PageTransitionIndicator.tsx","../../node_modules/@babel/runtime/helpers/esm/typeof.js","../../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../node_modules/@babel/runtime/helpers/esm/objectSpread2.js","../../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js","../../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js","../.Line truncated
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface AProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
}
/**
* 기본 a(링크) 컴포넌트
*/
export declare const A: React.FC<AProps>;
@@ -0,0 +1,9 @@
import { default as React } from 'react';
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'danger' | 'success';
size?: 'sm' | 'md' | 'lg';
}
/**
* 기본 버튼 컴포넌트
*/
export declare const Button: React.ForwardRefExoticComponent<ButtonProps & React.RefAttributes<HTMLButtonElement>>;
@@ -0,0 +1,18 @@
import { default as React } from 'react';
export interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
/**
* indeterminate 상태 (부분 선택 상태)
*
* 부모-자식 체크박스 연동에서 일부 자식만 선택되었을 때 사용합니다.
* HTML checkbox의 indeterminate 속성을 JavaScript로 설정합니다.
*/
indeterminate?: boolean;
}
/**
* 기본 체크박스 컴포넌트
*
* forwardRef를 사용하여 ref 전달을 지원합니다.
* indeterminate prop을 통해 부분 선택 상태를 표시할 수 있습니다.
*/
export declare const Checkbox: React.ForwardRefExoticComponent<CheckboxProps & React.RefAttributes<HTMLInputElement>>;
@@ -0,0 +1,10 @@
import { default as React } from 'react';
export interface CodeProps extends React.HTMLAttributes<HTMLElement> {
}
/**
* 기본 code 컴포넌트
*
* 인라인 코드 또는 코드 스니펫을 표시하기 위한 기본 컴포넌트입니다.
* HTML <code> 태그를 래핑합니다.
*/
export declare const Code: React.FC<CodeProps>;
@@ -0,0 +1,8 @@
import { default as React } from 'react';
export interface DivProps extends React.HTMLAttributes<HTMLDivElement> {
ref?: React.Ref<HTMLDivElement>;
}
/**
* 기본 div 컴포넌트
*/
export declare const Div: React.ForwardRefExoticComponent<Omit<DivProps, "ref"> & React.RefAttributes<HTMLDivElement>>;
@@ -0,0 +1,21 @@
import { default as React } from 'react';
export interface FileInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type' | 'onChange' | 'onError'> {
/** 허용되는 파일 확장자 (예: ".zip,.pdf") */
accept?: string;
/** 최대 파일 크기 (MB) */
maxSize?: number;
/** 파일 선택 시 콜백 */
onChange?: (file: File | null) => void;
/** 에러 발생 시 콜백 */
onError?: (error: string) => void;
/** 버튼 텍스트 */
buttonText?: string;
/** 빈 상태 텍스트 */
placeholder?: string;
}
/**
* 파일 업로드 입력 컴포넌트
*
* ZIP 파일 등의 파일 업로드를 처리하며, 파일 크기 검증을 지원합니다.
*/
export declare const FileInput: React.ForwardRefExoticComponent<FileInputProps & React.RefAttributes<HTMLInputElement>>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {
}
/**
* 기본 form 컴포넌트
*/
export declare const Form: React.FC<FormProps>;
@@ -0,0 +1,31 @@
import { default as React } from 'react';
export interface FragmentProps {
children?: React.ReactNode;
className?: string;
style?: React.CSSProperties;
}
/**
* Fragment 기본 컴포넌트
*
* React.Fragment와 유사하게 DOM 요소를 추가하지 않고 children만 렌더링합니다.
* iterator와 함께 사용하여 불필요한 wrapper div 없이 반복 렌더링할 때 유용합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "type": "basic",
* "name": "Fragment",
* "iterator": {
* "source": "{{items}}",
* "item": "item"
* },
* "children": [
* {
* "type": "basic",
* "name": "Button",
* "text": "{{item.label}}"
* }
* ]
* }
*/
export declare const Fragment: React.FC<FragmentProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface H1Props extends React.HTMLAttributes<HTMLHeadingElement> {
}
/**
* 기본 h1 제목 컴포넌트
*/
export declare const H1: React.FC<H1Props>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface H2Props extends React.HTMLAttributes<HTMLHeadingElement> {
}
/**
* 기본 h2 제목 컴포넌트
*/
export declare const H2: React.FC<H2Props>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface H3Props extends React.HTMLAttributes<HTMLHeadingElement> {
}
/**
* 기본 h3 제목 컴포넌트
*/
export declare const H3: React.FC<H3Props>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface H4Props extends React.HTMLAttributes<HTMLHeadingElement> {
}
/**
* 기본 h4 제목 컴포넌트
*/
export declare const H4: React.FC<H4Props>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface HrProps extends React.HTMLAttributes<HTMLHRElement> {
}
/**
* 기본 hr(수평선) 컴포넌트
*/
export declare const Hr: React.FC<HrProps>;
@@ -0,0 +1,19 @@
import { default as React } from 'react';
export interface IProps extends React.HTMLAttributes<HTMLElement> {
className?: string;
children?: React.ReactNode;
style?: React.CSSProperties;
}
/**
* I 기본 컴포넌트
*
* HTML <i> 태그를 래핑한 기본 컴포넌트입니다.
* 주로 아이콘 폰트 (FontAwesome 등)와 함께 사용됩니다.
*
* @example
* ```tsx
* <I className="fas fa-user" />
* <I className="fas fa-home" />
* ```
*/
export declare const I: React.FC<IProps>;
@@ -0,0 +1,81 @@
import { default as React } from 'react';
import { IconName, IconStyle, IconSize } from './IconTypes';
export interface IconProps extends Omit<React.HTMLAttributes<HTMLElement>, 'style'> {
/**
* 아이콘 이름 (Font Awesome 클래스명 또는 IconName enum)
*
* @example
* // 문자열로 직접 지정
* <Icon name="fa-user" />
*
* // enum 사용 (타입 안전)
* <Icon name={IconName.User} />
*/
name: string | IconName;
/**
* 아이콘 스타일 (Font Awesome 5/6)
*
* - solid: fas (기본값)
* - regular: far
* - light: fal
* - duotone: fad
* - brands: fab
*/
iconStyle?: IconStyle;
/**
* CSS 스타일 객체 (HTML style 속성)
*/
style?: React.CSSProperties;
/**
* 아이콘 크기
*
* @default 'md'
*/
size?: IconSize;
/**
* 색상 (Tailwind 클래스 또는 CSS 색상)
*/
color?: string;
/**
* 회전 애니메이션 활성화
*/
spin?: boolean;
/**
* 펄스 애니메이션 활성화 (8단계 회전)
*/
pulse?: boolean;
/**
* 고정 너비 (아이콘 정렬 시 유용)
*/
fixedWidth?: boolean;
/**
* 접근성 레이블 (자동 생성 가능)
*/
ariaLabel?: string;
}
/**
* Font Awesome 아이콘 컴포넌트
*
* Font Awesome 5/6 버전과 호환되며 다양한 props를 지원합니다.
*
* @example
* // 기본 사용
* <Icon name="fa-user" />
*
* // enum 사용 (타입 안전)
* <Icon name={IconName.Search} />
*
* // 스타일 및 크기 지정
* <Icon name={IconName.Heart} style="regular" size="2x" />
*
* // 애니메이션
* <Icon name={IconName.Spinner} spin />
* <Icon name={IconName.CircleNotch} pulse />
*
* // 색상 지정
* <Icon name={IconName.Star} color="text-yellow-500" />
*
* // 접근성
* <Icon name={IconName.User} ariaLabel="사용자 프로필" />
*/
export declare const Icon: React.FC<IconProps>;
@@ -0,0 +1,123 @@
/**
* Font Awesome 아이콘 스타일
*/
export type IconStyle = 'solid' | 'regular' | 'light' | 'duotone' | 'brands';
/**
* Font Awesome 아이콘 크기
*/
export type IconSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2x' | '3x' | '4x' | '5x';
/**
* 자주 사용되는 Font Awesome 아이콘 이름
*
* @example
* // 사용 예시
* <Icon name="user" />
* <Icon name="search" />
* <Icon name="shopping-cart" />
*/
export declare enum IconName {
User = "fa-user",
Users = "fa-users",
UserCircle = "fa-user-circle",
UserPlus = "fa-user-plus",
UserMinus = "fa-user-minus",
UserShield = "fa-user-shield",
Search = "fa-search",
Edit = "fa-edit",
Pencil = "fa-pencil-alt",
Trash = "fa-trash",
Save = "fa-save",
Plus = "fa-plus",
Minus = "fa-minus",
Check = "fa-check",
Times = "fa-times",
Download = "fa-download",
Upload = "fa-upload",
Copy = "fa-copy",
ExternalLink = "fa-external-link-alt",
Home = "fa-home",
CaretRight = "fa-caret-right",
CaretDown = "fa-caret-down",
ChevronLeft = "fa-chevron-left",
ChevronRight = "fa-chevron-right",
ChevronUp = "fa-chevron-up",
ChevronDown = "fa-chevron-down",
AngleLeft = "fa-angle-left",
AngleRight = "fa-angle-right",
AngleUp = "fa-angle-up",
AngleDown = "fa-angle-down",
ArrowUp = "fa-arrow-up",
ArrowDown = "fa-arrow-down",
ArrowLeft = "fa-arrow-left",
ArrowRight = "fa-arrow-right",
Bars = "fa-bars",
EllipsisVertical = "fa-ellipsis-v",
EllipsisHorizontal = "fa-ellipsis-h",
CheckCircle = "fa-check-circle",
TimesCircle = "fa-times-circle",
ExclamationCircle = "fa-exclamation-circle",
ExclamationTriangle = "fa-exclamation-triangle",
InfoCircle = "fa-info-circle",
QuestionCircle = "fa-question-circle",
XCircle = "fa-times-circle",
ShoppingCart = "fa-shopping-cart",
ShoppingBag = "fa-shopping-bag",
CreditCard = "fa-credit-card",
Tag = "fa-tag",
Tags = "fa-tags",
File = "fa-file",
FileAlt = "fa-file-alt",
Folder = "fa-folder",
FolderOpen = "fa-folder-open",
Envelope = "fa-envelope",
Phone = "fa-phone",
Comment = "fa-comment",
Comments = "fa-comments",
Cog = "fa-cog",
Cogs = "fa-cogs",
Settings = "fa-cog",
Wrench = "fa-wrench",
Sliders = "fa-sliders-h",
Image = "fa-image",
Images = "fa-images",
Video = "fa-video",
Camera = "fa-camera",
Heart = "fa-heart",
Star = "fa-star",
ThumbsUp = "fa-thumbs-up",
ThumbsDown = "fa-thumbs-down",
Share = "fa-share",
Clock = "fa-clock",
Calendar = "fa-calendar",
CalendarAlt = "fa-calendar-alt",
Lock = "fa-lock",
Unlock = "fa-unlock",
Eye = "fa-eye",
EyeSlash = "fa-eye-slash",
Bell = "fa-bell",
Flag = "fa-flag",
Map = "fa-map",
MapMarker = "fa-map-marker-alt",
Globe = "fa-globe",
Link = "fa-link",
Unlink = "fa-unlink",
Sun = "fa-sun",
Moon = "fa-moon",
ChartBar = "fa-chart-bar",
ChartLine = "fa-chart-line",
ChartPie = "fa-chart-pie",
ChartArea = "fa-chart-area",
Spinner = "fa-spinner",
CircleNotch = "fa-circle-notch",
CheckBadge = "fa-badge-check",
Cube = "fa-cube",
Cubes = "fa-cubes",
Plug = "fa-plug",
PuzzlePiece = "fa-puzzle-piece",
Palette = "fa-palette"
}
/**
* 문자열 아이콘 이름을 IconName enum으로 매핑합니다.
* JSON 레이아웃에서 문자열로 아이콘 이름을 지정할 때 사용합니다.
*/
export declare const iconNameMap: Record<string, IconName>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface ImgProps extends React.ImgHTMLAttributes<HTMLImageElement> {
}
/**
* 기본 이미지 컴포넌트
*/
export declare const Img: React.FC<ImgProps>;
@@ -0,0 +1,15 @@
import { default as React } from 'react';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
}
/**
* 기본 입력 필드 컴포넌트
*
* IME(한글 등) 조합 중에는 외부 onChange 이벤트를 발생시키지 않습니다.
* 내부 로컬 상태를 사용하여 입력을 처리하고, 조합이 완료되면 외부에 알립니다.
*
* forwardRef를 사용하여 외부에서 ref로 input 요소에 접근할 수 있습니다.
* 예: indeterminate 상태 설정 시 ref.current.indeterminate = true
*/
export declare const Input: React.ForwardRefExoticComponent<InputProps & React.RefAttributes<HTMLInputElement>>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {
}
/**
* 기본 레이블 컴포넌트
*/
export declare const Label: React.FC<LabelProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface LiProps extends React.LiHTMLAttributes<HTMLLIElement> {
}
/**
* 기본 li(목록 항목) 컴포넌트
*/
export declare const Li: React.FC<LiProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface NavProps extends React.HTMLAttributes<HTMLElement> {
}
/**
* 기본 nav 컴포넌트
*/
export declare const Nav: React.FC<NavProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface OlProps extends React.HTMLAttributes<HTMLOListElement> {
}
/**
* 기본 ol(순서있는 목록) 컴포넌트
*/
export declare const Ol: React.FC<OlProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface OptgroupProps extends React.OptgroupHTMLAttributes<HTMLOptGroupElement> {
}
/**
* 기본 optgroup 컴포넌트 (Select 내부에서 옵션 그룹화)
*/
export declare const Optgroup: React.FC<OptgroupProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface OptionProps extends React.OptionHTMLAttributes<HTMLOptionElement> {
}
/**
* 기본 option 컴포넌트 (Select 내부에서 사용)
*/
export declare const Option: React.FC<OptionProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface PProps extends React.HTMLAttributes<HTMLParagraphElement> {
}
/**
* 기본 p(단락) 컴포넌트
*/
export declare const P: React.FC<PProps>;
@@ -0,0 +1,10 @@
import { default as React } from 'react';
export interface PreProps extends React.HTMLAttributes<HTMLPreElement> {
}
/**
* 기본 pre 컴포넌트
*
* 서식이 지정된 텍스트를 표시하기 위한 기본 컴포넌트입니다.
* HTML <pre> 태그를 래핑합니다.
*/
export declare const Pre: React.FC<PreProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface SectionProps extends React.HTMLAttributes<HTMLElement> {
}
/**
* 기본 section 컴포넌트
*/
export declare const Section: React.FC<SectionProps>;
@@ -0,0 +1,23 @@
import { default as React } from 'react';
export interface SelectOption {
value: string | number;
label: string;
disabled?: boolean;
}
export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectElement>, 'onChange'> {
label?: string;
error?: string;
options?: SelectOption[] | string[];
onChange?: (e: React.ChangeEvent<HTMLSelectElement> | {
target: {
value: string | number;
};
}) => void;
}
/**
* 커스텀 Select 컴포넌트
*
* options prop을 사용하여 드롭다운 메뉴를 생성합니다.
* 둥근 모서리, 그림자, 체크마크가 있는 커스텀 스타일을 지원합니다.
*/
export declare const Select: React.FC<SelectProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface SpanProps extends React.HTMLAttributes<HTMLSpanElement> {
}
/**
* 기본 span 컴포넌트
*/
export declare const Span: React.FC<SpanProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface SvgProps extends React.SVGAttributes<SVGSVGElement> {
}
/**
* 기본 svg 컴포넌트
*/
export declare const Svg: React.FC<SvgProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface TableProps extends React.TableHTMLAttributes<HTMLTableElement> {
}
/**
* 기본 table 컴포넌트
*/
export declare const Table: React.FC<TableProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface TbodyProps extends React.HTMLAttributes<HTMLTableSectionElement> {
}
/**
* 기본 tbody 컴포넌트
*/
export declare const Tbody: React.FC<TbodyProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface TdProps extends React.TdHTMLAttributes<HTMLTableCellElement> {
}
/**
* 기본 td(테이블 데이터 셀) 컴포넌트
*/
export declare const Td: React.FC<TdProps>;
@@ -0,0 +1,12 @@
import { default as React } from 'react';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
label?: string;
error?: string;
}
/**
* 기본 텍스트 영역 컴포넌트
*
* IME(한글 등) 조합 중에는 외부 onChange 이벤트를 발생시키지 않습니다.
* 내부 로컬 상태를 사용하여 입력을 처리하고, 조합이 완료되면 외부에 알립니다.
*/
export declare const Textarea: React.FC<TextareaProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface TfootProps extends React.HTMLAttributes<HTMLTableSectionElement> {
}
/**
* 기본 tfoot 컴포넌트
*/
export declare const Tfoot: React.FC<TfootProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface ThProps extends React.ThHTMLAttributes<HTMLTableCellElement> {
}
/**
* 기본 th(테이블 헤더 셀) 컴포넌트
*/
export declare const Th: React.FC<ThProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface TheadProps extends React.HTMLAttributes<HTMLTableSectionElement> {
}
/**
* 기본 thead 컴포넌트
*/
export declare const Thead: React.FC<TheadProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface TrProps extends React.HTMLAttributes<HTMLTableRowElement> {
}
/**
* 기본 tr(테이블 행) 컴포넌트
*/
export declare const Tr: React.FC<TrProps>;
@@ -0,0 +1,7 @@
import { default as React } from 'react';
export interface UlProps extends React.HTMLAttributes<HTMLUListElement> {
}
/**
* 기본 ul(순서없는 목록) 컴포넌트
*/
export declare const Ul: React.FC<UlProps>;
@@ -0,0 +1,43 @@
/**
* 기본 HTML 매핑 컴포넌트 Export
*
* DOM 요소에 직접 매핑되는 기본 컴포넌트들
*/
export { Button, type ButtonProps } from './Button';
export { FileInput, type FileInputProps } from './FileInput';
export { Input, type InputProps } from './Input';
export { Textarea, type TextareaProps } from './Textarea';
export { Label, type LabelProps } from './Label';
export { Div, type DivProps } from './Div';
export { Span, type SpanProps } from './Span';
export { P, type PProps } from './P';
export { Img, type ImgProps } from './Img';
export { H1, type H1Props } from './H1';
export { H2, type H2Props } from './H2';
export { H3, type H3Props } from './H3';
export { H4, type H4Props } from './H4';
export { Ul, type UlProps } from './Ul';
export { Ol, type OlProps } from './Ol';
export { Li, type LiProps } from './Li';
export { A, type AProps } from './A';
export { Form, type FormProps } from './Form';
export { Select, type SelectProps } from './Select';
export { Option, type OptionProps } from './Option';
export { Optgroup, type OptgroupProps } from './Optgroup';
export { Checkbox, type CheckboxProps } from './Checkbox';
export { Table, type TableProps } from './Table';
export { Thead, type TheadProps } from './Thead';
export { Tbody, type TbodyProps } from './Tbody';
export { Tfoot, type TfootProps } from './Tfoot';
export { Tr, type TrProps } from './Tr';
export { Th, type ThProps } from './Th';
export { Td, type TdProps } from './Td';
export { Nav, type NavProps } from './Nav';
export { Section, type SectionProps } from './Section';
export { Svg, type SvgProps } from './Svg';
export { Icon, type IconProps } from './Icon';
export { Code, type CodeProps } from './Code';
export { Pre, type PreProps } from './Pre';
export { Fragment, type FragmentProps } from './Fragment';
export { Hr, type HrProps } from './Hr';
export { IconName, type IconStyle, type IconSize } from './IconTypes';
@@ -0,0 +1,45 @@
import { default as React, ReactNode } from 'react';
export interface AccordionProps {
/** 기본 열림 상태 */
defaultOpen?: boolean;
/** 외부에서 열림 상태 제어 */
isOpen?: boolean;
/** 열림 상태 변경 콜백 */
onToggle?: (isOpen: boolean) => void;
/** 추가 클래스명 */
className?: string;
/** 인라인 스타일 */
style?: React.CSSProperties;
/** 자식 요소 (trigger, content 슬롯) */
children?: ReactNode;
/** 비활성화 여부 */
disabled?: boolean;
}
/**
* Accordion 집합 컴포넌트
*
* 접기/펼치기가 가능한 아코디언 UI를 제공합니다.
* trigger 슬롯과 content 슬롯을 통해 헤더와 내용을 정의합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Accordion",
* "props": { "defaultOpen": false },
* "children": [
* {
* "slot": "trigger",
* "type": "basic",
* "name": "Div",
* "children": [{ "type": "basic", "name": "Span", "text": "제목" }]
* },
* {
* "slot": "content",
* "type": "basic",
* "name": "Div",
* "children": [{ "type": "basic", "name": "P", "text": "내용" }]
* }
* ]
* }
*/
export declare const Accordion: React.FC<AccordionProps>;
@@ -0,0 +1,61 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
export interface ActionMenuItem {
id: string | number;
label?: string;
iconName?: IconName;
onClick?: () => void;
disabled?: boolean;
variant?: 'default' | 'danger';
/** 구분선 여부 (true면 구분선으로 렌더링) */
divider?: boolean;
/** 행 데이터의 필드 경로로 disabled 여부를 결정 (값이 falsy면 disabled) */
disabledField?: string;
/** 조건부 표시 (false면 아이템 숨김, 엔진이 표현식 평가 후 boolean 전달) */
if?: boolean;
}
export interface ActionMenuProps {
items: ActionMenuItem[];
triggerLabel?: string;
triggerIconName?: IconName;
position?: 'left' | 'right';
className?: string;
style?: React.CSSProperties;
/**
* 커스텀 트리거 콘텐츠
*
* children이 제공되면 기본 Button 트리거 대신 children을 클릭 트리거로 사용합니다.
* 레이아웃 JSON에서 ActionMenu의 children으로 정의한 컴포넌트가 트리거가 됩니다.
*/
children?: React.ReactNode;
/**
* 메뉴 아이템 클릭 시 호출되는 콜백
* JSON 레이아웃의 actions에서 onItemClick 이벤트로 바인딩됨
*
* @param itemId - 클릭된 아이템의 id
* @param item - 클릭된 아이템 전체 객체
*/
onItemClick?: (itemId: string | number, item: ActionMenuItem) => void;
}
/**
* ActionMenu 집합 컴포넌트
*
* 드롭다운 형태의 액션 메뉴 컴포넌트입니다.
* 트리거 버튼과 메뉴 아이템 목록을 제공합니다.
*
* 기본 컴포넌트 조합: Button + Div + Span + Icon
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "ActionMenu",
* "props": {
* "triggerLabel": "작업",
* "items": [
* {"id": 1, "label": "수정", "iconName": "pencil"},
* {"id": 2, "label": "삭제", "iconName": "trash", "variant": "danger"}
* ]
* }
* }
*/
export declare const ActionMenu: React.FC<ActionMenuProps>;
@@ -0,0 +1,40 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
/**
* 빠른 링크 인터페이스
*/
export interface QuickLink {
id: string | number;
label: string;
url: string;
iconName?: IconName;
}
/**
* AdminFooter Props
*/
export interface AdminFooterProps {
copyright?: string;
version?: string;
quickLinks?: QuickLink[];
className?: string;
copyrightModalId?: string;
changelogModalId?: string;
}
/**
* AdminFooter 컴포넌트
*
* 관리자 푸터 - 버전 정보, 빠른 링크
*
* @example
* ```tsx
* <AdminFooter
* copyright="© 2026 G7"
* version="1.0.0"
* quickLinks={[
* { id: 1, label: '문서', url: '/docs', iconName: IconName.FileText },
* { id: 2, label: '지원', url: '/support', iconName: IconName.HelpCircle }
* ]}
* />
* ```
*/
export declare const AdminFooter: React.FC<AdminFooterProps>;
@@ -0,0 +1,55 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
/**
* 사용자 정보 인터페이스
*/
export interface AdminUser {
name: string;
email: string;
avatar?: string;
role?: string;
}
/**
* 알림 아이템 인터페이스
*/
export interface NotificationItem {
id: string | number;
title: string;
message: string;
time: string;
read?: boolean;
iconName?: IconName;
onClick?: () => void;
}
/**
* AdminHeader Props
*/
export interface AdminHeaderProps {
user: AdminUser;
notifications?: NotificationItem[];
onNotificationClick?: (id: string | number) => void;
onProfileClick?: () => void;
onLogoutClick?: () => void;
className?: string;
}
/**
* AdminHeader 컴포넌트
*
* 관리자 헤더 - 사용자 프로필, 알림 센터
*
* @example
* ```tsx
* <AdminHeader
* user={{
* name: '홍길동',
* email: 'hong@example.com',
* avatar: '/avatar.png',
* role: '관리자'
* }}
* notifications={[
* { id: 1, title: '새 댓글', message: '게시물에 댓글이 달렸습니다', time: '5분 전' }
* ]}
* />
* ```
*/
export declare const AdminHeader: React.FC<AdminHeaderProps>;
@@ -0,0 +1,57 @@
import { default as React } from 'react';
/**
* 메뉴 아이템 인터페이스 (API 응답 구조)
*/
export interface MenuItem {
id: string | number;
name: string | {
ko: string;
en: string;
};
slug: string;
url?: string | null;
icon?: string;
children?: MenuItem[];
is_active?: boolean;
module_id?: number | null;
}
/**
* AdminSidebar Props
*/
export interface AdminSidebarProps {
logo?: string;
logoAlt?: string;
menu: MenuItem[];
collapsed?: boolean;
onToggleCollapse?: () => void;
className?: string;
/** 현재 로케일 (다국어 메뉴 이름 표시용). 미지정 시 G7Core.locale.current() 자동 사용 */
currentLocale?: string;
}
/**
* AdminSidebar 컴포넌트
*
* 관리자 사이드바 - 계층형 메뉴, 접기/펼치기 기능 제공
*
* @example
* ```tsx
* <AdminSidebar
* logo="/logo.png"
* menu={[
* { id: 1, name: { ko: '대시보드', en: 'Dashboard' }, slug: 'dashboard', url: '/admin', icon: 'fas fa-tachometer-alt' },
* {
* id: 2,
* name: { ko: '콘텐츠', en: 'Content' },
* slug: 'content',
* icon: 'fas fa-file-text',
* children: [
* { id: 21, name: { ko: '게시물', en: 'Posts' }, slug: 'posts', url: '/admin/posts', icon: 'fas fa-list' },
* { id: 22, name: { ko: '페이지', en: 'Pages' }, slug: 'pages', url: '/admin/pages', icon: 'fas fa-file' }
* ]
* }
* ]}
* collapsed={false}
* />
* ```
*/
export declare const AdminSidebar: React.FC<AdminSidebarProps>;
@@ -0,0 +1,52 @@
import { default as React } from 'react';
/**
* 알림 타입
*/
export type AlertType = 'info' | 'success' | 'warning' | 'error';
export interface AlertProps {
/**
* 알림 타입
*/
type: AlertType;
/**
* 알림 메시지
*/
message: string;
/**
* 닫기 버튼 표시 여부
*/
dismissible?: boolean;
/**
* 닫기 버튼 클릭 시 콜백
*/
onDismiss?: () => void;
/**
* 사용자 정의 클래스
*/
className?: string;
}
/**
* Alert 알림 컴포넌트
*
* 알림 메시지를 표시하는 composite 컴포넌트입니다.
* type에 따라 다른 색상과 아이콘을 표시하며 dismissible 옵션을 지원합니다.
*
* @example
* // 정보 알림
* <Alert type="info" message="정보 메시지입니다." />
*
* // 성공 알림 (닫기 버튼 포함)
* <Alert
* type="success"
* message="작업이 완료되었습니다."
* dismissible
* onDismiss={() => console.log('dismissed')}
* />
*
* // 경고 알림
* <Alert type="warning" message="주의가 필요합니다." />
*
* // 에러 알림
* <Alert type="error" message="오류가 발생했습니다." />
*/
export declare const Alert: React.FC<AlertProps>;
@@ -0,0 +1,35 @@
import { default as React } from 'react';
export interface AlertDialogProps {
isOpen: boolean;
onClose: () => void;
title: string;
message: string | React.ReactNode;
confirmText?: string;
onConfirm?: () => void;
confirmButtonVariant?: 'primary' | 'secondary' | 'danger' | 'ghost';
width?: string;
closeOnOverlay?: boolean;
}
/**
* AlertDialog 집합 컴포넌트
*
* Dialog 기반 단일 확인 알림 다이얼로그 컴포넌트.
* 사용자에게 정보를 전달하고 확인만 받습니다.
*
* 기본 컴포넌트 조합:
* - Dialog > P(message) + Button(확인)
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "AlertDialog",
* "props": {
* "isOpen": "{{dialogs.successAlert}}",
* "title": "성공",
* "message": "작업이 성공적으로 완료되었습니다.",
* "confirmText": "$t:common.confirm",
* "confirmButtonVariant": "primary"
* }
* }
*/
export declare const AlertDialog: React.FC<AlertDialogProps>;
@@ -0,0 +1,26 @@
import { default as React } from 'react';
export interface BadgeProps {
color?: string;
text?: string;
size?: 'sm' | 'md' | 'lg';
className?: string;
style?: React.CSSProperties;
}
/**
* Badge 집합 컴포넌트
*
* 색상 기반의 라벨 뱃지입니다. 상태, 타입 등의 분류를 시각적으로 표현합니다.
*
* 기본 컴포넌트 조합: Span
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Badge",
* "props": {
* "color": "blue",
* "text": "활성"
* }
* }
*/
export declare const Badge: React.FC<React.PropsWithChildren<BadgeProps>>;
@@ -0,0 +1,39 @@
import { default as React } from 'react';
export interface BreadcrumbItem {
label: string;
href?: string;
onClick?: () => void;
}
export interface BreadcrumbProps {
items: BreadcrumbItem[];
separator?: React.ReactNode;
showHome?: boolean;
homeHref?: string;
maxItems?: number;
className?: string;
}
/**
* Breadcrumb 집합 컴포넌트
*
* 현재 페이지의 경로를 계층적으로 표시하는 내비게이션 컴포넌트.
* separator 커스터마이징, showHome 옵션, maxItems로 중간 생략 기능 제공.
*
* 기본 컴포넌트 조합:
* - Nav > Div > A(링크) + Span(구분자)
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Breadcrumb",
* "props": {
* "items": [
* {"label": "대시보드", "href": "/admin"},
* {"label": "사용자 관리", "href": "/admin/users"},
* {"label": "사용자 목록"}
* ],
* "showHome": true,
* "maxItems": 4
* }
* }
*/
export declare const Breadcrumb: React.FC<BreadcrumbProps>;
@@ -0,0 +1,29 @@
import { default as React } from 'react';
export interface CardProps {
title?: string;
content?: string;
imageUrl?: string;
imageAlt?: string;
className?: string;
onClick?: () => void;
style?: React.CSSProperties;
}
/**
* Card 집합 컴포넌트
*
* 기본 컴포넌트를 조합하여 카드 UI를 구성합니다.
* 레이아웃 JSON에서 title, content, imageUrl 등의 props만 전달하면
* 내부적으로 Div, H2, P, Img 컴포넌트를 조합하여 완성된 카드를 렌더링합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Card",
* "props": {
* "title": "사용자 정보",
* "content": "홍길동 (hong@example.com)",
* "imageUrl": "/avatar.png"
* }
* }
*/
export declare const Card: React.FC<CardProps>;
@@ -0,0 +1,100 @@
import { default as React } from 'react';
import { ActionMenuItem } from './ActionMenu';
/**
* CardGrid 셀 자식 요소 타입
*/
export interface CardGridCellChild {
id?: string;
type: 'basic' | 'composite';
name: string;
props?: Record<string, any>;
text?: string;
children?: CardGridCellChild[];
condition?: string;
if?: string;
iteration?: {
source: string;
item_var?: string;
index_var?: string;
};
actions?: any[];
}
/**
* 카드 컬럼 정의 (DataGrid의 컬럼 패턴과 동일)
*/
export interface CardGridColumn {
id: string;
cellChildren?: CardGridCellChild[];
}
/**
* CardGrid Props 인터페이스
*/
export interface CardGridProps {
data?: any[];
cardColumns?: CardGridColumn[];
gridColumns?: number;
gap?: number;
responsiveColumns?: {
sm?: number;
md?: number;
lg?: number;
xl?: number;
};
cardClassName?: string;
idField?: string;
pagination?: boolean;
pageSize?: number;
serverSidePagination?: boolean;
serverCurrentPage?: number;
serverTotalPages?: number;
alwaysShowPagination?: boolean;
onPageChange?: (page: number) => void;
rowActions?: ActionMenuItem[];
onRowAction?: (actionId: string | number, row: any) => void;
className?: string;
style?: React.CSSProperties;
emptyMessage?: string;
paginationInfoText?: string;
prevText?: string;
nextText?: string;
showSkeleton?: boolean;
skeletonCount?: number;
skeletonCellChildren?: CardGridCellChild[];
}
/**
* CardGrid 집합 컴포넌트
*
* 카드 레이아웃으로 데이터를 표시하는 그리드 컴포넌트입니다.
* DataGrid의 cellChildren 패턴을 사용하여 카드 내용을 JSON으로 정의할 수 있습니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "type": "composite",
* "name": "CardGrid",
* "props": {
* "data": "{{boards.data.data}}",
* "columns": 3,
* "gap": 4,
* "pagination": true,
* "pageSize": 12,
* "cellChildren": [
* {
* "type": "basic",
* "name": "Div",
* "props": {
* "className": "bg-white dark:bg-gray-800 rounded-lg p-6"
* },
* "children": [
* {
* "type": "basic",
* "name": "H3",
* "text": "{{row.name}}"
* }
* ]
* }
* ]
* }
* }
*/
export declare const CardGrid: React.FC<CardGridProps>;
@@ -0,0 +1,66 @@
import { default as React } from 'react';
/**
* 카테고리 노드 인터페이스 (CategoryResource API 응답 기반)
*/
export interface CategoryNode {
id: number;
name: string;
localized_name?: string;
path?: string;
products_count?: number;
children_count?: number;
children?: CategoryNode[];
}
export interface CategoryTreeProps {
/** 카테고리 트리 데이터 (CategoryResource API 응답) */
data?: CategoryNode[];
/** 펼쳐진 노드 ID 배열 */
expandedIds?: number[];
/** 선택된 노드 ID 배열 */
selectedIds?: number[];
/** 검색 키워드 (하이라이트용) */
searchKeyword?: string;
/** 상품 수 표시 여부 */
showProductCount?: boolean;
/** 체크박스 선택 기능 활성화 */
selectable?: boolean;
/** 추가 클래스명 */
className?: string;
/** 펼치기/접기 콜백: (expandedIds: number[]) => void */
onToggle?: (expandedIds: number[]) => void;
/** 선택 변경 콜백: (selectedIds: number[]) => void */
onSelectionChange?: (selectedIds: number[]) => void;
}
/**
* CategoryTree 집합 컴포넌트
*
* 계층형 카테고리 트리를 렌더링하고 체크박스로 카테고리를 선택할 수 있습니다.
* expandedIds와 selectedIds를 외부에서 제어하는 Controlled 컴포넌트입니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "CategoryTree",
* "props": {
* "data": "{{categories?.data?.data ?? []}}",
* "expandedIds": "{{_local.categoryExpandedIds ?? []}}",
* "selectedIds": "{{_local.categorySearchSelected ?? []}}",
* "searchKeyword": "{{_local.categorySearchKeyword ?? ''}}",
* "showProductCount": true,
* "selectable": true
* },
* "actions": [
* {
* "event": "onToggle",
* "handler": "setState",
* "params": { "target": "_local", "categoryExpandedIds": "{{$args[0]}}" }
* },
* {
* "event": "onSelectionChange",
* "handler": "setState",
* "params": { "target": "_local", "categorySearchSelected": "{{$args[0]}}" }
* }
* ]
* }
*/
export declare const CategoryTree: React.FC<CategoryTreeProps>;
@@ -0,0 +1,62 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
export interface ChipCheckboxProps {
value: string;
checked?: boolean;
icon?: IconName | string;
label: string;
variant?: 'green' | 'orange' | 'yellow' | 'gray' | 'blue';
customColor?: string;
className?: string;
style?: React.CSSProperties;
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
}
/**
* ChipCheckbox 집합 컴포넌트
*
* 체크박스 + 아이콘 + 라벨을 조합한 칩 형태의 체크박스 컴포넌트입니다.
* 필터 UI에서 주로 사용되며, 선택 여부에 따라 스타일이 변경됩니다.
*
* 기본 컴포넌트 조합: Div + Label + Input(checkbox) + Icon
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "ChipCheckbox",
* "props": {
* "value": "pending_order",
* "checked": "{{(_local.filter.orderStatus || []).includes('pending_order')}}",
* "icon": "clock",
* "label": "$t:sirsoft-ecommerce.admin.order.status.waiting",
* "variant": "gray"
* },
* "actions": [
* {
* "type": "change",
* "handler": "sirsoft-ecommerce.toggleArrayValue",
* "params": {
* "target": "_local",
* "path": "filter.orderStatus",
* "value": "pending_order"
* }
* }
* ]
* }
*
* @example
* // customColor 사용 예시 (임의의 hex 색상)
* {
* "name": "ChipCheckbox",
* "props": {
* "value": "{{String(label.id)}}",
* "checked": "{{(assignments ?? []).some(a => a.label_id === label.id)}}",
* "label": "{{$localized(label.name)}}",
* "customColor": "{{label.color ?? '#3B82F6'}}"
* }
* }
*
* @remarks
* - variant: green (연두색, 긍정 상태), orange (주황색, 진행 중), yellow (노란색, 회수), gray (회색, 대기/보류), blue (기본값)
* - customColor: 임의의 hex 색상 코드 지정 시 variant 무시, 다크모드/호버 자동 처리
*/
export declare const ChipCheckbox: React.FC<ChipCheckboxProps>;
@@ -0,0 +1,14 @@
import { default as React } from 'react';
export interface CodeEditorProps {
value: string;
onChange?: (event: {
target: {
value: string;
};
}) => void;
language?: string;
height?: string;
readOnly?: boolean;
theme?: 'vs-dark' | 'vs-light';
}
export declare const CodeEditor: React.FC<CodeEditorProps>;
@@ -0,0 +1,100 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
/**
* 전역 window 타입 확장
* 그누보드7 Core의 AuthManager에 접근하기 위한 타입 선언
*/
declare global {
interface Window {
G7Core?: {
AuthManager?: {
getInstance: () => {
getUser: () => {
uuid: string;
[key: string]: any;
} | null;
};
};
};
}
}
export interface ColumnItem {
field: string;
header: string;
required?: boolean;
visible?: boolean;
}
export interface ColumnSelectorProps {
/** 컴포넌트 고유 ID (레이아웃 JSON의 id 값, localStorage 키 생성에 사용) */
id?: string;
columns: ColumnItem[];
visibleColumns?: string[];
onColumnVisibilityChange?: (visibleFields: string[]) => void;
triggerLabel?: string;
triggerIconName?: IconName;
position?: 'left' | 'right';
className?: string;
style?: React.CSSProperties;
requiredText?: string;
/** 드롭다운 메뉴 상단 제목 */
menuTitle?: string;
/** 드롭다운 메뉴 상단 설명 */
menuDescription?: string;
/** 기본 표시 컬럼 (localStorage에 값이 없을 때 사용) */
defaultColumns?: string[];
/** 트리거 버튼에 적용할 추가 className (기존 스타일과 병합됨) */
triggerClassName?: string;
/** 라벨 Span에 적용할 추가 className (기존 스타일과 병합됨) */
labelClassName?: string;
/**
* 동적 컬럼 배열 (v1.4.0+)
*
* 기존 columns 배열에 동적으로 병합될 컬럼들입니다.
* dynamicColumnsInsertAfter가 지정된 경우 해당 필드 뒤에 삽입되고,
* 그렇지 않으면 columns 배열 끝에 추가됩니다.
*/
dynamicColumns?: ColumnItem[];
/**
* 동적 컬럼 삽입 위치를 지정하는 필드명
* 해당 필드 뒤에 dynamicColumns가 삽입됩니다.
* 지정하지 않으면 columns 끝에 추가됩니다.
*/
dynamicColumnsInsertAfter?: string;
}
/**
* ColumnSelector 집합 컴포넌트
*
* 테이블 컬럼의 표시/숨김을 선택할 수 있는 드롭다운 컴포넌트입니다.
* required 속성이 있는 컬럼은 항상 표시되며 비활성화됩니다.
*
* 기본 컴포넌트 조합: Button + Div + Span + Icon + Checkbox
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "ColumnSelector",
* "props": {
* "columns": [
* {"field": "id", "header": "$t:admin.users.columns.id", "required": true},
* {"field": "name", "header": "$t:admin.users.columns.name", "required": true},
* {"field": "email", "header": "$t:admin.users.columns.email"},
* {"field": "status", "header": "$t:admin.users.columns.status"}
* ],
* "visibleColumns": "{{_local.visibleColumns}}",
* "triggerLabel": "$t:common.column_selector",
* "requiredText": "$t:common.required"
* },
* "actions": [
* {
* "event": "onColumnVisibilityChange",
* "type": "change",
* "handler": "setState",
* "params": {
* "target": "local",
* "visibleColumns": "{{$args[0]}}"
* }
* }
* ]
* }
*/
export declare const ColumnSelector: React.FC<ColumnSelectorProps>;
@@ -0,0 +1,43 @@
import { default as React } from 'react';
export interface ConfirmDialogProps {
isOpen: boolean;
onClose: () => void;
title: string;
message: string | React.ReactNode;
confirmText?: string;
cancelText?: string;
onConfirm: () => void;
onCancel?: () => void;
confirmButtonVariant?: 'primary' | 'secondary' | 'danger' | 'ghost';
cancelButtonVariant?: 'primary' | 'secondary' | 'danger' | 'ghost';
width?: string;
closeOnOverlay?: boolean;
/** 로딩 중 여부 (확인 버튼 비활성화 및 텍스트 변경) */
isLoading?: boolean;
/** 로딩 중 확인 버튼에 표시할 텍스트 */
loadingText?: string;
}
/**
* ConfirmDialog 집합 컴포넌트
*
* Modal 기반 확인/취소 다이얼로그 컴포넌트.
* 사용자에게 확인을 요청하고 확인/취소 중 하나를 선택하도록 합니다.
*
* 기본 컴포넌트 조합:
* - Modal > P(message) + Button(확인) + Button(취소)
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "ConfirmDialog",
* "props": {
* "isOpen": "{{dialogs.deleteConfirm}}",
* "title": "삭제 확인",
* "message": "정말 이 항목을 삭제하시겠습니까?",
* "confirmText": "삭제",
* "cancelText": "$t:common.cancel",
* "confirmButtonVariant": "danger"
* }
* }
*/
export declare const ConfirmDialog: React.FC<ConfirmDialogProps>;
@@ -0,0 +1,301 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
import { ActionMenuItem } from './ActionMenu';
export interface DataGridCellChild {
id?: string;
type: 'basic' | 'composite';
name: string;
props?: Record<string, any>;
text?: string;
children?: DataGridCellChild[];
condition?: string;
}
export interface DataGridColumn {
field: string;
header: string;
width?: string;
sortable?: boolean;
hidden?: boolean;
required?: boolean;
render?: (value: any, row: any) => React.ReactNode;
cellChildren?: DataGridCellChild[];
}
/**
* 확장 행(Expandable Row)에 렌더링할 자식 컴포넌트 정의
* 레이아웃 JSON에서 사용됩니다.
*/
export interface DataGridExpandChildren {
id?: string;
type: 'basic' | 'composite';
name: string;
props?: Record<string, any>;
text?: string;
children?: DataGridExpandChildren[];
iteration?: {
source: string;
item_var?: string;
index_var?: string;
};
}
/**
* 서브 행(Sub Row)에 렌더링할 자식 컴포넌트 정의 (v1.6.0+)
*
* 각 데이터 행 아래에 추가 정보를 표시하는 병합된 행입니다.
* expandable row와 달리 항상 표시되거나 조건부로 표시됩니다.
* 모든 컬럼이 병합된 단일 셀로 렌더링됩니다.
*
* @example
* // 배송비 요약 표시
* {
* "subRowChildren": [
* {
* "type": "basic",
* "name": "Span",
* "props": { "className": "text-sm text-gray-500" },
* "text": "{{row.fee_summary}}"
* }
* ],
* "subRowCondition": "{{row.charge_policy !== 'free'}}"
* }
*/
export interface DataGridSubRowChildren {
id?: string;
type: 'basic' | 'composite';
name: string;
props?: Record<string, any>;
text?: string;
children?: DataGridSubRowChildren[];
condition?: string;
}
/**
* 푸터 행(Footer Row)의 각 셀 정의 (v1.19.0+)
*
* 테이블 하단에 합계/요약 행을 표시합니다.
* 각 셀은 특정 컬럼의 field에 매핑되거나, colSpan으로 여러 컬럼을 병합합니다.
*/
export interface DataGridFooterCell {
/** 매핑할 컬럼 field명 (이 필드의 컬럼 위치에 셀 배치) */
field?: string;
/** 병합할 컬럼 수 (field 미지정 시 사용) */
colSpan?: number;
/** 셀 CSS 클래스 */
className?: string;
/** 셀 내부에 렌더링할 컴포넌트 (cellChildren과 동일 구조) */
children?: DataGridCellChild[];
/** 단순 텍스트 (children 미사용 시) */
text?: string;
}
export interface DataGridProps {
columns: DataGridColumn[];
data: any[];
sortable?: boolean;
pagination?: boolean;
pageSize?: number;
onRowClick?: (row: any) => void;
className?: string;
style?: React.CSSProperties;
sortField?: string | null;
sortDirection?: 'asc' | 'desc';
onSortChange?: (field: string, direction: 'asc' | 'desc') => void;
selectable?: boolean;
selectedIds?: (string | number)[];
onSelectionChange?: (ids: (string | number)[]) => void;
idField?: string;
showColumnSelector?: boolean;
visibleColumns?: string[];
onColumnVisibilityChange?: (fields: string[]) => void;
responsiveBreakpoint?: number;
cardRenderer?: (row: any, columns: DataGridColumn[]) => React.ReactNode;
rowActions?: ActionMenuItem[];
onRowAction?: (actionId: string | number, row: any) => void;
alwaysShowPagination?: boolean;
serverSidePagination?: boolean;
serverCurrentPage?: number;
serverTotalPages?: number;
onPageChange?: (page: number) => void;
prevText?: string;
nextText?: string;
columnSelectorText?: string;
emptyMessage?: string;
actionsColumnHeader?: string;
requiredText?: string;
selectedCountText?: string;
loadErrorMessage?: string;
showFirstLast?: boolean;
expandable?: boolean;
expandedRowIds?: (string | number)[];
onExpandChange?: (ids: (string | number)[]) => void;
expandChildren?: DataGridExpandChildren[];
expandedRowRender?: (row: any) => React.ReactNode;
expandColumnWidth?: string;
expandIconExpanded?: IconName;
expandIconCollapsed?: IconName;
/** 행 단위 조건부 확장 필드명 — 해당 필드가 truthy인 행만 확장 가능 */
expandConditionField?: string;
/**
* 동적 컬럼 배열 (v1.4.0+)
*
* 기존 columns 배열에 동적으로 병합될 컬럼들입니다.
* insertAfterField가 지정된 경우 해당 필드 뒤에 삽입되고,
* 그렇지 않으면 columns 배열 끝에 추가됩니다.
*
* 모듈 핸들러의 resultTo 패턴과 함께 사용하여
* 환경설정 기반 동적 컬럼을 구현할 수 있습니다.
*
* @example
* // 레이아웃 JSON에서 init_action으로 동적 컬럼 생성
* {
* "handler": "sirsoft-ecommerce.buildProductColumns",
* "params": { ... },
* "resultTo": { "target": "_local", "key": "dynamicCols" }
* }
*
* // DataGrid에서 동적 컬럼 사용
* {
* "name": "DataGrid",
* "props": {
* "columns": [...],
* "dynamicColumns": "{{_local.dynamicCols}}"
* }
* }
*/
dynamicColumns?: DataGridColumn[];
/**
* 동적 컬럼 삽입 위치를 지정하는 필드명
* 해당 필드 뒤에 dynamicColumns가 삽입됩니다.
* 지정하지 않으면 columns 끝에 추가됩니다.
*/
dynamicColumnsInsertAfter?: string;
/**
* expandChildren에 전달할 추가 컨텍스트 (v1.5.0+)
*
* expandChildren 렌더링 시 row 외에 추가로 전달할 데이터입니다.
* 레이아웃 JSON에서 _local, _computed 값 등을 전달할 때 사용합니다.
*
* @example
* {
* "name": "DataGrid",
* "props": {
* "expandContext": {
* "optionColumns": "{{_local.optionColumns}}",
* "currencies": "{{_computed.optionCurrencyColumns}}"
* }
* }
* }
*/
expandContext?: Record<string, any>;
/**
* 부모 컴포넌트 컨텍스트 (내부 사용)
*
* DynamicRenderer에서 전달되며, expandChildren 내부 액션에서
* G7Core.state.setLocal()이 부모 상태를 업데이트할 수 있도록 합니다.
*/
__componentContext?: {
state?: any;
setState?: (updates: any) => void;
};
/**
* 서브 행에 렌더링할 컴포넌트 정의
*
* 각 데이터 행 아래에 추가 정보를 표시합니다.
* 모든 컬럼이 병합된 단일 셀로 렌더링됩니다.
* 이 prop이 없거나 빈 배열이면 서브 행이 표시되지 않습니다.
*
* @example
* // 배송비 요약을 서브 행으로 표시
* {
* "subRowChildren": [
* {
* "type": "basic",
* "name": "Span",
* "props": { "className": "text-sm text-gray-500" },
* "text": "배송비: {{row.fee_summary}}"
* }
* ]
* }
*/
subRowChildren?: DataGridSubRowChildren[];
/**
* 서브 행 표시 조건 (선택적)
*
* JavaScript 표현식으로, true일 때만 서브 행이 표시됩니다.
* row 객체에 접근할 수 있습니다.
*
* @example
* "{{row.charge_policy !== 'free'}}" // 무료 배송이 아닐 때만 표시
* "{{row.fee_summary}}" // fee_summary가 있을 때만 표시
*/
subRowCondition?: string;
/**
* 서브 행 셀의 CSS 클래스 (선택적)
*
* @default "px-6 py-2 bg-gray-50 dark:bg-gray-750"
*/
subRowClassName?: string;
/**
* 서브 행 렌더 함수 (선택적)
*
* subRowChildren 대신 함수로 서브 행 내용을 렌더링합니다.
* TypeScript/React 코드에서 직접 사용할 때 유용합니다.
*/
subRowRender?: (row: any) => React.ReactNode;
/**
* 푸터 행 셀 정의 (v1.19.0+)
*
* 테이블 하단에 합계/요약 행을 렌더링합니다.
* 각 셀은 field로 컬럼 위치에 매핑하거나 colSpan으로 병합합니다.
*
* @example
* {
* "footerCells": [
* { "field": "product_info", "text": "합계", "className": "font-bold" },
* { "field": "quantity", "text": "3개" },
* { "field": "subtotal", "text": "690,000원", "className": "font-bold" }
* ]
* }
*/
footerCells?: DataGridFooterCell[];
/**
* 푸터 행 CSS 클래스 (선택적)
*
* @default "bg-gray-50 dark:bg-gray-800/50 font-medium"
*/
footerClassName?: string;
/**
* 모바일 카드 뷰에서 푸터 렌더링용 컴포넌트 (선택적)
*
* 미지정 시 footerCells를 key-value 형태로 자동 렌더링합니다.
*/
footerCardChildren?: DataGridCellChild[];
}
/**
* DataGrid 집합 컴포넌트
*
* Table 기본 컴포넌트를 조합하여 데이터 그리드 UI를 구성합니다.
* 정렬, 필터, 페이지네이션, 체크박스 선택, 컬럼 선택, 반응형 카드 뷰 기능을 포함합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "DataGrid",
* "props": {
* "columns": [
* {"field": "name", "header": "$t:admin.users.name", "sortable": true, "required": true},
* {"field": "email", "header": "$t:admin.users.email", "required": true}
* ],
* "data": "{{users.data}}",
* "sortable": true,
* "pagination": true,
* "pageSize": 10,
* "selectable": true,
* "showColumnSelector": true,
* "prevText": "$t:common.prev",
* "nextText": "$t:common.next",
* "columnSelectorText": "$t:common.column_selector",
* "emptyMessage": "$t:common.no_data",
* "actionsColumnHeader": "$t:common.actions",
* "requiredText": "$t:common.required"
* }
* }
*/
export declare const DataGrid: React.FC<DataGridProps>;
@@ -0,0 +1,48 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
export interface DialogAction {
label: string;
onClick: () => void;
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
iconName?: IconName;
disabled?: boolean;
}
export interface DialogProps {
isOpen: boolean;
onClose: () => void;
title: string;
content: React.ReactNode;
actions?: DialogAction[];
width?: string;
closeOnOverlay?: boolean;
showCloseButton?: boolean;
className?: string;
style?: React.CSSProperties;
}
/**
* Dialog 집합 컴포넌트
*
* Modal의 특화 버전으로 제목 + 본문 + 액션 영역 구조를 표준화한 컴포넌트.
* Modal보다 더 구조화된 레이아웃 제공.
*
* 기본 컴포넌트 조합:
* - Modal > Div(header) > H2(title) + Button(close)
* - Div(body) > {content}
* - Div(footer) > Button[](actions)
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Dialog",
* "props": {
* "isOpen": "{{dialogs.confirm}}",
* "title": "확인",
* "content": "정말 삭제하시겠습니까?",
* "actions": [
* {"label": "취소", "variant": "secondary"},
* {"label": "삭제", "variant": "danger"}
* ]
* }
* }
*/
export declare const Dialog: React.FC<DialogProps>;
@@ -0,0 +1,38 @@
import { default as React } from 'react';
export interface DropdownItem {
label: string;
value: string;
onClick?: () => void;
disabled?: boolean;
}
export interface DropdownProps {
label: string;
items: DropdownItem[];
/** 아이템 클릭 시 호출되는 콜백. value 문자열을 전달합니다. */
onItemClick?: (value: string, item: DropdownItem) => void;
position?: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';
/** 드롭다운 스타일 변형 */
variant?: 'default' | 'text';
className?: string;
style?: React.CSSProperties;
}
/**
* Dropdown 집합 컴포넌트
*
* Button + Div 기본 컴포넌트를 조합하여 드롭다운 메뉴 UI를 구성합니다.
* 키보드 네비게이션 (Arrow Up/Down, Enter, Escape) 지원, 외부 클릭 감지 기능을 포함합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "Dropdown",
* "props": {
* "label": "작업",
* "items": [
* {"label": "수정", "value": "edit"},
* {"label": "삭제", "value": "delete"}
* ]
* }
* }
*/
export declare const Dropdown: React.FC<DropdownProps>;
@@ -0,0 +1,40 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
export interface DropdownButtonProps {
label?: string;
icon?: IconName | string;
iconPosition?: 'left' | 'right';
position?: 'left' | 'right';
className?: string;
style?: React.CSSProperties;
children?: React.ReactNode;
}
/**
* DropdownButton 집합 컴포넌트
*
* 드롭다운 형태의 버튼 컴포넌트입니다.
* ActionMenu와 유사하지만 children을 통해 자유롭게 메뉴 내용을 구성할 수 있습니다.
*
* 기본 컴포넌트 조합: Button + Div + Span + Icon
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "DropdownButton",
* "props": {
* "label": "더보기",
* "icon": "chevron-down",
* "iconPosition": "right",
* "className": "btn btn-outline btn-sm"
* },
* "children": [
* {
* "name": "DropdownItem",
* "props": {
* "label": "메뉴 1"
* }
* }
* ]
* }
*/
export declare const DropdownButton: React.FC<DropdownButtonProps>;
@@ -0,0 +1,63 @@
import { default as React } from 'react';
import { IconName } from '../basic/IconTypes';
export interface DropdownMenuItemProps {
label?: string;
icon?: IconName | string;
variant?: 'default' | 'danger';
disabled?: boolean;
divider?: boolean;
className?: string;
style?: React.CSSProperties;
onClick?: () => void;
}
/**
* DropdownMenuItem 집합 컴포넌트
*
* DropdownButton의 자식으로 사용되는 메뉴 아이템 컴포넌트입니다.
* ActionMenu의 아이템과 동일한 디자인을 사용합니다.
*
* 기본 컴포넌트 조합: Div + Icon + Span
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "name": "DropdownButton",
* "props": {
* "label": "작업",
* "icon": "chevron-down"
* },
* "children": [
* {
* "name": "DropdownMenuItem",
* "props": {
* "label": "수정",
* "icon": "pencil"
* },
* "actions": [
* {
* "type": "click",
* "handler": "navigate",
* "params": {
* "path": "/edit/{{id}}"
* }
* }
* ]
* },
* {
* "name": "DropdownMenuItem",
* "props": {
* "divider": true
* }
* },
* {
* "name": "DropdownMenuItem",
* "props": {
* "label": "삭제",
* "icon": "trash",
* "variant": "danger"
* }
* }
* ]
* }
*/
export declare const DropdownMenuItem: React.FC<DropdownMenuItemProps>;
@@ -0,0 +1,4 @@
import { default as React } from 'react';
import { DynamicFieldListProps } from './types';
export declare const DynamicFieldList: React.FC<DynamicFieldListProps>;
export default DynamicFieldList;
Loaded 100 of 3967 files, more files were not shown because too many files have changed in this diff. Show more