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

+1
View File
@@ -0,0 +1 @@
import './bootstrap';
+4
View File
@@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,501 @@
/**
* ActionDispatcher conditions 핸들러 테스트
*
* conditions 핸들러를 통한 조건부 액션 실행 테스트
*
* @since engine-v1.10.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ActionDispatcher, ActionDefinition } from '../template-engine/ActionDispatcher';
import { DataBindingEngine } from '../template-engine/DataBindingEngine';
// Mock 의존성
vi.mock('../template-engine/TranslationEngine', () => ({
TranslationEngine: {
getInstance: () => ({
resolveTranslations: (text: string) => text,
translate: (key: string) => key,
}),
},
}));
vi.mock('../auth/AuthManager', () => ({
AuthManager: {
getInstance: () => ({
getToken: () => null,
isAuthenticated: () => false,
}),
},
AuthType: { Bearer: 'Bearer' },
}));
vi.mock('../api/ApiClient', () => ({
getApiClient: () => ({
request: vi.fn().mockResolvedValue({ data: {} }),
}),
}));
// window.G7Core mock
const mockG7Core = {
state: {
getGlobal: vi.fn(() => ({})),
setGlobal: vi.fn(),
setLocal: vi.fn(),
getComputed: vi.fn(() => ({})),
},
modal: {
open: vi.fn(),
close: vi.fn(),
},
toast: {
show: vi.fn(),
},
router: {
navigate: vi.fn(),
},
devTools: undefined,
};
(global as any).window = {
G7Core: mockG7Core,
location: { href: '' },
history: { back: vi.fn(), forward: vi.fn() },
localStorage: {
getItem: vi.fn(),
setItem: vi.fn(),
},
};
describe('ActionDispatcher conditions 핸들러', () => {
let dispatcher: ActionDispatcher;
let executedActions: any[];
beforeEach(() => {
vi.clearAllMocks();
executedActions = [];
dispatcher = new ActionDispatcher({
navigate: vi.fn(),
router: {
navigate: vi.fn(),
} as any,
});
// executeAction을 spy하여 실행된 액션 추적
const originalExecuteAction = (dispatcher as any).executeAction.bind(dispatcher);
vi.spyOn(dispatcher as any, 'executeAction').mockImplementation(async (action: any, context: any) => {
executedActions.push({ handler: action.handler, params: action.params });
// setState, toast, navigate 등 기본 핸들러는 실제 실행하지 않고 기록만
if (['setState', 'toast', 'navigate', 'openModal', 'closeModal'].includes(action.handler)) {
return { success: true, handler: action.handler };
}
// conditions는 실제 로직 실행
if (action.handler === 'conditions') {
return originalExecuteAction(action, context);
}
return { success: true };
});
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('기본 if/else 체인', () => {
it('첫 번째 조건이 true면 해당 브랜치의 then 액션을 실행해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{action === 'edit'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/edit' } },
},
{
if: "{{action === 'delete'}}",
then: { type: 'click', handler: 'openModal', params: { id: 'delete_modal' } },
},
],
};
await dispatcher.dispatchAction(action, { data: { action: 'edit' } });
expect(executedActions).toHaveLength(2); // conditions + navigate
expect(executedActions[1]).toEqual({
handler: 'navigate',
params: { path: '/edit' },
});
});
it('두 번째 조건이 true면 해당 브랜치의 then 액션을 실행해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{action === 'edit'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/edit' } },
},
{
if: "{{action === 'delete'}}",
then: { type: 'click', handler: 'openModal', params: { id: 'delete_modal' } },
},
],
};
await dispatcher.dispatchAction(action, { data: { action: 'delete' } });
expect(executedActions).toHaveLength(2); // conditions + openModal
expect(executedActions[1]).toEqual({
handler: 'openModal',
params: { id: 'delete_modal' },
});
});
it('모든 조건이 false면 아무 액션도 실행하지 않아야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{action === 'edit'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/edit' } },
},
{
if: "{{action === 'delete'}}",
then: { type: 'click', handler: 'openModal', params: { id: 'delete_modal' } },
},
],
};
await dispatcher.dispatchAction(action, { data: { action: 'view' } });
// conditions만 실행되고 내부 액션은 실행되지 않음
expect(executedActions).toHaveLength(1);
expect(executedActions[0].handler).toBe('conditions');
});
it('else 브랜치 (if 없음)가 있으면 기본 액션으로 실행해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{action === 'edit'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/edit' } },
},
{
// else 브랜치 (if 없음)
then: { type: 'click', handler: 'toast', params: { message: '기본 액션' } },
},
],
};
await dispatcher.dispatchAction(action, { data: { action: 'unknown' } });
expect(executedActions).toHaveLength(2); // conditions + toast
expect(executedActions[1]).toEqual({
handler: 'toast',
params: { message: '기본 액션' },
});
});
});
describe('$args 지원', () => {
it('$args[0]로 전달된 값으로 조건을 평가해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{$args[0] === 'edit'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/edit' } },
},
{
if: "{{$args[0] === 'delete'}}",
then: { type: 'click', handler: 'openModal', params: { id: 'delete_modal' } },
},
],
};
await dispatcher.dispatchAction(action, { data: { $args: ['edit'] } });
expect(executedActions).toHaveLength(2);
expect(executedActions[1]).toEqual({
handler: 'navigate',
params: { path: '/edit' },
});
});
});
describe('AND 그룹 조건', () => {
it('AND 그룹의 모든 조건이 true면 브랜치를 실행해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: {
and: ['{{user.isLoggedIn}}', '{{user.hasPermission}}'],
},
then: { type: 'click', handler: 'navigate', params: { path: '/premium' } },
},
{
then: { type: 'click', handler: 'toast', params: { type: 'error', message: '접근 권한 없음' } },
},
],
};
await dispatcher.dispatchAction(action, {
data: { user: { isLoggedIn: true, hasPermission: true } },
});
expect(executedActions).toHaveLength(2);
expect(executedActions[1]).toEqual({
handler: 'navigate',
params: { path: '/premium' },
});
});
it('AND 그룹의 하나라도 false면 다음 브랜치로 넘어가야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: {
and: ['{{user.isLoggedIn}}', '{{user.hasPermission}}'],
},
then: { type: 'click', handler: 'navigate', params: { path: '/premium' } },
},
{
then: { type: 'click', handler: 'toast', params: { type: 'error', message: '접근 권한 없음' } },
},
],
};
await dispatcher.dispatchAction(action, {
data: { user: { isLoggedIn: true, hasPermission: false } },
});
expect(executedActions).toHaveLength(2);
expect(executedActions[1]).toEqual({
handler: 'toast',
params: { type: 'error', message: '접근 권한 없음' },
});
});
});
describe('OR 그룹 조건', () => {
it('OR 그룹의 하나라도 true면 브랜치를 실행해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: {
or: ['{{user.isAdmin}}', '{{user.isManager}}'],
},
then: { type: 'click', handler: 'navigate', params: { path: '/admin' } },
},
{
then: { type: 'click', handler: 'navigate', params: { path: '/user' } },
},
],
};
await dispatcher.dispatchAction(action, {
data: { user: { isAdmin: false, isManager: true } },
});
expect(executedActions).toHaveLength(2);
expect(executedActions[1]).toEqual({
handler: 'navigate',
params: { path: '/admin' },
});
});
});
describe('중첩 AND/OR 조건', () => {
it('OR 안에 AND가 중첩된 조건을 평가할 수 있어야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: {
or: [
'{{user.isSuperAdmin}}',
{
and: ['{{user.isAdmin}}', "{{user.department === 'sales'}}"],
},
],
},
then: { type: 'click', handler: 'navigate', params: { path: '/sales-dashboard' } },
},
{
then: { type: 'click', handler: 'navigate', params: { path: '/home' } },
},
],
};
// admin + sales 부서
await dispatcher.dispatchAction(action, {
data: { user: { isSuperAdmin: false, isAdmin: true, department: 'sales' } },
});
expect(executedActions[1]).toEqual({
handler: 'navigate',
params: { path: '/sales-dashboard' },
});
});
});
describe('then 배열 (sequence)', () => {
it('then이 배열이면 순차적으로 실행해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{action === 'delete'}}",
then: [
{ type: 'click', handler: 'setState', params: { target: '_local', deleteTargetId: '123' } },
{ type: 'click', handler: 'openModal', params: { id: 'delete_confirm_modal' } },
],
},
],
};
// handleSequence를 spy
const handleSequenceSpy = vi.spyOn(dispatcher as any, 'handleSequence');
await dispatcher.dispatchAction(action, { data: { action: 'delete' } });
// handleSequence가 호출되었는지 확인
expect(handleSequenceSpy).toHaveBeenCalled();
});
});
describe('에러 처리', () => {
it('conditions가 없으면 경고를 출력하고 종료해야 함', async () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
// conditions 없음
};
// 실제 executeAction 호출을 위해 spy 복원
vi.restoreAllMocks();
dispatcher = new ActionDispatcher({
navigate: vi.fn(),
router: { navigate: vi.fn() } as any,
});
const result = await dispatcher.dispatchAction(action, {});
// 에러 없이 종료
expect(result).toBeDefined();
});
it('conditions가 배열이 아니면 경고를 출력하고 종료해야 함', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: 'invalid' as any, // 잘못된 타입
};
vi.restoreAllMocks();
dispatcher = new ActionDispatcher({
navigate: vi.fn(),
router: { navigate: vi.fn() } as any,
});
const result = await dispatcher.dispatchAction(action, {});
expect(result).toBeDefined();
});
});
});
describe('실제 사용 사례', () => {
let dispatcher: ActionDispatcher;
let executedActions: any[];
beforeEach(() => {
vi.clearAllMocks();
executedActions = [];
dispatcher = new ActionDispatcher({
navigate: vi.fn(),
router: { navigate: vi.fn() } as any,
});
const originalExecuteAction = (dispatcher as any).executeAction.bind(dispatcher);
vi.spyOn(dispatcher as any, 'executeAction').mockImplementation(async (action: any, context: any) => {
executedActions.push({ handler: action.handler, params: action.params });
if (['setState', 'toast', 'navigate', 'openModal', 'closeModal', 'apiCall'].includes(action.handler)) {
return { success: true, handler: action.handler };
}
if (action.handler === 'conditions') {
return originalExecuteAction(action, context);
}
return { success: true };
});
});
afterEach(() => {
vi.restoreAllMocks();
});
it('DataGrid 행 액션 처리 - edit/delete/view 분기', async () => {
const action: ActionDefinition = {
type: 'click',
handler: 'conditions',
conditions: [
{
if: "{{$args[0] === 'edit'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/products/edit/{{row.id}}' } },
},
{
if: "{{$args[0] === 'delete'}}",
then: [
{ type: 'click', handler: 'setState', params: { target: '_local', deleteTargetId: '{{row.id}}' } },
{ type: 'click', handler: 'openModal', params: { id: 'delete_confirm_modal' } },
],
},
{
if: "{{$args[0] === 'view'}}",
then: { type: 'click', handler: 'navigate', params: { path: '/products/view/{{row.id}}' } },
},
{
then: { type: 'click', handler: 'toast', params: { type: 'warning', message: '알 수 없는 액션입니다.' } },
},
],
};
// edit 클릭
executedActions = [];
await dispatcher.dispatchAction(action, { data: { $args: ['edit'], row: { id: '123' } } });
expect(executedActions[1].handler).toBe('navigate');
// delete 클릭
executedActions = [];
await dispatcher.dispatchAction(action, { data: { $args: ['delete'], row: { id: '456' } } });
// handleSequence가 실행되므로 setState와 openModal이 순차적으로 호출될 것으로 예상
// unknown 클릭
executedActions = [];
await dispatcher.dispatchAction(action, { data: { $args: ['unknown'], row: { id: '789' } } });
expect(executedActions[1].handler).toBe('toast');
});
});
@@ -0,0 +1,168 @@
/**
* AuthManager 로그인 리다이렉트 테스트
*
* Issue #57: 로그아웃 후 redirect= 에 queryString이 미포함되는 문제 수정 검증
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { AuthManager, type AuthType } from '../auth/AuthManager';
// Mock ApiClient
const mockApiClient = {
post: vi.fn().mockResolvedValue({}),
get: vi.fn().mockResolvedValue({}),
removeToken: vi.fn(),
setToken: vi.fn(),
getToken: vi.fn().mockReturnValue(null),
setOnUnauthorized: vi.fn(),
};
vi.mock('../api/ApiClient', () => ({
getApiClient: () => mockApiClient,
}));
vi.mock('../utils/Logger', () => ({
createLogger: () => ({
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}),
}));
describe('AuthManager - 로그인 리다이렉트 (Issue #57)', () => {
let authManager: AuthManager;
beforeEach(() => {
// 싱글톤 인스턴스 리셋
(AuthManager as any).instance = undefined;
authManager = AuthManager.getInstance();
// window.location mock
Object.defineProperty(window, 'location', {
value: {
href: '',
pathname: '/admin/ecommerce/products',
search: '?page=1&end_date=2026-02-13&date_type=created_at',
},
writable: true,
configurable: true,
});
// G7Core DevTools mock
(window as any).G7Core = {
devTools: {
trackAuthEvent: vi.fn(),
},
};
vi.clearAllMocks();
});
afterEach(() => {
delete (window as any).G7Core;
});
describe('getLoginRedirectUrl', () => {
it('queryString이 포함된 URL을 올바르게 인코딩하여 redirect 파라미터에 포함해야 한다', () => {
const returnUrl = '/admin/ecommerce/products?page=1&end_date=2026-02-13&date_type=created_at';
const result = authManager.getLoginRedirectUrl('admin', returnUrl);
expect(result).toBe(
`/admin/login?redirect=${encodeURIComponent(returnUrl)}`
);
// queryString이 인코딩되어 포함되었는지 확인
expect(result).toContain('redirect=');
expect(result).toContain(encodeURIComponent('?page=1'));
expect(result).toContain(encodeURIComponent('&end_date=2026-02-13'));
});
it('queryString이 없는 URL도 정상 처리해야 한다', () => {
const returnUrl = '/admin/ecommerce/products';
const result = authManager.getLoginRedirectUrl('admin', returnUrl);
expect(result).toBe(
`/admin/login?redirect=${encodeURIComponent(returnUrl)}`
);
});
it('user 타입에 대해 올바른 loginPath를 사용해야 한다', () => {
const returnUrl = '/mypage?tab=orders&sort=desc';
const result = authManager.getLoginRedirectUrl('user', returnUrl);
expect(result).toBe(
`/login?redirect=${encodeURIComponent(returnUrl)}`
);
});
it('설정이 없는 타입은 /login 을 반환해야 한다', () => {
const result = authManager.getLoginRedirectUrl('unknown' as AuthType, '/some/path?q=1');
expect(result).toBe('/login');
});
});
describe('logout() - redirect에 queryString 포함', () => {
it('로그아웃 시 현재 URL의 pathname + search가 redirect에 포함되어야 한다', async () => {
// 인증 상태 설정 (admin)
(authManager as any).state = {
isAuthenticated: true,
user: { id: 1, name: 'Admin', email: 'admin@test.com' },
type: 'admin',
};
await authManager.logout();
// window.location.href에 redirect 파라미터가 포함되어야 함
const expectedReturnUrl = '/admin/ecommerce/products?page=1&end_date=2026-02-13&date_type=created_at';
const expectedHref = `/admin/login?redirect=${encodeURIComponent(expectedReturnUrl)}`;
expect(window.location.href).toBe(expectedHref);
});
it('queryString이 없는 경우에도 정상 동작해야 한다', async () => {
Object.defineProperty(window, 'location', {
value: {
href: '',
pathname: '/admin/dashboard',
search: '',
},
writable: true,
configurable: true,
});
(authManager as any).state = {
isAuthenticated: true,
user: { id: 1, name: 'Admin', email: 'admin@test.com' },
type: 'admin',
};
await authManager.logout();
const expectedHref = `/admin/login?redirect=${encodeURIComponent('/admin/dashboard')}`;
expect(window.location.href).toBe(expectedHref);
});
it('user 타입 로그아웃 시 올바른 loginPath로 리다이렉트해야 한다', async () => {
Object.defineProperty(window, 'location', {
value: {
href: '',
pathname: '/mypage',
search: '?tab=orders',
},
writable: true,
configurable: true,
});
(authManager as any).state = {
isAuthenticated: true,
user: { id: 1, name: 'User', email: 'user@test.com' },
type: 'user',
};
await authManager.logout();
const expectedReturnUrl = '/mypage?tab=orders';
const expectedHref = `/login?redirect=${encodeURIComponent(expectedReturnUrl)}`;
expect(window.location.href).toBe(expectedHref);
});
});
});
@@ -0,0 +1,696 @@
/**
* ConditionEvaluator 단위 테스트
*
* conditions 통합 조건 시스템의 핵심 함수들을 테스트합니다.
* - evaluateStringCondition: 문자열 조건 평가
* - evaluateConditionExpression: AND/OR 그룹 평가
* - evaluateConditionBranches: if/else 체인 평가
* - evaluateConditions: 통합 평가
*
* @since engine-v1.10.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
evaluateStringCondition,
evaluateConditionExpression,
evaluateConditionBranches,
evaluateConditions,
isConditionExpression,
isConditionBranches,
type ConditionExpression,
type ConditionBranch,
type ConditionsProperty,
} from '../template-engine/helpers/ConditionEvaluator';
import { evaluateIfCondition } from '../template-engine/helpers/RenderHelpers';
import { DataBindingEngine } from '../template-engine/DataBindingEngine';
describe('ConditionEvaluator', () => {
let bindingEngine: DataBindingEngine;
beforeEach(() => {
bindingEngine = new DataBindingEngine();
});
// ==========================================================================
// evaluateStringCondition 테스트
// ==========================================================================
describe('evaluateStringCondition', () => {
describe('JavaScript 리터럴 표현식', () => {
it('{{true}}는 true 반환', () => {
expect(evaluateStringCondition('{{true}}', {}, bindingEngine)).toBe(true);
});
it('{{false}}는 false 반환', () => {
expect(evaluateStringCondition('{{false}}', {}, bindingEngine)).toBe(false);
});
it('{{null}}은 false 반환', () => {
expect(evaluateStringCondition('{{null}}', {}, bindingEngine)).toBe(false);
});
it('{{undefined}}은 false 반환', () => {
expect(evaluateStringCondition('{{undefined}}', {}, bindingEngine)).toBe(false);
});
it('컨텍스트에 true 키가 있어도 리터럴 우선', () => {
const context = { true: false };
expect(evaluateStringCondition('{{true}}', context, bindingEngine)).toBe(true);
});
});
describe('단순 바인딩 표현식', () => {
it('truthy 값은 true 반환', () => {
const context = { user: { isAdmin: true } };
expect(evaluateStringCondition('{{user.isAdmin}}', context, bindingEngine)).toBe(true);
});
it('falsy 값(false)은 false 반환', () => {
const context = { user: { isAdmin: false } };
expect(evaluateStringCondition('{{user.isAdmin}}', context, bindingEngine)).toBe(false);
});
it('falsy 값(0)은 false 반환', () => {
const context = { count: 0 };
expect(evaluateStringCondition('{{count}}', context, bindingEngine)).toBe(false);
});
it('falsy 값(null)은 false 반환', () => {
const context = { value: null };
expect(evaluateStringCondition('{{value}}', context, bindingEngine)).toBe(false);
});
it('falsy 값(undefined)은 false 반환', () => {
const context = { value: undefined };
expect(evaluateStringCondition('{{value}}', context, bindingEngine)).toBe(false);
});
it('빈 문자열은 false 반환', () => {
const context = { value: '' };
expect(evaluateStringCondition('{{value}}', context, bindingEngine)).toBe(false);
});
it('문자열 "false"는 false 반환', () => {
const context = { value: 'false' };
expect(evaluateStringCondition('{{value}}', context, bindingEngine)).toBe(false);
});
it('존재하지 않는 경로는 false 반환', () => {
const context = { user: {} };
expect(evaluateStringCondition('{{user.notExist}}', context, bindingEngine)).toBe(false);
});
});
describe('비교 연산자', () => {
it('=== 동등 비교', () => {
const context = { status: 'active' };
expect(evaluateStringCondition("{{status === 'active'}}", context, bindingEngine)).toBe(true);
expect(evaluateStringCondition("{{status === 'inactive'}}", context, bindingEngine)).toBe(false);
});
it('!== 부등 비교', () => {
const context = { status: 'active' };
expect(evaluateStringCondition("{{status !== 'inactive'}}", context, bindingEngine)).toBe(true);
});
it('숫자 비교 (<, >, <=, >=)', () => {
const context = { count: 10 };
expect(evaluateStringCondition('{{count > 5}}', context, bindingEngine)).toBe(true);
expect(evaluateStringCondition('{{count < 5}}', context, bindingEngine)).toBe(false);
expect(evaluateStringCondition('{{count >= 10}}', context, bindingEngine)).toBe(true);
expect(evaluateStringCondition('{{count <= 10}}', context, bindingEngine)).toBe(true);
});
});
describe('논리 연산자', () => {
it('&& AND 연산', () => {
const context = { a: true, b: true, c: false };
expect(evaluateStringCondition('{{a && b}}', context, bindingEngine)).toBe(true);
expect(evaluateStringCondition('{{a && c}}', context, bindingEngine)).toBe(false);
});
it('|| OR 연산', () => {
const context = { a: false, b: true, c: false };
expect(evaluateStringCondition('{{a || b}}', context, bindingEngine)).toBe(true);
expect(evaluateStringCondition('{{a || c}}', context, bindingEngine)).toBe(false);
});
it('! NOT 연산', () => {
const context = { value: false };
expect(evaluateStringCondition('{{!value}}', context, bindingEngine)).toBe(true);
});
});
describe('Optional Chaining', () => {
it('존재하는 중첩 경로', () => {
const context = { user: { profile: { name: 'John' } } };
expect(evaluateStringCondition('{{user?.profile?.name}}', context, bindingEngine)).toBe(true);
});
it('중간에 null인 경로', () => {
const context = { user: { profile: null } };
expect(evaluateStringCondition('{{user?.profile?.name}}', context, bindingEngine)).toBe(false);
});
it('최상위가 존재하지 않는 경로', () => {
const context = {};
expect(evaluateStringCondition('{{user?.profile?.name}}', context, bindingEngine)).toBe(false);
});
});
describe('삼항 연산자', () => {
it('조건 true일 때', () => {
const context = { isEdit: true };
expect(evaluateStringCondition("{{isEdit ? 'yes' : 'no'}}", context, bindingEngine)).toBe(true); // 'yes' → truthy
});
it('조건 false일 때 빈 문자열 반환', () => {
const context = { isEdit: false };
expect(evaluateStringCondition("{{isEdit ? 'yes' : ''}}", context, bindingEngine)).toBe(false); // '' → falsy
});
});
describe('함수 호출', () => {
it('_global.hasPermission 같은 함수 호출', () => {
const context = {
_global: {
hasPermission: (perm: string) => perm === 'admin',
},
};
expect(evaluateStringCondition("{{_global.hasPermission('admin')}}", context, bindingEngine)).toBe(true);
expect(evaluateStringCondition("{{_global.hasPermission('guest')}}", context, bindingEngine)).toBe(false);
});
it('배열 메서드 호출', () => {
const context = {
items: [1, 2, 3],
};
expect(evaluateStringCondition('{{items.length > 0}}', context, bindingEngine)).toBe(true);
expect(evaluateStringCondition('{{items.includes(2)}}', context, bindingEngine)).toBe(true);
});
});
describe('빈 조건', () => {
it('빈 문자열 조건은 true 반환', () => {
expect(evaluateStringCondition('', {}, bindingEngine)).toBe(true);
});
it('undefined 조건은 true 반환', () => {
expect(evaluateStringCondition(undefined as any, {}, bindingEngine)).toBe(true);
});
});
});
// ==========================================================================
// evaluateConditionExpression 테스트
// ==========================================================================
describe('evaluateConditionExpression', () => {
describe('문자열 조건', () => {
it('문자열은 evaluateStringCondition으로 평가', () => {
const context = { user: { isAdmin: true } };
expect(evaluateConditionExpression('{{user.isAdmin}}', context, bindingEngine)).toBe(true);
});
});
describe('AND 그룹', () => {
it('모든 조건 true → true', () => {
const context = { a: true, b: true, c: true };
const condition: ConditionExpression = {
and: ['{{a}}', '{{b}}', '{{c}}'],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(true);
});
it('하나라도 false → false', () => {
const context = { a: true, b: false, c: true };
const condition: ConditionExpression = {
and: ['{{a}}', '{{b}}', '{{c}}'],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(false);
});
it('빈 AND 그룹은 true 반환', () => {
const condition: ConditionExpression = { and: [] };
expect(evaluateConditionExpression(condition, {}, bindingEngine)).toBe(true);
});
it('단락 평가: 첫 false에서 중단', () => {
const evalOrder: string[] = [];
const context = {
get first() {
evalOrder.push('first');
return false;
},
get second() {
evalOrder.push('second');
return true;
},
};
const condition: ConditionExpression = {
and: ['{{first}}', '{{second}}'],
};
evaluateConditionExpression(condition, context, bindingEngine);
expect(evalOrder).toEqual(['first']); // second는 평가되지 않음
});
});
describe('OR 그룹', () => {
it('하나라도 true → true', () => {
const context = { a: false, b: true, c: false };
const condition: ConditionExpression = {
or: ['{{a}}', '{{b}}', '{{c}}'],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(true);
});
it('모든 조건 false → false', () => {
const context = { a: false, b: false, c: false };
const condition: ConditionExpression = {
or: ['{{a}}', '{{b}}', '{{c}}'],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(false);
});
it('빈 OR 그룹은 false 반환', () => {
const condition: ConditionExpression = { or: [] };
expect(evaluateConditionExpression(condition, {}, bindingEngine)).toBe(false);
});
it('단락 평가: 첫 true에서 중단', () => {
const evalOrder: string[] = [];
const context = {
get first() {
evalOrder.push('first');
return true;
},
get second() {
evalOrder.push('second');
return false;
},
};
const condition: ConditionExpression = {
or: ['{{first}}', '{{second}}'],
};
evaluateConditionExpression(condition, context, bindingEngine);
expect(evalOrder).toEqual(['first']); // second는 평가되지 않음
});
});
describe('중첩 AND/OR', () => {
it('OR 안에 AND', () => {
const context = { isAdmin: false, isManager: true, department: 'sales' };
// isAdmin이거나 (isManager이면서 sales 부서)
const condition: ConditionExpression = {
or: [
'{{isAdmin}}',
{
and: ['{{isManager}}', "{{department === 'sales'}}"],
},
],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(true);
});
it('AND 안에 OR', () => {
const context = { isLoggedIn: true, hasBasicPlan: false, hasPremiumPlan: true };
// 로그인하고 (기본 플랜 또는 프리미엄 플랜)
const condition: ConditionExpression = {
and: [
'{{isLoggedIn}}',
{
or: ['{{hasBasicPlan}}', '{{hasPremiumPlan}}'],
},
],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(true);
});
it('복잡한 3단 중첩', () => {
const context = {
user: { role: 'editor', department: 'content' },
feature: { enabled: true },
};
// (editor이면서 content 부서) 또는 feature enabled
const condition: ConditionExpression = {
or: [
{
and: [
"{{user.role === 'editor'}}",
"{{user.department === 'content'}}",
],
},
'{{feature.enabled}}',
],
};
expect(evaluateConditionExpression(condition, context, bindingEngine)).toBe(true);
});
});
});
// ==========================================================================
// evaluateConditionBranches 테스트
// ==========================================================================
describe('evaluateConditionBranches', () => {
describe('if/else if/else 체인', () => {
it('첫 번째 조건 매칭', () => {
const context = { mode: 'edit' };
const branches: ConditionBranch[] = [
{ if: "{{mode === 'edit'}}", then: { handler: 'save' } },
{ if: "{{mode === 'view'}}", then: { handler: 'view' } },
{ then: { handler: 'default' } },
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(true);
expect(result.branchIndex).toBe(0);
});
it('두 번째 조건 매칭', () => {
const context = { mode: 'view' };
const branches: ConditionBranch[] = [
{ if: "{{mode === 'edit'}}", then: { handler: 'save' } },
{ if: "{{mode === 'view'}}", then: { handler: 'view' } },
{ then: { handler: 'default' } },
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(true);
expect(result.branchIndex).toBe(1);
});
it('else 브랜치 매칭', () => {
const context = { mode: 'other' };
const branches: ConditionBranch[] = [
{ if: "{{mode === 'edit'}}", then: { handler: 'save' } },
{ if: "{{mode === 'view'}}", then: { handler: 'view' } },
{ then: { handler: 'default' } }, // else
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(true);
expect(result.branchIndex).toBe(2);
});
it('매칭 없음 (else 없이)', () => {
const context = { mode: 'other' };
const branches: ConditionBranch[] = [
{ if: "{{mode === 'edit'}}", then: { handler: 'save' } },
{ if: "{{mode === 'view'}}", then: { handler: 'view' } },
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(false);
expect(result.branchIndex).toBe(-1);
});
});
describe('AND/OR 조건 브랜치', () => {
it('AND 그룹 조건', () => {
const context = { user: { isLoggedIn: true, hasPermission: true } };
const branches: ConditionBranch[] = [
{
if: { and: ['{{user.isLoggedIn}}', '{{user.hasPermission}}'] },
then: { handler: 'proceed' },
},
{ then: { handler: 'deny' } },
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(true);
expect(result.branchIndex).toBe(0);
});
it('OR 그룹 조건', () => {
const context = { user: { isAdmin: false, isModerator: true } };
const branches: ConditionBranch[] = [
{
if: { or: ['{{user.isAdmin}}', '{{user.isModerator}}'] },
then: { handler: 'moderate' },
},
{ then: { handler: 'view' } },
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(true);
expect(result.branchIndex).toBe(0);
});
});
describe('엣지 케이스', () => {
it('빈 배열은 매칭 없음', () => {
const result = evaluateConditionBranches([], {}, bindingEngine);
expect(result.matched).toBe(false);
expect(result.branchIndex).toBe(-1);
});
it('then 없는 브랜치도 정상 처리', () => {
const context = { show: true };
const branches: ConditionBranch[] = [
{ if: '{{show}}' }, // then 없음 (컴포넌트용)
];
const result = evaluateConditionBranches(branches, context, bindingEngine);
expect(result.matched).toBe(true);
expect(result.branchIndex).toBe(0);
});
});
});
// ==========================================================================
// evaluateConditions 테스트
// ==========================================================================
describe('evaluateConditions', () => {
describe('단일 ConditionExpression', () => {
it('문자열 조건', () => {
const context = { show: true };
expect(evaluateConditions('{{show}}', context, bindingEngine)).toBe(true);
});
it('AND 그룹', () => {
const context = { a: true, b: true };
const cond: ConditionsProperty = { and: ['{{a}}', '{{b}}'] };
expect(evaluateConditions(cond, context, bindingEngine)).toBe(true);
});
it('OR 그룹', () => {
const context = { a: false, b: true };
const cond: ConditionsProperty = { or: ['{{a}}', '{{b}}'] };
expect(evaluateConditions(cond, context, bindingEngine)).toBe(true);
});
});
describe('ConditionBranch[] (if/else 체인)', () => {
it('하나라도 매칭되면 true', () => {
const context = { role: 'admin' };
const cond: ConditionsProperty = [
{ if: "{{role === 'admin'}}" },
{ if: "{{role === 'manager'}}" },
];
expect(evaluateConditions(cond, context, bindingEngine)).toBe(true);
});
it('모든 조건 false면 false (else 없이)', () => {
const context = { role: 'guest' };
const cond: ConditionsProperty = [
{ if: "{{role === 'admin'}}" },
{ if: "{{role === 'manager'}}" },
];
expect(evaluateConditions(cond, context, bindingEngine)).toBe(false);
});
it('else 브랜치 있으면 항상 true', () => {
const context = { role: 'guest' };
const cond: ConditionsProperty = [
{ if: "{{role === 'admin'}}" },
{}, // else 브랜치
];
expect(evaluateConditions(cond, context, bindingEngine)).toBe(true);
});
});
});
// ==========================================================================
// 타입 가드 테스트
// ==========================================================================
describe('타입 가드', () => {
describe('isConditionExpression', () => {
it('문자열은 true', () => {
expect(isConditionExpression('{{user.isAdmin}}')).toBe(true);
});
it('AND 객체는 true', () => {
expect(isConditionExpression({ and: ['{{a}}', '{{b}}'] })).toBe(true);
});
it('OR 객체는 true', () => {
expect(isConditionExpression({ or: ['{{a}}', '{{b}}'] })).toBe(true);
});
it('ConditionBranch 배열은 false', () => {
expect(isConditionExpression([{ if: '{{a}}' }])).toBe(false);
});
it('null/undefined는 false', () => {
expect(isConditionExpression(null)).toBe(false);
expect(isConditionExpression(undefined)).toBe(false);
});
});
describe('isConditionBranches', () => {
it('ConditionBranch 배열은 true', () => {
expect(isConditionBranches([{ if: '{{a}}' }])).toBe(true);
expect(isConditionBranches([{ then: { handler: 'test' } }])).toBe(true);
expect(isConditionBranches([{ if: '{{a}}', then: { handler: 'test' } }])).toBe(true);
});
it('빈 배열은 false', () => {
expect(isConditionBranches([])).toBe(false);
});
it('문자열 배열은 false', () => {
expect(isConditionBranches(['{{a}}', '{{b}}'])).toBe(false);
});
it('문자열은 false', () => {
expect(isConditionBranches('{{a}}')).toBe(false);
});
});
});
// ==========================================================================
// 실제 사용 시나리오 테스트
// ==========================================================================
describe('실제 사용 시나리오', () => {
it('컴포넌트 조건부 렌더링 - route.id와 form_data 둘 다 필요', () => {
const context1 = { route: { id: '123' }, form_data: { data: { author: 'John' } } };
const context2 = { route: { id: '123' }, form_data: null };
const context3 = { route: {}, form_data: { data: { author: 'John' } } };
const condition: ConditionExpression = {
and: ['{{route.id}}', '{{form_data?.data?.author}}'],
};
expect(evaluateConditionExpression(condition, context1, bindingEngine)).toBe(true);
expect(evaluateConditionExpression(condition, context2, bindingEngine)).toBe(false);
expect(evaluateConditionExpression(condition, context3, bindingEngine)).toBe(false);
});
it('액션 분기 처리 - 행 액션별 다른 핸들러', () => {
const branches: ConditionBranch[] = [
{
if: "{{$args[0] === 'edit'}}",
then: { handler: 'navigate', params: { path: '/edit' } },
},
{
if: "{{$args[0] === 'delete'}}",
then: { handler: 'openModal', params: { id: 'confirm' } },
},
{
then: { handler: 'toast', params: { message: '알 수 없는 액션' } },
},
];
// edit 액션
const result1 = evaluateConditionBranches(branches, { $args: ['edit'] }, bindingEngine);
expect(result1.branchIndex).toBe(0);
// delete 액션
const result2 = evaluateConditionBranches(branches, { $args: ['delete'] }, bindingEngine);
expect(result2.branchIndex).toBe(1);
// 알 수 없는 액션
const result3 = evaluateConditionBranches(branches, { $args: ['unknown'] }, bindingEngine);
expect(result3.branchIndex).toBe(2);
});
it('데이터 소스 조건부 fetch - 권한 및 route 조건', () => {
const condition: ConditionExpression = {
and: [
'{{!!route.itemCode}}',
"{{_global.hasPermission('view_product')}}",
],
};
// 권한 있고 itemCode 있음
const context1 = {
route: { itemCode: 'P001' },
_global: { hasPermission: (p: string) => p === 'view_product' },
};
expect(evaluateConditionExpression(condition, context1, bindingEngine)).toBe(true);
// 권한 없음
const context2 = {
route: { itemCode: 'P001' },
_global: { hasPermission: () => false },
};
expect(evaluateConditionExpression(condition, context2, bindingEngine)).toBe(false);
// itemCode 없음
const context3 = {
route: {},
_global: { hasPermission: () => true },
};
expect(evaluateConditionExpression(condition, context3, bindingEngine)).toBe(false);
});
it('스크립트 조건부 로드 - 플러그인 활성화 또는 관리자', () => {
const condition: ConditionExpression = {
or: [
"{{_global.installedPlugins?.find(p => p.identifier === 'analytics' && p.status === 'active')}}",
"{{_global.user?.role === 'admin'}}",
],
};
// 플러그인 활성화됨
const context1 = {
_global: {
installedPlugins: [{ identifier: 'analytics', status: 'active' }],
user: { role: 'user' },
},
};
expect(evaluateConditionExpression(condition, context1, bindingEngine)).toBe(true);
// 관리자
const context2 = {
_global: {
installedPlugins: [],
user: { role: 'admin' },
},
};
expect(evaluateConditionExpression(condition, context2, bindingEngine)).toBe(true);
// 둘 다 아님
const context3 = {
_global: {
installedPlugins: [],
user: { role: 'user' },
},
};
expect(evaluateConditionExpression(condition, context3, bindingEngine)).toBe(false);
});
});
// ==========================================================================
// evaluateIfCondition (RenderHelpers) 리터럴 테스트
// ==========================================================================
describe('evaluateIfCondition - JavaScript 리터럴', () => {
it('{{true}}는 true 반환', () => {
expect(evaluateIfCondition('{{true}}', {}, bindingEngine)).toBe(true);
});
it('{{false}}는 false 반환', () => {
expect(evaluateIfCondition('{{false}}', {}, bindingEngine)).toBe(false);
});
it('{{null}}은 false 반환', () => {
expect(evaluateIfCondition('{{null}}', {}, bindingEngine)).toBe(false);
});
it('{{undefined}}은 false 반환', () => {
expect(evaluateIfCondition('{{undefined}}', {}, bindingEngine)).toBe(false);
});
it('컨텍스트에 true 키가 있어도 리터럴 우선', () => {
const context = { true: false };
expect(evaluateIfCondition('{{true}}', context, bindingEngine)).toBe(true);
});
it('일반 경로 표현식은 기존대로 동작', () => {
const context = { user: { isAdmin: true } };
expect(evaluateIfCondition('{{user.isAdmin}}', context, bindingEngine)).toBe(true);
});
});
});
@@ -0,0 +1,388 @@
/**
* Defines/Computed 기능 테스트
*
* 레이아웃 JSON의 defines와 computed 속성 처리 테스트
*
* @since engine-v1.9.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
/**
* calculateComputed 함수 로직을 테스트하기 위한 헬퍼 함수
*
* TemplateApp의 private 메서드 로직을 분리하여 테스트
*/
function calculateComputed(
computed: Record<string, string>,
dataContext: Record<string, any>
): Record<string, any> {
const result: Record<string, any> = {};
for (const [key, expression] of Object.entries(computed)) {
try {
if (typeof expression === 'string') {
let value: any;
if (expression.startsWith('{{') && expression.endsWith('}}')) {
const innerExpression = expression.slice(2, -2).trim();
value = evaluateComputedExpression(innerExpression, dataContext);
} else {
value = expression;
}
result[key] = value;
}
} catch (error) {
result[key] = undefined;
}
}
return result;
}
/**
* evaluateComputedExpression 함수 로직
*/
function evaluateComputedExpression(expression: string, context: Record<string, any>): any {
try {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const fn = new Function('ctx', `
with(ctx) {
try {
return ${expression};
} catch (e) {
return undefined;
}
}
`);
return fn(context);
} catch (error) {
return undefined;
}
}
describe('Defines 기능', () => {
describe('정적 상수 정의', () => {
it('간단한 문자열 매핑을 정의할 수 있어야 함', () => {
const defines = {
currencyToFlag: {
KRW: 'kr',
USD: 'us',
JPY: 'jp',
CNY: 'cn',
EUR: 'eu',
},
};
expect(defines.currencyToFlag.KRW).toBe('kr');
expect(defines.currencyToFlag.USD).toBe('us');
expect(defines.currencyToFlag.JPY).toBe('jp');
});
it('중첩된 객체를 정의할 수 있어야 함', () => {
const defines = {
statusColors: {
active: { bg: 'green', text: 'white' },
inactive: { bg: 'gray', text: 'black' },
pending: { bg: 'yellow', text: 'black' },
},
};
expect(defines.statusColors.active.bg).toBe('green');
expect(defines.statusColors.pending.text).toBe('black');
});
it('배열을 정의할 수 있어야 함', () => {
const defines = {
supportedCurrencies: ['KRW', 'USD', 'JPY', 'CNY', 'EUR'],
};
expect(defines.supportedCurrencies).toContain('KRW');
expect(defines.supportedCurrencies.length).toBe(5);
});
});
describe('dataContext에 _defines 주입', () => {
it('defines가 있으면 _defines로 주입되어야 함', () => {
const layoutData = {
defines: {
currencyToFlag: {
KRW: 'kr',
USD: 'us',
},
},
};
const definesData = layoutData.defines || {};
const dataContext: Record<string, any> = {};
if (Object.keys(definesData).length > 0) {
dataContext._defines = definesData;
}
expect(dataContext._defines).toBeDefined();
expect(dataContext._defines.currencyToFlag.KRW).toBe('kr');
});
it('defines가 없으면 _defines는 undefined이어야 함', () => {
const layoutData = {
defines: {},
};
const definesData = layoutData.defines || {};
const dataContext: Record<string, any> = {};
if (Object.keys(definesData).length > 0) {
dataContext._defines = definesData;
}
expect(dataContext._defines).toBeUndefined();
});
});
});
describe('Computed 기능', () => {
describe('표현식 평가', () => {
it('단순 속성 접근을 평가할 수 있어야 함', () => {
const context = {
user: { name: '홍길동', age: 30 },
};
const result = evaluateComputedExpression('user.name', context);
expect(result).toBe('홍길동');
});
it('산술 연산을 평가할 수 있어야 함', () => {
const context = {
price: 1000,
quantity: 5,
};
const result = evaluateComputedExpression('price * quantity', context);
expect(result).toBe(5000);
});
it('비교 연산을 평가할 수 있어야 함', () => {
const context = {
user: { role: 'admin' },
};
const result = evaluateComputedExpression("user.role === 'admin'", context);
expect(result).toBe(true);
});
it('삼항 연산자를 평가할 수 있어야 함', () => {
const context = {
isActive: true,
};
const result = evaluateComputedExpression("isActive ? '활성' : '비활성'", context);
expect(result).toBe('활성');
});
it('nullish 연산자를 평가할 수 있어야 함', () => {
const context = {
value: null,
defaultValue: '기본값',
};
const result = evaluateComputedExpression('value ?? defaultValue', context);
expect(result).toBe('기본값');
});
it('옵셔널 체이닝을 평가할 수 있어야 함', () => {
const context = {
user: { profile: null },
};
const result = evaluateComputedExpression("user?.profile?.name ?? '없음'", context);
expect(result).toBe('없음');
});
it('_defines 값을 참조할 수 있어야 함', () => {
const context = {
_defines: {
currencyToFlag: {
KRW: 'kr',
USD: 'us',
},
},
currency: 'KRW',
};
const result = evaluateComputedExpression('_defines.currencyToFlag[currency]', context);
expect(result).toBe('kr');
});
});
describe('calculateComputed 함수', () => {
it('여러 computed 값을 계산할 수 있어야 함', () => {
const computed = {
fullName: "{{user.firstName + ' ' + user.lastName}}",
isAdult: '{{user.age >= 18}}',
};
const context = {
user: { firstName: '길동', lastName: '홍', age: 25 },
};
const result = calculateComputed(computed, context);
expect(result.fullName).toBe('길동 홍');
expect(result.isAdult).toBe(true);
});
it('{{}} 없는 순수 문자열은 그대로 사용해야 함', () => {
const computed = {
staticValue: '고정 문자열',
};
const context = {};
const result = calculateComputed(computed, context);
expect(result.staticValue).toBe('고정 문자열');
});
it('평가 실패 시 undefined를 반환해야 함', () => {
const computed = {
invalid: '{{nonExistent.property.deep}}',
};
const context = {};
const result = calculateComputed(computed, context);
expect(result.invalid).toBeUndefined();
});
it('_defines를 참조하는 computed를 계산할 수 있어야 함', () => {
const computed = {
flagCode: '{{_defines.currencyToFlag[currentCurrency]}}',
};
const context = {
_defines: {
currencyToFlag: {
KRW: 'kr',
USD: 'us',
},
},
currentCurrency: 'USD',
};
const result = calculateComputed(computed, context);
expect(result.flagCode).toBe('us');
});
});
describe('실제 사용 사례', () => {
it('통화-국기 매핑을 처리할 수 있어야 함', () => {
// 레이아웃 JSON에서 정의한 것처럼 테스트
const layoutData = {
defines: {
currencyToFlag: {
KRW: 'kr',
USD: 'us',
JPY: 'jp',
CNY: 'cn',
EUR: 'eu',
},
},
computed: {
currentFlag: '{{_defines.currencyToFlag[currency.code] ?? "un"}}',
},
};
// dataContext 구성 (TemplateApp에서 하는 것처럼)
const dataContext = {
currency: { code: 'JPY', name: 'JPY (엔)' },
_defines: layoutData.defines,
};
// computed 계산
const computedResult = calculateComputed(layoutData.computed, dataContext);
expect(computedResult.currentFlag).toBe('jp');
});
it('알 수 없는 통화에 대해 기본값을 반환해야 함', () => {
const layoutData = {
defines: {
currencyToFlag: {
KRW: 'kr',
USD: 'us',
},
},
computed: {
currentFlag: '{{_defines.currencyToFlag[currency.code] ?? "un"}}',
},
};
const dataContext = {
currency: { code: 'GBP', name: 'GBP (파운드)' },
_defines: layoutData.defines,
};
const computedResult = calculateComputed(layoutData.computed, dataContext);
expect(computedResult.currentFlag).toBe('un');
});
it('복잡한 조건부 computed를 처리할 수 있어야 함', () => {
const layoutData = {
defines: {
statusLabels: {
active: '활성',
inactive: '비활성',
pending: '대기중',
},
statusColors: {
active: 'text-green-600',
inactive: 'text-gray-600',
pending: 'text-yellow-600',
},
},
computed: {
statusLabel: "{{_defines.statusLabels[status] ?? '알 수 없음'}}",
statusClass: "{{_defines.statusColors[status] ?? 'text-gray-400'}}",
},
};
const dataContext = {
status: 'active',
_defines: layoutData.defines,
};
const computedResult = calculateComputed(layoutData.computed, dataContext);
expect(computedResult.statusLabel).toBe('활성');
expect(computedResult.statusClass).toBe('text-green-600');
});
});
});
describe('LayoutLoader defines/computed 인터페이스', () => {
it('LayoutData 인터페이스에 defines 필드가 포함되어야 함', () => {
// TypeScript 인터페이스 검증을 위한 타입 테스트
interface LayoutData {
defines?: Record<string, any>;
computed?: Record<string, string>;
}
const layoutData: LayoutData = {
defines: {
mapping: { a: 1, b: 2 },
},
computed: {
result: '{{mapping.a + mapping.b}}',
},
};
expect(layoutData.defines).toBeDefined();
expect(layoutData.computed).toBeDefined();
});
});
@@ -0,0 +1,512 @@
/**
* DynamicRenderer conditions 기능 테스트
*
* 컴포넌트의 conditions 속성을 통한 조건부 렌더링 테스트
*
* @since engine-v1.10.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { render, screen } from '@testing-library/react';
import { evaluateRenderCondition } from '../template-engine/helpers/RenderHelpers';
import { DataBindingEngine } from '../template-engine/DataBindingEngine';
// Mock 컴포넌트들
const MockDiv = ({ children, ...props }: any) => <div {...props}>{children}</div>;
const MockSpan = ({ children, ...props }: any) => <span {...props}>{children}</span>;
// DataBindingEngine 인스턴스
let bindingEngine: DataBindingEngine;
beforeEach(() => {
bindingEngine = new DataBindingEngine();
});
describe('evaluateRenderCondition', () => {
describe('기존 if 속성 (하위 호환)', () => {
it('if 속성이 없으면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{},
{ _local: {} },
bindingEngine
);
expect(result).toBe(true);
});
it('if 속성이 truthy 표현식이면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{ if: '{{user.isAdmin}}' },
{ user: { isAdmin: true } },
bindingEngine
);
expect(result).toBe(true);
});
it('if 속성이 falsy 표현식이면 false를 반환해야 함', () => {
const result = evaluateRenderCondition(
{ if: '{{user.isAdmin}}' },
{ user: { isAdmin: false } },
bindingEngine
);
expect(result).toBe(false);
});
it('if 속성의 비교 연산이 올바르게 동작해야 함', () => {
const result = evaluateRenderCondition(
{ if: "{{status === 'active'}}" },
{ status: 'active' },
bindingEngine
);
expect(result).toBe(true);
const result2 = evaluateRenderCondition(
{ if: "{{status === 'active'}}" },
{ status: 'inactive' },
bindingEngine
);
expect(result2).toBe(false);
});
});
describe('conditions - 단순 문자열', () => {
it('단순 문자열 조건이 truthy면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{ conditions: '{{user.isLoggedIn}}' },
{ user: { isLoggedIn: true } },
bindingEngine
);
expect(result).toBe(true);
});
it('단순 문자열 조건이 falsy면 false를 반환해야 함', () => {
const result = evaluateRenderCondition(
{ conditions: '{{user.isLoggedIn}}' },
{ user: { isLoggedIn: false } },
bindingEngine
);
expect(result).toBe(false);
});
});
describe('conditions - AND 그룹', () => {
it('모든 조건이 true면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: {
and: ['{{route.id}}', '{{form_data?.data?.author}}'],
},
},
{
route: { id: '123' },
form_data: { data: { author: 'John' } },
},
bindingEngine
);
expect(result).toBe(true);
});
it('하나라도 false면 false를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: {
and: ['{{route.id}}', '{{form_data?.data?.author}}'],
},
},
{
route: { id: '123' },
form_data: { data: { author: null } },
},
bindingEngine
);
expect(result).toBe(false);
});
it('빈 배열이면 true를 반환해야 함 (vacuous truth)', () => {
const result = evaluateRenderCondition(
{
conditions: { and: [] },
},
{},
bindingEngine
);
expect(result).toBe(true);
});
});
describe('conditions - OR 그룹', () => {
it('하나라도 true면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: {
or: ['{{user.isAdmin}}', '{{user.isManager}}'],
},
},
{
user: { isAdmin: false, isManager: true },
},
bindingEngine
);
expect(result).toBe(true);
});
it('모든 조건이 false면 false를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: {
or: ['{{user.isAdmin}}', '{{user.isManager}}'],
},
},
{
user: { isAdmin: false, isManager: false },
},
bindingEngine
);
expect(result).toBe(false);
});
it('빈 배열이면 false를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: { or: [] },
},
{},
bindingEngine
);
expect(result).toBe(false);
});
});
describe('conditions - 중첩 AND/OR', () => {
it('OR 안에 AND가 중첩된 조건을 평가할 수 있어야 함', () => {
// user.isSuperAdmin OR (user.isAdmin AND user.department === 'sales')
const result = evaluateRenderCondition(
{
conditions: {
or: [
'{{user.isSuperAdmin}}',
{
and: [
'{{user.isAdmin}}',
"{{user.department === 'sales'}}",
],
},
],
},
},
{
user: { isSuperAdmin: false, isAdmin: true, department: 'sales' },
},
bindingEngine
);
expect(result).toBe(true);
// 중첩 AND 조건 실패
const result2 = evaluateRenderCondition(
{
conditions: {
or: [
'{{user.isSuperAdmin}}',
{
and: [
'{{user.isAdmin}}',
"{{user.department === 'sales'}}",
],
},
],
},
},
{
user: { isSuperAdmin: false, isAdmin: true, department: 'marketing' },
},
bindingEngine
);
expect(result2).toBe(false);
});
});
describe('conditions - if/else 체인 (ConditionBranch[])', () => {
it('첫 번째 조건이 true면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: [
{ if: "{{user.role === 'admin'}}" },
{ if: "{{user.role === 'manager'}}" },
],
},
{ user: { role: 'admin' } },
bindingEngine
);
expect(result).toBe(true);
});
it('두 번째 조건이 true면 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: [
{ if: "{{user.role === 'admin'}}" },
{ if: "{{user.role === 'manager'}}" },
],
},
{ user: { role: 'manager' } },
bindingEngine
);
expect(result).toBe(true);
});
it('모든 조건이 false면 false를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: [
{ if: "{{user.role === 'admin'}}" },
{ if: "{{user.role === 'manager'}}" },
],
},
{ user: { role: 'user' } },
bindingEngine
);
expect(result).toBe(false);
});
it('else 브랜치가 있으면 항상 true를 반환해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: [
{ if: "{{user.role === 'admin'}}" },
{ if: "{{user.role === 'manager'}}" },
{}, // else 브랜치
],
},
{ user: { role: 'user' } },
bindingEngine
);
expect(result).toBe(true);
});
});
describe('우선순위: if vs conditions', () => {
it('if와 conditions가 둘 다 있으면 if가 우선되어야 함', () => {
// if: false, conditions: true → false 반환 (if 우선)
const result = evaluateRenderCondition(
{
if: '{{ifValue}}',
conditions: '{{condValue}}',
},
{ ifValue: false, condValue: true },
bindingEngine
);
expect(result).toBe(false);
// if: true, conditions: false → true 반환 (if 우선)
const result2 = evaluateRenderCondition(
{
if: '{{ifValue}}',
conditions: '{{condValue}}',
},
{ ifValue: true, condValue: false },
bindingEngine
);
expect(result2).toBe(true);
});
});
describe('표현식 호환성', () => {
it('Optional Chaining을 지원해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: '{{form_data?.data?.author}}',
},
{ form_data: null },
bindingEngine
);
expect(result).toBe(false);
const result2 = evaluateRenderCondition(
{
conditions: '{{form_data?.data?.author}}',
},
{ form_data: { data: { author: 'John' } } },
bindingEngine
);
expect(result2).toBe(true);
});
it('논리 연산자를 지원해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: '{{a && b}}',
},
{ a: true, b: true },
bindingEngine
);
expect(result).toBe(true);
const result2 = evaluateRenderCondition(
{
conditions: '{{a || b}}',
},
{ a: false, b: true },
bindingEngine
);
expect(result2).toBe(true);
});
it('삼항 연산자를 지원해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: '{{isActive ? true : false}}',
},
{ isActive: true },
bindingEngine
);
expect(result).toBe(true);
});
it('Nullish Coalescing을 지원해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: '{{value ?? defaultValue}}',
},
{ value: null, defaultValue: true },
bindingEngine
);
expect(result).toBe(true);
});
it('함수 호출을 지원해야 함', () => {
const result = evaluateRenderCondition(
{
conditions: '{{_global.hasPermission("edit")}}',
},
{
_global: {
hasPermission: (perm: string) => perm === 'edit',
},
},
bindingEngine
);
expect(result).toBe(true);
});
});
});
describe('실제 사용 사례', () => {
describe('관리자 전용 영역 렌더링', () => {
it('admin 또는 manager 역할일 때만 렌더링해야 함', () => {
const conditions = {
conditions: {
or: [
"{{user.role === 'admin'}}",
"{{user.role === 'manager'}}",
],
},
};
// admin 역할
expect(
evaluateRenderCondition(conditions, { user: { role: 'admin' } }, bindingEngine)
).toBe(true);
// manager 역할
expect(
evaluateRenderCondition(conditions, { user: { role: 'manager' } }, bindingEngine)
).toBe(true);
// user 역할
expect(
evaluateRenderCondition(conditions, { user: { role: 'user' } }, bindingEngine)
).toBe(false);
});
});
describe('저자 정보 영역 렌더링', () => {
it('route.id와 form_data.data.author가 둘 다 있을 때만 렌더링해야 함', () => {
const conditions = {
conditions: {
and: ['{{route.id}}', '{{form_data?.data?.author}}'],
},
};
// 둘 다 있음
expect(
evaluateRenderCondition(
conditions,
{ route: { id: '123' }, form_data: { data: { author: 'John' } } },
bindingEngine
)
).toBe(true);
// route.id 없음
expect(
evaluateRenderCondition(
conditions,
{ route: {}, form_data: { data: { author: 'John' } } },
bindingEngine
)
).toBe(false);
// author 없음
expect(
evaluateRenderCondition(
conditions,
{ route: { id: '123' }, form_data: { data: {} } },
bindingEngine
)
).toBe(false);
});
});
describe('복합 권한 체크', () => {
it('superAdmin이거나 (admin + sales 부서)일 때 렌더링해야 함', () => {
const conditions = {
conditions: {
or: [
'{{user.isSuperAdmin}}',
{
and: [
'{{user.isAdmin}}',
"{{user.department === 'sales'}}",
],
},
],
},
};
// superAdmin
expect(
evaluateRenderCondition(
conditions,
{ user: { isSuperAdmin: true, isAdmin: false, department: 'hr' } },
bindingEngine
)
).toBe(true);
// admin + sales
expect(
evaluateRenderCondition(
conditions,
{ user: { isSuperAdmin: false, isAdmin: true, department: 'sales' } },
bindingEngine
)
).toBe(true);
// admin + hr (부서 불일치)
expect(
evaluateRenderCondition(
conditions,
{ user: { isSuperAdmin: false, isAdmin: true, department: 'hr' } },
bindingEngine
)
).toBe(false);
// 일반 사용자
expect(
evaluateRenderCondition(
conditions,
{ user: { isSuperAdmin: false, isAdmin: false, department: 'sales' } },
bindingEngine
)
).toBe(false);
});
});
});
@@ -0,0 +1,279 @@
/**
* FormContext 유틸리티 함수 테스트
*
* parseDataKey, updateByScope, getValueByScope 등 isolated state 관련 헬퍼 테스트
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
parseDataKey,
updateByScope,
getValueByScope,
getNestedValue,
setNestedValue,
isAutoBindingEnabled,
getAutoBindingPath,
FormContextValue,
} from '../template-engine/FormContext';
describe('FormContext 유틸리티', () => {
describe('parseDataKey', () => {
it('should parse _global prefix correctly', () => {
const result = parseDataKey('_global.settings');
expect(result).toEqual({ scope: 'global', path: 'settings' });
});
it('should parse _isolated prefix correctly', () => {
const result = parseDataKey('_isolated.miniForm');
expect(result).toEqual({ scope: 'isolated', path: 'miniForm' });
});
it('should parse _local prefix correctly', () => {
const result = parseDataKey('_local.formData');
expect(result).toEqual({ scope: 'local', path: 'formData' });
});
it('should default to local scope when no prefix', () => {
const result = parseDataKey('formData');
expect(result).toEqual({ scope: 'local', path: 'formData' });
});
it('should handle nested paths with _global prefix', () => {
const result = parseDataKey('_global.user.profile');
expect(result).toEqual({ scope: 'global', path: 'user.profile' });
});
it('should handle nested paths with _isolated prefix', () => {
const result = parseDataKey('_isolated.form.fields.email');
expect(result).toEqual({ scope: 'isolated', path: 'form.fields.email' });
});
});
describe('getNestedValue', () => {
it('should get value at simple path', () => {
const obj = { formData: { email: 'test@example.com' } };
expect(getNestedValue(obj, 'formData.email')).toBe('test@example.com');
});
it('should return undefined for non-existent path', () => {
const obj = { formData: {} };
expect(getNestedValue(obj, 'formData.email')).toBeUndefined();
});
it('should return undefined when obj is undefined', () => {
expect(getNestedValue(undefined, 'any.path')).toBeUndefined();
});
it('should handle deeply nested paths', () => {
const obj = { a: { b: { c: { d: 'value' } } } };
expect(getNestedValue(obj, 'a.b.c.d')).toBe('value');
});
});
describe('setNestedValue', () => {
it('should set value at simple path', () => {
const obj = { formData: { name: '' } };
const result = setNestedValue(obj, 'formData.email', 'test@example.com');
expect(result.formData.email).toBe('test@example.com');
expect(result.formData.name).toBe(''); // 기존 값 유지
});
it('should preserve immutability', () => {
const obj = { formData: { email: '' } };
const result = setNestedValue(obj, 'formData.email', 'new@example.com');
expect(obj.formData.email).toBe(''); // 원본 불변
expect(result.formData.email).toBe('new@example.com');
});
it('should handle single key path', () => {
const obj = { email: '' };
const result = setNestedValue(obj, 'email', 'test@example.com');
expect(result.email).toBe('test@example.com');
});
it('should create nested structure if not exists', () => {
const obj = {};
const result = setNestedValue(obj, 'a.b.c', 'value');
expect(result.a.b.c).toBe('value');
});
});
describe('updateByScope - isolated', () => {
let mockIsolatedContext: any;
let context: FormContextValue;
beforeEach(() => {
mockIsolatedContext = {
state: { miniForm: { email: '' } },
mergeState: vi.fn(),
};
context = {
dataKey: '_isolated.miniForm',
isolatedContext: mockIsolatedContext,
setState: vi.fn(),
state: {},
};
});
it('should update isolated state when scope is isolated', () => {
updateByScope('_isolated.miniForm', 'email', 'test@example.com', context);
expect(mockIsolatedContext.mergeState).toHaveBeenCalledWith({
miniForm: { email: 'test@example.com' },
});
expect(context.setState).not.toHaveBeenCalled();
});
it('should handle empty path', () => {
updateByScope('_isolated.miniForm', '', { email: 'test@example.com' }, context);
expect(mockIsolatedContext.mergeState).toHaveBeenCalledWith({
miniForm: { email: 'test@example.com' },
});
});
});
describe('updateByScope - local', () => {
let context: FormContextValue;
beforeEach(() => {
context = {
dataKey: 'formData',
setState: vi.fn(),
state: { formData: {} },
isolatedContext: null,
};
});
it('should update local state when scope is local', () => {
updateByScope('formData', 'email', 'test@example.com', context);
expect(context.setState).toHaveBeenCalledWith({
formData: { email: 'test@example.com' },
});
});
it('should handle _local prefix', () => {
updateByScope('_local.formData', 'email', 'test@example.com', context);
expect(context.setState).toHaveBeenCalledWith({
formData: { email: 'test@example.com' },
});
});
});
describe('updateByScope - global', () => {
let originalG7Core: any;
beforeEach(() => {
originalG7Core = (window as any).G7Core;
(window as any).G7Core = {
state: {
set: vi.fn(),
},
};
});
afterEach(() => {
(window as any).G7Core = originalG7Core;
});
it('should update global state when scope is global', () => {
const context: FormContextValue = {
dataKey: '_global.settings',
setState: vi.fn(),
state: {},
};
updateByScope('_global.settings', 'theme', 'dark', context);
expect((window as any).G7Core.state.set).toHaveBeenCalledWith({
settings: { theme: 'dark' },
});
expect(context.setState).not.toHaveBeenCalled();
});
});
describe('getValueByScope - isolated', () => {
it('should get value from isolated state', () => {
const context: FormContextValue = {
dataKey: '_isolated.miniForm',
isolatedContext: {
state: { miniForm: { email: 'test@example.com' } },
setState: vi.fn(),
getState: vi.fn(),
mergeState: vi.fn(),
},
state: {},
};
const value = getValueByScope('_isolated.miniForm', 'email', context);
expect(value).toBe('test@example.com');
});
it('should return undefined when isolatedContext is null', () => {
const context: FormContextValue = {
dataKey: '_isolated.miniForm',
isolatedContext: null,
state: {},
};
const value = getValueByScope('_isolated.miniForm', 'email', context);
expect(value).toBeUndefined();
});
});
describe('getValueByScope - local', () => {
it('should get value from local state', () => {
const context: FormContextValue = {
dataKey: 'formData',
state: { formData: { email: 'local@example.com' } },
};
const value = getValueByScope('formData', 'email', context);
expect(value).toBe('local@example.com');
});
});
describe('isAutoBindingEnabled', () => {
it('should return true when all conditions met', () => {
const context: FormContextValue = {
dataKey: 'formData',
setState: vi.fn(),
};
expect(isAutoBindingEnabled(context, 'email')).toBe(true);
});
it('should return false when dataKey is missing', () => {
const context: FormContextValue = {
setState: vi.fn(),
};
expect(isAutoBindingEnabled(context, 'email')).toBe(false);
});
it('should return false when name is missing', () => {
const context: FormContextValue = {
dataKey: 'formData',
setState: vi.fn(),
};
expect(isAutoBindingEnabled(context, undefined)).toBe(false);
});
it('should return false when setState is missing', () => {
const context: FormContextValue = {
dataKey: 'formData',
};
expect(isAutoBindingEnabled(context, 'email')).toBe(false);
});
});
describe('getAutoBindingPath', () => {
it('should combine dataKey and name', () => {
expect(getAutoBindingPath('formData', 'email')).toBe('formData.email');
});
it('should work with isolated prefix', () => {
expect(getAutoBindingPath('_isolated.miniForm', 'email')).toBe('_isolated.miniForm.email');
});
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,450 @@
/**
* TemplateApp.resolveRouteExpressions() 테스트
*
* routes.json의 path/redirect 내 {{expression}} 표현식을 DataBindingEngine으로
* 평가하는 기능을 검증합니다.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { TemplateApp } from '../TemplateApp';
import type { TemplateAppConfig } from '../TemplateApp';
import type { Route } from '../routing/Router';
// 공유 ActionDispatcher mock 객체 (vi.mock 호이스팅 대응)
const { sharedActionDispatcher } = vi.hoisted(() => ({
sharedActionDispatcher: {
setNavigate: vi.fn(),
setGlobalState: vi.fn(),
setDefaultContext: vi.fn(),
setGlobalStateUpdater: vi.fn(),
registerHandler: vi.fn(),
customHandlers: new Map(),
},
}));
vi.mock('../template-engine', () => ({
initTemplateEngine: vi.fn().mockResolvedValue(undefined),
renderTemplate: vi.fn().mockResolvedValue(undefined),
destroyTemplate: vi.fn(),
getActionDispatcher: vi.fn().mockReturnValue(sharedActionDispatcher),
getState: vi.fn().mockReturnValue({
actionDispatcher: sharedActionDispatcher,
reactRoot: null,
currentLayoutJson: null,
}),
}));
vi.mock('../template-engine/TransitionManager', () => ({
transitionManager: {
setPending: vi.fn(),
getIsPending: vi.fn(() => false),
subscribe: vi.fn(() => vi.fn()),
clearSubscribers: vi.fn(),
},
}));
vi.mock('../routing/Router', () => ({
Router: vi.fn(function (this: any) {
this.loadRoutes = vi.fn().mockResolvedValue(undefined);
this.on = vi.fn();
this.navigateToCurrentPath = vi.fn();
this.getRoutes = vi.fn().mockReturnValue([]);
this.setRoutes = vi.fn();
}),
}));
vi.mock('../template-engine/LayoutLoader', () => ({
LayoutLoader: vi.fn(function (this: any) {
this.loadLayout = vi.fn().mockResolvedValue({ components: [] });
}),
}));
vi.mock('../template-engine/ComponentRegistry', () => {
const mockInstance = {
loadComponents: vi.fn().mockResolvedValue(undefined),
getComponent: vi.fn().mockReturnValue(() => null),
hasComponent: vi.fn().mockReturnValue(true),
getInstance: vi.fn(),
};
mockInstance.getInstance.mockReturnValue(mockInstance);
return {
ComponentRegistry: {
getInstance: vi.fn(() => mockInstance),
},
};
});
describe('resolveRouteExpressions', () => {
let app: TemplateApp;
let resolveRouteExpressions: (routes: Route[]) => Route[];
const config: TemplateAppConfig = {
templateId: 'test-template',
templateType: 'user',
locale: 'ko',
debug: false,
};
/** routes.json에서 사용하는 이커머스 경로 표현식 */
const ECOMMERCE_PATH_EXPR =
"/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.no_route ? '' : (_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop')}}";
beforeEach(() => {
// localStorage mock
const store: Record<string, string> = {};
Object.defineProperty(global, 'localStorage', {
value: {
getItem: vi.fn((key: string) => store[key] ?? null),
setItem: vi.fn((key: string, val: string) => {
store[key] = val;
}),
removeItem: vi.fn((key: string) => {
delete store[key];
}),
},
writable: true,
configurable: true,
});
// window.G7Config mock
(window as any).G7Config = {};
// DOM 요소 mock
const appDiv = document.createElement('div');
appDiv.id = 'app';
document.body.appendChild(appDiv);
app = new TemplateApp(config);
resolveRouteExpressions = (app as any).resolveRouteExpressions.bind(app);
});
afterEach(() => {
const appDiv = document.getElementById('app');
if (appDiv) document.body.removeChild(appDiv);
vi.clearAllMocks();
delete (window as any).G7Config;
});
describe('기본 표현식 치환', () => {
it('route_path가 "shop"일 때 경로를 올바르게 치환', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/shop/cart');
});
it('route_path가 "store"일 때 경로를 올바르게 치환', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'store' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/store/cart');
});
it('route_path가 "mall/items"일 때 중첩 경로를 올바르게 치환', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'mall/items' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/mall/items/cart');
});
it('경로 prefix만 있는 경우 (index 페이지 → /products)', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/products`, layout: 'shop/index' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/shop/products');
});
it('라우트 파라미터가 포함된 경로 치환', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [
{ path: `${ECOMMERCE_PATH_EXPR}/products/:id`, layout: 'shop/show' },
{ path: `${ECOMMERCE_PATH_EXPR}/category/:slug`, layout: 'shop/category' },
{ path: `${ECOMMERCE_PATH_EXPR}/orders/:id/complete`, layout: 'shop/order_complete' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/shop/products/:id');
expect(result[1].path).toBe('/shop/category/:slug');
expect(result[2].path).toBe('/shop/orders/:id/complete');
});
});
describe('no_route 처리', () => {
it('no_route=true일 때 빈 prefix (이중 슬래시 자동 정리)', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { no_route: true, route_path: 'shop' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/cart');
});
it('no_route=false일 때 정상 prefix', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { no_route: false, route_path: 'shop' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/shop/cart');
});
it('no_route 미설정(undefined)일 때 정상 prefix', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/shop/cart');
});
it('no_route=true + index 경로 → /products로 정리', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { no_route: true, route_path: 'shop' } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/products`, layout: 'shop/index' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/products');
});
});
describe('이중 슬래시 정리', () => {
it('빈 값 치환 시 이중 슬래시를 단일 슬래시로 정리', () => {
// no_route=true → 빈 문자열 → //cart → /cart
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { no_route: true } },
};
const routes: Route[] = [{ path: `${ECOMMERCE_PATH_EXPR}/checkout`, layout: 'shop/checkout' }];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/checkout');
expect(result[0].path).not.toContain('//');
});
it('여러 하위 경로에서도 이중 슬래시 정리', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { no_route: true } },
};
const routes: Route[] = [
{ path: `${ECOMMERCE_PATH_EXPR}/orders/:id/complete`, layout: 'shop/order_complete' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/orders/:id/complete');
});
});
describe('표현식 없는 경로', () => {
it('일반 정적 경로를 그대로 통과', () => {
const routes: Route[] = [
{ path: '/about', layout: 'policy/about' },
{ path: '/login', layout: 'auth/login' },
{ path: '/mypage/profile', layout: 'mypage/profile' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/about');
expect(result[1].path).toBe('/login');
expect(result[2].path).toBe('/mypage/profile');
});
it('라우트 파라미터가 포함된 정적 경로를 그대로 통과', () => {
const routes: Route[] = [
{ path: '/board/:slug', layout: 'board/index' },
{ path: '/board/:slug/:id', layout: 'board/show' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/board/:slug');
expect(result[1].path).toBe('/board/:slug/:id');
});
it('다른 route 속성(layout, meta 등)을 변경하지 않음', () => {
const routes: Route[] = [
{
path: `${ECOMMERCE_PATH_EXPR}/cart`,
layout: 'shop/cart',
auth_required: false,
meta: { title: '$t:user.shop.cart_title' },
},
];
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const result = resolveRouteExpressions(routes);
expect(result[0].layout).toBe('shop/cart');
expect(result[0].auth_required).toBe(false);
expect(result[0].meta?.title).toBe('$t:user.shop.cart_title');
});
});
describe('redirect 표현식', () => {
it('redirect에 표현식이 있으면 치환', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [
{ path: '/old-shop', redirect: `${ECOMMERCE_PATH_EXPR}` },
];
const result = resolveRouteExpressions(routes);
expect(result[0].redirect).toBe('/shop');
expect(result[0].path).toBe('/old-shop');
});
it('redirect가 없는 route는 무시', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [
{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].redirect).toBeUndefined();
expect(result[0].path).toBe('/shop/cart');
});
});
describe('플러그인/코어 설정 참조', () => {
it('플러그인 설정을 참조하여 경로 치환', () => {
(app as any).globalState.plugins = {
'sirsoft-payment': { api_mode: 'sandbox' },
};
const routes: Route[] = [
{ path: "/pay/{{_global.plugins?.['sirsoft-payment']?.api_mode ?? 'live'}}", layout: 'pay' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/pay/sandbox');
});
it('코어 설정을 참조하여 경로 치환', () => {
(app as any).globalState.settings = {
general: { site_slug: 'mysite' },
};
const routes: Route[] = [
{ path: "/{{_global.settings?.general?.site_slug}}/home", layout: 'home' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/mysite/home');
});
});
describe('엣지 케이스', () => {
it('빈 routes 배열을 처리', () => {
const result = resolveRouteExpressions([]);
expect(result).toEqual([]);
});
it('_global에 modules 키가 없을 때 fallback 기본값 사용', () => {
// globalState에 modules가 없는 상태
(app as any).globalState.modules = undefined;
const routes: Route[] = [
{
path: "/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop'}}/cart",
layout: 'shop/cart',
},
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/shop/cart');
});
it('경로에 다중 표현식을 처리', () => {
(app as any).globalState.settings = { section: 'admin' };
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [
{
path: "/{{_global.settings?.section ?? 'user'}}/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop'}}",
layout: 'test',
},
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/admin/shop');
});
it('원본 route 객체를 변경하지 않음 (immutability)', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const originalRoutes: Route[] = [
{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' },
];
const originalPath = originalRoutes[0].path;
resolveRouteExpressions(originalRoutes);
expect(originalRoutes[0].path).toBe(originalPath);
});
it('여러 route를 한꺼번에 처리 (실제 routes.json 시나리오)', () => {
(app as any).globalState.modules = {
'sirsoft-ecommerce': { basic_info: { route_path: 'shop' } },
};
const routes: Route[] = [
{ path: '/', layout: 'home' },
{ path: '/login', layout: 'auth/login' },
{ path: `${ECOMMERCE_PATH_EXPR}/products`, layout: 'shop/index' },
{ path: `${ECOMMERCE_PATH_EXPR}/category/:slug`, layout: 'shop/category' },
{ path: `${ECOMMERCE_PATH_EXPR}/products/:id`, layout: 'shop/show' },
{ path: `${ECOMMERCE_PATH_EXPR}/cart`, layout: 'shop/cart' },
{ path: `${ECOMMERCE_PATH_EXPR}/checkout`, layout: 'shop/checkout' },
{ path: `${ECOMMERCE_PATH_EXPR}/orders/:id/complete`, layout: 'shop/order_complete' },
{ path: '/mypage/orders', layout: 'mypage/orders' },
];
const result = resolveRouteExpressions(routes);
expect(result[0].path).toBe('/');
expect(result[1].path).toBe('/login');
expect(result[2].path).toBe('/shop/products');
expect(result[3].path).toBe('/shop/category/:slug');
expect(result[4].path).toBe('/shop/products/:id');
expect(result[5].path).toBe('/shop/cart');
expect(result[6].path).toBe('/shop/checkout');
expect(result[7].path).toBe('/shop/orders/:id/complete');
expect(result[8].path).toBe('/mypage/orders');
});
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,178 @@
/**
* 레이아웃 전환 시 전체 컨테이너 블러 테스트
*
* React 18의 비동기 root.render()로 인해 레이아웃 전환 시
* 이전 DOM이 잠깐 보이는 현상을 방지하기 위한 컨테이너 블러 로직 검증
* @since engine-v1.23.0
*/
import { describe, it, expect } from 'vitest';
/**
* TemplateApp.ts의 레이아웃 전환 블러 로직을 순수 함수로 추출하여 테스트
* 실제 코드 경로: TemplateApp.ts renderTemplate 호출 전후
*/
interface BlurTestParams {
currentLayoutName: string;
newLayoutName: string;
containerId: string;
}
/**
* isLayoutChanged 계산 로직 (TemplateApp.ts 963행)
*/
function computeIsLayoutChanged(currentLayoutName: string, newLayoutName: string): boolean {
return currentLayoutName !== '' && currentLayoutName !== newLayoutName;
}
/**
* 블러 적용 조건 판단
*/
function shouldApplyContainerBlur(params: BlurTestParams): boolean {
const isLayoutChanged = computeIsLayoutChanged(params.currentLayoutName, params.newLayoutName);
const container = document.getElementById(params.containerId);
return isLayoutChanged && container !== null;
}
/**
* 블러 스타일 적용 (실제 TemplateApp.ts 로직과 동일)
*/
function applyContainerBlur(container: HTMLElement): void {
container.style.opacity = '0.5';
container.style.filter = 'blur(4px)';
container.style.transition = 'opacity 0.15s ease, filter 0.15s ease';
container.style.pointerEvents = 'none';
}
/**
* 블러 스타일 해제 (실제 TemplateApp.ts 로직과 동일)
*/
function removeContainerBlur(container: HTMLElement): void {
container.style.opacity = '';
container.style.filter = '';
container.style.transition = '';
container.style.pointerEvents = '';
}
describe('레이아웃 전환 컨테이너 블러', () => {
describe('isLayoutChanged 계산', () => {
it('첫 페이지 로드 (currentLayoutName === "") → false', () => {
expect(computeIsLayoutChanged('', 'board/show')).toBe(false);
});
it('같은 레이아웃 → false', () => {
expect(computeIsLayoutChanged('board/show', 'board/show')).toBe(false);
});
it('다른 레이아웃 → true', () => {
expect(computeIsLayoutChanged('board/index', 'board/show')).toBe(true);
});
it('board/show → board/index → board/show (중간 경유) → true', () => {
expect(computeIsLayoutChanged('board/index', 'board/show')).toBe(true);
});
});
describe('블러 적용 조건', () => {
it('레이아웃 변경 + 컨테이너 존재 → 블러 적용', () => {
const container = document.createElement('div');
container.id = 'app';
document.body.appendChild(container);
expect(shouldApplyContainerBlur({
currentLayoutName: 'board/index',
newLayoutName: 'board/show',
containerId: 'app',
})).toBe(true);
document.body.removeChild(container);
});
it('같은 레이아웃 → 블러 미적용', () => {
const container = document.createElement('div');
container.id = 'app';
document.body.appendChild(container);
expect(shouldApplyContainerBlur({
currentLayoutName: 'board/show',
newLayoutName: 'board/show',
containerId: 'app',
})).toBe(false);
document.body.removeChild(container);
});
it('첫 페이지 로드 → 블러 미적용', () => {
const container = document.createElement('div');
container.id = 'app';
document.body.appendChild(container);
expect(shouldApplyContainerBlur({
currentLayoutName: '',
newLayoutName: 'board/show',
containerId: 'app',
})).toBe(false);
document.body.removeChild(container);
});
it('컨테이너 미존재 → 블러 미적용', () => {
expect(shouldApplyContainerBlur({
currentLayoutName: 'board/index',
newLayoutName: 'board/show',
containerId: 'nonexistent',
})).toBe(false);
});
});
describe('블러 스타일 적용/해제', () => {
it('블러 적용 시 올바른 CSS 스타일 설정', () => {
const container = document.createElement('div');
applyContainerBlur(container);
expect(container.style.opacity).toBe('0.5');
expect(container.style.filter).toBe('blur(4px)');
expect(container.style.pointerEvents).toBe('none');
expect(container.style.transition).toContain('opacity');
expect(container.style.transition).toContain('filter');
});
it('블러 해제 시 모든 스타일 초기화', () => {
const container = document.createElement('div');
applyContainerBlur(container);
removeContainerBlur(container);
expect(container.style.opacity).toBe('');
expect(container.style.filter).toBe('');
expect(container.style.pointerEvents).toBe('');
expect(container.style.transition).toBe('');
});
it('블러 해제 후 기존 스타일에 영향 없음', () => {
const container = document.createElement('div');
container.style.backgroundColor = 'red';
container.style.display = 'flex';
applyContainerBlur(container);
removeContainerBlur(container);
expect(container.style.backgroundColor).toBe('red');
expect(container.style.display).toBe('flex');
});
});
describe('시나리오: 자유게시판 글 → 공지사항 목록 → 공지사항 글', () => {
it('board/show → board/index: 레이아웃 변경 → 블러 적용', () => {
expect(computeIsLayoutChanged('board/show', 'board/index')).toBe(true);
});
it('board/index → board/show: 레이아웃 변경 → 블러 적용', () => {
expect(computeIsLayoutChanged('board/index', 'board/show')).toBe(true);
});
it('board/show → board/show (같은 게시판 내 이동): 블러 미적용', () => {
expect(computeIsLayoutChanged('board/show', 'board/show')).toBe(false);
});
});
});
@@ -0,0 +1,284 @@
/**
* skeleton 3단계 fallback chain 단위 테스트
*
* 네비게이션 컨텍스트에 따라 스켈레톤 범위가 달라지는 로직 검증:
* 1. target DOM 존재 → 해당 영역만 (페이지 내부 전환)
* 2. fallback_target 존재 → 해당 영역만 (페이지 전환)
* 3. 둘 다 미존재 → 전체 페이지 (#app fullpage)
*
* @since engine-v1.24.2
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
// --- renderSkeletonOverlay에서 추출한 핵심 로직 ---
type SkeletonScope = 'target' | 'fallback' | 'fullpage';
interface FallbackResult {
targetEl: HTMLElement | null;
skeletonScope: SkeletonScope;
}
/**
* 3단계 fallback chain (TemplateApp.renderSkeletonOverlay 내부 로직)
*
* target → fallback_target → #app
*/
function resolveFallbackChain(target: string, fallbackTarget?: string): FallbackResult {
let targetEl = document.getElementById(target);
let skeletonScope: SkeletonScope = 'target';
if (!targetEl && fallbackTarget) {
targetEl = document.getElementById(fallbackTarget);
skeletonScope = 'fallback';
}
if (!targetEl) {
targetEl = document.getElementById('app');
skeletonScope = 'fullpage';
}
return { targetEl, skeletonScope };
}
/**
* CSS ::after 타겟 ID 결정 (TemplateApp.renderSkeletonOverlay 내부 로직)
*/
function getCssTargetId(skeletonScope: SkeletonScope, target: string, fallbackTarget?: string): string {
if (skeletonScope === 'fullpage') return 'app';
if (skeletonScope === 'fallback') return fallbackTarget!;
return target;
}
/**
* 스켈레톤 컴포넌트 트리 결정 (TemplateApp.renderSkeletonOverlay 내부 로직)
*
* fullpage: 전체 컴포넌트 트리
* fallback/target: findComponentChildrenById로 추출한 하위 트리
*/
function resolveComponentTree(
skeletonScope: SkeletonScope,
components: any[],
target: string,
fallbackTarget?: string,
findChildrenById?: (components: any[], id: string) => any[]
): any[] {
if (skeletonScope === 'fullpage') {
return components;
}
const searchId = skeletonScope === 'fallback' ? fallbackTarget! : target;
return findChildrenById ? findChildrenById(components, searchId) : [];
}
// --- 테스트 ---
describe('skeleton 3단계 fallback chain (@since engine-v1.24.2)', () => {
let appEl: HTMLDivElement;
beforeEach(() => {
// #app은 항상 존재 (React 렌더 컨테이너)
appEl = document.createElement('div');
appEl.id = 'app';
document.body.appendChild(appEl);
});
afterEach(() => {
// DOM 정리
['app', 'main_content_area', 'mypage_tab_content'].forEach(id => {
const el = document.getElementById(id);
if (el) el.remove();
});
});
describe('resolveFallbackChain', () => {
it('target DOM 존재 시 scope=target으로 해결해야 한다', () => {
const targetEl = document.createElement('div');
targetEl.id = 'mypage_tab_content';
document.body.appendChild(targetEl);
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('target');
expect(result.targetEl).toBe(targetEl);
});
it('target 미존재 + fallback_target 존재 시 scope=fallback으로 해결해야 한다', () => {
const fallbackEl = document.createElement('div');
fallbackEl.id = 'main_content_area';
document.body.appendChild(fallbackEl);
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('fallback');
expect(result.targetEl).toBe(fallbackEl);
});
it('target + fallback_target 모두 미존재 시 scope=fullpage (#app)로 해결해야 한다', () => {
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('fullpage');
expect(result.targetEl).toBe(appEl);
});
it('fallback_target 미지정 + target 미존재 시 scope=fullpage로 해결해야 한다', () => {
const result = resolveFallbackChain('mypage_tab_content');
expect(result.skeletonScope).toBe('fullpage');
expect(result.targetEl).toBe(appEl);
});
it('#app도 미존재 시 targetEl=null을 반환해야 한다', () => {
appEl.remove();
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('fullpage');
expect(result.targetEl).toBeNull();
});
it('fallback_target 없이 target만 존재 시 scope=target으로 해결해야 한다', () => {
const targetEl = document.createElement('div');
targetEl.id = 'main_content_area';
document.body.appendChild(targetEl);
const result = resolveFallbackChain('main_content_area');
expect(result.skeletonScope).toBe('target');
expect(result.targetEl).toBe(targetEl);
});
});
describe('getCssTargetId', () => {
it('scope=target일 때 target ID를 반환해야 한다', () => {
expect(getCssTargetId('target', 'mypage_tab_content', 'main_content_area'))
.toBe('mypage_tab_content');
});
it('scope=fallback일 때 fallback_target ID를 반환해야 한다', () => {
expect(getCssTargetId('fallback', 'mypage_tab_content', 'main_content_area'))
.toBe('main_content_area');
});
it('scope=fullpage일 때 "app"을 반환해야 한다', () => {
expect(getCssTargetId('fullpage', 'mypage_tab_content', 'main_content_area'))
.toBe('app');
});
});
describe('resolveComponentTree', () => {
const fullTree = [
{ id: 'header', name: 'Header', children: [] },
{
id: 'main_content_area', name: 'Div', children: [
{ id: 'tab_nav', name: 'TabNavigation', children: [] },
{
id: 'mypage_tab_content', name: 'Div', children: [
{ id: 'orders_list', name: 'Div', children: [] },
],
},
],
},
{ id: 'footer', name: 'Footer', children: [] },
];
function mockFindChildrenById(components: any[], id: string): any[] {
for (const comp of components) {
if (comp.id === id) return comp.children || [];
if (comp.children) {
const found = mockFindChildrenById(comp.children, id);
if (found.length > 0) return found;
}
}
return [];
}
it('scope=fullpage일 때 전체 컴포넌트 트리를 반환해야 한다', () => {
const result = resolveComponentTree('fullpage', fullTree, 'mypage_tab_content', 'main_content_area', mockFindChildrenById);
expect(result).toBe(fullTree);
expect(result).toHaveLength(3); // header + content + footer
});
it('scope=fallback일 때 fallback_target의 자식만 반환해야 한다', () => {
const result = resolveComponentTree('fallback', fullTree, 'mypage_tab_content', 'main_content_area', mockFindChildrenById);
expect(result).toHaveLength(2); // tab_nav + mypage_tab_content
expect(result[0].id).toBe('tab_nav');
expect(result[1].id).toBe('mypage_tab_content');
});
it('scope=target일 때 target의 자식만 반환해야 한다', () => {
const result = resolveComponentTree('target', fullTree, 'mypage_tab_content', 'main_content_area', mockFindChildrenById);
expect(result).toHaveLength(1); // orders_list only
expect(result[0].id).toBe('orders_list');
});
});
describe('실제 시나리오', () => {
it('초기 로드 (직접 URL 접속) — fullpage 스켈레톤', () => {
// 초기 로드: renderTemplate() 전이므로 target/fallback DOM 미존재
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('fullpage');
expect(result.targetEl!.id).toBe('app');
});
it('헤더에서 게시판→마이페이지 전환 — fallback (main_content_area) 스켈레톤', () => {
// 페이지 전환: main_content_area는 존재하지만 mypage_tab_content는 아직 없음
const mainEl = document.createElement('div');
mainEl.id = 'main_content_area';
document.body.appendChild(mainEl);
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('fallback');
expect(result.targetEl!.id).toBe('main_content_area');
});
it('마이페이지 내 탭 전환 (주문→프로필) — target (mypage_tab_content) 스켈레톤', () => {
// 마이페이지 내부 전환: 둘 다 존재
const mainEl = document.createElement('div');
mainEl.id = 'main_content_area';
document.body.appendChild(mainEl);
const tabEl = document.createElement('div');
tabEl.id = 'mypage_tab_content';
mainEl.appendChild(tabEl);
const result = resolveFallbackChain('mypage_tab_content', 'main_content_area');
expect(result.skeletonScope).toBe('target');
expect(result.targetEl!.id).toBe('mypage_tab_content');
});
it('일반 페이지 (fallback_target 미사용) — target 존재 시 target, 미존재 시 fullpage', () => {
// _user_base 기본 설정: target="main_content_area", fallback_target 없음
// 페이지 전환: main_content_area 존재
const mainEl = document.createElement('div');
mainEl.id = 'main_content_area';
document.body.appendChild(mainEl);
const result1 = resolveFallbackChain('main_content_area');
expect(result1.skeletonScope).toBe('target');
// 초기 로드: main_content_area 미존재
mainEl.remove();
const result2 = resolveFallbackChain('main_content_area');
expect(result2.skeletonScope).toBe('fullpage');
});
it('마이페이지에서 헤더→게시판 전환 — 게시판의 target (main_content_area) 사용', () => {
// 마이페이지 DOM이 있더라도, 게시판 레이아웃의 transition_overlay가 적용됨
// 게시판: target="main_content_area" (fallback_target 없음)
const mainEl = document.createElement('div');
mainEl.id = 'main_content_area';
document.body.appendChild(mainEl);
const result = resolveFallbackChain('main_content_area');
expect(result.skeletonScope).toBe('target');
expect(result.targetEl!.id).toBe('main_content_area');
});
});
});
@@ -0,0 +1,806 @@
/**
* template-engine.ts 테스트
*
* 템플릿 엔진의 초기화, 렌더링, 데이터 업데이트, 정리 기능 테스트
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { act } from '@testing-library/react';
import TemplateEngine, {
initTemplateEngine,
renderTemplate,
updateTemplateData,
destroyTemplate,
getState,
} from '../template-engine';
import { ComponentRegistry } from '../template-engine/ComponentRegistry';
import { Logger } from '../utils/Logger';
/**
* React 스케줄러가 pending work를 완료할 수 있도록 대기
* React 18 concurrent rendering으로 인해 unmount 후에도 비동기 작업이 남아있을 수 있음
*/
const flushReactScheduler = async () => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
};
// ComponentRegistry mock
vi.mock('../template-engine/ComponentRegistry', () => {
const mockInstance = {
loadComponents: vi.fn().mockResolvedValue(undefined),
getComponent: vi.fn().mockReturnValue(() => null),
hasComponent: vi.fn().mockReturnValue(true),
getInstance: vi.fn(),
};
mockInstance.getInstance.mockReturnValue(mockInstance);
return {
ComponentRegistry: {
getInstance: vi.fn(() => mockInstance),
},
};
});
// DataBindingEngine mock
vi.mock('../template-engine/DataBindingEngine', () => ({
DataBindingEngine: vi.fn(function(this: any) {
this.bind = vi.fn();
this.unbind = vi.fn();
}),
}));
// TranslationEngine mock
vi.mock('../template-engine/TranslationEngine', () => {
const mockInstance = {
translate: vi.fn((key: string) => key),
setLocale: vi.fn(),
loadTranslations: vi.fn().mockResolvedValue({}),
resolveTranslations: vi.fn((text: string) => text),
clearCache: vi.fn(),
};
return {
TranslationEngine: {
getInstance: vi.fn(() => mockInstance),
resetInstance: vi.fn(),
},
TranslationContext: {} as any,
};
});
// ActionDispatcher mock
vi.mock('../template-engine/ActionDispatcher', () => ({
ActionDispatcher: vi.fn(function(this: any) {
this.dispatch = vi.fn();
this.register = vi.fn();
}),
setActionDispatcherInstance: vi.fn(),
getActionDispatcher: vi.fn(() => ({
dispatch: vi.fn(),
register: vi.fn(),
})),
}));
// DynamicRenderer mock
vi.mock('../template-engine/DynamicRenderer', () => ({
default: vi.fn(() => null),
}));
// ResponsiveManager mock
vi.mock('../template-engine/ResponsiveManager', () => ({
responsiveManager: {
getWidth: vi.fn(() => 1024),
subscribe: vi.fn(() => () => {}),
getMatchingKey: vi.fn(() => null),
parseRange: vi.fn(() => null),
},
}));
// ResponsiveContext mock
vi.mock('../template-engine/ResponsiveContext', () => ({
ResponsiveProvider: ({ children }: { children: React.ReactNode }) => children,
useResponsive: vi.fn(() => ({
width: 1024,
isMobile: false,
isTablet: false,
isDesktop: true,
matchedPreset: 'desktop',
})),
}));
describe('TemplateEngine - initTemplateEngine()', () => {
beforeEach(() => {
// 각 테스트 전에 정리
destroyTemplate();
vi.clearAllMocks();
});
afterEach(async () => {
destroyTemplate();
await flushReactScheduler();
});
it('정상적으로 초기화되어야 함', async () => {
await initTemplateEngine({
templateId: 'test-template',
locale: 'ko',
});
const state = getState();
expect(state.isInitialized).toBe(true);
expect(state.templateId).toBe('test-template');
expect(state.locale).toBe('ko');
expect(state.registry).not.toBeNull();
expect(state.bindingEngine).not.toBeNull();
expect(state.translationEngine).not.toBeNull();
expect(state.actionDispatcher).not.toBeNull();
});
it('templateId가 필수여야 함', async () => {
// TemplateNotFoundError가 던져짐 (다국어 키 사용)
await expect(
initTemplateEngine({ templateId: '' })
).rejects.toThrow('$t:core.errors.template_not_found');
const state = getState();
expect(state.isInitialized).toBe(false);
});
it('locale 기본값은 "ko"여야 함', async () => {
await initTemplateEngine({ templateId: 'test-template' });
const state = getState();
expect(state.locale).toBe('ko');
});
it('locale을 지정할 수 있어야 함', async () => {
await initTemplateEngine({
templateId: 'test-template',
locale: 'en',
});
const state = getState();
expect(state.locale).toBe('en');
});
it('중복 초기화를 방지해야 함', async () => {
await initTemplateEngine({ templateId: 'test-template' });
await expect(
initTemplateEngine({ templateId: 'test-template-2' })
).rejects.toThrow('템플릿 엔진이 이미 초기화되었습니다');
});
// NOTE: ComponentRegistry.loadComponents()는 initTemplateEngine에서 호출되지 않음
// TemplateApp에서 routes.json과 함께 병렬로 로드됨 (성능 최적화)
it.skip('ComponentRegistry.loadComponents()를 호출해야 함', async () => {
const mockRegistry = ComponentRegistry.getInstance();
await initTemplateEngine({ templateId: 'test-template' });
expect(mockRegistry.loadComponents).toHaveBeenCalledWith('test-template', 'admin');
expect(mockRegistry.loadComponents).toHaveBeenCalledTimes(1);
});
// NOTE: ComponentRegistry.loadComponents()는 initTemplateEngine에서 호출되지 않음
// TemplateApp에서 별도로 로드됨
it.skip('초기화 실패 시 상태를 롤백해야 함', async () => {
const mockRegistry = ComponentRegistry.getInstance();
(mockRegistry.loadComponents as any).mockRejectedValueOnce(
new Error('Load failed')
);
await expect(
initTemplateEngine({ templateId: 'test-template' })
).rejects.toThrow('Load failed');
const state = getState();
expect(state.isInitialized).toBe(false);
expect(state.registry).toBeNull();
expect(state.bindingEngine).toBeNull();
});
it('debug 모드를 설정할 수 있어야 함', async () => {
// debug: true로 초기화 (로그 출력 확인은 수동)
await initTemplateEngine({
templateId: 'test-template',
debug: true,
});
const state = getState();
expect(state.isInitialized).toBe(true);
});
});
describe('TemplateEngine - renderTemplate()', () => {
beforeEach(async () => {
destroyTemplate();
vi.clearAllMocks();
// DOM 환경 준비
document.body.innerHTML = '<div id="app"></div>';
// 초기화
await initTemplateEngine({ templateId: 'test-template' });
});
afterEach(async () => {
destroyTemplate();
await flushReactScheduler();
document.body.innerHTML = '';
});
it('정상적으로 렌더링되어야 함', async () => {
const layoutJson = {
version: '1.0.0',
components: [
{
id: 'comp-1',
type: 'Text',
props: { text: 'Hello' },
children: [],
},
],
};
await renderTemplate({
containerId: 'app',
layoutJson,
});
const state = getState();
expect(state.reactRoot).not.toBeNull();
expect(state.containerId).toBe('app');
expect(state.currentLayoutJson).toEqual(layoutJson);
});
it('초기화 없이 렌더링 시 에러를 던져야 함', async () => {
destroyTemplate();
await expect(
renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
})
).rejects.toThrow('템플릿 엔진이 초기화되지 않았습니다');
});
it('containerId가 필수여야 함', async () => {
await expect(
renderTemplate({
containerId: '',
layoutJson: { components: [] },
})
).rejects.toThrow('containerId는 필수입니다');
});
it('layoutJson이 필수여야 함', async () => {
await expect(
renderTemplate({
containerId: 'app',
layoutJson: null as any,
})
).rejects.toThrow('layoutJson은 필수입니다');
});
it('존재하지 않는 containerId 시 에러를 던져야 함', async () => {
await expect(
renderTemplate({
containerId: 'non-existent',
layoutJson: { components: [] },
})
).rejects.toThrow('컨테이너를 찾을 수 없습니다: #non-existent');
});
it('dataContext를 전달할 수 있어야 함', async () => {
const dataContext = { userName: 'John', age: 30 };
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
dataContext,
});
const state = getState();
// 전역 변수($locale, $locales)도 함께 포함됨
expect(state.currentDataContext.userName).toBe('John');
expect(state.currentDataContext.age).toBe(30);
expect(state.currentDataContext.$locale).toBe('ko');
});
it('dataContext 기본값에 전역 변수가 포함되어야 함', async () => {
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
});
const state = getState();
// 전역 변수($locale, $locales)가 자동으로 추가됨
expect(state.currentDataContext.$locale).toBe('ko');
expect(state.currentDataContext.$locales).toBeDefined();
});
it('translationContext를 전달할 수 있어야 함', async () => {
const translationContext = {
templateId: 'custom-template',
locale: 'en',
};
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
translationContext,
});
const state = getState();
expect(state.translationContext).toEqual(translationContext);
});
it('translationContext 기본값은 templateId와 locale이어야 함', async () => {
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
});
const state = getState();
expect(state.translationContext).toEqual({
templateId: 'test-template',
locale: 'ko',
});
});
it('components가 비어있으면 경고를 출력해야 함', async () => {
// Logger 디버그 모드 활성화
Logger.getInstance().setDebug(true);
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
});
expect(consoleWarnSpy).toHaveBeenCalledWith('[TemplateEngine]', '렌더링할 컴포넌트가 없습니다.');
consoleWarnSpy.mockRestore();
Logger.getInstance().setDebug(false);
});
});
describe('TemplateEngine - updateTemplateData()', () => {
beforeEach(async () => {
destroyTemplate();
vi.clearAllMocks();
document.body.innerHTML = '<div id="app"></div>';
await initTemplateEngine({ templateId: 'test-template' });
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
dataContext: { a: 1, b: 2 },
});
});
afterEach(async () => {
destroyTemplate();
await flushReactScheduler();
document.body.innerHTML = '';
});
it('데이터를 병합하고 재렌더링해야 함', () => {
updateTemplateData({ b: 3, c: 4 });
const state = getState();
// 전역 변수($locale, $locales)도 함께 유지됨
expect(state.currentDataContext.a).toBe(1);
expect(state.currentDataContext.b).toBe(3);
expect(state.currentDataContext.c).toBe(4);
expect(state.currentDataContext.$locale).toBe('ko');
});
it('초기화 없이 업데이트 시 에러를 던져야 함', () => {
destroyTemplate();
expect(() => updateTemplateData({ a: 1 })).toThrow(
'템플릿 엔진이 초기화되지 않았습니다'
);
});
it('렌더링 없이 업데이트 시 에러를 던져야 함', async () => {
destroyTemplate();
await initTemplateEngine({ templateId: 'test-template' });
expect(() => updateTemplateData({ a: 1 })).toThrow(
'렌더링된 템플릿이 없습니다'
);
});
it('기존 데이터를 유지해야 함', () => {
updateTemplateData({ c: 3 });
const state = getState();
expect(state.currentDataContext.a).toBe(1);
expect(state.currentDataContext.b).toBe(2);
expect(state.currentDataContext.c).toBe(3);
});
it('빈 객체로 업데이트해도 작동해야 함', () => {
updateTemplateData({});
const state = getState();
// 기존 데이터와 전역 변수가 유지됨
expect(state.currentDataContext.a).toBe(1);
expect(state.currentDataContext.b).toBe(2);
expect(state.currentDataContext.$locale).toBe('ko');
});
it('_localInit 데이터를 데이터 컨텍스트에 저장해야 함', () => {
updateTemplateData({
_localInit: {
form: {
name: 'Test Role',
permission_ids: [1, 2, 3],
},
},
});
const state = getState();
expect(state.currentDataContext._localInit).toBeDefined();
expect(state.currentDataContext._localInit.form).toEqual({
name: 'Test Role',
permission_ids: [1, 2, 3],
});
});
it('sync 옵션으로 업데이트해도 정상 작동해야 함', () => {
updateTemplateData({ c: 5 }, { sync: true });
const state = getState();
expect(state.currentDataContext.a).toBe(1);
expect(state.currentDataContext.b).toBe(2);
expect(state.currentDataContext.c).toBe(5);
});
it('_localInit과 sync 옵션을 함께 사용해도 정상 작동해야 함', () => {
updateTemplateData(
{
_localInit: {
form: {
name: 'Clone Role',
description: 'Cloned description',
permission_ids: [10, 20, 30],
},
},
},
{ sync: true }
);
const state = getState();
expect(state.currentDataContext._localInit).toBeDefined();
expect(state.currentDataContext._localInit.form.name).toBe('Clone Role');
expect(state.currentDataContext._localInit.form.permission_ids).toEqual([10, 20, 30]);
});
// NOTE: vi.doMock으로 이미 로드된 react 모듈을 동적 모킹하면 ESM 환경에서 정상 작동하지 않음
// 실제 startTransition 호출은 template-engine.ts의 updateTemplateData 구현에서 확인 가능
it.skip('startTransition으로 렌더링을 래핑해야 함', async () => {
// React의 startTransition을 모킹
const mockStartTransition = vi.fn((callback) => callback());
// React 모듈을 동적으로 모킹
vi.doMock('react', () => ({
default: vi.fn(),
startTransition: mockStartTransition,
useDeferredValue: vi.fn(),
}));
// 새로운 환경에서 template-engine을 재로드
const { updateTemplateData: updateFn } = await import('../template-engine');
// 테스트 환경 재설정
destroyTemplate();
document.body.innerHTML = '<div id="app"></div>';
await initTemplateEngine({ templateId: 'test-template' });
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
dataContext: { a: 1 },
});
// 모킹 초기화
mockStartTransition.mockClear();
// 데이터 업데이트 실행
updateFn({ b: 2 });
// startTransition이 호출되었는지 검증
expect(mockStartTransition).toHaveBeenCalledTimes(1);
expect(mockStartTransition).toHaveBeenCalledWith(expect.any(Function));
// 모킹 해제
vi.doUnmock('react');
});
});
describe('TemplateEngine - destroyTemplate()', () => {
beforeEach(async () => {
destroyTemplate();
vi.clearAllMocks();
document.body.innerHTML = '<div id="app"></div>';
});
afterEach(async () => {
await flushReactScheduler();
document.body.innerHTML = '';
});
it('모든 상태를 초기화해야 함', async () => {
await initTemplateEngine({ templateId: 'test-template' });
await renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
});
destroyTemplate();
const state = getState();
expect(state.isInitialized).toBe(false);
expect(state.templateId).toBeNull();
expect(state.locale).toBe('ko');
expect(state.reactRoot).toBeNull();
expect(state.containerId).toBeNull();
expect(state.currentLayoutJson).toBeNull();
expect(state.currentDataContext).toEqual({});
expect(state.translationContext).toEqual({
templateId: '',
locale: 'ko',
});
expect(state.registry).toBeNull();
expect(state.bindingEngine).toBeNull();
expect(state.translationEngine).toBeNull();
expect(state.actionDispatcher).toBeNull();
});
it('초기화하지 않고 정리해도 에러가 발생하지 않아야 함', () => {
expect(() => destroyTemplate()).not.toThrow();
});
it('정리 후 재초기화가 가능해야 함', async () => {
await initTemplateEngine({ templateId: 'test-template-1' });
destroyTemplate();
await initTemplateEngine({ templateId: 'test-template-2' });
const state = getState();
expect(state.isInitialized).toBe(true);
expect(state.templateId).toBe('test-template-2');
});
});
describe('TemplateEngine - getState()', () => {
beforeEach(() => {
destroyTemplate();
});
afterEach(async () => {
destroyTemplate();
await flushReactScheduler();
});
it('현재 상태를 반환해야 함', async () => {
await initTemplateEngine({ templateId: 'test-template', locale: 'en' });
const state = getState();
expect(state).toHaveProperty('isInitialized');
expect(state).toHaveProperty('templateId');
expect(state).toHaveProperty('locale');
expect(state.templateId).toBe('test-template');
expect(state.locale).toBe('en');
});
it('읽기 전용 상태를 반환해야 함', () => {
const state = getState();
// Object.freeze()로 인해 수정 불가
expect(() => {
(state as any).templateId = 'hacked';
}).toThrow();
});
it('초기화 전 상태를 반환해야 함', () => {
const state = getState();
expect(state.isInitialized).toBe(false);
expect(state.templateId).toBeNull();
expect(state.locale).toBe('ko');
});
});
describe('TemplateEngine - 전체 라이프사이클 통합 테스트', () => {
beforeEach(() => {
destroyTemplate();
vi.clearAllMocks();
document.body.innerHTML = '<div id="integration-test"></div>';
});
afterEach(async () => {
destroyTemplate();
await flushReactScheduler();
document.body.innerHTML = '';
});
it('초기화 → 렌더링 → 업데이트 → 정리 흐름이 정상 작동해야 함', async () => {
// 1. 초기화
await initTemplateEngine({
templateId: 'integration-template',
locale: 'ko',
debug: false,
});
let state = getState();
expect(state.isInitialized).toBe(true);
expect(state.templateId).toBe('integration-template');
// 2. 렌더링
await renderTemplate({
containerId: 'integration-test',
layoutJson: {
version: '1.0.0',
components: [
{ id: 'text-1', type: 'Text', props: { text: '{{ message }}' } },
],
},
dataContext: { message: 'Hello' },
});
state = getState();
expect(state.reactRoot).not.toBeNull();
expect(state.currentDataContext.message).toBe('Hello');
// 3. 데이터 업데이트
updateTemplateData({ message: 'Updated' });
state = getState();
expect(state.currentDataContext.message).toBe('Updated');
// 4. 정리
destroyTemplate();
state = getState();
expect(state.isInitialized).toBe(false);
expect(state.reactRoot).toBeNull();
});
it('여러 번 렌더링해도 동일한 React Root를 재사용해야 함', async () => {
await initTemplateEngine({ templateId: 'test-template' });
await renderTemplate({
containerId: 'integration-test',
layoutJson: { components: [] },
});
const firstRoot = getState().reactRoot;
await renderTemplate({
containerId: 'integration-test',
layoutJson: { components: [] },
});
const secondRoot = getState().reactRoot;
expect(firstRoot).toBe(secondRoot);
});
});
describe('TemplateEngine - 전역 객체 노출 검증', () => {
it('window.G7Core.TemplateEngine이 존재해야 함', () => {
expect(window.G7Core).toBeDefined();
expect(window.G7Core.TemplateEngine).toBeDefined();
});
it('전역 객체와 ESM export가 동일해야 함', () => {
expect(window.G7Core.TemplateEngine).toBe(TemplateEngine);
});
it('모든 공개 함수가 노출되어야 함', () => {
expect(window.G7Core.TemplateEngine.initTemplateEngine).toBe(
initTemplateEngine
);
expect(window.G7Core.TemplateEngine.renderTemplate).toBe(renderTemplate);
expect(window.G7Core.TemplateEngine.updateTemplateData).toBe(
updateTemplateData
);
expect(window.G7Core.TemplateEngine.destroyTemplate).toBe(destroyTemplate);
expect(window.G7Core.TemplateEngine.getState).toBe(getState);
});
});
describe('TemplateEngine - 에러 처리 시나리오', () => {
beforeEach(() => {
destroyTemplate();
vi.clearAllMocks();
});
afterEach(async () => {
destroyTemplate();
await flushReactScheduler();
});
// NOTE: ComponentRegistry.loadComponents()는 initTemplateEngine에서 호출되지 않음
// TemplateApp에서 별도로 로드됨
it.skip('ComponentRegistry 로드 실패 시 적절한 에러를 던져야 함', async () => {
const mockRegistry = ComponentRegistry.getInstance();
const loadError = new Error('Network error');
(mockRegistry.loadComponents as any).mockRejectedValueOnce(loadError);
await expect(
initTemplateEngine({ templateId: 'test-template' })
).rejects.toThrow('Network error');
const state = getState();
expect(state.isInitialized).toBe(false);
});
it('잘못된 layoutJson으로 렌더링 시 에러를 던져야 함', async () => {
document.body.innerHTML = '<div id="app"></div>';
await initTemplateEngine({ templateId: 'test-template' });
await expect(
renderTemplate({
containerId: 'app',
layoutJson: undefined as any,
})
).rejects.toThrow('layoutJson은 필수입니다');
});
it('순서가 잘못된 호출 시 명확한 에러 메시지를 제공해야 함', async () => {
// renderTemplate before init
await expect(
renderTemplate({
containerId: 'app',
layoutJson: { components: [] },
})
).rejects.toThrow('템플릿 엔진이 초기화되지 않았습니다');
// updateTemplateData before init
expect(() => updateTemplateData({ a: 1 })).toThrow(
'템플릿 엔진이 초기화되지 않았습니다'
);
// updateTemplateData before render
await initTemplateEngine({ templateId: 'test' });
expect(() => updateTemplateData({ a: 1 })).toThrow(
'렌더링된 템플릿이 없습니다'
);
});
// NOTE: ComponentRegistry.loadComponents()는 initTemplateEngine에서 호출되지 않음
// TemplateApp에서 별도로 로드됨
it.skip('초기화 실패 후 재시도가 가능해야 함', async () => {
const mockRegistry = ComponentRegistry.getInstance();
// 첫 번째 시도 실패
(mockRegistry.loadComponents as any).mockRejectedValueOnce(
new Error('First attempt failed')
);
await expect(
initTemplateEngine({ templateId: 'test-template' })
).rejects.toThrow('First attempt failed');
// 두 번째 시도 성공
(mockRegistry.loadComponents as any).mockResolvedValueOnce(undefined);
await initTemplateEngine({ templateId: 'test-template' });
const state = getState();
expect(state.isInitialized).toBe(true);
});
});
@@ -0,0 +1,610 @@
/**
* transition_overlay 레이아웃 옵션 단위 테스트
*
* 페이지 전환 시 오버레이를 표시하여
* React 비동기 렌더링 중 stale DOM flash를 방지하는 기능 검증
*
* - target 지정 시: CSS <style> 주입 + ::after 의사 요소 (React 렌더 트리 외부)
* - target 미지정 시: DOM 오버레이 (document.body에 fixed)
*
* @since engine-v1.23.0
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
type SkeletonConfig = {
component: string;
animation?: 'pulse' | 'wave' | 'none';
iteration_count?: number;
};
type SpinnerConfig = {
component?: string;
text?: string;
};
type TransitionOverlayConfig = boolean | { enabled: boolean; style?: string; target?: string; skeleton?: SkeletonConfig; spinner?: SpinnerConfig };
interface NormalizedConfig {
enabled: boolean;
style: string;
target?: string;
skeleton?: SkeletonConfig;
spinner?: SpinnerConfig;
}
/**
* config 정규화 (TemplateApp.showTransitionOverlay 내부 로직)
*/
function normalizeConfig(config: TransitionOverlayConfig): NormalizedConfig {
return typeof config === 'boolean'
? { enabled: config, style: 'opaque' }
: { enabled: config.enabled, style: config.style || 'opaque', target: config.target, skeleton: config.skeleton, spinner: config.spinner };
}
/**
* 스타일별 CSS 생성
*/
function getStyleCss(style: string, isDark: boolean): { bgCss: string; extraCss: string } {
switch (style) {
case 'blur':
return {
bgCss: isDark ? 'rgba(17,24,39,0.3)' : 'rgba(255,255,255,0.3)',
extraCss: 'backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);',
};
case 'fade':
return {
bgCss: isDark ? 'rgba(17,24,39,0.8)' : 'rgba(255,255,255,0.8)',
extraCss: '',
};
case 'opaque':
default:
return {
bgCss: isDark ? 'rgb(17,24,39)' : 'rgb(249,250,251)',
extraCss: '',
};
}
}
/**
* 오버레이 생성 (TemplateApp.showTransitionOverlay 로직)
*
* - target 지정 시: <style> 태그를 <head>에 삽입 (::after 의사 요소)
* - target 미지정 시: <div> 오버레이를 body에 삽입 (position:fixed)
*/
function showTransitionOverlay(config: TransitionOverlayConfig): HTMLElement | null {
const normalized = normalizeConfig(config);
if (!normalized.enabled) return null;
// 기존 오버레이 제거
hideTransitionOverlay();
const isDark = document.documentElement.classList.contains('dark');
const { bgCss, extraCss } = getStyleCss(normalized.style, isDark);
if (normalized.target) {
// CSS <style> 주입 방식
const selector = `#${normalized.target}`;
const style = document.createElement('style');
style.id = 'g7-transition-overlay';
style.textContent = `${selector}{position:relative;z-index:0;}${selector}::after{content:'';position:absolute;inset:0;background:${bgCss};${extraCss}z-index:2147483647;pointer-events:none;}`;
document.head.appendChild(style);
return style;
} else {
// DOM 오버레이 방식 (폴백)
const overlay = document.createElement('div');
overlay.id = 'g7-transition-overlay';
overlay.setAttribute('aria-hidden', 'true');
overlay.style.cssText = `position:fixed;inset:0;z-index:9999;pointer-events:none;background:${bgCss};${extraCss}`;
document.body.appendChild(overlay);
return overlay;
}
}
/**
* 오버레이 제거 (TemplateApp.hideTransitionOverlay 로직)
*/
function hideTransitionOverlay(): void {
const existing = document.getElementById('g7-transition-overlay');
if (existing) existing.remove();
}
describe('transition_overlay', () => {
beforeEach(() => {
hideTransitionOverlay();
document.documentElement.classList.remove('dark');
});
afterEach(() => {
hideTransitionOverlay();
document.documentElement.classList.remove('dark');
const target = document.getElementById('main_content_area');
if (target) target.remove();
});
describe('normalizeConfig', () => {
it('true를 opaque 스타일로 정규화해야 한다', () => {
expect(normalizeConfig(true)).toEqual({ enabled: true, style: 'opaque' });
});
it('false를 enabled: false로 정규화해야 한다', () => {
expect(normalizeConfig(false)).toEqual({ enabled: false, style: 'opaque' });
});
it('객체 config를 그대로 반환해야 한다', () => {
expect(normalizeConfig({ enabled: true, style: 'blur' })).toEqual({ enabled: true, style: 'blur' });
});
it('style 미지정 시 opaque를 기본값으로 사용해야 한다', () => {
expect(normalizeConfig({ enabled: true })).toEqual({ enabled: true, style: 'opaque' });
});
it('target을 보존해야 한다', () => {
expect(normalizeConfig({ enabled: true, target: 'my_container' }))
.toEqual({ enabled: true, style: 'opaque', target: 'my_container' });
});
});
describe('target 미지정 — DOM 오버레이 (폴백)', () => {
it('transition_overlay: true 시 body에 fixed 오버레이를 생성해야 한다', () => {
const el = showTransitionOverlay(true);
expect(el).not.toBeNull();
expect(el!.tagName).toBe('DIV');
expect(el!.id).toBe('g7-transition-overlay');
expect(document.body.contains(el!)).toBe(true);
});
it('transition_overlay: false 시 오버레이를 생성하지 않아야 한다', () => {
const el = showTransitionOverlay(false);
expect(el).toBeNull();
expect(document.getElementById('g7-transition-overlay')).toBeNull();
});
it('공통 스타일(fixed, inset, z-index, pointer-events)이 적용되어야 한다', () => {
const el = showTransitionOverlay(true) as HTMLDivElement;
expect(el.style.position).toBe('fixed');
expect(el.style.inset).toBe('0');
expect(el.style.zIndex).toBe('9999');
expect(el.style.pointerEvents).toBe('none');
});
it('opaque 스타일 시 gray-50 배경을 사용해야 한다', () => {
const el = showTransitionOverlay(true) as HTMLDivElement;
expect(el.style.background).toBe('rgb(249, 250, 251)');
});
it('blur 스타일 시 backdrop-filter를 적용해야 한다', () => {
const el = showTransitionOverlay({ enabled: true, style: 'blur' }) as HTMLDivElement;
// happy-dom은 backdrop-filter를 CSS 프로퍼티로 인식하지 않으므로
// DOM 오버레이 폴백의 blur는 배경색만 검증하고,
// backdrop-filter는 CSS <style> 주입 모드 테스트에서 검증
expect(el.style.background).toBe('rgba(255, 255, 255, 0.3)');
});
it('fade 스타일 시 반투명 배경을 적용해야 한다', () => {
const el = showTransitionOverlay({ enabled: true, style: 'fade' }) as HTMLDivElement;
expect(el.style.background).toBe('rgba(255, 255, 255, 0.8)');
});
});
describe('target 지정 — CSS <style> 주입', () => {
function createTargetContainer(id: string): HTMLDivElement {
const container = document.createElement('div');
container.id = id;
document.body.appendChild(container);
return container;
}
it('target 지정 시 <style> 태그를 <head>에 삽입해야 한다', () => {
createTargetContainer('main_content_area');
const el = showTransitionOverlay({ enabled: true, target: 'main_content_area' });
expect(el).not.toBeNull();
expect(el!.tagName).toBe('STYLE');
expect(el!.id).toBe('g7-transition-overlay');
expect(document.head.contains(el!)).toBe(true);
});
it('CSS에 타겟 selector와 ::after 규칙이 포함되어야 한다', () => {
createTargetContainer('main_content_area');
const el = showTransitionOverlay({ enabled: true, target: 'main_content_area' });
const css = el!.textContent!;
expect(css).toContain('#main_content_area{position:relative;z-index:0;}');
expect(css).toContain('#main_content_area::after{');
expect(css).toContain('position:absolute;');
expect(css).toContain('inset:0;');
expect(css).toContain('pointer-events:none;');
});
it('opaque 스타일 시 gray-50 배경 CSS가 포함되어야 한다', () => {
createTargetContainer('main_content_area');
const el = showTransitionOverlay({ enabled: true, target: 'main_content_area' });
expect(el!.textContent).toContain('background:rgb(249,250,251)');
});
it('blur 스타일 시 backdrop-filter CSS가 포함되어야 한다', () => {
createTargetContainer('main_content_area');
const el = showTransitionOverlay({ enabled: true, target: 'main_content_area', style: 'blur' });
const css = el!.textContent!;
expect(css).toContain('backdrop-filter:blur(4px)');
expect(css).toContain('background:rgba(255,255,255,0.3)');
});
it('fade 스타일 시 반투명 배경 CSS가 포함되어야 한다', () => {
createTargetContainer('main_content_area');
const el = showTransitionOverlay({ enabled: true, target: 'main_content_area', style: 'fade' });
expect(el!.textContent).toContain('background:rgba(255,255,255,0.8)');
});
it('제거 시 <style> 태그가 <head>에서 삭제되어야 한다', () => {
createTargetContainer('main_content_area');
showTransitionOverlay({ enabled: true, target: 'main_content_area' });
expect(document.getElementById('g7-transition-overlay')).toBeTruthy();
hideTransitionOverlay();
expect(document.getElementById('g7-transition-overlay')).toBeNull();
});
});
describe('다크 모드', () => {
it('다크 모드에서 opaque DOM 오버레이 시 gray-900 배경을 사용해야 한다', () => {
document.documentElement.classList.add('dark');
const el = showTransitionOverlay(true) as HTMLDivElement;
expect(el.style.background).toBe('rgb(17, 24, 39)');
});
it('다크 모드에서 target CSS 주입 시 gray-900 배경이 포함되어야 한다', () => {
document.documentElement.classList.add('dark');
const container = document.createElement('div');
container.id = 'main_content_area';
document.body.appendChild(container);
const el = showTransitionOverlay({ enabled: true, target: 'main_content_area' });
expect(el!.textContent).toContain('background:rgb(17,24,39)');
});
it('다크 모드에서 blur 스타일 시 dark 반투명 배경을 사용해야 한다', () => {
document.documentElement.classList.add('dark');
const el = showTransitionOverlay({ enabled: true, style: 'blur' }) as HTMLDivElement;
expect(el.style.background).toBe('rgba(17, 24, 39, 0.3)');
});
});
describe('라우트 변경 시나리오', () => {
it('오버레이 표시 후 제거가 정상 동작해야 한다', () => {
showTransitionOverlay(true);
expect(document.getElementById('g7-transition-overlay')).toBeTruthy();
hideTransitionOverlay();
expect(document.getElementById('g7-transition-overlay')).toBeNull();
});
it('target CSS 주입 후 제거가 정상 동작해야 한다', () => {
const container = document.createElement('div');
container.id = 'content';
document.body.appendChild(container);
showTransitionOverlay({ enabled: true, target: 'content' });
expect(document.getElementById('g7-transition-overlay')).toBeTruthy();
hideTransitionOverlay();
expect(document.getElementById('g7-transition-overlay')).toBeNull();
container.remove();
});
it('중복 호출 시 기존 오버레이를 제거하고 새로 생성해야 한다', () => {
showTransitionOverlay(true);
showTransitionOverlay(true);
const overlays = document.querySelectorAll('#g7-transition-overlay');
expect(overlays.length).toBe(1);
});
it('hideTransitionOverlay 중복 호출 시 에러 없이 처리해야 한다', () => {
expect(() => {
hideTransitionOverlay();
hideTransitionOverlay();
}).not.toThrow();
});
});
describe('skeleton 스타일 (@since engine-v1.24.0)', () => {
it('skeleton 스타일을 정규화해야 한다', () => {
const config: TransitionOverlayConfig = {
enabled: true,
style: 'skeleton',
target: 'main_content_area',
skeleton: {
component: 'PageSkeleton',
animation: 'pulse',
iteration_count: 5,
},
};
const normalized = normalizeConfig(config);
expect(normalized.style).toBe('skeleton');
expect(normalized.target).toBe('main_content_area');
expect(normalized.skeleton).toEqual({
component: 'PageSkeleton',
animation: 'pulse',
iteration_count: 5,
});
});
it('skeleton 설정 없이 skeleton 스타일 시 opaque 폴백 CSS를 생성해야 한다', () => {
// skeleton 스타일이지만 skeleton 설정이 없으면 CSS 폴백
const el = showTransitionOverlay({ enabled: true, style: 'skeleton' }) as HTMLDivElement;
expect(el).not.toBeNull();
// opaque와 동일한 배경 (폴백)
expect(el.style.background).toBe('rgb(249, 250, 251)');
});
it('skeleton 설정의 기본값이 올바르게 적용되어야 한다', () => {
const config: TransitionOverlayConfig = {
enabled: true,
style: 'skeleton',
target: 'main_content_area',
skeleton: {
component: 'PageSkeleton',
},
};
const normalized = normalizeConfig(config);
expect(normalized.skeleton!.component).toBe('PageSkeleton');
expect(normalized.skeleton!.animation).toBeUndefined();
expect(normalized.skeleton!.iteration_count).toBeUndefined();
});
it('skeleton 스타일 다크 모드에서 opaque 폴백 시 gray-900 배경을 사용해야 한다', () => {
document.documentElement.classList.add('dark');
const el = showTransitionOverlay({ enabled: true, style: 'skeleton' }) as HTMLDivElement;
expect(el.style.background).toBe('rgb(17, 24, 39)');
});
});
describe('spinner 스타일 (@since engine-v1.29.0)', () => {
/**
* renderSpinnerOverlay 로직을 테스트 환경에서 재현
* (TemplateApp.renderSpinnerOverlay의 핵심 로직)
*/
function renderSpinnerOverlay(
target: string,
spinnerConfig?: SpinnerConfig,
fallbackTarget?: string
): { container: HTMLDivElement | null; style: HTMLStyleElement | null; scope: string } {
// 3단계 fallback chain
let targetEl = document.getElementById(target);
let scope = 'target';
if (!targetEl && fallbackTarget) {
targetEl = document.getElementById(fallbackTarget);
scope = 'fallback';
}
if (!targetEl) {
targetEl = document.getElementById('app');
scope = 'fullpage';
}
if (!targetEl) {
return { container: null, style: null, scope };
}
// 기존 오버레이 제거
hideSpinnerOverlay();
const isDark = document.documentElement.classList.contains('dark');
const bgColor = isDark ? 'rgb(17,24,39)' : 'rgb(249,250,251)';
const spinnerColor = isDark ? '#6b7280' : '#9ca3af';
// Step 1: CSS ::after 주입
const cssTargetId = scope === 'fullpage' ? 'app'
: scope === 'fallback' ? fallbackTarget!
: target;
const selector = `#${cssTargetId}`;
const styleEl = document.createElement('style');
styleEl.id = 'g7-skeleton-overlay-style';
styleEl.textContent = [
`${selector}{position:relative;z-index:0;}`,
`${selector}::after{content:'';position:absolute;inset:0;background:${bgColor};z-index:2147483646;pointer-events:none;}`,
`@keyframes g7-spin{to{transform:rotate(360deg)}}`,
].join('');
document.head.appendChild(styleEl);
// Step 2: 스피너 컨테이너 생성
const container = document.createElement('div');
container.id = 'g7-skeleton-overlay';
container.setAttribute('role', 'status');
container.setAttribute('aria-busy', 'true');
if (scope === 'fullpage') {
container.style.cssText = `position:fixed;inset:0;z-index:20;overflow:hidden;pointer-events:none;background:${bgColor};`;
} else {
container.style.cssText = `position:absolute;z-index:20;overflow:hidden;pointer-events:none;background:${bgColor};`;
}
// 기본 스피너 (커스텀 컴포넌트 없을 때)
container.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;height:100%;"><div style="width:32px;height:32px;border:3px solid ${spinnerColor};border-top-color:transparent;border-radius:50%;animation:g7-spin 0.8s linear infinite;"></div></div>`;
document.body.appendChild(container);
return { container, style: styleEl, scope };
}
function hideSpinnerOverlay(): void {
const container = document.getElementById('g7-skeleton-overlay');
if (container) container.remove();
const styleEl = document.getElementById('g7-skeleton-overlay-style');
if (styleEl) styleEl.remove();
}
function createTargetContainer(id: string): HTMLDivElement {
const container = document.createElement('div');
container.id = id;
document.body.appendChild(container);
return container;
}
afterEach(() => {
hideSpinnerOverlay();
const app = document.getElementById('app');
if (app) app.remove();
const mypage = document.getElementById('mypage_tab_content');
if (mypage) mypage.remove();
});
it('spinner 스타일을 정규화해야 한다', () => {
const config: TransitionOverlayConfig = {
enabled: true,
style: 'spinner',
target: 'main_content_area',
spinner: { component: 'PageLoading' },
};
const normalized = normalizeConfig(config);
expect(normalized.style).toBe('spinner');
expect(normalized.target).toBe('main_content_area');
expect(normalized.spinner).toEqual({ component: 'PageLoading' });
});
it('target 존재 시 해당 영역에 스피너 컨테이너를 생성해야 한다', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container).not.toBeNull();
expect(result.container!.id).toBe('g7-skeleton-overlay');
expect(result.scope).toBe('target');
expect(document.body.contains(result.container!)).toBe(true);
});
it('CSS ::after 스타일이 <head>에 주입되어야 한다', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.style).not.toBeNull();
expect(result.style!.id).toBe('g7-skeleton-overlay-style');
expect(document.head.contains(result.style!)).toBe(true);
expect(result.style!.textContent).toContain('#main_content_area::after{');
expect(result.style!.textContent).toContain('@keyframes g7-spin');
});
it('기본 스피너 DOM이 생성되어야 한다 (컴포넌트 미지정 시)', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container!.innerHTML).toContain('g7-spin');
expect(result.container!.innerHTML).toContain('border-radius:50%');
});
it('aria 속성이 올바르게 설정되어야 한다', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container!.getAttribute('role')).toBe('status');
expect(result.container!.getAttribute('aria-busy')).toBe('true');
});
it('3단계 fallback chain: target 미존재 시 fallback_target 사용', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('mypage_tab_content', undefined, 'main_content_area');
expect(result.scope).toBe('fallback');
expect(result.style!.textContent).toContain('#main_content_area::after{');
});
it('3단계 fallback chain: target과 fallback 모두 미존재 시 #app 사용', () => {
createTargetContainer('app');
const result = renderSpinnerOverlay('nonexistent', undefined, 'also_nonexistent');
expect(result.scope).toBe('fullpage');
expect(result.container!.style.position).toBe('fixed');
expect(result.style!.textContent).toContain('#app::after{');
});
it('모든 DOM 미존재 시 null 반환', () => {
const result = renderSpinnerOverlay('nonexistent');
expect(result.container).toBeNull();
expect(result.style).toBeNull();
});
it('다크 모드에서 올바른 배경색을 사용해야 한다', () => {
document.documentElement.classList.add('dark');
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container!.style.background).toBe('rgb(17, 24, 39)');
expect(result.style!.textContent).toContain('background:rgb(17,24,39)');
});
it('다크 모드에서 스피너 색상이 gray-500이어야 한다', () => {
document.documentElement.classList.add('dark');
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container!.innerHTML).toContain('#6b7280');
});
it('라이트 모드에서 스피너 색상이 gray-400이어야 한다', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container!.innerHTML).toContain('#9ca3af');
});
it('hideSpinnerOverlay로 컨테이너와 스타일이 모두 제거되어야 한다', () => {
createTargetContainer('main_content_area');
renderSpinnerOverlay('main_content_area');
expect(document.getElementById('g7-skeleton-overlay')).toBeTruthy();
expect(document.getElementById('g7-skeleton-overlay-style')).toBeTruthy();
hideSpinnerOverlay();
expect(document.getElementById('g7-skeleton-overlay')).toBeNull();
expect(document.getElementById('g7-skeleton-overlay-style')).toBeNull();
});
it('중복 호출 시 기존 오버레이를 제거하고 새로 생성해야 한다', () => {
createTargetContainer('main_content_area');
renderSpinnerOverlay('main_content_area');
renderSpinnerOverlay('main_content_area');
expect(document.querySelectorAll('#g7-skeleton-overlay').length).toBe(1);
expect(document.querySelectorAll('#g7-skeleton-overlay-style').length).toBe(1);
});
it('fullpage 모드에서 position:fixed를 사용해야 한다', () => {
createTargetContainer('app');
const result = renderSpinnerOverlay('nonexistent');
expect(result.container!.style.position).toBe('fixed');
expect(result.container!.style.inset).toBe('0');
});
it('target 모드에서 position:absolute를 사용해야 한다', () => {
createTargetContainer('main_content_area');
const result = renderSpinnerOverlay('main_content_area');
expect(result.container!.style.position).toBe('absolute');
});
});
});
+451
View File
@@ -0,0 +1,451 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { AuthManager } from '../auth/AuthManager';
import { createLogger } from '../utils/Logger';
import type { G7DevToolsCore } from '../devtools/G7DevToolsCore';
const logger = createLogger('ApiClient');
/**
* DevTools 인스턴스 가져오기
*/
function getDevTools(): G7DevToolsCore | null {
if (typeof window !== 'undefined' && (window as any).__G7_DEVTOOLS__) {
return (window as any).__G7_DEVTOOLS__ as G7DevToolsCore;
}
return null;
}
/**
* Axios 설정에 DevTools 요청 ID를 저장하기 위한 확장 인터페이스
*/
interface AxiosConfigWithDevTools extends InternalAxiosRequestConfig {
_devToolsRequestId?: string | null;
_retry?: boolean;
}
/**
* API 에러 정보
*/
export interface ApiErrorInfo {
/** HTTP 상태 코드 */
status: number;
/** 에러 메시지 */
message: string;
/** API 응답 데이터 */
data?: any;
/** HTTP 상태 텍스트 */
statusText?: string;
}
/**
* API 에러 핸들러 타입
*/
export type ApiErrorHandler = (error: ApiErrorInfo) => void;
/**
* API 클라이언트 설정 인터페이스
*/
interface ApiClientConfig {
baseURL?: string;
timeout?: number;
/** @deprecated onUnauthorized 대신 onError를 사용하세요 */
onTokenExpired?: () => void;
/** 401 토큰 갱신 실패 시 호출 (로그인 페이지 리다이렉트용) */
onUnauthorized?: () => void;
/** 글로벌 에러 핸들러 (모든 API 에러에 대해 호출) */
onError?: ApiErrorHandler;
}
/**
* API 클라이언트 클래스
* 인증이 필요한 API 요청에 자동으로 Authorization 헤더를 추가합니다.
*/
class ApiClient {
private client: AxiosInstance;
private config: ApiClientConfig;
private readonly TOKEN_KEY = 'auth_token';
constructor(config: ApiClientConfig = {}) {
this.config = {
baseURL: config.baseURL || '/api',
timeout: config.timeout || 30000,
onTokenExpired: config.onTokenExpired, // eslint-disable-line deprecation/deprecation
onUnauthorized: config.onUnauthorized,
onError: config.onError,
};
this.client = axios.create({
baseURL: this.config.baseURL,
timeout: this.config.timeout,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
// 배열 파라미터를 key[]=a&key[]=b 형식으로 직렬화 (Laravel 호환)
paramsSerializer: {
serialize: (params) => {
const parts: string[] = [];
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) continue;
if (Array.isArray(value)) {
// 배열: key[]=a&key[]=b 형식
// 키에 이미 []가 있으면 그대로 사용, 없으면 []를 추가
const arrayKey = key.endsWith('[]') ? key : `${key}[]`;
for (const item of value) {
parts.push(`${encodeURIComponent(arrayKey)}=${encodeURIComponent(String(item))}`);
}
} else {
// 일반 값
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
}
return parts.join('&');
},
},
});
this.setupInterceptors();
}
/**
* 토큰 저장
*/
setToken(token: string): void {
if (typeof window !== 'undefined') {
localStorage.setItem(this.TOKEN_KEY, token);
}
}
/**
* 토큰 조회
*/
getToken(): string | null {
if (typeof window !== 'undefined') {
return localStorage.getItem(this.TOKEN_KEY);
}
return null;
}
/**
* 토큰 삭제
*/
removeToken(): void {
if (typeof window !== 'undefined') {
localStorage.removeItem(this.TOKEN_KEY);
}
}
/**
* 인터셉터 설정
*/
private setupInterceptors(): void {
// 요청 인터셉터
this.client.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// URL이 이미 /api로 시작하면 baseURL 제거 (중복 방지)
if (config.url?.startsWith('/api') && config.baseURL === '/api') {
config.baseURL = '';
}
const token = this.getToken();
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
// g7_locale이 설정되어 있으면 Accept-Language 헤더로 전송
if (typeof window !== 'undefined' && config.headers) {
const locale = localStorage.getItem('g7_locale');
if (locale) {
config.headers['Accept-Language'] = locale;
}
}
// DevTools 요청 추적 시작
const devTools = getDevTools();
if (devTools?.isEnabled()) {
const fullUrl = this.buildFullUrl(config);
const method = (config.method || 'GET').toUpperCase();
const requestId = devTools.trackRequest(
fullUrl,
method,
{ requestBody: config.data }
);
(config as AxiosConfigWithDevTools)._devToolsRequestId = requestId;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 응답 인터셉터
this.client.interceptors.response.use(
(response: AxiosResponse) => {
// DevTools 요청 완료 추적 (성공)
const config = response.config as AxiosConfigWithDevTools;
const requestId = config._devToolsRequestId;
if (requestId) {
const devTools = getDevTools();
if (devTools?.isEnabled()) {
devTools.completeRequest(requestId, response.status, response.data);
}
config._devToolsRequestId = null;
}
return response;
},
async (error) => {
const originalRequest = error.config as AxiosConfigWithDevTools | undefined;
const requestUrl = originalRequest?.url || '';
// onUnauthorized 콜백 실행을 건너뛸 엔드포인트 패턴
// - /auth/: 인증 관련 API (로그인 실패 시 리다이렉트 방지, 토큰 갱신 무한 루프 방지)
// - /layouts/: 레이아웃 서빙 API (공개 접근 가능, 토큰 만료 시 로그인 페이지 접근 허용)
const skipUnauthorizedPatterns = [
'/auth/',
'/layouts/',
];
const shouldSkipUnauthorized = skipUnauthorizedPatterns.some(pattern => requestUrl.includes(pattern));
// 401 Unauthorized 처리
if (error.response?.status === 401 && !originalRequest?._retry && !shouldSkipUnauthorized) {
originalRequest!._retry = true;
// AuthManager를 통한 토큰 갱신 시도
const authManager = AuthManager.getInstance();
const refreshed = await authManager.refreshToken();
if (refreshed) {
// 토큰 갱신 성공, 원래 요청 재시도 (DevTools 추적은 재시도된 요청에서 처리)
const token = this.getToken();
if (token) {
originalRequest!.headers.Authorization = `Bearer ${token}`;
}
// 재시도 전 requestId 클리어 (새 요청으로 다시 추적됨)
originalRequest!._devToolsRequestId = null;
return this.client(originalRequest!);
}
// 갱신 실패 - DevTools에 에러 기록
this.completeDevToolsRequest(originalRequest, error);
this.removeToken();
if (this.config.onUnauthorized) {
this.config.onUnauthorized();
}
return Promise.reject(error);
}
// 인증 관련 요청이 401인 경우 (로그인 실패, 토큰 만료/삭제 등)
// 각 호출 측에서 에러를 직접 처리하도록 함
if (error.response?.status === 401 && shouldSkipUnauthorized) {
this.completeDevToolsRequest(originalRequest, error);
return Promise.reject(error);
}
// 403 Forbidden 처리 - onUnauthorized를 호출하지 않고 onError로 처리
// 403은 "권한 없음"이므로 로그인 페이지로 리다이렉트하면 안됨
if (error.response?.status === 403) {
this.completeDevToolsRequest(originalRequest, error);
this.callOnError(error);
return Promise.reject(error);
}
// 기타 에러 처리 (404, 422, 500 등)
this.completeDevToolsRequest(originalRequest, error);
if (error.response) {
this.callOnError(error);
}
return Promise.reject(error);
}
);
}
/**
* GET 요청
*/
async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.get<T>(url, config);
return response.data;
}
/**
* POST 요청
*/
async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.post<T>(url, data, config);
return response.data;
}
/**
* PUT 요청
*/
async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.put<T>(url, data, config);
return response.data;
}
/**
* PATCH 요청
*/
async patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.patch<T>(url, data, config);
return response.data;
}
/**
* DELETE 요청
*/
async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.delete<T>(url, config);
return response.data;
}
/**
* Axios 인스턴스 직접 접근 (고급 사용)
*/
getInstance(): AxiosInstance {
return this.client;
}
/**
* onUnauthorized 콜백 설정
*
* 토큰 갱신 실패 시 호출될 콜백을 설정합니다.
* 싱글톤 인스턴스 생성 후에도 콜백을 설정할 수 있습니다.
*
* @param callback 401 토큰 갱신 실패 시 호출될 콜백
*/
setOnUnauthorized(callback: () => void): void {
this.config.onUnauthorized = callback;
}
/**
* 글로벌 에러 핸들러 설정
*
* API 에러 발생 시 호출될 핸들러를 설정합니다.
* ErrorHandlingResolver와 연동하여 계층적 에러 핸들링을 수행합니다.
*
* @param handler 에러 핸들러 함수
*/
setOnError(handler: ApiErrorHandler): void {
this.config.onError = handler;
}
/**
* DevTools 요청 완료 추적 (에러 응답용)
*
* @param config Axios 요청 설정
* @param error Axios 에러 객체
*/
private completeDevToolsRequest(config: AxiosConfigWithDevTools | undefined, error: any): void {
if (!config?._devToolsRequestId) return;
const devTools = getDevTools();
if (!devTools?.isEnabled()) return;
const requestId = config._devToolsRequestId;
config._devToolsRequestId = null;
if (error.response) {
// HTTP 응답이 있는 경우 (4xx, 5xx 등)
devTools.completeRequest(requestId, error.response.status, error.response.data);
} else if (error.request) {
// 요청은 보냈지만 응답이 없는 경우 (네트워크 오류, 타임아웃 등)
devTools.failRequest(requestId, error.message || 'Network error');
} else {
// 요청 설정 중 오류
devTools.failRequest(requestId, error.message || 'Request error');
}
}
/**
* 요청 설정에서 전체 URL을 생성합니다.
*
* @param config Axios 요청 설정
* @returns 전체 URL 문자열
*/
private buildFullUrl(config: InternalAxiosRequestConfig): string {
let url = config.url || '';
// baseURL이 있고, url이 상대 경로인 경우 결합
if (config.baseURL && !url.startsWith('http')) {
url = `${config.baseURL}${url.startsWith('/') ? '' : '/'}${url}`;
}
// 쿼리 파라미터가 있는 경우 추가
if (config.params && typeof config.params === 'object') {
const params = config.params as Record<string, any>;
const parts: string[] = [];
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) continue;
if (Array.isArray(value)) {
const arrayKey = key.endsWith('[]') ? key : `${key}[]`;
for (const item of value) {
parts.push(`${encodeURIComponent(arrayKey)}=${encodeURIComponent(String(item))}`);
}
} else {
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
}
if (parts.length > 0) {
url += (url.includes('?') ? '&' : '?') + parts.join('&');
}
}
return url;
}
/**
* 글로벌 에러 핸들러를 호출합니다.
*
* @param error Axios 에러 객체
*/
private callOnError(error: any): void {
if (!this.config.onError) {
return;
}
const errorInfo: ApiErrorInfo = {
status: error.response?.status || 0,
message: error.response?.data?.message || error.message || 'Unknown error',
data: error.response?.data,
statusText: error.response?.statusText,
};
try {
this.config.onError(errorInfo);
} catch (handlerError) {
logger.error('Error in onError handler:', handlerError);
}
}
}
// 싱글톤 인스턴스
let apiClientInstance: ApiClient | null = null;
/**
* API 클라이언트 인스턴스 생성 또는 가져오기
*/
export function createApiClient(config?: ApiClientConfig): ApiClient {
if (!apiClientInstance) {
apiClientInstance = new ApiClient(config);
}
return apiClientInstance;
}
/**
* 기본 API 클라이언트 인스턴스 가져오기
*/
export function getApiClient(): ApiClient {
if (!apiClientInstance) {
apiClientInstance = new ApiClient();
}
return apiClientInstance;
}
export default ApiClient;
@@ -0,0 +1,168 @@
/**
* ApiClient 테스트
*/
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import ApiClient, { createApiClient, getApiClient } from '../ApiClient';
import axios from 'axios';
// Axios 모킹
vi.mock('axios');
const mockedAxios = axios as any;
describe('ApiClient', () => {
let apiClient: ApiClient;
beforeEach(() => {
// localStorage 모킹
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => {
store[key] = value;
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
},
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock,
writable: true,
});
// Axios 인스턴스 모킹
mockedAxios.create.mockReturnValue({
interceptors: {
request: {
use: vi.fn((onFulfilled) => {
return 0;
}),
},
response: {
use: vi.fn((onFulfilled, onRejected) => {
return 0;
}),
},
},
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
patch: vi.fn(),
delete: vi.fn(),
});
apiClient = new ApiClient();
});
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
describe('토큰 관리', () => {
it('토큰을 저장할 수 있어야 함', () => {
apiClient.setToken('test-token');
expect(localStorage.getItem('auth_token')).toBe('test-token');
});
it('토큰을 조회할 수 있어야 함', () => {
localStorage.setItem('auth_token', 'test-token');
expect(apiClient.getToken()).toBe('test-token');
});
it('토큰을 삭제할 수 있어야 함', () => {
localStorage.setItem('auth_token', 'test-token');
apiClient.removeToken();
expect(localStorage.getItem('auth_token')).toBeNull();
});
it('토큰이 없으면 null을 반환해야 함', () => {
expect(apiClient.getToken()).toBeNull();
});
});
describe('HTTP 메서드', () => {
it('GET 요청을 수행할 수 있어야 함', async () => {
const mockData = { data: 'test' };
const mockResponse = { data: mockData };
const instance = apiClient.getInstance();
instance.get = vi.fn().mockResolvedValue(mockResponse);
const result = await apiClient.get('/test');
expect(result).toEqual(mockData);
expect(instance.get).toHaveBeenCalledWith('/test', undefined);
});
it('POST 요청을 수행할 수 있어야 함', async () => {
const mockData = { data: 'test' };
const mockResponse = { data: mockData };
const postData = { name: 'test' };
const instance = apiClient.getInstance();
instance.post = vi.fn().mockResolvedValue(mockResponse);
const result = await apiClient.post('/test', postData);
expect(result).toEqual(mockData);
expect(instance.post).toHaveBeenCalledWith('/test', postData, undefined);
});
it('PUT 요청을 수행할 수 있어야 함', async () => {
const mockData = { data: 'test' };
const mockResponse = { data: mockData };
const putData = { name: 'test' };
const instance = apiClient.getInstance();
instance.put = vi.fn().mockResolvedValue(mockResponse);
const result = await apiClient.put('/test', putData);
expect(result).toEqual(mockData);
expect(instance.put).toHaveBeenCalledWith('/test', putData, undefined);
});
it('PATCH 요청을 수행할 수 있어야 함', async () => {
const mockData = { data: 'test' };
const mockResponse = { data: mockData };
const patchData = { name: 'test' };
const instance = apiClient.getInstance();
instance.patch = vi.fn().mockResolvedValue(mockResponse);
const result = await apiClient.patch('/test', patchData);
expect(result).toEqual(mockData);
expect(instance.patch).toHaveBeenCalledWith('/test', patchData, undefined);
});
it('DELETE 요청을 수행할 수 있어야 함', async () => {
const mockData = { data: 'test' };
const mockResponse = { data: mockData };
const instance = apiClient.getInstance();
instance.delete = vi.fn().mockResolvedValue(mockResponse);
const result = await apiClient.delete('/test');
expect(result).toEqual(mockData);
expect(instance.delete).toHaveBeenCalledWith('/test', undefined);
});
});
describe('싱글톤 인스턴스', () => {
it('createApiClient는 싱글톤 인스턴스를 반환해야 함', () => {
const client1 = createApiClient();
const client2 = createApiClient();
expect(client1).toBe(client2);
});
it('getApiClient는 싱글톤 인스턴스를 반환해야 함', () => {
const client1 = getApiClient();
const client2 = getApiClient();
expect(client1).toBe(client2);
});
});
});
+521
View File
@@ -0,0 +1,521 @@
import { getApiClient } from '../api/ApiClient';
import { createLogger } from '../utils/Logger';
const logger = createLogger('AuthManager');
/**
* DevTools 추적 헬퍼
*/
function trackAuthEvent(
type: 'login' | 'logout' | 'token-refresh' | 'token-expired' | 'session-restored' | 'permission-denied' | 'api-unauthorized',
success: boolean,
error?: string,
details?: Record<string, any>
): void {
try {
const G7Core = (window as any).G7Core;
G7Core?.devTools?.trackAuthEvent?.(type, success, error, details);
} catch {
// DevTools 추적 실패 무시
}
}
/**
* 인증 타입
*/
export type AuthType = 'admin' | 'user';
/**
* 인증 설정 인터페이스
*/
export interface AuthConfig {
type: AuthType;
loginPath: string;
defaultPath: string;
userEndpoint: string;
loginEndpoint: string;
logoutEndpoint: string;
refreshEndpoint: string;
}
/**
* 인증된 사용자 정보
*/
export interface AuthUser {
uuid: string;
name: string;
email: string;
[key: string]: any;
}
/**
* 인증 상태
*/
export interface AuthState {
isAuthenticated: boolean;
user: AuthUser | null;
type: AuthType | null;
}
/**
* 이벤트 핸들러 타입
*/
type EventHandler = (...args: any[]) => void;
/**
* 기본 인증 설정
*/
const defaultConfigs: Record<AuthType, AuthConfig> = {
admin: {
type: 'admin',
loginPath: '/admin/login',
defaultPath: '/admin',
userEndpoint: '/admin/auth/user',
loginEndpoint: '/auth/admin/login',
logoutEndpoint: '/admin/auth/logout',
refreshEndpoint: '/admin/auth/refresh',
},
user: {
type: 'user',
loginPath: '/login',
defaultPath: '/',
userEndpoint: '/auth/user',
loginEndpoint: '/auth/login',
logoutEndpoint: '/auth/logout',
refreshEndpoint: '/auth/refresh',
},
};
/**
* AuthManager 클래스
*
* 인증 상태 관리 및 토큰 갱신을 담당하는 싱글톤 클래스입니다.
*/
export class AuthManager {
private static instance: AuthManager;
private state: AuthState;
private config: Map<AuthType, AuthConfig>;
private isRefreshing: boolean = false;
private refreshPromise: Promise<boolean> | null = null;
private eventHandlers: Map<string, EventHandler[]> = new Map();
/** 로케일 스토리지 키 (TemplateApp과 동일) */
private static readonly LOCALE_STORAGE_KEY = 'g7_locale';
private constructor() {
this.state = {
isAuthenticated: false,
user: null,
type: null,
};
this.config = new Map();
this.config.set('admin', defaultConfigs.admin);
this.config.set('user', defaultConfigs.user);
}
/**
* 싱글톤 인스턴스 반환
*/
static getInstance(): AuthManager {
if (!AuthManager.instance) {
AuthManager.instance = new AuthManager();
}
return AuthManager.instance;
}
/**
* 이벤트 핸들러 등록
*/
on(event: string, handler: EventHandler): void {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, []);
}
this.eventHandlers.get(event)!.push(handler);
}
/**
* 이벤트 발생
*/
private emit(event: string, ...args: any[]): void {
const handlers = this.eventHandlers.get(event);
if (handlers) {
handlers.forEach(handler => handler(...args));
}
}
/**
* 인증 상태 확인
*/
isAuthenticated(): boolean {
return this.state.isAuthenticated;
}
/**
* 현재 사용자 정보 반환
*/
getUser(): AuthUser | null {
return this.state.user;
}
/**
* 현재 인증 타입 반환
*/
getAuthType(): AuthType | null {
return this.state.type;
}
/**
* 백엔드 API로 인증 상태 확인
*
* @param type - 인증 타입 (admin 또는 user)
* @returns 인증 여부
*/
async checkAuth(type: AuthType): Promise<boolean> {
const apiClient = getApiClient();
const token = apiClient.getToken();
// 토큰이 없으면 미인증
if (!token) {
this.clearState();
return false;
}
const config = this.config.get(type);
if (!config) {
logger.error(`Unknown auth type: ${type}`);
return false;
}
try {
// 사용자 정보 조회 API 호출
const response = await apiClient.get<{ success: boolean; data: AuthUser }>(config.userEndpoint);
if (response.success && response.data) {
this.state = {
isAuthenticated: true,
user: response.data,
type: type,
};
this.emit('authStateChange', this.state);
return true;
}
this.clearState();
return false;
} catch (error: any) {
// 401 에러인 경우 토큰 갱신 시도
if (error.response?.status === 401) {
const refreshed = await this.refreshToken();
if (refreshed) {
// 갱신 성공 후 다시 인증 확인
return this.checkAuth(type);
}
}
this.clearState();
return false;
}
}
/**
* 사용자 정보 프리로드 (병렬 로딩용)
*
* checkAuth와 동일하지만 에러를 throw하지 않고 조용히 실패합니다.
*
* @param type - 인증 타입 (admin 또는 user)
* @returns 인증 여부
*/
async preloadAuth(type: AuthType): Promise<boolean> {
try {
return await this.checkAuth(type);
} catch (error) {
logger.warn(`Preload auth failed for type ${type}:`, error);
return false;
}
}
/**
* 로그인 처리
*
* @param type - 인증 타입
* @param credentials - 로그인 자격 증명
* @param options - 추가 옵션 (headers 등)
* @returns 인증된 사용자 정보
*/
async login(
type: AuthType,
credentials: { email: string; password: string },
options?: { headers?: Record<string, string> }
): Promise<AuthUser> {
const apiClient = getApiClient();
const config = this.config.get(type);
if (!config) {
throw new Error(`Unknown auth type: ${type}`);
}
// 로그인 엔드포인트 결정
const loginEndpoint = type === 'admin'
? defaultConfigs.admin.loginEndpoint
: defaultConfigs.user.loginEndpoint;
try {
// 추가 헤더 설정 (globalHeaders 지원)
const requestConfig = options?.headers ? { headers: options.headers } : undefined;
const response = await apiClient.post<{
success: boolean;
data: {
token: string;
user: AuthUser;
};
}>(loginEndpoint, credentials, requestConfig);
if (response.success && response.data) {
// 토큰 저장
apiClient.setToken(response.data.token);
// 사용자의 language 설정 확인 및 로케일 변경 처리
const userLanguage = response.data.user.language;
const currentLocale = localStorage.getItem(AuthManager.LOCALE_STORAGE_KEY);
const localeChanged = userLanguage && userLanguage !== currentLocale;
if (userLanguage) {
try {
localStorage.setItem(AuthManager.LOCALE_STORAGE_KEY, userLanguage);
} catch (error) {
logger.warn('Failed to save user language to localStorage:', error);
}
}
// 상태 업데이트
this.state = {
isAuthenticated: true,
user: response.data.user,
type: type,
};
this.emit('login', this.state);
this.emit('authStateChange', this.state);
// DevTools 추적
trackAuthEvent('login', true, undefined, {
userId: response.data.user.uuid,
email: response.data.user.email,
type,
});
// 로케일이 변경된 경우 TemplateApp 재초기화
if (localeChanged && (window as any).__templateApp) {
// changeLocale은 비동기이므로 await 하지 않고 실행
// navigate가 먼저 실행되고, changeLocale이 완료되면 UI가 업데이트됨
(window as any).__templateApp.changeLocale(userLanguage);
}
return response.data.user;
}
throw new Error('Login failed');
} catch (error: any) {
this.clearState();
// Axios 에러에서 API 응답 메시지 추출
// error.response.data.message가 실제 서버 응답 메시지
const apiMessage = error.response?.data?.message;
const enhancedError: any = new Error(apiMessage || error.message || 'Login failed');
enhancedError.response = error.response;
enhancedError.status = error.response?.status;
// DevTools 추적
trackAuthEvent('login', false, enhancedError.message, {
type,
status: error.response?.status,
});
throw enhancedError;
}
}
/**
* 로그아웃 처리
*/
async logout(): Promise<void> {
const apiClient = getApiClient();
const config = this.state.type ? this.config.get(this.state.type) : null;
try {
// 백엔드 로그아웃 API 호출
if (config) {
await apiClient.post(config.logoutEndpoint);
}
} catch (error) {
logger.warn('Logout API call failed:', error);
} finally {
// 토큰 삭제
apiClient.removeToken();
// 상태 초기화
const previousState = { ...this.state };
this.clearState();
this.emit('logout', previousState);
this.emit('authStateChange', this.state);
// DevTools 추적
trackAuthEvent('logout', true, undefined, {
previousType: previousState.type,
});
// 로그인 페이지로 리다이렉트 (queryString 포함)
if (config && previousState.type) {
const returnUrl = window.location.pathname + window.location.search;
window.location.href = this.getLoginRedirectUrl(previousState.type, returnUrl);
}
}
}
/**
* 토큰 갱신
*
* @returns 갱신 성공 여부
*/
async refreshToken(): Promise<boolean> {
// 이미 갱신 중이면 기존 Promise 반환
if (this.isRefreshing && this.refreshPromise) {
return this.refreshPromise;
}
this.isRefreshing = true;
this.refreshPromise = this.doRefreshToken();
try {
return await this.refreshPromise;
} finally {
this.isRefreshing = false;
this.refreshPromise = null;
}
}
/**
* 실제 토큰 갱신 수행
*/
private async doRefreshToken(): Promise<boolean> {
const authType = this.state.type;
if (!authType) return false;
const config = this.config.get(authType);
if (!config) return false;
const apiClient = getApiClient();
try {
const response = await apiClient.post<{
success: boolean;
data: {
token: string;
};
}>(config.refreshEndpoint);
if (response.success && response.data?.token) {
apiClient.setToken(response.data.token);
this.emit('tokenRefreshed');
// DevTools 추적
trackAuthEvent('token-refresh', true, undefined, { type: authType });
return true;
}
// DevTools 추적 (실패 - 응답은 있지만 토큰 없음)
trackAuthEvent('token-refresh', false, 'No token in response', { type: authType });
return false;
} catch (error) {
logger.error('Token refresh failed:', error);
// DevTools 추적 (실패 - 예외)
trackAuthEvent('token-refresh', false, error instanceof Error ? error.message : 'Unknown error', {
type: authType,
});
return false;
}
}
/**
* 보호된 라우트 접근 시 로그인 리다이렉트 URL 생성
*
* @param type - 인증 타입
* @param returnUrl - 로그인 후 돌아갈 URL
* @returns 로그인 페이지 URL (redirect 파라미터 포함)
*/
getLoginRedirectUrl(type: AuthType, returnUrl: string): string {
const config = this.config.get(type);
if (!config) {
return '/login';
}
// URL 파라미터로 redirect 경로 추가
const encodedReturnUrl = encodeURIComponent(returnUrl);
return `${config.loginPath}?redirect=${encodedReturnUrl}`;
}
/**
* 로그인 후 리다이렉트 URL 가져오기
*
* URL 파라미터에서 redirect 값을 읽어 반환합니다.
*
* @param type - 인증 타입
* @returns 리다이렉트할 URL
*/
getRedirectUrl(type: AuthType): string {
const config = this.config.get(type);
const defaultPath = config?.defaultPath || '/';
// URL 파라미터에서 redirect 값 읽기
const urlParams = new URLSearchParams(window.location.search);
const redirectUrl = urlParams.get('redirect');
if (redirectUrl) {
// 보안: 같은 도메인 경로만 허용
try {
const decoded = decodeURIComponent(redirectUrl);
if (decoded.startsWith('/')) {
return decoded;
}
} catch {
// 디코딩 실패 시 기본 경로 반환
}
}
return defaultPath;
}
/**
* 인증 설정 조회
*/
getConfig(type: AuthType): AuthConfig | undefined {
return this.config.get(type);
}
/**
* 상태 초기화
*/
private clearState(): void {
this.state = {
isAuthenticated: false,
user: null,
type: null,
};
}
/**
* 테스트용 인스턴스 초기화
*/
static resetInstance(): void {
AuthManager.instance = null as any;
}
}
export default AuthManager;
@@ -0,0 +1,383 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { AuthManager, AuthType, AuthUser } from '../AuthManager';
import * as ApiClientModule from '../../api/ApiClient';
// Mock ApiClient
vi.mock('../../api/ApiClient', () => ({
getApiClient: vi.fn(),
}));
describe('AuthManager', () => {
let authManager: AuthManager;
let mockApiClient: any;
beforeEach(() => {
// AuthManager 인스턴스 초기화
AuthManager.resetInstance();
authManager = AuthManager.getInstance();
// Mock ApiClient 설정
mockApiClient = {
getToken: vi.fn(),
setToken: vi.fn(),
removeToken: vi.fn(),
get: vi.fn(),
post: vi.fn(),
};
(ApiClientModule.getApiClient as any).mockReturnValue(mockApiClient);
});
afterEach(() => {
vi.clearAllMocks();
});
describe('싱글톤 패턴', () => {
it('항상 동일한 인스턴스를 반환해야 합니다', () => {
const instance1 = AuthManager.getInstance();
const instance2 = AuthManager.getInstance();
expect(instance1).toBe(instance2);
});
});
describe('checkAuth', () => {
it('토큰이 없으면 false를 반환해야 합니다', async () => {
mockApiClient.getToken.mockReturnValue(null);
const result = await authManager.checkAuth('admin');
expect(result).toBe(false);
expect(authManager.isAuthenticated()).toBe(false);
});
it('유효한 토큰이면 true를 반환하고 사용자 정보를 저장해야 합니다', async () => {
const mockUser: AuthUser = {
id: 1,
name: 'Test User',
email: 'test@example.com',
};
mockApiClient.getToken.mockReturnValue('valid-token');
mockApiClient.get.mockResolvedValue({
success: true,
data: mockUser,
});
const result = await authManager.checkAuth('admin');
expect(result).toBe(true);
expect(authManager.isAuthenticated()).toBe(true);
expect(authManager.getUser()).toEqual(mockUser);
expect(authManager.getAuthType()).toBe('admin');
});
it('관리자 인증과 일반 사용자 인증을 구분해야 합니다', async () => {
mockApiClient.getToken.mockReturnValue('valid-token');
mockApiClient.get.mockResolvedValue({
success: true,
data: { id: 1, name: 'User', email: 'user@example.com' },
});
// 관리자 인증
await authManager.checkAuth('admin');
expect(mockApiClient.get).toHaveBeenCalledWith('/admin/auth/user');
// 인스턴스 리셋
AuthManager.resetInstance();
authManager = AuthManager.getInstance();
// 일반 사용자 인증 (defaultConfigs.user.userEndpoint = '/auth/user')
await authManager.checkAuth('user');
expect(mockApiClient.get).toHaveBeenCalledWith('/auth/user');
});
it('API 호출 실패 시 false를 반환해야 합니다', async () => {
mockApiClient.getToken.mockReturnValue('valid-token');
mockApiClient.get.mockRejectedValue(new Error('Network error'));
const result = await authManager.checkAuth('admin');
expect(result).toBe(false);
expect(authManager.isAuthenticated()).toBe(false);
});
});
describe('refreshToken', () => {
beforeEach(async () => {
// 먼저 인증 상태 설정
mockApiClient.getToken.mockReturnValue('valid-token');
mockApiClient.get.mockResolvedValue({
success: true,
data: { id: 1, name: 'User', email: 'user@example.com' },
});
await authManager.checkAuth('admin');
});
it('토큰 갱신이 성공하면 true를 반환해야 합니다', async () => {
mockApiClient.post.mockResolvedValue({
success: true,
data: { token: 'new-token' },
});
const result = await authManager.refreshToken();
expect(result).toBe(true);
expect(mockApiClient.setToken).toHaveBeenCalledWith('new-token');
});
it('토큰 갱신이 실패하면 false를 반환해야 합니다', async () => {
mockApiClient.post.mockRejectedValue(new Error('Refresh failed'));
const result = await authManager.refreshToken();
expect(result).toBe(false);
});
it('동시 갱신 요청은 하나의 요청으로 처리해야 합니다', async () => {
mockApiClient.post.mockImplementation(() =>
new Promise(resolve =>
setTimeout(() => resolve({
success: true,
data: { token: 'new-token' },
}), 100)
)
);
// 동시에 여러 갱신 요청
const promises = [
authManager.refreshToken(),
authManager.refreshToken(),
authManager.refreshToken(),
];
await Promise.all(promises);
// API는 한 번만 호출되어야 함
expect(mockApiClient.post).toHaveBeenCalledTimes(1);
});
it('인증 타입이 없으면 false를 반환해야 합니다', async () => {
// 인스턴스 리셋하여 인증 타입 없음
AuthManager.resetInstance();
authManager = AuthManager.getInstance();
const result = await authManager.refreshToken();
expect(result).toBe(false);
});
});
describe('getLoginRedirectUrl', () => {
it('관리자 로그인 URL에 redirect 파라미터를 포함해야 합니다', () => {
const url = authManager.getLoginRedirectUrl('admin', '/admin/dashboard');
expect(url).toBe('/admin/login?redirect=%2Fadmin%2Fdashboard');
});
it('일반 사용자 로그인 URL에 redirect 파라미터를 포함해야 합니다', () => {
const url = authManager.getLoginRedirectUrl('user', '/profile');
expect(url).toBe('/login?redirect=%2Fprofile');
});
});
describe('getRedirectUrl', () => {
it('URL 파라미터에서 redirect 값을 읽어야 합니다', () => {
// URL 파라미터 설정
Object.defineProperty(window, 'location', {
value: {
search: '?redirect=%2Fadmin%2Fdashboard',
},
writable: true,
});
const url = authManager.getRedirectUrl('admin');
expect(url).toBe('/admin/dashboard');
});
it('redirect 파라미터가 없으면 기본 경로를 반환해야 합니다', () => {
Object.defineProperty(window, 'location', {
value: {
search: '',
},
writable: true,
});
const adminUrl = authManager.getRedirectUrl('admin');
const userUrl = authManager.getRedirectUrl('user');
expect(adminUrl).toBe('/admin');
expect(userUrl).toBe('/');
});
it('외부 URL은 무시하고 기본 경로를 반환해야 합니다', () => {
Object.defineProperty(window, 'location', {
value: {
search: '?redirect=https%3A%2F%2Fevil.com',
},
writable: true,
});
const url = authManager.getRedirectUrl('admin');
expect(url).toBe('/admin');
});
});
describe('logout', () => {
beforeEach(async () => {
// 먼저 인증 상태 설정
mockApiClient.getToken.mockReturnValue('valid-token');
mockApiClient.get.mockResolvedValue({
success: true,
data: { id: 1, name: 'User', email: 'user@example.com' },
});
await authManager.checkAuth('admin');
});
it('로그아웃 시 토큰과 사용자 정보를 삭제해야 합니다', async () => {
// window.location.href mock
const locationMock = { href: '' };
Object.defineProperty(window, 'location', {
value: locationMock,
writable: true,
});
mockApiClient.post.mockResolvedValue({ success: true });
await authManager.logout();
expect(mockApiClient.removeToken).toHaveBeenCalled();
expect(authManager.isAuthenticated()).toBe(false);
expect(authManager.getUser()).toBeNull();
});
it('로그아웃 이벤트를 발생시켜야 합니다', async () => {
const locationMock = { href: '' };
Object.defineProperty(window, 'location', {
value: locationMock,
writable: true,
});
mockApiClient.post.mockResolvedValue({ success: true });
const logoutHandler = vi.fn();
authManager.on('logout', logoutHandler);
await authManager.logout();
expect(logoutHandler).toHaveBeenCalled();
});
it('로그아웃 후 로그인 페이지로 리다이렉트해야 합니다', async () => {
const locationMock = { href: '' };
Object.defineProperty(window, 'location', {
value: locationMock,
writable: true,
});
mockApiClient.post.mockResolvedValue({ success: true });
await authManager.logout();
expect(locationMock.href).toBe('/admin/login');
});
});
describe('login', () => {
it('로그인 성공 시 토큰을 저장하고 사용자 정보를 반환해야 합니다', async () => {
const mockUser: AuthUser = {
id: 1,
name: 'Test User',
email: 'test@example.com',
};
mockApiClient.post.mockResolvedValue({
success: true,
data: {
token: 'new-token',
user: mockUser,
},
});
const result = await authManager.login('admin', {
email: 'test@example.com',
password: 'password',
});
expect(result).toEqual(mockUser);
expect(mockApiClient.setToken).toHaveBeenCalledWith('new-token');
expect(authManager.isAuthenticated()).toBe(true);
expect(authManager.getUser()).toEqual(mockUser);
});
it('로그인 실패 시 에러를 throw해야 합니다', async () => {
mockApiClient.post.mockRejectedValue(new Error('Invalid credentials'));
await expect(
authManager.login('admin', {
email: 'test@example.com',
password: 'wrong',
})
).rejects.toThrow('Invalid credentials');
expect(authManager.isAuthenticated()).toBe(false);
});
it('options.headers가 있으면 ApiClient.post에 전달해야 합니다', async () => {
const mockUser: AuthUser = {
id: 1,
name: 'Test User',
email: 'test@example.com',
};
mockApiClient.post.mockResolvedValue({
success: true,
data: {
token: 'new-token',
user: mockUser,
},
});
await authManager.login(
'user',
{ email: 'test@example.com', password: 'password' },
{ headers: { 'X-Cart-Key': 'ck_abc123' } }
);
expect(mockApiClient.post).toHaveBeenCalledWith(
'/auth/login',
{ email: 'test@example.com', password: 'password' },
{ headers: { 'X-Cart-Key': 'ck_abc123' } }
);
});
it('options가 없으면 ApiClient.post에 config를 전달하지 않아야 합니다', async () => {
const mockUser: AuthUser = {
id: 1,
name: 'Test User',
email: 'test@example.com',
};
mockApiClient.post.mockResolvedValue({
success: true,
data: {
token: 'new-token',
user: mockUser,
},
});
await authManager.login('user', {
email: 'test@example.com',
password: 'password',
});
expect(mockApiClient.post).toHaveBeenCalledWith(
'/auth/login',
{ email: 'test@example.com', password: 'password' },
undefined
);
});
});
});
+7
View File
@@ -0,0 +1,7 @@
export {
AuthManager,
type AuthType,
type AuthConfig,
type AuthUser,
type AuthState,
} from './AuthManager';
@@ -0,0 +1,898 @@
/**
* G7 DevTools 진단 엔진
*
* 증상 기반으로 템플릿 엔진 문제를 자동 진단하는 규칙 엔진
*
* @module DiagnosticEngine
*/
import type {
DiagnosticRule,
DiagnosticCategory,
DiagnosticContext,
DiagnosisResult,
FixSuggestion,
CommonIssue,
StateSnapshot,
ActionLog,
CacheStats,
StateView,
LifecycleInfo,
PerformanceInfo,
NetworkInfo,
ConditionalInfo,
FormInfo,
WebSocketInfo,
} from './types';
import { G7DevToolsCore } from './G7DevToolsCore';
/**
* 진단 규칙 정의
*
* 트러블슈팅 가이드의 주요 이슈를 규칙으로 정의
*/
const diagnosticRules: DiagnosticRule[] = [
// ============================================
// 상태 관련 문제
// ============================================
{
id: 'stale-closure',
name: 'Stale Closure',
category: 'state',
symptoms: [
'이전 값이 전송됨',
'저장 시 오래된 데이터',
'API 호출 시 첫 값만 전송',
'클릭할 때마다 같은 값',
],
detector: (ctx) => {
// 액션 이력에서 동일한 값이 반복되는 패턴 감지
const recentActions = ctx.actionHistory.slice(-10);
const apiCalls = recentActions.filter(a => a.type === 'apiCall');
if (apiCalls.length < 2) return false;
// 연속된 API 호출에서 동일한 파라미터가 사용되는지 확인
for (let i = 1; i < apiCalls.length; i++) {
const prevParams = JSON.stringify(apiCalls[i - 1].params);
const currParams = JSON.stringify(apiCalls[i].params);
if (prevParams === currParams && apiCalls[i].params) {
return true;
}
}
return false;
},
probability: 0.85,
solution: 'G7Core.state.get()._global 사용하여 최신 상태 참조',
docLink: 'troubleshooting-state.md#stale-closure',
codeExample: `
// ❌ 문제: 클로저가 이전 상태 캡처
"body": { "email": "{{_global.email}}" }
// ✅ 해결: 최신 상태 참조
"body": { "email": "{{G7Core.state.get()._global.email}}" }
`,
},
{
id: 'sequence-merge',
name: 'Sequence setState 병합 충돌',
category: 'state',
symptoms: [
'sequence 내 setState 일부 누락',
'여러 setState 중 마지막만 적용',
'상태 업데이트 순서 문제',
],
detector: (ctx) => {
const sequenceActions = ctx.actionHistory.filter(a => a.type === 'sequence');
return sequenceActions.some(seq =>
seq.children?.filter(c => c.type === 'setState').length! > 1
);
},
probability: 0.75,
solution: 'currentState 추적 패턴 사용 또는 단일 setState로 병합',
docLink: 'troubleshooting-state.md#사례3',
codeExample: `
// ❌ 문제: sequence 내 여러 setState
"actions": [
{ "handler": "setState", "params": { "a": 1 } },
{ "handler": "setState", "params": { "b": 2 } }
]
// ✅ 해결: 단일 setState로 병합
"actions": [
{ "handler": "setState", "params": { "a": 1, "b": 2 } }
]
`,
},
{
id: 'init-actions-timing',
name: 'init_actions 타이밍 이슈',
category: 'timing',
symptoms: [
'init_actions 값이 렌더링에 반영 안됨',
'초기 상태가 undefined',
'첫 클릭 시 초기값 손실',
],
detector: (ctx) => {
// 첫 번째 스냅샷이 init_actions이고 이후 상태가 비어있는지 확인
if (ctx.stateHistory.length === 0) return false;
const firstSnapshot = ctx.stateHistory[0];
return firstSnapshot?.source === 'init_actions' &&
Object.keys(firstSnapshot.next || {}).length === 0;
},
probability: 0.70,
solution: 'init_actions 후 _global 상태 병합 확인',
docLink: 'troubleshooting-state.md#init_actions-관련-이슈',
},
{
id: 'datakey-global-init',
name: 'dataKey="_global.xxx" 초기화 누락',
category: 'form',
symptoms: [
'Form dataKey가 전역 상태에 바인딩 안됨',
'Input 값이 _global에 저장 안됨',
'Form 제출 시 빈 값 전송',
],
detector: (ctx) => {
// Form이 _global.으로 시작하는 dataKey를 가지고 있고
// init_actions에서 초기화되지 않은 경우
const formsWithGlobalKey = ctx.form.filter(f =>
f.dataKey?.startsWith('_global.')
);
if (formsWithGlobalKey.length === 0) return false;
// init_actions 스냅샷이 없으면 문제
return !ctx.stateHistory.some(s => s.source === 'init_actions');
},
probability: 0.95,
solution: 'init_actions에서 _global 상태 초기화 필수',
docLink: 'troubleshooting-state.md#datakey-자동-바인딩-이슈',
codeExample: `
// init_actions에서 초기화 필요
"init_actions": [
{
"handler": "setState",
"params": {
"target": "global",
"loginForm": { "email": "", "password": "" }
}
}
]
`,
},
// ============================================
// 캐시 관련 문제
// ============================================
{
id: 'cache-iteration',
name: '캐시 반복 렌더링 문제',
category: 'cache',
symptoms: [
'모든 행이 같은 값',
'iteration에서 첫 항목만 표시',
'DataGrid 데이터 중복',
],
detector: (ctx) => {
// 캐시 히트율이 매우 높고 iteration이 있는 경우
const hitRate = ctx.cacheStats.hitRate ?? 0;
return hitRate > 0.9 && ctx.conditional.iterations.length > 0;
},
probability: 0.90,
solution: 'skipCache: true 추가',
docLink: 'troubleshooting-cache.md#사례4',
codeExample: `
// ❌ 문제: 캐시된 값이 모든 행에 적용
"cellChildren": [{ "props": { "value": "{{item.name}}" } }]
// ✅ 해결: 렌더러에서 skipCache 옵션 사용
// 또는 ActionDispatcher에서 skipCache: true로 호출
`,
},
{
id: 'cache-dynamic-query',
name: '동적 쿼리 파라미터 캐싱',
category: 'cache',
symptoms: [
'페이지네이션이 동작 안함',
'필터 변경해도 같은 결과',
'정렬이 적용 안됨',
],
detector: (ctx) => {
// 네트워크 요청이 반복되지만 같은 결과를 받는 경우
const requests = ctx.network.requestHistory.slice(-5);
if (requests.length < 2) return false;
// 같은 URL에 대한 요청이 있는지 확인
const urls = requests.map(r => r.url.split('?')[0]);
return new Set(urls).size < urls.length;
},
probability: 0.85,
solution: '데이터소스 params에 skipCache: true 추가',
docLink: 'troubleshooting-cache.md#사례2',
},
// ============================================
// 라이프사이클 문제
// ============================================
{
id: 'orphaned-listener',
name: '정리되지 않은 이벤트 리스너',
category: 'lifecycle',
symptoms: [
'메모리 사용량 증가',
'이벤트가 여러 번 실행됨',
'페이지 이동 후에도 이벤트 발생',
],
detector: (ctx) => {
return ctx.lifecycle.orphanedListeners.length > 0;
},
probability: 0.80,
solution: 'useEffect cleanup 또는 removeEventListener 추가',
docLink: 'troubleshooting-components.md#lifecycle',
},
{
id: 'unmount-state-update',
name: '언마운트 후 상태 업데이트',
category: 'lifecycle',
symptoms: [
'Cannot update state on unmounted component',
'비동기 작업 완료 후 에러',
'모달 닫힘 후 에러',
],
detector: (ctx) => {
return ctx.actionHistory.some(a =>
a.status === 'error' &&
a.error?.message?.includes('unmounted')
);
},
probability: 0.90,
solution: 'AbortController 또는 isMounted 플래그 사용',
docLink: 'troubleshooting-state.md#unmount-update',
},
// ============================================
// 성능 문제
// ============================================
{
id: 'excessive-rerenders',
name: '과도한 리렌더링',
category: 'performance',
symptoms: [
'UI가 느림',
'스크롤 버벅임',
'입력 지연',
],
detector: (ctx) => {
// 렌더링 횟수가 50회 이상인 컴포넌트가 있는지
for (const count of ctx.performance.renderCounts.values()) {
if (count > 50) return true;
}
return false;
},
probability: 0.75,
solution: 'React.memo, useMemo, useCallback 사용',
docLink: 'troubleshooting-components.md#performance',
},
{
id: 'binding-eval-flood',
name: '바인딩 평가 과다',
category: 'performance',
symptoms: [
'페이지 로드 느림',
'CPU 사용량 높음',
],
detector: (ctx) => {
return ctx.performance.bindingEvalCount > 1000;
},
probability: 0.85,
solution: '불필요한 {{}} 바인딩 제거, 정적 값 사용',
docLink: 'troubleshooting-cache.md#binding-performance',
},
{
id: 'memory-leak',
name: '잠재적 메모리 누수',
category: 'performance',
symptoms: [
'시간이 지남에 따라 느려짐',
'브라우저 탭 메모리 증가',
'오래 사용 시 크래시',
],
detector: (ctx) => {
return ctx.performance.memoryWarnings.length > 0;
},
probability: 0.70,
solution: '클린업 함수 확인, WeakMap 사용',
docLink: 'troubleshooting-state.md#memory-leak',
},
// ============================================
// 네트워크 문제
// ============================================
{
id: 'request-timeout',
name: 'API 요청 타임아웃',
category: 'network',
symptoms: [
'데이터가 로딩 안됨',
'무한 로딩 스피너',
'타임아웃 에러',
],
detector: (ctx) => {
return ctx.network.requestHistory.some(r =>
r.status === 'timeout' || (r.duration && r.duration > 30000)
);
},
probability: 0.90,
solution: '서버 상태 확인, 타임아웃 설정 조정',
docLink: 'troubleshooting-backend.md#timeout',
},
{
id: 'duplicate-requests',
name: '중복 API 요청',
category: 'network',
symptoms: [
'같은 요청이 여러 번 실행',
'네트워크 탭에 동일 요청 반복',
'불필요한 서버 부하',
],
detector: (ctx) => {
const history = ctx.network.requestHistory;
const recent = history.slice(-20);
const urls = recent.map(r => `${r.method}:${r.url}`);
return urls.length !== new Set(urls).size;
},
probability: 0.85,
solution: 'debounce 추가, 데이터소스 의존성 확인',
docLink: 'troubleshooting-cache.md#duplicate-request',
},
{
id: 'datasource-not-loading',
name: '데이터소스 미로딩',
category: 'network',
symptoms: [
'데이터가 undefined',
'빈 테이블/목록',
'API 호출이 안됨',
],
detector: (ctx) => {
return ctx.network.pendingDataSources.length > 0 &&
ctx.network.activeRequests.length === 0;
},
probability: 0.80,
solution: '데이터소스 strategy 확인, 의존성 확인',
docLink: 'troubleshooting-backend.md#datasource',
},
// ============================================
// 권한/인증 문제
// ============================================
{
id: 'permission-denied',
name: '레이아웃 권한 거부 (403)',
category: 'network',
symptoms: [
'403 Forbidden',
'권한이 없습니다',
'레이아웃 로드 실패',
'페이지 접근 불가',
'빈 화면',
],
detector: (ctx) => {
return ctx.network.requestHistory.some(r => r.statusCode === 403);
},
probability: 0.90,
solution: '사용자 권한 확인 또는 레이아웃 permissions 설정 확인',
docLink: 'frontend/layout-json.md#permissions',
codeExample: `
// 레이아웃 JSON의 permissions 필드 확인
{
"permissions": ["core.products.read"] // 필요 권한
}
// 권한 없이 공개로 설정하려면:
{
"permissions": [] // 빈 배열 = 공개 레이아웃
}
`,
},
{
id: 'auth-required',
name: '인증 필요 (401)',
category: 'network',
symptoms: [
'401 Unauthorized',
'로그인 필요',
'토큰 만료',
'인증되지 않음',
'Unauthenticated',
],
detector: (ctx) => {
return ctx.network.requestHistory.some(r => r.statusCode === 401);
},
probability: 0.95,
solution: '로그인 상태 확인 또는 토큰 갱신 필요',
docLink: 'frontend/auth-system.md',
},
// ============================================
// 무한 스크롤 문제
// ============================================
{
id: 'infinite-scroll-state-reset',
name: '무한 스크롤 상태 미초기화',
category: 'state',
symptoms: [
'삭제 후 스크롤 안됨',
'무한 스크롤이 멈춤',
'hasMore가 false로 유지',
'더 이상 데이터 로드 안됨',
],
detector: (ctx) => {
// infiniteScroll.hasMore가 false이고 refetchDataSource 액션이 있는 경우
const state = ctx.currentState;
const hasRefetch = ctx.actionHistory.some(a => a.type === 'refetchDataSource');
return hasRefetch && state?._global?.infiniteScroll?.hasMore === false;
},
probability: 0.85,
solution: 'refetchDataSource 전에 infiniteScroll 상태 초기화 필요',
docLink: 'frontend/actions-handlers.md#appendDataSource',
codeExample: `
// 삭제 성공 시 상태 초기화 후 refetch
"onSuccess": [
{
"handler": "setState",
"params": {
"target": "global",
"infiniteScroll": {
"currentPage": 1,
"hasMore": true,
"isLoadingMore": false
}
}
},
{ "handler": "refetchDataSource", "params": { "id": "list" } }
]
`,
},
{
id: 'scroll-event-not-configured',
name: '스크롤 이벤트 미설정',
category: 'lifecycle',
symptoms: [
'스크롤해도 데이터 로드 안됨',
'무한 스크롤 작동 안함',
'스크롤 이벤트 안잡힘',
],
detector: (ctx) => {
// scroll 타입 액션이 없고 appendDataSource도 없는 경우
const hasScrollAction = ctx.actionHistory.some(a => a.type === 'scroll');
const hasAppendAction = ctx.actionHistory.some(a => a.type === 'appendDataSource');
// 스크롤 액션과 append 액션 모두 없으면 미설정 가능성
return !hasScrollAction && !hasAppendAction && ctx.actionHistory.length > 5;
},
probability: 0.70,
solution: 'scroll 이벤트 핸들러 설정 및 컨테이너 overflow 속성 확인',
docLink: 'frontend/actions.md#scroll-event',
codeExample: `
// 무한 스크롤 컨테이너 설정 예시
{
"type": "Div",
"props": {
"className": "overflow-y-auto h-full"
},
"actions": {
"scroll": [
{
"handler": "appendDataSource",
"params": {
"id": "list",
"dataPath": "data",
"sourcePath": "{{_global.infiniteScroll.currentPage}}"
}
}
]
}
}
`,
},
{
id: 'append-datasource-wrong-path',
name: 'appendDataSource 경로 오류',
category: 'state',
symptoms: [
'무한 스크롤 시 데이터 덮어씀',
'기존 데이터가 사라짐',
'데이터가 병합 안됨',
],
detector: (ctx) => {
// appendDataSource 액션 후 데이터가 줄어드는 패턴
const appendActions = ctx.actionHistory.filter(a => a.type === 'appendDataSource');
// 연속된 append 후 데이터 수가 줄어들면 문제
return appendActions.length >= 2 && appendActions.some(a => a.status === 'error');
},
probability: 0.75,
solution: 'dataPath와 sourcePath 설정 확인, 데이터소스 dataPath가 병합 대상인지 확인',
docLink: 'frontend/actions-handlers.md#appendDataSource',
},
// ============================================
// WebSocket 문제
// ============================================
{
id: 'websocket-disconnected',
name: 'WebSocket 연결 끊김',
category: 'websocket',
symptoms: [
'실시간 업데이트 안됨',
'알림이 오지 않음',
],
detector: (ctx) => {
return ctx.websocket.connectionState === 'disconnected';
},
probability: 0.90,
solution: '네트워크 상태 확인, 재연결 로직 확인',
docLink: 'troubleshooting-backend.md#websocket',
},
// ============================================
// 조건부 렌더링 문제
// ============================================
{
id: 'if-condition-always-false',
name: 'if 조건 항상 false',
category: 'conditional',
symptoms: [
'컴포넌트가 표시 안됨',
'조건부 영역이 비어있음',
],
detector: (ctx) => {
return ctx.conditional.ifConditions.some(c =>
c.evaluatedValue === false && c.evaluationCount > 5
);
},
probability: 0.85,
solution: 'if 조건식 확인, 상태값 확인',
docLink: 'troubleshooting-state.md#if-condition',
},
{
id: 'iteration-empty',
name: 'iteration 소스 비어있음',
category: 'conditional',
symptoms: [
'반복 영역이 비어있음',
'목록이 표시 안됨',
],
detector: (ctx) => {
return ctx.conditional.iterations.some(i => i.sourceLength === 0);
},
probability: 0.80,
solution: 'iteration source 표현식 확인, 데이터 로딩 확인',
docLink: 'troubleshooting-guide.md#iteration',
},
{
id: 'iteration-item-var',
name: 'iteration 변수명 오류',
category: 'conditional',
symptoms: [
'반복 항목 내 바인딩 빈값',
'올바른 개수는 표시되나 내용 없음',
],
detector: (ctx) => {
// item 또는 index가 변수명으로 사용되면 문제 가능성
return ctx.conditional.iterations.some(i =>
i.itemVar === 'item' || i.indexVar === 'index'
);
},
probability: 0.95,
solution: 'item_var, index_var 사용 (item, index 아님)',
docLink: 'troubleshooting-guide.md#iteration-바인딩-문제',
codeExample: `
// ❌ 잘못된 속성명
"iteration": {
"source": "{{data}}",
"item": "file", // 잘못됨!
"index": "fileIdx" // 잘못됨!
}
// ✅ 올바른 속성명
"iteration": {
"source": "{{data}}",
"item_var": "file",
"index_var": "fileIdx"
}
`,
},
// ============================================
// Form 문제
// ============================================
{
id: 'form-no-datakey',
name: 'Form dataKey 미설정',
category: 'form',
symptoms: [
'Input 값이 저장 안됨',
'Form 제출 시 빈 값',
],
detector: (ctx) => {
return ctx.form.some(f => !f.dataKey);
},
probability: 0.90,
solution: 'Form에 dataKey prop 추가',
docLink: 'troubleshooting-components.md#form-datakey',
},
{
id: 'input-no-name',
name: 'Input name 미설정',
category: 'form',
symptoms: [
'자동 바인딩 안됨',
'Input 값 변경이 상태에 반영 안됨',
],
detector: (ctx) => {
return ctx.form.some(f =>
f.inputs.some(i => !i.name)
);
},
probability: 0.95,
solution: 'Input에 name prop 추가',
docLink: 'troubleshooting-components.md#input-name',
},
// ============================================
// i18n 문제
// ============================================
{
id: 'i18n-key-missing',
name: '번역 키 누락',
category: 'i18n',
symptoms: [
'$t:key가 그대로 표시됨',
'번역되지 않은 텍스트',
],
detector: (_ctx) => {
// DOM에서 $t: 패턴 검색
if (typeof document !== 'undefined') {
return document.body.innerHTML.includes('$t:');
}
return false;
},
probability: 0.95,
solution: '번역 파일에 키 추가',
docLink: 'troubleshooting-components.md#i18n',
},
];
/**
* 진단 엔진 클래스
*
* 증상을 기반으로 템플릿 엔진 문제를 자동 진단
*/
export class DiagnosticEngine {
private devTools: G7DevToolsCore;
constructor() {
this.devTools = G7DevToolsCore.getInstance();
}
/**
* 증상을 분석하여 진단 결과 반환
*
* @param symptoms 사용자가 보고한 증상 목록
* @returns 진단 결과 (신뢰도 순 정렬)
*/
analyze(symptoms: string[]): DiagnosisResult[] {
const context = this.buildContext();
const matches: DiagnosisResult[] = [];
for (const rule of diagnosticRules) {
// 증상 매칭 확인
const symptomMatch = symptoms.some(s =>
rule.symptoms.some(rs =>
rs.toLowerCase().includes(s.toLowerCase()) ||
s.toLowerCase().includes(rs.toLowerCase())
)
);
// 자동 감지 실행
let detectorMatch = false;
try {
detectorMatch = rule.detector(context);
} catch {
// 감지기 실행 실패 시 무시
}
if (symptomMatch || detectorMatch) {
matches.push({
rule,
confidence: this.calculateConfidence(rule, symptoms, symptomMatch, detectorMatch),
evidence: this.collectEvidence(rule, context),
});
}
}
// 신뢰도 순 정렬
return matches.sort((a, b) => b.confidence - a.confidence);
}
/**
* 진단 결과에 대한 해결 제안 반환
*
* @param diagnosis 진단 결과
* @returns 해결 제안
*/
suggestFix(diagnosis: DiagnosisResult): FixSuggestion {
return {
title: diagnosis.rule.name,
description: diagnosis.rule.solution,
codeExample: diagnosis.rule.codeExample,
docLink: diagnosis.rule.docLink,
};
}
/**
* 자주 발생하는 이슈 목록 반환
*
* @returns 빈도순 정렬된 이슈 목록
*/
getCommonIssues(): CommonIssue[] {
// 현재 컨텍스트에서 감지된 이슈 수집
const context = this.buildContext();
const detected: { rule: DiagnosticRule; count: number }[] = [];
for (const rule of diagnosticRules) {
try {
if (rule.detector(context)) {
detected.push({ rule, count: 1 });
}
} catch {
// 무시
}
}
return detected
.sort((a, b) => b.count - a.count)
.map(d => ({
id: d.rule.id,
name: d.rule.name,
description: d.rule.solution,
frequency: d.count,
}));
}
/**
* 특정 카테고리의 규칙만 반환
*
* @param category 진단 카테고리
* @returns 해당 카테고리의 규칙 목록
*/
getRulesByCategory(category: DiagnosticCategory): DiagnosticRule[] {
return diagnosticRules.filter(r => r.category === category);
}
/**
* 모든 진단 규칙 반환
*/
getAllRules(): DiagnosticRule[] {
return [...diagnosticRules];
}
/**
* 진단 컨텍스트 구축
*/
private buildContext(): DiagnosticContext {
return {
stateHistory: this.devTools.getStateHistory(),
actionHistory: this.devTools.getActionHistory(),
cacheStats: this.devTools.getCacheStats(),
currentState: this.devTools.getState(),
lifecycle: this.devTools.getLifecycleInfo(),
performance: this.devTools.getPerformanceInfo(),
network: this.devTools.getNetworkInfo(),
conditional: this.devTools.getConditionalInfo(),
form: this.devTools.getFormInfo(),
websocket: this.devTools.getWebSocketInfo(),
stateAtTime: (timestamp: number) => this.devTools.getStateAtTime(timestamp),
layoutHas: (prop: string, value: string) => this.checkLayoutHas(prop, value),
};
}
/**
* 신뢰도 계산
*/
private calculateConfidence(
rule: DiagnosticRule,
symptoms: string[],
symptomMatch: boolean,
detectorMatch: boolean
): number {
let confidence = rule.probability;
// 증상 매칭 시 신뢰도 증가
if (symptomMatch) {
const matchCount = symptoms.filter(s =>
rule.symptoms.some(rs =>
rs.toLowerCase().includes(s.toLowerCase()) ||
s.toLowerCase().includes(rs.toLowerCase())
)
).length;
confidence += matchCount * 0.05;
}
// 자동 감지 시 신뢰도 증가
if (detectorMatch) {
confidence += 0.1;
}
// 최대 0.99로 제한
return Math.min(confidence, 0.99);
}
/**
* 증거 수집
*/
private collectEvidence(rule: DiagnosticRule, context: DiagnosticContext): string[] {
const evidence: string[] = [];
switch (rule.category) {
case 'state':
if (context.stateHistory.length > 0) {
evidence.push(`상태 변경 이력: ${context.stateHistory.length}개`);
}
break;
case 'cache':
evidence.push(`캐시 히트율: ${((context.cacheStats.hitRate ?? 0) * 100).toFixed(1)}%`);
break;
case 'lifecycle':
if (context.lifecycle.orphanedListeners.length > 0) {
evidence.push(`정리되지 않은 리스너: ${context.lifecycle.orphanedListeners.length}개`);
}
break;
case 'performance':
evidence.push(`바인딩 평가 횟수: ${context.performance.bindingEvalCount}`);
break;
case 'network':
evidence.push(`진행 중인 요청: ${context.network.activeRequests.length}개`);
break;
case 'form':
evidence.push(`추적 중인 Form: ${context.form.length}개`);
break;
}
return evidence;
}
/**
* 레이아웃에서 특정 속성/값 존재 확인
*/
private checkLayoutHas(prop: string, value: string): boolean {
// 현재 레이아웃 JSON에서 특정 패턴 검색
// 실제 구현에서는 레이아웃 데이터 접근 필요
try {
const g7Core = (window as any).G7Core;
const layoutData = g7Core?.getCurrentLayout?.();
if (!layoutData) return false;
const jsonStr = JSON.stringify(layoutData);
return jsonStr.includes(`"${prop}":"${value}`) ||
jsonStr.includes(`"${prop}": "${value}`);
} catch {
return false;
}
}
}
/**
* DiagnosticEngine 싱글톤 인스턴스
*/
let instance: DiagnosticEngine | null = null;
/**
* DiagnosticEngine 싱글톤 인스턴스 반환
*/
export function getDiagnosticEngine(): DiagnosticEngine {
if (!instance) {
instance = new DiagnosticEngine();
}
return instance;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,558 @@
/**
* G7 DevTools 서버 커넥터
*
* 디버깅 데이터를 서버로 전송하고 파일로 저장하는 기능
*
* @module ServerConnector
*/
import type { ServerResponse, SerializablePerformanceInfo } from './types';
import { G7DevToolsCore } from './G7DevToolsCore';
/**
* 서버 커넥터 설정
*/
interface ServerConnectorConfig {
/** 상태 덤프 엔드포인트 */
dumpEndpoint: string;
/** 로그 전송 엔드포인트 */
logEndpoint: string;
/** 연결 타임아웃 (ms) */
timeout: number;
/** 자동 덤프 활성화 */
autoCapture: boolean;
/** 자동 덤프 간격 (ms) */
autoCaptureInterval: number;
}
/**
* 기본 설정
*/
const DEFAULT_CONFIG: ServerConnectorConfig = {
dumpEndpoint: '/_boost/g7-debug/dump-state',
logEndpoint: '/_boost/g7-debug/log',
timeout: 10000,
autoCapture: false,
autoCaptureInterval: 30000,
};
/**
* 서버 커넥터 클래스
*
* 디버깅 데이터를 서버로 전송하여 파일로 저장하거나
* MCP를 통해 Claude가 접근할 수 있게 합니다.
*/
export class ServerConnector {
private config: ServerConnectorConfig;
private devTools: G7DevToolsCore;
private connected: boolean = false;
private autoCaptureTimer: ReturnType<typeof setInterval> | null = null;
constructor(config?: Partial<ServerConnectorConfig>) {
this.config = { ...DEFAULT_CONFIG, ...config };
this.devTools = G7DevToolsCore.getInstance();
// 자동 캡처 설정
if (this.config.autoCapture) {
this.startAutoCapture();
}
}
/** 청크 크기 (2MB - 서버 메모리 제한 고려) */
private readonly CHUNK_SIZE = 2 * 1024 * 1024;
/** 일괄 전송 임계값 (4MB - 이하면 일괄 전송, 초과하면 분할 전송) */
private readonly BULK_THRESHOLD = 4 * 1024 * 1024;
/**
* 현재 상태를 서버로 덤프
*
* 데이터 크기에 따라 전송 방식 자동 선택:
* - 4MB 이하: 일괄 전송 (단일 요청)
* - 4MB 초과: 섹션별 청크 분할 전송
*
* @param saveHistory 이력 파일도 저장할지 여부
* @returns 세션 ID
*/
async dumpState(saveHistory: boolean = false): Promise<string> {
const sessionId = `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
const timestamp = Date.now();
// PerformanceInfo의 Map을 객체로 변환
const perfInfo = this.devTools.getPerformanceInfo();
const serializablePerf: SerializablePerformanceInfo = {
renderCounts: Object.fromEntries(perfInfo.renderCounts),
bindingEvalCount: perfInfo.bindingEvalCount,
memoryWarnings: perfInfo.memoryWarnings,
};
// 섹션별 데이터 정의
const sectionGetters: Record<string, () => any> = {
state: () => this.devTools.getState(),
actions: () => this.devTools.getActionHistory(),
cache: () => this.devTools.getCacheStats(),
lifecycle: () => this.devTools.getLifecycleInfo(),
network: () => this.devTools.getNetworkInfo(),
expressions: () => this.devTools.getExpressions(),
forms: () => this.devTools.getForms(),
performance: () => serializablePerf,
conditionals: () => this.devTools.getConditionalInfo(),
dataSources: () => this.devTools.getDataSources(),
handlers: () => this.devTools.getHandlers(),
componentEvents: () => this.devTools.getComponentEventInfo(),
stateRendering: () => this.devTools.getStateRenderingInfo(),
stateHierarchy: () => this.devTools.getStateHierarchyInfo(),
contextFlow: () => this.devTools.getContextFlowInfo(),
styleValidation: () => this.devTools.getStyleValidationInfo(),
authDebug: () => this.devTools.getAuthDebugInfo(),
logs: () => this.devTools.getLogInfo(),
layout: () => this.devTools.getLayoutDebugInfo(),
changeDetection: () => this.devTools.getChangeDetectionInfo(),
sequenceTracking: () => this.devTools.getSequenceTrackingInfo(),
staleClosureTracking: () => this.devTools.getStaleClosureTrackingInfo(),
cacheDecisionTracking: () => this.devTools.getCacheDecisionTrackingInfo(),
dataPathTransformTracking: () => this.devTools.getDataPathTransformTrackingInfo(),
nestedContextTracking: () => this.devTools.getNestedContextTrackingInfo(),
formBindingValidationTracking: () => this.devTools.getFormBindingValidationTrackingInfo(),
computedDependencyTracking: () => this.devTools.getComputedDependencyTrackingInfo(),
modalStateScopeTracking: () => this.devTools.getModalStateScopeTrackingInfo(),
namedActionTracking: () => this.devTools.getNamedActionTrackingInfo(),
};
// 모든 섹션 데이터 수집 및 직렬화
const serializedSections: Record<string, string> = {};
const errors: string[] = [];
let totalSize = 0;
for (const [sectionName, getData] of Object.entries(sectionGetters)) {
try {
const data = getData();
const serialized = this.safeStringify(data, sectionName);
if (serialized === null) {
errors.push(`${sectionName}: 직렬화 실패`);
serializedSections[sectionName] = JSON.stringify({ _error: `${sectionName} 섹션 직렬화 실패` });
} else {
serializedSections[sectionName] = serialized;
}
totalSize += serializedSections[sectionName].length;
} catch (e) {
const errorMsg = e instanceof Error ? e.message : String(e);
errors.push(`${sectionName}: ${errorMsg}`);
serializedSections[sectionName] = JSON.stringify({ _error: `${sectionName} 섹션 수집 실패: ${errorMsg}` });
totalSize += serializedSections[sectionName].length;
}
}
const totalSections = Object.keys(serializedSections).length;
const successCount = totalSections - errors.length;
try {
// 데이터 크기에 따라 전송 방식 선택
if (totalSize <= this.BULK_THRESHOLD) {
// 일괄 전송 (기존 레거시 방식)
await this.sendBulkDump(serializedSections, timestamp, saveHistory);
console.log(`[G7DevTools] 상태 덤프 완료 - 일괄 전송 (${(totalSize / 1024).toFixed(1)}KB, ${successCount}/${totalSections} 섹션 성공)`);
} else {
// 분할 전송 (대용량 데이터)
await this.sendChunkedDump(sessionId, serializedSections, timestamp, saveHistory);
console.log(`[G7DevTools] 상태 덤프 완료 - 분할 전송 (${(totalSize / 1024 / 1024).toFixed(2)}MB, ${successCount}/${totalSections} 섹션 성공)`);
}
this.connected = true;
if (errors.length > 0) {
console.warn('[G7DevTools] 일부 섹션 실패:', errors.join(', '));
}
return sessionId;
} catch (error) {
this.connected = false;
console.error('[G7DevTools] 상태 덤프 실패:', error);
throw error;
}
}
/**
* 일괄 전송 (소용량 데이터용)
*/
private async sendBulkDump(
serializedSections: Record<string, string>,
timestamp: number,
saveHistory: boolean
): Promise<void> {
// 각 섹션을 JSON 파싱하여 객체로 변환
const sectionsData: Record<string, any> = {};
for (const [name, serialized] of Object.entries(serializedSections)) {
try {
sectionsData[name] = JSON.parse(serialized);
} catch {
sectionsData[name] = { _error: '파싱 실패' };
}
}
await this.sendRequest(this.config.dumpEndpoint, {
bulk: true,
sections: sectionsData,
timestamp,
saveHistory,
});
}
/**
* 분할 전송 (대용량 데이터용)
*/
private async sendChunkedDump(
sessionId: string,
serializedSections: Record<string, string>,
timestamp: number,
saveHistory: boolean
): Promise<void> {
const sectionNames = Object.keys(serializedSections);
const totalSections = sectionNames.length;
for (let i = 0; i < sectionNames.length; i++) {
const sectionName = sectionNames[i];
const serializedData = serializedSections[sectionName];
const isLastSection = i === sectionNames.length - 1;
await this.sendChunkedSection(
sessionId, sectionName, serializedData,
isLastSection, timestamp, saveHistory, totalSections
);
}
}
/**
* 섹션을 청크로 분할하여 전송
*/
private async sendChunkedSection(
sessionId: string,
sectionName: string,
serializedData: string,
isLastSection: boolean,
timestamp: number,
saveHistory: boolean,
totalSections: number
): Promise<void> {
const chunks = this.splitIntoChunks(serializedData);
const totalChunks = chunks.length;
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
const isLastChunk = chunkIndex === chunks.length - 1;
const chunkData = chunks[chunkIndex];
await this.sendRequest(this.config.dumpEndpoint, {
sessionId,
sectionName,
chunkData,
chunkIndex,
totalChunks,
isLastChunk,
isLastSection: isLastSection && isLastChunk,
timestamp,
saveHistory,
totalSections,
});
}
}
/**
* 문자열을 청크로 분할
*/
private splitIntoChunks(data: string): string[] {
const chunks: string[] = [];
for (let i = 0; i < data.length; i += this.CHUNK_SIZE) {
chunks.push(data.slice(i, i + this.CHUNK_SIZE));
}
return chunks.length > 0 ? chunks : [''];
}
/**
* 안전한 JSON 직렬화 (순환 참조 처리)
* @returns 직렬화된 문자열 또는 실패 시 null
*/
private safeStringify(data: any, sectionName: string): string | null {
const seen = new WeakSet();
try {
const result = JSON.stringify(data, (_key, value) => {
// 순환 참조 감지
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular Reference]';
}
seen.add(value);
}
// 함수, Symbol 등 직렬화 불가능한 타입 처리
if (typeof value === 'function') {
return '[Function]';
}
if (typeof value === 'symbol') {
return '[Symbol]';
}
if (typeof value === 'bigint') {
return value.toString();
}
return value;
});
return result;
} catch (e) {
console.warn(`[G7DevTools] ${sectionName} 직렬화 오류:`, e);
return null;
}
}
/**
* 디버그 로그를 서버로 전송
*
* @param data 로그 데이터
*/
async sendLog(data: any): Promise<void> {
// 콘솔에 특별한 형식으로 출력 (BrowserLogger가 캡처할 수 있도록)
console.log('[G7:DEBUG]', JSON.stringify(data));
// 서버로도 전송 시도
try {
await this.sendRequest(this.config.logEndpoint, {
type: 'debug',
data,
timestamp: Date.now(),
});
} catch {
// 로그 전송 실패는 무시
}
}
/**
* 에러 정보를 서버로 전송
*
* @param error 에러 객체
* @param context 추가 컨텍스트
*/
async sendError(error: Error, context?: Record<string, any>): Promise<void> {
const errorData = {
name: error.name,
message: error.message,
stack: error.stack,
context,
state: this.devTools.getState(),
actions: this.devTools.getActionHistory().slice(-10),
timestamp: Date.now(),
};
console.log('[G7:ERROR]', JSON.stringify(errorData));
try {
await this.sendRequest(this.config.logEndpoint, {
type: 'error',
data: errorData,
timestamp: Date.now(),
});
} catch {
// 에러 전송 실패는 무시
}
}
/**
* 성능 프로파일 결과를 서버로 전송
*
* @param profile 프로파일 데이터
*/
async sendProfile(profile: any): Promise<void> {
console.log('[G7:PROFILE]', JSON.stringify(profile));
try {
await this.sendRequest(this.config.logEndpoint, {
type: 'profile',
data: profile,
timestamp: Date.now(),
});
} catch {
// 전송 실패는 무시
}
}
/**
* 연결 상태 확인
*/
isConnected(): boolean {
return this.connected;
}
/**
* 연결 테스트
*/
async testConnection(): Promise<boolean> {
try {
const response = await this.sendRequest(this.config.dumpEndpoint, {
test: true,
timestamp: Date.now(),
});
this.connected = response.status === 'success';
return this.connected;
} catch {
this.connected = false;
return false;
}
}
/**
* 자동 캡처 시작
*/
startAutoCapture(): void {
if (this.autoCaptureTimer) {
this.stopAutoCapture();
}
this.autoCaptureTimer = setInterval(() => {
if (this.devTools.isEnabled()) {
this.dumpState().catch(() => {
// 자동 캡처 실패는 무시
});
}
}, this.config.autoCaptureInterval);
console.log('[G7DevTools] 자동 캡처 시작 (간격:', this.config.autoCaptureInterval, 'ms)');
}
/**
* 자동 캡처 중지
*/
stopAutoCapture(): void {
if (this.autoCaptureTimer) {
clearInterval(this.autoCaptureTimer);
this.autoCaptureTimer = null;
console.log('[G7DevTools] 자동 캡처 중지');
}
}
/**
* 설정 업데이트
*/
updateConfig(config: Partial<ServerConnectorConfig>): void {
this.config = { ...this.config, ...config };
// 자동 캡처 설정이 변경된 경우 재시작
if ('autoCapture' in config || 'autoCaptureInterval' in config) {
this.stopAutoCapture();
if (this.config.autoCapture) {
this.startAutoCapture();
}
}
}
/**
* HTTP 요청 전송
*/
private async sendRequest(endpoint: string, data: any): Promise<ServerResponse> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify(data),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// 응답 텍스트를 먼저 확인
const text = await response.text();
// HTML 응답인지 확인 (PHP 오류 등)
if (text.trim().startsWith('<') || text.includes('<br />') || text.includes('<b>')) {
const errorMessage = this.extractErrorFromHtml(text);
throw new Error(`서버 오류: ${errorMessage}`);
}
// JSON 파싱 시도
try {
return JSON.parse(text);
} catch {
throw new Error(`잘못된 JSON 응답: ${text.substring(0, 100)}...`);
}
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === 'AbortError') {
throw new Error('요청 타임아웃');
}
throw error;
}
}
/**
* HTML 응답에서 에러 메시지 추출
*/
private extractErrorFromHtml(html: string): string {
// PHP 에러 메시지 패턴 추출
// 예: <b>Fatal error</b>: ... in <b>/path/to/file.php</b> on line <b>123</b>
const patterns = [
// Fatal error, Warning, Notice 등
/<b>(Fatal error|Warning|Notice|Parse error)<\/b>:\s*([^<]+)/i,
// Exception 메시지
/Exception:\s*([^<\n]+)/i,
// 일반 에러 메시지
/Error:\s*([^<\n]+)/i,
// TypeError, ArgumentCountError 등
/(TypeError|ArgumentCountError|ValueError)[^:]*:\s*([^<\n]+)/i,
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match) {
// 마지막 캡처 그룹 반환 (에러 메시지 부분)
const message = match[match.length - 1] || match[1];
// HTML 엔티티 디코딩 및 정리
return message
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.trim()
.substring(0, 200);
}
}
// 패턴 매칭 실패 시 HTML 태그 제거 후 첫 줄 반환
const plainText = html
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return plainText.substring(0, 200) || 'Unknown server error';
}
/**
* 리소스 정리
*/
destroy(): void {
this.stopAutoCapture();
}
}
/**
* ServerConnector 싱글톤 인스턴스
*/
let instance: ServerConnector | null = null;
/**
* ServerConnector 싱글톤 인스턴스 반환
*/
export function getServerConnector(): ServerConnector {
if (!instance) {
instance = new ServerConnector();
}
return instance;
}
+473
View File
@@ -0,0 +1,473 @@
/**
* G7 DevTools 스타일 추적기
*
* 렌더링된 컴포넌트의 DOM 요소를 추적하고 computed styles를 수집합니다.
* 시각적 이상(보이지 않는 요소, z-index 충돌 등)을 자동으로 감지합니다.
*
* @module StyleTracker
*/
import { G7DevToolsCore } from './G7DevToolsCore';
import type { StyleIssue, StyleIssueType } from './types';
/**
* 스타일 추적에 필요한 computed styles 속성
*/
const TRACKED_STYLE_PROPERTIES = [
'display',
'visibility',
'opacity',
'position',
'zIndex',
'overflow',
'width',
'height',
'backgroundColor',
'color',
] as const;
/**
* 컴포넌트 스타일 정보
*/
interface ComponentStyleData {
componentId: string;
componentName: string;
classes: string[];
computedStyles: Record<string, string>;
element: WeakRef<HTMLElement>;
timestamp: number;
}
/**
* 스타일 추적기 클래스
*
* MutationObserver와 ResizeObserver를 사용하여
* DOM 변경 시 자동으로 스타일 이상을 감지합니다.
*/
export class StyleTracker {
private static instance: StyleTracker | null = null;
private enabled: boolean = false;
private trackedComponents: Map<string, ComponentStyleData> = new Map();
private mutationObserver: MutationObserver | null = null;
private scanInterval: ReturnType<typeof setInterval> | null = null;
private devTools: G7DevToolsCore;
private constructor() {
this.devTools = G7DevToolsCore.getInstance();
}
/**
* 싱글톤 인스턴스 반환
*/
static getInstance(): StyleTracker {
if (!StyleTracker.instance) {
StyleTracker.instance = new StyleTracker();
}
return StyleTracker.instance;
}
/**
* 스타일 추적 활성화
*/
enable(): void {
if (this.enabled) return;
this.enabled = true;
// DOM 변경 감지
this.setupMutationObserver();
// 주기적 스캔 (5초마다)
this.scanInterval = setInterval(() => {
this.scanVisibleComponents();
}, 5000);
console.log('[StyleTracker] 스타일 추적 활성화됨');
}
/**
* 스타일 추적 비활성화
*/
disable(): void {
if (!this.enabled) return;
this.enabled = false;
if (this.mutationObserver) {
this.mutationObserver.disconnect();
this.mutationObserver = null;
}
if (this.scanInterval) {
clearInterval(this.scanInterval);
this.scanInterval = null;
}
this.trackedComponents.clear();
console.log('[StyleTracker] 스타일 추적 비활성화됨');
}
/**
* 컴포넌트 스타일 추적 시작
*
* DynamicRenderer에서 컴포넌트 마운트 시 호출됩니다.
*/
trackComponent(
componentId: string,
componentName: string,
element: HTMLElement | null
): void {
if (!this.enabled || !this.devTools.isEnabled() || !element) return;
const classes = this.extractClasses(element);
const computedStyles = this.getComputedStyles(element);
// DevTools에 추적
this.devTools.trackComponentStyle(componentId, componentName, classes, computedStyles);
// 내부 맵에 저장 (WeakRef로 메모리 누수 방지)
this.trackedComponents.set(componentId, {
componentId,
componentName,
classes,
computedStyles,
element: new WeakRef(element),
timestamp: Date.now(),
});
// 즉시 이상 감지
this.detectIssues(componentId, componentName, element, classes, computedStyles);
}
/**
* 컴포넌트 추적 해제
*
* 컴포넌트 언마운트 시 호출됩니다.
*/
untrackComponent(componentId: string): void {
this.trackedComponents.delete(componentId);
}
/**
* 모든 보이는 컴포넌트 스캔
*/
scanVisibleComponents(): void {
if (!this.enabled || !this.devTools.isEnabled()) return;
// 1. DevTools에 마운트된 컴포넌트 목록 가져오기
const lifecycleInfo = this.devTools.getLifecycleInfo();
const mountedComponents = lifecycleInfo.mountedComponents || [];
// 2. 마운트된 컴포넌트 ID로 DOM 요소 찾기
mountedComponents.forEach((comp) => {
const componentId = comp.id;
const componentName = comp.name;
// ID로 DOM 요소 찾기 (여러 방식 시도)
let element: HTMLElement | null = null;
// 1) 정확한 ID로 찾기
if (componentId) {
element = document.getElementById(componentId);
}
// 2) data-component-id 속성으로 찾기
if (!element && componentId) {
element = document.querySelector(`[data-component-id="${componentId}"]`) as HTMLElement;
}
// 3) data-editor-id 속성으로 찾기
if (!element && componentId) {
element = document.querySelector(`[data-editor-id="${componentId}"]`) as HTMLElement;
}
if (!element) return;
const classes = this.extractClasses(element);
const computedStyles = this.getComputedStyles(element);
// DevTools에 추적
this.devTools.trackComponentStyle(componentId, componentName, classes, computedStyles);
// 이슈 감지
this.detectIssues(componentId, componentName, element, classes, computedStyles);
// 맵 업데이트
this.trackedComponents.set(componentId, {
componentId,
componentName,
classes,
computedStyles,
element: new WeakRef(element),
timestamp: Date.now(),
});
});
// 3. 기존 셀렉터로도 스캔 (하위 호환성)
const additionalElements = document.querySelectorAll('[data-editor-id], [id^="comp-"]');
additionalElements.forEach((element) => {
if (!(element instanceof HTMLElement)) return;
const componentId = element.getAttribute('data-editor-id') || element.id;
const componentName = element.getAttribute('data-editor-name') || element.tagName;
if (!componentId || this.trackedComponents.has(componentId)) return;
const classes = this.extractClasses(element);
const computedStyles = this.getComputedStyles(element);
this.devTools.trackComponentStyle(componentId, componentName, classes, computedStyles);
this.detectIssues(componentId, componentName, element, classes, computedStyles);
this.trackedComponents.set(componentId, {
componentId,
componentName,
classes,
computedStyles,
element: new WeakRef(element),
timestamp: Date.now(),
});
});
}
/**
* 특정 요소의 시각적 이상 감지
*/
private detectIssues(
componentId: string,
componentName: string,
element: HTMLElement,
classes: string[],
styles: Record<string, string>
): void {
// 1. 보이지 않는 요소 감지
if (styles.display === 'none') {
this.addIssue({
type: 'invisible-element',
componentId,
componentName,
property: 'display',
currentValue: 'none',
severity: 'info',
description: '요소가 display:none으로 숨겨져 있습니다',
suggestion: '의도적인 숨김이 아니라면 조건부 렌더링(if)을 확인하세요',
});
}
if (styles.visibility === 'hidden') {
this.addIssue({
type: 'invisible-element',
componentId,
componentName,
property: 'visibility',
currentValue: 'hidden',
severity: 'info',
description: '요소가 visibility:hidden으로 숨겨져 있습니다',
suggestion: '공간은 유지되지만 보이지 않습니다. 의도적인지 확인하세요',
});
}
if (styles.opacity === '0') {
this.addIssue({
type: 'invisible-element',
componentId,
componentName,
property: 'opacity',
currentValue: '0',
severity: 'warning',
description: '요소가 opacity:0으로 투명합니다',
suggestion: '애니메이션 상태가 아니라면 스타일을 확인하세요',
});
}
// 2. 크기가 0인 요소
if (styles.width === '0px' || styles.height === '0px') {
this.addIssue({
type: 'invisible-element',
componentId,
componentName,
property: styles.width === '0px' ? 'width' : 'height',
currentValue: '0px',
severity: 'warning',
description: '요소의 크기가 0입니다',
suggestion: '컨텐츠가 있는데 크기가 0이라면 레이아웃 문제일 수 있습니다',
});
}
// 3. overflow:hidden으로 잘린 컨텐츠
if (styles.overflow === 'hidden') {
const hasOverflow = element.scrollWidth > element.clientWidth ||
element.scrollHeight > element.clientHeight;
if (hasOverflow) {
this.addIssue({
type: 'overflow-hidden',
componentId,
componentName,
property: 'overflow',
currentValue: 'hidden',
severity: 'warning',
description: '컨텐츠가 overflow:hidden으로 잘리고 있습니다',
suggestion: 'overflow-auto 또는 컨테이너 크기를 확인하세요',
});
}
}
// 4. 다크 모드 클래스 누락 감지
const hasDarkVariant = classes.some(c => c.startsWith('dark:'));
const hasLightOnlyBg = classes.some(c =>
(c.startsWith('bg-white') || c.startsWith('bg-gray-')) && !c.startsWith('dark:')
);
if (hasLightOnlyBg && !hasDarkVariant) {
this.addIssue({
type: 'dark-mode-missing',
componentId,
componentName,
property: 'className',
currentValue: classes.filter(c => c.startsWith('bg-')).join(' '),
severity: 'info',
description: '다크 모드 변형 클래스가 누락되었을 수 있습니다',
suggestion: 'bg-white 사용 시 dark:bg-gray-800 등을 함께 지정하세요',
});
}
// 5. z-index 충돌 가능성
const zIndex = parseInt(styles.zIndex, 10);
if (!isNaN(zIndex) && zIndex > 50 && styles.position !== 'static') {
this.addIssue({
type: 'z-index-conflict',
componentId,
componentName,
property: 'z-index',
currentValue: styles.zIndex,
severity: 'info',
description: `높은 z-index(${zIndex})가 설정되어 있습니다`,
suggestion: 'z-index 충돌을 피하려면 10, 20, 30, 40, 50 단위를 사용하세요',
});
}
// 6. 반응형 클래스 누락 (모바일 전용 또는 데스크톱 전용)
const hasResponsive = classes.some(c =>
c.startsWith('sm:') || c.startsWith('md:') || c.startsWith('lg:') || c.startsWith('xl:')
);
const hasHiddenClass = classes.includes('hidden');
const hasMobileOnly = classes.includes('portable:block') || classes.includes('portable:flex');
const hasDesktopOnly = classes.includes('desktop:block') || classes.includes('desktop:flex');
if (hasHiddenClass && !hasResponsive && !hasMobileOnly && !hasDesktopOnly) {
// hidden 클래스만 있고 반응형 표시가 없으면
this.addIssue({
type: 'responsive-issue',
componentId,
componentName,
property: 'className',
currentValue: 'hidden',
severity: 'info',
description: '반응형 표시 클래스 없이 hidden이 설정되어 있습니다',
suggestion: '조건에 따라 표시하려면 sm:block, desktop:flex 등을 추가하세요',
});
}
}
/**
* 이슈 추가
*/
private addIssue(issue: Omit<StyleIssue, 'id'>): void {
this.devTools.addStyleIssue(issue);
}
/**
* DOM 요소에서 CSS 클래스 추출
*/
private extractClasses(element: HTMLElement): string[] {
const className = element.getAttribute('class') || '';
return className.split(/\s+/).filter(Boolean);
}
/**
* computed styles 가져오기
*/
private getComputedStyles(element: HTMLElement): Record<string, string> {
const computed = window.getComputedStyle(element);
const result: Record<string, string> = {};
for (const prop of TRACKED_STYLE_PROPERTIES) {
result[prop] = computed.getPropertyValue(
prop.replace(/([A-Z])/g, '-$1').toLowerCase()
);
}
return result;
}
/**
* MutationObserver 설정
*/
private setupMutationObserver(): void {
if (typeof MutationObserver === 'undefined') return;
this.mutationObserver = new MutationObserver((mutations) => {
let shouldScan = false;
for (const mutation of mutations) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
shouldScan = true;
break;
}
if (mutation.type === 'attributes' &&
(mutation.attributeName === 'class' || mutation.attributeName === 'style')) {
shouldScan = true;
break;
}
}
if (shouldScan) {
// 디바운스
setTimeout(() => this.scanVisibleComponents(), 100);
}
});
this.mutationObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'style'],
});
}
/**
* 수동 전체 스캔
*/
fullScan(): StyleIssue[] {
this.scanVisibleComponents();
return this.devTools.getStyleValidationInfo().issues;
}
/**
* 이슈 목록 조회
*/
getIssues(): StyleIssue[] {
return this.devTools.getStyleValidationInfo().issues;
}
/**
* 특정 컴포넌트 이슈 조회
*/
getIssuesForComponent(componentId: string): StyleIssue[] {
return this.getIssues().filter(i => i.componentId === componentId);
}
/**
* 데이터 초기화
*/
clear(): void {
this.trackedComponents.clear();
this.devTools.clearStyleValidationData();
}
}
/**
* StyleTracker 싱글톤 인스턴스 반환
*/
export function getStyleTracker(): StyleTracker {
return StyleTracker.getInstance();
}
@@ -0,0 +1,388 @@
/**
* G7 DevTools Tailwind 빌드 검증기
*
* 레이아웃 JSON에서 사용된 Tailwind 클래스와 빌드된 CSS를 비교하여
* 퍼지되었을 수 있는 클래스를 감지합니다.
*
* @module TailwindValidator
*/
/**
* 검증 결과
*/
export interface TailwindValidationResult {
/** 검증 성공 여부 */
valid: boolean;
/** 총 사용된 클래스 수 */
totalClasses: number;
/** 유효한 클래스 수 */
validClasses: number;
/** 퍼지 가능성 있는 클래스 */
potentiallyPurged: PurgedClassInfo[];
/** 동적 클래스 (검증 스킵) */
dynamicClasses: string[];
/** 알 수 없는 클래스 */
unknownClasses: string[];
/** 검증 시간 */
timestamp: number;
}
/**
* 퍼지된 클래스 정보
*/
export interface PurgedClassInfo {
/** 클래스명 */
className: string;
/** 사용된 위치 (파일 또는 컴포넌트) */
usedIn: string[];
/** 퍼지 가능성 이유 */
reason: 'not-in-css' | 'dynamic-value' | 'custom-class';
/** 권장 사항 */
suggestion?: string;
}
/**
* Tailwind 클래스 패턴
*/
const TAILWIND_PATTERNS = {
// 레이아웃
layout: /^(flex|grid|block|inline|hidden|container|box-|float-|clear-|object-|overflow-|overscroll-|z-)/,
// 간격
spacing: /^(p[xytblr]?-|m[xytblr]?-|space-[xy]-|gap-)/,
// 크기
sizing: /^(w-|h-|min-w-|min-h-|max-w-|max-h-|size-)/,
// 타이포그래피
typography: /^(text-|font-|tracking-|leading-|list-|placeholder-|truncate|break-|whitespace-|align-)/,
// 배경
background: /^(bg-|from-|via-|to-|gradient-)/,
// 테두리
border: /^(border|rounded|ring|outline|divide|shadow)/,
// 효과
effects: /^(opacity-|mix-|backdrop-|blur-|brightness-|contrast-|grayscale|hue-|invert|saturate|sepia|drop-)/,
// 필터
filters: /^(filter|blur|brightness|contrast)/,
// 테이블
table: /^(table|border-collapse|border-spacing)/,
// 트랜지션
transition: /^(transition|duration-|ease-|delay-|animate-)/,
// 변환
transform: /^(transform|scale-|rotate-|translate-|skew-|origin-)/,
// 상호작용
interactivity: /^(cursor-|pointer-|resize|select-|scroll-|snap-|touch-|will-)/,
// 접근성
accessibility: /^(sr-only|not-sr-only)/,
// 색상
colors: /^(text-|bg-|border-|ring-|outline-|fill-|stroke-)(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)/,
};
/**
* 변형 접두사
*/
const VARIANTS = [
'hover',
'focus',
'active',
'visited',
'disabled',
'first',
'last',
'odd',
'even',
'group-hover',
'peer-hover',
'dark',
'sm',
'md',
'lg',
'xl',
'2xl',
'portable',
'desktop',
'print',
'motion-safe',
'motion-reduce',
];
/**
* Tailwind 빌드 검증기
*/
export class TailwindValidator {
private static instance: TailwindValidator | null = null;
private loadedCssRules: Set<string> = new Set();
private cssLoaded: boolean = false;
private constructor() {
// 싱글톤
}
/**
* 싱글톤 인스턴스 반환
*/
static getInstance(): TailwindValidator {
if (!TailwindValidator.instance) {
TailwindValidator.instance = new TailwindValidator();
}
return TailwindValidator.instance;
}
/**
* 빌드된 CSS에서 클래스 목록 로드
*/
async loadCssClasses(): Promise<void> {
if (this.cssLoaded) return;
this.loadedCssRules.clear();
// 모든 스타일시트에서 클래스 추출
try {
const styleSheets = document.styleSheets;
for (const sheet of styleSheets) {
try {
// CORS 제한된 스타일시트는 스킵
if (!sheet.cssRules) continue;
for (const rule of sheet.cssRules) {
if (rule instanceof CSSStyleRule) {
// 셀렉터에서 클래스 추출
const classes = this.extractClassesFromSelector(rule.selectorText);
classes.forEach(c => this.loadedCssRules.add(c));
}
}
} catch {
// 접근 불가 스타일시트 스킵
}
}
this.cssLoaded = true;
console.log(`[TailwindValidator] ${this.loadedCssRules.size}개 CSS 클래스 로드됨`);
} catch (error) {
console.error('[TailwindValidator] CSS 로드 실패:', error);
}
}
/**
* CSS 셀렉터에서 클래스명 추출
*/
private extractClassesFromSelector(selector: string): string[] {
const classRegex = /\.([a-zA-Z_-][a-zA-Z0-9_-]*)/g;
const classes: string[] = [];
let match;
while ((match = classRegex.exec(selector)) !== null) {
// 이스케이프된 문자 처리 (예: hover\:bg-blue-500)
const className = match[1].replace(/\\/g, '');
classes.push(className);
}
return classes;
}
/**
* 레이아웃 JSON에서 클래스 추출
*/
extractClassesFromLayout(layout: any): string[] {
const classes = new Set<string>();
const traverse = (node: any) => {
if (!node) return;
// props.className에서 추출
if (node.props?.className) {
const classNames = this.parseClassName(node.props.className);
classNames.forEach(c => classes.add(c));
}
// props.class에서 추출 (일부 컴포넌트)
if (node.props?.class) {
const classNames = this.parseClassName(node.props.class);
classNames.forEach(c => classes.add(c));
}
// children 순회
if (Array.isArray(node.children)) {
node.children.forEach(traverse);
}
// slots 순회
if (node.slots) {
Object.values(node.slots).forEach((slot: any) => {
if (Array.isArray(slot)) {
slot.forEach(traverse);
}
});
}
};
traverse(layout);
return Array.from(classes);
}
/**
* className 문자열에서 개별 클래스 파싱
*/
private parseClassName(className: string): string[] {
if (!className) return [];
// 바인딩 표현식 제거 ({{...}})
const withoutBindings = className.replace(/\{\{[^}]+\}\}/g, '');
// 공백으로 분리
return withoutBindings
.split(/\s+/)
.filter(Boolean)
.filter(c => !c.includes('{{') && !c.includes('}}'));
}
/**
* 클래스가 Tailwind 패턴인지 확인
*/
isTailwindClass(className: string): boolean {
// 변형 접두사 제거
let baseClass = className;
for (const variant of VARIANTS) {
if (className.startsWith(`${variant}:`)) {
baseClass = className.slice(variant.length + 1);
break;
}
}
// 패턴 매칭
for (const pattern of Object.values(TAILWIND_PATTERNS)) {
if (pattern.test(baseClass)) {
return true;
}
}
// 일반적인 Tailwind 유틸리티 패턴
if (/^-?[a-z]+-[a-z0-9/[\]]+$/.test(baseClass)) {
return true;
}
return false;
}
/**
* 동적 값이 포함된 클래스인지 확인
*/
isDynamicClass(className: string): boolean {
// 바인딩 표현식
if (className.includes('{{') || className.includes('}}')) {
return true;
}
// 대괄호 표기법 (arbitrary values)
if (className.includes('[') && className.includes(']')) {
return true;
}
return false;
}
/**
* 클래스 검증
*/
async validateClasses(classes: string[]): Promise<TailwindValidationResult> {
await this.loadCssClasses();
const potentiallyPurged: PurgedClassInfo[] = [];
const dynamicClasses: string[] = [];
const unknownClasses: string[] = [];
let validCount = 0;
for (const className of classes) {
// 동적 클래스는 스킵
if (this.isDynamicClass(className)) {
dynamicClasses.push(className);
continue;
}
// CSS에 존재하는지 확인
if (this.loadedCssRules.has(className)) {
validCount++;
continue;
}
// Tailwind 패턴인지 확인
if (this.isTailwindClass(className)) {
// Tailwind 패턴이지만 CSS에 없음 = 퍼지됨
potentiallyPurged.push({
className,
usedIn: [],
reason: 'not-in-css',
suggestion: `safelist에 추가하거나 정적 클래스로 사용하세요: '${className}'`,
});
} else {
// Tailwind 패턴이 아님 = 커스텀 클래스
unknownClasses.push(className);
}
}
return {
valid: potentiallyPurged.length === 0,
totalClasses: classes.length,
validClasses: validCount,
potentiallyPurged,
dynamicClasses,
unknownClasses,
timestamp: Date.now(),
};
}
/**
* DOM에서 사용 중인 클래스 검증
*/
async validateDom(): Promise<TailwindValidationResult> {
const usedClasses = new Set<string>();
// 모든 요소의 클래스 수집
document.querySelectorAll('[class]').forEach(el => {
const className = el.getAttribute('class') || '';
className.split(/\s+/).filter(Boolean).forEach(c => usedClasses.add(c));
});
return this.validateClasses(Array.from(usedClasses));
}
/**
* 빠른 검증 (주요 클래스만)
*/
quickValidate(classes: string[]): { purged: string[]; valid: string[] } {
const purged: string[] = [];
const valid: string[] = [];
for (const className of classes) {
if (this.isDynamicClass(className)) continue;
if (this.loadedCssRules.has(className)) {
valid.push(className);
} else if (this.isTailwindClass(className)) {
purged.push(className);
}
}
return { purged, valid };
}
/**
* CSS 클래스 캐시 초기화
*/
clearCache(): void {
this.loadedCssRules.clear();
this.cssLoaded = false;
}
/**
* 로드된 CSS 클래스 수 반환
*/
getLoadedClassCount(): number {
return this.loadedCssRules.size;
}
}
/**
* TailwindValidator 싱글톤 인스턴스 반환
*/
export function getTailwindValidator(): TailwindValidator {
return TailwindValidator.getInstance();
}
@@ -0,0 +1,250 @@
/**
* DiagnosticEngine 테스트
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { DiagnosticEngine } from '../DiagnosticEngine';
describe('DiagnosticEngine', () => {
let engine: DiagnosticEngine;
beforeEach(() => {
// G7DevToolsCore 모킹
vi.mock('../G7DevToolsCore', () => ({
G7DevToolsCore: {
getInstance: () => ({
getStateHistory: () => [],
getActionHistory: () => [],
getCacheStats: () => ({ hits: 0, misses: 0, entries: 0, hitRate: 0 }),
getState: () => ({ _global: {}, _local: {}, _computed: {} }),
getLifecycleInfo: () => ({ mountedComponents: [], orphanedListeners: [] }),
getPerformanceInfo: () => ({
renderCounts: new Map(),
bindingEvalCount: 0,
memoryWarnings: [],
}),
getNetworkInfo: () => ({
activeRequests: [],
requestHistory: [],
pendingDataSources: [],
}),
getFormInfo: () => [],
getConditionalInfo: () => ({ ifConditions: [], iterations: [] }),
getWebSocketInfo: () => ({
connectionState: 'disconnected',
connections: [],
messageHistory: [],
}),
}),
},
}));
engine = new DiagnosticEngine();
});
describe('증상 기반 분석', () => {
it('빈 증상 배열에 대해 detector 기반 결과만 반환해야 한다', () => {
const results = engine.analyze([]);
// detector 기반 진단 결과는 증상 없이도 나올 수 있음 (예: websocket disconnected)
// 하지만 symptom 기반 매칭은 없어야 함
results.forEach(result => {
// symptom 매칭 기반 confidence가 아닌 detector 기반만 있어야 함
expect(result.confidence).toBeLessThanOrEqual(1);
});
});
it('Stale Closure 증상을 진단해야 한다', () => {
const results = engine.analyze(['이전 값이 전송됨']);
expect(results.length).toBeGreaterThan(0);
const staleClosureResult = results.find(r => r.rule.id === 'stale-closure');
expect(staleClosureResult).toBeDefined();
});
it('캐시 반복 렌더링 문제를 진단해야 한다', () => {
const results = engine.analyze(['모든 행이 같은 값']);
expect(results.length).toBeGreaterThan(0);
const cacheIterationResult = results.find(r => r.rule.id === 'cache-iteration');
expect(cacheIterationResult).toBeDefined();
});
it('Sequence setState 병합 문제를 진단해야 한다', () => {
const results = engine.analyze(['여러 setState 중 마지막만 적용']);
const sequenceMergeResult = results.find(r => r.rule.id === 'sequence-merge');
expect(sequenceMergeResult).toBeDefined();
});
it('dataKey 초기화 문제를 진단해야 한다', () => {
const results = engine.analyze(['Form dataKey가 전역 상태에 바인딩 안됨']);
const dataKeyResult = results.find(r => r.rule.id === 'datakey-global-init');
expect(dataKeyResult).toBeDefined();
});
it('Form dataKey 문제를 진단해야 한다', () => {
const results = engine.analyze(['Form 값이 저장 안됨']);
expect(results.length).toBeGreaterThan(0);
});
it('iteration 문제를 진단해야 한다', () => {
const results = engine.analyze(['반복 영역이 비어있음']);
const iterationResult = results.find(r => r.rule.id === 'iteration-empty');
expect(iterationResult).toBeDefined();
});
it('여러 증상에 대해 여러 진단을 반환해야 한다', () => {
const results = engine.analyze([
'이전 값이 전송됨',
'모든 행이 같은 값',
'Form 값이 저장 안됨',
]);
expect(results.length).toBeGreaterThan(1);
});
it('신뢰도 순으로 정렬되어야 한다', () => {
const results = engine.analyze(['이전 값이 전송됨', '모든 행이 같은 값']);
for (let i = 1; i < results.length; i++) {
expect(results[i - 1].confidence).toBeGreaterThanOrEqual(results[i].confidence);
}
});
});
describe('수정 제안', () => {
it('진단 결과에 대한 수정 제안을 반환해야 한다', () => {
const results = engine.analyze(['이전 값이 전송됨']);
expect(results.length).toBeGreaterThan(0);
const suggestion = engine.suggestFix(results[0]);
expect(suggestion).toBeDefined();
expect(suggestion.title).toBeDefined();
expect(suggestion.description).toBeDefined();
expect(suggestion.docLink).toBeDefined();
});
it('코드 예제가 있는 경우 포함해야 한다', () => {
const results = engine.analyze(['이전 값이 전송됨']);
const staleClosureResult = results.find(r => r.rule.id === 'stale-closure');
if (staleClosureResult) {
const suggestion = engine.suggestFix(staleClosureResult);
// codeExample이 있을 수 있음
expect(suggestion.title).toBeDefined();
expect(typeof suggestion.codeExample === 'string' || suggestion.codeExample === undefined).toBe(true);
}
});
});
describe('일반적인 이슈 목록', () => {
it('일반적인 이슈 목록을 반환해야 한다', () => {
const issues = engine.getCommonIssues();
expect(Array.isArray(issues)).toBe(true);
// detector 기반이므로 이슈가 없을 수도 있음 (websocket disconnected만 감지됨)
});
it('각 이슈에는 id, name, description, frequency가 있어야 한다', () => {
const issues = engine.getCommonIssues();
issues.forEach(issue => {
expect(issue.id).toBeDefined();
expect(issue.name).toBeDefined();
expect(issue.description).toBeDefined();
expect(typeof issue.frequency).toBe('number');
});
});
});
describe('카테고리별 규칙', () => {
it('상태 카테고리 규칙을 반환해야 한다', () => {
const rules = engine.getRulesByCategory('state');
expect(Array.isArray(rules)).toBe(true);
rules.forEach(rule => {
expect(rule.category).toBe('state');
});
});
it('캐시 카테고리 규칙을 반환해야 한다', () => {
const rules = engine.getRulesByCategory('cache');
expect(Array.isArray(rules)).toBe(true);
rules.forEach(rule => {
expect(rule.category).toBe('cache');
});
});
it('폼 카테고리 규칙을 반환해야 한다', () => {
const rules = engine.getRulesByCategory('form');
expect(Array.isArray(rules)).toBe(true);
rules.forEach(rule => {
expect(rule.category).toBe('form');
});
});
it('라이프사이클 카테고리 규칙을 반환해야 한다', () => {
const rules = engine.getRulesByCategory('lifecycle');
expect(Array.isArray(rules)).toBe(true);
rules.forEach(rule => {
expect(rule.category).toBe('lifecycle');
});
});
it('성능 카테고리 규칙을 반환해야 한다', () => {
const rules = engine.getRulesByCategory('performance');
expect(Array.isArray(rules)).toBe(true);
rules.forEach(rule => {
expect(rule.category).toBe('performance');
});
});
it('네트워크 카테고리 규칙을 반환해야 한다', () => {
const rules = engine.getRulesByCategory('network');
expect(Array.isArray(rules)).toBe(true);
rules.forEach(rule => {
expect(rule.category).toBe('network');
});
});
});
describe('진단 규칙 구조', () => {
it('모든 규칙에는 필수 필드가 있어야 한다', () => {
const allCategories = [
'state',
'cache',
'timing',
'lifecycle',
'performance',
'network',
'form',
'conditional',
'i18n',
] as const;
allCategories.forEach(category => {
const rules = engine.getRulesByCategory(category);
rules.forEach(rule => {
expect(rule.id).toBeDefined();
expect(rule.name).toBeDefined();
expect(rule.symptoms).toBeDefined();
expect(Array.isArray(rule.symptoms)).toBe(true);
expect(rule.probability).toBeDefined();
expect(rule.probability).toBeGreaterThan(0);
expect(rule.probability).toBeLessThanOrEqual(1);
expect(rule.solution).toBeDefined();
expect(rule.docLink).toBeDefined();
expect(rule.category).toBe(category);
});
});
});
});
});
@@ -0,0 +1,664 @@
/**
* G7DevToolsCore 테스트
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { G7DevToolsCore } from '../G7DevToolsCore';
describe('G7DevToolsCore', () => {
let devTools: G7DevToolsCore;
let originalWindow: any;
beforeEach(() => {
// 싱글톤 인스턴스 초기화를 위해 private 프로퍼티에 접근
(G7DevToolsCore as any).instance = undefined;
// 기존 window 저장
originalWindow = global.window;
// window.G7Core 모킹 (addEventListener 포함)
(global as any).window = {
G7Core: {
state: {
get: () => ({
settings: {
advanced: {
debug_mode: true,
},
},
}),
},
},
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
devTools = G7DevToolsCore.getInstance();
devTools.initialize();
});
afterEach(() => {
vi.clearAllMocks();
(G7DevToolsCore as any).instance = undefined;
global.window = originalWindow;
});
describe('싱글톤 패턴', () => {
it('동일한 인스턴스를 반환해야 한다', () => {
const instance1 = G7DevToolsCore.getInstance();
const instance2 = G7DevToolsCore.getInstance();
expect(instance1).toBe(instance2);
});
});
describe('활성화 상태', () => {
it('디버그 모드가 활성화되면 true를 반환해야 한다', () => {
expect(devTools.isEnabled()).toBe(true);
});
it('디버그 모드가 비활성화되면 false를 반환해야 한다', () => {
(global as any).window.G7Core.state.get = () => ({
settings: { advanced: { debug_mode: false } },
});
(G7DevToolsCore as any).instance = undefined;
const newDevTools = G7DevToolsCore.getInstance();
newDevTools.initialize();
expect(newDevTools.isEnabled()).toBe(false);
});
});
describe('상태 관리', () => {
it('초기 상태는 비어 있어야 한다', () => {
const state = devTools.getState();
expect(state).toHaveProperty('_global');
expect(state).toHaveProperty('_local');
expect(state).toHaveProperty('_computed');
});
it('상태 스냅샷을 캡처해야 한다', () => {
devTools.captureStateSnapshot({
source: 'test',
prev: { test: 1 },
next: { test: 2 },
});
const history = devTools.getStateHistory();
expect(history.length).toBe(1);
expect(history[0].source).toBe('test');
});
it('최대 이력 크기를 준수해야 한다', () => {
// setMaxHistory는 최솟값 10을 보장함
devTools.setMaxHistory(15);
for (let i = 0; i < 20; i++) {
devTools.captureStateSnapshot({
source: `test${i}`,
prev: {},
next: {},
});
}
const history = devTools.getStateHistory();
expect(history.length).toBe(15);
});
it('상태 변경을 구독할 수 있어야 한다', () => {
const callback = vi.fn();
const unsubscribe = devTools.watchState('*', callback);
devTools.captureStateSnapshot({
source: 'test',
prev: {},
next: { test: true },
});
expect(callback).toHaveBeenCalled();
unsubscribe();
callback.mockClear();
devTools.captureStateSnapshot({
source: 'test2',
prev: {},
next: {},
});
expect(callback).not.toHaveBeenCalled();
});
});
describe('액션 로깅', () => {
it('액션을 로깅해야 한다', () => {
devTools.logAction({
id: 'test-action-1',
type: 'setState',
params: { key: 'value' },
startTime: Date.now(),
status: 'success',
});
const history = devTools.getActionHistory();
expect(history.length).toBe(1);
expect(history[0].type).toBe('setState');
});
it('액션 실행을 구독할 수 있어야 한다', () => {
const callback = vi.fn();
const unsubscribe = devTools.watchActions(callback);
devTools.logAction({
id: 'test-action-2',
type: 'apiCall',
params: {},
startTime: Date.now(),
status: 'started',
});
expect(callback).toHaveBeenCalled();
unsubscribe();
});
it('액션 메트릭을 계산해야 한다', () => {
devTools.logAction({
id: 'action-1',
type: 'setState',
params: {},
startTime: Date.now(),
status: 'success',
duration: 10,
});
devTools.logAction({
id: 'action-2',
type: 'apiCall',
params: {},
startTime: Date.now(),
status: 'error',
duration: 50,
});
const metrics = devTools.getActionMetrics();
expect(metrics.totalActions).toBe(2);
expect(metrics.successCount).toBe(1);
expect(metrics.errorCount).toBe(1);
});
});
describe('캐시 통계', () => {
it('캐시 히트를 기록해야 한다', () => {
devTools.recordCacheHit();
devTools.recordCacheHit();
const stats = devTools.getCacheStats();
expect(stats.hits).toBe(2);
});
it('캐시 미스를 기록해야 한다', () => {
devTools.recordCacheMiss();
const stats = devTools.getCacheStats();
expect(stats.misses).toBe(1);
});
it('히트율을 계산해야 한다', () => {
devTools.recordCacheHit();
devTools.recordCacheHit();
devTools.recordCacheHit();
devTools.recordCacheMiss();
const stats = devTools.getCacheStats();
// hitRate는 소수점으로 반환 (0.75 = 75%)
expect(stats.hitRate).toBe(0.75);
});
it('캐시 통계를 초기화할 수 있어야 한다', () => {
devTools.recordCacheHit();
devTools.recordCacheMiss();
devTools.resetCacheStats();
const stats = devTools.getCacheStats();
expect(stats.hits).toBe(0);
expect(stats.misses).toBe(0);
});
});
describe('라이프사이클 추적', () => {
it('컴포넌트 마운트를 추적해야 한다', () => {
devTools.trackMount('comp-1', { name: 'TestComponent' });
const info = devTools.getLifecycleInfo();
expect(info.mountedComponents.length).toBe(1);
expect(info.mountedComponents[0].name).toBe('TestComponent');
});
it('컴포넌트 언마운트를 추적해야 한다', () => {
devTools.trackMount('comp-1', { name: 'TestComponent' });
devTools.trackUnmount('comp-1');
const info = devTools.getLifecycleInfo();
expect(info.mountedComponents.length).toBe(0);
});
it('이벤트 리스너를 추적해야 한다', () => {
devTools.trackMount('comp-1', { name: 'TestComponent' });
devTools.trackListener('comp-1', 'click', 'button');
devTools.trackUnmount('comp-1');
const info = devTools.getLifecycleInfo();
expect(info.orphanedListeners.length).toBe(1);
});
});
describe('성능 추적', () => {
it('렌더링 횟수를 추적해야 한다', () => {
devTools.trackRender('TestComponent');
devTools.trackRender('TestComponent');
devTools.trackRender('OtherComponent');
const info = devTools.getPerformanceInfo();
expect(info.renderCounts.get('TestComponent')).toBe(2);
expect(info.renderCounts.get('OtherComponent')).toBe(1);
});
it('바인딩 평가 횟수를 추적해야 한다', () => {
devTools.trackBindingEval();
devTools.trackBindingEval();
devTools.trackBindingEval();
const info = devTools.getPerformanceInfo();
expect(info.bindingEvalCount).toBe(3);
});
it('프로파일링을 시작하고 중지할 수 있어야 한다', () => {
devTools.startProfiling();
devTools.trackRender('TestComponent');
const report = devTools.stopProfiling();
expect(report).toBeDefined();
});
});
describe('네트워크 추적', () => {
it('요청을 추적해야 한다', () => {
// trackRequest(url, method) - requestId를 반환
const requestId = devTools.trackRequest('/api/test', 'GET');
const info = devTools.getNetworkInfo();
expect(info.activeRequests.length).toBe(1);
expect(requestId).toBeTruthy();
});
it('요청 완료를 기록해야 한다', () => {
// trackRequest가 requestId를 반환
const requestId = devTools.trackRequest('/api/test', 'GET');
// completeRequest(requestId, statusCode, response?)
devTools.completeRequest(requestId, 200, { data: 'test' });
const info = devTools.getNetworkInfo();
expect(info.activeRequests.length).toBe(0);
expect(info.requestHistory.length).toBe(1);
});
it('데이터소스를 추적해야 한다', () => {
devTools.trackDataSource('users');
const info = devTools.getNetworkInfo();
expect(info.pendingDataSources.includes('users')).toBe(true);
});
});
describe('설정', () => {
it('로그 레벨을 설정할 수 있어야 한다', () => {
expect(() => devTools.setLogLevel('warn')).not.toThrow();
});
it('최대 이력 크기를 설정할 수 있어야 한다', () => {
devTools.setMaxHistory(50);
// 내부 값 변경 확인을 위해 많은 스냅샷 추가
for (let i = 0; i < 100; i++) {
devTools.captureStateSnapshot({
source: `test${i}`,
prev: {},
next: {},
});
}
expect(devTools.getStateHistory().length).toBe(50);
});
});
describe('로그 추적', () => {
it('로그를 추적해야 한다', () => {
devTools.trackLog('info', 'TestPrefix', ['테스트 메시지', { data: 123 }]);
const logs = devTools.getLogs();
expect(logs.length).toBe(1);
expect(logs[0].level).toBe('info');
expect(logs[0].prefix).toBe('TestPrefix');
// message는 모든 args를 join한 결과
expect(logs[0].message).toBe('테스트 메시지 {"data":123}');
// args는 원본 args (첫 번째 문자열 제외한 나머지)
expect(logs[0].args).toEqual(['테스트 메시지', { data: 123 }]);
});
it('여러 레벨의 로그를 추적해야 한다', () => {
devTools.trackLog('log', 'App', ['일반 로그']);
devTools.trackLog('warn', 'App', ['경고 메시지']);
devTools.trackLog('error', 'App', ['에러 메시지']);
devTools.trackLog('debug', 'App', ['디버그 메시지']);
const logs = devTools.getLogs();
expect(logs.length).toBe(4);
const levels = logs.map(l => l.level);
expect(levels).toContain('log');
expect(levels).toContain('warn');
expect(levels).toContain('error');
expect(levels).toContain('debug');
});
it('로그 필터링이 작동해야 한다 - 레벨', () => {
devTools.trackLog('info', 'App', ['정보']);
devTools.trackLog('error', 'App', ['에러']);
devTools.trackLog('warn', 'App', ['경고']);
const errorLogs = devTools.getLogs({ level: 'error' });
expect(errorLogs.length).toBe(1);
expect(errorLogs[0].level).toBe('error');
});
it('로그 필터링이 작동해야 한다 - prefix', () => {
devTools.trackLog('info', 'DataBindingEngine', ['바인딩 처리']);
devTools.trackLog('info', 'ActionDispatcher', ['액션 실행']);
devTools.trackLog('warn', 'DataBindingEngine', ['바인딩 경고']);
const bindingLogs = devTools.getLogs({ prefix: 'DataBindingEngine' });
expect(bindingLogs.length).toBe(2);
bindingLogs.forEach(log => {
expect(log.prefix).toBe('DataBindingEngine');
});
});
it('로그 필터링이 작동해야 한다 - 검색어', () => {
devTools.trackLog('info', 'App', ['사용자 로그인 성공']);
devTools.trackLog('info', 'App', ['상품 목록 조회']);
devTools.trackLog('error', 'App', ['사용자 인증 실패']);
const userLogs = devTools.getLogs({ search: '사용자' });
expect(userLogs.length).toBe(2);
});
it('로그 통계를 계산해야 한다', () => {
devTools.trackLog('info', 'App', ['정보1']);
devTools.trackLog('info', 'Service', ['정보2']);
devTools.trackLog('error', 'App', ['에러1']);
devTools.trackLog('error', 'App', ['에러2']);
devTools.trackLog('warn', 'Service', ['경고1']);
const stats = devTools.getLogStats();
expect(stats.totalLogs).toBe(5);
expect(stats.byLevel.info).toBe(2);
expect(stats.byLevel.error).toBe(2);
expect(stats.byLevel.warn).toBe(1);
expect(stats.byPrefix['App']).toBe(3);
expect(stats.byPrefix['Service']).toBe(2);
});
it('로그를 초기화할 수 있어야 한다', () => {
devTools.trackLog('info', 'App', ['테스트']);
devTools.trackLog('error', 'App', ['에러']);
expect(devTools.getLogs().length).toBe(2);
devTools.clearLogs();
expect(devTools.getLogs().length).toBe(0);
});
it('최대 로그 이력 크기를 준수해야 한다', () => {
// 내부적으로 maxLogHistory는 500이지만, 테스트를 위해 많은 로그 추가
for (let i = 0; i < 600; i++) {
devTools.trackLog('info', 'App', [`메시지 ${i}`]);
}
const logs = devTools.getLogs();
// 최대 500개 유지
expect(logs.length).toBeLessThanOrEqual(500);
});
it('getLogInfo가 로그와 통계를 함께 반환해야 한다', () => {
devTools.trackLog('info', 'App', ['정보']);
devTools.trackLog('error', 'Service', ['에러']);
const logInfo = devTools.getLogInfo();
expect(logInfo).toHaveProperty('entries');
expect(logInfo).toHaveProperty('stats');
expect(logInfo.entries.length).toBe(2);
expect(logInfo.stats.totalLogs).toBe(2);
});
it('error 로그에 스택 트레이스가 포함되어야 한다', () => {
devTools.trackLog('error', 'App', ['에러 발생']);
const logs = devTools.getLogs();
expect(logs[0].stack).toBeDefined();
expect(typeof logs[0].stack).toBe('string');
});
it('limit 필터가 작동해야 한다', () => {
for (let i = 0; i < 10; i++) {
devTools.trackLog('info', 'App', [`메시지 ${i}`]);
}
const limitedLogs = devTools.getLogs({ limit: 5 });
expect(limitedLogs.length).toBe(5);
});
});
describe('Named Actions 추적', () => {
it('named_actions 정의를 등록해야 한다', () => {
devTools.setNamedActionDefinitions({
searchProducts: { handler: 'navigate', params: { path: '/products' } },
resetFilters: { handler: 'setState', params: { target: 'local', key: 'filters', value: {} } },
});
const info = devTools.getNamedActionTrackingInfo();
expect(info.stats.totalDefinitions).toBe(2);
expect(info.definitions['searchProducts']).toBeDefined();
expect(info.definitions['resetFilters']).toBeDefined();
});
it('actionRef 해석 이력을 기록해야 한다', () => {
devTools.setNamedActionDefinitions({
searchProducts: { handler: 'navigate', params: { path: '/products' } },
});
devTools.trackNamedActionRef({
actionRefName: 'searchProducts',
resolvedHandler: 'navigate',
timestamp: Date.now(),
});
const info = devTools.getNamedActionTrackingInfo();
expect(info.refLogs.length).toBe(1);
expect(info.refLogs[0].actionRefName).toBe('searchProducts');
expect(info.refLogs[0].resolvedHandler).toBe('navigate');
expect(info.refLogs[0].id).toBeDefined();
});
it('참조 횟수 통계를 계산해야 한다', () => {
devTools.setNamedActionDefinitions({
searchProducts: { handler: 'navigate', params: {} },
resetFilters: { handler: 'setState', params: {} },
});
devTools.trackNamedActionRef({
actionRefName: 'searchProducts',
resolvedHandler: 'navigate',
timestamp: Date.now(),
});
devTools.trackNamedActionRef({
actionRefName: 'searchProducts',
resolvedHandler: 'navigate',
timestamp: Date.now(),
});
devTools.trackNamedActionRef({
actionRefName: 'resetFilters',
resolvedHandler: 'setState',
timestamp: Date.now(),
});
const info = devTools.getNamedActionTrackingInfo();
expect(info.stats.totalRefs).toBe(3);
expect(info.stats.refCountByName['searchProducts']).toBe(2);
expect(info.stats.refCountByName['resetFilters']).toBe(1);
});
it('미사용 정의를 감지해야 한다', () => {
devTools.setNamedActionDefinitions({
searchProducts: { handler: 'navigate', params: {} },
unusedAction: { handler: 'setState', params: {} },
});
devTools.trackNamedActionRef({
actionRefName: 'searchProducts',
resolvedHandler: 'navigate',
timestamp: Date.now(),
});
const info = devTools.getNamedActionTrackingInfo();
expect(info.stats.unusedDefinitions).toContain('unusedAction');
expect(info.stats.unusedDefinitions).not.toContain('searchProducts');
});
it('최대 이력 크기를 준수해야 한다', () => {
devTools.setNamedActionDefinitions({
testAction: { handler: 'navigate', params: {} },
});
// 최대 200개 제한 테스트
for (let i = 0; i < 250; i++) {
devTools.trackNamedActionRef({
actionRefName: 'testAction',
resolvedHandler: 'navigate',
timestamp: Date.now(),
});
}
const info = devTools.getNamedActionTrackingInfo();
expect(info.refLogs.length).toBeLessThanOrEqual(200);
});
it('추적 상태를 초기화할 수 있어야 한다', () => {
devTools.setNamedActionDefinitions({
searchProducts: { handler: 'navigate', params: {} },
});
devTools.trackNamedActionRef({
actionRefName: 'searchProducts',
resolvedHandler: 'navigate',
timestamp: Date.now(),
});
devTools.clearNamedActionTracking();
const info = devTools.getNamedActionTrackingInfo();
expect(info.stats.totalDefinitions).toBe(0);
expect(info.refLogs.length).toBe(0);
});
});
describe('모달 정의 누락 감지 (missing-definition)', () => {
it('레이아웃 modals에 없는 모달 열기 시 missing-definition 이슈를 기록해야 한다', () => {
// 레이아웃에 modal_a만 정의
devTools.trackLayoutLoad(
'admin/test_page',
'sirsoft-admin_basic',
{
layout_name: 'test_page',
components: [],
modals: [
{ id: 'modal_a', type: 'composite', name: 'Modal', children: [] },
],
},
'api'
);
// modal_b를 열기 시도 (레이아웃에 없음)
devTools.trackModalOpen({
modalId: 'modal_b',
modalName: 'modal_b',
});
const trackingInfo = devTools.getModalStateScopeTrackingInfo();
const missingIssues = trackingInfo.issues.filter(i => i.type === 'missing-definition');
expect(missingIssues).toHaveLength(1);
expect(missingIssues[0].modalId).toBe('modal_b');
expect(missingIssues[0].severity).toBe('error');
expect(missingIssues[0].description).toContain('modal_b');
expect(missingIssues[0].description).toContain('modals 섹션');
});
it('레이아웃 modals에 정의된 모달 열기 시 missing-definition 이슈가 없어야 한다', () => {
devTools.trackLayoutLoad(
'admin/test_page',
'sirsoft-admin_basic',
{
layout_name: 'test_page',
components: [],
modals: [
{ id: 'modal_confirm', type: 'composite', name: 'Modal', children: [] },
],
},
'api'
);
devTools.trackModalOpen({
modalId: 'modal_confirm',
modalName: 'modal_confirm',
});
const trackingInfo = devTools.getModalStateScopeTrackingInfo();
const missingIssues = trackingInfo.issues.filter(i => i.type === 'missing-definition');
expect(missingIssues).toHaveLength(0);
});
it('레이아웃에 modals 섹션 자체가 없으면 missing-definition 이슈를 기록해야 한다', () => {
devTools.trackLayoutLoad(
'admin/test_page',
'sirsoft-admin_basic',
{
layout_name: 'test_page',
components: [],
},
'api'
);
devTools.trackModalOpen({
modalId: 'modal_x',
modalName: 'modal_x',
});
const trackingInfo = devTools.getModalStateScopeTrackingInfo();
const missingIssues = trackingInfo.issues.filter(i => i.type === 'missing-definition');
expect(missingIssues).toHaveLength(1);
expect(missingIssues[0].description).toContain('modals 섹션이 없습니다');
});
it('stats에서 missing-definition 카운트가 반영되어야 한다', () => {
devTools.trackLayoutLoad(
'admin/test_page',
'sirsoft-admin_basic',
{ layout_name: 'test_page', components: [], modals: [] },
'api'
);
devTools.trackModalOpen({ modalId: 'modal_missing', modalName: 'modal_missing' });
const trackingInfo = devTools.getModalStateScopeTrackingInfo();
expect(trackingInfo.stats.issuesByType['missing-definition']).toBe(1);
expect(trackingInfo.stats.issuesBySeverity.error).toBeGreaterThanOrEqual(1);
});
});
});
@@ -0,0 +1,355 @@
/**
* ServerConnector 테스트
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { ServerConnector, getServerConnector } from '../ServerConnector';
// fetch 모킹
const mockFetch = vi.fn();
describe('ServerConnector', () => {
let connector: ServerConnector;
beforeEach(() => {
// 전역 fetch 모킹
global.fetch = mockFetch;
// G7DevToolsCore 모킹
vi.mock('../G7DevToolsCore', () => ({
G7DevToolsCore: {
getInstance: () => ({
isEnabled: () => true,
getState: () => ({ _global: { test: true }, _local: {}, _computed: {} }),
getActionHistory: () => [],
getCacheStats: () => ({ hits: 10, misses: 2, entries: 5, hitRate: 83.3 }),
getLifecycleInfo: () => ({ mountedComponents: [], orphanedListeners: [] }),
getNetworkInfo: () => ({
activeRequests: [],
requestHistory: [],
pendingDataSources: [],
}),
getExpressions: () => [],
getForms: () => [],
getPerformanceInfo: () => ({
renderCounts: new Map(),
bindingEvalCount: 0,
memoryWarnings: [],
}),
getConditionalInfo: () => ({ conditionals: [], iterations: [] }),
getDataSources: () => [],
getHandlers: () => ({ builtIn: [], custom: [], module: [] }),
getComponentEventInfo: () => ({ subscriptions: [], history: [] }),
getStateRenderingInfo: () => [],
getStateHierarchyInfo: () => ({
layers: [],
conflicts: [],
resolutionOrder: [],
}),
getContextFlowInfo: () => ({
tree: [],
unusedContexts: [],
}),
getStyleValidationInfo: () => ({
issues: [],
tailwindAnalysis: { purgedClasses: [], darkModeClasses: [], responsiveClasses: [] },
}),
getAuthDebugInfo: () => ({
isAuthenticated: false,
tokenInfo: null,
events: [],
headerAnalysis: [],
}),
getLogInfo: () => ({
logs: [],
stats: { total: 0, byLevel: {}, byPrefix: {} },
}),
getLayoutDebugInfo: () => ({
currentLayout: null,
layoutHistory: [],
cacheStatus: { cached: false },
}),
getChangeDetectionInfo: () => ({
executionDetails: [],
stateChangeHistory: [],
dataSourceChangeHistory: [],
alerts: [],
stats: {
totalExecutions: 0,
earlyReturns: 0,
noChangeExecutions: 0,
totalAlerts: 0,
alertsByType: {},
},
timestamp: Date.now(),
}),
}),
},
}));
connector = new ServerConnector();
});
afterEach(() => {
vi.clearAllMocks();
connector.destroy();
});
describe('상태 덤프', () => {
it('성공적으로 상태를 덤프해야 한다', async () => {
const responseData = {
status: 'success',
path: 'storage/debug-dump/state-latest.json',
timestamp: '20260109_1530',
};
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify(responseData),
});
const sessionId = await connector.dumpState();
expect(mockFetch).toHaveBeenCalledWith(
'/_boost/g7-debug/dump-state',
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({
'Content-Type': 'application/json',
}),
})
);
// dumpState는 이제 sessionId를 반환함
expect(sessionId).toBeTruthy();
});
it('이력 저장 옵션을 전달해야 한다', async () => {
const responseData = {
status: 'success',
path: 'storage/debug-dump/state-latest.json',
};
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify(responseData),
});
await connector.dumpState(true);
expect(mockFetch).toHaveBeenCalledWith(
'/_boost/g7-debug/dump-state',
expect.objectContaining({
body: expect.stringContaining('"saveHistory":true'),
})
);
});
it('API가 error 응답을 반환해도 dumpState는 성공해야 한다 (디버그 로깅 특성상 에러 무시)', async () => {
// 현재 구현에서 sendBulkDump는 응답 status를 확인하지 않음
// 디버그 데이터 덤프 실패가 애플리케이션 크래시를 유발하면 안 되므로
// 이 동작은 의도된 것임
const responseData = {
status: 'error',
message: '디버그 모드가 비활성화되어 있습니다.',
};
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify(responseData),
});
// 에러를 throw하지 않고 정상 완료되어야 함
await expect(connector.dumpState()).resolves.toBeTruthy();
});
it('네트워크 에러 시 에러를 throw해야 한다', async () => {
mockFetch.mockRejectedValueOnce(new Error('Network error'));
await expect(connector.dumpState()).rejects.toThrow('Network error');
});
});
describe('로그 전송', () => {
it('디버그 로그를 전송해야 한다', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ status: 'success', logged: true }),
});
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await connector.sendLog({ message: 'test log' });
expect(consoleSpy).toHaveBeenCalledWith(
'[G7:DEBUG]',
expect.stringContaining('test log')
);
consoleSpy.mockRestore();
});
it('로그 전송 실패를 무시해야 한다', async () => {
mockFetch.mockRejectedValueOnce(new Error('Network error'));
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
// 에러 throw 없이 완료되어야 함
await expect(connector.sendLog({ message: 'test' })).resolves.toBeUndefined();
consoleSpy.mockRestore();
});
});
describe('에러 전송', () => {
it('에러 정보를 전송해야 한다', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ status: 'success', logged: true }),
});
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const error = new Error('Test error');
await connector.sendError(error, { component: 'TestComponent' });
expect(consoleSpy).toHaveBeenCalledWith(
'[G7:ERROR]',
expect.stringContaining('Test error')
);
consoleSpy.mockRestore();
});
});
describe('연결 상태', () => {
it('초기 연결 상태는 false여야 한다', () => {
expect(connector.isConnected()).toBe(false);
});
it('성공적인 덤프 후 연결 상태가 true가 되어야 한다', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({
status: 'success',
path: 'storage/debug-dump/state-latest.json',
}),
});
await connector.dumpState();
expect(connector.isConnected()).toBe(true);
});
it('실패한 덤프 후 연결 상태가 false가 되어야 한다', async () => {
// 먼저 성공하여 connected 상태로 만듦
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({
status: 'success',
path: 'storage/debug-dump/state-latest.json',
}),
});
await connector.dumpState();
expect(connector.isConnected()).toBe(true);
// 실패
mockFetch.mockRejectedValueOnce(new Error('Network error'));
await expect(connector.dumpState()).rejects.toThrow();
expect(connector.isConnected()).toBe(false);
});
});
describe('연결 테스트', () => {
it('성공적인 연결 테스트', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ status: 'success', message: '연결 성공' }),
});
const result = await connector.testConnection();
expect(result).toBe(true);
expect(connector.isConnected()).toBe(true);
});
it('실패한 연결 테스트', async () => {
mockFetch.mockRejectedValueOnce(new Error('Connection failed'));
const result = await connector.testConnection();
expect(result).toBe(false);
expect(connector.isConnected()).toBe(false);
});
});
describe('자동 캡처', () => {
it('자동 캡처를 시작할 수 있어야 한다', () => {
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
connector.startAutoCapture();
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('[G7DevTools] 자동 캡처 시작'),
expect.any(Number),
'ms)'
);
connector.stopAutoCapture();
consoleSpy.mockRestore();
});
it('자동 캡처를 중지할 수 있어야 한다', () => {
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
connector.startAutoCapture();
connector.stopAutoCapture();
expect(consoleSpy).toHaveBeenCalledWith('[G7DevTools] 자동 캡처 중지');
consoleSpy.mockRestore();
});
});
describe('설정 업데이트', () => {
it('타임아웃을 업데이트할 수 있어야 한다', () => {
connector.updateConfig({ timeout: 5000 });
// 설정이 업데이트되었는지 직접 확인하기 어려우므로 에러가 없으면 성공
expect(true).toBe(true);
});
it('자동 캡처 설정을 업데이트할 수 있어야 한다', () => {
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
connector.updateConfig({ autoCapture: true, autoCaptureInterval: 10000 });
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('[G7DevTools] 자동 캡처 시작'),
expect.any(Number),
'ms)'
);
connector.stopAutoCapture();
consoleSpy.mockRestore();
});
});
describe('싱글톤', () => {
it('getServerConnector는 동일한 인스턴스를 반환해야 한다', () => {
const instance1 = getServerConnector();
const instance2 = getServerConnector();
expect(instance1).toBe(instance2);
});
});
describe('리소스 정리', () => {
it('destroy 시 자동 캡처를 중지해야 한다', () => {
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
connector.startAutoCapture();
connector.destroy();
expect(consoleSpy).toHaveBeenCalledWith('[G7DevTools] 자동 캡처 중지');
consoleSpy.mockRestore();
});
});
});
@@ -0,0 +1,138 @@
/**
* DevTools Types 유틸리티 함수 테스트
*
* parseQueryParams, extractPath 함수 등 types.ts에 정의된 유틸리티 함수 테스트
*/
import { describe, it, expect } from 'vitest';
import { parseQueryParams, extractPath } from '../types';
describe('parseQueryParams', () => {
describe('기본 쿼리 파라미터 파싱', () => {
it('단일 쿼리 파라미터를 파싱해야 한다', () => {
const result = parseQueryParams('/api/products?page=1');
expect(result).toEqual({ page: '1' });
});
it('여러 쿼리 파라미터를 파싱해야 한다', () => {
const result = parseQueryParams('/api/products?page=1&per_page=20&sort=created_at');
expect(result).toEqual({
page: '1',
per_page: '20',
sort: 'created_at',
});
});
it('쿼리 파라미터가 없는 URL은 빈 객체를 반환해야 한다', () => {
const result = parseQueryParams('/api/products');
expect(result).toEqual({});
});
it('빈 문자열은 빈 객체를 반환해야 한다', () => {
const result = parseQueryParams('');
expect(result).toEqual({});
});
});
describe('배열 쿼리 파라미터 파싱', () => {
it('[]로 끝나는 키를 배열로 처리해야 한다', () => {
const result = parseQueryParams('/api/products?status[]=active');
expect(result).toEqual({ 'status[]': ['active'] });
});
it('동일한 키가 여러 번 나오면 배열로 처리해야 한다', () => {
const result = parseQueryParams('/api/products?status[]=active&status[]=pending');
expect(result).toEqual({ 'status[]': ['active', 'pending'] });
});
it('복합 쿼리 파라미터 (일반 + 배열)를 파싱해야 한다', () => {
const result = parseQueryParams('/api/products?page=1&sales_status[]=suspended&sales_status[]=sold_out&sort=name');
expect(result).toEqual({
page: '1',
'sales_status[]': ['suspended', 'sold_out'],
sort: 'name',
});
});
});
describe('전체 URL 파싱', () => {
it('전체 URL에서 쿼리 파라미터를 파싱해야 한다', () => {
const result = parseQueryParams('https://example.com/api/products?page=1&limit=10');
expect(result).toEqual({
page: '1',
limit: '10',
});
});
it('포트가 포함된 URL을 파싱해야 한다', () => {
const result = parseQueryParams('http://localhost:8000/api/users?active=true');
expect(result).toEqual({ active: 'true' });
});
});
describe('특수 문자 처리', () => {
it('URL 인코딩된 값을 디코딩해야 한다', () => {
const result = parseQueryParams('/api/search?q=hello%20world');
expect(result).toEqual({ q: 'hello world' });
});
it('특수 문자가 포함된 값을 처리해야 한다', () => {
const result = parseQueryParams('/api/search?email=test%40example.com');
expect(result).toEqual({ email: 'test@example.com' });
});
});
describe('에러 처리', () => {
it('잘못된 URL은 빈 객체를 반환해야 한다', () => {
// parseQueryParams는 상대 경로도 처리할 수 있어야 함
const result = parseQueryParams('not-a-valid-url');
// URL 객체가 생성되지 않으면 빈 객체 반환
expect(typeof result).toBe('object');
});
});
});
describe('extractPath', () => {
describe('기본 경로 추출', () => {
it('쿼리스트링 없는 URL에서 경로를 추출해야 한다', () => {
const result = extractPath('/api/products');
expect(result).toBe('/api/products');
});
it('쿼리스트링이 있는 URL에서 경로만 추출해야 한다', () => {
const result = extractPath('/api/products?page=1&limit=10');
expect(result).toBe('/api/products');
});
it('전체 URL에서 경로를 추출해야 한다', () => {
const result = extractPath('https://example.com/api/users?active=true');
expect(result).toBe('/api/users');
});
});
describe('특수 케이스', () => {
it('루트 경로를 처리해야 한다', () => {
const result = extractPath('/?page=1');
expect(result).toBe('/');
});
it('빈 문자열은 루트 경로를 반환해야 한다', () => {
const result = extractPath('');
// URL 객체 생성 시 빈 경로는 '/'로 처리됨
expect(result).toBe('/');
});
it('해시가 포함된 URL에서 경로만 추출해야 한다', () => {
const result = extractPath('/products#section1?ignored=true');
// 해시 이전의 경로만 추출
expect(result).toBe('/products');
});
});
describe('포트와 호스트 처리', () => {
it('포트가 포함된 URL에서 경로를 추출해야 한다', () => {
const result = extractPath('http://localhost:8000/api/test?foo=bar');
expect(result).toBe('/api/test');
});
});
});
+18
View File
@@ -0,0 +1,18 @@
/**
* G7 DevTools 모듈
*
* 템플릿 엔진 디버깅을 위한 종합 도구
*
* @module G7DevTools
*/
// 핵심 클래스
export { G7DevToolsCore } from './G7DevToolsCore';
export { DiagnosticEngine } from './DiagnosticEngine';
export { ServerConnector, getServerConnector } from './ServerConnector';
// 타입
export type * from './types';
// UI 컴포넌트
export { DevToolsPanel } from './ui';
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,570 @@
/**
* G7 DevTools 패널 컴포넌트
*
* 브라우저에서 실시간 디버깅을 위한 UI 패널
* Ctrl+Shift+G로 토글 가능
* 헤더 드래그로 자유 이동 가능
*
* @module DevToolsPanel
*/
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { G7DevToolsCore } from '../G7DevToolsCore';
import { getServerConnector } from '../ServerConnector';
import type { StateView, ActionLog, CacheStats } from '../types';
// 스타일, 상수, 유틸리티 import
import { injectDevToolsStyles } from './styles';
import {
TabType,
PanelPosition,
PanelSize,
ResizeDirection,
TAB_LABELS,
DEFAULT_PANEL_WIDTH,
DEFAULT_PANEL_HEIGHT,
MIN_PANEL_WIDTH,
MIN_PANEL_HEIGHT,
} from './constants';
import { loadPanelConfig, savePanelConfig } from './utils';
// 탭 컴포넌트 import
import {
StateTab,
ActionsTab,
CacheTab,
DiagnoseTab,
PerformanceTab,
LifecycleTab,
NetworkTab,
FormTab,
ConditionalTab,
ExpressionTab,
HandlersTab,
EventsTab,
DataSourcesTab,
RendersTab,
StylesTab,
AuthTab,
LogsTab,
LayoutTab,
ChangeDetectionTab,
StaleClosureTab,
NestedContextTab,
ModalScopeTab,
NamedActionsTab,
} from './tabs';
/**
* DevTools 패널 메인 컴포넌트
*/
export const DevToolsPanel: React.FC = () => {
// 컴포넌트 마운트 시 스타일 주입
useEffect(() => {
injectDevToolsStyles();
}, []);
// 로컬스토리지에서 저장된 설정 로드
const savedConfig = useRef(loadPanelConfig());
const [isOpen, setIsOpen] = useState(savedConfig.current.isOpen ?? false);
const [isMinimized, setIsMinimized] = useState(false);
const [activeTab, setActiveTab] = useState<TabType>('state');
const [state, setState] = useState<StateView>({ _global: {}, _local: {}, _computed: {} });
const [actions, setActions] = useState<ActionLog[]>([]);
const [cacheStats, setCacheStats] = useState<CacheStats>({ hits: 0, misses: 0, entries: 0, hitRate: 0 });
const [isConnected, setIsConnected] = useState(false);
// 드래그 관련 상태 - 저장된 위치 사용
const [position, setPosition] = useState<PanelPosition>(
savedConfig.current.position ?? { x: -1, y: -1 }
);
const [isDragging, setIsDragging] = useState(false);
const dragStartRef = useRef<{ x: number; y: number; posX: number; posY: number } | null>(null);
const panelRef = useRef<HTMLDivElement>(null);
// 크기 조절 관련 상태 - 저장된 크기 사용
const [size, setSize] = useState<PanelSize>(
savedConfig.current.size ?? { width: DEFAULT_PANEL_WIDTH, height: DEFAULT_PANEL_HEIGHT }
);
const [isResizing, setIsResizing] = useState(false);
const [resizeDirection, setResizeDirection] = useState<ResizeDirection>(null);
const resizeStartRef = useRef<{ x: number; y: number; width: number; height: number; posX: number; posY: number } | null>(null);
// 최대화 상태
const [isMaximized, setIsMaximized] = useState(false);
const preMaximizeStateRef = useRef<{ position: PanelPosition; size: PanelSize } | null>(null);
const devTools = G7DevToolsCore.getInstance();
const serverConnector = getServerConnector();
// 초기 위치 설정 (저장된 위치가 없으면 우측 상단)
useEffect(() => {
if (position.x === -1 && position.y === -1) {
const initialX = window.innerWidth - size.width - 16;
const initialY = 16;
setPosition({ x: initialX, y: initialY });
}
}, [position, size.width]);
// 위치/크기 변경 시 로컬스토리지에 저장 (디바운스)
useEffect(() => {
// 초기화 전이면 저장하지 않음
if (position.x === -1 && position.y === -1) return;
// 드래그/리사이즈 중이면 저장하지 않음 (끝날 때 저장)
if (isDragging || isResizing) return;
const timeoutId = setTimeout(() => {
savePanelConfig({ position, size });
}, 300);
return () => clearTimeout(timeoutId);
}, [position, size, isDragging, isResizing]);
// isOpen 변경 시 로컬스토리지에 저장
useEffect(() => {
savePanelConfig({ isOpen });
}, [isOpen]);
// 드래그 시작
const handleDragStart = useCallback((e: React.MouseEvent) => {
// 버튼 클릭 시 드래그 방지
if ((e.target as HTMLElement).tagName === 'BUTTON') return;
setIsDragging(true);
dragStartRef.current = {
x: e.clientX,
y: e.clientY,
posX: position.x,
posY: position.y,
};
e.preventDefault();
}, [position]);
// 드래그 중
useEffect(() => {
if (!isDragging) return;
const handleMouseMove = (e: MouseEvent) => {
if (!dragStartRef.current) return;
const deltaX = e.clientX - dragStartRef.current.x;
const deltaY = e.clientY - dragStartRef.current.y;
let newX = dragStartRef.current.posX + deltaX;
let newY = dragStartRef.current.posY + deltaY;
// 화면 경계 제한
const maxX = window.innerWidth - size.width;
const maxY = window.innerHeight - size.height;
newX = Math.max(0, Math.min(newX, maxX));
newY = Math.max(0, Math.min(newY, maxY));
setPosition({ x: newX, y: newY });
};
const handleMouseUp = () => {
setIsDragging(false);
dragStartRef.current = null;
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
}, [isDragging, size.width, size.height]);
// 리사이즈 시작
const handleResizeStart = useCallback((direction: ResizeDirection) => (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
setIsResizing(true);
setResizeDirection(direction);
resizeStartRef.current = {
x: e.clientX,
y: e.clientY,
width: size.width,
height: size.height,
posX: position.x,
posY: position.y,
};
}, [size, position]);
// 리사이즈 중
useEffect(() => {
if (!isResizing || !resizeDirection) return;
const handleMouseMove = (e: MouseEvent) => {
if (!resizeStartRef.current) return;
const deltaX = e.clientX - resizeStartRef.current.x;
const deltaY = e.clientY - resizeStartRef.current.y;
let newWidth = resizeStartRef.current.width;
let newHeight = resizeStartRef.current.height;
let newX = resizeStartRef.current.posX;
let newY = resizeStartRef.current.posY;
// 방향에 따른 크기/위치 계산
if (resizeDirection.includes('e')) {
newWidth = Math.max(MIN_PANEL_WIDTH, resizeStartRef.current.width + deltaX);
}
if (resizeDirection.includes('w')) {
const widthChange = Math.min(deltaX, resizeStartRef.current.width - MIN_PANEL_WIDTH);
newWidth = resizeStartRef.current.width - widthChange;
newX = resizeStartRef.current.posX + widthChange;
}
if (resizeDirection.includes('s')) {
newHeight = Math.max(MIN_PANEL_HEIGHT, resizeStartRef.current.height + deltaY);
}
if (resizeDirection.includes('n')) {
const heightChange = Math.min(deltaY, resizeStartRef.current.height - MIN_PANEL_HEIGHT);
newHeight = resizeStartRef.current.height - heightChange;
newY = resizeStartRef.current.posY + heightChange;
}
// 화면 경계 제한
newWidth = Math.min(newWidth, window.innerWidth - newX);
newHeight = Math.min(newHeight, window.innerHeight - newY);
newX = Math.max(0, newX);
newY = Math.max(0, newY);
setSize({ width: newWidth, height: newHeight });
setPosition({ x: newX, y: newY });
};
const handleMouseUp = () => {
setIsResizing(false);
setResizeDirection(null);
resizeStartRef.current = null;
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
}, [isResizing, resizeDirection]);
// 최대화 토글
const toggleMaximize = useCallback(() => {
if (isMaximized) {
// 복원
if (preMaximizeStateRef.current) {
setPosition(preMaximizeStateRef.current.position);
setSize(preMaximizeStateRef.current.size);
}
setIsMaximized(false);
} else {
// 최대화 전 상태 저장
preMaximizeStateRef.current = { position, size };
setPosition({ x: 0, y: 0 });
setSize({ width: window.innerWidth, height: window.innerHeight });
setIsMaximized(true);
}
}, [isMaximized, position, size]);
// 데이터 새로고침
const refreshData = useCallback(() => {
if (!devTools.isEnabled()) return;
setState(devTools.getState());
setActions(devTools.getActionHistory());
setCacheStats(devTools.getCacheStats());
setIsConnected(serverConnector.isConnected());
}, [devTools, serverConnector]);
// 키보드 단축키 (Ctrl+Shift+G)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey && e.shiftKey && e.key === 'G') {
e.preventDefault();
setIsOpen(prev => !prev);
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
// 초기 데이터 로드 및 상태 변경 구독
useEffect(() => {
if (!isOpen || !devTools.isEnabled()) return;
// 초기 데이터 로드
refreshData();
// 상태 변경 구독
const unsubscribeState = devTools.watchState('*', () => {
setState(devTools.getState());
});
// 액션 변경 구독
const unsubscribeActions = devTools.watchActions(() => {
setActions(devTools.getActionHistory());
setCacheStats(devTools.getCacheStats());
});
// 주기적 갱신 (5초)
const intervalId = setInterval(refreshData, 5000);
return () => {
unsubscribeState();
unsubscribeActions();
clearInterval(intervalId);
};
}, [isOpen, devTools, refreshData]);
// 서버로 상태 덤프
const handleDumpState = async () => {
try {
const path = await serverConnector.dumpState();
console.log('[G7DevTools] 상태 덤프 완료:', path);
setIsConnected(true);
} catch (error) {
console.error('[G7DevTools] 상태 덤프 실패:', error);
setIsConnected(false);
}
};
// DevTools가 비활성화된 경우
if (!devTools.isEnabled()) {
if (!isOpen) return null;
return (
<div className="g7dt-disabled-notice">
<div className="g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-2">
<span className="g7dt-font-bold g7dt-text-yellow">G7 DevTools</span>
<button
onClick={() => setIsOpen(false)}
className="g7dt-btn"
>
✕
</button>
</div>
<p className="g7dt-text-sm g7dt-text-gray">
DevTools가 비활성화되어 있습니다.
</p>
<p className="g7dt-text-xs g7dt-text-gray-dark g7dt-mt-2">
환경설정 &gt; 고급 설정 &gt; 디버그 모드를 켜세요.
</p>
</div>
);
}
// 닫힌 상태 - 플로팅 버튼만 표시
if (!isOpen) {
return (
<button
onClick={() => setIsOpen(true)}
className="g7dt-floating-btn"
title="G7 DevTools (Ctrl+Shift+G)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
</button>
);
}
// 최소화 상태
if (isMinimized) {
return (
<div className="g7dt-minimized">
<div className="g7dt-minimized-content">
<span className="g7dt-font-bold g7dt-text-sm">G7 DevTools</span>
<button
onClick={() => setIsMinimized(false)}
className="g7dt-btn g7dt-text-xs"
title="확장"
>
▲
</button>
<button
onClick={() => setIsOpen(false)}
className="g7dt-btn g7dt-text-xs"
>
✕
</button>
</div>
</div>
);
}
// 메인 패널
return (
<div
ref={panelRef}
className={`g7dt-panel ${isMaximized ? 'maximized' : ''} ${isResizing ? 'g7dt-resizing' : ''}`}
style={{
left: `${position.x >= 0 ? position.x : 0}px`,
top: `${position.y >= 0 ? position.y : 0}px`,
width: `${size.width}px`,
height: `${size.height}px`,
}}
>
{/* 리사이즈 핸들들 - 최대화 상태에서는 숨김 */}
{!isMaximized && (
<>
{/* 모서리 핸들 */}
<div
className="g7dt-resize-handle g7dt-resize-corner g7dt-resize-nw"
onMouseDown={handleResizeStart('nw')}
/>
<div
className="g7dt-resize-handle g7dt-resize-corner g7dt-resize-ne"
onMouseDown={handleResizeStart('ne')}
/>
<div
className="g7dt-resize-handle g7dt-resize-corner g7dt-resize-sw"
onMouseDown={handleResizeStart('sw')}
/>
<div
className="g7dt-resize-handle g7dt-resize-corner g7dt-resize-se"
onMouseDown={handleResizeStart('se')}
/>
{/* 가장자리 핸들 */}
<div
className="g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-n"
onMouseDown={handleResizeStart('n')}
/>
<div
className="g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-s"
onMouseDown={handleResizeStart('s')}
/>
<div
className="g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-w"
onMouseDown={handleResizeStart('w')}
/>
<div
className="g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-e"
onMouseDown={handleResizeStart('e')}
/>
</>
)}
{/* 헤더 (드래그 핸들) */}
<div
className={`g7dt-header ${isDragging ? 'dragging' : ''}`}
onMouseDown={handleDragStart}
>
<div className="g7dt-header-left">
<span className="g7dt-header-title">G7 DevTools</span>
<span
className={`g7dt-header-badge ${isConnected ? 'connected' : ''}`}
title={isConnected ? '서버 덤프 성공' : '서버에 덤프되지 않음 (덤프 버튼 클릭)'}
>
{isConnected ? '덤프 완료' : '로컬 모드'}
</span>
</div>
<div className="g7dt-header-right">
<button
onClick={handleDumpState}
className="g7dt-btn g7dt-btn-primary"
title="서버로 상태 덤프"
>
덤프
</button>
<button
onClick={refreshData}
className="g7dt-btn"
title="새로고침"
>
↻
</button>
<button
onClick={toggleMaximize}
className="g7dt-btn"
title={isMaximized ? '복원' : '최대화'}
>
{isMaximized ? '❐' : '□'}
</button>
<button
onClick={() => setIsMinimized(true)}
className="g7dt-btn"
title="최소화"
>
▼
</button>
<button
onClick={() => setIsOpen(false)}
className="g7dt-btn"
>
✕
</button>
</div>
</div>
{/* 탭 */}
<div className="g7dt-tabs">
{(Object.keys(TAB_LABELS) as TabType[]).map(tab => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`g7dt-tab ${activeTab === tab ? 'active' : ''}`}
>
{TAB_LABELS[tab]}
</button>
))}
</div>
{/* 내용 */}
<div className="g7dt-content">
{activeTab === 'state' && <StateTab state={state} devTools={devTools} />}
{activeTab === 'actions' && <ActionsTab actions={actions} devTools={devTools} />}
{activeTab === 'cache' && <CacheTab stats={cacheStats} devTools={devTools} />}
{activeTab === 'diagnose' && <DiagnoseTab />}
{activeTab === 'performance' && <PerformanceTab devTools={devTools} />}
{activeTab === 'lifecycle' && <LifecycleTab devTools={devTools} />}
{activeTab === 'network' && <NetworkTab devTools={devTools} />}
{activeTab === 'form' && <FormTab devTools={devTools} />}
{activeTab === 'conditional' && <ConditionalTab devTools={devTools} />}
{activeTab === 'expression' && <ExpressionTab devTools={devTools} />}
{activeTab === 'handlers' && <HandlersTab devTools={devTools} />}
{activeTab === 'events' && <EventsTab devTools={devTools} />}
{activeTab === 'datasources' && <DataSourcesTab devTools={devTools} />}
{activeTab === 'renders' && <RendersTab devTools={devTools} />}
{activeTab === 'styles' && <StylesTab devTools={devTools} />}
{activeTab === 'auth' && <AuthTab devTools={devTools} />}
{activeTab === 'logs' && <LogsTab devTools={devTools} />}
{activeTab === 'layout' && <LayoutTab devTools={devTools} />}
{activeTab === 'changedetection' && <ChangeDetectionTab devTools={devTools} />}
{activeTab === 'staleclosure' && <StaleClosureTab devTools={devTools} />}
{activeTab === 'nestedcontext' && <NestedContextTab devTools={devTools} />}
{activeTab === 'modalscope' && <ModalScopeTab devTools={devTools} />}
{activeTab === 'namedactions' && <NamedActionsTab devTools={devTools} />}
</div>
{/* 푸터 */}
<div className="g7dt-footer">
<span>Ctrl+Shift+G 토글 | 헤더 드래그로 이동</span>
<span>
액션: {actions.length} | 캐시 히트율: {(cacheStats.hitRate * 100).toFixed(1)}%
</span>
</div>
</div>
);
};
export default DevToolsPanel;
@@ -0,0 +1,129 @@
/**
* JSON 트리 노드 컴포넌트
*
* 중첩된 JSON 데이터를 트리 형태로 렌더링합니다.
* 펼침/접기, 검색 하이라이트 기능을 제공합니다.
*/
import React from 'react';
import { getValueColor, getTypeLabel, formatValue } from '../utils';
export interface JsonTreeNodeProps {
/** 표시할 키 이름 */
keyName: string;
/** 표시할 값 */
value: unknown;
/** 현재 노드의 경로 (예: "_global.user.name") */
path: string;
/** 펼쳐진 경로들의 Set */
expandedPaths: Set<string>;
/** 경로 토글 핸들러 */
onToggle: (path: string) => void;
/** 검색어 (하이라이트용) */
searchTerm: string;
/** 현재 깊이 (기본값: 0) */
depth?: number;
}
/**
* JSON 트리 노드 컴포넌트
*/
export const JsonTreeNode: React.FC<JsonTreeNodeProps> = ({
keyName,
value,
path,
expandedPaths,
onToggle,
searchTerm,
depth = 0,
}) => {
const isExpandable = value !== null && typeof value === 'object';
const isExpanded = expandedPaths.has(path);
const isArray = Array.isArray(value);
// 검색어 하이라이트 체크
const matchesSearch =
searchTerm &&
(keyName.toLowerCase().includes(searchTerm.toLowerCase()) ||
(typeof value === 'string' && value.toLowerCase().includes(searchTerm.toLowerCase())) ||
(typeof value === 'number' && String(value).includes(searchTerm)));
const handleToggle = (e: React.MouseEvent) => {
e.stopPropagation();
if (isExpandable) {
onToggle(path);
}
};
// 렌더링할 자식 엔트리
const childEntries = isExpandable ? Object.entries(value as Record<string, unknown>) : [];
return (
<div style={{ marginLeft: depth > 0 ? '16px' : '0' }}>
<div
className={`g7dt-tree-node g7dt-flex g7dt-items-center g7dt-gap-1 ${matchesSearch ? 'g7dt-ring-highlight' : ''}`}
onClick={handleToggle}
>
{/* 펼침/접기 아이콘 */}
{isExpandable ? (
<span
className="g7dt-text-gray g7dt-w-4 g7dt-text-xs g7dt-select-none"
style={{ textAlign: 'center' }}
>
{isExpanded ? '▼' : '▶'}
</span>
) : (
<span className="g7dt-w-4" />
)}
{/* 키 이름 */}
<span className="g7dt-text-purple g7dt-text-xs">{keyName}</span>
<span className="g7dt-text-gray-dark g7dt-text-xs">:</span>
{/* 값 또는 타입 */}
{isExpandable ? (
<span className={`g7dt-text-xs ${getValueColor(value)}`}>
{isArray ? '[' : '{'}
{!isExpanded && (
<span className="g7dt-text-gray" style={{ margin: '0 4px' }}>
{getTypeLabel(value)}
</span>
)}
{!isExpanded && (isArray ? ']' : '}')}
</span>
) : (
<span className={`g7dt-text-xs ${getValueColor(value)}`}>{formatValue(value)}</span>
)}
{/* 타입 힌트 (primitive) */}
{!isExpandable && (
<span className="g7dt-text-gray-dark g7dt-text-xs g7dt-ml-1">({typeof value})</span>
)}
</div>
{/* 자식 노드 */}
{isExpandable && isExpanded && (
<div className="g7dt-border-l" style={{ marginLeft: '8px' }}>
{childEntries.map(([childKey, childValue]) => (
<JsonTreeNode
key={`${path}.${childKey}`}
keyName={isArray ? `[${childKey}]` : childKey}
value={childValue}
path={`${path}.${childKey}`}
expandedPaths={expandedPaths}
onToggle={onToggle}
searchTerm={searchTerm}
depth={depth + 1}
/>
))}
{/* 닫는 괄호 */}
<div className="g7dt-ml-4 g7dt-text-xs">
<span className={getValueColor(value)}>{isArray ? ']' : '}'}</span>
</div>
</div>
)}
</div>
);
};
export default JsonTreeNode;
@@ -0,0 +1,6 @@
/**
* G7 DevTools 공통 컴포넌트 내보내기
*/
export { JsonTreeNode } from './JsonTreeNode';
export type { JsonTreeNodeProps } from './JsonTreeNode';
@@ -0,0 +1,89 @@
/**
* G7 DevTools 상수 및 타입 정의
*
* DevToolsPanel에서 사용되는 타입, 상수, 인터페이스를 정의합니다.
*/
// 탭 타입 정의
export type TabType =
| 'state'
| 'actions'
| 'cache'
| 'diagnose'
| 'performance'
| 'lifecycle'
| 'network'
| 'form'
| 'conditional'
| 'expression'
| 'handlers'
| 'events'
| 'datasources'
| 'renders'
| 'styles'
| 'auth'
| 'logs'
| 'layout'
| 'changedetection'
| 'staleclosure'
| 'nestedcontext'
| 'modalscope'
| 'namedactions';
// 패널 위치 타입
export interface PanelPosition {
x: number;
y: number;
}
// 패널 크기 타입
export interface PanelSize {
width: number;
height: number;
}
// 리사이즈 방향
export type ResizeDirection = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw' | null;
// 탭 라벨 매핑
export const TAB_LABELS: Record<TabType, string> = {
state: '상태',
actions: '액션',
cache: '캐시',
diagnose: '진단',
performance: '성능',
lifecycle: '라이프사이클',
network: '네트워크',
form: 'Form',
conditional: '조건부',
expression: '표현식',
handlers: '핸들러',
events: '이벤트',
datasources: '데이터소스',
renders: '렌더링',
styles: '스타일',
auth: '인증',
logs: '로그',
layout: '레이아웃',
changedetection: '변경감지',
staleclosure: 'Stale Closure',
nestedcontext: 'Context',
modalscope: '모달스코프',
namedactions: 'Named Actions',
};
// 패널 크기 상수
export const DEFAULT_PANEL_WIDTH = 700;
export const DEFAULT_PANEL_HEIGHT = 500;
export const MIN_PANEL_WIDTH = 400;
export const MIN_PANEL_HEIGHT = 300;
// 로컬스토리지 키
export const STORAGE_KEY = 'g7-devtools-panel';
// 저장되는 설정 타입
export interface StoredPanelConfig {
position: PanelPosition;
size: PanelSize;
isOpen: boolean;
}
+7
View File
@@ -0,0 +1,7 @@
/**
* G7 DevTools UI 컴포넌트
*
* @module DevToolsUI
*/
export { DevToolsPanel, default } from './DevToolsPanel';
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,262 @@
/**
* 액션 탭 컴포넌트
*
* 액션 실행 이력과 Sequence 상세 정보를 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { ActionLog, SequenceTrackingInfo } from '../../types';
export interface ActionsTabProps {
actions: ActionLog[];
devTools?: G7DevToolsCore;
}
/**
* 액션 탭
*/
export const ActionsTab: React.FC<ActionsTabProps> = ({ actions, devTools }) => {
const [filter, setFilter] = useState<string>('');
const [viewMode, setViewMode] = useState<'actions' | 'sequences'>('actions');
const [sequenceInfo, setSequenceInfo] = useState<SequenceTrackingInfo | null>(null);
const [selectedSequence, setSelectedSequence] = useState<string | null>(null);
// Sequence 데이터 새로고침
const refreshSequenceData = useCallback(() => {
if (devTools) {
setSequenceInfo(devTools.getSequenceTrackingInfo());
}
}, [devTools]);
useEffect(() => {
if (viewMode === 'sequences' && devTools) {
refreshSequenceData();
const intervalId = setInterval(refreshSequenceData, 2000);
return () => clearInterval(intervalId);
}
}, [viewMode, devTools, refreshSequenceData]);
const filteredActions = filter
? actions.filter(a => a.type.toLowerCase().includes(filter.toLowerCase()) || a.status === filter)
: actions;
const getStatusColor = (status: string) => {
switch (status) {
case 'success':
return 'g7dt-status-success';
case 'error':
return 'g7dt-status-error';
case 'started':
return 'g7dt-status-started';
default:
return 'g7dt-status-default';
}
};
const getStatusBadgeColor = (status: string) => {
switch (status) {
case 'success':
return 'g7dt-badge-success';
case 'error':
return 'g7dt-badge-error';
default:
return 'g7dt-badge-warning';
}
};
// 선택된 Sequence
const selectedSequenceData = selectedSequence && sequenceInfo
? sequenceInfo.executions.find(s => s.id === selectedSequence)
: null;
return (
<div className="g7dt-space-y-4">
{/* 뷰 모드 선택 */}
{devTools && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-gap-2">
<button
className={`g7dt-tab-button ${viewMode === 'actions' ? 'g7dt-tab-active' : ''}`}
onClick={() => setViewMode('actions')}
>
📋 액션 ({actions.length})
</button>
<button
className={`g7dt-tab-button ${viewMode === 'sequences' ? 'g7dt-tab-active' : ''}`}
onClick={() => setViewMode('sequences')}
>
🔗 Sequence ({sequenceInfo?.executions.length || 0})
</button>
</div>
</div>
)}
{/* 필터 (액션 모드) */}
{viewMode === 'actions' && (
<div className="g7dt-flex g7dt-gap-2 g7dt-flex-shrink-0">
<input
type="text"
placeholder="액션 타입 또는 상태로 필터..."
value={filter}
onChange={e => setFilter(e.target.value)}
className="g7dt-input g7dt-flex-1"
/>
<button onClick={() => setFilter('')} className="g7dt-btn-text">
초기화
</button>
</div>
)}
{/* Sequence Details (시퀀스 모드) */}
{viewMode === 'sequences' && sequenceInfo && (
<>
{/* Sequence 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">Sequence 통계</h3>
<div className="g7dt-stats-grid-3">
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-blue">
{sequenceInfo.stats.totalSequences}
</div>
<div className="g7dt-text-xs g7dt-text-muted">총 실행</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-green">
{sequenceInfo.stats.successCount}
</div>
<div className="g7dt-text-xs g7dt-text-muted">성공</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-red">
{sequenceInfo.stats.errorCount}
</div>
<div className="g7dt-text-xs g7dt-text-muted">실패</div>
</div>
</div>
</div>
{/* Sequence 목록 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">Sequence 실행 목록</h3>
{sequenceInfo.executions.length === 0 ? (
<div className="g7dt-empty-state">실행된 Sequence가 없습니다</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto">
{sequenceInfo.executions.slice().reverse().map((seq) => (
<div
key={seq.id}
className={`g7dt-list-item g7dt-cursor-pointer ${
selectedSequence === seq.id ? 'g7dt-selected' : ''
} ${seq.status === 'error' ? 'g7dt-border-red' : ''}`}
onClick={() => setSelectedSequence(
selectedSequence === seq.id ? null : seq.id
)}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{seq.status === 'completed' ? '✅' : seq.status === 'error' ? '❌' : '⏳'}</span>
<span className="g7dt-text-xs g7dt-text-white">
{seq.actions.length}개 액션
</span>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{seq.totalDuration.toFixed(0)}ms
</span>
</div>
</div>
))}
</div>
)}
</div>
{/* 선택된 Sequence 상세 */}
{selectedSequenceData && (
<div className="g7dt-card g7dt-border-blue">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
🔗 Sequence 상세 ({selectedSequenceData.actions.length}개 액션)
</h3>
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{selectedSequenceData.actions.map((action, idx) => (
<div
key={idx}
className={`g7dt-list-item ${
action.status === 'error' ? 'g7dt-border-red' : ''
}`}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-xs g7dt-text-muted">#{action.index + 1}</span>
<span className="g7dt-text-xs g7dt-text-white g7dt-font-mono">
{action.handler}
</span>
<span className={`g7dt-text-xs ${
action.status === 'success' ? 'g7dt-text-green' : 'g7dt-text-red'
}`}>
{action.status === 'success' ? '✓' : '✕'}
</span>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{action.duration.toFixed(0)}ms
</span>
</div>
{action.stateChanges && action.stateChanges.length > 0 && (
<div className="g7dt-mt-1">
<div className="g7dt-text-xs g7dt-text-muted">상태 변경:</div>
{action.stateChanges.slice(0, 3).map((change, cIdx) => (
<div key={cIdx} className="g7dt-text-xs g7dt-text-yellow g7dt-ml-2">
{change.path}
</div>
))}
{action.stateChanges.length > 3 && (
<div className="g7dt-text-xs g7dt-text-muted g7dt-ml-2">
...외 {action.stateChanges.length - 3}개
</div>
)}
</div>
)}
</div>
))}
</div>
</div>
)}
</>
)}
{/* 액션 목록 (액션 모드) */}
{viewMode === 'actions' && (
<div className="g7dt-section">
<div className="g7dt-scroll-list g7dt-space-y-2-flat g7dt-action-list">
{filteredActions.length === 0 ? (
<div className="g7dt-empty-message">액션 이력이 없습니다</div>
) : (
filteredActions
.slice(-30)
.reverse()
.map((action, i) => (
<div key={`${action.id}-${i}`} className={`g7dt-action-item ${getStatusColor(action.status)}`}>
<div className="g7dt-flex g7dt-justify-between g7dt-items-start">
<div>
<span className="g7dt-font-mono g7dt-font-bold">{action.type}</span>
<span className={`g7dt-status-badge ${getStatusBadgeColor(action.status)}`}>
{action.status}
</span>
</div>
<span className="g7dt-text-gray">
{action.duration ? `${action.duration.toFixed(2)}ms` : '-'}
</span>
</div>
{action.error && <div className="g7dt-error-box">{action.error.message}</div>}
{action.params && Object.keys(action.params).length > 0 && (
<details className="g7dt-details">
<summary className="g7dt-summary">파라미터</summary>
<pre className="g7dt-pre">{JSON.stringify(action.params, null, 2)}</pre>
</details>
)}
</div>
))
)}
</div>
</div>
)}
</div>
);
};
export default ActionsTab;
@@ -0,0 +1,363 @@
/**
* 인증 디버깅 탭 컴포넌트
*
* 인증 상태, 토큰 정보, 인증 이벤트 이력을 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { AuthDebugInfo } from '../../types';
export interface AuthTabProps {
devTools: G7DevToolsCore;
}
/**
* 인증 디버깅 탭
*/
export const AuthTab: React.FC<AuthTabProps> = ({ devTools }) => {
const [authInfo, setAuthInfo] = useState<AuthDebugInfo | null>(null);
const [selectedEvent, setSelectedEvent] = useState<string | null>(null);
const [typeFilter, setTypeFilter] = useState<string>('all');
// 데이터 새로고침
const refreshData = useCallback(() => {
setAuthInfo(devTools.getAuthDebugInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
if (!authInfo) {
return <div className="g7dt-empty-state">로딩 중...</div>;
}
// 필터링된 이벤트
const filteredEvents = authInfo.events.filter(event => {
if (typeFilter === 'all') return true;
return event.type === typeFilter;
});
// 선택된 이벤트
const selectedEventData = selectedEvent
? authInfo.events.find(e => e.id === selectedEvent)
: null;
const stats = authInfo.stats;
const state = authInfo.state;
return (
<div className="g7dt-space-y-4">
{/* 현재 인증 상태 */}
<div className="g7dt-card">
<div className="g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-3">
<h3 className="g7dt-text-sm g7dt-font-bold">현재 인증 상태</h3>
<span className="g7dt-text-xs g7dt-text-muted">
소스: {state.source || 'unknown'}
</span>
</div>
<div className="g7dt-stats-grid-3 g7dt-mb-3">
<div className="g7dt-text-center">
<div className={`g7dt-text-lg g7dt-font-bold ${state.isAuthenticated ? 'g7dt-text-green' : 'g7dt-text-red'}`}>
{state.isAuthenticated ? '✓ 인증됨' : '✕ 미인증'}
</div>
</div>
<div className="g7dt-text-center">
<div className={`g7dt-text-lg g7dt-font-bold ${state.tokens.hasAccessToken ? 'g7dt-text-green' : 'g7dt-text-yellow'}`}>
{state.tokens.hasAccessToken ? '✓ 토큰 유효' : '⚠ 토큰 없음'}
</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-lg g7dt-font-bold g7dt-text-blue">
{state.user?.name || state.user?.email || '익명'}
</div>
</div>
</div>
{/* 사용자 상세 정보 */}
{state.user && (
<div className="g7dt-border-t g7dt-pt-3 g7dt-mt-3">
<div className="g7dt-grid-2 g7dt-gap-2 g7dt-text-xs">
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">ID:</span>
<span className="g7dt-text-white g7dt-mono">{state.user.id}</span>
</div>
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">이메일:</span>
<span className="g7dt-text-white g7dt-truncate g7dt-ml-2" title={state.user.email}>{state.user.email}</span>
</div>
{state.user.name && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">이름:</span>
<span className="g7dt-text-white">{state.user.name}</span>
</div>
)}
{state.user.nickname && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">닉네임:</span>
<span className="g7dt-text-white">{state.user.nickname}</span>
</div>
)}
{state.user.phone && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">전화번호:</span>
<span className="g7dt-text-white">{state.user.phone}</span>
</div>
)}
{state.user.status && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">상태:</span>
<span className={state.user.status === 'active' ? 'g7dt-text-green' : 'g7dt-text-yellow'}>
{state.user.status}
</span>
</div>
)}
{state.user.locale && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">언어:</span>
<span className="g7dt-text-white">{state.user.locale}</span>
</div>
)}
</div>
{/* 역할 정보 */}
{state.user.roles && state.user.roles.length > 0 && (
<div className="g7dt-mt-2">
<span className="g7dt-text-muted g7dt-text-xs">역할: </span>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1">
{state.user.roles.map((role: any, idx: number) => (
<span
key={idx}
className="g7dt-role-tag"
title={role.guard_name ? `guard: ${role.guard_name}` : undefined}
>
{typeof role === 'string' ? role : role.name}
</span>
))}
</div>
</div>
)}
{/* 권한 정보 */}
{state.user.permissions && state.user.permissions.length > 0 && (
<div className="g7dt-mt-2">
<span className="g7dt-text-muted g7dt-text-xs">권한: </span>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1 g7dt-max-h-16 g7dt-overflow-auto">
{state.user.permissions.slice(0, 10).map((perm: any, idx: number) => (
<span
key={idx}
className="g7dt-perm-tag"
title={perm.guard_name ? `guard: ${perm.guard_name}` : undefined}
>
{typeof perm === 'string' ? perm : perm.name}
</span>
))}
{state.user.permissions.length > 10 && (
<span className="g7dt-text-muted g7dt-text-xs">+{state.user.permissions.length - 10}개</span>
)}
</div>
</div>
)}
{/* 날짜 정보 */}
<div className="g7dt-mt-2 g7dt-grid-2 g7dt-gap-2 g7dt-text-xs">
{state.user.created_at && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">가입일:</span>
<span className="g7dt-text-muted">{new Date(state.user.created_at).toLocaleDateString()}</span>
</div>
)}
{state.user.last_login_at && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">마지막 로그인:</span>
<span className="g7dt-text-muted">{new Date(state.user.last_login_at).toLocaleString()}</span>
</div>
)}
{state.user.email_verified_at && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">이메일 인증:</span>
<span className="g7dt-text-green">✓ 인증됨</span>
</div>
)}
</div>
</div>
)}
{/* 토큰 상세 정보 */}
<div className="g7dt-border-t g7dt-pt-3 g7dt-mt-3">
<div className="g7dt-grid-2 g7dt-gap-2 g7dt-text-xs">
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">저장소:</span>
<span className="g7dt-text-white">{state.tokens.storage}</span>
</div>
{state.tokens.accessTokenPreview && (
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-muted">토큰:</span>
<span className="g7dt-text-muted g7dt-mono">{state.tokens.accessTokenPreview}</span>
</div>
)}
</div>
</div>
{state.tokens.accessTokenExpiresAt && (
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-2 g7dt-text-center">
토큰 만료: {new Date(state.tokens.accessTokenExpiresAt).toLocaleString()}
</div>
)}
</div>
{/* 통계 */}
<div className="g7dt-stats-grid-5">
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-blue">{stats.loginAttempts}</div>
<div className="g7dt-stat-label">로그인 시도</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-green">{stats.successfulLogins}</div>
<div className="g7dt-stat-label">성공</div>
</div>
<div className="g7dt-stat-card-sm">
<div className={`g7dt-stat-value-sm ${stats.failedLogins > 0 ? 'g7dt-text-red' : 'g7dt-text-muted'}`}>
{stats.failedLogins}
</div>
<div className="g7dt-stat-label">실패</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-purple">{stats.tokenRefreshes}</div>
<div className="g7dt-stat-label">토큰 갱신</div>
</div>
<div className="g7dt-stat-card-sm">
<div className={`g7dt-stat-value-sm ${stats.unauthorizedResponses > 0 ? 'g7dt-text-red' : 'g7dt-text-muted'}`}>
{stats.unauthorizedResponses}
</div>
<div className="g7dt-stat-label">401 응답</div>
</div>
</div>
{/* 필터 */}
<div className="g7dt-flex g7dt-gap-2">
<select
value={typeFilter}
onChange={e => setTypeFilter(e.target.value)}
className="g7dt-select"
>
<option value="all">모든 이벤트</option>
<option value="login">로그인</option>
<option value="logout">로그아웃</option>
<option value="token-refresh">토큰 갱신</option>
<option value="token-expired">토큰 만료</option>
<option value="api-unauthorized">401 응답</option>
</select>
<button
onClick={refreshData}
className="g7dt-btn-secondary"
>
새로고침
</button>
</div>
{/* 이벤트 목록 */}
<div className="g7dt-scroll-list-sm">
{filteredEvents.length === 0 ? (
<div className="g7dt-empty-state">
인증 이벤트가 없습니다
</div>
) : (
filteredEvents.slice(-20).reverse().map(event => {
const icon = event.success ? '✅' : '❌';
const time = new Date(event.timestamp).toLocaleTimeString();
return (
<div
key={event.id}
onClick={() => setSelectedEvent(event.id)}
className={`g7dt-auth-event-item ${
selectedEvent === event.id
? 'g7dt-selected'
: event.success
? ''
: 'g7dt-error'
}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-mono">
{icon} {event.type}
</span>
<span className="g7dt-text-muted">{time}</span>
</div>
{event.error && (
<div className="g7dt-text-red g7dt-mt-1 g7dt-truncate">{event.error}</div>
)}
</div>
);
})
)}
</div>
{/* 선택된 이벤트 상세 */}
{selectedEventData && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">{selectedEventData.type}</h3>
<button
onClick={() => setSelectedEvent(null)}
className="g7dt-close-btn"
>
✕
</button>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
<div>
<span className="g7dt-text-muted">결과:</span>
<span className={`g7dt-ml-2 ${selectedEventData.success ? 'g7dt-text-green' : 'g7dt-text-red'}`}>
{selectedEventData.success ? '성공' : '실패'}
</span>
</div>
{selectedEventData.error && (
<div>
<span className="g7dt-text-muted">에러:</span>
<div className="g7dt-mt-1 g7dt-text-red">{selectedEventData.error}</div>
</div>
)}
{selectedEventData.details && Object.keys(selectedEventData.details).length > 0 && (
<div>
<span className="g7dt-text-muted">상세:</span>
<pre className="g7dt-pre g7dt-text-green">
{JSON.stringify(selectedEventData.details, null, 2)}
</pre>
</div>
)}
</div>
</div>
)}
{/* API 헤더 분석 */}
{authInfo.headerAnalysis.length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">최근 API 인증 헤더</h3>
<div className="g7dt-scroll-list-xs">
{authInfo.headerAnalysis.slice(-10).reverse().map((header, i) => (
<div key={i} className="g7dt-header-item">
<span className="g7dt-text-blue g7dt-truncate g7dt-flex-1">{header.url}</span>
<span className={`g7dt-ml-2 ${header.hasAuthHeader ? 'g7dt-text-green' : 'g7dt-text-yellow'}`}>
{header.hasAuthHeader ? `✓ ${header.headerType}` : '✕ 헤더 없음'}
</span>
{header.responseStatus && (
<span className={`g7dt-ml-2 ${header.responseStatus < 400 ? 'g7dt-text-muted' : 'g7dt-text-red'}`}>
{header.responseStatus}
</span>
)}
</div>
))}
</div>
</div>
)}
</div>
);
};
export default AuthTab;
@@ -0,0 +1,144 @@
/**
* 캐시 탭 컴포넌트
*
* 캐시 통계와 캐시 결정 로그를 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import type { CacheStats, CacheDecisionTrackingInfo } from '../../types';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface CacheTabProps {
stats: CacheStats;
devTools: G7DevToolsCore;
}
/**
* 캐시 탭
*/
export const CacheTab: React.FC<CacheTabProps> = ({ stats, devTools }) => {
const [decisionInfo, setDecisionInfo] = useState<CacheDecisionTrackingInfo | null>(null);
const [showDecisionLog, setShowDecisionLog] = useState(false);
// 캐시 결정 데이터 새로고침
const refreshDecisionData = useCallback(() => {
setDecisionInfo(devTools.getCacheDecisionTrackingInfo());
}, [devTools]);
useEffect(() => {
if (showDecisionLog) {
refreshDecisionData();
const intervalId = setInterval(refreshDecisionData, 2000);
return () => clearInterval(intervalId);
}
}, [showDecisionLog, refreshDecisionData]);
const handleClearCache = () => {
devTools.resetCacheStats();
console.log('[G7DevTools] 캐시 통계 초기화');
};
// 결정 타입 아이콘
const getDecisionIcon = (decision: string) => {
switch (decision) {
case 'use_cache': return '✅';
case 'skip_cache': return '⏭️';
case 'invalidate': return '🗑️';
default: return '❓';
}
};
return (
<div className="g7dt-space-y-6">
{/* 통계 카드 */}
<div className="g7dt-stats-grid">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-green">{stats.hits}</div>
<div className="g7dt-stat-label">Cache Hits</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-red">{stats.misses}</div>
<div className="g7dt-stat-label">Cache Misses</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-blue">{stats.entries}</div>
<div className="g7dt-stat-label">Entries</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-purple">{stats.hitRate.toFixed(1)}%</div>
<div className="g7dt-stat-label">Hit Rate</div>
</div>
</div>
{/* 히트율 바 */}
<div className="g7dt-space-y-2">
<div className="g7dt-text-sm g7dt-text-gray">캐시 히트율</div>
<div className="g7dt-progress-bar">
<div className="g7dt-progress-fill" style={{ width: `${stats.hitRate}%` }} />
</div>
</div>
{/* 버튼 */}
<div className="g7dt-flex g7dt-gap-2">
<button onClick={handleClearCache} className="g7dt-btn-danger">
캐시 통계 초기화
</button>
<button
onClick={() => setShowDecisionLog(!showDecisionLog)}
className={`g7dt-tab-button ${showDecisionLog ? 'g7dt-tab-active' : ''}`}
>
📋 Decision Log
</button>
</div>
{/* Decision Log 섹션 */}
{showDecisionLog && decisionInfo && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
캐시 결정 로그 ({decisionInfo.decisions.length}개)
</h3>
{decisionInfo.decisions.length === 0 ? (
<div className="g7dt-empty-state">캐시 결정 기록이 없습니다</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{decisionInfo.decisions.slice().reverse().slice(0, 50).map((d) => (
<div
key={d.id}
className={`g7dt-list-item ${
d.decision === 'skip_cache' ? 'g7dt-border-yellow' :
d.decision === 'invalidate' ? 'g7dt-border-red' : ''
}`}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getDecisionIcon(d.decision)}</span>
<span className="g7dt-text-xs g7dt-text-white g7dt-font-mono g7dt-truncate" style={{ maxWidth: '200px' }}>
{d.expression}
</span>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{d.decision}
</span>
</div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-1">
{d.reason}
</div>
{d.context && (
<div className="g7dt-flex g7dt-gap-2 g7dt-mt-1">
{d.context.isInIteration && (
<span className="g7dt-badge g7dt-text-xs">🔄 iteration</span>
)}
{d.context.isInAction && (
<span className="g7dt-badge g7dt-text-xs">⚡ action</span>
)}
</div>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
);
};
export default CacheTab;
@@ -0,0 +1,377 @@
/**
* 변경 감지 탭 컴포넌트
*
* 핸들러 실행 시 상태/데이터소스 변경 여부를 추적하고
* early return, 기대 변경 미발생 등의 문제를 감지하여 표시합니다.
*/
import React, { useState, useEffect } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { ChangeDetectionInfo, ChangeAlertType } from '../../types';
export interface ChangeDetectionTabProps {
devTools: G7DevToolsCore;
}
/**
* 변경 감지 탭
*/
export const ChangeDetectionTab: React.FC<ChangeDetectionTabProps> = ({ devTools }) => {
const [changeInfo, setChangeInfo] = useState<ChangeDetectionInfo>(devTools.getChangeDetectionInfo());
const [selectedExecution, setSelectedExecution] = useState<string | null>(null);
const [showWarningsOnly, setShowWarningsOnly] = useState(false);
const [expandedAlerts, setExpandedAlerts] = useState<Set<string>>(new Set());
useEffect(() => {
const interval = setInterval(() => {
setChangeInfo(devTools.getChangeDetectionInfo());
}, 500);
return () => clearInterval(interval);
}, [devTools]);
const { executionDetails, alerts, stats } = changeInfo;
// 필터링된 실행 목록
const filteredExecutions = showWarningsOnly
? executionDetails.filter(e => e.alerts.length > 0 || e.stateChanges.length === 0)
: executionDetails;
// 선택된 실행 상세
const selectedDetail = selectedExecution
? executionDetails.find(e => e.executionId === selectedExecution)
: null;
// 알림 토글
const toggleAlert = (alertId: string) => {
setExpandedAlerts(prev => {
const next = new Set(prev);
if (next.has(alertId)) {
next.delete(alertId);
} else {
next.add(alertId);
}
return next;
});
};
// 종료 사유별 아이콘
const getExitReasonIcon = (reason?: string): string => {
switch (reason) {
case 'normal': return '✅';
case 'early-return-condition': return '⏎';
case 'early-return-validation': return '❌';
case 'error': return '💥';
default: return '❓';
}
};
// 알림 유형별 아이콘
const getAlertTypeIcon = (type: ChangeAlertType): string => {
switch (type) {
case 'no-state-change': return '⚠️';
case 'no-datasource-change': return '📊';
case 'expected-not-fulfilled': return '❗';
case 'object-reference-same': return '🔄';
case 'early-return-detected': return '⏎';
case 'async-timing-issue': return '⏱️';
default: return '📢';
}
};
// 심각도별 색상
const getSeverityColor = (severity: string): string => {
switch (severity) {
case 'error': return 'g7dt-text-red';
case 'warning': return 'g7dt-text-yellow';
case 'info': return 'g7dt-text-blue';
default: return 'g7dt-text-white';
}
};
// 시간 포맷
const formatTime = (timestamp: number): string => {
return new Date(timestamp).toLocaleTimeString('ko-KR', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
fractionalSecondDigits: 3,
});
};
return (
<div className="g7dt-space-y-4">
{/* 알림 배너 (경고/에러가 있는 경우) */}
{alerts.filter(a => a.severity === 'error' || a.severity === 'warning').length > 0 && (
<div className="g7dt-card" style={{ backgroundColor: '#7f1d1d', borderColor: '#991b1b' }}>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-font-bold">
⚠️ 변경 감지 알림: {alerts.filter(a => a.severity === 'error').length}개 에러,{' '}
{alerts.filter(a => a.severity === 'warning').length}개 경고
</span>
<button
onClick={() => devTools.clearChangeDetectionData()}
className="g7dt-btn-small"
>
초기화
</button>
</div>
</div>
)}
{/* 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">📊 변경 감지 통계</h3>
<div className="g7dt-grid-3">
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">총 실행:</span>
<span className="g7dt-text-blue">{stats.totalExecutions}</span>
</div>
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">상태 변경 있음:</span>
<span className="g7dt-text-green">{stats.executionsWithStateChange}</span>
</div>
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">상태 변경 없음:</span>
<span className={stats.executionsWithoutStateChange > 0 ? 'g7dt-text-yellow' : 'g7dt-text-gray'}>
{stats.executionsWithoutStateChange}
</span>
</div>
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">Early Return:</span>
<span className="g7dt-text-orange">{stats.earlyReturnCount}</span>
</div>
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">알림:</span>
<span className={stats.alertCount > 0 ? 'g7dt-text-red' : 'g7dt-text-gray'}>
{stats.alertCount}
</span>
</div>
</div>
</div>
{/* 최근 알림 목록 */}
{alerts.length > 0 && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">🔔 최근 알림</h3>
<div className="g7dt-space-y-2" style={{ maxHeight: '200px', overflowY: 'auto' }}>
{alerts.slice(-10).reverse().map(alert => (
<div
key={alert.id}
className="g7dt-list-item"
onClick={() => toggleAlert(alert.id)}
style={{ cursor: 'pointer' }}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-start">
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getAlertTypeIcon(alert.type)}</span>
<span className={`g7dt-text-xs ${getSeverityColor(alert.severity)}`}>
{alert.message}
</span>
</div>
<span className="g7dt-text-xs g7dt-text-muted">
{formatTime(alert.timestamp)}
</span>
</div>
{expandedAlerts.has(alert.id) && (
<div className="g7dt-mt-2 g7dt-text-xs g7dt-text-muted g7dt-pl-6">
<p>{alert.description}</p>
{alert.statePath && (
<p className="g7dt-mt-1">
<span className="g7dt-text-cyan">경로:</span> {alert.statePath}
</p>
)}
{alert.suggestion && (
<p className="g7dt-mt-1">
<span className="g7dt-text-green">제안:</span> {alert.suggestion}
</p>
)}
{alert.docLink && (
<p className="g7dt-mt-1">
<span className="g7dt-text-blue">문서:</span>{' '}
<code className="g7dt-code">{alert.docLink}</code>
</p>
)}
</div>
)}
</div>
))}
</div>
</div>
)}
{/* 핸들러 실행 목록 */}
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">🔧 핸들러 실행 이력</h3>
<label className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs">
<input
type="checkbox"
checked={showWarningsOnly}
onChange={e => setShowWarningsOnly(e.target.checked)}
/>
<span>경고만 표시</span>
</label>
</div>
{filteredExecutions.length === 0 ? (
<div className="g7dt-empty-state">
핸들러 실행 이력이 없습니다.
<br />
액션을 실행하면 여기에 표시됩니다.
</div>
) : (
<div className="g7dt-space-y-1" style={{ maxHeight: '300px', overflowY: 'auto' }}>
{filteredExecutions.slice(-20).reverse().map(exec => (
<div
key={exec.executionId}
className={`g7dt-list-item ${selectedExecution === exec.executionId ? 'g7dt-selected' : ''}`}
onClick={() => setSelectedExecution(
selectedExecution === exec.executionId ? null : exec.executionId
)}
style={{ cursor: 'pointer' }}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getExitReasonIcon(exec.exitReason)}</span>
<span className="g7dt-text-white g7dt-font-mono g7dt-text-xs">
{exec.handlerName}
</span>
{exec.alerts.length > 0 && (
<span className="g7dt-badge g7dt-badge-warning">
{exec.alerts.length}
</span>
)}
</div>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs">
<span className="g7dt-text-muted">
상태: {exec.stateChanges.length}
</span>
<span className="g7dt-text-muted">
{exec.duration ? `${exec.duration}ms` : '-'}
</span>
<span className="g7dt-text-muted">
{formatTime(exec.startTime)}
</span>
</div>
</div>
{/* 선택된 실행 상세 */}
{selectedExecution === exec.executionId && selectedDetail && (
<div className="g7dt-mt-3 g7dt-pt-3 g7dt-border-t g7dt-border-gray-700">
{/* 종료 정보 */}
<div className="g7dt-mb-2">
<span className="g7dt-text-xs g7dt-text-muted">종료 사유: </span>
<span className="g7dt-text-xs g7dt-text-white">
{selectedDetail.exitReason || 'unknown'}
</span>
{selectedDetail.exitLocation && (
<>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-2">위치: </span>
<code className="g7dt-code g7dt-text-xs">
{selectedDetail.exitLocation}
</code>
</>
)}
</div>
{selectedDetail.exitDescription && (
<div className="g7dt-mb-2 g7dt-text-xs g7dt-text-muted">
{selectedDetail.exitDescription}
</div>
)}
{/* 상태 변경 목록 */}
{selectedDetail.stateChanges.length > 0 && (
<div className="g7dt-mb-2">
<span className="g7dt-text-xs g7dt-font-bold g7dt-text-green">
상태 변경 ({selectedDetail.stateChanges.length})
</span>
<div className="g7dt-mt-1 g7dt-space-y-1">
{selectedDetail.stateChanges.map(sc => (
<div key={sc.id} className="g7dt-text-xs g7dt-pl-2">
<span className="g7dt-text-cyan">{sc.path}</span>
<span className="g7dt-text-muted"> ({sc.changeType})</span>
{sc.comparison.changedKeys && (
<span className="g7dt-text-muted g7dt-ml-1">
[변경: {sc.comparison.changedKeys.join(', ')}]
</span>
)}
</div>
))}
</div>
</div>
)}
{/* 데이터소스 변경 목록 */}
{selectedDetail.dataSourceChanges.length > 0 && (
<div className="g7dt-mb-2">
<span className="g7dt-text-xs g7dt-font-bold g7dt-text-blue">
데이터소스 변경 ({selectedDetail.dataSourceChanges.length})
</span>
<div className="g7dt-mt-1 g7dt-space-y-1">
{selectedDetail.dataSourceChanges.map((dc, idx) => (
<div key={idx} className="g7dt-text-xs g7dt-pl-2">
<span className="g7dt-text-cyan">{dc.dataSourceId}</span>
<span className="g7dt-text-muted">
{' '}({dc.changeType}: {dc.previousStatus} → {dc.newStatus})
</span>
</div>
))}
</div>
</div>
)}
{/* 기대 변경 */}
{selectedDetail.expectedChanges && (
<div className="g7dt-mb-2">
<span className="g7dt-text-xs g7dt-font-bold g7dt-text-yellow">
기대 변경
</span>
<div className="g7dt-mt-1 g7dt-text-xs g7dt-pl-2 g7dt-text-muted">
상태: {selectedDetail.expectedChanges.expectedStatePaths.join(', ') || '없음'}
<br />
데이터소스: {selectedDetail.expectedChanges.expectedDataSources.join(', ') || '없음'}
</div>
</div>
)}
{/* 알림 */}
{selectedDetail.alerts.length > 0 && (
<div>
<span className="g7dt-text-xs g7dt-font-bold g7dt-text-red">
알림 ({selectedDetail.alerts.length})
</span>
<div className="g7dt-mt-1 g7dt-space-y-1">
{selectedDetail.alerts.map(alert => (
<div key={alert.id} className="g7dt-text-xs g7dt-pl-2">
<span>{getAlertTypeIcon(alert.type)}</span>
<span className={`g7dt-ml-1 ${getSeverityColor(alert.severity)}`}>
{alert.message}
</span>
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
))}
</div>
)}
</div>
{/* 사용 가이드 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">💡 변경 감지 가이드</h3>
<ul className="g7dt-help-list">
<li>핸들러 실행 후 상태 변경이 없으면 ⚠️ 경고가 표시됩니다</li>
<li>early return으로 종료된 경우 ⏎ 아이콘으로 표시됩니다</li>
<li>객체 변경 시 참조가 동일하면 🔄 경고가 발생합니다</li>
<li>문제 해결: exitLocation 확인 → 조건문 검토 → 불변성 확인</li>
</ul>
</div>
</div>
);
};
export default ChangeDetectionTab;
@@ -0,0 +1,115 @@
/**
* 조건부 렌더링 탭 컴포넌트
*
* if 조건과 iteration 정보를 표시합니다.
*/
import React from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { ConditionInfo, IterationInfo } from '../../types';
export interface ConditionalTabProps {
devTools: G7DevToolsCore;
}
/**
* 조건부 렌더링 탭
*/
export const ConditionalTab: React.FC<ConditionalTabProps> = ({ devTools }) => {
const conditionalInfo = devTools.getConditionalInfo();
return (
<div className="g7dt-space-y-4">
{/* if 조건들 */}
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-2">
if 조건 ({conditionalInfo.ifConditions.length})
</h3>
<div className="g7dt-space-y-1 g7dt-scroll-list">
{conditionalInfo.ifConditions.length === 0 ? (
<div className="g7dt-empty-message">추적된 if 조건 없음</div>
) : (
conditionalInfo.ifConditions.map((cond: ConditionInfo) => (
<div
key={cond.id}
className={`g7dt-condition-item ${cond.evaluatedValue ? 'g7dt-condition-true' : 'g7dt-condition-false'}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60">
{cond.expression}
</span>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className={cond.evaluatedValue ? 'g7dt-badge-success' : 'g7dt-badge-error'}>
{cond.evaluatedValue ? 'true' : 'false'}
</span>
<span className="g7dt-text-gray">
{cond.evaluationCount}회
</span>
</div>
</div>
</div>
))
)}
</div>
</div>
{/* iteration들 */}
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-2">
iteration ({conditionalInfo.iterations.length})
</h3>
<div className="g7dt-space-y-1 g7dt-scroll-list">
{conditionalInfo.iterations.length === 0 ? (
<div className="g7dt-empty-message">추적된 iteration 없음</div>
) : (
conditionalInfo.iterations.map((iter: IterationInfo) => (
<div
key={iter.id}
className="g7dt-card g7dt-text-xs"
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-1">
<span className="g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60">
{iter.source}
</span>
<span className={iter.sourceLength > 0 ? 'g7dt-badge-blue' : 'g7dt-badge-warning'}>
{iter.sourceLength}개 항목
</span>
</div>
<div className="g7dt-text-gray">
<span className="g7dt-mr-2">item_var: {iter.itemVar}</span>
{iter.indexVar && <span>index_var: {iter.indexVar}</span>}
</div>
</div>
))
)}
</div>
</div>
{/* 문제 감지 */}
{(conditionalInfo.ifConditions.some((c: ConditionInfo) => c.evaluatedValue === false && c.evaluationCount > 5) ||
conditionalInfo.iterations.some((i: IterationInfo) => i.sourceLength === 0)) && (
<div className="g7dt-warning-box">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2">잠재적 문제</h3>
<div className="g7dt-space-y-1 g7dt-text-xs">
{conditionalInfo.ifConditions
.filter((c: ConditionInfo) => c.evaluatedValue === false && c.evaluationCount > 5)
.map((c: ConditionInfo) => (
<div key={c.id} className="g7dt-text-lightgray">
⚠️ if 조건 항상 false: {c.expression}
</div>
))}
{conditionalInfo.iterations
.filter((i: IterationInfo) => i.sourceLength === 0)
.map((i: IterationInfo) => (
<div key={i.id} className="g7dt-text-lightgray">
⚠️ iteration 소스 비어있음: {i.source}
</div>
))}
</div>
</div>
)}
</div>
);
};
export default ConditionalTab;
@@ -0,0 +1,322 @@
/**
* 데이터소스 탭 컴포넌트
*
* 데이터소스 정의 및 상태를 표시합니다.
* Path Transform 추적 기능 포함 (Phase 4).
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { DataPathTransformTrackingInfo, DataPathTransformStep } from '../../types';
export interface DataSourcesTabProps {
devTools: G7DevToolsCore;
}
/**
* 데이터소스 탭
*/
export const DataSourcesTab: React.FC<DataSourcesTabProps> = ({ devTools }) => {
const dataSources = devTools.getDataSources();
const [statusFilter, setStatusFilter] = useState<string>('all');
const [selectedDs, setSelectedDs] = useState<string | null>(null);
const [showPathTransform, setShowPathTransform] = useState(false);
const [transformInfo, setTransformInfo] = useState<DataPathTransformTrackingInfo | null>(null);
// Path Transform 데이터 새로고침
const refreshTransformData = useCallback(() => {
setTransformInfo(devTools.getDataPathTransformTrackingInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
if (showPathTransform) {
refreshTransformData();
const intervalId = setInterval(refreshTransformData, 2000);
return () => clearInterval(intervalId);
}
}, [showPathTransform, refreshTransformData]);
// 변환 단계 아이콘
const getStepIcon = (step: DataPathTransformStep) => {
switch (step) {
case 'api_response': return '📥';
case 'extract_data': return '📄';
case 'apply_path': return '🔗';
case 'init_global': return '🌐';
case 'init_local': return '📌';
default: return '❓';
}
};
// 상태별 필터링
const filteredDataSources = dataSources.filter(ds => {
if (statusFilter === 'all') return true;
return ds.status === statusFilter;
});
// 상태별 카운트
const statusCounts = {
all: dataSources.length,
idle: dataSources.filter(ds => ds.status === 'idle').length,
loading: dataSources.filter(ds => ds.status === 'loading').length,
loaded: dataSources.filter(ds => ds.status === 'loaded').length,
error: dataSources.filter(ds => ds.status === 'error').length,
};
// 상태에 따른 색상
const getStatusColor = (status: string) => {
switch (status) {
case 'loaded':
return 'g7dt-badge-success';
case 'loading':
return 'g7dt-badge-warning';
case 'error':
return 'g7dt-badge-error';
default:
return 'g7dt-badge-gray';
}
};
// 선택된 데이터소스
const selectedDataSource = selectedDs
? dataSources.find(ds => ds.id === selectedDs)
: null;
return (
<div className="g7dt-space-y-4">
{/* 상태 필터 */}
<div className="g7dt-flex g7dt-gap-2">
{(['all', 'idle', 'loading', 'loaded', 'error'] as const).map(status => (
<button
key={status}
onClick={() => setStatusFilter(status)}
className={statusFilter === status ? 'g7dt-filter-btn g7dt-filter-active' : 'g7dt-filter-btn'}
>
{status === 'all' ? '전체' : status} ({statusCounts[status]})
</button>
))}
</div>
{/* 데이터소스 목록 */}
<div className="g7dt-ds-grid">
{filteredDataSources.length === 0 ? (
<div className="g7dt-empty-message g7dt-col-span-2 g7dt-py-4">
데이터소스가 없습니다
</div>
) : (
filteredDataSources.map(ds => (
<div
key={ds.id}
onClick={() => setSelectedDs(ds.id)}
className={`g7dt-ds-item ${selectedDs === ds.id ? 'g7dt-ds-selected' : ''}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-font-mono g7dt-text-blue g7dt-truncate">{ds.id}</span>
<span className={`g7dt-mini-badge ${getStatusColor(ds.status)}`}>
{ds.status}
</span>
</div>
<div className="g7dt-text-gray g7dt-mt-1 g7dt-truncate">
{ds.endpoint || '(endpoint 없음)'}
</div>
{ds.itemCount !== undefined && (
<div className="g7dt-text-lightgray g7dt-mt-1">
{ds.itemCount}개 항목
</div>
)}
</div>
))
)}
</div>
{/* 선택된 데이터소스 상세 */}
{selectedDataSource && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">{selectedDataSource.id}</h3>
<button
onClick={() => setSelectedDs(null)}
className="g7dt-btn-close"
>
✕
</button>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
{/* 엔드포인트 */}
<div>
<span className="g7dt-text-gray">엔드포인트:</span>
<span className="g7dt-ml-2 g7dt-text-green">{selectedDataSource.endpoint || '-'}</span>
</div>
{/* 데이터 경로 */}
{selectedDataSource.dataPath && (
<div>
<span className="g7dt-text-gray">데이터 경로:</span>
<span className="g7dt-ml-2 g7dt-text-yellow">{selectedDataSource.dataPath}</span>
</div>
)}
{/* 상태 */}
<div>
<span className="g7dt-text-gray">상태:</span>
<span className={`g7dt-ml-2 g7dt-mini-badge ${getStatusColor(selectedDataSource.status)}`}>
{selectedDataSource.status}
</span>
</div>
{/* 항목 수 */}
{selectedDataSource.itemCount !== undefined && (
<div>
<span className="g7dt-text-gray">항목 수:</span>
<span className="g7dt-ml-2 g7dt-text-blue">{selectedDataSource.itemCount}</span>
</div>
)}
{/* 키 목록 */}
{selectedDataSource.keys && selectedDataSource.keys.length > 0 && (
<div>
<span className="g7dt-text-gray">키:</span>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1">
{selectedDataSource.keys.slice(0, 10).map((key: string) => (
<span key={key} className="g7dt-key-tag">
{key}
</span>
))}
{selectedDataSource.keys.length > 10 && (
<span className="g7dt-text-gray">+{selectedDataSource.keys.length - 10}개</span>
)}
</div>
</div>
)}
{/* 의존성 */}
{selectedDataSource.dependencies && selectedDataSource.dependencies.length > 0 && (
<div>
<span className="g7dt-text-gray">의존성:</span>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1">
{selectedDataSource.dependencies.map((dep: string) => (
<span key={dep} className="g7dt-dep-tag">
{dep}
</span>
))}
</div>
</div>
)}
</div>
</div>
)}
{/* 통계 및 버튼 */}
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<div className="g7dt-text-xs g7dt-text-gray">
총 {dataSources.length}개 데이터소스 |
로드됨 {statusCounts.loaded} |
로딩중 {statusCounts.loading} |
에러 {statusCounts.error}
</div>
<button
onClick={() => setShowPathTransform(!showPathTransform)}
className={`g7dt-tab-button ${showPathTransform ? 'g7dt-tab-active' : ''}`}
>
🔀 Path Transform
</button>
</div>
{/* Path Transform 섹션 */}
{showPathTransform && transformInfo && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
데이터 경로 변환 추적 ({transformInfo.transforms.length}개)
</h3>
{/* 통계 */}
<div className="g7dt-stats-grid-3 g7dt-mb-3">
<div className="g7dt-text-center">
<div className="g7dt-text-xl g7dt-font-bold g7dt-text-blue">
{transformInfo.stats.totalTransforms}
</div>
<div className="g7dt-text-xs g7dt-text-muted">총 변환</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-xl g7dt-font-bold g7dt-text-purple">
{Object.keys(transformInfo.stats.byDataSource).length}
</div>
<div className="g7dt-text-xs g7dt-text-muted">데이터소스</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-xl g7dt-font-bold g7dt-text-yellow">
{transformInfo.stats.warningsCount}
</div>
<div className="g7dt-text-xs g7dt-text-muted">경고</div>
</div>
</div>
{/* 변환 목록 */}
{transformInfo.transforms.length === 0 ? (
<div className="g7dt-empty-state">변환 기록이 없습니다</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{transformInfo.transforms.slice().reverse().slice(0, 20).map((transform, idx) => (
<div
key={`${transform.dataSourceId}-${idx}`}
className={`g7dt-list-item ${transform.warnings.length > 0 ? 'g7dt-border-yellow' : ''}`}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-xs g7dt-text-blue g7dt-font-mono">
{transform.dataSourceId}
</span>
{transform.warnings.length > 0 && (
<span className="g7dt-badge g7dt-text-xs g7dt-text-yellow">
⚠️ {transform.warnings.length}
</span>
)}
</div>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1">
{transform.transformSteps.map((step, stepIdx) => (
<span
key={stepIdx}
className="g7dt-badge g7dt-text-xs"
title={`${step.inputPath} → ${step.outputPath}`}
>
{getStepIcon(step.step)} {step.step}
</span>
))}
</div>
{transform.finalBinding && (
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-1">
최종: <span className="g7dt-text-green">{transform.finalBinding.expression}</span>
→ <span className="g7dt-text-blue">{transform.finalBinding.resolvedPath}</span>
</div>
)}
{transform.warnings.length > 0 && (
<div className="g7dt-text-xs g7dt-text-yellow g7dt-mt-1">
{transform.warnings[0]}
</div>
)}
</div>
))}
</div>
)}
{/* 일반적인 경고 */}
{transformInfo.stats.commonWarnings.length > 0 && (
<div className="g7dt-mt-3">
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-1">자주 발생하는 경고</div>
<div className="g7dt-space-y-1">
{transformInfo.stats.commonWarnings.slice(0, 5).map((w, idx) => (
<div key={idx} className="g7dt-text-xs g7dt-text-yellow">
{w.warning} ({w.count}회)
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
);
};
export default DataSourcesTab;
@@ -0,0 +1,121 @@
/**
* 진단 탭 컴포넌트
*
* 증상을 선택하여 자동 진단을 실행합니다.
*/
import React, { useState } from 'react';
/**
* 진단 탭
*/
export const DiagnoseTab: React.FC = () => {
const [symptoms, setSymptoms] = useState<string[]>([]);
const [results, setResults] = useState<any[]>([]);
const [customSymptom, setCustomSymptom] = useState('');
const commonSymptoms = [
'이전 값이 전송됨',
'모든 행이 같은 값',
'상태가 업데이트 안됨',
'API 호출이 안됨',
'초기값이 없음',
'무한 로딩',
'Form 값이 저장 안됨',
'iteration 데이터 중복',
];
const toggleSymptom = (symptom: string) => {
setSymptoms(prev =>
prev.includes(symptom)
? prev.filter(s => s !== symptom)
: [...prev, symptom]
);
};
const addCustomSymptom = () => {
if (customSymptom && !symptoms.includes(customSymptom)) {
setSymptoms(prev => [...prev, customSymptom]);
setCustomSymptom('');
}
};
const runDiagnosis = async () => {
const { DiagnosticEngine } = await import('../../DiagnosticEngine');
const engine = new DiagnosticEngine();
const diagnoses = engine.analyze(symptoms);
setResults(diagnoses);
};
return (
<div className="g7dt-space-y-4">
{/* 증상 선택 */}
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">증상 선택</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-2">
{commonSymptoms.map(symptom => (
<button
key={symptom}
onClick={() => toggleSymptom(symptom)}
className={symptoms.includes(symptom) ? 'g7dt-symptom-btn g7dt-symptom-active' : 'g7dt-symptom-btn'}
>
{symptom}
</button>
))}
</div>
</div>
{/* 커스텀 증상 입력 */}
<div className="g7dt-flex g7dt-gap-2">
<input
type="text"
placeholder="직접 증상 입력..."
value={customSymptom}
onChange={e => setCustomSymptom(e.target.value)}
onKeyDown={e => e.key === 'Enter' && addCustomSymptom()}
className="g7dt-input g7dt-flex-1"
/>
<button
onClick={addCustomSymptom}
className="g7dt-btn-secondary"
>
추가
</button>
</div>
{/* 진단 버튼 */}
<button
onClick={runDiagnosis}
disabled={symptoms.length === 0}
className={symptoms.length === 0 ? 'g7dt-btn-primary g7dt-btn-disabled g7dt-w-full' : 'g7dt-btn-primary g7dt-w-full'}
>
진단 실행 ({symptoms.length}개 증상)
</button>
{/* 진단 결과 */}
{results.length > 0 && (
<div className="g7dt-space-y-3">
<h3 className="g7dt-text-sm g7dt-font-bold">진단 결과</h3>
{results.slice(0, 5).map((result, i) => (
<div key={i} className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<span className="g7dt-font-bold g7dt-text-yellow">{result.rule.name}</span>
<span className="g7dt-confidence-badge">
{(result.confidence * 100).toFixed(0)}%
</span>
</div>
<div className="g7dt-text-sm g7dt-text-lightgray">{result.rule.solution}</div>
{result.rule.codeExample && (
<pre className="g7dt-pre g7dt-mt-2">
{result.rule.codeExample}
</pre>
)}
</div>
))}
</div>
)}
</div>
);
};
export default DiagnoseTab;
@@ -0,0 +1,141 @@
/**
* 이벤트 탭 컴포넌트
*
* 컴포넌트 이벤트 구독/발생을 추적합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface EventsTabProps {
devTools: G7DevToolsCore;
}
/**
* 이벤트 탭
*/
export const EventsTab: React.FC<EventsTabProps> = ({ devTools }) => {
const [eventInfo, setEventInfo] = useState(devTools.getComponentEventInfo());
const [selectedEvent, setSelectedEvent] = useState<string | null>(null);
// 데이터 새로고침
const refreshData = useCallback(() => {
setEventInfo(devTools.getComponentEventInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
// 선택된 이벤트의 emit 이력 필터링
const filteredEmitHistory = selectedEvent
? eventInfo.emitHistory.filter(e => e.eventName === selectedEvent)
: eventInfo.emitHistory;
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-stats-grid-3">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value-lg g7dt-text-blue">
{eventInfo.subscriptions.length}
</div>
<div className="g7dt-stat-label">이벤트 타입</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value-lg g7dt-text-green">
{eventInfo.totalSubscribers}
</div>
<div className="g7dt-stat-label">총 구독자</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value-lg g7dt-text-purple">
{eventInfo.totalEmits}
</div>
<div className="g7dt-stat-label">총 발행</div>
</div>
</div>
{/* 구독된 이벤트 목록 */}
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">구독된 이벤트</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-2">
<button
onClick={() => setSelectedEvent(null)}
className={selectedEvent === null ? 'g7dt-filter-btn g7dt-filter-active' : 'g7dt-filter-btn'}
>
전체
</button>
{eventInfo.subscriptions.map(sub => (
<button
key={sub.eventName}
onClick={() => setSelectedEvent(sub.eventName)}
className={selectedEvent === sub.eventName ? 'g7dt-filter-btn g7dt-filter-active' : 'g7dt-filter-btn'}
>
{sub.eventName} ({sub.subscriberCount})
</button>
))}
</div>
</div>
{/* Emit 이력 */}
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">
발행 이력 {selectedEvent && `(${selectedEvent})`}
</h3>
<div className="g7dt-space-y-1 g7dt-event-list">
{filteredEmitHistory.length === 0 ? (
<div className="g7dt-empty-message g7dt-py-4">
이벤트 발행 이력이 없습니다
</div>
) : (
filteredEmitHistory.slice(-30).reverse().map(emit => (
<div
key={emit.id}
className={`g7dt-card g7dt-text-xs ${emit.hasError ? 'g7dt-card-error' : ''}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-font-mono g7dt-text-green">{emit.eventName}</span>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-gray">{emit.listenerCount} listeners</span>
{emit.hasError && (
<span className="g7dt-text-red g7dt-text-xxs">에러</span>
)}
</div>
</div>
{emit.data !== undefined && (
<details className="g7dt-details g7dt-mt-1">
<summary className="g7dt-summary">
데이터
</summary>
<pre className="g7dt-pre">
{JSON.stringify(emit.data, null, 2)}
</pre>
</details>
)}
{emit.hasError && emit.errorMessage && (
<div className="g7dt-error-inline">
{emit.errorMessage}
</div>
)}
</div>
))
)}
</div>
</div>
{/* 새로고침 버튼 */}
<button
onClick={refreshData}
className="g7dt-btn-secondary"
>
새로고침
</button>
</div>
);
};
export default EventsTab;
@@ -0,0 +1,390 @@
/**
* 표현식 탭 컴포넌트
*
* 현재 화면에서 평가된 모든 표현식을 추적하고 디버깅 정보를 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { ExpressionEvalInfo, ExpressionStats } from '../../types';
export interface ExpressionTabProps {
devTools: G7DevToolsCore;
}
/**
* 표현식 탭
*/
export const ExpressionTab: React.FC<ExpressionTabProps> = ({ devTools }) => {
const [expressions, setExpressions] = useState<ExpressionEvalInfo[]>([]);
const [stats, setStats] = useState<ExpressionStats>({
totalEvaluations: 0,
uniqueExpressions: 0,
warningCount: 0,
cacheHitRate: 0,
averageDuration: 0,
byType: {},
byWarning: {},
});
const [filter, setFilter] = useState<string>('');
const [showWarningsOnly, setShowWarningsOnly] = useState(false);
const [selectedExpression, setSelectedExpression] = useState<ExpressionEvalInfo | null>(null);
// 데이터 새로고침
const refreshData = useCallback(() => {
const info = devTools.getExpressionInfo();
setExpressions(info.expressions);
setStats(info.stats);
}, [devTools]);
// 초기 로드 및 구독
useEffect(() => {
refreshData();
// 표현식 변경 구독
const unsubscribe = devTools.watchExpressions(() => {
refreshData();
});
// 주기적 갱신 (2초)
const intervalId = setInterval(refreshData, 2000);
return () => {
unsubscribe();
clearInterval(intervalId);
};
}, [devTools, refreshData]);
// 필터링된 표현식
const filteredExpressions = expressions.filter(expr => {
if (showWarningsOnly && !expr.warning) return false;
if (filter) {
const searchLower = filter.toLowerCase();
return (
expr.expression.toLowerCase().includes(searchLower) ||
expr.componentName?.toLowerCase().includes(searchLower) ||
expr.propName?.toLowerCase().includes(searchLower) ||
expr.resultType.toLowerCase().includes(searchLower)
);
}
return true;
});
// 결과 타입에 따른 색상
const getTypeColor = (type: string) => {
switch (type) {
case 'string':
return 'g7dt-text-green';
case 'number':
return 'g7dt-text-blue';
case 'boolean':
return 'g7dt-text-purple';
case 'array':
return 'g7dt-text-cyan';
case 'object':
return 'g7dt-text-yellow';
case 'undefined':
case 'null':
return 'g7dt-text-red';
default:
return 'g7dt-text-gray';
}
};
// 경고 타입에 따른 메시지
const getWarningLabel = (type: string) => {
switch (type) {
case 'undefined-result':
return 'undefined 결과';
case 'null-result':
return 'null 결과';
case 'array-to-string':
return '배열→문자열';
case 'object-to-string':
return '객체→문자열';
case 'missing-optional-chain':
return '?. 누락 의심';
case 'wrong-iteration-var':
return '잘못된 반복 변수';
case 'type-mismatch':
return '타입 불일치';
case 'cache-stale':
return '캐시 오래됨';
case 'slow-evaluation':
return '느린 평가';
default:
return type;
}
};
// 결과값 포맷팅
const formatResult = (result: any, type: string): string => {
if (type === 'undefined') return 'undefined';
if (type === 'null') return 'null';
if (type === 'string') return `"${String(result).substring(0, 50)}${String(result).length > 50 ? '...' : ''}"`;
if (type === 'array') return `Array(${Array.isArray(result) ? result.length : '?'})`;
if (type === 'object') return 'Object{...}';
return String(result);
};
// 표현식 초기화
const handleClear = () => {
devTools.clearExpressions();
setExpressions([]);
setSelectedExpression(null);
};
return (
<div className="g7dt-space-y-4">
{/* 통계 요약 */}
<div className="g7dt-stats-grid-5">
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-lg g7dt-text-blue">{stats.totalEvaluations}</div>
<div className="g7dt-stat-label-xs">총 평가</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-lg g7dt-text-green">{stats.uniqueExpressions}</div>
<div className="g7dt-stat-label-xs">고유 표현식</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-lg g7dt-text-yellow">{stats.warningCount}</div>
<div className="g7dt-stat-label-xs">경고</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-lg g7dt-text-purple">{(stats.cacheHitRate * 100).toFixed(0)}%</div>
<div className="g7dt-stat-label-xs">캐시 히트</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-lg g7dt-text-cyan">{stats.averageDuration.toFixed(1)}ms</div>
<div className="g7dt-stat-label-xs">평균 시간</div>
</div>
</div>
{/* 필터 및 컨트롤 */}
<div className="g7dt-flex g7dt-gap-2 g7dt-items-center">
<input
type="text"
placeholder="표현식, 컴포넌트, prop 검색..."
value={filter}
onChange={e => setFilter(e.target.value)}
className="g7dt-input g7dt-flex-1"
/>
<label className="g7dt-checkbox-label">
<input
type="checkbox"
checked={showWarningsOnly}
onChange={e => setShowWarningsOnly(e.target.checked)}
className="g7dt-checkbox"
/>
경고만
</label>
<button
onClick={handleClear}
className="g7dt-btn-danger-sm"
>
초기화
</button>
</div>
{/* 타입별 분포 */}
{Object.keys(stats.byType).length > 0 && (
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1">
{Object.entries(stats.byType).map(([type, count]) => (
<span
key={type}
className={`g7dt-type-tag ${getTypeColor(type)}`}
>
{type}: {count}
</span>
))}
</div>
)}
{/* 표현식 목록 */}
<div className="g7dt-space-y-1 g7dt-expr-list">
{filteredExpressions.length === 0 ? (
<div className="g7dt-empty-message g7dt-py-4">
{filter || showWarningsOnly ? '조건에 맞는 표현식이 없습니다' : '추적된 표현식이 없습니다'}
</div>
) : (
filteredExpressions.slice(-50).reverse().map(expr => (
<div
key={expr.id}
onClick={() => setSelectedExpression(expr)}
className={`g7dt-expr-item ${
selectedExpression?.id === expr.id
? 'g7dt-expr-selected'
: expr.warning
? 'g7dt-expr-warning'
: ''
}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-start g7dt-gap-2">
<div className="g7dt-flex-1 g7dt-min-w-0">
<div className="g7dt-font-mono g7dt-text-white g7dt-truncate" title={expr.expression}>
{expr.expression}
</div>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-mt-1 g7dt-text-xxs">
{expr.componentName && (
<span className="g7dt-text-gray">
{expr.componentName}
{expr.propName && `.${expr.propName}`}
</span>
)}
<span className={getTypeColor(expr.resultType)}>
{formatResult(expr.result, expr.resultType)}
</span>
</div>
</div>
<div className="g7dt-flex g7dt-flex-col g7dt-items-end g7dt-gap-1">
<div className="g7dt-flex g7dt-items-center g7dt-gap-1">
{expr.fromCache && (
<span className="g7dt-mini-badge g7dt-badge-success">
캐시
</span>
)}
{expr.warning && (
<span className="g7dt-mini-badge g7dt-badge-warning">
{getWarningLabel(expr.warning.type)}
</span>
)}
</div>
{expr.duration !== undefined && (
<span className="g7dt-text-xxs g7dt-text-gray">
{expr.duration.toFixed(2)}ms
</span>
)}
</div>
</div>
</div>
))
)}
</div>
{/* 선택된 표현식 상세 정보 */}
{selectedExpression && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">표현식 상세</h3>
<button
onClick={() => setSelectedExpression(null)}
className="g7dt-btn-close"
>
✕
</button>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
{/* 표현식 */}
<div>
<span className="g7dt-text-gray">표현식:</span>
<code className="g7dt-code g7dt-text-green">
{selectedExpression.expression}
</code>
</div>
{/* 결과 */}
<div>
<span className="g7dt-text-gray">결과:</span>
<span className={`g7dt-ml-2 ${getTypeColor(selectedExpression.resultType)}`}>
{JSON.stringify(selectedExpression.result, null, 2)?.substring(0, 200)}
</span>
<span className="g7dt-ml-2 g7dt-text-darkgray">({selectedExpression.resultType})</span>
</div>
{/* 컴포넌트 정보 */}
{selectedExpression.componentName && (
<div>
<span className="g7dt-text-gray">컴포넌트:</span>
<span className="g7dt-ml-2 g7dt-text-blue">{selectedExpression.componentName}</span>
{selectedExpression.propName && (
<span className="g7dt-text-gray">.{selectedExpression.propName}</span>
)}
</div>
)}
{/* 메서드 */}
{selectedExpression.method && (
<div>
<span className="g7dt-text-gray">메서드:</span>
<span className="g7dt-ml-2 g7dt-text-purple">{selectedExpression.method}</span>
</div>
)}
{/* 캐시 상태 */}
<div>
<span className="g7dt-text-gray">캐시:</span>
<span className={`g7dt-ml-2 ${selectedExpression.fromCache ? 'g7dt-text-green' : 'g7dt-text-gray'}`}>
{selectedExpression.fromCache ? '캐시에서 로드' : '새로 평가'}
{selectedExpression.skipCache && ' (skipCache)'}
</span>
</div>
{/* 소요 시간 */}
{selectedExpression.duration !== undefined && (
<div>
<span className="g7dt-text-gray">소요 시간:</span>
<span className={`g7dt-ml-2 ${selectedExpression.duration > 10 ? 'g7dt-text-red' : 'g7dt-text-lightgray'}`}>
{selectedExpression.duration.toFixed(3)}ms
</span>
</div>
)}
{/* 경고 */}
{selectedExpression.warning && (
<div className="g7dt-warning-box-light">
<div className="g7dt-text-yellow g7dt-font-bold">
⚠️ {getWarningLabel(selectedExpression.warning.type)}
</div>
<div className="g7dt-text-lightgray g7dt-mt-1">{selectedExpression.warning.message}</div>
{selectedExpression.warning.suggestion && (
<div className="g7dt-text-gray g7dt-mt-1 g7dt-text-xxs">
💡 {selectedExpression.warning.suggestion}
</div>
)}
</div>
)}
{/* 평가 단계 */}
{selectedExpression.steps && selectedExpression.steps.length > 0 && (
<details className="g7dt-details">
<summary className="g7dt-summary">
평가 단계 ({selectedExpression.steps.length})
</summary>
<div className="g7dt-mt-1 g7dt-space-y-1 g7dt-pl-2 g7dt-border-l">
{selectedExpression.steps.map((step, i) => (
<div key={i} className="g7dt-text-xxs">
<span className="g7dt-text-purple">{step.step}</span>
{step.path && <span className="g7dt-text-gray g7dt-ml-1">{step.path}</span>}
{step.fromCache && <span className="g7dt-text-green g7dt-ml-1">(cached)</span>}
{step.error && <span className="g7dt-text-red g7dt-ml-1">{step.error}</span>}
</div>
))}
</div>
</details>
)}
</div>
</div>
)}
{/* 경고 요약 */}
{Object.keys(stats.byWarning).length > 0 && (
<div className="g7dt-warning-box-light">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2">경고 요약</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-2">
{Object.entries(stats.byWarning).map(([type, count]) => (
<span
key={type}
className="g7dt-warning-tag"
>
{getWarningLabel(type)}: {count}
</span>
))}
</div>
</div>
)}
</div>
);
};
export default ExpressionTab;
@@ -0,0 +1,218 @@
/**
* Form 탭 컴포넌트
*
* 추적된 Form 정보와 Input 바인딩을 표시합니다.
* Auto-Binding Check 기능 포함 (Phase 6).
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { FormBindingValidationTrackingInfo, FormBindingIssueType } from '../../types';
export interface FormTabProps {
devTools: G7DevToolsCore;
}
/**
* Form 탭
*/
export const FormTab: React.FC<FormTabProps> = ({ devTools }) => {
const formInfo = devTools.getFormInfo();
const [showBindingCheck, setShowBindingCheck] = useState(false);
const [validationInfo, setValidationInfo] = useState<FormBindingValidationTrackingInfo | null>(null);
// 바인딩 검증 데이터 새로고침
const refreshValidationData = useCallback(() => {
setValidationInfo(devTools.getFormBindingValidationTrackingInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
if (showBindingCheck) {
refreshValidationData();
const intervalId = setInterval(refreshValidationData, 2000);
return () => clearInterval(intervalId);
}
}, [showBindingCheck, refreshValidationData]);
// 이슈 타입 아이콘
const getIssueIcon = (type: FormBindingIssueType) => {
switch (type) {
case 'missing-datakey': return '🔑';
case 'missing-input-name': return '📝';
case 'context-not-propagated': return '🔗';
case 'sortable-context-break': return '📊';
case 'modal-context-isolation': return '🪟';
case 'duplicate-input-name': return '👯';
case 'value-type-mismatch': return '⚠️';
case 'binding-path-invalid': return '❌';
default: return '❓';
}
};
// 심각도 색상
const getSeverityColor = (severity: string) => {
switch (severity) {
case 'error': return 'g7dt-text-red';
case 'warning': return 'g7dt-text-yellow';
case 'info': return 'g7dt-text-blue';
default: return 'g7dt-text-gray';
}
};
return (
<div className="g7dt-space-y-4">
{formInfo.length === 0 ? (
<div className="g7dt-empty-message g7dt-py-8">
추적된 Form이 없습니다
</div>
) : (
formInfo.map(form => (
<div key={form.id} className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<span className="g7dt-font-bold g7dt-text-blue">
{form.dataKey || '(no dataKey)'}
</span>
{!form.dataKey && (
<span className="g7dt-text-red g7dt-text-xs">dataKey 필요</span>
)}
</div>
<div className="g7dt-space-y-1 g7dt-mb-2">
{form.inputs.map((input, i) => (
<div key={i} className="g7dt-text-xs g7dt-flex g7dt-justify-between">
<span>
{input.name || (
<span className="g7dt-text-red">name 없음</span>
)}
</span>
<span className="g7dt-text-gray">{input.type}</span>
</div>
))}
</div>
<details className="g7dt-details">
<summary className="g7dt-summary">
현재 값 보기
</summary>
<pre className="g7dt-pre">
{JSON.stringify(form, null, 2)}
</pre>
</details>
</div>
))
)}
{/* Auto-Binding Check 토글 */}
<div className="g7dt-flex g7dt-justify-end">
<button
onClick={() => setShowBindingCheck(!showBindingCheck)}
className={`g7dt-tab-button ${showBindingCheck ? 'g7dt-tab-active' : ''}`}
>
🔍 Auto-Binding Check
</button>
</div>
{/* Auto-Binding Check 섹션 */}
{showBindingCheck && validationInfo && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
Form 바인딩 검증 결과
</h3>
{/* 통계 */}
<div className="g7dt-stats-grid g7dt-mb-3">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-blue">
{validationInfo.stats.totalFormsValidated}
</div>
<div className="g7dt-stat-label">검증된 Form</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-green">
{validationInfo.stats.validForms}
</div>
<div className="g7dt-stat-label">유효</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-red">
{validationInfo.stats.formsWithIssues}
</div>
<div className="g7dt-stat-label">문제 있음</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-yellow">
{validationInfo.stats.totalIssues}
</div>
<div className="g7dt-stat-label">총 이슈</div>
</div>
</div>
{/* 자주 발생하는 이슈 */}
{validationInfo.stats.topIssues.length > 0 && (
<div className="g7dt-mb-3">
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">자주 발생하는 이슈</div>
<div className="g7dt-space-y-1">
{validationInfo.stats.topIssues.slice(0, 3).map((issue, idx) => (
<div key={idx} className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs">
<span>{getIssueIcon(issue.type)}</span>
<span className="g7dt-text-white">{issue.description}</span>
<span className="g7dt-text-muted">({issue.count})</span>
</div>
))}
</div>
</div>
)}
{/* 이슈 목록 */}
{validationInfo.issues.length === 0 ? (
<div className="g7dt-empty-state">바인딩 이슈가 없습니다 ✅</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{validationInfo.issues.slice().reverse().slice(0, 30).map((issue) => (
<div
key={issue.id}
className={`g7dt-list-item ${
issue.severity === 'error' ? 'g7dt-border-red' :
issue.severity === 'warning' ? 'g7dt-border-yellow' : ''
}`}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getIssueIcon(issue.type)}</span>
<span className={`g7dt-text-xs g7dt-font-bold ${getSeverityColor(issue.severity)}`}>
{issue.type}
</span>
{issue.formDataKey && (
<span className="g7dt-text-xs g7dt-text-blue g7dt-font-mono">
{issue.formDataKey}
</span>
)}
</div>
<div className="g7dt-text-xs g7dt-text-white g7dt-mt-1">
{issue.description}
</div>
<div className="g7dt-text-xs g7dt-text-green g7dt-mt-1">
💡 {issue.suggestion}
</div>
{issue.contextInfo && (
<div className="g7dt-flex g7dt-gap-2 g7dt-mt-1">
{issue.contextInfo.isInsideModal && (
<span className="g7dt-badge g7dt-text-xs">🪟 modal</span>
)}
{issue.contextInfo.isInsideSortable && (
<span className="g7dt-badge g7dt-text-xs">📊 sortable</span>
)}
<span className="g7dt-text-xs g7dt-text-muted">
depth: {issue.contextInfo.depth}
</span>
</div>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
);
};
export default FormTab;
@@ -0,0 +1,123 @@
/**
* 핸들러 탭 컴포넌트
*
* 등록된 액션 핸들러 목록을 표시합니다.
*/
import React, { useState } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface HandlersTabProps {
devTools: G7DevToolsCore;
}
/**
* 핸들러 탭
*/
export const HandlersTab: React.FC<HandlersTabProps> = ({ devTools }) => {
const handlers = devTools.getHandlers();
const [filter, setFilter] = useState<string>('');
const [categoryFilter, setCategoryFilter] = useState<string>('all');
// 핸들러 분류
const categorizedHandlers = {
'built-in': handlers.filter(h => h.category === 'built-in'),
'custom': handlers.filter(h => h.category === 'custom'),
'module': handlers.filter(h => h.category === 'module'),
'plugin': handlers.filter(h => h.category === 'plugin'),
};
// 카테고리 카운트
const categoryCounts = {
all: handlers.length,
'built-in': categorizedHandlers['built-in'].length,
custom: categorizedHandlers['custom'].length,
module: categorizedHandlers['module'].length,
plugin: categorizedHandlers['plugin'].length,
};
// 필터링된 핸들러
const filteredHandlers = handlers.filter(h => {
if (categoryFilter !== 'all' && h.category !== categoryFilter) return false;
if (filter) {
return h.name.toLowerCase().includes(filter.toLowerCase()) ||
h.description?.toLowerCase().includes(filter.toLowerCase());
}
return true;
});
return (
<div className="g7dt-space-y-4">
{/* 카테고리 필터 */}
<div className="g7dt-flex g7dt-gap-2">
{(['all', 'built-in', 'custom', 'module', 'plugin'] as const).map(cat => (
<button
key={cat}
onClick={() => setCategoryFilter(cat)}
className={categoryFilter === cat ? 'g7dt-filter-btn g7dt-filter-active' : 'g7dt-filter-btn'}
>
{cat === 'all' ? '전체' : cat} ({categoryCounts[cat]})
</button>
))}
</div>
{/* 검색 */}
<input
type="text"
placeholder="핸들러 이름 검색..."
value={filter}
onChange={e => setFilter(e.target.value)}
className="g7dt-input g7dt-w-full"
/>
{/* 핸들러 목록 */}
<div className="g7dt-space-y-1 g7dt-handler-list">
{filteredHandlers.length === 0 ? (
<div className="g7dt-empty-message g7dt-py-4">
등록된 핸들러가 없습니다
</div>
) : (
filteredHandlers.map(handler => (
<div
key={handler.name}
className="g7dt-card"
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-font-mono g7dt-text-blue">{handler.name}</span>
<span
className={
handler.category === 'built-in'
? 'g7dt-mini-badge g7dt-badge-success'
: handler.category === 'module'
? 'g7dt-mini-badge g7dt-badge-purple'
: handler.category === 'plugin'
? 'g7dt-mini-badge g7dt-badge-info'
: 'g7dt-mini-badge g7dt-badge-warning'
}
>
{handler.category}
</span>
</div>
{handler.description && (
<div className="g7dt-text-xs g7dt-text-gray g7dt-mt-1">
{handler.description}
</div>
)}
</div>
))
)}
</div>
{/* 통계 */}
<div className="g7dt-text-xs g7dt-text-gray">
총 {handlers.length}개 핸들러 |
빌트인 {categoryCounts['built-in']} |
커스텀 {categoryCounts.custom} |
모듈 {categoryCounts.module} |
플러그인 {categoryCounts.plugin}
</div>
</div>
);
};
export default HandlersTab;
@@ -0,0 +1,313 @@
/**
* 레이아웃 탭 컴포넌트
*
* 현재 렌더링 중인 레이아웃 JSON을 조회합니다.
* 레이아웃 캐시 문제를 진단하거나 실제 렌더링되는 구조를 확인할 때 사용합니다.
*/
import React, { useState, useEffect } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface LayoutTabProps {
devTools: G7DevToolsCore;
}
/**
* 레이아웃 탭
*/
export const LayoutTab: React.FC<LayoutTabProps> = ({ devTools }) => {
const [layoutInfo, setLayoutInfo] = useState(devTools.getLayoutDebugInfo());
const [showFull, setShowFull] = useState(false);
const [selectedSection, setSelectedSection] = useState<string | null>(null);
const [expandedHistory, setExpandedHistory] = useState(false);
const [permissionNames, setPermissionNames] = useState<Record<string, string>>({});
useEffect(() => {
const interval = setInterval(() => {
setLayoutInfo(devTools.getLayoutDebugInfo());
}, 1000);
return () => clearInterval(interval);
}, [devTools]);
// 권한 목록 조회 (컴포넌트 마운트 시)
useEffect(() => {
const fetchPermissions = async () => {
try {
const response = await fetch('/api/admin/permissions', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
'Accept': 'application/json',
},
});
if (response.ok) {
const data = await response.json();
const nameMap: Record<string, string> = {};
// 재귀적으로 권한 트리 순회
const extractNames = (perms: any[]) => {
perms.forEach(p => {
nameMap[p.identifier] = p.name;
if (p.children?.length) extractNames(p.children);
});
};
Object.values(data.data?.permissions || {}).forEach((group: any) => {
if (group.permissions) extractNames(group.permissions);
});
setPermissionNames(nameMap);
}
} catch (e) {
console.warn('[G7DevTools] 권한 목록 조회 실패:', e);
}
};
fetchPermissions();
}, []);
const current = layoutInfo.current;
const layoutJson = current?.layoutJson;
const history = layoutInfo.history;
const stats = layoutInfo.stats;
// 섹션 목록
const sections = layoutJson ? [
{ key: 'components', label: '컴포넌트', count: Array.isArray(layoutJson.components) ? layoutJson.components.length : 0 },
{ key: 'data_sources', label: '데이터소스', count: Array.isArray(layoutJson.data_sources) ? layoutJson.data_sources.length : 0 },
{ key: 'computed', label: 'Computed', count: layoutJson.computed ? Object.keys(layoutJson.computed).length : 0 },
{ key: 'defines', label: 'Defines', count: layoutJson.defines ? Object.keys(layoutJson.defines).length : 0 },
{ key: 'slots', label: 'Slots', count: layoutJson.slots ? Object.keys(layoutJson.slots).length : 0 },
{ key: 'modals', label: 'Modals', count: layoutJson.modals ? Object.keys(layoutJson.modals).length : 0 },
{ key: 'init_actions', label: '초기화 액션', count: Array.isArray(layoutJson.init_actions) ? layoutJson.init_actions.length : 0 },
{ key: 'scripts', label: '스크립트', count: Array.isArray(layoutJson.scripts) ? layoutJson.scripts.length : 0 },
{ key: 'meta', label: '메타데이터', count: layoutJson.meta ? Object.keys(layoutJson.meta).length : 0 },
{ key: 'errorHandling', label: '에러핸들링', count: layoutJson.errorHandling ? Object.keys(layoutJson.errorHandling).length : 0 },
{ key: 'permissions', label: '권한', count: Array.isArray(layoutJson.permissions) ? layoutJson.permissions.length : 0 },
] : [];
const copyToClipboard = (data: any) => {
navigator.clipboard.writeText(JSON.stringify(data, null, 2));
};
if (!current) {
return (
<div className="g7dt-space-y-4">
<div className="g7dt-empty-state">
현재 로드된 레이아웃이 없습니다.
<br />
페이지를 새로고침하거나 라우트를 변경해보세요.
</div>
</div>
);
}
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">📊 로드 통계</h3>
<div className="g7dt-grid-3">
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">총 로드:</span>
<span className="g7dt-text-blue">{stats.totalLoads}</span>
</div>
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">캐시 히트:</span>
<span className="g7dt-text-green">{stats.cacheHits}</span>
</div>
<div className="g7dt-stat-item">
<span className="g7dt-text-muted">API 로드:</span>
<span className="g7dt-text-yellow">{stats.apiLoads}</span>
</div>
</div>
</div>
{/* 현재 레이아웃 정보 */}
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">📋 현재 레이아웃</h3>
<div className="g7dt-flex g7dt-gap-2">
<button
onClick={() => copyToClipboard(layoutJson)}
className="g7dt-btn-small"
title="전체 JSON 복사"
>
📋 복사
</button>
<button
onClick={() => setShowFull(!showFull)}
className="g7dt-btn-small"
>
{showFull ? '요약 보기' : '전체 보기'}
</button>
</div>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
<div className="g7dt-flex g7dt-gap-4">
<div>
<span className="g7dt-text-muted">경로:</span>
<span className="g7dt-ml-1 g7dt-text-white g7dt-font-mono">{current.layoutPath}</span>
</div>
<div>
<span className="g7dt-text-muted">템플릿:</span>
<span className="g7dt-ml-1 g7dt-text-blue">{current.templateId}</span>
</div>
</div>
<div className="g7dt-flex g7dt-gap-4">
<div>
<span className="g7dt-text-muted">버전:</span>
<span className="g7dt-ml-1 g7dt-text-white">{current.version || '-'}</span>
</div>
<div>
<span className="g7dt-text-muted">소스:</span>
<span className={`g7dt-ml-1 ${current.source === 'cache' ? 'g7dt-text-green' : 'g7dt-text-yellow'}`}>
{current.source === 'cache' ? '💾 캐시' : '🌐 API'}
</span>
</div>
<div>
<span className="g7dt-text-muted">로드 시간:</span>
<span className="g7dt-ml-1 g7dt-text-white">
{current.loadedAt ? new Date(current.loadedAt).toLocaleTimeString() : '-'}
</span>
</div>
</div>
{/* 권한 표시 */}
<div className="g7dt-flex g7dt-gap-4 g7dt-mt-2">
<div>
<span className="g7dt-text-muted">권한:</span>
{layoutJson.permissions && layoutJson.permissions.length > 0 ? (
<span className="g7dt-ml-1 g7dt-text-yellow">
🔒 {layoutJson.permissions.map((permId: string) =>
permissionNames[permId] || permId
).join(', ')}
</span>
) : layoutJson.permissions && layoutJson.permissions.length === 0 ? (
<span className="g7dt-ml-1 g7dt-text-green">🌐 공개</span>
) : (
<span className="g7dt-ml-1 g7dt-text-muted">미정의 (부모 상속)</span>
)}
</div>
</div>
</div>
</div>
{/* 섹션 목록 */}
{!showFull && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">🏗️ 레이아웃 구조</h3>
<div className="g7dt-grid-2">
{sections.map(section => (
<button
key={section.key}
onClick={() => setSelectedSection(selectedSection === section.key ? null : section.key)}
className={`g7dt-section-btn ${selectedSection === section.key ? 'g7dt-selected' : ''}`}
>
<span>{section.label}</span>
<span className="g7dt-text-blue">{section.count}개</span>
</button>
))}
</div>
</div>
)}
{/* 선택된 섹션 또는 전체 JSON */}
{(showFull || selectedSection) && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">
{showFull ? '📄 전체 레이아웃 JSON' : `📎 ${selectedSection} 섹션`}
</h3>
<button
onClick={() => {
if (showFull) {
copyToClipboard(layoutJson);
} else if (selectedSection && layoutJson) {
copyToClipboard((layoutJson as any)[selectedSection]);
}
}}
className="g7dt-btn-small"
>
복사
</button>
</div>
{/* 권한 섹션은 테이블로 표시 */}
{selectedSection === 'permissions' && !showFull ? (
<div className="g7dt-text-xs">
{layoutJson.permissions && layoutJson.permissions.length > 0 ? (
<table className="g7dt-table g7dt-w-full">
<thead>
<tr className="g7dt-border-b g7dt-border-gray-700">
<th className="g7dt-text-left g7dt-p-2 g7dt-text-muted">권한 ID</th>
<th className="g7dt-text-left g7dt-p-2 g7dt-text-muted">명칭</th>
</tr>
</thead>
<tbody>
{layoutJson.permissions.map((permId: string) => (
<tr key={permId} className="g7dt-border-b g7dt-border-gray-800">
<td className="g7dt-p-2 g7dt-font-mono g7dt-text-blue">{permId}</td>
<td className="g7dt-p-2 g7dt-text-white">
{permissionNames[permId] || <span className="g7dt-text-muted">-</span>}
</td>
</tr>
))}
</tbody>
</table>
) : layoutJson.permissions && layoutJson.permissions.length === 0 ? (
<p className="g7dt-text-muted g7dt-p-2">🌐 공개 레이아웃 (permissions: [])</p>
) : (
<p className="g7dt-text-muted g7dt-p-2">권한 미정의 (부모 레이아웃 상속)</p>
)}
</div>
) : (
<pre className="g7dt-pre g7dt-text-green g7dt-max-h-96 g7dt-overflow-auto">
{showFull
? JSON.stringify(layoutJson, null, 2)
: JSON.stringify(selectedSection && layoutJson ? (layoutJson as any)[selectedSection] : null, null, 2)
}
</pre>
)}
</div>
)}
{/* 로드 이력 */}
{history.length > 0 && (
<div className="g7dt-card">
<div
className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-cursor-pointer"
onClick={() => setExpandedHistory(!expandedHistory)}
>
<h3 className="g7dt-text-sm g7dt-font-bold">📜 로드 이력 ({history.length})</h3>
<span className="g7dt-text-muted">{expandedHistory ? '▼' : '▶'}</span>
</div>
{expandedHistory && (
<div className="g7dt-mt-2 g7dt-space-y-1">
{history.slice(-20).reverse().map(entry => (
<div key={entry.id} className="g7dt-history-item">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-font-mono g7dt-text-xs">{entry.layoutPath}</span>
<span className={`g7dt-text-xs ${entry.source === 'cache' ? 'g7dt-text-green' : 'g7dt-text-yellow'}`}>
{entry.source === 'cache' ? '💾' : '🌐'}
</span>
</div>
<div className="g7dt-text-xs g7dt-text-muted">
{entry.templateId} · {entry.loadedAt ? new Date(entry.loadedAt).toLocaleTimeString() : '-'}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* 안내 메시지 */}
<div className="g7dt-card g7dt-text-xs g7dt-text-muted">
💡 레이아웃 캐시 문제가 의심되면:
<ul className="g7dt-ml-4 g7dt-list-disc">
<li>"소스" 항목이 💾 캐시인지 🌐 API인지 확인</li>
<li>캐시에서 로드된 경우, JSON 내용이 최신인지 확인</li>
<li>문제가 있으면 <code className="g7dt-code">php artisan template:refresh-layout</code> 실행</li>
</ul>
</div>
</div>
);
};
export default LayoutTab;
@@ -0,0 +1,61 @@
/**
* 라이프사이클 탭 컴포넌트
*
* 마운트된 컴포넌트와 정리되지 않은 리스너를 표시합니다.
*/
import React from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface LifecycleTabProps {
devTools: G7DevToolsCore;
}
/**
* 라이프사이클 탭
*/
export const LifecycleTab: React.FC<LifecycleTabProps> = ({ devTools }) => {
const lifecycleInfo = devTools.getLifecycleInfo();
return (
<div className="g7dt-space-y-4">
{/* 마운트된 컴포넌트 */}
<div className="g7dt-section">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-2 g7dt-flex-shrink-0">
마운트된 컴포넌트 ({lifecycleInfo.mountedComponents.length})
</h3>
<div className="g7dt-scroll-list">
{lifecycleInfo.mountedComponents.length === 0 ? (
<div className="g7dt-empty-message">추적된 컴포넌트 없음</div>
) : (
lifecycleInfo.mountedComponents.map(comp => (
<div key={comp.id} className="g7dt-list-item g7dt-text-xs">
<span className="g7dt-text-lightgray">{comp.name}</span>
<span className="g7dt-text-gray">{comp.id}</span>
</div>
))
)}
</div>
</div>
{/* 정리되지 않은 리스너 */}
{lifecycleInfo.orphanedListeners.length > 0 && (
<div className="g7dt-section">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2 g7dt-flex-shrink-0">
정리되지 않은 리스너 ({lifecycleInfo.orphanedListeners.length})
</h3>
<div className="g7dt-scroll-list">
{lifecycleInfo.orphanedListeners.map((listener, i) => (
<div key={i} className="g7dt-warning-card g7dt-text-xs">
<span className="g7dt-text-lightgray">{listener.type}</span>
<span className="g7dt-text-gray g7dt-ml-2">on {listener.target}</span>
</div>
))}
</div>
</div>
)}
</div>
);
};
export default LifecycleTab;
@@ -0,0 +1,268 @@
/**
* 로그 조회 탭 컴포넌트
*
* Logger로 쌓인 로그 이력을 조회합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { LogEntry, LogStats, LogLevel } from '../../types';
export interface LogsTabProps {
devTools: G7DevToolsCore;
}
/**
* 로그 조회 탭
*/
export const LogsTab: React.FC<LogsTabProps> = ({ devTools }) => {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [stats, setStats] = useState<LogStats | null>(null);
const [selectedLog, setSelectedLog] = useState<string | null>(null);
const [levelFilter, setLevelFilter] = useState<string>('all');
const [prefixFilter, setPrefixFilter] = useState<string>('');
const [searchFilter, setSearchFilter] = useState<string>('');
// 데이터 새로고침
const refreshData = useCallback(() => {
const logInfo = devTools.getLogInfo();
setLogs(logInfo.entries);
setStats(logInfo.stats);
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 1000);
return () => clearInterval(intervalId);
}, [refreshData]);
// 필터링된 로그
const filteredLogs = logs.filter(log => {
if (levelFilter !== 'all' && log.level !== levelFilter) return false;
if (prefixFilter && !log.prefix.toLowerCase().includes(prefixFilter.toLowerCase())) return false;
if (searchFilter && !log.message.toLowerCase().includes(searchFilter.toLowerCase())) return false;
return true;
});
// 선택된 로그
const selectedLogData = selectedLog
? logs.find(l => l.id === selectedLog)
: null;
// 로그 초기화
const clearLogs = () => {
devTools.clearLogs();
refreshData();
setSelectedLog(null);
};
// 레벨별 색상
const getLevelColor = (level: LogLevel): string => {
switch (level) {
case 'error': return 'g7dt-text-red';
case 'warn': return 'g7dt-text-yellow';
case 'info': return 'g7dt-text-blue';
case 'debug': return 'g7dt-text-muted';
default: return 'g7dt-text-white';
}
};
const getLevelBgColor = (level: LogLevel): string => {
switch (level) {
case 'error': return 'g7dt-log-error';
case 'warn': return 'g7dt-log-warn';
case 'info': return 'g7dt-log-info';
case 'debug': return 'g7dt-log-debug';
default: return 'g7dt-log-default';
}
};
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
{stats && (
<div className="g7dt-stats-grid-6">
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-white">{stats.totalLogs}</div>
<div className="g7dt-stat-label">전체</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-red">{stats.byLevel.error}</div>
<div className="g7dt-stat-label">에러</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-yellow">{stats.byLevel.warn}</div>
<div className="g7dt-stat-label">경고</div>
</div>
<div className="g7dt-stat-card-sm">
<div className="g7dt-stat-value-sm g7dt-text-blue">{stats.byLevel.info}</div>
<div className="g7dt-stat-label">정보</div>
</div>
<div className="g7dt-stat-card-sm">
<div className={`g7dt-stat-value-sm ${stats.recentErrors > 0 ? 'g7dt-text-red' : 'g7dt-text-green'}`}>
{stats.recentErrors}
</div>
<div className="g7dt-stat-label">최근 에러</div>
</div>
<div className="g7dt-stat-card-sm">
<div className={`g7dt-stat-value-sm ${stats.recentWarnings > 0 ? 'g7dt-text-yellow' : 'g7dt-text-green'}`}>
{stats.recentWarnings}
</div>
<div className="g7dt-stat-label">최근 경고</div>
</div>
</div>
)}
{/* 필터 */}
<div className="g7dt-flex g7dt-gap-2 g7dt-flex-wrap">
<select
value={levelFilter}
onChange={e => setLevelFilter(e.target.value)}
className="g7dt-select"
>
<option value="all">모든 레벨</option>
<option value="error">에러</option>
<option value="warn">경고</option>
<option value="info">정보</option>
<option value="log">로그</option>
<option value="debug">디버그</option>
</select>
<input
type="text"
placeholder="prefix 필터"
value={prefixFilter}
onChange={e => setPrefixFilter(e.target.value)}
className="g7dt-input g7dt-w-32"
/>
<input
type="text"
placeholder="메시지 검색"
value={searchFilter}
onChange={e => setSearchFilter(e.target.value)}
className="g7dt-input g7dt-flex-1"
/>
<button
onClick={refreshData}
className="g7dt-btn-secondary"
>
새로고침
</button>
<button
onClick={clearLogs}
className="g7dt-btn-danger"
>
초기화
</button>
</div>
{/* 로그 목록 */}
<div className="g7dt-scroll-list-lg">
{filteredLogs.length === 0 ? (
<div className="g7dt-empty-state">
{logs.length === 0 ? '로그가 없습니다' : '필터에 맞는 로그가 없습니다'}
</div>
) : (
filteredLogs.slice(-50).reverse().map(log => {
const time = new Date(log.timestamp).toLocaleTimeString();
return (
<div
key={log.id}
onClick={() => setSelectedLog(log.id)}
className={`g7dt-log-item ${
selectedLog === log.id
? 'g7dt-selected'
: getLevelBgColor(log.level)
}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className={`g7dt-font-bold g7dt-uppercase ${getLevelColor(log.level)}`}>
{log.level}
</span>
<span className="g7dt-text-purple">[{log.prefix}]</span>
</div>
<span className="g7dt-text-muted">{time}</span>
</div>
<div className="g7dt-text-white g7dt-mt-1 g7dt-truncate">{log.message}</div>
</div>
);
})
)}
</div>
{/* 선택된 로그 상세 */}
{selectedLogData && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">
<span className={getLevelColor(selectedLogData.level)}>{selectedLogData.level.toUpperCase()}</span>
{' '}<span className="g7dt-text-purple">[{selectedLogData.prefix}]</span>
</h3>
<button
onClick={() => setSelectedLog(null)}
className="g7dt-close-btn"
>
✕
</button>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
<div>
<span className="g7dt-text-muted">시간:</span>
<span className="g7dt-ml-2 g7dt-text-white">
{new Date(selectedLogData.timestamp).toLocaleString()}
</span>
</div>
<div>
<span className="g7dt-text-muted">메시지:</span>
<pre className="g7dt-pre g7dt-text-white g7dt-whitespace-pre-wrap">
{selectedLogData.message}
</pre>
</div>
{selectedLogData.args.length > 0 && (
<div>
<span className="g7dt-text-muted">인수:</span>
<pre className="g7dt-pre g7dt-text-green">
{JSON.stringify(selectedLogData.args, null, 2)}
</pre>
</div>
)}
{selectedLogData.stack && (
<div>
<span className="g7dt-text-muted">스택 트레이스:</span>
<pre className="g7dt-pre-stack g7dt-text-red">
{selectedLogData.stack}
</pre>
</div>
)}
</div>
</div>
)}
{/* Prefix별 통계 */}
{stats && Object.keys(stats.byPrefix).length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">Prefix별 로그 수</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-2">
{Object.entries(stats.byPrefix)
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([prefix, count]) => (
<button
key={prefix}
onClick={() => setPrefixFilter(prefix)}
className={prefixFilter === prefix ? 'g7dt-prefix-btn-active' : 'g7dt-prefix-btn'}
>
{prefix}: <span className="g7dt-text-blue">{count}</span>
</button>
))
}
</div>
</div>
)}
</div>
);
};
export default LogsTab;
@@ -0,0 +1,418 @@
/**
* 모달 상태 스코프 추적 탭 컴포넌트
*
* 모달 상태 격리, 유출 감지, 중첩 모달 관계를 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { ModalStateScopeTrackingInfo, ModalStateInfo, ModalStateIssue } from '../../types';
export interface ModalScopeTabProps {
devTools: G7DevToolsCore;
}
/**
* 모달 상태 스코프 추적 탭
*/
export const ModalScopeTab: React.FC<ModalScopeTabProps> = ({ devTools }) => {
const [trackingInfo, setTrackingInfo] = useState<ModalStateScopeTrackingInfo | null>(null);
const [selectedModal, setSelectedModal] = useState<string | null>(null);
const [selectedIssue, setSelectedIssue] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'modals' | 'issues' | 'logs'>('modals');
// 데이터 새로고침
const refreshData = useCallback(() => {
setTrackingInfo(devTools.getModalStateScopeTrackingInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
if (!trackingInfo) {
return <div className="g7dt-empty-state">로딩 중...</div>;
}
const { modals, issues, relations, changeLogs, stats } = trackingInfo;
// 선택된 모달
const selectedModalData = selectedModal
? modals.find(m => m.modalId === selectedModal)
: null;
// 선택된 이슈
const selectedIssueData = selectedIssue
? issues.find(i => i.id === selectedIssue)
: null;
// 스코프 타입 아이콘
const getScopeIcon = (scopeType: string) => {
switch (scopeType) {
case 'isolated': return '🔒';
case 'shared': return '🔓';
case 'inherited': return '📥';
default: return '❓';
}
};
// 이슈 타입 아이콘
const getIssueTypeIcon = (type: string) => {
switch (type) {
case 'state-leakage': return '💧';
case 'isolation-violation': return '🔓';
case 'parent-mutation': return '👆';
case 'orphaned-state': return '👻';
case 'scope-mismatch': return '🔀';
case 'cleanup-failure': return '🧹';
case 'missing-definition': return '🚫';
default: return '❓';
}
};
// 심각도 아이콘
const getSeverityIcon = (severity: string) => {
switch (severity) {
case 'error': return '❌';
case 'warning': return '⚠️';
default: return '❓';
}
};
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">모달 상태 스코프 통계</h3>
<div className="g7dt-stats-grid-3">
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-blue">{stats.totalModals}</div>
<div className="g7dt-text-xs g7dt-text-muted">총 모달</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-green">{stats.openModals}</div>
<div className="g7dt-text-xs g7dt-text-muted">열린 모달</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-red">{stats.totalIssues}</div>
<div className="g7dt-text-xs g7dt-text-muted">이슈</div>
</div>
</div>
</div>
{/* 스코프 타입별 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">스코프별 / 이슈별</h3>
<div className="g7dt-grid-2 g7dt-gap-4">
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">스코프 타입</div>
<div className="g7dt-space-y-1">
{Object.entries(stats.byScope).map(([scope, count]) => (
<div key={scope} className="g7dt-flex g7dt-justify-between g7dt-text-xs">
<span>{getScopeIcon(scope)} {scope}</span>
<span className="g7dt-font-mono">{count as number}</span>
</div>
))}
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">이슈 타입</div>
<div className="g7dt-space-y-1">
{Object.entries(stats.issuesByType)
.filter(([_, count]) => (count as number) > 0)
.map(([type, count]) => (
<div key={type} className="g7dt-flex g7dt-justify-between g7dt-text-xs">
<span>{getIssueTypeIcon(type)} {type}</span>
<span className="g7dt-font-mono g7dt-text-red">{count as number}</span>
</div>
))}
{Object.values(stats.issuesByType).every(v => v === 0) && (
<div className="g7dt-text-xs g7dt-text-green">✅ 이슈 없음</div>
)}
</div>
</div>
</div>
</div>
{/* 뷰 모드 선택 */}
<div className="g7dt-card">
<div className="g7dt-flex g7dt-gap-2">
<button
className={`g7dt-tab-button ${viewMode === 'modals' ? 'g7dt-tab-active' : ''}`}
onClick={() => setViewMode('modals')}
>
🪟 모달 ({modals.length})
</button>
<button
className={`g7dt-tab-button ${viewMode === 'issues' ? 'g7dt-tab-active' : ''}`}
onClick={() => setViewMode('issues')}
>
⚠️ 이슈 ({issues.length})
</button>
<button
className={`g7dt-tab-button ${viewMode === 'logs' ? 'g7dt-tab-active' : ''}`}
onClick={() => setViewMode('logs')}
>
📝 로그 ({changeLogs.length})
</button>
</div>
</div>
{/* 모달 목록 */}
{viewMode === 'modals' && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">모달 목록</h3>
{modals.length === 0 ? (
<div className="g7dt-empty-state">추적된 모달이 없습니다</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{modals.map((modal) => {
const hasIssues = issues.some(i => i.modalId === modal.modalId);
return (
<div
key={modal.modalId}
className={`g7dt-list-item g7dt-cursor-pointer ${
selectedModal === modal.modalId ? 'g7dt-selected' : ''
} ${hasIssues ? 'g7dt-border-red' : ''}`}
onClick={() => setSelectedModal(
selectedModal === modal.modalId ? null : modal.modalId
)}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{modal.closedAt === null ? '📭' : '📪'}</span>
<span>{getScopeIcon(modal.scopeType)}</span>
<span className="g7dt-text-xs g7dt-text-white">
{modal.modalName}
</span>
{hasIssues && <span className="g7dt-text-red">⚠️</span>}
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
변경: {modal.stateChangeCount}
</span>
</div>
</div>
);
})}
</div>
)}
</div>
)}
{/* 이슈 목록 */}
{viewMode === 'issues' && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">이슈 목록</h3>
{issues.length === 0 ? (
<div className="g7dt-empty-state g7dt-text-green">
✅ 모달 상태 이슈가 없습니다
</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{issues.slice().reverse().map((issue) => (
<div
key={issue.id}
className={`g7dt-list-item g7dt-cursor-pointer ${
selectedIssue === issue.id ? 'g7dt-selected' : ''
}`}
onClick={() => setSelectedIssue(
selectedIssue === issue.id ? null : issue.id
)}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getSeverityIcon(issue.severity)}</span>
<span>{getIssueTypeIcon(issue.type)}</span>
<span className="g7dt-text-xs g7dt-text-white">
{issue.modalName}
</span>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{new Date(issue.timestamp).toLocaleTimeString()}
</span>
</div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate">
{issue.description}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* 상태 변경 로그 */}
{viewMode === 'logs' && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">상태 변경 로그</h3>
{changeLogs.length === 0 ? (
<div className="g7dt-empty-state">상태 변경 로그가 없습니다</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{changeLogs.slice().reverse().slice(0, 50).map((log) => (
<div
key={log.id}
className={`g7dt-list-item ${log.violatesIsolation ? 'g7dt-border-red' : ''}`}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-xs g7dt-text-white">
{log.modalName}
</span>
<span className="g7dt-text-xs g7dt-text-blue g7dt-mono">
{log.stateKey}
</span>
{log.violatesIsolation && (
<span className="g7dt-text-red">⚠️ 격리 위반</span>
)}
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{new Date(log.timestamp).toLocaleTimeString()}
</span>
</div>
<div className="g7dt-flex g7dt-gap-2 g7dt-text-xs g7dt-mt-1">
<span className="g7dt-text-red g7dt-truncate" style={{ maxWidth: '45%' }}>
{JSON.stringify(log.previousValue)}
</span>
<span className="g7dt-text-muted">→</span>
<span className="g7dt-text-green g7dt-truncate" style={{ maxWidth: '45%' }}>
{JSON.stringify(log.newValue)}
</span>
</div>
</div>
))}
</div>
)}
</div>
)}
{/* 선택된 모달 상세 */}
{selectedModalData && viewMode === 'modals' && (
<div className="g7dt-card g7dt-border-blue">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
{getScopeIcon(selectedModalData.scopeType)} 모달 상세: {selectedModalData.modalName}
</h3>
<div className="g7dt-space-y-3">
<div className="g7dt-grid-2 g7dt-gap-3">
<div>
<div className="g7dt-text-xs g7dt-text-muted">스코프</div>
<div className="g7dt-text-sm g7dt-text-white">
{getScopeIcon(selectedModalData.scopeType)} {selectedModalData.scopeType}
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">상태</div>
<div className="g7dt-text-sm g7dt-text-white">
{selectedModalData.closedAt === null ? '📭 열림' : '📪 닫힘'}
</div>
</div>
</div>
{selectedModalData.parentModalId && (
<div>
<div className="g7dt-text-xs g7dt-text-muted">부모 모달</div>
<div className="g7dt-text-sm g7dt-text-purple g7dt-mono">
{selectedModalData.parentModalId}
</div>
</div>
)}
<div>
<div className="g7dt-text-xs g7dt-text-muted">상태 변경 횟수</div>
<div className="g7dt-text-sm g7dt-text-white">
{selectedModalData.stateChangeCount}
</div>
</div>
{selectedModalData.isolatedStateKeys.length > 0 && (
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-1">격리된 상태 키</div>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1">
{selectedModalData.isolatedStateKeys.map((key) => (
<span key={key} className="g7dt-badge g7dt-badge-red g7dt-text-xs">
🔒 {key}
</span>
))}
</div>
</div>
)}
{selectedModalData.sharedStateKeys.length > 0 && (
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-1">공유된 상태 키</div>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1">
{selectedModalData.sharedStateKeys.map((key) => (
<span key={key} className="g7dt-badge g7dt-badge-blue g7dt-text-xs">
🔓 {key}
</span>
))}
</div>
</div>
)}
</div>
</div>
)}
{/* 선택된 이슈 상세 */}
{selectedIssueData && viewMode === 'issues' && (
<div className="g7dt-card g7dt-border-red">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
{getSeverityIcon(selectedIssueData.severity)} 이슈 상세
</h3>
<div className="g7dt-space-y-3">
<div>
<div className="g7dt-text-xs g7dt-text-muted">타입</div>
<div className="g7dt-text-sm g7dt-text-white">
{getIssueTypeIcon(selectedIssueData.type)} {selectedIssueData.type}
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">설명</div>
<div className="g7dt-text-sm g7dt-text-white">
{selectedIssueData.description}
</div>
</div>
{selectedIssueData.affectedStateKeys.length > 0 && (
<div>
<div className="g7dt-text-xs g7dt-text-muted">영향 받는 상태 키</div>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1">
{selectedIssueData.affectedStateKeys.map((key) => (
<span key={key} className="g7dt-badge g7dt-text-xs">
{key}
</span>
))}
</div>
</div>
)}
{selectedIssueData.leakedValue !== undefined && (
<div>
<div className="g7dt-text-xs g7dt-text-muted">유출된 값</div>
<pre className="g7dt-code-block g7dt-text-red">
{JSON.stringify(selectedIssueData.leakedValue, null, 2)}
</pre>
</div>
)}
</div>
</div>
)}
{/* 모달 관계 (항상 표시) */}
{relations.length > 0 && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">모달 관계</h3>
<div className="g7dt-space-y-2">
{relations.map((rel, idx) => (
<div key={idx} className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs">
<span className="g7dt-text-purple">{rel.parentModalId}</span>
<span className="g7dt-text-muted">→</span>
<span className="g7dt-text-blue">{rel.childModalId}</span>
<span className="g7dt-badge g7dt-text-xs g7dt-ml-auto">
{rel.relationType}
</span>
</div>
))}
</div>
</div>
)}
</div>
);
};
export default ModalScopeTab;
@@ -0,0 +1,185 @@
/**
* NOTE: @since versions (engine-v1.x.x) refer to internal template engine
* development iterations, not G7 platform release versions.
*/
/**
* Named Actions 탭 컴포넌트
*
* 레이아웃의 named_actions 정의 목록과 actionRef 해석 이력을 표시합니다.
*
* @since engine-v1.19.0
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { NamedActionTrackingInfo } from '../../types';
export interface NamedActionsTabProps {
devTools: G7DevToolsCore;
}
/**
* Named Actions 탭
*/
export const NamedActionsTab: React.FC<NamedActionsTabProps> = ({ devTools }) => {
const [viewMode, setViewMode] = useState<'definitions' | 'refs'>('definitions');
const [trackingInfo, setTrackingInfo] = useState<NamedActionTrackingInfo | null>(null);
const [filter, setFilter] = useState<string>('');
const refreshData = useCallback(() => {
if (devTools) {
setTrackingInfo(devTools.getNamedActionTrackingInfo());
}
}, [devTools]);
useEffect(() => {
refreshData();
const timer = setInterval(refreshData, 2000);
return () => clearInterval(timer);
}, [refreshData]);
if (!trackingInfo) {
return <div className="g7dt-empty-message g7dt-py-4">데이터 로딩 중...</div>;
}
const { definitions, refLogs, stats } = trackingInfo;
const definitionNames = Object.keys(definitions);
// 필터링
const filteredDefs = definitionNames.filter(name =>
!filter || name.toLowerCase().includes(filter.toLowerCase()) ||
definitions[name]?.handler?.toLowerCase().includes(filter.toLowerCase())
);
const filteredRefs = refLogs.filter(log =>
!filter || log.actionRefName.toLowerCase().includes(filter.toLowerCase()) ||
log.resolvedHandler.toLowerCase().includes(filter.toLowerCase())
);
return (
<div className="g7dt-space-y-4">
{/* 통계 요약 */}
<div className="g7dt-grid g7dt-grid-cols-3 g7dt-gap-2">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value">{stats.totalDefinitions}</div>
<div className="g7dt-stat-label">정의</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value">{stats.totalRefs}</div>
<div className="g7dt-stat-label">참조</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value" style={{ color: stats.unusedDefinitions.length > 0 ? '#f59e0b' : '#10b981' }}>
{stats.unusedDefinitions.length}
</div>
<div className="g7dt-stat-label">미사용</div>
</div>
</div>
{/* 뷰 모드 토글 */}
<div className="g7dt-flex g7dt-gap-2">
<button
onClick={() => setViewMode('definitions')}
className={viewMode === 'definitions' ? 'g7dt-filter-btn g7dt-filter-active' : 'g7dt-filter-btn'}
>
정의 목록 ({definitionNames.length})
</button>
<button
onClick={() => setViewMode('refs')}
className={viewMode === 'refs' ? 'g7dt-filter-btn g7dt-filter-active' : 'g7dt-filter-btn'}
>
참조 이력 ({refLogs.length})
</button>
<button
onClick={refreshData}
className="g7dt-filter-btn"
title="새로고침"
>
↻
</button>
</div>
{/* 검색 */}
<input
type="text"
placeholder={viewMode === 'definitions' ? '액션 이름 검색...' : 'actionRef 검색...'}
value={filter}
onChange={e => setFilter(e.target.value)}
className="g7dt-input g7dt-w-full"
/>
{/* 정의 목록 뷰 */}
{viewMode === 'definitions' && (
<div className="g7dt-space-y-1">
{filteredDefs.length === 0 ? (
<div className="g7dt-empty-message g7dt-py-4">
{definitionNames.length === 0 ? '정의된 named_actions가 없습니다' : '검색 결과 없음'}
</div>
) : (
filteredDefs.map(name => {
const def = definitions[name];
const refCount = stats.refCountByName[name] || 0;
const isUnused = stats.unusedDefinitions.includes(name);
return (
<div
key={name}
className="g7dt-card"
style={{ borderLeft: isUnused ? '3px solid #f59e0b' : '3px solid #10b981' }}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<div>
<span className="g7dt-font-bold">{name}</span>
<span className="g7dt-text-muted g7dt-ml-2">→ {def.handler}</span>
</div>
<span className="g7dt-badge" title="참조 횟수">
{refCount}회
</span>
</div>
{def.params && (
<details className="g7dt-mt-1">
<summary className="g7dt-text-xs g7dt-text-muted g7dt-cursor-pointer">params</summary>
<pre className="g7dt-pre g7dt-text-xs g7dt-mt-1" style={{ maxHeight: '200px', overflow: 'auto' }}>
{JSON.stringify(def.params, null, 2)}
</pre>
</details>
)}
{isUnused && (
<div className="g7dt-text-xs" style={{ color: '#f59e0b', marginTop: '4px' }}>
⚠ 미사용 정의
</div>
)}
</div>
);
})
)}
</div>
)}
{/* 참조 이력 뷰 */}
{viewMode === 'refs' && (
<div className="g7dt-space-y-1">
{filteredRefs.length === 0 ? (
<div className="g7dt-empty-message g7dt-py-4">
{refLogs.length === 0 ? 'actionRef 해석 이력이 없습니다' : '검색 결과 없음'}
</div>
) : (
[...filteredRefs].reverse().map(log => (
<div key={log.id} className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<div>
<span className="g7dt-font-bold">{log.actionRefName}</span>
<span className="g7dt-text-muted g7dt-ml-2">→ {log.resolvedHandler}</span>
</div>
<span className="g7dt-text-xs g7dt-text-muted">
{new Date(log.timestamp).toLocaleTimeString()}
</span>
</div>
</div>
))
)}
</div>
)}
</div>
);
};
@@ -0,0 +1,275 @@
/**
* Nested Context 추적 탭 컴포넌트
*
* expandChildren, cellChildren, iteration, modal, slot 컨텍스트 추적을 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { NestedContextTrackingInfo, NestedContextInfo } from '../../types';
export interface NestedContextTabProps {
devTools: G7DevToolsCore;
}
/**
* Nested Context 추적 탭
*/
export const NestedContextTab: React.FC<NestedContextTabProps> = ({ devTools }) => {
const [trackingInfo, setTrackingInfo] = useState<NestedContextTrackingInfo | null>(null);
const [selectedContext, setSelectedContext] = useState<string | null>(null);
const [typeFilter, setTypeFilter] = useState<string>('all');
// 데이터 새로고침
const refreshData = useCallback(() => {
setTrackingInfo(devTools.getNestedContextTrackingInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
if (!trackingInfo) {
return <div className="g7dt-empty-state">로딩 중...</div>;
}
const { contexts, stats } = trackingInfo;
// 필터링된 컨텍스트
const filteredContexts = contexts.filter(ctx => {
if (typeFilter === 'all') return true;
return ctx.componentType === typeFilter;
});
// 선택된 컨텍스트
const selectedContextData = selectedContext
? contexts.find(c => c.id === selectedContext)
: null;
// 컨텍스트 타입 아이콘
const getTypeIcon = (type: string) => {
switch (type) {
case 'expandChildren': return '📂';
case 'cellChildren': return '📊';
case 'iteration': return '🔄';
case 'modal': return '🪟';
case 'slot': return '🔲';
default: return '❓';
}
};
// 깊이 표시
const getDepthIndicator = (depth: number) => {
return '│'.repeat(Math.max(0, depth - 1)) + (depth > 0 ? '├─' : '');
};
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">Nested Context 통계</h3>
<div className="g7dt-stats-grid-3">
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-blue">{stats.totalContexts || 0}</div>
<div className="g7dt-text-xs g7dt-text-muted">총 컨텍스트</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-purple">{stats.maxDepth || 0}</div>
<div className="g7dt-text-xs g7dt-text-muted">최대 깊이</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-red">{stats.failedAccessCount || 0}</div>
<div className="g7dt-text-xs g7dt-text-muted">접근 오류</div>
</div>
</div>
</div>
{/* 타입별 통계 */}
{stats.byType && Object.keys(stats.byType).length > 0 && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">타입별 분포</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-3">
{Object.entries(stats.byType).map(([type, count]) => (
<div
key={type}
className={`g7dt-badge g7dt-cursor-pointer ${
typeFilter === type ? 'g7dt-badge-selected' : ''
}`}
onClick={() => setTypeFilter(typeFilter === type ? 'all' : type)}
>
{getTypeIcon(type)} {type}: {count as number}
</div>
))}
</div>
</div>
)}
{/* 필터 */}
<div className="g7dt-card">
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-xs g7dt-text-muted">타입:</span>
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="g7dt-select"
>
<option value="all">전체</option>
<option value="expandChildren">expandChildren</option>
<option value="cellChildren">cellChildren</option>
<option value="iteration">iteration</option>
<option value="modal">modal</option>
<option value="slot">slot</option>
</select>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{filteredContexts.length}개 표시
</span>
</div>
</div>
{/* 컨텍스트 목록 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">컨텍스트 목록</h3>
{filteredContexts.length === 0 ? (
<div className="g7dt-empty-state">
추적된 Nested Context가 없습니다
</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{filteredContexts.slice().reverse().map((ctx) => {
const hasAccessError = ctx.accessAttempts?.some(a => !a.found);
const availableVars = ctx.mergedContext?.all || [];
return (
<div
key={ctx.id}
className={`g7dt-list-item g7dt-cursor-pointer ${
selectedContext === ctx.id ? 'g7dt-selected' : ''
} ${hasAccessError ? 'g7dt-border-red' : ''}`}
onClick={() => setSelectedContext(
selectedContext === ctx.id ? null : ctx.id
)}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-muted g7dt-mono g7dt-text-xs">
{getDepthIndicator(ctx.depth)}
</span>
<span>{getTypeIcon(ctx.componentType)}</span>
<span className="g7dt-text-xs g7dt-text-white">
{ctx.componentId || ctx.componentType}
</span>
{hasAccessError && (
<span className="g7dt-text-red g7dt-text-xs">⚠️ 오류</span>
)}
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
깊이: {ctx.depth}
</span>
</div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-1">
변수: {availableVars.slice(0, 5).join(', ')}
{availableVars.length > 5 && '...'}
</div>
</div>
);
})}
</div>
)}
</div>
{/* 선택된 컨텍스트 상세 */}
{selectedContextData && (
<div className="g7dt-card g7dt-border-blue">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
{getTypeIcon(selectedContextData.componentType)} 컨텍스트 상세
</h3>
<div className="g7dt-space-y-3">
<div className="g7dt-grid-2 g7dt-gap-3">
<div>
<div className="g7dt-text-xs g7dt-text-muted">타입</div>
<div className="g7dt-text-sm g7dt-text-white">
{selectedContextData.componentType}
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">깊이</div>
<div className="g7dt-text-sm g7dt-text-white">
{selectedContextData.depth}
</div>
</div>
</div>
{selectedContextData.componentId && (
<div>
<div className="g7dt-text-xs g7dt-text-muted">컴포넌트 ID</div>
<div className="g7dt-text-sm g7dt-text-blue g7dt-mono">
{selectedContextData.componentId}
</div>
</div>
)}
{selectedContextData.parentId && (
<div>
<div className="g7dt-text-xs g7dt-text-muted">부모 컨텍스트</div>
<div className="g7dt-text-sm g7dt-text-purple g7dt-mono">
{selectedContextData.parentId}
</div>
</div>
)}
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">사용 가능한 변수</div>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1">
{(selectedContextData.mergedContext?.all || []).map((varName) => (
<span
key={varName}
className="g7dt-badge g7dt-badge-blue g7dt-text-xs"
>
{varName}
</span>
))}
</div>
</div>
{selectedContextData.ownContext?.added && selectedContextData.ownContext.added.length > 0 && (
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">추가된 변수 (이 컨텍스트에서)</div>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-1">
{selectedContextData.ownContext.added.map((varName) => (
<span
key={varName}
className="g7dt-badge g7dt-badge-green g7dt-text-xs"
>
+ {varName}
</span>
))}
</div>
</div>
)}
{selectedContextData.accessAttempts && selectedContextData.accessAttempts.length > 0 && (
<div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">접근 시도</div>
<div className="g7dt-space-y-1">
{selectedContextData.accessAttempts.slice(0, 10).map((attempt, idx) => (
<div
key={idx}
className={`g7dt-flex g7dt-justify-between g7dt-text-xs ${
attempt.found ? '' : 'g7dt-text-red'
}`}
>
<span className="g7dt-mono">{attempt.path}</span>
<span>{attempt.found ? '✓' : '✕'}</span>
</div>
))}
</div>
</div>
)}
</div>
</div>
)}
</div>
);
};
export default NestedContextTab;
@@ -0,0 +1,200 @@
/**
* 네트워크 탭 컴포넌트
*
* API 요청 이력과 대기 중인 데이터소스를 표시합니다.
*/
import React from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface NetworkTabProps {
devTools: G7DevToolsCore;
}
/**
* 네트워크 탭
*/
export const NetworkTab: React.FC<NetworkTabProps> = ({ devTools }) => {
const networkInfo = devTools.getNetworkInfo();
const getStatusColor = (status: string) => {
switch (status) {
case 'success':
return 'g7dt-text-green';
case 'error':
return 'g7dt-text-red';
case 'pending':
return 'g7dt-text-yellow';
default:
return 'g7dt-text-gray';
}
};
// 쿼리 파라미터 객체 여부 확인 및 표시
const hasQueryParams = (req: any) => {
return req.queryParams && Object.keys(req.queryParams).length > 0;
};
// 쿼리 파라미터 렌더링
const renderQueryParams = (queryParams: Record<string, string | string[]>) => {
return Object.entries(queryParams).map(([key, value]) => (
<div key={key} className="g7dt-flex g7dt-gap-2 g7dt-text-xs">
<span className="g7dt-text-purple">{key}:</span>
<span className="g7dt-text-lightgray">
{Array.isArray(value) ? JSON.stringify(value) : value}
</span>
</div>
));
};
// JSON 안전하게 stringify
const safeStringify = (obj: any, maxLength: number = 5000) => {
try {
const str = JSON.stringify(obj, null, 2);
if (str.length > maxLength) {
return str.substring(0, maxLength) + '\n... (truncated)';
}
return str;
} catch {
return '(직렬화 불가)';
}
};
return (
<div className="g7dt-space-y-4">
{/* 진행 중인 요청 */}
{networkInfo.activeRequests.length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2">
진행 중 ({networkInfo.activeRequests.length})
</h3>
<div className="g7dt-space-y-1">
{networkInfo.activeRequests.map(req => (
<details key={req.id} className="g7dt-details">
<summary className="g7dt-summary g7dt-pending-request">
<span className="g7dt-font-bold">{req.method}</span>
<span className="g7dt-ml-2 g7dt-text-lightgray g7dt-truncate">
{req.fullUrl || req.url}
</span>
</summary>
<div className="g7dt-card g7dt-mt-1 g7dt-text-xs">
{/* 쿼리 파라미터 */}
{hasQueryParams(req) && (
<div className="g7dt-mb-2">
<div className="g7dt-text-blue g7dt-font-bold g7dt-mb-1">쿼리 파라미터</div>
<div className="g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue">
{renderQueryParams(req.queryParams)}
</div>
</div>
)}
{/* 요청 본문 */}
{req.requestBody && (
<div>
<div className="g7dt-text-orange g7dt-font-bold g7dt-mb-1">요청 본문</div>
<pre className="g7dt-pre g7dt-text-xs">
{safeStringify(req.requestBody, 2000)}
</pre>
</div>
)}
</div>
</details>
))}
</div>
</div>
)}
{/* 요청 이력 */}
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">요청 이력</h3>
<div className="g7dt-space-y-1 g7dt-scroll-list-lg">
{networkInfo.requestHistory.length === 0 ? (
<div className="g7dt-empty-message">요청 이력 없음</div>
) : (
networkInfo.requestHistory.slice(-20).reverse().map(req => (
<details key={req.id} className="g7dt-details">
<summary className="g7dt-summary g7dt-card g7dt-text-xs">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-w-full">
<div>
<span className="g7dt-font-bold">{req.method}</span>
<span className={`g7dt-ml-2 ${getStatusColor(req.status)}`}>
{req.statusCode || req.status}
</span>
</div>
<span className="g7dt-text-gray">{req.duration}ms</span>
</div>
<div className="g7dt-text-gray g7dt-truncate g7dt-mt-1">
{req.fullUrl || req.url}
</div>
</summary>
<div className="g7dt-card g7dt-mt-1 g7dt-text-xs g7dt-ml-2 g7dt-border-l-2 g7dt-border-gray">
{/* 기본 정보 */}
<div className="g7dt-mb-2">
<div className="g7dt-text-xs g7dt-space-y-1">
<div><span className="g7dt-text-gray">URL:</span> <span className="g7dt-text-lightgray">{req.fullUrl || req.url}</span></div>
<div><span className="g7dt-text-gray">상태:</span> <span className={getStatusColor(req.status)}>{req.statusCode || req.status}</span></div>
<div><span className="g7dt-text-gray">소요시간:</span> <span className="g7dt-text-lightgray">{req.duration}ms</span></div>
{req.dataSourceId && (
<div><span className="g7dt-text-gray">데이터소스:</span> <span className="g7dt-text-blue">{req.dataSourceId}</span></div>
)}
{req.error && (
<div><span className="g7dt-text-gray">에러:</span> <span className="g7dt-text-red">{req.error}</span></div>
)}
</div>
</div>
{/* 쿼리 파라미터 */}
{hasQueryParams(req) && (
<div className="g7dt-mb-2">
<div className="g7dt-text-blue g7dt-font-bold g7dt-mb-1">쿼리 파라미터</div>
<div className="g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue">
{renderQueryParams(req.queryParams)}
</div>
</div>
)}
{/* 요청 본문 */}
{req.requestBody && (
<div className="g7dt-mb-2">
<div className="g7dt-text-orange g7dt-font-bold g7dt-mb-1">요청 본문</div>
<pre className="g7dt-pre g7dt-text-xs g7dt-max-h-40 g7dt-overflow-auto">
{safeStringify(req.requestBody, 2000)}
</pre>
</div>
)}
{/* 응답 내용 */}
{req.response !== undefined && (
<div>
<div className="g7dt-text-green g7dt-font-bold g7dt-mb-1">응답 내용</div>
<pre className="g7dt-pre g7dt-text-xs g7dt-max-h-60 g7dt-overflow-auto">
{safeStringify(req.response, 5000)}
</pre>
</div>
)}
</div>
</details>
))
)}
</div>
</div>
{/* 대기 중인 데이터소스 */}
{networkInfo.pendingDataSources.length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-2">
대기 중인 데이터소스 ({networkInfo.pendingDataSources.length})
</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-2">
{networkInfo.pendingDataSources.map(ds => (
<span key={ds} className="g7dt-tag-blue">
{ds}
</span>
))}
</div>
</div>
)}
</div>
);
};
export default NetworkTab;
@@ -0,0 +1,80 @@
/**
* 성능 탭 컴포넌트
*
* 렌더링 성능 정보와 메모리 경고를 표시합니다.
*/
import React from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface PerformanceTabProps {
devTools: G7DevToolsCore;
}
/**
* 성능 탭
*/
export const PerformanceTab: React.FC<PerformanceTabProps> = ({ devTools }) => {
const perfInfo = devTools.getPerformanceInfo();
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-stats-grid-2">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-blue">
{perfInfo.bindingEvalCount}
</div>
<div className="g7dt-stat-label">바인딩 평가 횟수</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-purple">
{perfInfo.renderCounts.size}
</div>
<div className="g7dt-stat-label">렌더링된 컴포넌트</div>
</div>
</div>
{/* 메모리 경고 */}
{perfInfo.memoryWarnings.length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2">메모리 경고</h3>
<div className="g7dt-space-y-2">
{perfInfo.memoryWarnings.map((warning, i) => (
<div key={i} className="g7dt-warning-card">
<div className="g7dt-font-bold">{warning.type}</div>
<div className="g7dt-text-lightgray">{warning.message}</div>
<div className="g7dt-text-xs g7dt-text-gray g7dt-mt-1">{warning.suggestion}</div>
</div>
))}
</div>
</div>
)}
{/* 렌더링 횟수 */}
{perfInfo.renderCounts.size > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">컴포넌트별 렌더링</h3>
<div className="g7dt-space-y-1 g7dt-scroll-list">
{Array.from(perfInfo.renderCounts.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([name, count]) => (
<div
key={name}
className="g7dt-list-item"
>
<span className="g7dt-text-lightgray g7dt-truncate">{name}</span>
<span className={count > 50 ? 'g7dt-text-red' : 'g7dt-text-gray'}>
{count}회
</span>
</div>
))}
</div>
</div>
)}
</div>
);
};
export default PerformanceTab;
@@ -0,0 +1,279 @@
/**
* 렌더링 탭 컴포넌트
*
* setState 후 렌더링 추적 정보를 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
export interface RendersTabProps {
devTools: G7DevToolsCore;
}
/**
* 렌더링 탭
*/
export const RendersTab: React.FC<RendersTabProps> = ({ devTools }) => {
const [renderInfo, setRenderInfo] = useState(devTools.getStateRenderingInfo());
const [selectedLog, setSelectedLog] = useState<string | null>(null);
const [showNoRenderOnly, setShowNoRenderOnly] = useState(false);
const [pathFilter, setPathFilter] = useState('');
// 데이터 새로고침
const refreshData = useCallback(() => {
setRenderInfo(devTools.getStateRenderingInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
// 필터링된 로그
const filteredLogs = renderInfo.logs.filter(log => {
// 렌더링 없는 것만 필터
if (showNoRenderOnly && log.renderedComponents.length > 0) return false;
// 경로 필터
if (pathFilter && !log.statePath.toLowerCase().includes(pathFilter.toLowerCase())) return false;
return true;
});
// 선택된 로그
const selectedLogData = selectedLog
? renderInfo.logs.find(log => log.setStateId === selectedLog)
: null;
// 통계
const stats = renderInfo.stats;
const noRenderCount = renderInfo.logs.filter(log => log.renderedComponents.length === 0).length;
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-stats-grid">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-blue">
{stats.totalStateChanges}
</div>
<div className="g7dt-stat-label">상태 변경</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-green">
{stats.totalRenders}
</div>
<div className="g7dt-stat-label">총 렌더링</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-purple">
{stats.avgRenderDuration.toFixed(1)}ms
</div>
<div className="g7dt-stat-label">평균 렌더 시간</div>
</div>
<div className="g7dt-stat-card">
<div className={`g7dt-stat-value ${noRenderCount > 0 ? 'g7dt-text-yellow' : 'g7dt-text-green'}`}>
{noRenderCount}
</div>
<div className="g7dt-stat-label">렌더링 없음</div>
</div>
</div>
{/* 필터 */}
<div className="g7dt-flex g7dt-gap-2">
<input
type="text"
placeholder="상태 경로 필터 (예: _global.user)"
value={pathFilter}
onChange={e => setPathFilter(e.target.value)}
className="g7dt-input g7dt-flex-1"
/>
<button
onClick={() => setShowNoRenderOnly(!showNoRenderOnly)}
className={showNoRenderOnly ? 'g7dt-filter-btn-active-yellow' : 'g7dt-filter-btn'}
>
렌더링 없음만
</button>
</div>
{/* 로그 목록 */}
<div className="g7dt-scroll-list">
{filteredLogs.length === 0 ? (
<div className="g7dt-empty-state">
상태-렌더링 로그가 없습니다
</div>
) : (
filteredLogs.slice(-30).reverse().map(log => {
const hasRender = log.renderedComponents.length > 0;
const icon = hasRender ? '✅' : '⚠️';
const time = new Date(log.timestamp).toLocaleTimeString();
return (
<div
key={log.setStateId}
onClick={() => setSelectedLog(log.setStateId)}
className={`g7dt-render-log-item ${
selectedLog === log.setStateId
? 'g7dt-selected'
: hasRender
? ''
: 'g7dt-warning'
}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-mono g7dt-text-blue">
{icon} {log.statePath}
</span>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
{hasRender ? (
<span className="g7dt-text-green">
{log.renderedComponents.length}개 렌더
</span>
) : (
<span className="g7dt-text-yellow">렌더링 없음</span>
)}
<span className="g7dt-text-muted">{time}</span>
</div>
</div>
{log.triggeredBy?.handlerType && (
<div className="g7dt-text-muted g7dt-mt-1">
트리거: {log.triggeredBy.handlerType}
</div>
)}
</div>
);
})
)}
</div>
{/* 선택된 로그 상세 */}
{selectedLogData && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">{selectedLogData.statePath}</h3>
<button
onClick={() => setSelectedLog(null)}
className="g7dt-close-btn"
>
✕
</button>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
{/* ID 및 시간 */}
<div>
<span className="g7dt-text-muted">setStateId:</span>
<span className="g7dt-ml-2 g7dt-text-purple g7dt-mono">{selectedLogData.setStateId}</span>
</div>
{/* 트리거 정보 */}
{selectedLogData.triggeredBy && (
<div>
<span className="g7dt-text-muted">트리거:</span>
<span className="g7dt-ml-2 g7dt-text-yellow">
{selectedLogData.triggeredBy.handlerType}
{selectedLogData.triggeredBy.actionId && ` (${selectedLogData.triggeredBy.actionId})`}
</span>
</div>
)}
{/* 값 변경 */}
<div>
<span className="g7dt-text-muted">이전 값:</span>
<pre className="g7dt-pre g7dt-text-red">
{JSON.stringify(selectedLogData.oldValue, null, 2)?.slice(0, 200)}
</pre>
</div>
<div>
<span className="g7dt-text-muted">새 값:</span>
<pre className="g7dt-pre g7dt-text-green">
{JSON.stringify(selectedLogData.newValue, null, 2)?.slice(0, 200)}
</pre>
</div>
{/* 렌더링 정보 */}
{selectedLogData.renderedComponents.length > 0 ? (
<div>
<span className="g7dt-text-muted">
렌더링된 컴포넌트 ({selectedLogData.renderedComponents.length}개):
</span>
<div className="g7dt-mt-1 g7dt-space-y-1">
{selectedLogData.renderedComponents.slice(0, 10).map((comp, i) => (
<div
key={i}
className="g7dt-render-comp-item"
>
<span className="g7dt-text-blue">{comp.componentName}</span>
<span className="g7dt-text-muted">
{comp.renderDuration.toFixed(2)}ms
</span>
</div>
))}
{selectedLogData.renderedComponents.length > 10 && (
<div className="g7dt-text-muted g7dt-text-center">
... 외 {selectedLogData.renderedComponents.length - 10}개
</div>
)}
</div>
<div className="g7dt-mt-2 g7dt-text-muted">
총 렌더 시간: {selectedLogData.totalRenderDuration.toFixed(2)}ms
</div>
</div>
) : (
<div className="g7dt-warning-box">
<span className="g7dt-text-yellow">⚠️ 렌더링이 발생하지 않았습니다</span>
<div className="g7dt-text-muted g7dt-mt-1 g7dt-text-xxs">
가능한 원인:
<ul className="g7dt-list g7dt-mt-1">
<li>해당 상태를 바인딩하는 컴포넌트가 없음</li>
<li>컴포넌트가 마운트되지 않은 상태</li>
<li>동일한 값으로 상태 설정</li>
</ul>
</div>
</div>
)}
</div>
</div>
)}
{/* Top 렌더링 컴포넌트 */}
{stats.topRenderedComponents.length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">가장 많이 렌더링된 컴포넌트</h3>
<div className="g7dt-flex g7dt-flex-wrap g7dt-gap-2">
{stats.topRenderedComponents.slice(0, 5).map((item, i) => (
<span
key={i}
className="g7dt-tag"
>
{item.name}: <span className="g7dt-text-blue">{item.count}</span>
</span>
))}
</div>
</div>
)}
{/* 새로고침 및 초기화 버튼 */}
<div className="g7dt-flex g7dt-gap-2">
<button
onClick={refreshData}
className="g7dt-btn-secondary"
>
새로고침
</button>
<button
onClick={() => {
devTools.clearStateRenderingLogs();
refreshData();
}}
className="g7dt-btn-danger"
>
로그 초기화
</button>
</div>
</div>
);
};
export default RendersTab;
@@ -0,0 +1,226 @@
/**
* Stale Closure 추적 탭 컴포넌트
*
* Stale Closure 경고, 캡처된 상태 vs 최신 상태 비교를 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { StaleClosureTrackingInfo, StaleClosureWarning } from '../../types';
export interface StaleClosureTabProps {
devTools: G7DevToolsCore;
}
/**
* Stale Closure 추적 탭
*/
export const StaleClosureTab: React.FC<StaleClosureTabProps> = ({ devTools }) => {
const [trackingInfo, setTrackingInfo] = useState<StaleClosureTrackingInfo | null>(null);
const [selectedWarning, setSelectedWarning] = useState<string | null>(null);
const [severityFilter, setSeverityFilter] = useState<string>('all');
// 데이터 새로고침
const refreshData = useCallback(() => {
setTrackingInfo(devTools.getStaleClosureTrackingInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
if (!trackingInfo) {
return <div className="g7dt-empty-state">로딩 중...</div>;
}
const { warnings, stats } = trackingInfo;
// 필터링된 경고
const filteredWarnings = warnings.filter(warning => {
if (severityFilter === 'all') return true;
return warning.severity === severityFilter;
});
// 선택된 경고
const selectedWarningData = selectedWarning
? warnings.find(w => w.id === selectedWarning)
: null;
// 심각도 아이콘
const getSeverityIcon = (severity: string) => {
switch (severity) {
case 'error': return '❌';
case 'warning': return '⚠️';
default: return '❓';
}
};
// 경고 타입 아이콘
const getTypeIcon = (type: string) => {
switch (type) {
case 'state-changed-during-async': return '⏳';
case 'captured-in-callback': return '📸';
case 'stale-in-handler': return '🔄';
default: return '❓';
}
};
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">Stale Closure 통계</h3>
<div className="g7dt-stats-grid-3">
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-yellow">{stats.totalWarnings || 0}</div>
<div className="g7dt-text-xs g7dt-text-muted">총 경고</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-red">{stats.warningsBySeverity?.error || 0}</div>
<div className="g7dt-text-xs g7dt-text-muted">에러</div>
</div>
<div className="g7dt-text-center">
<div className="g7dt-text-2xl g7dt-font-bold g7dt-text-orange">{stats.warningsBySeverity?.warning || 0}</div>
<div className="g7dt-text-xs g7dt-text-muted">경고</div>
</div>
</div>
</div>
{/* 타입별 통계 */}
{stats.warningsByType && Object.keys(stats.warningsByType).length > 0 && (
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">타입별 분포</h3>
<div className="g7dt-space-y-2">
{Object.entries(stats.warningsByType).map(([type, count]) => (
<div key={type} className="g7dt-flex g7dt-justify-between g7dt-text-xs">
<span className="g7dt-text-muted">
{getTypeIcon(type)} {type}
</span>
<span className="g7dt-text-white g7dt-font-mono">{count as number}</span>
</div>
))}
</div>
</div>
)}
{/* 필터 */}
<div className="g7dt-card">
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span className="g7dt-text-xs g7dt-text-muted">심각도:</span>
<select
value={severityFilter}
onChange={(e) => setSeverityFilter(e.target.value)}
className="g7dt-select"
>
<option value="all">전체</option>
<option value="error">에러</option>
<option value="warning">경고</option>
</select>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{filteredWarnings.length}개 표시
</span>
</div>
</div>
{/* 경고 목록 */}
<div className="g7dt-card">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">Stale Closure 경고</h3>
{filteredWarnings.length === 0 ? (
<div className="g7dt-empty-state g7dt-text-green">
✅ Stale Closure 경고가 없습니다
</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto">
{filteredWarnings.slice().reverse().map((warning) => (
<div
key={warning.id}
className={`g7dt-list-item g7dt-cursor-pointer ${
selectedWarning === warning.id ? 'g7dt-selected' : ''
}`}
onClick={() => setSelectedWarning(
selectedWarning === warning.id ? null : warning.id
)}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getSeverityIcon(warning.severity)}</span>
<span>{getTypeIcon(warning.type)}</span>
<span className="g7dt-text-xs g7dt-text-white g7dt-truncate">
{warning.location}
</span>
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{new Date(warning.timestamp).toLocaleTimeString()}
</span>
</div>
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate">
{warning.statePath}
</div>
</div>
))}
</div>
)}
</div>
{/* 선택된 경고 상세 */}
{selectedWarningData && (
<div className="g7dt-card g7dt-border-yellow">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
{getSeverityIcon(selectedWarningData.severity)} 경고 상세
</h3>
<div className="g7dt-space-y-3">
<div>
<div className="g7dt-text-xs g7dt-text-muted">위치</div>
<div className="g7dt-text-sm g7dt-text-white g7dt-mono">
{selectedWarningData.location}
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">타입</div>
<div className="g7dt-text-sm g7dt-text-white">
{getTypeIcon(selectedWarningData.type)} {selectedWarningData.type}
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">상태 경로</div>
<div className="g7dt-text-sm g7dt-text-yellow g7dt-mono">
{selectedWarningData.statePath}
</div>
</div>
<div className="g7dt-grid-2 g7dt-gap-3">
<div>
<div className="g7dt-text-xs g7dt-text-muted">캡처된 값</div>
<pre className="g7dt-code-block g7dt-text-red">
{JSON.stringify(selectedWarningData.capturedValue, null, 2)}
</pre>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">현재 값</div>
<pre className="g7dt-code-block g7dt-text-green">
{JSON.stringify(selectedWarningData.currentValue, null, 2)}
</pre>
</div>
</div>
<div>
<div className="g7dt-text-xs g7dt-text-muted">시간 차이</div>
<div className="g7dt-text-sm g7dt-text-white">
{selectedWarningData.timeDiff}ms
</div>
</div>
{selectedWarningData.suggestion && (
<div className="g7dt-bg-blue-dark g7dt-p-2 g7dt-rounded">
<div className="g7dt-text-xs g7dt-text-blue">💡 제안</div>
<div className="g7dt-text-sm g7dt-text-white g7dt-mt-1">
{selectedWarningData.suggestion}
</div>
</div>
)}
</div>
</div>
)}
</div>
);
};
export default StaleClosureTab;
@@ -0,0 +1,410 @@
/**
* 상태 탭 컴포넌트
*
* _global, _local, _computed, _isolated, $parent 상태를 트리 형태로 표시합니다.
* Computed 의존성 추적 기능 포함 (Phase 7).
*/
import React, { useState, useCallback, useEffect } from 'react';
import type { StateView, ComputedDependencyTrackingInfo, ComputedRecalcTrigger } from '../../types';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import { JsonTreeNode } from '../components/JsonTreeNode';
export interface StateTabProps {
state: StateView;
devTools?: G7DevToolsCore;
}
/**
* 상태 탭
*/
export const StateTab: React.FC<StateTabProps> = ({ state, devTools }) => {
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(
new Set(['_global', '_local', '_computed', '_isolated', '$parent'])
);
const [searchTerm, setSearchTerm] = useState('');
const [expandAll, setExpandAll] = useState(false);
const [showComputedTracking, setShowComputedTracking] = useState(false);
const [computedInfo, setComputedInfo] = useState<ComputedDependencyTrackingInfo | null>(null);
// Computed 추적 데이터 새로고침
const refreshComputedData = useCallback(() => {
if (devTools) {
setComputedInfo(devTools.getComputedDependencyTrackingInfo());
}
}, [devTools]);
// 주기적 갱신
useEffect(() => {
if (showComputedTracking && devTools) {
refreshComputedData();
const intervalId = setInterval(refreshComputedData, 2000);
return () => clearInterval(intervalId);
}
}, [showComputedTracking, devTools, refreshComputedData]);
// 트리거 아이콘
const getTriggerIcon = (trigger: ComputedRecalcTrigger) => {
switch (trigger) {
case 'state-change': return '📊';
case 'prop-change': return '📥';
case 'dependency-change': return '🔗';
case 'manual': return '👆';
case 'initial': return '🚀';
default: return '❓';
}
};
// 경로 토글
const handleToggle = useCallback((path: string) => {
setExpandedPaths(prev => {
const next = new Set(prev);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
return next;
});
}, []);
// 모든 경로 수집 (재귀)
const collectAllPaths = useCallback((obj: unknown, prefix: string): string[] => {
const paths: string[] = [prefix];
if (obj !== null && typeof obj === 'object') {
for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
paths.push(...collectAllPaths(value, `${prefix}.${key}`));
}
}
return paths;
}, []);
// 모두 펼치기/접기
const handleExpandAll = useCallback(() => {
if (expandAll) {
// 모두 접기 - 루트만 남김
setExpandedPaths(new Set(['_global', '_local', '_computed', '_isolated', '$parent']));
} else {
// 모두 펼치기
const allPaths = new Set<string>();
collectAllPaths(state._global, '_global').forEach(p => allPaths.add(p));
collectAllPaths(state._local, '_local').forEach(p => allPaths.add(p));
collectAllPaths(state._computed, '_computed').forEach(p => allPaths.add(p));
collectAllPaths(state._isolated, '_isolated').forEach(p => allPaths.add(p));
if (state.$parent) {
collectAllPaths(state.$parent, '$parent').forEach(p => allPaths.add(p));
}
setExpandedPaths(allPaths);
}
setExpandAll(!expandAll);
}, [expandAll, state, collectAllPaths]);
// 섹션별 키 개수
const globalCount = Object.keys(state._global || {}).length;
const localCount = Object.keys(state._local || {}).length;
const computedCount = Object.keys(state._computed || {}).length;
const isolatedCount = Object.keys(state._isolated || {}).length;
const parentCount = Object.keys(state.$parent || {}).length;
return (
<div className="g7dt-space-y-4">
{/* 검색 및 컨트롤 */}
<div className="g7dt-flex g7dt-gap-2 g7dt-items-center g7dt-flex-shrink-0">
<input
type="text"
placeholder="키 또는 값 검색..."
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
className="g7dt-input g7dt-flex-1"
/>
<button onClick={handleExpandAll} className="g7dt-btn g7dt-bg-gray-700">
{expandAll ? '모두 접기' : '모두 펼치기'}
</button>
</div>
{/* 타입 범례 */}
<div className="g7dt-flex g7dt-gap-3 g7dt-text-xs g7dt-text-gray g7dt-flex-wrap g7dt-flex-shrink-0">
<span>
<span className="g7dt-text-yellow">●</span> string
</span>
<span>
<span className="g7dt-text-cyan">●</span> number
</span>
<span>
<span className="g7dt-text-pink">●</span> boolean
</span>
<span>
<span className="g7dt-text-gray">●</span> null
</span>
<span>
<span className="g7dt-text-orange">●</span> array
</span>
<span>
<span className="g7dt-text-blue">●</span> object
</span>
</div>
{/* 상태 트리 - flex로 남은 공간 채움 */}
<div
className="g7dt-bg-gray-800 g7dt-rounded g7dt-p-2 g7dt-overflow-auto g7dt-border"
style={{ flex: 1, minHeight: 0 }}
>
{/* _global 섹션 */}
<div className="g7dt-mb-2">
<div
className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-1 g7dt-cursor-pointer"
onClick={() => handleToggle('_global')}
>
<span>{expandedPaths.has('_global') ? '▼' : '▶'}</span>
<span>_global</span>
<span className="g7dt-text-gray g7dt-text-xs" style={{ fontWeight: 'normal' }}>
({globalCount}개 키)
</span>
</div>
{expandedPaths.has('_global') && (
<div className="g7dt-ml-2 g7dt-border-l">
{Object.entries(state._global || {}).map(([key, value]) => (
<JsonTreeNode
key={`_global.${key}`}
keyName={key}
value={value}
path={`_global.${key}`}
expandedPaths={expandedPaths}
onToggle={handleToggle}
searchTerm={searchTerm}
/>
))}
</div>
)}
</div>
{/* _local 섹션 */}
<div className="g7dt-mb-2">
<div
className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-1 g7dt-cursor-pointer"
onClick={() => handleToggle('_local')}
>
<span>{expandedPaths.has('_local') ? '▼' : '▶'}</span>
<span>_local</span>
<span className="g7dt-text-gray g7dt-text-xs" style={{ fontWeight: 'normal' }}>
({localCount}개 키)
</span>
</div>
{expandedPaths.has('_local') && (
<div className="g7dt-ml-2 g7dt-border-l">
{Object.entries(state._local || {}).map(([key, value]) => (
<JsonTreeNode
key={`_local.${key}`}
keyName={key}
value={value}
path={`_local.${key}`}
expandedPaths={expandedPaths}
onToggle={handleToggle}
searchTerm={searchTerm}
/>
))}
</div>
)}
</div>
{/* _computed 섹션 */}
<div className="g7dt-mb-2">
<div
className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-1 g7dt-cursor-pointer"
onClick={() => handleToggle('_computed')}
>
<span>{expandedPaths.has('_computed') ? '▼' : '▶'}</span>
<span>_computed</span>
<span className="g7dt-text-gray g7dt-text-xs" style={{ fontWeight: 'normal' }}>
({computedCount}개 키)
</span>
</div>
{expandedPaths.has('_computed') && (
<div className="g7dt-ml-2 g7dt-border-l">
{Object.entries(state._computed || {}).map(([key, value]) => (
<JsonTreeNode
key={`_computed.${key}`}
keyName={key}
value={value}
path={`_computed.${key}`}
expandedPaths={expandedPaths}
onToggle={handleToggle}
searchTerm={searchTerm}
/>
))}
</div>
)}
</div>
{/* _isolated 섹션 (격리된 상태) */}
{isolatedCount > 0 && (
<div>
<div
className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-orange g7dt-mb-1 g7dt-cursor-pointer"
onClick={() => handleToggle('_isolated')}
>
<span>{expandedPaths.has('_isolated') ? '▼' : '▶'}</span>
<span>_isolated</span>
<span className="g7dt-text-gray g7dt-text-xs" style={{ fontWeight: 'normal' }}>
({isolatedCount}개 스코프)
</span>
</div>
{expandedPaths.has('_isolated') && (
<div className="g7dt-ml-2 g7dt-border-l">
{Object.entries(state._isolated || {}).map(([scopeId, scopeState]) => (
<JsonTreeNode
key={`_isolated.${scopeId}`}
keyName={scopeId}
value={scopeState}
path={`_isolated.${scopeId}`}
expandedPaths={expandedPaths}
onToggle={handleToggle}
searchTerm={searchTerm}
/>
))}
</div>
)}
</div>
)}
{/* $parent 섹션 (부모 컨텍스트 - 모달에서 사용) */}
{parentCount > 0 && (
<div>
<div
className="g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-1 g7dt-cursor-pointer"
onClick={() => handleToggle('$parent')}
>
<span>{expandedPaths.has('$parent') ? '▼' : '▶'}</span>
<span>$parent</span>
<span className="g7dt-text-gray g7dt-text-xs" style={{ fontWeight: 'normal' }}>
({parentCount}개 키)
</span>
</div>
{expandedPaths.has('$parent') && (
<div className="g7dt-ml-2 g7dt-border-l">
{Object.entries(state.$parent || {}).map(([key, value]) => (
<JsonTreeNode
key={`$parent.${key}`}
keyName={key}
value={value}
path={`$parent.${key}`}
expandedPaths={expandedPaths}
onToggle={handleToggle}
searchTerm={searchTerm}
/>
))}
</div>
)}
</div>
)}
</div>
{/* Computed 추적 토글 */}
{devTools && (
<div className="g7dt-flex g7dt-justify-end g7dt-mt-2">
<button
onClick={() => setShowComputedTracking(!showComputedTracking)}
className={`g7dt-tab-button ${showComputedTracking ? 'g7dt-tab-active' : ''}`}
>
🧮 Computed 추적
</button>
</div>
)}
{/* Computed 추적 섹션 */}
{showComputedTracking && computedInfo && (
<div className="g7dt-card g7dt-mt-2">
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-3">
Computed 의존성 추적 ({computedInfo.properties.length}개)
</h3>
{/* 통계 */}
<div className="g7dt-stats-grid g7dt-mb-3">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-purple">
{computedInfo.stats.totalComputed}
</div>
<div className="g7dt-stat-label">Computed</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-blue">
{computedInfo.stats.totalRecalculations}
</div>
<div className="g7dt-stat-label">재계산</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-yellow">
{computedInfo.stats.unnecessaryRecalculations}
</div>
<div className="g7dt-stat-label">불필요</div>
</div>
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-green">
{computedInfo.stats.avgComputationTime.toFixed(1)}ms
</div>
<div className="g7dt-stat-label">평균시간</div>
</div>
</div>
{/* 순환 의존성 경고 */}
{computedInfo.stats.cycleDetectionCount > 0 && (
<div className="g7dt-text-xs g7dt-text-red g7dt-mb-3 g7dt-p-2 g7dt-bg-red-900 g7dt-rounded">
⚠️ 순환 의존성 감지: {computedInfo.stats.cycleDetectionCount}건
</div>
)}
{/* 자주 재계산되는 속성 */}
{computedInfo.stats.topRecalculated.length > 0 && (
<div className="g7dt-mb-3">
<div className="g7dt-text-xs g7dt-text-muted g7dt-mb-2">자주 재계산되는 속성</div>
<div className="g7dt-space-y-1">
{computedInfo.stats.topRecalculated.slice(0, 3).map((item, idx) => (
<div key={idx} className="g7dt-flex g7dt-justify-between g7dt-text-xs">
<span className="g7dt-text-purple g7dt-font-mono">{item.name}</span>
<span className="g7dt-text-muted">{item.count}회</span>
</div>
))}
</div>
</div>
)}
{/* 재계산 로그 */}
{computedInfo.recalcLogs.length === 0 ? (
<div className="g7dt-empty-state">재계산 로그가 없습니다</div>
) : (
<div className="g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto">
{computedInfo.recalcLogs.slice().reverse().slice(0, 20).map((log) => (
<div
key={log.id}
className={`g7dt-list-item ${!log.valueChanged ? 'g7dt-border-yellow' : ''}`}
>
<div className="g7dt-flex g7dt-items-center g7dt-gap-2">
<span>{getTriggerIcon(log.trigger)}</span>
<span className="g7dt-text-xs g7dt-text-purple g7dt-font-mono">
{log.computedName}
</span>
{!log.valueChanged && (
<span className="g7dt-badge g7dt-text-xs g7dt-text-yellow">
값 변경 없음
</span>
)}
<span className="g7dt-text-xs g7dt-text-muted g7dt-ml-auto">
{log.computationTime.toFixed(1)}ms
</span>
</div>
{log.triggeredBy && (
<div className="g7dt-text-xs g7dt-text-muted g7dt-mt-1">
트리거: <span className="g7dt-text-blue">{log.triggeredBy.path}</span>
</div>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
);
};
export default StateTab;
@@ -0,0 +1,207 @@
/**
* 스타일 검증 탭 컴포넌트
*
* CSS 스타일 이슈를 감지하고 표시합니다.
*/
import React, { useState, useEffect, useCallback } from 'react';
import { G7DevToolsCore } from '../../G7DevToolsCore';
import type { StyleValidationInfo } from '../../types';
export interface StylesTabProps {
devTools: G7DevToolsCore;
}
/**
* 스타일 검증 탭
*/
export const StylesTab: React.FC<StylesTabProps> = ({ devTools }) => {
const [styleInfo, setStyleInfo] = useState<StyleValidationInfo | null>(null);
const [selectedIssue, setSelectedIssue] = useState<string | null>(null);
const [typeFilter, setTypeFilter] = useState<string>('all');
// 데이터 새로고침
const refreshData = useCallback(() => {
setStyleInfo(devTools.getStyleValidationInfo());
}, [devTools]);
// 주기적 갱신
useEffect(() => {
refreshData();
const intervalId = setInterval(refreshData, 2000);
return () => clearInterval(intervalId);
}, [refreshData]);
if (!styleInfo) {
return <div className="g7dt-empty-state">로딩 중...</div>;
}
// 필터링된 이슈
const filteredIssues = styleInfo.issues.filter(issue => {
if (typeFilter === 'all') return true;
return issue.type === typeFilter;
});
// 선택된 이슈
const selectedIssueData = selectedIssue
? styleInfo.issues.find(i => i.componentId === selectedIssue)
: null;
const stats = styleInfo.stats;
return (
<div className="g7dt-space-y-4">
{/* 통계 */}
<div className="g7dt-stats-grid">
<div className="g7dt-stat-card">
<div className="g7dt-stat-value g7dt-text-blue">
{stats.totalComponents}
</div>
<div className="g7dt-stat-label">총 컴포넌트</div>
</div>
<div className="g7dt-stat-card">
<div className={`g7dt-stat-value ${stats.invisibleCount > 0 ? 'g7dt-text-red' : 'g7dt-text-green'}`}>
{stats.invisibleCount}
</div>
<div className="g7dt-stat-label">숨겨진 요소</div>
</div>
<div className="g7dt-stat-card">
<div className={`g7dt-stat-value ${stats.tailwindIssueCount > 0 ? 'g7dt-text-yellow' : 'g7dt-text-green'}`}>
{stats.tailwindIssueCount}
</div>
<div className="g7dt-stat-label">Tailwind 이슈</div>
</div>
<div className="g7dt-stat-card">
<div className={`g7dt-stat-value ${stats.darkModeIssueCount > 0 ? 'g7dt-text-purple' : 'g7dt-text-green'}`}>
{stats.darkModeIssueCount}
</div>
<div className="g7dt-stat-label">다크모드 이슈</div>
</div>
</div>
{/* 필터 */}
<div className="g7dt-flex g7dt-gap-2">
<select
value={typeFilter}
onChange={e => setTypeFilter(e.target.value)}
className="g7dt-select"
>
<option value="all">모든 이슈</option>
<option value="invisible-element">숨겨진 요소</option>
<option value="tailwind-purging">Tailwind 퍼징</option>
<option value="dark-mode-missing">다크모드 누락</option>
</select>
<button
onClick={refreshData}
className="g7dt-btn-secondary"
>
새로고침
</button>
</div>
{/* 이슈 목록 */}
<div className="g7dt-scroll-list">
{filteredIssues.length === 0 ? (
<div className="g7dt-empty-state">
{styleInfo.issues.length === 0 ? '스타일 이슈가 없습니다 ✓' : '필터에 맞는 이슈가 없습니다'}
</div>
) : (
filteredIssues.map(issue => {
const icon = issue.type === 'invisible-element' ? '👁️' :
issue.type === 'tailwind-purging' ? '🎨' : '🌙';
const severityClass = issue.severity === 'error' ? 'g7dt-severity-error' :
issue.severity === 'warning' ? 'g7dt-severity-warning' : 'g7dt-severity-info';
return (
<div
key={issue.componentId}
onClick={() => setSelectedIssue(issue.componentId)}
className={`g7dt-style-issue-item ${severityClass} ${
selectedIssue === issue.componentId ? 'g7dt-selected' : ''
}`}
>
<div className="g7dt-flex g7dt-justify-between g7dt-items-center">
<span className="g7dt-mono g7dt-text-blue">
{icon} {issue.componentName}
</span>
<span className={
issue.severity === 'error' ? 'g7dt-badge-error' :
issue.severity === 'warning' ? 'g7dt-badge-warning' :
'g7dt-badge-info'
}>
{issue.type}
</span>
</div>
<div className="g7dt-text-muted g7dt-mt-1 g7dt-truncate">{issue.description}</div>
</div>
);
})
)}
</div>
{/* 선택된 이슈 상세 */}
{selectedIssueData && (
<div className="g7dt-card">
<div className="g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2">
<h3 className="g7dt-text-sm g7dt-font-bold">{selectedIssueData.componentName}</h3>
<button
onClick={() => setSelectedIssue(null)}
className="g7dt-close-btn"
>
✕
</button>
</div>
<div className="g7dt-space-y-2 g7dt-text-xs">
<div>
<span className="g7dt-text-muted">이슈 타입:</span>
<span className="g7dt-ml-2 g7dt-text-yellow">{selectedIssueData.type}</span>
</div>
<div>
<span className="g7dt-text-muted">설명:</span>
<div className="g7dt-mt-1 g7dt-text-white">{selectedIssueData.description}</div>
</div>
<div>
<span className="g7dt-text-muted">CSS 속성:</span>
<span className="g7dt-ml-2 g7dt-text-purple">{selectedIssueData.property}</span>
<span className="g7dt-ml-2 g7dt-text-muted">= {selectedIssueData.currentValue}</span>
{selectedIssueData.expectedValue && (
<span className="g7dt-ml-2 g7dt-text-green">(예상: {selectedIssueData.expectedValue})</span>
)}
</div>
{selectedIssueData.suggestion && (
<div>
<span className="g7dt-text-muted">해결 방법:</span>
<div className="g7dt-mt-1 g7dt-text-green">{selectedIssueData.suggestion}</div>
</div>
)}
</div>
</div>
)}
{/* 컴포넌트 스타일 정보 */}
{styleInfo.componentStyles.length > 0 && (
<div>
<h3 className="g7dt-text-sm g7dt-font-bold g7dt-mb-2">컴포넌트 스타일 ({styleInfo.componentStyles.length})</h3>
<div className="g7dt-scroll-list-sm">
{styleInfo.componentStyles.slice(0, 20).map((comp, i) => (
<div key={i} className="g7dt-list-item">
<div className="g7dt-flex g7dt-justify-between">
<span className="g7dt-text-blue">{comp.componentName}</span>
<span className="g7dt-text-muted">{comp.classes.length} classes</span>
</div>
{comp.classes.length > 0 && (
<div className="g7dt-text-muted g7dt-mt-1 g7dt-truncate">
{comp.classes.slice(0, 5).join(' ')}
{comp.classes.length > 5 && '...'}
</div>
)}
</div>
))}
</div>
</div>
)}
</div>
);
};
export default StylesTab;
@@ -0,0 +1,27 @@
/**
* G7 DevTools 탭 컴포넌트 내보내기
*/
export { StateTab } from './StateTab';
export { ActionsTab } from './ActionsTab';
export { CacheTab } from './CacheTab';
export { DiagnoseTab } from './DiagnoseTab';
export { PerformanceTab } from './PerformanceTab';
export { LifecycleTab } from './LifecycleTab';
export { NetworkTab } from './NetworkTab';
export { FormTab } from './FormTab';
export { ConditionalTab } from './ConditionalTab';
export { ExpressionTab } from './ExpressionTab';
export { HandlersTab } from './HandlersTab';
export { EventsTab } from './EventsTab';
export { DataSourcesTab } from './DataSourcesTab';
export { RendersTab } from './RendersTab';
export { StylesTab } from './StylesTab';
export { AuthTab } from './AuthTab';
export { LogsTab } from './LogsTab';
export { LayoutTab } from './LayoutTab';
export { ChangeDetectionTab } from './ChangeDetectionTab';
export { StaleClosureTab } from './StaleClosureTab';
export { NestedContextTab } from './NestedContextTab';
export { ModalScopeTab } from './ModalScopeTab';
export { NamedActionsTab } from './NamedActionsTab';
+227
View File
@@ -0,0 +1,227 @@
/**
* G7 DevTools 유틸리티 함수
*
* DevToolsPanel에서 사용되는 공통 유틸리티 함수들을 정의합니다.
*/
import { STORAGE_KEY, StoredPanelConfig } from './constants';
/**
* JSON 값의 타입에 따른 색상 클래스 반환
*
* @param value - 색상을 결정할 값
* @returns CSS 클래스 이름
*/
export const getValueColor = (value: unknown): string => {
if (value === null) return 'g7dt-text-gray';
if (value === undefined) return 'g7dt-text-gray';
if (typeof value === 'string') return 'g7dt-text-yellow';
if (typeof value === 'number') return 'g7dt-text-cyan';
if (typeof value === 'boolean') return 'g7dt-text-pink';
if (Array.isArray(value)) return 'g7dt-text-orange';
if (typeof value === 'object') return 'g7dt-text-blue';
return 'g7dt-text-white';
};
/**
* JSON 값의 타입 라벨 반환
*
* @param value - 타입 라벨을 반환할 값
* @returns 타입 라벨 문자열
*/
export const getTypeLabel = (value: unknown): string => {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
if (Array.isArray(value)) return `Array(${value.length})`;
if (typeof value === 'object') return `Object(${Object.keys(value).length})`;
return typeof value;
};
/**
* 값을 표시용 문자열로 변환
*
* @param value - 변환할 값
* @returns 표시용 문자열
*/
export const formatValue = (value: unknown): string => {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
if (typeof value === 'string') {
// 긴 문자열은 줄임
if (value.length > 50) {
return `"${value.substring(0, 50)}..."`;
}
return `"${value}"`;
}
if (typeof value === 'boolean') return value ? 'true' : 'false';
if (typeof value === 'number') return String(value);
return '';
};
/**
* 타임스탬프를 포맷팅된 문자열로 변환
*
* @param timestamp - 타임스탬프 (밀리초)
* @returns 포맷팅된 시간 문자열 (HH:MM:SS.mmm)
*/
export const formatTimestamp = (timestamp: number): string => {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const ms = date.getMilliseconds().toString().padStart(3, '0');
return `${hours}:${minutes}:${seconds}.${ms}`;
};
/**
* 로컬스토리지에서 패널 설정 로드
*
* @returns 저장된 패널 설정 (부분적)
*/
export const loadPanelConfig = (): Partial<StoredPanelConfig> => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
return JSON.parse(stored);
}
} catch (e) {
console.warn('[G7DevTools] 설정 로드 실패:', e);
}
return {};
};
/**
* 로컬스토리지에 패널 설정 저장
*
* @param config - 저장할 설정 (부분적)
*/
export const savePanelConfig = (config: Partial<StoredPanelConfig>): void => {
try {
const current = loadPanelConfig();
const merged = { ...current, ...config };
localStorage.setItem(STORAGE_KEY, JSON.stringify(merged));
} catch (e) {
console.warn('[G7DevTools] 설정 저장 실패:', e);
}
};
/**
* 바이트 크기를 읽기 쉬운 형식으로 변환
*
* @param bytes - 바이트 크기
* @returns 포맷팅된 크기 문자열
*/
export const formatBytes = (bytes: number): string => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
/**
* 경과 시간을 읽기 쉬운 형식으로 변환
*
* @param ms - 밀리초
* @returns 포맷팅된 시간 문자열
*/
export const formatDuration = (ms: number): string => {
if (ms < 1) return `${(ms * 1000).toFixed(0)}μs`;
if (ms < 1000) return `${ms.toFixed(1)}ms`;
if (ms < 60000) return `${(ms / 1000).toFixed(2)}s`;
return `${(ms / 60000).toFixed(2)}m`;
};
/**
* 상태 뱃지 색상 클래스 반환
*
* @param status - 상태 문자열
* @returns CSS 클래스 이름
*/
export const getStatusBadgeClass = (status: string): string => {
const statusMap: Record<string, string> = {
success: 'g7dt-badge-success',
completed: 'g7dt-badge-success',
done: 'g7dt-badge-success',
error: 'g7dt-badge-error',
failed: 'g7dt-badge-error',
warning: 'g7dt-badge-warning',
pending: 'g7dt-badge-pending',
loading: 'g7dt-badge-loading',
idle: 'g7dt-badge-idle',
};
return statusMap[status.toLowerCase()] || 'g7dt-badge-default';
};
/**
* 객체를 안전하게 JSON 문자열로 변환
*
* @param obj - 변환할 객체
* @param indent - 들여쓰기 (기본: 2)
* @returns JSON 문자열
*/
export const safeStringify = (obj: unknown, indent: number = 2): string => {
try {
const seen = new WeakSet();
return JSON.stringify(
obj,
(key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
if (typeof value === 'function') {
return '[Function]';
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack,
};
}
return value;
},
indent
);
} catch (e) {
return '[Stringify Error]';
}
};
/**
* 깊은 객체에서 경로로 값 가져오기
*
* @param obj - 대상 객체
* @param path - 점으로 구분된 경로 (예: "user.profile.name")
* @param defaultValue - 기본값
* @returns 경로에 해당하는 값 또는 기본값
*/
export const getValueByPath = (obj: unknown, path: string, defaultValue: unknown = undefined): unknown => {
if (!obj || typeof obj !== 'object') return defaultValue;
const keys = path.split('.');
let current: unknown = obj;
for (const key of keys) {
if (current === null || current === undefined) return defaultValue;
if (typeof current !== 'object') return defaultValue;
current = (current as Record<string, unknown>)[key];
}
return current ?? defaultValue;
};
/**
* 문자열을 잘라서 말줄임표 추가
*
* @param str - 원본 문자열
* @param maxLength - 최대 길이
* @returns 잘린 문자열
*/
export const truncate = (str: string, maxLength: number): string => {
if (str.length <= maxLength) return str;
return str.substring(0, maxLength - 3) + '...';
};
@@ -0,0 +1,348 @@
/**
* ErrorHandlingResolver.ts
*
* 계층적 에러 핸들링 설정을 해석하고 실행하는 클래스
*
* 우선순위:
* 1. 액션/데이터소스 errorHandling[코드]
* 2. 액션/데이터소스 errorHandling[default]
* 3. 액션/데이터소스 onError
* 4. 레이아웃 errorHandling[코드]
* 5. 레이아웃 errorHandling[default]
* 6. 템플릿 errorHandling[코드]
* 7. 템플릿 errorHandling[default]
* 8. 시스템 기본값
*
* @module ErrorHandlingResolver
*/
import type {
ErrorCode,
ErrorContext,
ErrorHandlerConfig,
ErrorHandlingLevel,
ErrorHandlingMap,
ErrorHandlingResult,
ErrorHandlingSource,
OnErrorHandler,
} from '../types/ErrorHandling';
import {
DEFAULT_ERROR_HANDLING,
ErrorHandlingUtils,
} from '../types/ErrorHandling';
import { createLogger } from '../utils/Logger';
const logger = createLogger('ErrorHandlingResolver');
/**
* 에러 핸들링 설정 해석기
*
* 계층별 에러 핸들링 설정을 관리하고, 에러 코드에 맞는 핸들러를 결정합니다.
*
* @example
* ```ts
* const resolver = ErrorHandlingResolver.getInstance();
*
* // 템플릿/레이아웃 설정 등록
* resolver.setTemplateConfig(templateErrorHandling);
* resolver.setLayoutConfig(layoutErrorHandling);
*
* // 에러 발생 시 핸들러 찾기
* const result = resolver.resolve(403, {
* errorHandling: actionErrorHandling,
* onError: actionOnError,
* });
*
* if (result.handler) {
* await resolver.executeHandler(result.handler, errorContext);
* }
* ```
*/
export class ErrorHandlingResolver {
/** 싱글톤 인스턴스 */
private static instance: ErrorHandlingResolver | null = null;
/** 템플릿 레벨 에러 핸들링 설정 */
private templateErrorHandling: ErrorHandlingMap | null = null;
/** 레이아웃 레벨 에러 핸들링 설정 */
private layoutErrorHandling: ErrorHandlingMap | null = null;
/** 액션 실행 함수 (ActionDispatcher.dispatchAction) */
private executeAction: ((handler: ErrorHandlerConfig, errorContext: any) => Promise<any>) | null = null;
private constructor() {}
/**
* 싱글톤 인스턴스를 반환합니다.
*/
static getInstance(): ErrorHandlingResolver {
if (!ErrorHandlingResolver.instance) {
ErrorHandlingResolver.instance = new ErrorHandlingResolver();
}
return ErrorHandlingResolver.instance;
}
/**
* 싱글톤 인스턴스를 초기화합니다. (테스트용)
*/
static resetInstance(): void {
ErrorHandlingResolver.instance = null;
}
/**
* 템플릿 레벨 에러 핸들링 설정을 등록합니다.
*
* @param config 템플릿의 errorHandling 설정
*/
setTemplateConfig(config: ErrorHandlingMap | null): void {
this.templateErrorHandling = config;
logger.log('Template config set:', config);
}
/**
* 레이아웃 레벨 에러 핸들링 설정을 등록합니다.
*
* @param config 레이아웃의 errorHandling 설정
*/
setLayoutConfig(config: ErrorHandlingMap | null): void {
this.layoutErrorHandling = config;
logger.log('Layout config set:', config);
}
/**
* 액션 실행 함수를 설정합니다.
*
* ActionDispatcher.dispatchAction을 주입받아 핸들러를 실행합니다.
*
* @param executor 액션 실행 함수
*/
setActionExecutor(
executor: (handler: ErrorHandlerConfig, errorContext: any) => Promise<any>
): void {
this.executeAction = executor;
}
/**
* 에러 코드에 맞는 핸들러를 결정합니다.
*
* @param errorCode HTTP 에러 코드
* @param options 액션/데이터소스 레벨 설정
* @returns 핸들러 결정 결과
*/
resolve(
errorCode: number,
options: {
errorHandling?: ErrorHandlingMap;
onError?: OnErrorHandler;
} = {}
): ErrorHandlingResult {
const { errorHandling, onError } = options;
logger.log('Resolving error:', errorCode, {
hasActionErrorHandling: !!errorHandling,
hasActionOnError: !!onError,
hasLayoutConfig: !!this.layoutErrorHandling,
hasTemplateConfig: !!this.templateErrorHandling,
});
// 1. 액션/데이터소스 errorHandling[코드] 확인
let handler = ErrorHandlingUtils.findHandler(errorHandling, errorCode);
if (handler) {
const matchedKey = this.getMatchedKey(errorHandling!, errorCode);
return {
handler: ErrorHandlingUtils.injectErrorCode(handler, matchedKey, errorCode),
level: 'action',
matchedKey,
};
}
// 2. 액션/데이터소스 onError 확인
if (onError) {
const normalizedOnError = ErrorHandlingUtils.normalizeOnError(onError);
if (normalizedOnError.length > 0) {
// onError가 배열인 경우 sequence로 래핑
const sequenceHandler: ErrorHandlerConfig =
normalizedOnError.length === 1
? normalizedOnError[0]
: {
handler: 'sequence',
actions: normalizedOnError as any,
};
return {
handler: sequenceHandler,
level: 'action',
matchedKey: 'onError',
};
}
}
// 3. 레이아웃 errorHandling 확인
handler = ErrorHandlingUtils.findHandler(this.layoutErrorHandling || undefined, errorCode);
if (handler) {
const matchedKey = this.getMatchedKey(this.layoutErrorHandling!, errorCode);
return {
handler: ErrorHandlingUtils.injectErrorCode(handler, matchedKey, errorCode),
level: 'layout',
matchedKey,
};
}
// 4. 템플릿 errorHandling 확인
handler = ErrorHandlingUtils.findHandler(this.templateErrorHandling || undefined, errorCode);
if (handler) {
const matchedKey = this.getMatchedKey(this.templateErrorHandling!, errorCode);
return {
handler: ErrorHandlingUtils.injectErrorCode(handler, matchedKey, errorCode),
level: 'template',
matchedKey,
};
}
// 5. 시스템 기본값
handler = ErrorHandlingUtils.findHandler(DEFAULT_ERROR_HANDLING, errorCode);
if (handler) {
const matchedKey = this.getMatchedKey(DEFAULT_ERROR_HANDLING, errorCode);
return {
handler: ErrorHandlingUtils.injectErrorCode(handler, matchedKey, errorCode),
level: 'system',
matchedKey,
};
}
// 핸들러를 찾지 못함
return {
handler: null,
level: null,
matchedKey: null,
};
}
/**
* 에러 핸들러를 실행합니다.
*
* @param handler 실행할 핸들러 설정
* @param errorContext 에러 컨텍스트
* @returns 실행 결과
*/
async execute(
handler: ErrorHandlerConfig,
errorContext: ErrorContext
): Promise<any> {
if (!this.executeAction) {
logger.error('Action executor is not set');
return;
}
logger.log('Executing handler:', handler.handler, {
errorContext,
});
try {
return await this.executeAction(handler, { error: errorContext });
} catch (error) {
logger.error('Failed to execute handler:', error);
throw error;
}
}
/**
* 에러 코드에 맞는 핸들러를 찾아 실행합니다.
*
* resolve()와 execute()를 한 번에 수행합니다.
*
* @param errorCode HTTP 에러 코드
* @param errorContext 에러 컨텍스트
* @param options 액션/데이터소스 레벨 설정
* @returns 실행 결과
*/
async resolveAndExecute(
errorCode: number,
errorContext: ErrorContext,
options: {
errorHandling?: ErrorHandlingMap;
onError?: OnErrorHandler;
} = {}
): Promise<{ handled: boolean; result?: any }> {
const result = this.resolve(errorCode, options);
logger.log('Resolve result:', {
errorCode,
handler: result.handler?.handler,
level: result.level,
matchedKey: result.matchedKey,
});
if (!result.handler) {
logger.warn('No handler found for error:', errorCode);
return { handled: false };
}
try {
const execResult = await this.execute(result.handler, errorContext);
return { handled: true, result: execResult };
} catch (error) {
logger.error('Handler execution failed:', error);
return { handled: false };
}
}
/**
* 에러 핸들링 맵에서 매칭된 키를 반환합니다.
*/
private getMatchedKey(
errorHandling: ErrorHandlingMap,
errorCode: number
): ErrorCode {
if (errorHandling[errorCode]) {
return errorCode;
}
if (errorHandling[String(errorCode)]) {
return String(errorCode);
}
return 'default';
}
/**
* 현재 설정을 초기화합니다.
*
* 레이아웃 변경 시 호출하여 이전 설정을 제거합니다.
*/
clearLayoutConfig(): void {
this.layoutErrorHandling = null;
logger.log('Layout config cleared');
}
/**
* 모든 설정을 초기화합니다.
*
* 템플릿 변경 시 호출하여 모든 설정을 제거합니다.
*/
clearAllConfig(): void {
this.templateErrorHandling = null;
this.layoutErrorHandling = null;
logger.log('All config cleared');
}
/**
* 현재 설정 상태를 반환합니다. (디버그용)
*/
getConfigStatus(): {
hasTemplate: boolean;
hasLayout: boolean;
hasExecutor: boolean;
} {
return {
hasTemplate: this.templateErrorHandling !== null,
hasLayout: this.layoutErrorHandling !== null,
hasExecutor: this.executeAction !== null,
};
}
}
/**
* ErrorHandlingResolver 싱글톤 인스턴스를 반환합니다.
*/
export function getErrorHandlingResolver(): ErrorHandlingResolver {
return ErrorHandlingResolver.getInstance();
}
@@ -0,0 +1,517 @@
/**
* ErrorHandlingResolver 테스트
*
* 계층적 에러 핸들링 설정 해석 및 실행 테스트
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { ErrorHandlingResolver, getErrorHandlingResolver } from '../ErrorHandlingResolver';
import type { ErrorHandlingMap, ErrorHandlerConfig, ErrorContext } from '../../types/ErrorHandling';
import { Logger } from '../../utils/Logger';
describe('ErrorHandlingResolver', () => {
beforeEach(() => {
// 각 테스트 전에 싱글톤 인스턴스 초기화
ErrorHandlingResolver.resetInstance();
// Logger 디버그 모드 활성화
Logger.getInstance().setDebug(true);
});
afterEach(() => {
// Logger 디버그 모드 비활성화
Logger.getInstance().setDebug(false);
});
describe('싱글톤 패턴', () => {
it('getInstance()는 동일한 인스턴스를 반환해야 함', () => {
const instance1 = ErrorHandlingResolver.getInstance();
const instance2 = ErrorHandlingResolver.getInstance();
expect(instance1).toBe(instance2);
});
it('resetInstance() 후에는 새 인스턴스를 반환해야 함', () => {
const instance1 = ErrorHandlingResolver.getInstance();
ErrorHandlingResolver.resetInstance();
const instance2 = ErrorHandlingResolver.getInstance();
expect(instance1).not.toBe(instance2);
});
it('getErrorHandlingResolver()는 getInstance()와 동일한 결과를 반환해야 함', () => {
const instance1 = getErrorHandlingResolver();
const instance2 = ErrorHandlingResolver.getInstance();
expect(instance1).toBe(instance2);
});
});
describe('resolve() - 우선순위 테스트', () => {
let resolver: ErrorHandlingResolver;
beforeEach(() => {
resolver = ErrorHandlingResolver.getInstance();
});
it('액션 레벨 errorHandling[코드]가 최우선 순위', () => {
// 템플릿 설정
resolver.setTemplateConfig({
403: { handler: 'navigate', params: { path: '/template-403' } },
});
// 레이아웃 설정
resolver.setLayoutConfig({
403: { handler: 'toast', params: { message: 'layout 403' } },
});
// 액션 레벨 설정
const result = resolver.resolve(403, {
errorHandling: {
403: { handler: 'openModal', target: 'action_modal' },
},
});
expect(result.handler?.handler).toBe('openModal');
expect(result.handler?.target).toBe('action_modal'); // target도 검증
expect(result.level).toBe('action');
expect(result.matchedKey).toBe(403);
});
it('문자열 키로 정의된 errorHandling에서 target이 보존됨 (JSON 파싱 시나리오)', () => {
// JSON 파싱 결과를 시뮬레이션 (키가 문자열)
const jsonParsedErrorHandling: ErrorHandlingMap = {
'404': { handler: 'openModal', target: 'tempOrderNotFoundModal' },
};
const result = resolver.resolve(404, {
errorHandling: jsonParsedErrorHandling,
});
expect(result.handler?.handler).toBe('openModal');
expect(result.handler?.target).toBe('tempOrderNotFoundModal');
expect(result.level).toBe('action');
// 문자열 키 "404"로 매칭되므로 matchedKey는 404 (숫자) 또는 "404" (문자열)
expect([404, '404']).toContain(result.matchedKey);
});
it('액션 errorHandling에 코드가 없으면 default 사용', () => {
const result = resolver.resolve(500, {
errorHandling: {
403: { handler: 'openModal', target: 'modal' },
default: { handler: 'toast', params: { message: 'default error' } },
},
});
expect(result.handler?.handler).toBe('toast');
expect(result.level).toBe('action');
expect(result.matchedKey).toBe('default');
});
it('액션 errorHandling에 없으면 onError 사용', () => {
const result = resolver.resolve(500, {
errorHandling: {
403: { handler: 'openModal', target: 'modal' },
},
onError: { handler: 'toast', params: { message: 'onError fallback' } },
});
expect(result.handler?.handler).toBe('toast');
expect(result.level).toBe('action');
expect(result.matchedKey).toBe('onError');
});
it('onError가 배열이면 sequence로 래핑', () => {
const result = resolver.resolve(500, {
onError: [
{ handler: 'setState', params: { key: 'error', value: true } },
{ handler: 'toast', params: { message: 'error' } },
],
});
expect(result.handler?.handler).toBe('sequence');
expect(result.handler?.actions).toHaveLength(2);
expect(result.level).toBe('action');
});
it('액션 레벨에 없으면 레이아웃 설정 사용', () => {
resolver.setLayoutConfig({
403: { handler: 'toast', params: { message: 'layout 403' } },
});
const result = resolver.resolve(403, {
errorHandling: {
500: { handler: 'navigate', params: { path: '/500' } },
},
});
expect(result.handler?.handler).toBe('toast');
expect(result.level).toBe('layout');
expect(result.matchedKey).toBe(403);
});
it('레이아웃에도 없으면 템플릿 설정 사용', () => {
resolver.setTemplateConfig({
403: { handler: 'navigate', params: { path: '/template-403' } },
});
const result = resolver.resolve(403, {});
expect(result.handler?.handler).toBe('navigate');
expect(result.level).toBe('template');
expect(result.matchedKey).toBe(403);
});
it('모든 레벨에 없으면 시스템 기본값 사용', () => {
const result = resolver.resolve(403, {});
expect(result.handler?.handler).toBe('toast');
expect(result.level).toBe('system');
});
it('문자열 키와 숫자 키 모두 지원', () => {
resolver.setTemplateConfig({
'404': { handler: 'navigate', params: { path: '/404' } },
});
const result = resolver.resolve(404, {});
expect(result.handler?.handler).toBe('navigate');
// getMatchedKey는 숫자 키를 먼저 확인하므로 404 숫자 반환
// (errorHandling[404] 먼저 확인 → errorHandling['404'] 확인)
expect(result.matchedKey).toBe(404);
});
});
describe('showErrorPage 핸들러 errorCode 자동 주입', () => {
let resolver: ErrorHandlingResolver;
beforeEach(() => {
resolver = ErrorHandlingResolver.getInstance();
});
it('showErrorPage에 errorCode가 없으면 매칭된 키값으로 자동 주입', () => {
resolver.setTemplateConfig({
403: {
handler: 'showErrorPage',
params: { target: 'content' },
},
});
const result = resolver.resolve(403, {});
expect(result.handler?.handler).toBe('showErrorPage');
expect(result.handler?.params?.errorCode).toBe(403);
});
it('showErrorPage에 errorCode가 이미 있으면 그대로 유지', () => {
resolver.setTemplateConfig({
403: {
handler: 'showErrorPage',
params: { errorCode: 401, target: 'full' },
},
});
const result = resolver.resolve(403, {});
expect(result.handler?.handler).toBe('showErrorPage');
expect(result.handler?.params?.errorCode).toBe(401);
});
it('default 키로 매칭될 때는 실제 에러 코드(actualErrorCode)로 주입', () => {
resolver.setTemplateConfig({
default: {
handler: 'showErrorPage',
params: { target: 'content' },
},
});
const result = resolver.resolve(500, {});
// default 키로 매칭되었지만, actualErrorCode fallback으로 실제 에러 코드 주입
expect(result.handler?.handler).toBe('showErrorPage');
expect(result.matchedKey).toBe('default');
expect(result.handler?.params?.errorCode).toBe(500);
});
it('default 키로 매칭 + HTTP 403 에러 시 실제 에러 코드 403 주입', () => {
const result = resolver.resolve(403, {
errorHandling: {
default: {
handler: 'showErrorPage',
params: { target: 'content' },
},
},
});
expect(result.handler?.handler).toBe('showErrorPage');
expect(result.handler?.params?.errorCode).toBe(403);
expect(result.matchedKey).toBe('default');
});
});
describe('execute() - 핸들러 실행', () => {
let resolver: ErrorHandlingResolver;
let mockExecutor: ReturnType<typeof vi.fn>;
beforeEach(() => {
resolver = ErrorHandlingResolver.getInstance();
mockExecutor = vi.fn().mockResolvedValue({ success: true });
resolver.setActionExecutor(mockExecutor);
});
it('executeAction이 설정되지 않으면 에러 로그 출력', async () => {
ErrorHandlingResolver.resetInstance();
const newResolver = ErrorHandlingResolver.getInstance();
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const handler: ErrorHandlerConfig = {
handler: 'toast',
params: { message: 'test' },
};
await newResolver.execute(handler, { status: 500, message: 'error' });
expect(consoleSpy).toHaveBeenCalledWith(
'[ErrorHandlingResolver]',
'Action executor is not set'
);
consoleSpy.mockRestore();
});
it('핸들러 실행 시 executeAction 호출', async () => {
const handler: ErrorHandlerConfig = {
handler: 'toast',
params: { message: 'test error' },
};
const errorContext: ErrorContext = {
status: 500,
message: 'Internal Server Error',
};
await resolver.execute(handler, errorContext);
expect(mockExecutor).toHaveBeenCalledWith(handler, { error: errorContext });
});
it('openModal 핸들러 실행 시 target이 executor에 전달됨', async () => {
const handler: ErrorHandlerConfig = {
handler: 'openModal',
target: 'tempOrderNotFoundModal',
};
const errorContext: ErrorContext = {
status: 404,
message: 'Not Found',
};
await resolver.execute(handler, errorContext);
// executor가 target을 포함한 handler 객체를 받는지 확인
expect(mockExecutor).toHaveBeenCalledWith(
expect.objectContaining({
handler: 'openModal',
target: 'tempOrderNotFoundModal',
}),
{ error: errorContext }
);
});
it('executeAction 실패 시 에러 throw', async () => {
mockExecutor.mockRejectedValue(new Error('Execution failed'));
const handler: ErrorHandlerConfig = {
handler: 'toast',
params: { message: 'test' },
};
await expect(
resolver.execute(handler, { status: 500, message: 'error' })
).rejects.toThrow('Execution failed');
});
});
describe('resolveAndExecute() - 통합 테스트', () => {
let resolver: ErrorHandlingResolver;
let mockExecutor: ReturnType<typeof vi.fn>;
beforeEach(() => {
resolver = ErrorHandlingResolver.getInstance();
mockExecutor = vi.fn().mockResolvedValue({ success: true });
resolver.setActionExecutor(mockExecutor);
});
it('핸들러 찾아서 실행 후 handled: true 반환', async () => {
resolver.setTemplateConfig({
403: { handler: 'toast', params: { message: 'forbidden' } },
});
const result = await resolver.resolveAndExecute(
403,
{ status: 403, message: 'Forbidden' },
{}
);
expect(result.handled).toBe(true);
expect(mockExecutor).toHaveBeenCalled();
});
it('핸들러를 찾지 못하면 handled: false 반환', async () => {
// 모든 설정 초기화
resolver.clearAllConfig();
// 존재하지 않는 에러 코드 (시스템 기본값에도 없는)
// 참고: 시스템 기본값에 default가 있으므로 항상 핸들러를 찾음
// 이 테스트는 시스템 기본값을 우회할 수 없으므로 항상 handled: true
const result = await resolver.resolveAndExecute(
999,
{ status: 999, message: 'Unknown' },
{}
);
// 시스템 기본값의 default 핸들러가 적용됨
expect(result.handled).toBe(true);
});
it('실행 실패 시 handled: false 반환', async () => {
mockExecutor.mockRejectedValue(new Error('Execution failed'));
resolver.setTemplateConfig({
500: { handler: 'toast', params: { message: 'error' } },
});
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const result = await resolver.resolveAndExecute(
500,
{ status: 500, message: 'Server Error' },
{}
);
expect(result.handled).toBe(false);
consoleSpy.mockRestore();
});
});
describe('suppress 핸들러 - 에러 전파 방지 (engine-v1.21.0)', () => {
let resolver: ErrorHandlingResolver;
beforeEach(() => {
resolver = ErrorHandlingResolver.getInstance();
});
it('suppress 핸들러가 action 레벨로 resolve되어 상위 전파를 중단한다', () => {
// 레이아웃에 401 → showErrorPage 설정
resolver.setLayoutConfig({
401: { handler: 'showErrorPage', params: { errorCode: 401, target: 'content' } },
});
// 데이터소스 레벨에서 suppress로 전파 방지
const result = resolver.resolve(401, {
errorHandling: {
401: { handler: 'suppress' },
},
});
// suppress가 action 레벨로 resolve → 레이아웃 showErrorPage 미도달
expect(result.handler?.handler).toBe('suppress');
expect(result.level).toBe('action');
expect(result.matchedKey).toBe(401);
});
it('suppress가 없으면 레이아웃 레벨 errorHandling이 실행된다', () => {
// 레이아웃에 401 → showErrorPage 설정
resolver.setLayoutConfig({
401: { handler: 'showErrorPage', params: { errorCode: 401, target: 'content' } },
});
// 데이터소스 레벨에 errorHandling 없음 → 레이아웃으로 전파
const result = resolver.resolve(401, {});
expect(result.handler?.handler).toBe('showErrorPage');
expect(result.level).toBe('layout');
});
it('suppress를 default 키로 사용하면 모든 에러 코드의 전파를 방지한다', () => {
resolver.setLayoutConfig({
401: { handler: 'showErrorPage', params: { target: 'content' } },
403: { handler: 'showErrorPage', params: { target: 'content' } },
});
const result = resolver.resolve(403, {
errorHandling: {
default: { handler: 'suppress' },
},
});
expect(result.handler?.handler).toBe('suppress');
expect(result.level).toBe('action');
expect(result.matchedKey).toBe('default');
});
it('suppress와 다른 핸들러를 혼합 사용할 수 있다', () => {
resolver.setLayoutConfig({
401: { handler: 'showErrorPage', params: { target: 'content' } },
});
// 401은 suppress, 403은 showErrorPage
const errorHandling: ErrorHandlingMap = {
401: { handler: 'suppress' },
403: { handler: 'showErrorPage', params: { target: 'content' } },
};
const result401 = resolver.resolve(401, { errorHandling });
expect(result401.handler?.handler).toBe('suppress');
expect(result401.level).toBe('action');
const result403 = resolver.resolve(403, { errorHandling });
expect(result403.handler?.handler).toBe('showErrorPage');
expect(result403.level).toBe('action');
});
});
describe('설정 관리', () => {
let resolver: ErrorHandlingResolver;
beforeEach(() => {
resolver = ErrorHandlingResolver.getInstance();
});
it('clearLayoutConfig()은 레이아웃 설정만 초기화', () => {
resolver.setTemplateConfig({
403: { handler: 'toast', params: {} },
});
resolver.setLayoutConfig({
404: { handler: 'toast', params: {} },
});
resolver.clearLayoutConfig();
const status = resolver.getConfigStatus();
expect(status.hasTemplate).toBe(true);
expect(status.hasLayout).toBe(false);
});
it('clearAllConfig()은 모든 설정 초기화', () => {
resolver.setTemplateConfig({
403: { handler: 'toast', params: {} },
});
resolver.setLayoutConfig({
404: { handler: 'toast', params: {} },
});
resolver.clearAllConfig();
const status = resolver.getConfigStatus();
expect(status.hasTemplate).toBe(false);
expect(status.hasLayout).toBe(false);
});
it('getConfigStatus()는 현재 설정 상태 반환', () => {
const mockExecutor = vi.fn();
resolver.setActionExecutor(mockExecutor);
resolver.setTemplateConfig({ 403: { handler: 'toast', params: {} } });
const status = resolver.getConfigStatus();
expect(status.hasTemplate).toBe(true);
expect(status.hasLayout).toBe(false);
expect(status.hasExecutor).toBe(true);
});
});
});
+21
View File
@@ -0,0 +1,21 @@
/**
* 에러 핸들링 모듈
*
* 계층적 에러 핸들링 시스템을 제공합니다.
*
* @module error
*/
export { ErrorHandlingResolver, getErrorHandlingResolver } from './ErrorHandlingResolver';
export type {
ErrorCode,
ErrorContext,
ErrorHandlerConfig,
ErrorHandlingLevel,
ErrorHandlingMap,
ErrorHandlingResult,
ErrorHandlingSource,
OnErrorHandler,
ShowErrorPageParams,
} from '../types/ErrorHandling';
export { DEFAULT_ERROR_HANDLING, ErrorHandlingUtils } from '../types/ErrorHandling';
+17
View File
@@ -0,0 +1,17 @@
/**
* 그누보드7 템플릿 엔진 훅 모듈
*
* 템플릿 컴포넌트에서 사용할 수 있는 React 훅들을 제공합니다.
*
* @module hooks
*/
export { useActions, dispatchAction } from './useActions';
export type { ActionDefinition, ActionResult, DispatchFunction } from './useActions';
export {
useControllableState,
shallowArrayEqual,
shallowObjectEqual,
} from './useControllableState';
export type { UseControllableStateOptions } from './useControllableState';
+208
View File
@@ -0,0 +1,208 @@
/**
* useActions Hook
*
* 템플릿 컴포넌트에서 ActionDispatcher를 쉽게 사용할 수 있도록 하는 훅입니다.
* 레이아웃 JSON의 액션 정의와 동일한 형태로 액션을 실행할 수 있습니다.
*
* @example
* ```tsx
* import { useActions } from '@g7/core/hooks';
*
* const MyComponent = () => {
* const dispatch = useActions();
*
* const handleClick = () => {
* dispatch({
* handler: 'navigate',
* params: { path: '/admin/users/1/edit' }
* });
* };
*
* const handleDelete = async () => {
* await dispatch({
* handler: 'apiCall',
* target: '/api/admin/users/1',
* params: { method: 'DELETE' },
* onSuccess: [
* { handler: 'toast', params: { type: 'success', message: '삭제되었습니다' } },
* { handler: 'navigate', params: { path: '/admin/users' } }
* ]
* });
* };
* };
* ```
*
* @module hooks/useActions
*/
import { useCallback, useMemo } from 'react';
import { createLogger } from '../utils/Logger';
const logger = createLogger('useActions');
/**
* 액션 정의 인터페이스 (ActionDispatcher의 ActionDefinition과 동일)
*/
export interface ActionDefinition {
/** 액션 핸들러 이름 */
handler: string;
/** 액션 타겟 (URL, API 엔드포인트, 모달 ID 등) */
target?: string;
/** 액션 파라미터 */
params?: Record<string, any>;
/** 액션 성공 시 실행할 후속 액션 */
onSuccess?: ActionDefinition | ActionDefinition[];
/** 액션 실패 시 실행할 후속 액션 */
onError?: ActionDefinition | ActionDefinition[];
/** 확인 메시지 표시 여부 */
confirm?: string;
/** switch 핸들러용 케이스 정의 */
cases?: Record<string, ActionDefinition>;
/** 인증 필요 여부 (apiCall 핸들러에서 Bearer 토큰 포함 여부) */
auth_required?: boolean;
}
/**
* 액션 실행 결과
*/
export interface ActionResult {
success: boolean;
data?: any;
error?: Error;
}
/**
* dispatch 함수 타입
*/
export type DispatchFunction = (action: ActionDefinition) => Promise<ActionResult>;
/**
* TemplateApp에서 ActionDispatcher와 컨텍스트를 가져옵니다.
*/
function getDispatcherContext() {
const templateApp = (window as any).__templateApp;
if (!templateApp) {
logger.warn('TemplateApp이 초기화되지 않았습니다.');
return null;
}
const actionDispatcher = templateApp.getActionDispatcher?.();
const router = templateApp.getRouter?.();
const globalState = templateApp.getGlobalState?.();
const setGlobalState = templateApp.setGlobalState?.bind(templateApp);
if (!actionDispatcher) {
logger.warn('ActionDispatcher를 찾을 수 없습니다.');
return null;
}
return {
actionDispatcher,
context: {
navigate: router ? (path: string) => router.navigate(path) : undefined,
setState: setGlobalState,
state: globalState,
data: globalState,
},
};
}
/**
* ActionDispatcher를 통해 액션을 실행할 수 있는 dispatch 함수를 반환하는 훅
*
* @returns dispatch 함수
*
* @example
* ```tsx
* const dispatch = useActions();
*
* // navigate
* dispatch({ handler: 'navigate', params: { path: '/admin/dashboard' } });
*
* // apiCall with onSuccess
* dispatch({
* handler: 'apiCall',
* target: '/api/admin/users',
* params: { method: 'GET' },
* onSuccess: [{ handler: 'toast', params: { type: 'success', message: '성공' } }]
* });
*
* // openModal
* dispatch({ handler: 'openModal', target: 'confirm_modal' });
*
* // setState
* dispatch({
* handler: 'setState',
* params: { target: 'global', selectedIds: [1, 2, 3] }
* });
* ```
*/
export function useActions(): DispatchFunction {
const dispatch = useCallback(async (action: ActionDefinition): Promise<ActionResult> => {
const dispatcherContext = getDispatcherContext();
if (!dispatcherContext) {
return {
success: false,
error: new Error('ActionDispatcher를 사용할 수 없습니다. TemplateApp이 초기화되었는지 확인하세요.'),
};
}
const { actionDispatcher, context } = dispatcherContext;
try {
// ActionDispatcher의 내부 executeAction 메서드 호출
// handleAction은 이벤트 핸들러용이므로, 직접 액션을 실행하는 방식 사용
const result = await actionDispatcher.dispatchAction(action, context);
return result;
} catch (error) {
logger.error('액션 실행 오류:', error);
return {
success: false,
error: error instanceof Error ? error : new Error(String(error)),
};
}
}, []);
return dispatch;
}
/**
* 전역에서 사용할 수 있는 dispatch 함수 (훅 외부에서 사용)
*
* @example
* ```tsx
* import { dispatchAction } from '@g7/core/hooks';
*
* // 이벤트 핸들러나 비동기 콜백에서 사용
* const handleExternalEvent = () => {
* dispatchAction({ handler: 'navigate', params: { path: '/admin' } });
* };
* ```
*/
export async function dispatchAction(action: ActionDefinition): Promise<ActionResult> {
const dispatcherContext = getDispatcherContext();
if (!dispatcherContext) {
return {
success: false,
error: new Error('ActionDispatcher를 사용할 수 없습니다.'),
};
}
const { actionDispatcher, context } = dispatcherContext;
try {
const result = await actionDispatcher.dispatchAction(action, context);
return result;
} catch (error) {
logger.error('액션 실행 오류:', error);
return {
success: false,
error: error instanceof Error ? error : new Error(String(error)),
};
}
}
export default useActions;
@@ -0,0 +1,203 @@
/**
* useControllableState Hook (Phase 1-4)
*
* Controlled/Uncontrolled 컴포넌트 패턴을 단순화하는 훅입니다.
* 외부에서 값이 제공되면 Controlled 모드로, 아니면 Uncontrolled 모드로 동작합니다.
*
* 이 훅은 DataGrid, SortableMenuList, PermissionTree 등에서
* 이중 상태 관리 패턴(외부 props vs 내부 useState)을 해소합니다.
*
* @example
* ```tsx
* // DataGrid에서 사용 예시
* const [selectedIds, setSelectedIds] = useControllableState(
* selectedIdsProp, // 외부 제어 값 (undefined면 내부 상태 사용)
* defaultSelectedIds ?? [], // 기본값
* onSelectedIdsChange // 변경 콜백 (옵션)
* );
*
* // Controlled 모드: selectedIdsProp이 있으면 해당 값 사용
* // Uncontrolled 모드: selectedIdsProp이 undefined면 내부 상태 사용
* ```
*
* @example
* ```tsx
* // SortableMenuList에서 사용 예시
* const [items, setItems] = useControllableState(
* itemsProp,
* initialItems,
* onChange
* );
*
* // 내부 상태 변경과 콜백 호출이 자동으로 처리됨
* const handleReorder = (newItems) => {
* setItems(newItems); // onChange도 자동 호출
* };
* ```
*
* @module hooks/useControllableState
*/
import { useState, useCallback, useRef, useEffect } from 'react';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Core:State')) ?? {
log: (...args: unknown[]) => console.log('[Core:State]', ...args),
warn: (...args: unknown[]) => console.warn('[Core:State]', ...args),
error: (...args: unknown[]) => console.error('[Core:State]', ...args),
};
/**
* useControllableState 옵션
*/
export interface UseControllableStateOptions<T> {
/**
* 외부 제어 값 변경 시 내부 상태 동기화 여부
* 기본값: true
*
* true: 외부 값 변경 시 내부 상태도 업데이트 (controlled → uncontrolled 전환 시 유용)
* false: 외부 값 변경 시 내부 상태 유지
*/
syncOnControlledChange?: boolean;
/**
* 값 비교 함수 (같으면 onChange 호출 안 함)
* 기본: 참조 비교 (===)
*/
isEqual?: (a: T, b: T) => boolean;
}
/**
* Controlled/Uncontrolled 상태를 통합 관리하는 훅
*
* @param controlledValue 외부에서 제어하는 값 (undefined면 내부 상태 사용)
* @param defaultValue 기본값 (Uncontrolled 모드 초기값)
* @param onChange 값 변경 시 호출할 콜백
* @param options 추가 옵션
* @returns [현재 값, 값 설정 함수]
*/
export function useControllableState<T>(
controlledValue: T | undefined,
defaultValue: T,
onChange?: (value: T) => void,
options?: UseControllableStateOptions<T>
): [T, (value: T | ((prev: T) => T)) => void] {
const { syncOnControlledChange = true, isEqual } = options ?? {};
// Controlled 모드 여부 판단 (첫 렌더링 시 결정)
const isControlled = controlledValue !== undefined;
const isControlledRef = useRef(isControlled);
// 개발 모드에서 controlled/uncontrolled 전환 경고
if (process.env.NODE_ENV !== 'production') {
if (isControlledRef.current !== isControlled) {
logger.warn(
'컴포넌트가 controlled에서 uncontrolled로 (또는 반대로) 전환되었습니다. ' +
'이는 예기치 않은 동작을 일으킬 수 있습니다. ' +
'controlledValue가 항상 정의되어 있거나 항상 undefined인지 확인하세요.'
);
}
}
// 내부 상태 (초기값은 controlledValue가 있으면 그것을 사용)
const [internalValue, setInternalValue] = useState<T>(
controlledValue !== undefined ? controlledValue : defaultValue
);
// 현재 값: 항상 내부 상태 사용 (낙관적 업데이트)
// Controlled 모드에서는 useEffect를 통해 외부 값과 동기화됨
const value = internalValue;
// 이전 controlled 값 추적 (동기화용)
const prevControlledValueRef = useRef(controlledValue);
// 내부 업데이트 중 플래그 (외부 동기화 무시용)
const isInternalUpdateRef = useRef(false);
// Controlled 값 변경 시 내부 상태 동기화
useEffect(() => {
// 내부 업데이트 중이면 외부 동기화 무시 (깜빡거림 방지)
if (isInternalUpdateRef.current) {
prevControlledValueRef.current = controlledValue;
return;
}
if (
syncOnControlledChange &&
isControlled &&
controlledValue !== prevControlledValueRef.current
) {
// 값이 실제로 다른 경우에만 동기화 (isEqual 함수 사용)
const isDifferent = isEqual
? !isEqual(internalValue, controlledValue)
: internalValue !== controlledValue;
if (isDifferent) {
setInternalValue(controlledValue);
}
}
prevControlledValueRef.current = controlledValue;
}, [controlledValue, isControlled, syncOnControlledChange, isEqual, internalValue]);
// 값 설정 함수
const setValue = useCallback(
(newValueOrUpdater: T | ((prev: T) => T)) => {
// updater 함수 또는 직접 값 처리
const newValue =
typeof newValueOrUpdater === 'function'
? (newValueOrUpdater as (prev: T) => T)(value)
: newValueOrUpdater;
// 값이 같으면 무시
if (isEqual ? isEqual(value, newValue) : value === newValue) {
return;
}
// 내부 업데이트 플래그 설정 (외부 동기화 무시)
isInternalUpdateRef.current = true;
// 내부 상태 항상 업데이트 (Controlled 모드에서도 리렌더링 유발)
// Controlled 모드: 외부 값이 업데이트될 때까지 낙관적 업데이트로 즉각 반응
// Uncontrolled 모드: 내부 상태가 실제 값으로 사용됨
setInternalValue(newValue);
// onChange 콜백 호출 (Controlled/Uncontrolled 모두)
onChange?.(newValue);
// 다음 프레임에서 플래그 리셋 (외부 값이 업데이트된 후)
requestAnimationFrame(() => {
isInternalUpdateRef.current = false;
});
},
[value, isControlled, onChange, isEqual]
);
return [value, setValue];
}
/**
* 배열 값을 위한 특수 비교 함수
* 얕은 비교로 배열 내용이 같으면 true 반환
*/
export function shallowArrayEqual<T>(a: T[], b: T[]): boolean {
if (a === b) return true;
if (a.length !== b.length) return false;
return a.every((item, index) => item === b[index]);
}
/**
* 객체 값을 위한 특수 비교 함수
* 얕은 비교로 객체 1단계 속성이 같으면 true 반환
*/
export function shallowObjectEqual<T extends Record<string, any>>(
a: T,
b: T
): boolean {
if (a === b) return true;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every((key) => a[key] === b[key]);
}
export default useControllableState;
+14
View File
@@ -0,0 +1,14 @@
{
"core": {
"errors": {
"template_not_found": "No active template found",
"layout_load_failed": "Failed to load layout",
"layout_load_failed_with_id": "Failed to load layout ({layoutId})",
"component_load_failed": "Failed to load component",
"component_load_failed_with_name": "Failed to load component ({componentName})",
"translation_load_failed": "Failed to load translation file",
"translation_load_failed_with_locale": "Failed to load {locale} translation file",
"template_init_error": "An error occurred while initializing the template engine"
}
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"core": {
"errors": {
"template_not_found": "활성화된 템플릿이 없습니다",
"layout_load_failed": "레이아웃을 불러오는데 실패했습니다",
"layout_load_failed_with_id": "레이아웃({layoutId})을 불러오는데 실패했습니다",
"component_load_failed": "컴포넌트를 불러오는데 실패했습니다",
"component_load_failed_with_name": "컴포넌트({componentName})를 불러오는데 실패했습니다",
"translation_load_failed": "다국어 파일을 불러오는데 실패했습니다",
"translation_load_failed_with_locale": "{locale} 다국어 파일을 불러오는데 실패했습니다",
"template_init_error": "템플릿 엔진을 초기화하는 중 오류가 발생했습니다"
}
}
}
@@ -0,0 +1,345 @@
/**
* ModuleAssetLoader
*
* 모듈/플러그인의 에셋(JS, CSS)을 동적으로 로드하는 클래스입니다.
* TemplateApp 초기화 시 window.G7Config.moduleAssets를 기반으로
* 활성화된 모듈의 에셋을 로드합니다.
*/
import { createLogger } from '../utils/Logger';
const logger = createLogger('ModuleAssetLoader');
/**
* 모듈 에셋 정보 인터페이스
*/
export interface ModuleAsset {
/** 모듈 식별자 (vendor-module 형식) */
identifier: string;
/** JS 번들 URL */
js?: string;
/** CSS 번들 URL */
css?: string;
/** 로드 우선순위 (낮을수록 먼저) */
priority: number;
/** 외부 스크립트 정의 (조건부 로드용) */
external?: ExternalScript[];
}
/**
* 외부 스크립트 정의 인터페이스
*/
export interface ExternalScript {
/** 스크립트 URL */
src: string;
/** 스크립트 ID (중복 로드 방지) */
id: string;
/** 조건부 로드 표현식 (예: "{{_global.settings.useLib}}") */
if?: string;
}
/**
* 로드된 에셋 정보
*/
interface LoadedAsset {
/** 에셋 타입 (js, css) */
type: 'js' | 'css';
/** DOM 요소 */
element: HTMLElement;
}
/**
* ModuleAssetLoader 클래스
*
* 모듈 에셋의 동적 로드/언로드를 관리합니다.
*/
export class ModuleAssetLoader {
/** 로드된 에셋 맵 (identifier -> LoadedAsset[]) */
private loadedAssets: Map<string, LoadedAsset[]> = new Map();
/** 로드 중인 프로미스 맵 (중복 로드 방지) */
private loadingPromises: Map<string, Promise<void>> = new Map();
/**
* 활성화된 모듈들의 에셋을 로드합니다.
*
* 우선순위 순으로 정렬하여 순차적으로 로드합니다.
* CSS는 병렬로 로드하고, JS는 순차적으로 로드합니다.
*
* @param extensions 모듈 에셋 배열
*/
async loadActiveExtensionAssets(extensions: ModuleAsset[]): Promise<void> {
if (!extensions || extensions.length === 0) {
logger.log('No module assets to load');
return;
}
// 우선순위 순으로 정렬 (낮을수록 먼저)
const sortedExtensions = [...extensions].sort((a, b) => a.priority - b.priority);
logger.log('Loading module assets:', sortedExtensions.map(e => e.identifier));
// CSS를 먼저 병렬로 로드 (렌더링 블로킹 방지)
const cssPromises = sortedExtensions
.filter(ext => ext.css)
.map(ext => this.loadCSS(ext.identifier, ext.css!));
await Promise.all(cssPromises);
logger.log('All CSS assets loaded');
// JS를 순차적으로 로드 (의존성 순서 보장)
for (const ext of sortedExtensions) {
if (ext.js) {
await this.loadJS(ext.identifier, ext.js);
}
}
logger.log('All module assets loaded successfully');
}
/**
* CSS 파일을 동적으로 로드합니다.
*
* @param identifier 모듈 식별자
* @param url CSS 파일 URL
*/
private async loadCSS(identifier: string, url: string): Promise<void> {
const elementId = `module-css-${identifier}`;
// 이미 로드된 경우 스킵
if (document.getElementById(elementId)) {
logger.log(`CSS already loaded: ${identifier}`);
return;
}
return new Promise<void>((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.id = elementId;
link.onload = () => {
logger.log(`CSS loaded: ${identifier}`);
this.registerLoadedAsset(identifier, { type: 'css', element: link });
resolve();
};
link.onerror = () => {
logger.warn(`Failed to load CSS: ${identifier} (${url})`);
// CSS 로드 실패는 경고만 출력하고 계속 진행
resolve();
};
document.head.appendChild(link);
});
}
/**
* JS 파일을 동적으로 로드합니다.
*
* 로드 완료 후 모듈의 initModule() 함수가 자동으로 실행됩니다.
* (IIFE 번들이 로드되면서 즉시 실행)
*
* @param identifier 모듈 식별자
* @param url JS 파일 URL
*/
private async loadJS(identifier: string, url: string): Promise<void> {
const elementId = `module-js-${identifier}`;
// 이미 로드된 경우 스킵
if (document.getElementById(elementId)) {
logger.log(`JS already loaded: ${identifier}`);
return;
}
// 이미 로딩 중인 경우 대기
const existingPromise = this.loadingPromises.get(identifier);
if (existingPromise) {
logger.log(`JS already loading: ${identifier}`);
return existingPromise;
}
const loadPromise = new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.id = elementId;
script.async = false; // 순차적 로드를 위해 async 비활성화
script.onload = () => {
logger.log(`JS loaded: ${identifier}`);
this.registerLoadedAsset(identifier, { type: 'js', element: script });
this.loadingPromises.delete(identifier);
resolve();
};
script.onerror = () => {
logger.warn(`Failed to load JS: ${identifier} (${url})`);
this.loadingPromises.delete(identifier);
// JS 로드 실패는 경고만 출력하고 계속 진행
resolve();
};
document.head.appendChild(script);
});
this.loadingPromises.set(identifier, loadPromise);
return loadPromise;
}
/**
* 로드된 에셋을 맵에 등록합니다.
*
* @param identifier 모듈 식별자
* @param asset 로드된 에셋 정보
*/
private registerLoadedAsset(identifier: string, asset: LoadedAsset): void {
const assets = this.loadedAssets.get(identifier) || [];
assets.push(asset);
this.loadedAssets.set(identifier, assets);
}
/**
* 특정 모듈의 에셋을 언로드합니다.
*
* 모듈 비활성화 시 호출하여 DOM에서 에셋을 제거합니다.
*
* @param identifier 모듈 식별자
*/
unloadExtensionAsset(identifier: string): void {
const assets = this.loadedAssets.get(identifier);
if (!assets || assets.length === 0) {
logger.log(`No assets to unload for: ${identifier}`);
return;
}
assets.forEach(asset => {
if (asset.element.parentNode) {
asset.element.parentNode.removeChild(asset.element);
logger.log(`${asset.type.toUpperCase()} unloaded: ${identifier}`);
}
});
this.loadedAssets.delete(identifier);
logger.log(`All assets unloaded for: ${identifier}`);
}
/**
* 모든 모듈 에셋을 언로드합니다.
*/
unloadAllAssets(): void {
const identifiers = Array.from(this.loadedAssets.keys());
identifiers.forEach(identifier => {
this.unloadExtensionAsset(identifier);
});
logger.log('All module assets unloaded');
}
/**
* 특정 모듈의 에셋이 로드되었는지 확인합니다.
*
* @param identifier 모듈 식별자
* @returns 로드 여부
*/
isLoaded(identifier: string): boolean {
return this.loadedAssets.has(identifier);
}
/**
* 로드된 모듈 목록을 반환합니다.
*
* @returns 로드된 모듈 식별자 배열
*/
getLoadedModules(): string[] {
return Array.from(this.loadedAssets.keys());
}
}
// 싱글톤 인스턴스
let moduleAssetLoaderInstance: ModuleAssetLoader | null = null;
/**
* ModuleAssetLoader 싱글톤 인스턴스를 반환합니다.
*/
export function getModuleAssetLoader(): ModuleAssetLoader {
if (!moduleAssetLoaderInstance) {
moduleAssetLoaderInstance = new ModuleAssetLoader();
}
return moduleAssetLoaderInstance;
}
/**
* window.G7Config.moduleAssets에서 ModuleAsset 배열을 생성합니다.
*
* @returns ModuleAsset 배열
*/
export function parseModuleAssetsFromConfig(): ModuleAsset[] {
if (typeof window === 'undefined') {
return [];
}
const g7Config = (window as any).G7Config;
if (!g7Config?.moduleAssets) {
return [];
}
const moduleAssets: ModuleAsset[] = [];
for (const [identifier, asset] of Object.entries(g7Config.moduleAssets)) {
const typedAsset = asset as {
js?: string;
css?: string;
priority: number;
external?: ExternalScript[];
};
moduleAssets.push({
identifier,
js: typedAsset.js,
css: typedAsset.css,
priority: typedAsset.priority,
external: typedAsset.external,
});
}
return moduleAssets;
}
/**
* 플러그인 에셋을 파싱합니다.
*
* @returns ModuleAsset 배열 (플러그인용)
*/
export function parsePluginAssetsFromConfig(): ModuleAsset[] {
if (typeof window === 'undefined') {
return [];
}
const g7Config = (window as any).G7Config;
if (!g7Config?.pluginAssets) {
return [];
}
const pluginAssets: ModuleAsset[] = [];
for (const [identifier, asset] of Object.entries(g7Config.pluginAssets)) {
const typedAsset = asset as {
js?: string;
css?: string;
priority: number;
external?: ExternalScript[];
};
pluginAssets.push({
identifier,
js: typedAsset.js,
css: typedAsset.css,
priority: typedAsset.priority,
external: typedAsset.external,
});
}
return pluginAssets;
}
+12
View File
@@ -0,0 +1,12 @@
/**
* 모듈 시스템 관련 유틸리티 모듈
*/
export {
ModuleAssetLoader,
getModuleAssetLoader,
parseModuleAssetsFromConfig,
parsePluginAssetsFromConfig,
} from './ModuleAssetLoader';
export type { ModuleAsset, ExternalScript } from './ModuleAssetLoader';
+105
View File
@@ -0,0 +1,105 @@
import { Router, RouteMatch } from './Router';
import { createLogger } from '../utils/Logger';
const logger = createLogger('RouteResolver');
/**
* 라우트 변경 콜백 함수 타입
*/
export type RouteChangeCallback = (match: RouteMatch | null) => void;
/**
* RouteResolver 클래스
*
* 브라우저 History API와 통합되어 라우트 변경을 감지하고 처리합니다.
* popstate 이벤트를 감지하여 브라우저 뒤로가기/앞으로가기를 처리합니다.
*/
export class RouteResolver {
private router: Router;
private onRouteChange: RouteChangeCallback | null = null;
private isInitialized = false;
constructor(router: Router) {
this.router = router;
}
/**
* RouteResolver를 초기화합니다.
*
* - router.loadRoutes()를 호출하여 라우트 목록을 로드합니다.
* - popstate 이벤트 리스너를 등록합니다.
* - 초기 라우트를 해석합니다.
*
* @param callback - 라우트 변경 시 호출될 콜백 함수
*/
async init(callback: RouteChangeCallback): Promise<void> {
if (this.isInitialized) {
logger.warn('RouteResolver is already initialized');
return;
}
this.onRouteChange = callback;
// 라우트 목록 로드
await this.router.loadRoutes();
// popstate 이벤트 리스너 등록 (뒤로가기/앞으로가기)
window.addEventListener('popstate', this.handlePopState);
this.isInitialized = true;
// 초기 라우트 해석
this.resolve();
}
/**
* popstate 이벤트 핸들러
*
* 브라우저 뒤로가기/앞으로가기 시 호출됩니다.
*/
private handlePopState = (): void => {
this.resolve();
};
/**
* 현재 URL을 router.match()로 매칭하고 onRouteChange 콜백을 실행합니다.
* 리다이렉트 라우트인 경우 자동으로 리다이렉트합니다.
*/
resolve(): void {
const pathname = window.location.pathname;
const match = this.router.match(pathname);
// 리다이렉트 라우트인 경우 처리
if (match && match.route.redirect) {
logger.log(`Redirecting from ${pathname} to ${match.route.redirect}`);
this.navigate(match.route.redirect);
return;
}
if (this.onRouteChange) {
this.onRouteChange(match);
}
}
/**
* window.history.pushState()를 사용하여 프로그래매틱 네비게이션을 수행합니다.
*
* @param path - 이동할 경로
* @param state - history state 객체 (선택사항)
*/
navigate(path: string, state?: unknown): void {
window.history.pushState(state ?? null, '', path);
this.resolve();
}
/**
* RouteResolver를 정리합니다.
*
* - popstate 이벤트 리스너를 제거합니다.
*/
destroy(): void {
window.removeEventListener('popstate', this.handlePopState);
this.onRouteChange = null;
this.isInitialized = false;
}
}
+358
View File
@@ -0,0 +1,358 @@
import { AuthManager } from '../auth/AuthManager';
import { createLogger } from '../utils/Logger';
const logger = createLogger('Router');
/**
* 라우트 메타 정보
*/
export interface RouteMeta {
title?: string;
[key: string]: unknown;
}
/**
* 인증 타입
*/
export type AuthType = 'admin' | 'user';
/**
* 라우트 인터페이스
*/
export interface Route {
path: string;
layout?: string;
redirect?: string;
endpoint?: string;
params?: Record<string, string>;
/** 쿼리 파라미터 (배열 쿼리 파라미터 지원: key[]=[...]) */
query?: Record<string, string | string[]>;
auth_required?: boolean;
auth_type?: AuthType;
meta?: RouteMeta;
}
/**
* 라우트 매칭 결과
*/
export interface RouteMatch {
route: Route;
params: Record<string, string>;
}
/**
* 이벤트 핸들러 타입
*/
type EventHandler = (...args: any[]) => void;
/**
* Router 클래스
*
* URL 패턴 매칭과 동적 파라미터 추출을 담당합니다.
*/
export class Router {
private routes: Route[] = [];
private templateIdentifier: string;
private eventHandlers: Map<string, EventHandler[]> = new Map();
private pendingNavigation: string | null = null;
private isNavigating: boolean = false;
constructor(templateIdentifier: string) {
this.templateIdentifier = templateIdentifier;
this.initPopstateListener();
}
/**
* 브라우저 뒤로가기/앞으로가기 이벤트 리스너 초기화
*/
private initPopstateListener(): void {
window.addEventListener('popstate', this.handlePopState);
}
/**
* popstate 이벤트 핸들러 (화살표 함수로 this 바인딩 유지)
*/
private handlePopState = (): void => {
this.navigateToCurrentPath();
};
/**
* 이벤트 핸들러 등록
*/
on(event: string, handler: EventHandler): void {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, []);
}
this.eventHandlers.get(event)!.push(handler);
}
/**
* 이벤트 발생 (async 핸들러 지원)
*/
private async emit(event: string, ...args: any[]): Promise<void> {
const handlers = this.eventHandlers.get(event);
if (handlers) {
// 모든 핸들러가 완료될 때까지 대기 (async 핸들러 지원)
await Promise.all(handlers.map(handler => handler(...args)));
}
}
/**
* API에서 라우트 목록을 로드합니다.
*/
async loadRoutes(): Promise<void> {
try {
const response = await fetch(`/api/templates/${this.templateIdentifier}/routes.json`);
if (!response.ok) {
throw new Error(`Failed to load routes: ${response.statusText}`);
}
const result = await response.json();
if (!result.success) {
throw new Error('Failed to load routes from API');
}
// API 응답 형태: { success: true, data: { version: "1.0.0", routes: [...] } }
if (result.data && Array.isArray(result.data.routes)) {
this.routes = result.data.routes;
logger.log(`Loaded ${this.routes.length} routes`);
} else {
throw new Error('Invalid routes data format');
}
} catch (error) {
logger.error('Error loading routes:', error);
throw error;
}
}
/**
* 라우트 목록을 직접 설정합니다 (병렬 로딩용).
*
* @param routes - 설정할 라우트 배열
*/
setRoutes(routes: Route[]): void {
this.routes = routes;
logger.log(`Set ${this.routes.length} routes`);
}
/**
* 현재 경로와 매칭되는 라우트를 찾습니다.
*
* @param pathname - 매칭할 URL 경로
* @returns 매칭된 라우트와 파라미터, 없으면 null
*/
match(pathname: string): RouteMatch | null {
for (const route of this.routes) {
const params = this.matchPattern(route.path, pathname);
if (params !== null) {
return {
route,
params,
};
}
}
return null;
}
/**
* 패턴과 경로를 매칭하고 파라미터를 추출합니다.
*
* 지원되는 패턴:
* - /admin - 정확한 매칭
* - /admin/users/:id - 동적 파라미터 (:id)
* - * /admin - 언어 prefix 지원 (/admin, /ko/admin, /en/admin)
*
* @param pattern - 라우트 패턴
* @param pathname - 실제 URL 경로
* @returns 추출된 파라미터 객체, 매칭 실패 시 null
*/
private matchPattern(pattern: string, pathname: string): Record<string, string> | null {
// 파라미터 이름 추출
const paramNames: string[] = [];
// 패턴을 정규식으로 변환
let regexPattern = pattern
// :id 형태의 동적 파라미터를 캡처 그룹으로 변환
.replace(/:([^/]+)/g, (_, paramName) => {
paramNames.push(paramName);
return '([^/]+)';
});
// 패턴 시작의 */를 optional 언어 prefix로 변환 (예: /ko, /en)
// */admin → /admin 또는 /ko/admin 또는 /en/admin
if (regexPattern.startsWith('*/')) {
regexPattern = '(?:/[^/]+)?' + regexPattern.slice(1);
}
// 특수 문자 이스케이프
regexPattern = regexPattern.replace(/\//g, '\\/');
// 정규식 생성 (전체 문자열 매칭)
const regex = new RegExp(`^${regexPattern}$`);
const match = pathname.match(regex);
if (!match) {
return null;
}
// 파라미터 추출
const params: Record<string, string> = {};
paramNames.forEach((name, index) => {
params[name] = match[index + 1];
});
return params;
}
/**
* 현재 로드된 라우트 목록을 반환합니다.
*/
getRoutes(): Route[] {
return [...this.routes];
}
/**
* 경로 기반 인증 타입 판단
*
* @param route - 라우트 정보
* @param pathname - URL 경로
* @returns 인증 타입
*/
private getAuthType(route: Route, pathname: string): AuthType {
// 1. 라우트에 명시된 경우 사용
if (route.auth_type) {
return route.auth_type;
}
// 2. 경로 기반 자동 판단
if (pathname.startsWith('/admin')) {
return 'admin';
}
return 'user';
}
/**
* 현재 URL 경로를 처리하여 매칭되는 라우트를 찾고 이벤트를 발생시킵니다.
*/
async navigateToCurrentPath(): Promise<void> {
const pathname = window.location.pathname;
const search = window.location.search;
const matchResult = this.match(pathname);
if (!matchResult) {
logger.warn(`No route matched for path: ${pathname}`);
this.emit('routeNotFound', pathname);
return;
}
// 리다이렉트 라우트인 경우 처리
if (matchResult.route.redirect) {
logger.log(`Redirecting from ${pathname} to ${matchResult.route.redirect}`);
this.navigate(matchResult.route.redirect);
return;
}
// 인증 검증
if (matchResult.route.auth_required) {
const authType = this.getAuthType(matchResult.route, pathname);
const authManager = AuthManager.getInstance();
// 이미 인증 상태가 확인된 경우 API 호출 스킵
let isAuthenticated = authManager.isAuthenticated() && authManager.getAuthType() === authType;
// 인증 상태가 없거나 타입이 다른 경우에만 API 호출
if (!isAuthenticated) {
isAuthenticated = await authManager.checkAuth(authType);
}
if (!isAuthenticated) {
const loginUrl = authManager.getLoginRedirectUrl(authType, pathname + search);
logger.log(`Not authenticated, redirecting to: ${loginUrl}`);
window.location.href = loginUrl;
return;
}
}
// query 파라미터 파싱 (배열 쿼리 파라미터 지원)
const queryParams = new URLSearchParams(search);
const query: Record<string, string | string[]> = {};
// 모든 키를 순회하며 배열 값 처리
for (const key of queryParams.keys()) {
// 이미 처리된 키는 스킵
if (key in query) continue;
const values = queryParams.getAll(key);
if (values.length > 1) {
// 여러 값이 있으면 배열로 저장
query[key] = values;
} else if (values.length === 1) {
// key[]로 끝나면 단일 값도 배열로 저장 (일관성 유지)
if (key.endsWith('[]')) {
query[key] = values;
} else {
query[key] = values[0];
}
}
}
// 라우트 변경 이벤트 발생 (핸들러가 완료될 때까지 대기)
await this.emit('routeChange', {
path: pathname,
layout: matchResult.route.layout,
endpoint: matchResult.route.endpoint,
params: { ...(matchResult.route.params || {}), ...matchResult.params },
query,
auth_required: matchResult.route.auth_required,
auth_type: matchResult.route.auth_type,
meta: matchResult.route.meta,
});
}
/**
* 지정된 경로로 이동합니다.
*
* 동시에 여러 navigate 호출이 발생할 경우, 마지막 요청만 처리합니다.
* 이전 navigate가 진행 중이면 대기했다가 최신 경로로 이동합니다.
*
* @param path - 이동할 경로 (예: '/admin/dashboard')
*/
navigate(path: string): void {
// 이미 navigate가 진행 중이면 대기열에 추가
if (this.isNavigating) {
this.pendingNavigation = path;
return;
}
this.executeNavigation(path);
}
/**
* 실제 navigate 실행
*/
private async executeNavigation(path: string): Promise<void> {
this.isNavigating = true;
this.pendingNavigation = null;
try {
// URL 변경 (브라우저 히스토리에 추가)
window.history.pushState({}, '', path);
// 라우트 매칭 및 렌더링 (완료까지 대기)
await this.navigateToCurrentPath();
} finally {
this.isNavigating = false;
// 대기 중인 navigate가 있으면 실행
if (this.pendingNavigation) {
const nextPath = this.pendingNavigation;
this.executeNavigation(nextPath);
}
}
}
}
@@ -0,0 +1,225 @@
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { Router } from '../Router';
import { RouteResolver } from '../RouteResolver';
import { Logger } from '../../utils/Logger';
// fetch 모킹
global.fetch = vi.fn();
describe('RouteResolver', () => {
let router: Router;
let resolver: RouteResolver;
let mockCallback: ReturnType<typeof vi.fn>;
beforeEach(() => {
router = new Router('sirsoft-admin_basic');
resolver = new RouteResolver(router);
mockCallback = vi.fn();
vi.clearAllMocks();
// Logger 디버그 모드 활성화
Logger.getInstance().setDebug(true);
// 기본 라우트 목록 모킹
// API 응답 형태: { success: true, data: { version: "1.0.0", routes: [...] } }
(global.fetch as any).mockResolvedValue({
ok: true,
json: async () => ({
success: true,
data: {
version: '1.0.0',
routes: [
{ path: '/admin', layout: 'dashboard' },
{ path: '/admin/users/:id', layout: 'user-detail' },
],
},
}),
});
});
afterEach(() => {
resolver.destroy();
// Logger 디버그 모드 비활성화
Logger.getInstance().setDebug(false);
});
describe('init', () => {
it('router.loadRoutes()를 호출해야 합니다', async () => {
const loadRoutesSpy = vi.spyOn(router, 'loadRoutes');
await resolver.init(mockCallback);
expect(loadRoutesSpy).toHaveBeenCalledOnce();
});
it('popstate 이벤트 리스너를 등록해야 합니다', async () => {
const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
await resolver.init(mockCallback);
expect(addEventListenerSpy).toHaveBeenCalledWith('popstate', expect.any(Function));
});
it('초기 라우트를 해석하고 콜백을 호출해야 합니다', async () => {
// 현재 경로를 /admin으로 설정
Object.defineProperty(window, 'location', {
value: { pathname: '/admin' },
writable: true,
});
await resolver.init(mockCallback);
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'dashboard' }),
params: {},
})
);
});
it('이미 초기화된 경우 경고를 출력하고 재초기화하지 않아야 합니다', async () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await resolver.init(mockCallback);
await resolver.init(mockCallback);
expect(consoleWarnSpy).toHaveBeenCalledWith('[RouteResolver]', 'RouteResolver is already initialized');
expect(mockCallback).toHaveBeenCalledOnce(); // 첫 번째 init만 콜백 호출
});
});
describe('resolve', () => {
beforeEach(async () => {
await resolver.init(mockCallback);
mockCallback.mockClear(); // init에서 호출된 것 제외
});
it('현재 경로와 매칭되는 라우트를 찾아 콜백을 호출해야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users/123' },
writable: true,
});
resolver.resolve();
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'user-detail' }),
params: { id: '123' },
})
);
});
it('매칭되지 않는 경로는 null로 콜백을 호출해야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/unknown' },
writable: true,
});
resolver.resolve();
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(null);
});
});
describe('navigate', () => {
beforeEach(async () => {
await resolver.init(mockCallback);
mockCallback.mockClear();
});
it('window.history.pushState()를 호출해야 합니다', () => {
const pushStateSpy = vi.spyOn(window.history, 'pushState');
resolver.navigate('/admin/users/456');
expect(pushStateSpy).toHaveBeenCalledOnce();
expect(pushStateSpy).toHaveBeenCalledWith(null, '', '/admin/users/456');
});
it('state를 전달하면 pushState에 포함되어야 합니다', () => {
const pushStateSpy = vi.spyOn(window.history, 'pushState');
const state = { fromSearch: true };
resolver.navigate('/admin/users/456', state);
expect(pushStateSpy).toHaveBeenCalledWith(state, '', '/admin/users/456');
});
it('navigate 후 resolve()를 호출하여 콜백이 실행되어야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users/456' },
writable: true,
});
resolver.navigate('/admin/users/456');
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'user-detail' }),
params: { id: '456' },
})
);
});
});
describe('popstate 이벤트 처리', () => {
beforeEach(async () => {
await resolver.init(mockCallback);
mockCallback.mockClear();
});
it('popstate 이벤트 발생 시 resolve()가 호출되어야 합니다', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin' },
writable: true,
});
window.dispatchEvent(new PopStateEvent('popstate'));
expect(mockCallback).toHaveBeenCalledOnce();
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
route: expect.objectContaining({ layout: 'dashboard' }),
params: {},
})
);
});
});
describe('destroy', () => {
it('popstate 이벤트 리스너를 제거해야 합니다', async () => {
const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');
await resolver.init(mockCallback);
resolver.destroy();
expect(removeEventListenerSpy).toHaveBeenCalledWith('popstate', expect.any(Function));
});
it('destroy 후 popstate 이벤트가 발생해도 콜백이 호출되지 않아야 합니다', async () => {
await resolver.init(mockCallback);
mockCallback.mockClear();
resolver.destroy();
window.dispatchEvent(new PopStateEvent('popstate'));
expect(mockCallback).not.toHaveBeenCalled();
});
it('destroy 후 isInitialized가 false로 설정되어야 합니다', async () => {
await resolver.init(mockCallback);
resolver.destroy();
// 다시 init 호출 시 경고 없이 초기화되어야 함
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await resolver.init(mockCallback);
expect(consoleWarnSpy).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,556 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { Router } from '../Router';
import { AuthManager } from '../../auth/AuthManager';
// fetch 모킹
global.fetch = vi.fn();
// AuthManager 모킹
vi.mock('../../auth/AuthManager', () => ({
AuthManager: {
getInstance: vi.fn(),
},
}));
describe('Router', () => {
let router: Router;
beforeEach(() => {
router = new Router('sirsoft-admin_basic');
vi.clearAllMocks();
});
describe('loadRoutes', () => {
it('API에서 라우트 목록을 성공적으로 로드해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin', layout: 'dashboard' },
{ path: '/admin/users/:id', layout: 'user-detail' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
expect(global.fetch).toHaveBeenCalledWith('/api/templates/sirsoft-admin_basic/routes.json');
expect(router.getRoutes()).toEqual(mockRoutes);
});
it('API 호출 실패 시 에러를 던져야 합니다', async () => {
(global.fetch as any).mockResolvedValueOnce({
ok: false,
statusText: 'Not Found',
});
await expect(router.loadRoutes()).rejects.toThrow('Failed to load routes: Not Found');
});
it('success가 false일 때 에러를 던져야 합니다', async () => {
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: false,
data: null,
}),
});
await expect(router.loadRoutes()).rejects.toThrow('Failed to load routes from API');
});
it('잘못된 데이터 형식 시 에러를 던져야 합니다', async () => {
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0' }, // routes 배열이 없음
}),
});
await expect(router.loadRoutes()).rejects.toThrow('Invalid routes data format');
});
});
describe('match', () => {
beforeEach(async () => {
const mockRoutes = [
{ path: '/admin', layout: 'dashboard' },
{ path: '/admin/users', layout: 'user-list' },
{ path: '/admin/users/:id', layout: 'user-detail' },
{ path: '/admin/files/*', layout: 'file-browser' },
{ path: '/admin/posts/:postId/comments/:commentId', layout: 'comment-detail' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
});
it('정확한 경로 매칭을 수행해야 합니다', () => {
const result = router.match('/admin');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('dashboard');
expect(result?.params).toEqual({});
});
it('동적 파라미터를 추출해야 합니다', () => {
const result = router.match('/admin/users/123');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('user-detail');
expect(result?.params).toEqual({ id: '123' });
});
it('다중 동적 파라미터를 추출해야 합니다', () => {
const result = router.match('/admin/posts/456/comments/789');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('comment-detail');
expect(result?.params).toEqual({
postId: '456',
commentId: '789',
});
});
// TODO: 와일드카드 패턴(*)은 아직 미구현 - 현재는 */만 언어 prefix용으로 지원
it.skip('와일드카드 패턴을 매칭해야 합니다', () => {
const result = router.match('/admin/files/documents/2024/report.pdf');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('file-browser');
expect(result?.params).toEqual({});
});
it('매칭되지 않는 경로는 null을 반환해야 합니다', () => {
const result = router.match('/unknown/path');
expect(result).toBeNull();
});
it('부분 매칭은 수행하지 않아야 합니다', () => {
const result = router.match('/admin/users/123/extra');
expect(result).toBeNull();
});
it('첫 번째로 매칭되는 라우트를 반환해야 합니다', () => {
// /admin/users는 /admin/users와 /admin/users/:id 둘 다 매칭 가능
// 하지만 정확히 매칭되는 /admin/users를 먼저 반환해야 함
const result = router.match('/admin/users');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('user-list');
expect(result?.params).toEqual({});
});
});
describe('matchPattern (간접 테스트)', () => {
beforeEach(async () => {
const mockRoutes = [
{ path: '/test/:param', layout: 'test' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
});
it('영숫자와 하이픈, 언더스코어를 포함한 파라미터를 추출해야 합니다', () => {
const result = router.match('/test/user-id_123');
expect(result).not.toBeNull();
expect(result?.params.param).toBe('user-id_123');
});
it('슬래시가 포함된 파라미터는 매칭하지 않아야 합니다', () => {
const result = router.match('/test/invalid/path');
expect(result).toBeNull();
});
});
describe('getRoutes', () => {
it('로드된 라우트 목록의 복사본을 반환해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin', layout: 'dashboard' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
const routes = router.getRoutes();
routes.push({ path: '/test', layout: 'test' });
// 원본은 변경되지 않아야 함
expect(router.getRoutes().length).toBe(1);
});
});
describe('redirect', () => {
beforeEach(async () => {
const mockRoutes = [
{ path: '/admin', redirect: '/admin/dashboard', auth_required: true },
{ path: '/admin/login', layout: 'admin_login', auth_required: false },
{ path: '/admin/dashboard', layout: 'admin_dashboard', auth_required: true },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
});
it('리다이렉트 라우트를 매칭해야 합니다', () => {
const result = router.match('/admin');
expect(result).not.toBeNull();
expect(result?.route.redirect).toBe('/admin/dashboard');
expect(result?.route.auth_required).toBe(true);
});
it('일반 라우트는 layout을 가져야 합니다', () => {
const result = router.match('/admin/dashboard');
expect(result).not.toBeNull();
expect(result?.route.layout).toBe('admin_dashboard');
expect(result?.route.redirect).toBeUndefined();
});
it('navigateToCurrentPath에서 리다이렉트 라우트를 처리해야 합니다', async () => {
// 리다이렉트 후 pathname이 변경되도록 시뮬레이션
let currentPathname = '/admin';
Object.defineProperty(window, 'location', {
get: () => ({ pathname: currentPathname, search: '', href: '' }),
configurable: true,
});
// window.history.pushState 모킹 - pathname도 함께 변경
const pushStateSpy = vi.spyOn(window.history, 'pushState').mockImplementation((_, __, url) => {
currentPathname = url as string;
});
// Mock AuthManager for auth_required routes
const mockAuthManager = {
isAuthenticated: vi.fn().mockReturnValue(false),
getAuthType: vi.fn().mockReturnValue(null),
checkAuth: vi.fn().mockResolvedValue(true),
getLoginRedirectUrl: vi.fn(),
};
(AuthManager.getInstance as any).mockReturnValue(mockAuthManager);
// routeChange 이벤트 리스너
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
// navigateToCurrentPath 호출 (async)
await router.navigateToCurrentPath();
// pushState가 리다이렉트 경로로 호출되어야 함
expect(pushStateSpy).toHaveBeenCalledWith({}, '', '/admin/dashboard');
// 최종적으로 routeChange가 dashboard 레이아웃으로 호출되어야 함
expect(routeChangeHandler).toHaveBeenCalledWith(
expect.objectContaining({
layout: 'admin_dashboard',
})
);
pushStateSpy.mockRestore();
});
});
describe('인증 가드', () => {
let mockAuthManager: any;
beforeEach(async () => {
const mockRoutes = [
{ path: '/admin/login', layout: 'admin_login', auth_required: false },
{ path: '/admin/dashboard', layout: 'admin_dashboard', auth_required: true },
{ path: '/admin/users', layout: 'admin_users', auth_required: true, auth_type: 'admin' as const },
{ path: '/profile', layout: 'user_profile', auth_required: true },
{ path: '/login', layout: 'user_login', auth_required: false },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
// Mock AuthManager
mockAuthManager = {
isAuthenticated: vi.fn().mockReturnValue(false),
getAuthType: vi.fn().mockReturnValue(null),
checkAuth: vi.fn(),
getLoginRedirectUrl: vi.fn(),
};
(AuthManager.getInstance as any).mockReturnValue(mockAuthManager);
});
afterEach(() => {
vi.clearAllMocks();
});
it('auth_required가 true이고 미인증 시 로그인 페이지로 리다이렉트해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/dashboard', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(false);
mockAuthManager.getLoginRedirectUrl.mockReturnValue('/admin/login?redirect=%2Fadmin%2Fdashboard');
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
expect(window.location.href).toBe('/admin/login?redirect=%2Fadmin%2Fdashboard');
expect(routeChangeHandler).not.toHaveBeenCalled();
});
it('auth_required가 true이고 인증됨 시 정상 렌더링해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/dashboard', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(true);
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
expect(routeChangeHandler).toHaveBeenCalledWith(
expect.objectContaining({
layout: 'admin_dashboard',
})
);
});
it('/admin 경로는 관리자 로그인 페이지로 리다이렉트해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(false);
mockAuthManager.getLoginRedirectUrl.mockReturnValue('/admin/login?redirect=%2Fadmin%2Fusers');
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
expect(mockAuthManager.getLoginRedirectUrl).toHaveBeenCalledWith('admin', '/admin/users');
});
it('일반 경로는 사용자 로그인 페이지로 리다이렉트해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/profile', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(false);
mockAuthManager.getLoginRedirectUrl.mockReturnValue('/login?redirect=%2Fprofile');
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('user');
expect(mockAuthManager.getLoginRedirectUrl).toHaveBeenCalledWith('user', '/profile');
});
it('auth_required가 false인 경우 인증 검증을 수행하지 않아야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/login', search: '', href: '' },
writable: true,
configurable: true,
});
const routeChangeHandler = vi.fn();
router.on('routeChange', routeChangeHandler);
await router.navigateToCurrentPath();
expect(mockAuthManager.checkAuth).not.toHaveBeenCalled();
expect(routeChangeHandler).toHaveBeenCalledWith(
expect.objectContaining({
layout: 'admin_login',
})
);
});
it('라우트에 auth_type이 명시된 경우 해당 타입을 사용해야 합니다', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/admin/users', search: '', href: '' },
writable: true,
configurable: true,
});
mockAuthManager.checkAuth.mockResolvedValue(true);
await router.navigateToCurrentPath();
// auth_type이 'admin'으로 명시되어 있으므로 'admin'으로 호출
expect(mockAuthManager.checkAuth).toHaveBeenCalledWith('admin');
});
});
describe('배열 쿼리 파라미터 파싱', () => {
it('같은 키의 여러 값을 배열로 파싱해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin/products', layout: 'products' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
let capturedRoute: any = null;
router.on('routeChange', (route: any) => {
capturedRoute = route;
});
// 배열 쿼리 파라미터가 있는 URL 설정
Object.defineProperty(window, 'location', {
value: {
pathname: '/admin/products',
search: '?sales_status[]=on_sale&sales_status[]=sold_out&page=1',
href: '',
},
writable: true,
configurable: true,
});
await router.navigateToCurrentPath();
// query에서 배열이 올바르게 파싱되었는지 확인
expect(capturedRoute).not.toBeNull();
expect(capturedRoute.query['sales_status[]']).toEqual(['on_sale', 'sold_out']);
expect(capturedRoute.query['page']).toBe('1');
});
it('단일 배열 값도 배열로 파싱해야 합니다 (key[] 형태)', async () => {
const mockRoutes = [
{ path: '/admin/products', layout: 'products' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
let capturedRoute: any = null;
router.on('routeChange', (route: any) => {
capturedRoute = route;
});
// 단일 배열 값이 있는 URL 설정
Object.defineProperty(window, 'location', {
value: {
pathname: '/admin/products',
search: '?sales_status[]=on_sale',
href: '',
},
writable: true,
configurable: true,
});
await router.navigateToCurrentPath();
// key[]로 끝나는 단일 값도 배열로 파싱되어야 함
expect(capturedRoute).not.toBeNull();
expect(capturedRoute.query['sales_status[]']).toEqual(['on_sale']);
});
it('일반 파라미터는 문자열로 유지해야 합니다', async () => {
const mockRoutes = [
{ path: '/admin/products', layout: 'products' },
];
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
success: true,
data: { version: '1.0.0', routes: mockRoutes },
}),
});
await router.loadRoutes();
let capturedRoute: any = null;
router.on('routeChange', (route: any) => {
capturedRoute = route;
});
Object.defineProperty(window, 'location', {
value: {
pathname: '/admin/products',
search: '?page=1&search=test',
href: '',
},
writable: true,
configurable: true,
});
await router.navigateToCurrentPath();
// 일반 파라미터는 문자열
expect(capturedRoute).not.toBeNull();
expect(capturedRoute.query['page']).toBe('1');
expect(capturedRoute.query['search']).toBe('test');
expect(typeof capturedRoute.query['page']).toBe('string');
});
});
});
+8
View File
@@ -0,0 +1,8 @@
/**
* Routing 모듈
*
* Router와 RouteResolver를 외부에서 사용할 수 있도록 export합니다.
*/
export { Router, Route, RouteMatch } from './Router';
export { RouteResolver, RouteChangeCallback } from './RouteResolver';
+117
View File
@@ -0,0 +1,117 @@
/**
* 그누보드7 템플릿 엔진 타입 선언 파일
*
* 전역 타입 정의 및 window 객체 확장
*/
declare module '*/template-engine' {
import type { ComponentType } from 'react';
import type ReactDOM from 'react-dom/client';
import type { ComponentRegistry } from './template-engine/ComponentRegistry';
import type { DataBindingEngine } from './template-engine/DataBindingEngine';
import type { TranslationEngine } from './template-engine/TranslationEngine';
import type { ActionDispatcher } from './template-engine/ActionDispatcher';
/**
* 템플릿 엔진 상태 인터페이스
*/
export interface TemplateEngineState {
templateId: string | null;
locale: string;
isInitialized: boolean;
reactRoot: ReactDOM.Root | null;
containerId: string | null;
currentLayoutJson: any | null;
currentDataContext: Record<string, any>;
translationContext: Record<string, any>;
registry: ComponentRegistry | null;
bindingEngine: DataBindingEngine | null;
translationEngine: TranslationEngine | null;
actionDispatcher: ActionDispatcher | null;
}
/**
* 템플릿 엔진 초기화 옵션
*/
export interface InitOptions {
templateId: string;
locale?: string;
debug?: boolean;
}
/**
* 렌더링 옵션
*/
export interface RenderOptions {
containerId: string;
layoutJson: any;
dataContext?: Record<string, any>;
translationContext?: Record<string, any>;
}
/**
* 템플릿 엔진 공개 API
*/
export interface TemplateEngineAPI {
/**
* 템플릿 엔진 초기화
*
* @param options - 초기화 옵션
* @throws {Error} 이미 초기화된 경우 또는 초기화 실패 시
*/
initTemplateEngine(options: InitOptions): Promise<void>;
/**
* 템플릿 렌더링
*
* @param options - 렌더링 옵션
* @throws {Error} 초기화되지 않은 경우 또는 렌더링 실패 시
*/
renderTemplate(options: RenderOptions): Promise<void>;
/**
* 템플릿 데이터 업데이트
*
* @param data - 업데이트할 데이터
* @throws {Error} 초기화되지 않은 경우 또는 렌더링되지 않은 경우
*/
updateTemplateData(data: Record<string, any>): void;
/**
* 템플릿 정리
*
* React Root를 언마운트하고 모든 상태를 초기화합니다.
*/
destroyTemplate(): void;
/**
* 현재 상태 조회
*
* @returns 현재 템플릿 엔진 상태 (읽기 전용)
*/
getState(): Readonly<TemplateEngineState>;
}
const TemplateEngine: TemplateEngineAPI;
export default TemplateEngine;
export function initTemplateEngine(options: InitOptions): Promise<void>;
export function renderTemplate(options: RenderOptions): Promise<void>;
export function updateTemplateData(data: Record<string, any>): void;
export function destroyTemplate(): void;
export function getState(): Readonly<TemplateEngineState>;
}
/**
* 전역 Window 인터페이스 확장
*/
declare global {
interface Window {
G7Core?: {
TemplateEngine?: import('*/template-engine').TemplateEngineAPI;
};
}
}
export {};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,718 @@
# Template Engine Changelog
> 이 문서는 그누보드7 템플릿 엔진의 내부 개발 버전 이력입니다.
> `engine-v1.x.x` 버전은 그누보드7 릴리스 버전과 독립적입니다.
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.29.2]
### Fixed
- (engine-v1.29.2) `if` 조건에서 `{{true}}`, `{{false}}`, `{{null}}`, `{{undefined}}` 리터럴이 컨텍스트 경로로 해석되어 항상 undefined 반환되는 버그 수정 (ConditionEvaluator, RenderHelpers)
- 원인: `isComplexExpression` 체크에서 연산자 없는 단순 문자열로 판정 → `resolve("true")` → `context["true"]` → `undefined`
- 영향 범위: `evaluateStringCondition` (ConditionEvaluator) + `evaluateIfCondition` (RenderHelpers) 양쪽에 동일 버그 존재
- 수정: ConditionEvaluator에 `resolveLiteral()`, RenderHelpers에 `LITERALS` Map 추가 — `resolve()` 호출 전에 JS 리터럴을 직접 반환
- SEO 엔진(`ExpressionEvaluator.php`)은 이미 리터럴 체크가 `resolvePath()` 전에 있어 수정 불필요
## [engine-v1.29.1]
### Fixed
- (engine-v1.29.1) 에러 페이지(404 등)에서 로그인 상태가 표시되지 않는 버그 수정 (ErrorPageHandler)
- 원인: `renderError()`가 data_sources fetch 후 `initGlobal`/`initLocal` 처리를 하지 않아 `_global.currentUser`가 undefined로 남음
- 수정: `processInitOptions()` 메서드 추가 — fetch된 데이터의 `initGlobal`/`initLocal` 옵션을 처리하여 `_global`/`_local` 상태에 매핑
- 지원 형태: 문자열(`"currentUser"`), 배열(`["user", "profile"]`), 객체(`{ key, path }`)
## [engine-v1.29.0]
### Added
- transition_overlay `spinner` 스타일 — 커스텀 로딩 컴포넌트 지정 가능 (TemplateApp)
- 엔진은 빈 컨테이너 + position:relative CSS만 제공 — 비주얼 스타일은 컴포넌트가 전적으로 결정
- 3단계 fallback chain: target → fallback_target → #app (fullpage)
- `spinner.component`: 컴포넌트 레지스트리에서 로딩 컴포넌트 조회 (예: PageLoading)
- 컴포넌트 미지정 시 CSS 커스텀 속성 기반 기본 스피너 폴백
- renderTemplate 후 `reattachSpinnerOverlay()`로 새 DOM 타겟에 재마운트
- LayoutLoader 타입 정의에 `spinner` 스타일 및 spinner config 타입 추가 (LayoutLoader)
- UpdateLayoutContentRequest에 `spinner` validation 규칙 추가
### Fixed
- (engine-v1.29.0) spinner overlay 번역 미동작 수정 — renderSpinnerOverlay에서 G7Core.t() 사전 해석 후 컴포넌트에 전달 (TemplateApp)
- (engine-v1.29.0) spinner overlay 하드코딩 스타일 제거 — 배경색/z-index/포지셔닝을 엔진에서 제거하고 컴포넌트 책임으로 이전 (TemplateApp)
## [engine-v1.28.1]
### Fixed
- cellChildren 표현식 평가 결과 `$t:` 번역 후처리 누락 수정 (RenderHelpers)
- 증상: `{{row.published ? '$t:sirsoft-page.admin.page.published_status.published' : '$t:...'}}` 표현식 결과가 번역되지 않고 `$t:key` 문자열 그대로 노출
- 원인: `renderItemChildren.resolveValue`에서 표현식 평가 후 결과가 `$t:` 접두사 문자열인 경우 `translationEngine.resolveTranslations()` 호출이 없었음 (DynamicRenderer의 `resolveTranslationsDeep`와 달리)
- 수정: 단일 바인딩 표현식 및 문자열 보간 결과에 `$t:` 패턴 감지 시 번역 처리 추가 (`raw:` 바인딩은 면제)
- `preprocessTranslationTokens` 정규식에서 하이픈(`-`) 포함 모듈키 미인식 수정 (DataBindingEngine)
- 증상: `$t:sirsoft-page.admin.key` 패턴에서 `sirsoft` 이후 `-page`가 키의 일부로 인식되지 않음
- 원인: 문자 클래스 `[a-zA-Z0-9_.]`에 하이픈 누락
- 수정: Step 1(따옴표 내), Step 2(따옴표 외), `preprocessOptionalChaining` $t: 토큰 정규식 3곳에 `\-` 추가
## [engine-v1.28.0]
### Added
- `_changedKeys` 디바운스 병합 프로토콜 — 객체 값 이벤트의 stale closure 키 유실 방지 (ActionDispatcher)
- 디바운스 대기 중 동일 debounceKey로 들어오는 객체 값의 변경 키만 누적 병합
- `debounceAccumulatedValues` Map으로 누적, 타이머 fire 시 자동 정리
- `_changedKeys` 미포함 이벤트는 기존 동작 유지 (하위 호환)
- `extractEventData`에서 커스텀 이벤트의 `_changedKeys` 메타데이터 보존
### Fixed
- 커스텀 컴포넌트 이벤트(plain object) → synthetic event 변환 시 `_changedKeys` 메타데이터 누락 수정 (ActionDispatcher)
- `isCustomComponentEvent` 분기에서 synthetic event 생성 시 `_changedKeys`를 복사하지 않아, MultilingualInput의 `_changedKeys` 프로토콜이 실제 환경에서 동작하지 않았음
- DOM 이벤트(`preventDefault` 포함) 경로에서는 정상이었으나, React 컴포넌트의 plain object 이벤트 경로에서 유실
## [engine-v1.27.0]
### Fixed
- `_localInit` 처리 전 자식 컴포넌트 usgeEffect의 setState가 API 데이터를 stale 기본값으로 덮어쓰는 레이스 컨디션 수정 (DynamicRenderer)
- 증상: 직접 URL 접근 시 상품 수정 저장 → 422 검증 오류 (category_ids, options 필수 위반). SPA 네비게이션에서는 정상
- 원인: (1) `_localInit`(useEffect)이 실행되기 전 자식 useEffect(FileUploader `onFilesChange`)가 먼저 발동 → ActionDispatcher가 stale `context.state`(init_actions 빈 배열) 기반 `__g7PendingLocalState` 생성 (2) `handleLocalSetState`에서 `__g7SetLocalOverrideKeys`(init_actions가 설정한 stale 값)가 `__g7PendingLocalState`보다 우선 → `effectivePrev`에 stale 빈 배열 적용
- 수정: `_localInit` 데이터가 준비되면 useLayoutEffect(모든 useEffect보다 먼저 실행)에서 `__g7PendingLocalState`와 `__7SetLocalOverrideKeys`를 API 데이터로 사전 동기화 — 후속 자식 useEffect의 ActionDispatcher가 정확한 base state 참조
### Added
- `{{raw:expression}}` 바인딩 문법 — 번역 면제 마커 시스템 (DataBindingEngine, DynamicRenderer, RenderHelpers)
- `raw:` 접두사가 붙은 바인딩 결과는 `resolveTranslationsDeep`에서 번역을 건너뜀
- 사용자 입력 데이터(게시판 제목, 댓글 등)에 `$t:` 패턴이 포함되어도 원본 보존
- Unicode Noncharacter (`\uFDD0`, `\uFDD1`) 기반 내부 마커 — 사용자 입력과 충돌 불가
- 파이프, 복잡한 표현식, 객체/배열 결과, 혼합 보간 모두 지원
- `rawMarkers.ts` 공유 유틸리티 모듈 — `wrapRaw`, `unwrapRaw`, `wrapRawDeep`, `isRawWrapped`, `containsRawMarker`
## [engine-v1.26.1]
### Added
- 프리뷰 모드 지원: `PREVIEW_SUPPRESSED_HANDLERS` 상수 기반 핸들러 억제 — navigate, navigateBack, navigateForward, replaceUrl, refresh, logout (ActionDispatcher)
### Fixed
- JSON 구조 문자열 내부의 `$t:` 번역 토큰이 `resolveTranslationsDeep`에 의해 번역되어 원본 데이터가 손상되는 버그 수정 (DynamicRenderer)
- 증상: CodeEditor에서 레이아웃 JSON 편집 후 프리뷰 시 `$t:` 토큰이 사라져 다국어가 깨짐
- 원인: `resolveTranslationsDeep`가 모든 string prop에 적용되어, JSON 문자열 내부의 `$t:` 토큰까지 번역
- 수정: `{`/`[`로 시작하고 `}`/`]`로 끝나는 JSON 구조 문자열은 번역 건너뛰기
- 프리뷰 모드 레이아웃 기능 억제: `PREVIEW_SUPPRESSED_LAYOUT_FEATURES` 상수 — redirect 등 페이지 이탈 유발 레이아웃 기능 정의 (ActionDispatcher)
- `ActionDispatcher.setPreviewMode()` / `isPreviewMode()` API 추가 — 프리뷰 모드 활성화/비활성화 및 조회
- `ActionDispatcher.getPreviewSuppressedHandlers()` / `getPreviewSuppressedLayoutFeatures()` static 메서드 — 억제 대상 목록 외부 조회용
- `_global.__isPreview` 전역 상태 플래그 추가 — 프리뷰 모드 시 레이아웃 JSON에서 조건부 렌더링에 사용 가능 (TemplateApp)
- 프리뷰 안내 배너: 프리뷰 모드 시 최상단에 고정 배너 표시 — 페이지 이동 비활성화 안내 (SystemBannerManager)
- `SystemBannerManager` 신규 모듈: 범용 시스템 배너 관리자 — show/hide/hideAll API, 다국어 메시지, order 기반 정렬, #app paddingTop 자동 조정
- 프리뷰 모드에서 `blur_until_loaded` 비활성화 — 시각적 확인이 목적이므로 데이터소스 로딩 상태와 무관하게 블러 미적용 (DynamicRenderer)
## [engine-v1.26.0]
### Added
- 시스템 레이아웃 분기 지원: `__preview__` 예약 레이아웃 이름을 감지하여 별도 API 엔드포인트(`/api/layouts/preview/{token}.json`)로 라우팅 (LayoutLoader, TemplateApp)
- LayoutLoader: `fetchLayout()`에서 `__preview__/` 접두사 감지 시 프리뷰 전용 API URL 구성
- TemplateApp: `__preview__` 레이아웃 감지 시 route params에서 token을 추출하여 layoutPath에 포함
## [engine-v1.25.0]
### Added
- $t: 파라미터 값 내 중첩 번역 토큰 지원 (TranslationEngine)
- `$t:key1|status=$t:key2` 형태에서 파라미터 값 위치의 `$t:key2`를 메인 해석 전에 사전 번역
- 다중 중첩 대응: 해석 결과에 다시 `=$t:`가 포함되면 변화 없을 때까지 반복 (깊이 제한 5)
- `=$t:` 패턴이 없으면 사전 해석 단계 자체를 skip (기존 동작 무영향)
## [engine-v1.24.8]
### Fixed
- extends 기반 레이아웃에서 SPA 네비게이션 시 base 컴포넌트(사이드바, 헤더, 로고 등) 불필요 remount로 깜빡이는 버그 수정 (template-engine, DynamicRenderer, LayoutService)
- engine-v1.24.5의 layout_name key 추가가 모든 최상위 컴포넌트에 적용되어 base 컴포넌트까지 강제 remount
- LayoutService.replaceSlots()에서 base 컴포넌트에 `_fromBase: true` 자동 마킹
- `_fromBase` 컴포넌트는 stable key(componentDef.id) 사용 → 페이지 전환 시 보존(update)
- 슬롯 래퍼(slot 매칭 컴포넌트)는 `_fromBase` 미마킹 → remount 보장 (localDynamicState 초기화)
- 슬롯 children(페이지 고유 컴포넌트)은 `_fromBase` 미마킹 → 기존 layout_name key → remount 보장
- non-extends 레이아웃은 replaceSlots 미호출 → `_fromBase` 없음 → 기존 동작 100% 유지
- `_fromBase` 보존 컴포넌트의 localDynamicState가 SPA 네비게이션 시 초기화되지 않아 이전 페이지 상태(visibleFilters 등)가 하위 트리에 전파되는 회귀 수정 (DynamicRenderer)
- 원인: stable key → React가 컴포넌트 보존 → localDynamicState 잔존 → componentContext.state를 통해 모든 children에 cascading 전파
- 증상: 주문목록 → 주문상세 이동 시 DataGrid에 컬럼/데이터 미표시 (이전 페이지의 visibleFilters 오염)
- 수정: layoutKey(= layout_name) 변경 감지 시 `_fromBase` 컴포넌트의 localDynamicState를 `{ loadingActions: {} }`로 초기화
- sidebar 메뉴 open/close 등 React 컴포넌트 내부 useState는 localDynamicState와 독립 → 보존됨
## [engine-v1.24.7]
### Fixed
- 모달 내부 setLocal() 호출 시 모달 localDynamicState가 globalState._local에 오염되어 페이지 DataGrid 깨지는 버그 수정 (G7CoreGlobals)
- engine-v1.22.1에서 도입된 actionContext.state 병합이 모달 컨텍스트에서도 적용되어 모달 전용 상태(cancelItems, refundLoading 등)가 페이지 _local에 유입
- __g7LayoutContextStack 기반 모달 감지: 모달 내부에서는 actionContext.state 병합 제외, 페이지에서는 기존 동작 유지
- init_actions에서 conditions 핸들러 사용 시 conditions 배열이 전달되지 않아 조건 분기가 무시되던 버그 수정 (TemplateApp, LayoutLoader)
- executeInitActions에서 actionDef 구성 시 conditions 프로퍼티 누락 → handleConditions에서 undefined로 평가 → 경고만 출력하고 리턴
- InitActionDefinition 타입에 conditions 프로퍼티 추가, actionDef에 conditions 전달 추가
## [engine-v1.24.6]
### Fixed
- 주문 취소 모달 닫기 후 주문상세 DataGrid 깨지는 버그 수정 — _local 상태 교차 오염 방지 (TemplateApp, ActionDispatcher)
- handleRouteChange에서 `__g7LastSetLocalSnapshot`, `__g7SetLocalOverrideKeys`, `__g7SequenceLocalSync` 3개 전역 변수 미정리 → 이전 페이지 상태 잔존하여 다음 페이지 _local에 축적
- handleSetState isRealComponentContext 경로에서 deep 모드 시 전체 _local 스냅샷을 context.setState에 전달 → localDynamicState에 전체 상태 축적 → dataContext._local override → SPA 이동 후 stale 필드 잔존
- 수정: context.setState에는 변경 필드만 전달, __g7PendingLocalState에만 전체 병합 상태 유지
## [engine-v1.24.5]
### Fixed
- SPA 네비게이션 시 DynamicRenderer 내부 useState가 이전 페이지 _local 잔존하여 DataGrid 데이터 깨지는 버그 수정 (template-engine)
- 동일 base layout 공유 페이지 간 루트 컴포넌트 ID 동일 → engine-v1.24.4 트리 구조 통일 후 React가 컴포넌트 보존(remount 안 함)
- DynamicRenderer key에 layout_name 포함하여 레이아웃 변경 시 React 강제 remount
- renderTemplate(), updateTemplateData() 양쪽 모두 적용
- layout_name 부재 시 기존 동작(componentDef.id만 사용) 유지 — 하위 호환
## [engine-v1.24.4]
### Fixed
- renderTemplate()/updateTemplateData() React 트리 구조 통일 — 이중 렌더링(깜빡임) 해소 (template-engine, DynamicRenderer)
- `renderTemplate()`은 `ResponsiveProvider → SlotProvider → [children]` 구조로, `updateTemplateData()`는 `ResponsiveProvider → [children]` 구조로 달랐음
- 데이터소스 완료 시 `updateTemplateData()` 호출 → React가 트리 구조 변경 감지 → 전체 서브트리 언마운트/리마운트
- `updateTemplateData()`에 외부 SlotProvider 추가하여 양쪽 트리 구조 통일
- `DynamicRenderer`의 `isRootRenderer` SlotProvider 래핑 제거 (외부에서 제공하므로 이중 래핑 방지)
- SlotProvider `window.__slotContextValue` 전역 변수 설정을 `useEffect` → `useLayoutEffect`로 변경 (SlotContext)
- 이중 렌더링 해소 후 슬롯 등록 타이밍 이슈 발생: 자식 `useEffect`(슬롯 등록)가 부모 `useEffect`(전역 변수 설정)보다 먼저 실행
- `useLayoutEffect`는 모든 `useEffect`보다 먼저 실행되므로 전역 변수가 슬롯 등록 시점에 항상 사용 가능
## [engine-v1.24.3]
### Fixed
- 다국어 파이프 파라미터에서 산술 연산자(+, -, *, /, %) 포함 표현식이 단순 경로로 오인되어 빈 문자열 반환되던 버그 수정 (TranslationEngine)
- `isComplexExpression` 정규식에 산술/비교 연산자 및 공백 패턴 추가
- 영향 예시: `$t:key|count={{row.options_count - 1}}` → 기존에 count 빈 문자열, 수정 후 정상 평가
## [engine-v1.24.2]
### Added
- `transition_overlay.fallback_target` — 3단계 스켈레톤 타겟팅 지원 (TemplateApp)
- target DOM 존재 → 해당 영역만 스켈레톤 (페이지 내부 전환, 예: 마이페이지 탭)
- target 미존재 + fallback_target 존재 → 해당 영역만 스켈레톤 (페이지 전환)
- 둘 다 미존재 → 전체 페이지 스켈레톤 (초기 로드, `position:fixed; inset:0`)
- CSS `::after` 가림막도 scope에 따라 적절한 selector 적용
- fullpage scope 시 전체 컴포넌트 트리를 스켈레톤으로 렌더
- `LayoutLoader.ts` 타입 정의 + `UpdateLayoutContentRequest` 검증 규칙 추가
## [engine-v1.24.1]
### Fixed
- 초기 페이지 로드 시 스켈레톤 미표시 — target DOM(`#main_content_area` 등)이 `renderTemplate()` 전에 존재하지 않아 opaque fallback 후 시각적 효과 없음 (TemplateApp)
- target DOM 부재 시 `#app`을 fallback 타겟으로 사용하여 스켈레톤 렌더
- CSS `::after` 주입도 `#app` selector로 적용
- 페이지 전환 시에는 기존대로 지정된 target 사용
## [engine-v1.24.0]
### Added
- `transition_overlay` skeleton 스타일 — 레이아웃 JSON 컴포넌트 트리 기반 동적 스켈레톤 UI 렌더링 (TemplateApp)
- `style: "skeleton"` + `skeleton.component`: 레이아웃에서 단일 스켈레톤 렌더러 컴포넌트 지정
- 엔진이 `components` 트리 + `options(animation, iteration_count)`를 props로 전달
- 컴포넌트가 트리를 재귀 순회하여 스켈레톤 플레이스홀더 자동 생성
- 데이터 로드 완료 후 `renderTemplate()` 호출 시 React reconciliation으로 자동 교체
- 컴포넌트 미등록/target 미존재 시 opaque 스타일 자동 폴백
- `skeleton.animation`: pulse / wave / none 선택
- `skeleton.iteration_count`: iteration 블록 기본 반복 횟수
- 백엔드 `UpdateLayoutContentRequest` 검증 규칙 동기화
## [engine-v1.23.0]
### Added
- `transition_overlay` 레이아웃 옵션 — 페이지 전환 시 오버레이로 stale flash 방지 (TemplateApp)
- `true` (축약): opaque 스타일 (document.body에 fixed div 폴백)
- `{ enabled, style, target }`: opaque / blur / fade 선택 + 타겟 컨테이너 지정 가능
- `target` 지정 시: CSS `<style>` 태그를 `<head>`에 주입 → `::after` 의사 요소로 해당 영역만 덮음 (React 렌더 트리 외부, 형제 요소 미영향)
- `target` 미지정 시: `document.body`에 `position:fixed` div 삽입 (폴백)
- React 렌더 사이클과 독립적 — 동기 DOM/CSS 조작으로 즉시 적용
- 모든 경로(progressive/non-progressive/취소/에러)에서 오버레이 정리 보장
## [engine-v1.22.1]
### Fixed
- setLocal() 후 openModal 시 dynamicState 값 누락 — actionContext.state를 globalLocal과 deepMerge하여 __g7PendingLocalState에 전체 _local 반영 (G7CoreGlobals)
- setState(target: "_local")로 설정된 값은 localDynamicState에만 존재하고 globalLocal에 없음
- setLocal → openModal 시퀀스에서 $parent._local 스냅샷에 dynamicState 값이 포함되지 않는 문제 수정
## [engine-v1.22.0]
### Added
- DevTools 모달 정의 교차 검증 — modalStack에 열린 모달 ID가 레이아웃 modals 섹션에 미정의 시 `missing-definition` 이슈 기록 (G7DevToolsCore)
## [engine-v1.21.2]
### Fixed
- getLocal() await 후 stale 반환 근본 수정 — `__g7LastSetLocalSnapshot` fallback 도입 (G7CoreGlobals)
- `__g7PendingLocalState`가 useLayoutEffect에서 클리어된 후에도 최신 setLocal 값 반환
- `dataContext._local` 갱신 시점에 queueMicrotask로 자동 클리어 (DynamicRenderer)
- `handleLocalSetState`에서는 참조하지 않으므로 기존 stale 오염 방지 로직과 충돌 없음
## [engine-v1.21.1]
### Added
- `condition` 속성을 `if`의 별칭으로 네이티브 지원 — 컴포넌트 정의, renderItemChildren, renderWithIteration 모든 경로에서 동작 (RenderHelpers, DynamicRenderer)
- evaluateIfCondition에서 boolean 타입 직접 처리 — 엔진 prop 사전 해석으로 조건이 boolean이 된 경우 대응 (RenderHelpers)
- ComponentDefinition 인터페이스에 `condition?: string | boolean` 속성 추가 (DynamicRenderer)
## [engine-v1.21.0]
### Added
- suppress 에러 핸들러 — 에러 전파를 의도적으로 방지하는 no-op 핸들러 (ActionDispatcher)
- multipart/form-data contentType 자동 감지 및 FormData 변환 (DataSourceManager)
- errorCondition 기능 — API 200 응답이어도 조건부 에러 처리 (DataSourceManager)
- replaceUrl 핸들러 — refetch 없이 URL만 변경
### Fixed
- SPA 네비게이션 시 _global._local에 이전 페이지 _local 상태 잔존 — 스냅샷 순서 수정 (TemplateApp)
- Form 자동 바인딩 setState 경합 — pendingLocal || context.state 우선 사용 (ActionDispatcher)
- Form 자동 바인딩 bindingType 메타데이터 기반 boolean 바인딩 수정 (DynamicRenderer)
- onChange raw value fallback 과도 적용 회귀 제거 (ActionDispatcher)
- DataSourceManager isMultipart 변수 TDZ(Temporal Dead Zone) — 선언 순서 수정
- errorHandling 레이아웃 병합 누락 및 showErrorPage 안정성 개선
- blocking 데이터소스 + errorHandling 데드락 — fallback 동기 적용, 에러핸들러 비동기 실행
- DataSourceManager fallback/errorHandling 우선순위 — errorHandling 먼저, fallback 후적용
- resolveObject 복잡 표현식 미지원 수정 (DataBindingEngine)
- dispatch 경로 context.data._local stale 버그 수정 (G7CoreGlobals)
- refetchDataSource stale localState 버그 수정 (ActionDispatcher)
- DynamicRenderer _localInit shallow merge — deep merge 적용
- 복수 root DynamicRenderer 전역 플래그 경쟁 조건 수정 (__g7ForcedLocalFields 등)
- sequence 내 커스텀 핸들러 상태 동기화 수정 (ActionDispatcher, G7CoreGlobals)
- setState params 키에 {{}} 표현식 사용 시 경고 출력
## [engine-v1.20.0]
### Added
- debounceFlush 기능 - 대기 중인 디바운스 핸들러 즉시 실행
### Fixed
- 디바운스 액션 레이스 컨디션 — 연속 호출 시 이전 결과 누락 방지 (flush 메커니즘)
## [engine-v1.19.1]
### Fixed
- DataGrid footerCells/footerCardChildren 내부 iteration 패턴 미작동 — 3가지 근본 원인 수정 (DataBindingEngine, DynamicRenderer, RenderHelpers)
- `resolveObject`가 iteration이 있는 ComponentDefinition을 사전 해석하여 iteration 변수(`currency` 등)가 미존재 상태에서 에러 발생 → iteration 객체 감지 시 선평가 건너뛰기
- `componentContext`에 데이터소스(`order`, `active_carriers` 등)가 포함되지 않아 `renderItemChildren` 컨텍스트에서 데이터소스 표현식이 빈 값으로 평가 → `parentDataContext` 필드 추가
- `getEffectiveContext`가 `componentContext.state`(= `_local`)만 병합하고 데이터소스 키 미병합 → `parentDataContext` 키를 최상위 컨텍스트에 병합 (기존 키 우선)
## [engine-v1.19.0]
### Added
- actionRef - named_actions 참조 시스템
- named_actions - 명명된 액션 정의 및 재사용
- sequence 내 setState 후 refetchDataSource 호출 시 마이크로태스크 기반 배칭
## [engine-v1.18.0]
### Added
- DataSource onSuccess 콜백에서 response 객체로 API 응답 데이터 접근
- ErrorHandling 에러 핸들링 시스템
### Fixed
- (engine-v1.18.1) __g7SetLocalOverrideKeys 처리를 별도 useLayoutEffect([dataContext._local])로 이동
- (engine-v1.18.2) __g7ForcedLocalFields 조건부 클리어 (불필요한 클리어 방지)
- (engine-v1.18.3) 전역 플래그 클리어를 queueMicrotask로 지연 처리
## [engine-v1.17.0]
### Fixed
#### 상태 동기화 (setLocal/dispatch)
- 커스텀 핸들러에서 setLocal 후 dispatch 호출 시 최신 로컬 상태 참조
- setLocal 후 즉시 dispatch 호출 시 최신 로컬 상태 참조 지원 (G7CoreGlobals)
- (engine-v1.17.1) 커스텀 핸들러에서 G7Core.state.getLocal() 호출 시 최신 상태 참조 지원
- (engine-v1.17.2) _isDispatchFallbackContext가 true면 전역 폴백(setGlobalState) 처리
- (engine-v1.17.2) sequence 내 연속 setState 시 이전 setState 결과 참조 지원
- (engine-v1.17.3) componentContext + context.data 저장하여 $parent 바인딩 지원
- (engine-v1.17.4) 비동기 콜백에서 setLocal 호출 시 dynamicState stale 값 방지
- (engine-v1.17.4) __g7ForcedLocalFields 처리로 최신 필드 값 우선 적용
- (engine-v1.17.5) dataKey 자동 바인딩 컴포넌트에서 setState 핸들러 호출 시 stale 값 방지
- (engine-v1.17.6) globalLocal + pendingState 2단계 병합
- (engine-v1.17.7) globalLocal 사용 (actionContext.state 사용 안 함)
- (engine-v1.17.7) actionContext 유무와 관계없이 항상 globalLocal 업데이트
- (engine-v1.17.8) isRootRenderer=false일 때 클리어 안 되는 버그 수정
- (engine-v1.17.8) setLocal이 업데이트한 키를 기록하여 ROOT의 localDynamicState에서 제거
- (engine-v1.17.9) resolvedPayload(변경된 필드만) 사용 — finalPayload(전체 상태 스냅샷) 사용 방지
- (engine-v1.17.10) pendingLocal 우선 사용 (Form 자동 바인딩 경합 방지)
- (engine-v1.17.10) __g7PendingLocalState 클리어
- (engine-v1.17.11) 모든 루트급 컴포넌트에서 __g7ForcedLocalFields, __g7PendingLocalState 클리어
- (engine-v1.17.12) 전역 _local 상태도 업데이트 (setLocal과 동일)
#### setState 옵션 및 동작
- setState 얕은 병합이 중첩 객체 덮어쓰기 — merge: "deep" / "replace" 옵션 추가 (ActionDispatcher)
- (engine-v1.17.1) setState 배열 조작 미지원 — arrayMethod 파라미터 추가 (push, filter, splice, map)
- (engine-v1.17.2) setState 동일 값 불필요 리렌더 방지 — shallow equality 검사 (G7CoreGlobals)
- (engine-v1.17.3) setState 동적 키 경로 표현식 미평가 — params key 표현식 평가 추가 (ActionDispatcher)
- (engine-v1.17.3) setState onSuccess 컨텍스트에서 {{response.xxx}} 표현식 미평가 수정
- (engine-v1.17.5) setState `_local` + `_global` 동시 수정 시 배치 업데이트 (sequence 내)
- (engine-v1.17.6) setState 순환 업데이트 감지 — 깊이 10 초과 시 에러 (G7CoreGlobals)
- (engine-v1.17.7) setState _isolated 스코프 지원 (target: "isolated")
- (engine-v1.17.9) setState undefined 값 처리 — no-op (removeKey 별도 액션으로 명시적 삭제)
- (engine-v1.17.9) setState 깊은 중첩 경로(4+ 레벨) 중간 객체/배열 자동 생성 (ActionDispatcher)
- (engine-v1.17.11) setState _local 전역 핸들러에서 target 컴포넌트 ID 스코프 지원
- setState dot notation — 멀티 키 병합 시 이전 키 변경 유실 방지 (ActionDispatcher)
#### initGlobal / initLocal
- initGlobal SPA 네비게이션 시 이미 초기화된 키 덮어쓰기 방지 (TemplateApp)
- (engine-v1.17.1) initGlobal 데이터소스 로드 전 실행 — DS 참조 표현식 지연 평가
- (engine-v1.17.2) initGlobal 배열 deep merge 파괴 방지 — replace 전략 적용
- (engine-v1.17.2) initGlobal 조건 표현식 (route.id ? 'edit' : 'create') 평가 지원
- (engine-v1.17.3) initGlobal dot 경로("settings.display.mode") 중첩 객체 확장
- (engine-v1.17.3) initLocal partial/extends 레이아웃에서 무시되는 문제 수정 (DynamicRenderer)
- (engine-v1.17.4) initGlobal 레이아웃 변경 시 이전 키 클린업 (TemplateApp)
- (engine-v1.17.4) initLocal Form 자동 바인딩 우선순위 충돌 해결 — initLocal 후 적용
#### init_actions 타이밍
- init_actions 컴포넌트 마운트 전 실행 — 첫 렌더 사이클 후 지연 (TemplateApp)
- (engine-v1.17.1) init_actions 조건 토글 시 재실행 — 컴포넌트 ID 기반 run-once 가드 (DynamicRenderer)
- (engine-v1.17.1) init_actions replaceUrl가 history.pushState 사용 — replaceState로 수정
- init_actions sequence 내 apiCall 비동기 대기 미지원 수정 (ActionDispatcher)
- (engine-v1.17.2) init_actions route.id 등 라우트 파라미터 선처리 후 실행 (TemplateApp)
- (engine-v1.17.3) init_actions 모달 내부 실행 미지원 — 모달 마운트 시 처리 추가 (DynamicRenderer)
- (engine-v1.17.4) init_actions HMR 중복 실행 방지 (TemplateApp)
- (engine-v1.17.5) init_actions 부모-자식 실행 순서 미보장 — 부모 완료 후 자식 마운트 (DynamicRenderer)
- (engine-v1.17.7) init_actions blocking 데이터소스 완료 대기 후 실행 (TemplateApp)
- (engine-v1.17.8) init_actions setState `_global` 첫 렌더 전 동기 초기화 경로 (G7CoreGlobals)
- (engine-v1.17.9) init_actions onSuccess 중첩 비동기 액션 대기 수정 (ActionDispatcher)
#### dataKey / Form 자동 바인딩
- (engine-v1.17.3) dataKey 자동 바인딩이 명시적 setState 덮어쓰기 — __g7ForcedLocalFields 추적 (FormContext)
- (engine-v1.17.3) Form 자동 바인딩 명시적 value prop 감지 시 스킵 (DynamicRenderer)
- (engine-v1.17.4) dataKey 중첩 객체 경로 (dot-notation name) 생성 지원 (FormContext)
- (engine-v1.17.4) Form 자동 바인딩 sortable 내 컨텍스트 차단 — parentFormContextProp={undefined} 지원
- (engine-v1.17.5) Form 제출 이중 클릭 방지 — 로딩 상태 기반 차단 (ActionDispatcher)
- (engine-v1.17.6) dataKey 데이터소스 로드 전 빈 구조 생성 방지 — waitForData 대기 (DynamicRenderer)
- (engine-v1.17.7) 동일 페이지 복수 폼 dataKey 스코프 분리 — 폼 ID 기반 컨텍스트 (FormContext)
- (engine-v1.17.8) dataKey iteration 내 인덱스 스코프 적용 (FormContext, DynamicRenderer)
- (engine-v1.17.8) FileUploader File/Blob 타입 감지 — 자동 직렬화 제외 (FormContext)
#### Stale Closure
- (engine-v1.17.5) 비동기 콜백(onSuccess/onError)에서 캡처된 상태 대신 현재 상태 재조회 (ActionDispatcher)
- (engine-v1.17.6) componentContext ref 기반 접근으로 마운트 시점 캡처 방지 (DynamicRenderer)
- (engine-v1.17.6) useCallback 과도한 메모이제이션 제거 — 인라인 함수 전환 (DynamicRenderer)
- (engine-v1.17.6) 이벤트 핸들러 라이브 상태 조회 래핑 (DynamicRenderer)
- (engine-v1.17.7) computed 콜백 스냅샷 대신 라이브 상태 getter 사용 (G7CoreGlobals)
- (engine-v1.17.8) _global setState 레이스 컨디션 — 함수형 업데이터 병합 패턴 (G7CoreGlobals)
- (engine-v1.17.8) _global subscribe 콜백 ref 기반 등록 (G7CoreGlobals)
- (engine-v1.17.9) useControllableState prop 동기화 효과 추가 (useControllableState)
#### 캐시
- (engine-v1.17.1) iteration 표현식 캐시 — 첫 아이템 값만 표시되는 문제 (skipCache 적용, DynamicRenderer)
- (engine-v1.17.2) 상태 의존 경로(_local/_global) 30초 영구 캐시 stale — skipCache 적용 (DataBindingEngine)
- (engine-v1.17.2) if 조건 표현식 캐시 — 상태 변경 후 조건 미토글 (skipCache 적용, DynamicRenderer)
- (engine-v1.17.3) 렌더 캐시 컴포넌트 인스턴스 ID 스코프 분리 (DynamicRenderer)
- (engine-v1.17.4) SPA 네비게이션 시 이전 페이지 캐시 잔존 — 레이아웃 변경 시 전체 캐시 클리어
- (engine-v1.17.4) 데이터소스 캐시 키에 직렬화된 params 해시 포함 (DataSourceManager)
- (engine-v1.17.5) computed 의존성 추적 기반 캐시 무효화 (DataBindingEngine)
- (engine-v1.17.5) 모달 데이터소스 refreshOnOpen 시 캐시 클리어 (ModalDataSourceWrapper)
- (engine-v1.17.6) apiCall 기본 cache: false 설정 — 명시적 opt-in 방식 (ActionDispatcher)
- (engine-v1.17.7) subscribe 알림 캐시 우회 — 라이브 상태 직접 조회 (G7CoreGlobals)
- (engine-v1.17.8) 데이터소스 refreshOn 트리거 시 캐시 버스트 (DataSourceManager)
- (engine-v1.17.9) 프리컴파일 표현식 캐시 키에 컨텍스트 변수명 포함 (RenderHelpers)
- (engine-v1.17.11) _computed prop 캐시 버그 — getComputedAwareOptions() skipCache 적용 (DynamicRenderer)
#### 기타
- (engine-v1.17.1) Form validation 에러 응답 경로 정규화 — error.errors / error.message 통일 (ActionDispatcher)
- (engine-v1.17.2) Button이 Form 내에서 기본 type="submit" — type="button" 기본값 적용 (ComponentRegistry)
- (engine-v1.17.5) iteration item_var 스코프 격리 — 부모 루프 변수 자식에 누출 방지 (DynamicRenderer)
- (engine-v1.17.6) 데이터소스 refreshOn 무한루프 — 리프레시 순환 감지 및 디바운스 (ActionDispatcher)
- (engine-v1.17.6) cellChildren 부모 데이터 변경 시 stale props — 재평가 추가 (DynamicRenderer)
- (engine-v1.17.6) 커스텀 핸들러 등록 타이밍 — 등록 대기 큐, 지연 액션 대기 (ActionDispatcher)
- (engine-v1.17.6) 커스텀 핸들러 async 반환값 sequence 내 자동 await (ActionDispatcher)
- (engine-v1.17.7) computed 순환 의존성 감지 — visited 세트 기반 에러 발생 (DataBindingEngine)
- (engine-v1.17.7) blocking 데이터소스 에러 시 무한 로딩 — fallback/에러 핸들러 트리거
- (engine-v1.17.8) 언마운트된 컴포넌트 setLocal 무시 — no-op 처리 (G7CoreGlobals)
- (engine-v1.17.8) 데이터소스 의존성 체이닝 — dependsOn 실행 순서 보장 (ActionDispatcher)
- (engine-v1.17.9) 데이터소스 params 표현식 캐시 — 상태 변경 후 re-fetch 미실행 방지 (G7CoreGlobals)
- (engine-v1.17.10) __g7PendingLocalState 컴포넌트 마운트 시 flush (DynamicRenderer)
- (engine-v1.17.10) __g7SetLocalOverrideKeys 레이아웃 변경 시 클리어 (G7CoreGlobals)
- (engine-v1.17.10) Input controlled/uncontrolled 전환 방지 — 빈 문자열 fallback
- (engine-v1.17.11) errorHandling + blocking 데드락 — fallback 정의 시 에러 핸들러 비동기 실행
## [engine-v1.16.0]
### Added
- globalHeaders - API 호출 시 패턴 매칭 기반 전역 HTTP 헤더 추가
- setGlobalHeaders, matchesPattern, getMatchingGlobalHeaders 메서드 (ActionDispatcher)
- DataSource globalHeaders - API 데이터 소스 헤더 추가
- parentDataContext - {{$parent._local.xxx}} 바인딩 지원 (DynamicRenderer)
- getParent, setParentLocal, setParentGlobal - 부모 컨텍스트 API (G7CoreGlobals)
- handleParentScopeSetState - $parent._global/._local setState 처리
- 레이아웃 레벨 globalHeaders 설정 (LayoutLoader)
- $parent 바인딩 컨텍스트 (모달 및 중첩 레이아웃)
### Fixed
- DataSourceManager onSuccess에서 openModal 시 $parent._local 접근 불가 수정
- ActionDispatcher 복합 표현식 (삼항 연산자 등) 미평가 수정
- setLocal()이 expandedRows 등 배열 상태를 초기값으로 덮어쓰기 수정 (DynamicRenderer)
- _computed stale closure 및 deepMerge sparse array 수정 (ActionDispatcher, DynamicRenderer, G7CoreGlobals)
- setParentLocal 후 getLocal() stale 데이터 반환 수정 (DynamicRenderer, G7CoreGlobals)
- deepMergeState 배열→객체 잘못된 병합 수정
- 콜백 prop 내 액션 정의 선평가 방지 및 비동기 콜백 상태 참조 수정 (DataBindingEngine, G7CoreGlobals)
- 레이아웃 전환 시 _global._local cleanup 미실행 수정 (TemplateApp)
## [engine-v1.15.0]
### Added
- permissions - 레이아웃 접근 권한 식별자 배열 (401/403 응답)
- extensionPointProps - 확장 영역에서 전달 가능한 props
- isInsideIteration - iteration 캐시 버그 방지 플래그
### Fixed
- expandChildren _computed 상태 동기화 — computedRef 패턴 적용 (DynamicRenderer, G7CoreGlobals)
- `_local` 변경 시 `_computed` 재계산 미발생 수정 (TemplateApp, DynamicRenderer)
- expandChildren 상태 동기화 버그 — stateRef 패턴 적용 (DynamicRenderer, G7CoreGlobals)
- cellChildren 글로벌 상태 접근 불가 수정 (G7CoreGlobals)
- $computed 별칭 미지원 수정 (DataBindingEngine)
- 언어 전환 시 모듈 핸들러 재등록 누락 수정
## [engine-v1.14.0]
### Added
- sortable - @dnd-kit 기반 네이티브 드래그앤드롭 정렬 기능
- SortableContainer, SortableItemWrapper 컴포넌트
- itemTemplate - sortable 내 아이템 렌더링 템플릿
- _isolated - 격리된 상태 바인딩 (성능 최적화)
- isolatedStateId - 격리된 상태 식별자 (DevTools용)
- IsolatedStateContext 시스템
### Fixed
- DataGrid expandChildren 상태 동기화 버그 수정 (DynamicRenderer)
- $event 표현식 캐시로 조건 잘못 평가 수정 (ActionDispatcher)
- _local 경로 캐시로 상태 변경 미반영 수정 (DataBindingEngine)
- DynamicRenderer text prop 파이프 표현식 미처리 수정
- 언어 전환 시 템플릿 핸들러 재등록 누락 수정 (TemplateApp)
## [engine-v1.13.0]
### Added
- classMap - 조건부 CSS 클래스 매핑 (중첩 삼항 연산자 대체)
- componentPath - 경로 기반 컴포넌트 식별 (ID 없는 컴포넌트 편집용)
- WYSIWYG 에디터 지원 (ensureComponentId, moveComponentByPaths, updateComponentByPath)
### Fixed
- onSuccess 배열 내 복수 setState 순차 실행 시 상태 동기화 수정 (ActionDispatcher)
- DataBindingEngine $t: 토큰 처리 개선
- init_actions setGlobalState 비동기 에러 수정 (TemplateApp)
- Form 자동 바인딩 debounce stale 상태 수정 (DynamicRenderer, FormContext, G7CoreGlobals)
- cellChildren remount 리렌더 및 _remountKeys 경로 수정 (ActionDispatcher, DynamicRenderer)
- remount 핸들러 cellChildren ID 표현식 해석 버그 수정 (G7CoreGlobals, RenderHelpers)
- sequence 내 closeModal 후 setState 시 모달 재오픈 수정 (ActionDispatcher)
- setState dot notation 멀티 키 병합 시 이전 키 변경 유실 수정 (ActionDispatcher)
## [engine-v1.12.0]
### Added
- expandChildren - 확장 영역 내 액션에서 부모 상태 업데이트
- _isolated 컨텍스트 시스템 (IsolatedStateContext)
- onDragStart, onDragEnd - 편집기에서 컴포넌트 드래그 지원
### Fixed
- actions 객체 형식 호환성 에러 수정 (DynamicRenderer)
- LayoutLoader 401 에러 시 토큰 삭제 및 재시도 미동작 수정
- SPA navigate 시 DataGrid 빈 화면 렌더링 수정 (TemplateApp)
- setState _global dot notation 시 기존 상태 유실 수정 (ActionDispatcher)
- 커스텀 컴포넌트 change 이벤트 핸들링 버그 수정 (ActionDispatcher)
- style prop CSS 문자열 자동 객체 변환 미지원 수정 (DynamicRenderer)
## [engine-v1.11.0]
### Added
- onComponentEvent - 컴포넌트 이벤트 구독 및 핸들러 실행
- extensionPointProps - 확장 영역 props 전달
- isEditMode, onComponentSelect, onComponentHover - 편집기 모드 지원
- initActions - 동적 표현식 기반 초기값 설정
- initGlobal, initLocal, initComputed - 데이터 바인딩 병합 (LayoutLoader)
- scrollIntoView 핸들러
- 위지윅 레이아웃 편집기 관련 전역 API (G7CoreGlobals)
### Fixed
- navigate/back 재진입 시 init_actions 데이터소스 유실 수정 (TemplateApp)
- sequence 핸들러 _local 상태 동기화 수정
- 배열 쿼리 파라미터 처리 버그 수정 (TemplateApp, ApiClient, Router, ActionDispatcher, DataSourceManager)
- dataKey 바인딩 버그 수정 (TemplateApp)
## [engine-v1.10.0]
### Added
- conditions 속성 - AND/OR 그룹 및 if-else 체인 조건부 렌더링 (DynamicRenderer)
- conditions 액션 - 조건부 액션 실행 (ActionDispatcher)
- conditions 속성 - 조건부 데이터 소스 로딩 (DataSourceManager)
- conditions 속성 - 조건부 레이아웃 로드 (LayoutLoader)
- slotId 동적 결정 - 표현식 지원으로 동적 슬롯 결정
- zIndex 속성 - 렌더링 순서 제어 (기본값: 0)
- SlotContext 시스템 모듈
- 배열 쿼리 파라미터 (navigate 핸들러)
### Fixed
- setState deep merge 및 배열 쿼리스트링 처리 수정
- Slot 컴포넌트 에러 및 검색 편집 모드 에러 수정
- 쿼리 스트링 기반 검색 필터 미설정 수정
## [engine-v1.9.0]
### Added
- _defines - 컴포넌트에서 {{_defines.xxx}}로 접근 가능한 정의 변수
- 파이프 함수 (`|uppercase`, `|lowercase` 등)
- $get 헬퍼 함수 - 안전한 중첩 속성 접근
- $switch 표현식 - 다중 분기 값 선택
- classMap - 조건부 CSS 클래스 (key → variants 매핑)
- computed - 계산된 값 시스템
- switch params.value 지원, default 케이스 지원
### Fixed
- 레이아웃 서빙 시 defines/computed 속성 미포함 수정
- validation 에러 성공 후 미클리어 수정
- 액션 핸들러 캐시 문제 수정 (ActionDispatcher)
- resolveValue 호출 캐시 문제 수정 (ActionDispatcher)
## [engine-v1.8.0]
### Added
- 동적 레이아웃 로드 시스템 (LayoutLoader)
- 외부 스크립트 동적 로드 (scripts 속성)
- if 조건을 사용한 조건부 로드
### Fixed
- dataKey 자동바인딩 버그 수정 (DynamicRenderer)
- data_source refetchOnMount 속성 누락 수정
- iterator 타입 지원 및 에러 수정 (DynamicRenderer, RenderHelpers)
- 에러 객체 deep merge 처리 수정 (ActionDispatcher)
## [engine-v1.7.0]
### Added
- loadScript 핸들러 - 외부 JavaScript 동적 로드
- callExternal 핸들러 - 외부 함수 호출
### Fixed
- 설정 탭 모듈 목록 iteration 버그 수정 (DynamicRenderer)
- 점진적 콘텐츠 에러 핸들링 실패 수정 (TemplateApp, ActionDispatcher, DynamicRenderer)
- refetchDataSource 시 blur_until_loaded 미적용 수정 (TemplateApp)
- blur_until_loaded 개별 DOM 요소 처리 수정
## [engine-v1.6.0]
### Added
- errorHandling - 레이아웃 레벨 에러 핸들링 설정
- showErrorPage 핸들러 - 에러 페이지 표시
## [engine-v1.5.0]
### Added
- blur_until_loaded 표현식 지원 (`{{_global.isSaving}}` 등 동적 조건)
### Fixed
- 복잡한 조건식이 포함된 다국어 문자열 처리 오류 수정 (TranslationEngine)
- 번역 파라미터로 공백 문자열 전달 시 파싱 오류 수정 (TranslationEngine)
- apiCall 액션에 auth_required 옵션 누락 수정 (ActionDispatcher)
- data_source.endpoint 표현식 미처리 수정 (DataSourceManager)
## [engine-v1.4.0]
### Added
- 조건부 데이터 소스 로딩 (if 속성) - 생성/수정 모드 분기
### Fixed
- 데이터그리드 표현식 렌더링 오류 수정
- validation error 미표시 수정
## [engine-v1.2.0]
### Added
- 모달 스택 - 중첩 모달 지원 (_global.modalStack)
- 멀티 모달 지원
- 반복 컨텍스트 바인딩 (iteration 내 표현식)
- text 속성 복합 바인딩
### Fixed
- ModalWrapper 데이터 바인딩 시 캐시 문제 수정 (ModalDataSourceWrapper)
- ModalWrapper 렌더링 시 iteration 미작동 수정 (DynamicRenderer)
- 모달 오픈 시 API 기반 바인딩 미동작 수정 (ModalDataSourceWrapper)
- 모달 클릭 시 API 응답 에러 처리 미개선 수정
- 모달 렌더링 오류 수정 (DynamicRenderer)
- 반복 컨텍스트에서 파라미터가 포함된 다국어 번역 미작동 수정 (DynamicRenderer, RenderHelpers)
- 다국어 파라미터로 데이터 미전달 수정
## [engine-v1.1.0]
### Added
- 다크 모드 지원 (Tailwind dark: variant)
- 반응형 레이아웃 (responsive 속성)
- 전역 상태 관리 (_global, _local)
- 데이터 바인딩 및 표현식 ({{user.name}}, {{route.id}})
- Optional Chaining & Nullish Coalescing 지원
### Fixed
- 언어 변경 후 navigate 핸들러 미작동 수정 (TemplateApp)
- 페이지네이션 오류, DataGrid 렌더링 오류 수정
- 검색어 입력 후 엔터 키 미반응 수정
- 검색 미작동, queryString 미반영 수정
- 체크박스 동작 오류 — preventDefault 누락 수정
- 로그인 시 ActionDispatcher actions 미실행 수정 (TemplateApp, Router)
- 토큰 만료 후 refresh 토큰 / 로그인 리다이렉션 미작동 수정
- 렌더링 오류 수정 (DataBindingEngine)
- 템플릿 엔진 로더/렌더링 오류 (hotfix)
@@ -0,0 +1,555 @@
/**
* ComponentRegistry.ts
*
* 템플릿 컴포넌트를 동적으로 로드하고 전역 레지스트리에 등록하는 클래스
*
* 역할:
* - /build/template/dist/components.js 동적 로딩
* - components.json 매니페스트 검증
* - 컴포넌트 타입별 분류 (basic, composite, layout)
* - 전역 레지스트리 관리 및 캐싱
*/
import type { ComponentType } from 'react';
import { createLogger } from '../utils/Logger';
const logger = createLogger('ComponentRegistry');
/**
* 컴포넌트 타입 정의
*/
export type ComponentTypeEnum = 'basic' | 'composite' | 'layout';
/**
* 컴포넌트 메타데이터 인터페이스
*/
export interface ComponentMetadata {
/** 컴포넌트 이름 */
name: string;
/** 컴포넌트 타입 */
type: ComponentTypeEnum;
/** 컴포넌트 설명 */
description?: string;
/** 허용된 props 목록 */
props?: string[];
/** children 허용 여부 */
allowsChildren?: boolean;
/**
* 바인딩 처리를 건너뛸 props 키 목록
*
* 컴포넌트가 내부적으로 row/iteration 컨텍스트 등을 사용하여
* 자체적으로 바인딩을 처리해야 하는 props 키를 지정합니다.
*
* 예시: DataGrid는 ['cellChildren', 'expandChildren', 'expandContext', 'render']
*/
skipBindingKeys?: string[];
/**
* Form 자동 바인딩 시 boolean 값의 바인딩 타입
*
* - 'checked': 항상 checked prop으로 바인딩 (Toggle, Checkbox 등)
* - 'checkable': type이 checkbox/radio일 때만 checked, 그 외 value (Input)
* - 미지정: 항상 value prop으로 바인딩 (RadioGroup, Select 등 기본값)
*/
bindingType?: 'checked' | 'checkable';
}
/**
* components.json 매니페스트 스키마
*/
export interface ComponentManifest {
/** 매니페스트 버전 */
version: string;
/** 템플릿 식별자 */
templateId: string;
/** 컴포넌트 목록 */
components: {
/** 기본 컴포넌트 목록 */
basic: ComponentMetadata[];
/** 집합 컴포넌트 목록 */
composite: ComponentMetadata[];
/** 레이아웃 컴포넌트 목록 */
layout: ComponentMetadata[];
};
}
/**
* 레지스트리 맵 인터페이스
*/
export interface RegistryMap {
[componentName: string]: {
component: ComponentType<any>;
metadata: ComponentMetadata;
};
}
/**
* 로딩 상태 타입
*/
export type LoadingState = 'idle' | 'loading' | 'loaded' | 'error';
/**
* ComponentRegistry 에러 클래스
*/
export class ComponentRegistryError extends Error {
constructor(message: string, public code: string, public details?: any) {
super(message);
this.name = 'ComponentRegistryError';
}
}
/**
* ComponentRegistry 클래스
*
* 싱글톤 패턴으로 전역 컴포넌트 레지스트리 관리
*/
export class ComponentRegistry {
private static instance: ComponentRegistry | null = null;
/** 매니페스트 캐시 (템플릿별) */
private static manifestCache = new Map<string, ComponentManifest>();
/** 컴포넌트 레지스트리 맵 */
private registry: RegistryMap = {};
/** 컴포넌트 매니페스트 */
private manifest: ComponentManifest | null = null;
/** 로딩 상태 */
private loadingState: LoadingState = 'idle';
/** 에러 정보 */
private error: Error | null = null;
/** 템플릿 ID */
private templateId: string | null = null;
/** 템플릿 타입 (admin 또는 user) */
private templateType: string | null = null;
/**
* private 생성자 (싱글톤 패턴)
*/
private constructor() {}
/**
* 싱글톤 인스턴스 반환
*/
public static getInstance(): ComponentRegistry {
if (!ComponentRegistry.instance) {
ComponentRegistry.instance = new ComponentRegistry();
}
return ComponentRegistry.instance;
}
/**
* 레지스트리 초기화 (테스트용)
*/
public static resetInstance(): void {
ComponentRegistry.instance = null;
}
/**
* 템플릿 컴포넌트 로드 및 등록
*
* @param templateId 템플릿 식별자
* @param templateType 템플릿 타입 (admin 또는 user)
*/
public async loadComponents(templateId: string, templateType: string): Promise<void> {
if (this.loadingState === 'loading') {
throw new ComponentRegistryError(
'Components are already being loaded',
'LOADING_IN_PROGRESS'
);
}
if (this.loadingState === 'loaded' && this.templateId === templateId && this.templateType === templateType) {
logger.log('Components already loaded for template:', templateId, templateType);
return;
}
this.loadingState = 'loading';
this.templateId = templateId;
this.templateType = templateType;
this.error = null;
try {
// 1. components.json 매니페스트 로드
await this.loadManifest();
// 2. 컴포넌트 번들 동적 import
await this.loadComponentBundle();
// 3. 로딩 완료
this.loadingState = 'loaded';
logger.log('Successfully loaded components:', Object.keys(this.registry).length);
} catch (error) {
this.loadingState = 'error';
this.error = error instanceof Error ? error : new Error(String(error));
throw new ComponentRegistryError(
`Failed to load components: ${this.error.message}`,
'LOAD_FAILED',
{ originalError: this.error }
);
}
}
/**
* components.json 매니페스트 로드 및 검증 (캐싱 지원)
*/
private async loadManifest(): Promise<void> {
try {
if (!this.templateId) {
throw new ComponentRegistryError(
'Template ID not set',
'TEMPLATE_ID_NOT_SET'
);
}
// 캐시 키 생성
const cacheKey = `${this.templateId}:${this.templateType}`;
// 캐시 확인
if (ComponentRegistry.manifestCache.has(cacheKey)) {
this.manifest = ComponentRegistry.manifestCache.get(cacheKey)!;
logger.log('Manifest loaded from cache:', this.manifest.templateId);
return;
}
// 캐시 미스 - API에서 로드
const manifestUrl = `/api/templates/${this.templateId}/components.json`;
const response = await fetch(manifestUrl);
if (!response.ok) {
throw new ComponentRegistryError(
`Failed to fetch manifest: ${response.status} ${response.statusText}`,
'MANIFEST_FETCH_FAILED',
{ status: response.status, statusText: response.statusText }
);
}
const manifest = await response.json();
// 매니페스트 검증
this.validateManifest(manifest);
this.manifest = manifest;
// 캐시에 저장
ComponentRegistry.manifestCache.set(cacheKey, manifest);
logger.log('Manifest loaded and cached:', manifest.templateId);
} catch (error) {
if (error instanceof ComponentRegistryError) {
throw error;
}
throw new ComponentRegistryError(
'Failed to load component manifest',
'MANIFEST_LOAD_FAILED',
{ originalError: error }
);
}
}
/**
* 매니페스트 검증
*/
private validateManifest(manifest: any): void {
// 필수 필드 검증
if (!manifest.version) {
throw new ComponentRegistryError(
'Manifest missing required field: version',
'MANIFEST_INVALID',
{ field: 'version' }
);
}
if (!manifest.templateId) {
throw new ComponentRegistryError(
'Manifest missing required field: templateId',
'MANIFEST_INVALID',
{ field: 'templateId' }
);
}
// 컴포넌트 객체 검증
if (!manifest.components || typeof manifest.components !== 'object') {
throw new ComponentRegistryError(
'Manifest missing required field: components',
'MANIFEST_INVALID',
{ field: 'components' }
);
}
// 컴포넌트 배열 검증
const componentTypes: ComponentTypeEnum[] = ['basic', 'composite', 'layout'];
for (const type of componentTypes) {
if (!Array.isArray(manifest.components[type])) {
throw new ComponentRegistryError(
`Manifest field 'components.${type}' must be an array`,
'MANIFEST_INVALID',
{ field: `components.${type}`, value: manifest.components[type] }
);
}
// 각 컴포넌트 메타데이터 검증
manifest.components[type].forEach((meta: any, index: number) => {
if (!meta.name || typeof meta.name !== 'string') {
throw new ComponentRegistryError(
`Invalid component metadata at ${type}[${index}]: missing or invalid 'name'`,
'MANIFEST_INVALID',
{ type, index, metadata: meta }
);
}
if (!meta.type || typeof meta.type !== 'string') {
throw new ComponentRegistryError(
`Invalid component metadata at ${type}[${index}]: missing or invalid 'type'`,
'MANIFEST_INVALID',
{ type, index, metadata: meta }
);
}
});
}
logger.log('Manifest validation passed');
}
/**
* 컴포넌트 번들에서 컴포넌트 가져오기
*
* admin.blade.php에서 이미 IIFE 번들을 로드했으므로,
* 전역 변수에서 컴포넌트를 가져옵니다 (HTTP 요청 불필요).
*/
private async loadComponentBundle(): Promise<void> {
try {
if (!this.templateId) {
throw new ComponentRegistryError(
'Template ID not set',
'TEMPLATE_ID_NOT_SET'
);
}
// 전역 객체에서 컴포넌트 가져오기
// admin.blade.php에서 이미 <script> 태그로 로드되어 전역 변수에 노출됨
const globalVarName = this.getGlobalVariableName();
const module = (window as any)[globalVarName];
if (!module || typeof module !== 'object') {
throw new ComponentRegistryError(
`Component bundle not loaded. Expected global variable: ${globalVarName}. ` +
`Ensure admin.blade.php includes the IIFE bundle script.`,
'BUNDLE_NOT_LOADED',
{ expectedVariable: globalVarName }
);
}
// 매니페스트의 모든 컴포넌트 등록
await this.registerComponentsFromManifest(module);
logger.log('Component bundle loaded from global variable:', globalVarName);
} catch (error) {
if (error instanceof ComponentRegistryError) {
throw error;
}
throw new ComponentRegistryError(
'Failed to load component bundle',
'BUNDLE_LOAD_FAILED',
{ originalError: error }
);
}
}
/**
* 템플릿 ID로부터 전역 변수명 생성
*/
private getGlobalVariableName(): string {
if (!this.templateId) {
throw new ComponentRegistryError(
'Template ID not set',
'TEMPLATE_ID_NOT_SET'
);
}
// sirsoft-admin_basic -> SirsoftAdminBasic
return this.templateId
.split(/[-_]/)
.map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join('');
}
/**
* 매니페스트 기반 컴포넌트 등록
*/
private async registerComponentsFromManifest(module: any): Promise<void> {
if (!this.manifest) {
throw new ComponentRegistryError(
'Manifest not loaded',
'MANIFEST_NOT_LOADED'
);
}
const componentTypes: ComponentTypeEnum[] = ['basic', 'composite', 'layout'];
for (const type of componentTypes) {
const components = this.manifest.components[type] || [];
for (const metadata of components) {
const componentName = metadata.name;
const component = module[componentName];
if (!component) {
logger.warn(`Component '${componentName}' not found in bundle`);
continue;
}
// 컴포넌트 등록
this.registerComponent(componentName, component, metadata);
}
}
}
/**
* 개별 컴포넌트 등록
*/
private registerComponent(
name: string,
component: ComponentType<any>,
metadata: ComponentMetadata
): void {
if (this.registry[name]) {
logger.warn(`Component '${name}' already registered, overwriting`);
}
this.registry[name] = {
component,
metadata,
};
logger.log(`[ComponentRegistry] Registered component: ${name} (${metadata.type})`);
}
/**
* 컴포넌트 조회
*
* @param name 컴포넌트 이름
* @returns 컴포넌트 또는 null
*/
public getComponent(name: string): ComponentType<any> | null {
const entry = this.registry[name];
return entry ? entry.component : null;
}
/**
* 컴포넌트 메타데이터 조회
*
* @param name 컴포넌트 이름
* @returns 메타데이터 또는 null
*/
public getMetadata(name: string): ComponentMetadata | null {
const entry = this.registry[name];
return entry ? entry.metadata : null;
}
/**
* 컴포넌트 존재 여부 확인
*
* @param name 컴포넌트 이름
* @returns 존재 여부
*/
public hasComponent(name: string): boolean {
return name in this.registry;
}
/**
* 타입별 컴포넌트 목록 조회
*
* @param type 컴포넌트 타입
* @returns 컴포넌트 이름 배열
*/
public getComponentsByType(type: ComponentTypeEnum): string[] {
return Object.entries(this.registry)
.filter(([_, entry]) => entry.metadata.type === type)
.map(([name, _]) => name);
}
/**
* 모든 컴포넌트 목록 조회
*
* @returns 컴포넌트 이름 배열
*/
public getAllComponents(): string[] {
return Object.keys(this.registry);
}
/**
* 전체 컴포넌트 맵 반환
*
* 컴포넌트 이름을 키로, React 컴포넌트를 값으로 하는 맵을 반환합니다.
* CardGrid 등 composite 컴포넌트에서 renderItemChildren 호출 시 사용합니다.
*
* @returns 컴포넌트 이름 → React 컴포넌트 맵
*/
public getComponentMap(): Record<string, ComponentType<any>> {
const map: Record<string, ComponentType<any>> = {};
for (const [name, entry] of Object.entries(this.registry)) {
map[name] = entry.component;
}
return map;
}
/**
* 로딩 상태 조회
*/
public getLoadingState(): LoadingState {
return this.loadingState;
}
/**
* 에러 정보 조회
*/
public getError(): Error | null {
return this.error;
}
/**
* 현재 템플릿 ID 조회
*/
public getTemplateId(): string | null {
return this.templateId;
}
/**
* 매니페스트 조회
*/
public getManifest(): ComponentManifest | null {
return this.manifest;
}
/**
* 레지스트리 클리어 (테스트용)
*/
public clear(): void {
this.registry = {};
this.manifest = null;
this.loadingState = 'idle';
this.error = null;
this.templateId = null;
this.templateType = null;
logger.log('Registry cleared');
}
}
// 전역 export
export default ComponentRegistry;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,293 @@
import type { TranslationContext } from './TranslationEngine';
import { TemplateEngineError } from './TemplateEngineError';
import { createLogger } from '../utils/Logger';
const logger = createLogger('ErrorDisplay');
/**
* 에러 표시 옵션
*/
export interface ErrorDisplayOptions {
/** 에러 제목 */
title: string;
/** 사용자 메시지 */
message: string;
/** 상세 메시지 (API 응답 메시지 등) */
detailMessage?: string;
/** Font Awesome 아이콘 클래스 */
icon: string;
/** Stack Trace 표시 여부 */
showStack: boolean;
/** Stack Trace 문자열 */
stackTrace?: string;
/** 새로고침 버튼 표시 여부 */
showReloadButton: boolean;
/** 디버그 모드 여부 */
debug: boolean;
}
/**
* 에러 화면 렌더링 컴포넌트
*
* 주의: 이 컴포넌트는 템플릿 엔진 초기화 실패 시에도 사용되므로
* Tailwind CSS 클래스 대신 인라인 스타일을 사용합니다.
* 초기화 실패 시점에는 CSS가 아직 로드되지 않았을 수 있기 때문입니다.
*/
export class ErrorDisplay {
/**
* 에러 화면을 렌더링합니다.
*
* @param containerId 컨테이너 요소 ID
* @param options 에러 표시 옵션
*/
static render(containerId: string, options: ErrorDisplayOptions): void {
const container = document.getElementById(containerId);
if (!container) {
logger.error(`Container #${containerId} not found`);
return;
}
// 스택 트레이스 표시 여부 결정
const shouldShowStack =
options.debug && options.showStack && options.stackTrace;
// 다크 모드 감지
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
// 인라인 스타일 정의 (CSS 의존성 없이 동작)
const styles = {
container: `
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background-color: ${isDarkMode ? '#111827' : '#f9fafb'};
padding: 1rem;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
`,
card: `
max-width: 28rem;
width: 100%;
background-color: ${isDarkMode ? '#1f2937' : '#ffffff'};
border-radius: 0.5rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
padding: 2rem;
text-align: center;
`,
iconContainer: `
margin-bottom: 1.5rem;
`,
icon: `
font-size: 4rem;
color: #ef4444;
`,
title: `
font-size: 1.5rem;
font-weight: 700;
color: ${isDarkMode ? '#ffffff' : '#111827'};
margin-bottom: 1rem;
`,
message: `
color: ${isDarkMode ? '#d1d5db' : '#4b5563'};
margin-bottom: 0.5rem;
line-height: 1.625;
`,
detailMessage: `
font-size: 0.875rem;
color: ${isDarkMode ? '#9ca3af' : '#6b7280'};
margin-bottom: 1.5rem;
background-color: ${isDarkMode ? '#374151' : '#f3f4f6'};
padding: 0.5rem 0.75rem;
border-radius: 0.25rem;
`,
spacer: `
margin-bottom: 1.5rem;
`,
stackContainer: `
margin-top: 1.5rem;
padding: 1rem;
background-color: ${isDarkMode ? '#374151' : '#f3f4f6'};
border-radius: 0.375rem;
text-align: left;
`,
stackTitle: `
font-size: 0.875rem;
font-weight: 600;
color: ${isDarkMode ? '#e5e7eb' : '#374151'};
margin-bottom: 0.5rem;
`,
stackTrace: `
font-size: 0.75rem;
color: ${isDarkMode ? '#d1d5db' : '#4b5563'};
overflow-x: auto;
white-space: pre-wrap;
word-break: break-word;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
`,
buttonContainer: `
margin-top: 1.5rem;
`,
button: `
display: inline-flex;
align-items: center;
padding: 0.75rem 1.5rem;
background-color: #2563eb;
color: #ffffff;
font-weight: 500;
border-radius: 0.375rem;
border: none;
cursor: pointer;
transition: background-color 0.2s;
`,
};
container.innerHTML = `
<div style="${styles.container}">
<div style="${styles.card}">
<!-- 아이콘 -->
<div style="${styles.iconContainer}">
<i class="fa-solid ${options.icon}" style="${styles.icon}"></i>
</div>
<!-- 제목 -->
<h1 style="${styles.title}">
${this.escapeHtml(options.title)}
</h1>
<!-- 사용자 메시지 -->
<p style="${styles.message}">
${this.escapeHtml(options.message)}
</p>
<!-- 상세 메시지 (API 응답 등) -->
${
options.detailMessage
? `
<p style="${styles.detailMessage}">
${this.escapeHtml(options.detailMessage)}
</p>
`
: `<div style="${styles.spacer}"></div>`
}
<!-- Stack Trace (디버그 모드일 때만) -->
${
shouldShowStack
? `
<div style="${styles.stackContainer}">
<p style="${styles.stackTitle}">
Stack Trace:
</p>
<pre style="${styles.stackTrace}">${this.escapeHtml(
options.stackTrace
)}</pre>
</div>
`
: ''
}
<!-- 새로고침 버튼 (복구 가능할 때만) -->
${
options.showReloadButton
? `
<div style="${styles.buttonContainer}">
<button
onclick="window.location.reload()"
style="${styles.button}"
onmouseover="this.style.backgroundColor='#1d4ed8'"
onmouseout="this.style.backgroundColor='#2563eb'"
>
<i class="fa-solid fa-rotate-right" style="margin-right: 0.5rem;"></i>
새로고침
</button>
</div>
`
: ''
}
</div>
</div>
`;
}
/**
* TemplateEngineError 객체로부터 에러 화면을 렌더링합니다.
*
* @param containerId 컨테이너 요소 ID
* @param error 템플릿 엔진 에러 객체
* @param title 에러 제목
* @param debug 디버그 모드 여부
* @param context 번역 컨텍스트 (선택)
* @param translationEngine 번역 엔진 (선택)
* @param originalError 원본 에러 객체 (선택, 상세 메시지 추출용)
*/
static renderFromError(
containerId: string,
error: TemplateEngineError,
title: string,
debug: boolean = false,
context?: TranslationContext,
translationEngine?: {
translate: (key: string, context: TranslationContext) => string;
},
originalError?: Error
): void {
// 다국어 메시지 조회
let message: string;
let detailMessage: string | undefined;
// userMessageKey가 $t: 로 시작하면 번역 시도
if (error.userMessageKey.startsWith('$t:')) {
if (translationEngine && context) {
try {
message = translationEngine.translate(error.userMessageKey, context);
} catch (e) {
// 번역 실패 시 키에서 $t: 제거하여 표시
message = error.userMessageKey.replace('$t:', '');
}
} else {
// 번역 엔진이 없으면 키에서 $t: 제거하여 표시
message = error.userMessageKey.replace('$t:', '');
}
} else {
// 일반 에러 메시지는 그대로 사용
message = error.userMessageKey;
}
// 원본 에러에서 상세 메시지 추출 (LayoutLoaderError 등)
if (originalError) {
const anyError = originalError as any;
// LayoutLoaderError의 details.apiMessage 추출
if (anyError.details?.apiMessage) {
detailMessage = anyError.details.apiMessage;
}
// Axios 에러의 response.data.message 추출
else if (anyError.response?.data?.message) {
detailMessage = anyError.response.data.message;
}
}
this.render(containerId, {
title,
message,
detailMessage,
icon: error.icon,
showStack: error.showStack,
stackTrace: error.stack,
showReloadButton: error.recoverable,
debug,
});
}
/**
* HTML 이스케이프 처리
*
* @param text 이스케이프할 텍스트
*/
private static escapeHtml(text: string | undefined): string {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}
@@ -0,0 +1,385 @@
/**
* ErrorPageHandler
*
* 에러 페이지를 처리하는 핸들러 클래스
* template.json의 error_config를 읽어 에러 코드에 맞는 레이아웃을 로드하고 렌더링합니다.
*/
import type { LayoutLoader } from './LayoutLoader';
import type { DataSourceManager, DataSource } from './DataSourceManager';
import { createLogger } from '../utils/Logger';
const logger = createLogger('ErrorPageHandler');
/**
* 렌더링 옵션 인터페이스
*/
export interface RenderOptions {
containerId: string;
layoutJson: unknown;
dataContext?: Record<string, unknown>;
translationContext?: {
templateId: string;
locale: string;
};
}
/**
* 렌더링 함수 타입 (의존성 주입용)
*/
export type RenderFunction = (options: RenderOptions) => Promise<void>;
/**
* 에러 설정 인터페이스
*/
export interface ErrorConfig {
layouts: Record<number | string, string>; // { 404: "404", 403: "403", 500: "500" }
}
/**
* ErrorPageHandler 생성자 옵션
*/
export interface ErrorPageHandlerOptions {
templateId: string;
layoutLoader: LayoutLoader;
locale: string;
debug: boolean;
renderFunction: RenderFunction;
dataSourceManager: DataSourceManager;
globalState?: Record<string, unknown>;
}
/**
* 에러 페이지 핸들러 클래스
*/
export class ErrorPageHandler {
private templateId: string;
private layoutLoader: LayoutLoader;
private locale: string;
private debug: boolean;
private renderFunction: RenderFunction;
private dataSourceManager: DataSourceManager;
private globalState: Record<string, unknown>;
private errorConfig: ErrorConfig | null = null;
private configLoaded: boolean = false;
constructor(options: ErrorPageHandlerOptions) {
this.templateId = options.templateId;
this.layoutLoader = options.layoutLoader;
this.locale = options.locale;
this.debug = options.debug;
this.renderFunction = options.renderFunction;
this.dataSourceManager = options.dataSourceManager;
this.globalState = options.globalState || {};
}
/**
* template.json에서 error_config를 로드합니다.
*/
async loadConfig(): Promise<ErrorConfig | null> {
if (this.configLoaded) {
return this.errorConfig;
}
try {
// template.json fetch
const response = await fetch(`/api/templates/${this.templateId}/config.json`);
if (!response.ok) {
if (this.debug) {
logger.warn('Failed to load template config:', response.statusText);
}
this.configLoaded = true;
return null;
}
const result = await response.json();
if (!result.success || !result.data) {
if (this.debug) {
logger.warn('Invalid template config response');
}
this.configLoaded = true;
return null;
}
const templateData = result.data;
// error_config 섹션 확인
if (!templateData.error_config || !templateData.error_config.layouts) {
if (this.debug) {
logger.warn('No error_config found in template.json');
}
this.configLoaded = true;
return null;
}
this.errorConfig = templateData.error_config;
this.configLoaded = true;
if (this.debug) {
logger.log('Error config loaded:', this.errorConfig);
}
return this.errorConfig;
} catch (error) {
logger.error('Failed to load error config:', error);
this.configLoaded = true;
return null;
}
}
/**
* 에러 페이지를 렌더링합니다.
*
* @param errorCode 에러 코드 (404, 403, 500 등)
* @param containerId 렌더링할 컨테이너 ID (기본값: 'app')
* @returns 렌더링 성공 여부
*/
async renderError(errorCode: number, containerId: string = 'app'): Promise<boolean> {
try {
// 1. error_config 로드
const config = await this.loadConfig();
if (!config) {
if (this.debug) {
logger.warn('No error config available, cannot render error page');
}
return false;
}
// 2. 에러 코드에 맞는 레이아웃 이름 찾기
const layoutName = config.layouts[errorCode] || config.layouts[String(errorCode)];
if (!layoutName) {
if (this.debug) {
logger.warn(`No layout defined for error code: ${errorCode}`);
}
return false;
}
if (this.debug) {
logger.log(`Loading error layout: ${layoutName} for code: ${errorCode}`);
}
// 3. 레이아웃 로드 (기존 LayoutLoader 활용 - extends 병합 자동 처리)
const layoutData = await this.layoutLoader.loadLayout(this.templateId, layoutName);
if (!layoutData) {
if (this.debug) {
logger.error(`Failed to load error layout: ${layoutName}`);
}
return false;
}
if (this.debug) {
logger.log('Error layout loaded:', layoutData);
}
// 4. data_sources fetch (레이아웃에 정의된 API 데이터 로드)
let fetchedData: Record<string, unknown> = {};
const dataSources: DataSource[] = layoutData.data_sources || [];
if (dataSources.length > 0) {
if (this.debug) {
logger.log('Fetching data sources:', dataSources.map((s: DataSource) => s.id));
}
// blocking 데이터 소스 먼저 fetch
const blockingSources = dataSources.filter(
(s: DataSource) => s.loading_strategy === 'blocking'
);
const progressiveSources = dataSources.filter(
(s: DataSource) => !s.loading_strategy || s.loading_strategy === 'progressive'
);
// blocking + progressive 모두 fetch (에러 페이지에서는 모든 데이터 로드 후 렌더링)
const allSourcesToFetch = [...blockingSources, ...progressiveSources];
if (allSourcesToFetch.length > 0) {
try {
fetchedData = await this.dataSourceManager.fetchDataSources(
allSourcesToFetch,
{}, // 에러 페이지는 라우트 파라미터 없음
new URLSearchParams() // 쿼리 파라미터도 없음
);
if (this.debug) {
logger.log('Data sources fetched:', Object.keys(fetchedData));
}
} catch (fetchError) {
logger.error('Failed to fetch data sources:', fetchError);
// 데이터 fetch 실패해도 에러 페이지는 렌더링 진행
}
}
}
// 5. initGlobal/initLocal 처리 (fetch된 데이터를 _global/_local에 매핑)
const localInit: Record<string, unknown> = {};
if (dataSources.length > 0) {
this.processInitOptions(dataSources, fetchedData, localInit);
if (this.debug) {
logger.log('initOptions processed:', {
globalKeys: Object.keys(this.globalState),
localKeys: Object.keys(localInit),
});
}
}
// 6. 렌더링 (에러 코드 + fetch된 데이터 + 전역 상태 + 로컬 상태)
const dataContext: Record<string, unknown> = {
...fetchedData,
errorCode,
_global: { ...this.globalState },
_local: { ...localInit },
};
await this.renderFunction({
containerId,
layoutJson: layoutData,
dataContext,
translationContext: {
templateId: this.templateId,
locale: this.locale,
},
});
if (this.debug) {
logger.log(`Error page ${errorCode} rendered successfully`);
}
return true;
} catch (error) {
logger.error(`Failed to render error page ${errorCode}:`, error);
return false;
}
}
/**
* data_sources의 initGlobal/initLocal 옵션을 처리하여
* globalState와 localInit에 fetch된 데이터를 매핑합니다.
*
* TemplateApp.processInitOptions()의 간소화 버전으로,
* 에러 페이지에서 필요한 형태만 지원합니다:
* - 문자열 형태: initGlobal: "currentUser"
* - 배열 형태: initGlobal: ["currentUser", "settings"]
* - 객체 형태: initGlobal: { key: "cartCount", path: "count" }
*
* @since engine-v1.28.1
* @param dataSources 데이터 소스 정의 배열
* @param fetchedData fetch된 데이터 (키: 데이터소스 ID)
* @param localInit _local 상태에 매핑할 데이터 (출력용)
*/
private processInitOptions(
dataSources: DataSource[],
fetchedData: Record<string, unknown>,
localInit: Record<string, unknown>
): void {
for (const source of dataSources) {
const rawData = fetchedData[source.id] as any;
if (!rawData) continue;
// API 응답의 data 필드 추출 (success/data 래핑 해제)
const actualData = rawData?.data ?? rawData;
// initLocal 처리
if (source.initLocal) {
if (typeof source.initLocal === 'string') {
localInit[source.initLocal] = actualData;
logger.log(`initLocal: ${source.id}.data -> _local.${source.initLocal}`);
} else if (typeof source.initLocal === 'object' && 'key' in (source.initLocal as any)) {
const { key, path } = source.initLocal as { key: string; path?: string };
localInit[key] = path ? this.getValueByPath(actualData, path) : actualData;
logger.log(`initLocal: ${source.id}.data${path ? '.' + path : ''} -> _local.${key}`);
}
}
// initGlobal 처리
if (source.initGlobal) {
const items = Array.isArray(source.initGlobal)
? source.initGlobal
: [source.initGlobal];
for (const item of items) {
if (typeof item === 'string') {
this.globalState[item] = actualData;
logger.log(`initGlobal: ${source.id}.data -> _global.${item}`);
} else if (typeof item === 'object' && item !== null && 'key' in item) {
const { key, path } = item as { key: string; path?: string };
this.globalState[key] = path ? this.getValueByPath(actualData, path) : actualData;
logger.log(`initGlobal: ${source.id}.data${path ? '.' + path : ''} -> _global.${key}`);
}
}
}
}
}
/**
* 점 표기법 경로로 중첩 객체의 값을 가져옵니다.
*
* @param obj 대상 객체
* @param path 점 표기법 경로 (예: "data.count")
* @returns 경로에 해당하는 값
*/
private getValueByPath(obj: any, path: string): any {
return path.split('.').reduce((acc, part) => acc?.[part], obj);
}
/**
* 전역 상태를 업데이트합니다.
*
* @param state 새로운 전역 상태
*/
updateGlobalState(state: Record<string, unknown>): void {
this.globalState = { ...this.globalState, ...state };
}
/**
* 로케일을 업데이트합니다.
*
* 언어 변경 시 번역 컨텍스트에 최신 로케일이 반영되도록 합니다.
*
* @param locale 새로운 로케일 (예: 'ko', 'en')
*/
updateLocale(locale: string): void {
this.locale = locale;
if (this.debug) {
logger.log('Locale updated:', locale);
}
}
/**
* 에러 설정이 로드되었는지 확인합니다.
*/
isConfigLoaded(): boolean {
return this.configLoaded;
}
/**
* 특정 에러 코드에 대한 레이아웃이 정의되어 있는지 확인합니다.
*
* @param errorCode 확인할 에러 코드
* @returns 레이아웃 정의 여부
*/
async hasErrorLayout(errorCode: number): Promise<boolean> {
const config = await this.loadConfig();
if (!config) {
return false;
}
return !!(config.layouts[errorCode] || config.layouts[String(errorCode)]);
}
/**
* 캐시된 설정을 초기화합니다.
*/
clearConfigCache(): void {
this.errorConfig = null;
this.configLoaded = false;
if (this.debug) {
logger.log('Config cache cleared');
}
}
}
@@ -0,0 +1,380 @@
/**
* FormContext.tsx
*
* Form 컴포넌트의 자동 바인딩 설정을 자식 컴포넌트에 전달하기 위한 Context
*
* 주요 기능:
* - dataKey: 폼 데이터가 저장될 경로
* - "formData" → _local.formData
* - "_global.settings" → _global.settings
* - "_isolated.miniForm" → _isolated.miniForm
* - trackChanges: 변경 사항 추적 여부 (hasChanges 자동 관리)
* - setState: 상태 업데이트 함수 전달
* - isolatedContext: 격리된 상태 컨텍스트 (target: "isolated" 지원)
*
* @module FormContext
*/
import React, { createContext, useContext } from 'react';
import type { IsolatedContextValue } from './IsolatedStateContext';
/**
* Form 컨텍스트 값 인터페이스
*/
export interface FormContextValue {
/**
* 폼 데이터가 저장될 경로
*
* 지원되는 형식:
* - "formData" → _local.formData (기본값)
* - "_global.settings" → _global.settings
* - "_isolated.miniForm" → _isolated.miniForm
*/
dataKey?: string;
/**
* 변경 사항 추적 여부
*
* true이면 입력 시 _local.hasChanges를 자동으로 true로 설정
*/
trackChanges?: boolean;
/**
* 자동 바인딩 debounce 설정 (밀리초)
*
* 설정되면 onChange 핸들러가 지정된 시간만큼 debounce됩니다.
* 빈번한 입력 시 성능 최적화에 사용됩니다.
*
* @example
* debounce: 300 // 300ms debounce
*/
debounce?: number;
/**
* 상태 업데이트 함수
*
* DynamicRenderer에서 주입되며, 자동 바인딩 시 사용
* 객체 또는 함수형 업데이트(prev => newState)를 지원합니다.
*/
setState?: (updates: Record<string, any> | ((prev: Record<string, any>) => Record<string, any>)) => void;
/**
* 현재 상태
*
* 폼 데이터 접근을 위해 사용
*/
state?: Record<string, any>;
/**
* 격리된 상태 컨텍스트
*
* dataKey가 "_isolated."로 시작할 때 사용
* IsolatedStateProvider 내부에서만 유효
*/
isolatedContext?: IsolatedContextValue | null;
}
/**
* Form Context
*
* 기본값은 빈 객체로, Form 컴포넌트 외부에서 사용 시 자동 바인딩이 비활성화됨
*/
export const FormContext = createContext<FormContextValue>({});
/**
* Form Context Provider Props
*/
export interface FormProviderProps {
children: React.ReactNode;
value: FormContextValue;
}
/**
* Form Context Provider
*
* Form 컴포넌트에서 사용하여 자식들에게 바인딩 설정을 전달
*/
export const FormProvider: React.FC<FormProviderProps> = ({ children, value }) => {
return (
<FormContext.Provider value={value}>
{children}
</FormContext.Provider>
);
};
/**
* Form Context Hook
*
* Input, Select, Textarea 등에서 자동 바인딩 설정을 가져올 때 사용
*
* @example
* ```tsx
* const { dataKey, trackChanges, setState } = useFormContext();
*
* if (dataKey && name && setState) {
* // 자동 바인딩 활성화
* const path = `${dataKey}.${name}`;
* // ...
* }
* ```
*/
export const useFormContext = (): FormContextValue => {
return useContext(FormContext);
};
/**
* 자동 바인딩 활성화 여부 확인 헬퍼
*
* dataKey가 설정되어 있고, name prop이 있으며, setState가 제공된 경우 true
*
* @param context Form 컨텍스트
* @param name Input의 name prop
* @returns 자동 바인딩 활성화 여부
*/
export const isAutoBindingEnabled = (
context: FormContextValue,
name?: string
): boolean => {
return !!(context.dataKey && name && context.setState);
};
/**
* 컴포넌트의 change actions에 해당 form 필드를 대상으로 하는 명시적 setState가 있는지 확인
*
* change 이벤트에서 setState로 동일 필드(dataKey.name)를 직접 관리하는 경우,
* 자동 바인딩이 value/onChange를 덮어쓰면 충돌이 발생합니다.
* 이 함수는 해당 충돌 조건을 탐지합니다.
*
* @param actions 컴포넌트의 actions 배열
* @param dataKey Form의 dataKey (예: "form")
* @param name Input의 name prop (예: "purchase_restriction")
* @returns true이면 자동 바인딩 스킵 권장
*/
export const hasExplicitSetStateForField = (
actions: any[] | undefined,
dataKey: string,
name: string
): boolean => {
if (!actions || !Array.isArray(actions)) return false;
const fieldPath = `${dataKey}.${name}`;
return actions.some((action: any) => {
if (!action || action.type !== 'change') return false;
// 직접 setState
if (action.handler === 'setState' && action.params) {
if (Object.keys(action.params).some(key => key === fieldPath)) return true;
}
// sequence 내부 setState
if (action.handler === 'sequence' && Array.isArray(action.actions)) {
return action.actions.some((sub: any) =>
sub.handler === 'setState' &&
sub.params &&
Object.keys(sub.params).some(key => key === fieldPath)
);
}
return false;
});
};
/**
* 자동 바인딩 경로 생성 헬퍼
*
* @param dataKey Form의 dataKey (예: "formData")
* @param name Input의 name (예: "email")
* @returns 전체 경로 (예: "formData.email")
*/
export const getAutoBindingPath = (dataKey: string, name: string): string => {
return `${dataKey}.${name}`;
};
/**
* 중첩 경로에서 값 가져오기 헬퍼
*
* @param obj 대상 객체
* @param path dot notation 경로
* @returns 해당 경로의 값 또는 undefined
*
* @example
* getNestedValue({ formData: { email: 'test@example.com' } }, 'formData.email')
* // 결과: 'test@example.com'
*/
export const getNestedValue = (obj: Record<string, any> | undefined, path: string): any => {
if (!obj) return undefined;
const keys = path.split('.');
let current: any = obj;
for (const key of keys) {
if (current === null || current === undefined) {
return undefined;
}
current = current[key];
}
return current;
};
/**
* 중첩 경로에 값 설정하기 헬퍼 (불변 업데이트)
*
* @param obj 대상 객체
* @param path dot notation 경로
* @param value 설정할 값
* @returns 새로운 객체 (불변성 유지)
*
* @example
* setNestedValue({ formData: { email: '', name: '' } }, 'formData.email', 'test@example.com')
* // 결과: { formData: { email: 'test@example.com', name: '' } }
*/
export const setNestedValue = (
obj: Record<string, any>,
path: string,
value: any
): Record<string, any> => {
const keys = path.split('.');
if (keys.length === 1) {
return { ...obj, [keys[0]]: value };
}
const result: Record<string, any> = { ...obj };
let current = result;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
const nextKey = keys[i + 1];
const isNextKeyArrayIndex = /^\d+$/.test(nextKey);
if (Array.isArray(current[key]) && !isNextKeyArrayIndex) {
// 배열이지만 다음 키가 문자열(숫자 인덱스가 아님) → 객체로 변환
// PHP json_decode(assoc=true)에서 {} → [] 변환 시 복원 + 배열에 문자열 속성 추가 방지
current[key] = { ...current[key] };
} else if (Array.isArray(current[key])) {
// 배열이고 다음 키가 숫자 인덱스 → 배열로 복사
current[key] = [...current[key]];
} else if (isNextKeyArrayIndex) {
// 다음 키가 숫자(배열 인덱스)인데 현재 값이 배열이 아니면 배열로 초기화
current[key] = Array.isArray(current[key]) ? [...current[key]] : [];
} else {
// 객체인 경우 객체로 복사
current[key] = { ...(current[key] || {}) };
}
current = current[key];
}
current[keys[keys.length - 1]] = value;
return result;
};
/**
* dataKey 파싱 결과 인터페이스
*/
export interface ParsedDataKey {
/** 상태 스코프: 'local' | 'global' | 'isolated' */
scope: 'local' | 'global' | 'isolated';
/** 스코프 접두사를 제외한 경로 */
path: string;
}
/**
* dataKey를 파싱하여 스코프와 경로를 분리하는 헬퍼
*
* @param dataKey Form의 dataKey (예: "_isolated.miniForm")
* @returns 파싱된 스코프와 경로 객체
*
* @example
* parseDataKey('_global.settings')
* // 결과: { scope: 'global', path: 'settings' }
*
* parseDataKey('_isolated.miniForm')
* // 결과: { scope: 'isolated', path: 'miniForm' }
*
* parseDataKey('formData')
* // 결과: { scope: 'local', path: 'formData' }
*/
export const parseDataKey = (dataKey: string): ParsedDataKey => {
if (dataKey.startsWith('_global.')) {
return { scope: 'global', path: dataKey.slice(8) };
} else if (dataKey.startsWith('_isolated.')) {
return { scope: 'isolated', path: dataKey.slice(10) };
} else if (dataKey.startsWith('_local.')) {
return { scope: 'local', path: dataKey.slice(7) };
}
// 접두사가 없으면 기본적으로 _local로 간주
return { scope: 'local', path: dataKey };
};
/**
* dataKey 스코프에 따른 상태 업데이트 헬퍼
*
* dataKey의 스코프를 파싱하여 적절한 상태 업데이터를 호출합니다.
*
* @param dataKey Form의 dataKey
* @param path 업데이트할 필드 경로 (dataKey 이후 부분)
* @param value 설정할 값
* @param context Form 컨텍스트
*
* @example
* // _isolated.miniForm 스코프에서 email 필드 업데이트
* updateByScope('_isolated.miniForm', 'email', 'test@example.com', context);
*/
export const updateByScope = (
dataKey: string,
path: string,
value: any,
context: FormContextValue
): void => {
const { scope, path: scopePath } = parseDataKey(dataKey);
const fullPath = path ? `${scopePath}.${path}` : scopePath;
if (scope === 'isolated' && context.isolatedContext) {
// 격리된 상태 업데이트
const update = setNestedValue({}, fullPath, value);
context.isolatedContext.mergeState(update);
} else if (scope === 'global') {
// 전역 상태 업데이트 (G7Core.state.set 사용)
if ((window as any).G7Core?.state?.set) {
const update = setNestedValue({}, fullPath, value);
(window as any).G7Core.state.set(update);
}
} else if (context.setState) {
// 로컬 상태 업데이트
const update = setNestedValue({}, fullPath, value);
context.setState(update);
}
};
/**
* dataKey 스코프에 따른 상태 값 조회 헬퍼
*
* @param dataKey Form의 dataKey
* @param path 조회할 필드 경로 (dataKey 이후 부분)
* @param context Form 컨텍스트
* @returns 해당 경로의 값 또는 undefined
*
* @example
* // _isolated.miniForm 스코프에서 email 필드 조회
* const email = getValueByScope('_isolated.miniForm', 'email', context);
*/
export const getValueByScope = (
dataKey: string,
path: string,
context: FormContextValue
): any => {
const { scope, path: scopePath } = parseDataKey(dataKey);
const fullPath = path ? `${scopePath}.${path}` : scopePath;
if (scope === 'isolated' && context.isolatedContext) {
return getNestedValue(context.isolatedContext.state, fullPath);
} else if (scope === 'global') {
const globalState = (window as any).G7Core?.state?.get?.();
return getNestedValue(globalState, fullPath);
} else {
return getNestedValue(context.state, fullPath);
}
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,386 @@
/**
* NOTE: @since versions (engine-v1.x.x) refer to internal template engine
* development iterations, not G7 platform release versions.
*/
/**
* IsolatedStateContext.tsx
*
* 격리된 상태 관리를 위한 Context
*
* isolatedState 속성을 가진 컴포넌트는 독립적인 상태 스코프를 가지며,
* 상태 변경 시 해당 스코프 내의 컴포넌트만 리렌더링됩니다.
*
* 주요 기능:
* - 독립적인 useState를 통한 격리된 상태 관리
* - _isolated.* 경로로 상태 접근
* - Stale Closure 방지를 위한 useRef 패턴
* - DevTools 연동 (G7Core._isolatedStates)
*
* @module IsolatedStateContext
* @since engine-v1.12.0
*/
import React, { createContext, useContext, useState, useCallback, useRef, useMemo, useEffect } from 'react';
import { createLogger } from '../utils/Logger';
const logger = createLogger('IsolatedStateContext');
/**
* 격리된 상태 컨텍스트 값 인터페이스
*/
export interface IsolatedStateContextValue {
/** 현재 격리된 상태 */
state: Record<string, any>;
/**
* 특정 경로의 상태를 설정
*
* @param path 상태 경로 (dot notation, 예: "user.name")
* @param value 설정할 값
*/
setState: (path: string, value: any) => void;
/**
* 특정 경로의 상태를 조회
*
* @param path 상태 경로 (dot notation, 빈 문자열이면 전체 상태 반환)
* @returns 조회된 값 또는 undefined
*/
getState: (path: string) => any;
/**
* 상태를 병합 모드에 따라 업데이트
*
* @param updates 병합할 상태 객체
* @param mergeMode 병합 모드 ('replace' | 'shallow' | 'deep', 기본값: 'deep')
*/
mergeState: (updates: Record<string, any>, mergeMode?: 'replace' | 'shallow' | 'deep') => void;
/**
* 최신 상태를 참조하는 ref (Stale Closure 방지용)
*/
stateRef: React.MutableRefObject<Record<string, any>>;
/**
* 스코프 ID (DevTools 식별용)
*/
scopeId: string;
}
/**
* 기본 컨텍스트 값 (컨텍스트 외부에서 사용 시)
*/
const defaultContextValue: IsolatedStateContextValue = {
state: {},
setState: () => {
logger.warn('IsolatedStateContext not available: setState called outside IsolatedStateProvider');
},
getState: () => undefined,
mergeState: () => {
logger.warn('IsolatedStateContext not available: mergeState called outside IsolatedStateProvider');
},
stateRef: { current: {} },
scopeId: '',
};
/**
* 격리된 상태 컨텍스트
*/
export const IsolatedStateContext = createContext<IsolatedStateContextValue>(defaultContextValue);
/**
* IsolatedStateProvider Props
*/
export interface IsolatedStateProviderProps {
/** 초기 상태 */
initialState?: Record<string, any>;
/**
* 스코프 ID (DevTools에서 식별용)
*
* 지정하지 않으면 자동 생성됩니다.
*/
scopeId?: string;
/** 자식 컴포넌트 */
children: React.ReactNode;
}
/**
* 고유한 스코프 ID를 생성합니다.
*/
let scopeIdCounter = 0;
function generateScopeId(): string {
return `isolated-${++scopeIdCounter}-${Date.now().toString(36)}`;
}
/**
* 깊은 병합을 수행하는 유틸리티 함수
*
* - 객체는 재귀적으로 병합
* - 배열은 교체 (병합하지 않음)
* - null/undefined는 덮어씀
*
* @param target 기존 상태 객체
* @param source 병합할 객체
* @returns 깊은 병합된 새 객체
*/
function deepMerge(target: any, source: any): any {
if (source === null || source === undefined) return target;
if (typeof source !== 'object' || Array.isArray(source)) return source;
const result = { ...target };
for (const key of Object.keys(source)) {
const sourceValue = source[key];
const targetValue = target?.[key];
if (
sourceValue !== null &&
typeof sourceValue === 'object' &&
!Array.isArray(sourceValue) &&
targetValue !== null &&
typeof targetValue === 'object' &&
!Array.isArray(targetValue)
) {
result[key] = deepMerge(targetValue, sourceValue);
} else {
result[key] = sourceValue;
}
}
return result;
}
/**
* dot notation 경로로 중첩된 값을 가져옵니다.
*
* @param obj 대상 객체
* @param path dot notation 경로 (예: "user.profile.name")
* @returns 해당 경로의 값 또는 undefined
*/
function getValueByPath(obj: any, path: string): any {
if (!path) return obj;
return path.split('.').reduce((current, key) => current?.[key], obj);
}
/**
* dot notation 경로에 값을 설정한 새 객체를 반환합니다.
*
* @param obj 대상 객체
* @param path dot notation 경로
* @param value 설정할 값
* @returns 새로운 객체 (원본 불변)
*/
function setValueByPath(obj: Record<string, any>, path: string, value: any): Record<string, any> {
const keys = path.split('.');
const result = { ...obj };
let current: any = result;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
current[key] = { ...current[key] };
current = current[key];
}
current[keys[keys.length - 1]] = value;
return result;
}
/**
* 격리된 상태 Provider
*
* isolatedState 속성을 가진 컴포넌트를 래핑하여 독립적인 상태 스코프를 제공합니다.
*
* @example
* ```tsx
* <IsolatedStateProvider
* initialState={{ selectedCategories: [null, null, null, null] }}
* scopeId="category-selector"
* >
* <DynamicRenderer componentDef={...} />
* </IsolatedStateProvider>
* ```
*/
export const IsolatedStateProvider: React.FC<IsolatedStateProviderProps> = ({
initialState = {},
scopeId: providedScopeId,
children,
}) => {
// 스코프 ID 결정 (제공되지 않으면 자동 생성)
const scopeIdRef = useRef<string>(providedScopeId || generateScopeId());
const scopeId = scopeIdRef.current;
// 격리된 상태
const [state, setStateInternal] = useState<Record<string, any>>(initialState);
// Stale Closure 방지를 위한 ref (SlotContext 패턴 참조)
const stateRef = useRef<Record<string, any>>(state);
stateRef.current = state;
/**
* 특정 경로의 상태를 조회
*/
const getState = useCallback((path: string): any => {
return getValueByPath(stateRef.current, path);
}, []);
/**
* 특정 경로에 값을 설정
*/
const setState = useCallback((path: string, value: any): void => {
setStateInternal(prev => {
const newState = setValueByPath(prev, path, value);
logger.log(`[${scopeId}] setState: ${path} =`, value);
return newState;
});
}, [scopeId]);
/**
* 상태를 병합 모드에 따라 업데이트
* @param updates 업데이트할 상태
* @param mergeMode 병합 모드 ('replace' | 'shallow' | 'deep', 기본값: 'deep')
*/
const mergeState = useCallback((updates: Record<string, any>, mergeMode: 'replace' | 'shallow' | 'deep' = 'deep'): void => {
setStateInternal(prev => {
let newState: Record<string, any>;
if (mergeMode === 'replace') {
newState = updates;
} else if (mergeMode === 'shallow') {
newState = { ...prev, ...updates };
} else {
newState = deepMerge(prev, updates);
}
logger.log(`[${scopeId}] mergeState (${mergeMode}):`, updates);
return newState;
});
}, [scopeId]);
/**
* 컨텍스트 값 메모이제이션
*/
const contextValue = useMemo<IsolatedStateContextValue>(() => ({
state,
setState,
getState,
mergeState,
stateRef,
scopeId,
}), [state, setState, getState, mergeState, scopeId]);
/**
* 레지스트리 등록용 컨텍스트 값 (stateRef와 함수들 포함)
*
* G7Core.state.getIsolated/setIsolated API에서 사용됨
*/
const registryValue = useMemo(() => ({
state: stateRef.current, // stateRef로 최신 상태 참조
setState,
getState,
mergeState,
}), [setState, getState, mergeState]);
/**
* 레지스트리 등록 및 DevTools 이벤트 발생
*
* __g7IsolatedStates 레지스트리:
* - G7Core.state.getIsolated(scopeId) / setIsolated(scopeId, updates)에서 사용
* - 전체 컨텍스트 값을 저장하여 mergeState 등 API 접근 가능
*/
useEffect(() => {
const G7Core = (window as any).G7Core;
const registry = (window as any).__g7IsolatedStates || {};
// __g7IsolatedStates 레지스트리 초기화
if (!(window as any).__g7IsolatedStates) {
(window as any).__g7IsolatedStates = registry;
}
// 현재 스코프 등록 (전체 컨텍스트 값)
registry[scopeId] = registryValue;
// G7Core._isolatedStates에도 등록 (DevTools 하위 호환성)
if (G7Core) {
if (!G7Core._isolatedStates) {
G7Core._isolatedStates = {};
}
G7Core._isolatedStates[scopeId] = state;
}
// DevTools 이벤트 발생 (생성)
if (G7Core?.devTools?.isEnabled?.()) {
G7Core.devTools.emit?.('isolated:created', { id: scopeId, state });
}
logger.log(`[${scopeId}] IsolatedStateProvider mounted with initial state:`, state);
// cleanup: 레지스트리에서 제거
return () => {
delete registry[scopeId];
if (G7Core?._isolatedStates) {
delete G7Core._isolatedStates[scopeId];
}
// DevTools 이벤트 발생 (삭제)
if (G7Core?.devTools?.isEnabled?.()) {
G7Core.devTools.emit?.('isolated:destroyed', { id: scopeId });
}
logger.log(`[${scopeId}] IsolatedStateProvider unmounted`);
};
}, [scopeId, registryValue]); // registryValue 변경 시에도 레지스트리 업데이트
/**
* 상태 변경 시 레지스트리 및 DevTools 업데이트
*/
useEffect(() => {
const G7Core = (window as any).G7Core;
const registry = (window as any).__g7IsolatedStates;
// 레지스트리의 state 참조 업데이트
if (registry?.[scopeId]) {
registry[scopeId].state = state;
}
// G7Core._isolatedStates 업데이트 (DevTools 하위 호환성)
if (G7Core?._isolatedStates) {
G7Core._isolatedStates[scopeId] = state;
}
// DevTools 이벤트 발생 (업데이트)
if (G7Core?.devTools?.isEnabled?.()) {
G7Core.devTools.emit?.('isolated:updated', { id: scopeId, state });
}
}, [state, scopeId]);
return (
<IsolatedStateContext.Provider value={contextValue}>
{children}
</IsolatedStateContext.Provider>
);
};
/**
* 격리된 상태 컨텍스트 Hook
*
* IsolatedStateProvider 내부에서만 유효한 값을 반환합니다.
* 외부에서 호출 시 null을 반환합니다.
*
* @returns 격리된 상태 컨텍스트 값 또는 null
*/
export const useIsolatedState = (): IsolatedStateContextValue | null => {
const context = useContext(IsolatedStateContext);
// 기본값(scopeId가 빈 문자열)인 경우 null 반환
return context.scopeId ? context : null;
};
/**
* 격리된 상태가 활성화되어 있는지 확인하는 Hook
*
* @returns IsolatedStateProvider 내부인지 여부
*/
export const useIsInIsolatedScope = (): boolean => {
const context = useContext(IsolatedStateContext);
return !!context.scopeId;
};
export default IsolatedStateContext;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,292 @@
/**
* ModalDataSourceWrapper.tsx
*
* 모달에 data_sources 지원을 추가하는 래퍼 컴포넌트
*
* 기존 DataSourceManager를 재사용하여 모달이 열릴 때 data_sources를 fetch하고
* 결과를 전역 상태(_global)에 저장합니다.
*
* @package G7
* @subpackage Template Engine
* @since 1.0.0
*/
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { DataSourceManager, DataSource } from './DataSourceManager';
import { DataBindingEngine } from './DataBindingEngine';
import { createLogger } from '../utils/Logger';
const logger = createLogger('ModalDataSourceWrapper');
/**
* 중첩된 객체에서 경로로 값을 추출하는 헬퍼 함수
*
* @param obj 대상 객체
* @param path 점(.) 구분 경로 (예: "data.items", "[0].name", "data[0].value")
* @returns 경로에 해당하는 값
*/
function getNestedValue(obj: any, path: string): any {
if (!obj || !path) return obj;
// ?. 를 . 로 정규화
const normalizedPath = path.replace(/\?\./g, '.');
// 경로를 파싱하여 각 부분 추출 (배열 인덱스 포함)
// "[0].name" → ["[0]", "name"]
// "data[0].name" → ["data", "[0]", "name"]
const parts = normalizedPath.split(/\.(?![^\[]*\])/).flatMap(part => {
// 배열 인덱스 분리: "data[0]" → ["data", "[0]"]
const matches = part.match(/^([^\[]*)((?:\[\d+\])*)$/);
if (matches) {
const [, base, indices] = matches;
const result: string[] = [];
if (base) result.push(base);
const indexMatches = indices.match(/\[\d+\]/g);
if (indexMatches) result.push(...indexMatches);
return result;
}
return [part];
}).filter(p => p !== '');
let current = obj;
for (const part of parts) {
if (current === undefined || current === null) {
return undefined;
}
// 배열 인덱스 처리: "[0]" → 0
if (part.startsWith('[') && part.endsWith(']')) {
const index = parseInt(part.slice(1, -1), 10);
current = current[index];
} else {
current = current[part];
}
}
return current;
}
/**
* ModalDataSourceWrapper Props
*/
interface ModalDataSourceWrapperProps {
/** 모달이 열린 상태인지 */
isOpen: boolean;
/** 모달 ID */
modalId: string;
/** 모달에 정의된 data_sources */
dataSources?: DataSource[];
/** 현재 데이터 컨텍스트 */
dataContext: Record<string, any>;
/** 전역 상태 업데이터 (ActionDispatcher의 globalStateUpdater와 동일한 시그니처) */
globalStateUpdater?: (updates: Record<string, any>) => void;
/** DataBindingEngine 인스턴스 (표현식 치환용) */
bindingEngine?: DataBindingEngine;
/** 디버그 모드 */
debug?: boolean;
/** 자식 요소 (모달 컴포넌트) */
children: React.ReactNode;
}
/**
* 모달 data_sources 래퍼 컴포넌트
*
* 모달이 열릴 때 정의된 data_sources를 fetch하고
* 결과를 전역 상태에 저장합니다.
*
* 사용 예:
* ```json
* {
* "id": "module_detail_modal",
* "type": "composite",
* "name": "Modal",
* "data_sources": [
* {
* "id": "moduleDetail",
* "type": "api",
* "endpoint": "/api/admin/modules/{{_global.selectedModuleIdentifier}}",
* "auth_required": true,
* "initGlobal": "selectedModule"
* }
* ],
* ...
* }
* ```
*/
export const ModalDataSourceWrapper: React.FC<ModalDataSourceWrapperProps> = ({
isOpen,
modalId,
dataSources,
dataContext,
globalStateUpdater,
bindingEngine,
debug = false,
children,
}) => {
const [isLoading, setIsLoading] = useState(false);
const [hasFetched, setHasFetched] = useState(false);
const prevIsOpenRef = useRef(false);
const dataSourceManagerRef = useRef<DataSourceManager | null>(null);
// DataSourceManager 싱글턴 생성
if (!dataSourceManagerRef.current) {
dataSourceManagerRef.current = new DataSourceManager();
}
/**
* 모달의 data_sources를 fetch합니다.
*/
const fetchModalDataSources = useCallback(async () => {
if (!dataSources || dataSources.length === 0) return;
if (!dataSourceManagerRef.current) return;
setIsLoading(true);
try {
// 현재 URL에서 라우트/쿼리 파라미터 추출
const routeParams = dataContext.route || {};
const queryParams = new URLSearchParams(window.location.search);
// data_sources의 endpoint에서 표현식 치환
// 예: /api/admin/modules/{{_global.selectedModuleIdentifier}} -> /api/admin/modules/sirsoft-ecommerce
const resolvedDataSources = dataSources.map((ds) => {
let resolvedDs = { ...ds };
if (ds.endpoint && bindingEngine) {
// endpoint 내 표현식 치환 (캐시 사용 안 함 - 모달이 열릴 때마다 새로운 값 필요)
const resolvedEndpoint = bindingEngine.resolveBindings(
ds.endpoint,
dataContext,
{ skipCache: true }
);
resolvedDs.endpoint = resolvedEndpoint;
}
// params의 표현식도 치환 (캐시 사용 안 함)
if (ds.params && bindingEngine) {
const resolvedParams: Record<string, any> = {};
Object.entries(ds.params).forEach(([key, value]) => {
if (typeof value === 'string') {
resolvedParams[key] = bindingEngine.resolveBindings(value, dataContext, { skipCache: true });
} else {
resolvedParams[key] = value;
}
});
resolvedDs.params = resolvedParams;
}
return resolvedDs;
});
if (debug) {
logger.log(`[ModalDataSourceWrapper] Modal "${modalId}" fetching data sources:`,
resolvedDataSources.map(ds => ({ id: ds.id, endpoint: ds.endpoint })));
}
// DataSourceManager를 사용하여 fetch (기존 로직 재사용)
const results = await dataSourceManagerRef.current.fetchDataSourcesWithResults(
resolvedDataSources,
routeParams,
queryParams
);
// 결과를 전역 상태에 저장
if (globalStateUpdater) {
results.forEach((result) => {
if (result.state === 'success' && result.data !== undefined) {
// 해당 data_source 정의 찾기
const sourceDef = resolvedDataSources.find(ds => ds.id === result.id);
if (sourceDef?.initGlobal) {
// API 응답에서 실제 데이터 추출 (data.data 또는 data 자체)
const actualData = result.data?.data ?? result.data;
// initGlobal 옵션에 따라 _global에 데이터 저장
// ActionDispatcher의 globalStateUpdater는 { key: value } 형태를 받음
// 배열 형태: 여러 전역 상태 동시 초기화
// 문자열 형태: 전체 데이터 저장
// 객체 형태: { key, path }로 특정 필드만 저장
const initGlobalItems = Array.isArray(sourceDef.initGlobal)
? sourceDef.initGlobal
: [sourceDef.initGlobal];
for (const item of initGlobalItems) {
if (typeof item === 'string') {
globalStateUpdater({
[item]: actualData,
});
if (debug) {
logger.log(`[ModalDataSourceWrapper] Modal "${modalId}" initGlobal: ${result.id}.data -> _global.${item}`);
}
} else if (typeof item === 'object' && item.key) {
const { key, path } = item;
// path가 지정되면 해당 경로의 데이터만 추출
const targetData = path ? getNestedValue(actualData, path) : actualData;
globalStateUpdater({
[key]: targetData,
});
if (debug) {
logger.log(`Modal "${modalId}" initGlobal: ${result.id}.data${path ? '.' + path : ''} -> _global.${key}`);
}
}
}
}
} else if (result.state === 'error') {
logger.error(`Modal "${modalId}" data source error:`, result.id, result.error);
}
});
}
if (debug) {
logger.log(`Modal "${modalId}" data sources fetched successfully`);
}
} catch (error) {
logger.error(`Modal "${modalId}" data source fetch error:`, error);
} finally {
setIsLoading(false);
setHasFetched(true);
}
}, [dataSources, dataContext, globalStateUpdater, bindingEngine, modalId, debug]);
// 모달 데이터 소스를 TemplateApp 레지스트리에 등록/해제
// refetchDataSource 핸들러에서 모달 데이터 소스를 찾을 수 있도록 함
useEffect(() => {
if (!dataSources || dataSources.length === 0) return;
const templateApp = (window as any).__templateApp;
if (templateApp?.registerModalDataSources) {
templateApp.registerModalDataSources(modalId, dataSources);
}
return () => {
if (templateApp?.unregisterModalDataSources) {
templateApp.unregisterModalDataSources(modalId);
}
};
}, [modalId, dataSources]);
useEffect(() => {
// 모달이 닫힐 때 hasFetched 리셋 (다음 열림 시 다시 fetch)
if (!isOpen && prevIsOpenRef.current) {
setHasFetched(false);
if (debug) {
logger.log(`[ModalDataSourceWrapper] Modal "${modalId}" closed, reset fetch state`);
}
}
// 모달이 열릴 때 data_sources fetch
if (isOpen && !prevIsOpenRef.current && dataSources && dataSources.length > 0 && !hasFetched) {
fetchModalDataSources();
}
prevIsOpenRef.current = isOpen;
}, [isOpen, dataSources, hasFetched, fetchModalDataSources, modalId, debug]);
// children에 로딩 상태 전달 (필요시 사용)
// 현재는 단순히 children을 렌더링
return <>{children}</>;
};
export default ModalDataSourceWrapper;
@@ -0,0 +1,158 @@
/**
* ParentContextProvider.tsx
*
* 모달의 부모 컨텍스트 변경 시 선택적 리렌더링을 위한 Context Provider
*
* 문제:
* - $parent._local 상태가 변경되면 모달이 최신 값을 반영해야 함
* - 기존 방식: _global 변경 → 전체 앱 리렌더링 (성능 문제)
*
* 해결:
* - ParentContextProvider로 모달만 감싸기
* - 부모 컨텍스트 변경 시 이 Provider의 상태만 업데이트
* - 모달만 리렌더링, 다른 컴포넌트는 영향 없음
*
* @package G7
* @subpackage Template Engine
* @since 1.17.0
*/
import React, { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
import { createLogger } from '../utils/Logger';
const logger = createLogger('ParentContextProvider');
/**
* 부모 컨텍스트 상태 인터페이스
*/
interface ParentContextState {
/** 부모 컨텍스트 버전 (변경 감지용) */
version: number;
/** 부모 데이터 컨텍스트 (최신 값) */
getParentDataContext: () => Record<string, any> | undefined;
}
/**
* Context 기본값
*/
const ParentContextContext = createContext<ParentContextState | null>(null);
/**
* 부모 컨텍스트 변경 트리거 함수
* 전역에서 호출 가능하도록 export
*/
let triggerParentContextUpdate: (() => void) | null = null;
/**
* 부모 컨텍스트 업데이트 트리거
*
* $parent._local이 변경되었을 때 호출하면
* ParentContextProvider를 구독하는 모달만 리렌더링됨
*
* @example
* // ActionDispatcher에서 $parent._local 업데이트 후
* import { triggerModalParentUpdate } from './ParentContextProvider';
* triggerModalParentUpdate();
*/
export function triggerModalParentUpdate(): void {
if (triggerParentContextUpdate) {
logger.log('[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거');
triggerParentContextUpdate();
} else {
logger.warn('[triggerModalParentUpdate] Provider가 아직 마운트되지 않음');
}
}
/**
* ParentContextProvider Props
*/
interface ParentContextProviderProps {
/** 자식 요소 (React.createElement에서 전달될 수 있음) */
children?: React.ReactNode;
}
/**
* 부모 컨텍스트 Provider
*
* 모달 섹션을 감싸서 부모 컨텍스트 변경 시
* 모달만 선택적으로 리렌더링합니다.
*
* @example
* <ParentContextProvider>
* {modals.map(modalDef => <DynamicRenderer ... />)}
* </ParentContextProvider>
*/
export const ParentContextProvider: React.FC<ParentContextProviderProps> = ({ children }) => {
const [version, setVersion] = useState(0);
const mountedRef = useRef(true);
// 부모 데이터 컨텍스트를 가져오는 함수 (항상 최신 값 반환)
const getParentDataContext = useCallback(() => {
const layoutContextStack: Array<{
state: Record<string, any>;
setState: (updates: any) => void;
dataContext?: Record<string, any>;
}> = (window as any).__g7LayoutContextStack || [];
const parentContextEntry = layoutContextStack[layoutContextStack.length - 1];
return parentContextEntry?.dataContext;
}, []);
// 전역 트리거 함수 등록
useEffect(() => {
mountedRef.current = true;
triggerParentContextUpdate = () => {
if (mountedRef.current) {
setVersion(v => v + 1);
logger.log('[ParentContextProvider] 버전 업데이트됨');
}
};
return () => {
mountedRef.current = false;
triggerParentContextUpdate = null;
};
}, []);
const contextValue: ParentContextState = {
version,
getParentDataContext,
};
return (
<ParentContextContext.Provider value={contextValue}>
{children}
</ParentContextContext.Provider>
);
};
/**
* 부모 컨텍스트 훅
*
* 모달 내부에서 사용하여 부모 컨텍스트 변경을 구독합니다.
* version이 변경되면 컴포넌트가 리렌더링됩니다.
*
* @returns 부모 컨텍스트 상태 또는 null (Provider 외부에서 사용 시)
*
* @example
* const parentContext = useParentContext();
* const parentDataContext = parentContext?.getParentDataContext();
*/
export function useParentContext(): ParentContextState | null {
return useContext(ParentContextContext);
}
/**
* 부모 데이터 컨텍스트 훅 (편의 함수)
*
* version 변경 시 자동으로 최신 부모 데이터 컨텍스트를 반환합니다.
*
* @returns 부모 데이터 컨텍스트 또는 undefined
*/
export function useParentDataContext(): Record<string, any> | undefined {
const context = useParentContext();
// version을 읽어서 변경 시 리렌더링되도록 함
const _version = context?.version;
return context?.getParentDataContext();
}
export default ParentContextProvider;
@@ -0,0 +1,908 @@
/**
* 그누보드7 템플릿 엔진 - 파이프 함수 레지스트리
*
* Angular/Vue 스타일의 파이프 함수를 지원합니다.
* `{{value | pipeName(arg1, arg2)}}` 형태로 값을 변환할 수 있습니다.
*
* @packageDocumentation
*
* @example
* ```typescript
* // 레이아웃 JSON에서 사용
* "text": "{{post.created_at | date}}"
* "text": "{{post.created_at | datetime}}"
* "text": "{{post.created_at | relativeTime}}"
* "text": "{{item.count | number}}"
* "text": "{{description | truncate(100)}}"
* ```
*/
import { createLogger } from '../utils/Logger';
const logger = createLogger('PipeRegistry');
/**
* 파이프 함수 타입
*
* 첫 번째 인자는 변환할 값, 나머지는 파이프 인자
*/
export type PipeFunction = (value: any, ...args: any[]) => any;
/**
* 파이프 정의 인터페이스
*/
interface PipeDefinition {
fn: PipeFunction;
description?: string;
}
/**
* 날짜 포맷 함수 (간단한 구현)
*
* dayjs나 date-fns 없이 기본적인 날짜 포맷을 지원합니다.
*/
function formatDateSimple(date: Date, format: string): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', String(year))
.replace('YY', String(year).slice(-2))
.replace('MM', month)
.replace('M', String(date.getMonth() + 1))
.replace('DD', day)
.replace('D', String(date.getDate()))
.replace('HH', hours)
.replace('H', String(date.getHours()))
.replace('mm', minutes)
.replace('m', String(date.getMinutes()))
.replace('ss', seconds)
.replace('s', String(date.getSeconds()));
}
/**
* 상대 시간 계산 함수
*
* @param date - 비교할 날짜
* @param locale - 로케일 (기본값: 'ko')
* @returns 상대 시간 문자열 (예: "3분 전", "2시간 전")
*/
function getRelativeTime(date: Date, locale: string = 'ko'): string {
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffSec = Math.floor(diffMs / 1000);
const diffMin = Math.floor(diffSec / 60);
const diffHour = Math.floor(diffMin / 60);
const diffDay = Math.floor(diffHour / 24);
const diffWeek = Math.floor(diffDay / 7);
const diffMonth = Math.floor(diffDay / 30);
const diffYear = Math.floor(diffDay / 365);
// 한국어
if (locale === 'ko') {
if (diffSec < 60) return '방금 전';
if (diffMin < 60) return `${diffMin}분 전`;
if (diffHour < 24) return `${diffHour}시간 전`;
if (diffDay < 7) return `${diffDay}일 전`;
if (diffWeek < 4) return `${diffWeek}주 전`;
if (diffMonth < 12) return `${diffMonth}개월 전`;
return `${diffYear}년 전`;
}
// 영어 (기본)
if (diffSec < 60) return 'just now';
if (diffMin < 60) return `${diffMin} minute${diffMin === 1 ? '' : 's'} ago`;
if (diffHour < 24) return `${diffHour} hour${diffHour === 1 ? '' : 's'} ago`;
if (diffDay < 7) return `${diffDay} day${diffDay === 1 ? '' : 's'} ago`;
if (diffWeek < 4) return `${diffWeek} week${diffWeek === 1 ? '' : 's'} ago`;
if (diffMonth < 12) return `${diffMonth} month${diffMonth === 1 ? '' : 's'} ago`;
return `${diffYear} year${diffYear === 1 ? '' : 's'} ago`;
}
/**
* 값을 Date 객체로 변환
*
* @param value - 변환할 값 (Date, 문자열, 숫자)
* @returns Date 객체 또는 null
*/
function toDate(value: any): Date | null {
if (value == null) return null;
if (value instanceof Date) return value;
if (typeof value === 'number') return new Date(value);
if (typeof value === 'string') {
const parsed = new Date(value);
return isNaN(parsed.getTime()) ? null : parsed;
}
return null;
}
/**
* 내장 파이프 함수들
*
* 모든 파이프 함수는 순수 함수입니다.
* - 입력값을 변경하지 않습니다.
* - 전역 상태에 접근하지 않습니다.
* - null/undefined 입력을 안전하게 처리합니다.
*/
const builtInPipes: Record<string, PipeDefinition> = {
// ============================================
// 날짜 파이프
// ============================================
/**
* date - 날짜 포맷 (날짜만)
*
* @example
* "{{post.created_at | date}}" → "2024-01-15"
* "{{post.created_at | date('YYYY/MM/DD')}}" → "2024/01/15"
*/
date: {
fn: (value: any, format: string = 'YYYY-MM-DD'): string => {
const date = toDate(value);
if (!date) return '';
return formatDateSimple(date, format);
},
description: '날짜 포맷 (기본: YYYY-MM-DD)',
},
/**
* datetime - 날짜+시간 포맷
*
* @example
* "{{post.created_at | datetime}}" → "2024-01-15 14:30"
* "{{post.created_at | datetime('YYYY/MM/DD HH:mm:ss')}}" → "2024/01/15 14:30:45"
*/
datetime: {
fn: (value: any, format: string = 'YYYY-MM-DD HH:mm'): string => {
const date = toDate(value);
if (!date) return '';
return formatDateSimple(date, format);
},
description: '날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)',
},
/**
* relativeTime - 상대 시간 표시
*
* @example
* "{{post.created_at | relativeTime}}" → "3분 전", "2시간 전", "1일 전"
*/
relativeTime: {
fn: (value: any, locale: string = 'ko'): string => {
const date = toDate(value);
if (!date) return '';
return getRelativeTime(date, locale);
},
description: '상대 시간 표시 (예: "3분 전")',
},
// ============================================
// 숫자 파이프
// ============================================
/**
* number - 숫자 포맷 (천단위 구분, 소수점)
*
* @example
* "{{item.count | number}}" → "1,234"
* "{{item.price | number(2)}}" → "1,234.56"
*/
number: {
fn: (value: any, decimals?: number): string => {
const num = Number(value);
if (isNaN(num)) return String(value ?? '');
const options: Intl.NumberFormatOptions = {};
if (decimals !== undefined) {
options.minimumFractionDigits = decimals;
options.maximumFractionDigits = decimals;
}
return num.toLocaleString(undefined, options);
},
description: '숫자 포맷 (천단위 구분, 선택적 소수점)',
},
// ============================================
// 문자열 파이프
// ============================================
/**
* truncate - 문자열 자르기
*
* @example
* "{{description | truncate(100)}}" → "Lorem ipsum dolor sit amet..."
* "{{description | truncate(50, ' [더보기]')}}" → "Lorem ipsum... [더보기]"
*/
truncate: {
fn: (value: any, length: number = 100, suffix: string = '...'): string => {
if (typeof value !== 'string') return String(value ?? '');
if (value.length <= length) return value;
return value.slice(0, length) + suffix;
},
description: '문자열 자르기 (기본: 100자, 접미사: "...")',
},
/**
* uppercase - 대문자 변환
*
* @example
* "{{name | uppercase}}" → "HELLO"
*/
uppercase: {
fn: (value: any): string => {
if (typeof value !== 'string') return String(value ?? '');
return value.toUpperCase();
},
description: '대문자 변환',
},
/**
* lowercase - 소문자 변환
*
* @example
* "{{name | lowercase}}" → "hello"
*/
lowercase: {
fn: (value: any): string => {
if (typeof value !== 'string') return String(value ?? '');
return value.toLowerCase();
},
description: '소문자 변환',
},
/**
* stripHtml - HTML 태그 제거
*
* @example
* "{{content | stripHtml}}" → "Hello World" (from "<p>Hello <b>World</b></p>")
*/
stripHtml: {
fn: (value: any): string => {
if (typeof value !== 'string') return String(value ?? '');
return value.replace(/<[^>]*>/g, '');
},
description: 'HTML 태그 제거',
},
// ============================================
// 기본값 파이프
// ============================================
/**
* default - 기본값 설정 (null, undefined, 빈문자열 시)
*
* @example
* "{{name | default('Unknown')}}" → "Unknown" (name이 없을 때)
*/
default: {
fn: (value: any, defaultValue: any = ''): any => {
if (value == null || value === '') return defaultValue;
return value;
},
description: '기본값 설정 (null, undefined, 빈문자열 시)',
},
/**
* fallback - 폴백 값 설정 (null, undefined 시만)
*
* @example
* "{{data | fallback([])}}" → [] (data가 null/undefined일 때)
*/
fallback: {
fn: (value: any, fallbackValue: any): any => {
return value ?? fallbackValue;
},
description: '폴백 값 설정 (null, undefined 시만)',
},
// ============================================
// 배열 파이프
// ============================================
/**
* first - 배열의 첫 번째 요소
*
* @example
* "{{items | first}}" → 첫 번째 아이템
*/
first: {
fn: (value: any): any => {
if (!Array.isArray(value)) return undefined;
return value[0];
},
description: '배열의 첫 번째 요소',
},
/**
* last - 배열의 마지막 요소
*
* @example
* "{{items | last}}" → 마지막 아이템
*/
last: {
fn: (value: any): any => {
if (!Array.isArray(value)) return undefined;
return value[value.length - 1];
},
description: '배열의 마지막 요소',
},
/**
* join - 배열을 문자열로 결합
*
* @example
* "{{tags | join(', ')}}" → "태그1, 태그2, 태그3"
*/
join: {
fn: (value: any, separator: string = ', '): string => {
if (!Array.isArray(value)) return '';
return value.join(separator);
},
description: '배열을 문자열로 결합 (기본 구분자: ", ")',
},
/**
* length - 배열/문자열 길이
*
* @example
* "{{items | length}}" → 5
* "{{text | length}}" → 10
*/
length: {
fn: (value: any): number => {
if (Array.isArray(value) || typeof value === 'string') {
return value.length;
}
return 0;
},
description: '배열/문자열 길이',
},
/**
* filterBy - 배열 필터링 (포함 여부)
*
* 배열의 각 요소에서 지정된 필드 값이 allowList 배열에 포함되어 있는지 확인하여 필터링합니다.
*
* @example
* "{{columns | filterBy(visibleColumns, 'field')}}"
* // columns 배열에서 item.field 값이 visibleColumns 배열에 포함된 항목만 반환
*
* "{{items | filterBy(selectedIds, 'id')}}"
* // items 배열에서 item.id 값이 selectedIds 배열에 포함된 항목만 반환
*/
filterBy: {
fn: (value: any, allowList: any[], field?: string): any[] => {
if (!Array.isArray(value)) return [];
if (!Array.isArray(allowList)) return value;
return value.filter((item) => {
const itemValue = field ? item?.[field] : item;
return allowList.includes(itemValue);
});
},
description: '배열 필터링 (allowList에 포함된 항목만 반환)',
},
// ============================================
// 객체 파이프
// ============================================
/**
* keys - 객체의 키 배열
*
* @example
* "{{object | keys}}" → ["key1", "key2"]
*/
keys: {
fn: (value: any): string[] => {
if (value == null || typeof value !== 'object') return [];
return Object.keys(value);
},
description: '객체의 키 배열',
},
/**
* values - 객체의 값 배열
*
* @example
* "{{object | values}}" → [value1, value2]
*/
values: {
fn: (value: any): any[] => {
if (value == null || typeof value !== 'object') return [];
return Object.values(value);
},
description: '객체의 값 배열',
},
/**
* json - JSON 문자열로 변환
*
* @example
* "{{object | json}}" → '{"key": "value"}'
*/
json: {
fn: (value: any, indent?: number): string => {
try {
return JSON.stringify(value, null, indent);
} catch {
return '';
}
},
description: 'JSON 문자열로 변환',
},
// ============================================
// 다국어 파이프
// ============================================
/**
* localized - 다국어 객체에서 현재 로케일 값 추출
*
* @example
* "{{product.name | localized}}" → "상품명" (현재 로케일이 ko인 경우)
*
* @note 이 파이프는 컨텍스트에서 $locale 값을 참조해야 합니다.
* evaluateExpression에서 컨텍스트와 함께 호출됩니다.
*/
localized: {
fn: (value: any, locale?: string): string => {
if (value == null) return '';
if (typeof value === 'string') return value;
if (typeof value !== 'object') return String(value);
// 로케일 우선순위: 인자 > ko > en > 첫 번째 값
const targetLocale = locale || 'ko';
return value[targetLocale] || value.ko || value.en || Object.values(value)[0] || '';
},
description: '다국어 객체에서 로케일에 맞는 값 추출',
},
};
/**
* 커스텀 파이프 레지스트리
*/
const customPipes: Map<string, PipeDefinition> = new Map();
/**
* 파이프 레지스트리 클래스
*
* 파이프 함수 등록, 조회, 실행을 관리합니다.
*/
export class PipeRegistry {
private static instance: PipeRegistry | null = null;
/**
* 싱글톤 인스턴스 반환
*/
public static getInstance(): PipeRegistry {
if (!PipeRegistry.instance) {
PipeRegistry.instance = new PipeRegistry();
}
return PipeRegistry.instance;
}
/**
* 파이프 함수 등록
*
* @param name - 파이프 이름
* @param fn - 파이프 함수
* @param description - 설명 (선택)
*
* @example
* ```typescript
* PipeRegistry.getInstance().register('currency', (value, symbol = '$') => {
* return `${symbol}${Number(value).toFixed(2)}`;
* }, '통화 포맷');
* ```
*/
public register(name: string, fn: PipeFunction, description?: string): void {
if (builtInPipes[name]) {
logger.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${name}`);
return;
}
customPipes.set(name, { fn, description });
logger.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${name}`);
}
/**
* 파이프 함수 해제
*
* @param name - 파이프 이름
*/
public unregister(name: string): boolean {
if (builtInPipes[name]) {
logger.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${name}`);
return false;
}
const result = customPipes.delete(name);
if (result) {
logger.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${name}`);
}
return result;
}
/**
* 파이프 함수 조회
*
* @param name - 파이프 이름
* @returns 파이프 함수 또는 undefined
*/
public get(name: string): PipeFunction | undefined {
// 내장 파이프 우선 조회
const builtIn = builtInPipes[name];
if (builtIn) return builtIn.fn;
// 커스텀 파이프 조회
const custom = customPipes.get(name);
return custom?.fn;
}
/**
* 파이프 존재 여부 확인
*
* @param name - 파이프 이름
*/
public has(name: string): boolean {
return !!builtInPipes[name] || customPipes.has(name);
}
/**
* 파이프 함수 실행
*
* @param name - 파이프 이름
* @param value - 변환할 값
* @param args - 파이프 인자들
* @returns 변환된 값
*
* @example
* ```typescript
* const result = pipeRegistry.execute('date', '2024-01-15');
* // 결과: "2024-01-15"
*
* const result2 = pipeRegistry.execute('truncate', 'Long text...', [50, '...']);
* // 결과: "Long text..."
* ```
*/
public execute(name: string, value: any, args: any[] = []): any {
const pipe = this.get(name);
if (!pipe) {
logger.warn(`[PipeRegistry] 알 수 없는 파이프: ${name}`);
return value; // 파이프가 없으면 원본 값 반환
}
try {
return pipe(value, ...args);
} catch (error) {
logger.error(`[PipeRegistry] 파이프 실행 오류 (${name}):`, error);
return value; // 오류 시 원본 값 반환
}
}
/**
* 등록된 모든 파이프 목록 반환
*/
public list(): { name: string; description?: string; type: 'built-in' | 'custom' }[] {
const pipes: { name: string; description?: string; type: 'built-in' | 'custom' }[] = [];
// 내장 파이프
for (const [name, def] of Object.entries(builtInPipes)) {
pipes.push({ name, description: def.description, type: 'built-in' });
}
// 커스텀 파이프
for (const [name, def] of customPipes.entries()) {
pipes.push({ name, description: def.description, type: 'custom' });
}
return pipes.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* 테스트/리셋용: 모든 커스텀 파이프 제거
*/
public clearCustomPipes(): void {
customPipes.clear();
}
}
/**
* 파이프 레지스트리 싱글톤 인스턴스
*/
export const pipeRegistry = PipeRegistry.getInstance();
/**
* 파이프 표현식 파싱 결과
*/
export interface ParsedPipe {
name: string;
args: any[];
}
/**
* 파이프 표현식 파싱
*
* `value | pipeName(arg1, arg2)` 형태의 문자열을 파싱합니다.
*
* @param pipeExpr - 파이프 표현식 (파이프 이름 + 인자, 예: "date", "truncate(100)")
* @returns 파싱된 파이프 정보
*
* @example
* ```typescript
* parsePipeExpression("date") // { name: "date", args: [] }
* parsePipeExpression("truncate(100)") // { name: "truncate", args: [100] }
* parsePipeExpression("truncate(100, '...')") // { name: "truncate", args: [100, "..."] }
* ```
*/
export function parsePipeExpression(pipeExpr: string): ParsedPipe {
const trimmed = pipeExpr.trim();
// 괄호가 없으면 인자 없음
const parenIndex = trimmed.indexOf('(');
if (parenIndex === -1) {
return { name: trimmed, args: [] };
}
const name = trimmed.slice(0, parenIndex).trim();
const argsStr = trimmed.slice(parenIndex + 1, -1); // 마지막 ')' 제외
// 빈 괄호
if (!argsStr.trim()) {
return { name, args: [] };
}
// 인자 파싱 (간단한 CSV 스타일)
const args: any[] = [];
let current = '';
let inString: string | null = null;
let depth = 0;
for (let i = 0; i < argsStr.length; i++) {
const char = argsStr[i];
const prevChar = i > 0 ? argsStr[i - 1] : '';
// 이스케이프 문자 처리
if (prevChar === '\\') {
current += char;
continue;
}
// 문자열 시작/종료
if ((char === '"' || char === "'") && !inString) {
inString = char;
continue;
}
if (char === inString) {
inString = null;
continue;
}
// 문자열 내부라면 그대로 추가
if (inString) {
current += char;
continue;
}
// 중첩 괄호/대괄호 처리
if (char === '(' || char === '[' || char === '{') {
depth++;
current += char;
continue;
}
if (char === ')' || char === ']' || char === '}') {
depth--;
current += char;
continue;
}
// 쉼표는 인자 구분자 (깊이 0일 때만)
if (char === ',' && depth === 0) {
args.push(parseArgValue(current.trim()));
current = '';
continue;
}
current += char;
}
// 마지막 인자
if (current.trim()) {
args.push(parseArgValue(current.trim()));
}
return { name, args };
}
/**
* 인자 값 파싱
*
* 문자열, 숫자, 불리언 등을 적절한 타입으로 변환합니다.
*/
function parseArgValue(value: string): any {
// null/undefined
if (value === 'null') return null;
if (value === 'undefined') return undefined;
// 불리언
if (value === 'true') return true;
if (value === 'false') return false;
// 숫자
const num = Number(value);
if (!isNaN(num) && value !== '') return num;
// 문자열 (따옴표 제거된 상태)
return value;
}
/**
* 표현식에서 파이프를 분리
*
* `expression | pipe1 | pipe2(arg)` 형태를 분석하여
* 기본 표현식과 파이프 목록을 반환합니다.
*
* @param expr - 전체 표현식
* @returns [기본 표현식, 파이프 배열]
*
* @example
* ```typescript
* splitPipes("post.created_at | date")
* // ["post.created_at", ["date"]]
*
* splitPipes("value | truncate(100) | uppercase")
* // ["value", ["truncate(100)", "uppercase"]]
*
* splitPipes("a || b ? 'yes' : 'no'")
* // ["a || b ? 'yes' : 'no'", []] - || 는 OR 연산자로 처리됨
* ```
*/
export function splitPipes(expr: string): [string, string[]] {
const parts: string[] = [];
let current = '';
let inString: string | null = null;
let depth = 0;
for (let i = 0; i < expr.length; i++) {
const char = expr[i];
const prevChar = i > 0 ? expr[i - 1] : '';
const nextChar = i < expr.length - 1 ? expr[i + 1] : '';
// 이스케이프 문자 처리
if (prevChar === '\\') {
current += char;
continue;
}
// 문자열 시작/종료
if ((char === '"' || char === "'") && !inString) {
inString = char;
current += char;
continue;
}
if (char === inString) {
inString = null;
current += char;
continue;
}
// 문자열 내부라면 그대로 추가
if (inString) {
current += char;
continue;
}
// 중첩 괄호/대괄호/중괄호 처리
if (char === '(' || char === '[' || char === '{') {
depth++;
current += char;
continue;
}
if (char === ')' || char === ']' || char === '}') {
depth--;
current += char;
continue;
}
// 파이프 구분 (단일 | 이고 || 가 아닌 경우, 깊이 0일 때만)
if (char === '|' && nextChar !== '|' && prevChar !== '|' && depth === 0) {
parts.push(current.trim());
current = '';
continue;
}
current += char;
}
// 마지막 부분
if (current.trim()) {
parts.push(current.trim());
}
// 첫 번째는 기본 표현식, 나머지는 파이프
if (parts.length === 0) {
return [expr, []];
}
return [parts[0], parts.slice(1)];
}
/**
* 표현식에 파이프가 포함되어 있는지 확인
*
* || (OR 연산자)는 파이프로 인식하지 않습니다.
*
* @param expr - 표현식
* @returns 파이프 포함 여부
*/
export function hasPipes(expr: string): boolean {
let inString: string | null = null;
let depth = 0;
for (let i = 0; i < expr.length; i++) {
const char = expr[i];
const prevChar = i > 0 ? expr[i - 1] : '';
const nextChar = i < expr.length - 1 ? expr[i + 1] : '';
// 이스케이프 문자 처리
if (prevChar === '\\') continue;
// 문자열 시작/종료
if ((char === '"' || char === "'") && !inString) {
inString = char;
continue;
}
if (char === inString) {
inString = null;
continue;
}
// 문자열 내부는 스킵
if (inString) continue;
// 중첩 처리
if (char === '(' || char === '[' || char === '{') {
depth++;
continue;
}
if (char === ')' || char === ']' || char === '}') {
depth--;
continue;
}
// 단일 | 감지 (|| 제외, 깊이 0)
if (char === '|' && nextChar !== '|' && prevChar !== '|' && depth === 0) {
return true;
}
}
return false;
}
/**
* 파이프 체인 실행
*
* 기본 값에 파이프들을 순차적으로 적용합니다.
*
* @param value - 초기 값
* @param pipes - 파이프 표현식 배열
* @returns 최종 변환된 값
*/
export function executePipeChain(value: any, pipes: string[]): any {
const registry = PipeRegistry.getInstance();
let result = value;
for (const pipeExpr of pipes) {
const parsed = parsePipeExpression(pipeExpr);
result = registry.execute(parsed.name, result, parsed.args);
}
return result;
}
@@ -0,0 +1,134 @@
/**
* ResponsiveContext.tsx
*
* 반응형 상태를 React Context로 제공하는 모듈
* DynamicRenderer에서 사용하여 모든 자식 컴포넌트에 반응형 상태를 전달합니다.
*/
import React, { createContext, useContext, useState, useEffect, useMemo } from 'react';
import { responsiveManager } from './ResponsiveManager';
/**
* Responsive Context 값 인터페이스
*/
export interface ResponsiveContextValue {
/** 현재 화면 너비 (px) */
width: number;
/** 모바일 여부 (< 768px) */
isMobile: boolean;
/** 태블릿 여부 (768-1023px) */
isTablet: boolean;
/** 데스크톱 여부 (>= 1024px) */
isDesktop: boolean;
/** 현재 매칭된 프리셋 */
matchedPreset: 'mobile' | 'tablet' | 'desktop';
}
/**
* 너비에 따른 프리셋 계산
*
* @param width 화면 너비
* @returns 매칭된 프리셋
*/
function getPresetFromWidth(width: number): 'mobile' | 'tablet' | 'desktop' {
if (width < 768) {
return 'mobile';
}
if (width < 1024) {
return 'tablet';
}
return 'desktop';
}
/**
* 너비에 따른 Context 값 계산
*
* @param width 화면 너비
* @returns ResponsiveContextValue
*/
function createContextValue(width: number): ResponsiveContextValue {
const matchedPreset = getPresetFromWidth(width);
return {
width,
isMobile: matchedPreset === 'mobile',
isTablet: matchedPreset === 'tablet',
isDesktop: matchedPreset === 'desktop',
matchedPreset,
};
}
/**
* Responsive Context
* 기본값은 데스크톱 (1024px)
*/
const ResponsiveContext = createContext<ResponsiveContextValue>(
createContextValue(1024)
);
/**
* Responsive Provider Props
*/
interface ResponsiveProviderProps {
children: React.ReactNode;
/**
* 뷰포트 너비 오버라이드 (위지윅 편집기용)
*
* 이 값이 설정되면 실제 브라우저 창 크기 대신 이 값을 사용합니다.
* 위지윅 편집기에서 모바일/태블릿 미리보기 시 활용됩니다.
*/
overrideWidth?: number;
}
/**
* Responsive Provider 컴포넌트
*
* ResponsiveManager를 구독하여 화면 크기 상태를 Context로 제공합니다.
* template-engine.ts의 renderTemplate에서 최상위에 래핑됩니다.
*
* @param overrideWidth - 위지윅 편집기에서 디바이스 미리보기 시 사용할 너비
*/
export const ResponsiveProvider: React.FC<ResponsiveProviderProps> = ({ children, overrideWidth }) => {
const [actualWidth, setActualWidth] = useState(() => responsiveManager.getWidth());
useEffect(() => {
// ResponsiveManager 구독
const unsubscribe = responsiveManager.subscribe((newWidth) => {
setActualWidth(newWidth);
});
return () => {
unsubscribe();
};
}, []);
// overrideWidth가 있으면 그 값 사용, 없으면 실제 브라우저 너비 사용
const effectiveWidth = overrideWidth ?? actualWidth;
const value = useMemo(() => createContextValue(effectiveWidth), [effectiveWidth]);
return (
<ResponsiveContext.Provider value={value}>
{children}
</ResponsiveContext.Provider>
);
};
/**
* Responsive 상태를 사용하는 Hook
*
* @returns ResponsiveContextValue
*
* @example
* // 컴포넌트에서 사용
* const { width, isMobile, isTablet, isDesktop, matchedPreset } = useResponsive();
*
* return (
* <div className={isMobile ? 'flex-col' : 'flex-row'}>
* {content}
* </div>
* );
*/
export const useResponsive = (): ResponsiveContextValue => {
return useContext(ResponsiveContext);
};
export { ResponsiveContext };
@@ -0,0 +1,279 @@
/**
* ResponsiveManager.ts
*
* 반응형 레이아웃 시스템의 핵심 싱글톤 모듈
* 화면 너비 감지, 범위 파싱, 매칭 키 찾기 기능을 제공합니다.
*/
/**
* 파싱된 범위 인터페이스
*/
interface ParsedRange {
min: number;
max: number;
}
/**
* Breakpoint 프리셋 정의
* mobile: 0-767px
* tablet: 768-1023px
* desktop: 1024px+
* portable: 0-1023px (mobile + tablet)
*/
const BREAKPOINT_PRESETS: Record<string, ParsedRange> = {
mobile: { min: 0, max: 767 },
tablet: { min: 768, max: 1023 },
desktop: { min: 1024, max: Infinity },
portable: { min: 0, max: 1023 },
};
/**
* 범위 파싱 결과 캐시 (성능 최적화)
*/
const parsedRangeCache = new Map<string, ParsedRange | null>();
/**
* debounce 함수
*
* @param fn 실행할 함수
* @param delay 지연 시간 (ms)
* @returns debounced 함수
*/
function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): T {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return ((...args: Parameters<T>) => {
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn(...args);
}, delay);
}) as T;
}
/**
* ResponsiveManager 클래스
*
* 싱글톤 패턴으로 화면 너비 감지 및 구독자 관리를 담당합니다.
* TransitionManager와 동일한 패턴을 사용합니다.
*/
class ResponsiveManager {
private subscribers: Set<(width: number) => void> = new Set();
private currentWidth: number = 1024; // 데스크톱 기본값
private debouncedHandler: (() => void) | null = null;
private isInitialized: boolean = false;
constructor() {
this.initialize();
}
/**
* 초기화
* 브라우저 환경에서만 resize 이벤트를 등록합니다.
*/
private initialize(): void {
if (typeof window === 'undefined') {
return;
}
this.currentWidth = window.innerWidth;
this.isInitialized = true;
this.debouncedHandler = debounce(() => {
this.currentWidth = window.innerWidth;
this.notifySubscribers();
}, 150);
window.addEventListener('resize', this.debouncedHandler);
}
/**
* 모든 구독자에게 현재 너비를 알립니다.
*/
private notifySubscribers(): void {
this.subscribers.forEach((callback) => {
callback(this.currentWidth);
});
}
/**
* 화면 너비 변경을 구독합니다.
*
* @param callback 너비 변경 시 호출될 콜백
* @returns 구독 해제 함수
*/
subscribe(callback: (width: number) => void): () => void {
this.subscribers.add(callback);
// 즉시 현재값 전달
callback(this.currentWidth);
return () => {
this.subscribers.delete(callback);
};
}
/**
* 현재 화면 너비를 반환합니다.
*
* @returns 현재 화면 너비 (px)
*/
getWidth(): number {
return this.currentWidth;
}
/**
* Breakpoint 키를 파싱하여 범위를 반환합니다.
*
* 지원 형식:
* - 프리셋: 'mobile', 'tablet', 'desktop'
* - 범위: '0-767', '768-1023', '1024-'
* - 열린 범위: '-599', '1200-'
*
* @param key Breakpoint 키
* @returns 파싱된 범위 또는 null (잘못된 형식)
*/
parseRange(key: string): ParsedRange | null {
// 캐시 확인
if (parsedRangeCache.has(key)) {
return parsedRangeCache.get(key) ?? null;
}
let result: ParsedRange | null = null;
// 프리셋 확인
if (BREAKPOINT_PRESETS[key]) {
result = { ...BREAKPOINT_PRESETS[key] };
} else {
// 커스텀 범위 파싱
// 패턴: "min-max", "-max", "min-"
const rangeMatch = key.match(/^(-?\d*)-(-?\d*)$/);
if (rangeMatch) {
const [, minStr, maxStr] = rangeMatch;
// min 파싱 (빈 문자열이면 0)
const min = minStr === '' ? 0 : parseInt(minStr, 10);
// max 파싱 (빈 문자열이면 Infinity)
const max = maxStr === '' ? Infinity : parseInt(maxStr, 10);
// 유효성 검사
if (!isNaN(min) && !isNaN(max) && min <= max) {
result = { min, max };
}
}
}
// 캐시에 저장
parsedRangeCache.set(key, result);
return result;
}
/**
* 주어진 너비에 매칭되는 가장 우선순위가 높은 키를 찾습니다.
*
* 우선순위 규칙:
* 1. 커스텀 범위 > 프리셋
* 2. 좁은 범위 > 넓은 범위
*
* @param responsive responsive 객체 (breakpoint 키 -> 오버라이드 값)
* @param width 현재 화면 너비
* @returns 매칭된 키 또는 null
*/
getMatchingKey(responsive: Record<string, any>, width: number): string | null {
const matchedKeys: Array<{
key: string;
range: ParsedRange;
isPreset: boolean;
}> = [];
// 모든 키에 대해 매칭 검사
for (const key of Object.keys(responsive)) {
const range = this.parseRange(key);
if (!range) {
continue;
}
// 너비가 범위 내에 있는지 확인
if (width >= range.min && width <= range.max) {
matchedKeys.push({
key,
range,
isPreset: !!BREAKPOINT_PRESETS[key],
});
}
}
// 매칭된 키가 없으면 null
if (matchedKeys.length === 0) {
return null;
}
// 우선순위에 따라 정렬
matchedKeys.sort((a, b) => {
// 1. 커스텀 범위가 프리셋보다 우선
if (a.isPreset !== b.isPreset) {
return a.isPreset ? 1 : -1;
}
// 2. 좁은 범위가 넓은 범위보다 우선
const aWidth = a.range.max - a.range.min;
const bWidth = b.range.max - b.range.min;
return aWidth - bWidth;
});
return matchedKeys[0].key;
}
/**
* 현재 너비가 주어진 breakpoint에 매칭되는지 확인합니다.
*
* @param key Breakpoint 키
* @returns 매칭 여부
*/
matches(key: string): boolean {
const range = this.parseRange(key);
if (!range) {
return false;
}
return this.currentWidth >= range.min && this.currentWidth <= range.max;
}
/**
* 모든 구독을 해제합니다.
*/
clearSubscribers(): void {
this.subscribers.clear();
}
/**
* ResponsiveManager를 정리합니다.
* 테스트 환경에서 사용됩니다.
*/
destroy(): void {
if (this.debouncedHandler && typeof window !== 'undefined') {
window.removeEventListener('resize', this.debouncedHandler);
}
this.clearSubscribers();
parsedRangeCache.clear();
}
/**
* 테스트용: 현재 너비를 강제로 설정합니다.
*
* @param width 설정할 너비
*/
_setWidthForTesting(width: number): void {
this.currentWidth = width;
this.notifySubscribers();
}
}
// 싱글톤 인스턴스 export
export const responsiveManager = new ResponsiveManager();
// 타입 및 상수 export
export type { ParsedRange };
export { BREAKPOINT_PRESETS };
@@ -0,0 +1,377 @@
/**
* NOTE: @since versions (engine-v1.x.x) refer to internal template engine
* development iterations, not G7 platform release versions.
*/
/**
* SlotContext.tsx
*
* 동적 슬롯 시스템을 위한 Context
*
* 슬롯 시스템은 컴포넌트를 원래 위치에서 다른 위치(SlotContainer)로
* 동적으로 이동시킬 수 있는 기능을 제공합니다.
*
* 주요 기능:
* - 컴포넌트를 슬롯에 등록/해제
* - 슬롯별 컴포넌트 수집 및 정렬
* - 슬롯 변경 시 구독자 알림
* - 레이아웃 언마운트 시 자동 클리어
*
* @module SlotContext
* @since engine-v1.10.0
*/
import React, { createContext, useContext, useCallback, useRef, useMemo, useLayoutEffect } from 'react';
import type { ComponentDefinition } from './DynamicRenderer';
import type { FormContextValue } from './FormContext';
import { createLogger } from '../utils/Logger';
const logger = createLogger('SlotContext');
/**
* 슬롯에 등록되는 컴포넌트 정보
*/
export interface SlotRegistration {
/** 컴포넌트 정의 (slot 속성이 제거된 상태) */
componentDef: ComponentDefinition;
/** 컴포넌트의 데이터 컨텍스트 (API 데이터, route params 등) */
dataContext: Record<string, any>;
/** 슬롯 내 정렬 순서 (낮을수록 먼저 렌더링) */
order: number;
/**
* 부모 Form 컨텍스트
*
* 슬롯 이동 후에도 폼 바인딩이 유지되도록 함
*/
parentFormContext: FormContextValue | null;
/**
* 부모 컴포넌트 컨텍스트 getter
*
* Stale Closure 문제를 방지하기 위해 getter 함수로 전달
* 호출 시점의 최신 state/setState를 반환
*/
getParentComponentContext: () => {
state: Record<string, any>;
setState: (updates: Record<string, any>) => void;
};
/** 번역 컨텍스트 */
translationContext: any;
/** 컴포넌트 등록 시점의 고유 키 (중복 등록 방지용) */
registrationKey: string;
}
/**
* 슬롯 컨텍스트 값 인터페이스
*/
export interface SlotContextValue {
/**
* 컴포넌트를 슬롯에 등록
*
* @param slotId 슬롯 ID (예: "basic_filters", "detail_filters")
* @param componentId 컴포넌트 ID (고유 식별자)
* @param registration 등록 정보
*/
registerToSlot: (slotId: string, componentId: string, registration: SlotRegistration) => void;
/**
* 컴포넌트를 슬롯에서 해제
*
* @param slotId 슬롯 ID
* @param componentId 컴포넌트 ID
*/
unregisterFromSlot: (slotId: string, componentId: string) => void;
/**
* 슬롯에 등록된 컴포넌트 목록 조회
*
* @param slotId 슬롯 ID
* @returns 등록된 컴포넌트 목록 (order 기준 정렬)
*/
getSlotComponents: (slotId: string) => SlotRegistration[];
/**
* 슬롯 변경 구독
*
* @param slotId 슬롯 ID
* @param callback 변경 시 호출될 콜백
* @returns 구독 해제 함수
*/
subscribeToSlot: (slotId: string, callback: () => void) => () => void;
/**
* 모든 슬롯 클리어 (레이아웃 언마운트 시 사용)
*/
clearAllSlots: () => void;
/**
* 슬롯 시스템 활성화 여부
*
* SlotProvider 내부에서만 true
*/
isEnabled: boolean;
}
/**
* 기본 슬롯 컨텍스트 값 (비활성화 상태)
*/
const defaultSlotContextValue: SlotContextValue = {
registerToSlot: () => {
logger.warn('SlotContext not available: registerToSlot called outside SlotProvider');
},
unregisterFromSlot: () => {
logger.warn('SlotContext not available: unregisterFromSlot called outside SlotProvider');
},
getSlotComponents: () => [],
subscribeToSlot: () => () => {},
clearAllSlots: () => {},
isEnabled: false,
};
/**
* 슬롯 컨텍스트
*/
export const SlotContext = createContext<SlotContextValue>(defaultSlotContextValue);
/**
* SlotProvider Props
*/
export interface SlotProviderProps {
children: React.ReactNode;
}
/**
* 슬롯 Provider
*
* 레이아웃 최상위에서 한 번만 래핑하여 슬롯 시스템을 활성화합니다.
* DynamicRenderer의 최상위 렌더러에서 자동으로 래핑됩니다.
*
* @example
* ```tsx
* <SlotProvider>
* <DynamicRenderer componentDef={...} />
* </SlotProvider>
* ```
*/
export const SlotProvider: React.FC<SlotProviderProps> = ({ children }) => {
/**
* 슬롯별 컴포넌트 저장소
*
* Map<slotId, Map<componentId, SlotRegistration>>
*/
const slotsRef = useRef<Map<string, Map<string, SlotRegistration>>>(new Map());
/**
* 슬롯별 구독자 저장소
*
* Map<slotId, Set<callback>>
*/
const subscribersRef = useRef<Map<string, Set<() => void>>>(new Map());
/**
* 슬롯 변경 알림
*/
const notifySlotSubscribers = useCallback((slotId: string) => {
const subscribers = subscribersRef.current.get(slotId);
if (subscribers) {
subscribers.forEach(callback => {
try {
callback();
} catch (error) {
logger.error(`Slot subscriber error (slotId: ${slotId}):`, error);
}
});
}
}, []);
/**
* 컴포넌트를 슬롯에 등록
*/
const registerToSlot = useCallback((
slotId: string,
componentId: string,
registration: SlotRegistration
) => {
if (!slotId || !componentId) {
logger.warn('registerToSlot: slotId and componentId are required');
return;
}
// 슬롯 맵 생성 (없으면)
if (!slotsRef.current.has(slotId)) {
slotsRef.current.set(slotId, new Map());
}
const slotMap = slotsRef.current.get(slotId)!;
// 기존 등록이 있고 같은 registrationKey면 스킵 (중복 등록 방지)
const existing = slotMap.get(componentId);
if (existing && existing.registrationKey === registration.registrationKey) {
return;
}
// 등록
slotMap.set(componentId, registration);
logger.log(`Component registered to slot: ${componentId} -> ${slotId} (order: ${registration.order})`);
// 구독자 알림
notifySlotSubscribers(slotId);
}, [notifySlotSubscribers]);
/**
* 컴포넌트를 슬롯에서 해제
*/
const unregisterFromSlot = useCallback((slotId: string, componentId: string) => {
const slotMap = slotsRef.current.get(slotId);
if (!slotMap) return;
if (slotMap.has(componentId)) {
slotMap.delete(componentId);
logger.log(`Component unregistered from slot: ${componentId} <- ${slotId}`);
// 슬롯이 비었으면 맵 제거
if (slotMap.size === 0) {
slotsRef.current.delete(slotId);
}
// 구독자 알림
notifySlotSubscribers(slotId);
}
}, [notifySlotSubscribers]);
/**
* 슬롯에 등록된 컴포넌트 목록 조회 (order 기준 정렬)
*/
const getSlotComponents = useCallback((slotId: string): SlotRegistration[] => {
const slotMap = slotsRef.current.get(slotId);
if (!slotMap) return [];
// Map을 배열로 변환 후 order 기준 정렬
return Array.from(slotMap.values()).sort((a, b) => a.order - b.order);
}, []);
/**
* 슬롯 변경 구독
*/
const subscribeToSlot = useCallback((slotId: string, callback: () => void): (() => void) => {
// 구독자 Set 생성 (없으면)
if (!subscribersRef.current.has(slotId)) {
subscribersRef.current.set(slotId, new Set());
}
const subscribers = subscribersRef.current.get(slotId)!;
subscribers.add(callback);
// 구독 해제 함수 반환
return () => {
subscribers.delete(callback);
if (subscribers.size === 0) {
subscribersRef.current.delete(slotId);
}
};
}, []);
/**
* 모든 슬롯 클리어
*/
const clearAllSlots = useCallback(() => {
// 모든 슬롯의 구독자에게 알림
slotsRef.current.forEach((_, slotId) => {
notifySlotSubscribers(slotId);
});
// 슬롯 및 구독자 클리어
slotsRef.current.clear();
subscribersRef.current.clear();
logger.log('All slots cleared');
}, [notifySlotSubscribers]);
/**
* 컨텍스트 값 메모이제이션
*/
const contextValue = useMemo<SlotContextValue>(() => ({
registerToSlot,
unregisterFromSlot,
getSlotComponents,
subscribeToSlot,
clearAllSlots,
isEnabled: true,
}), [registerToSlot, unregisterFromSlot, getSlotComponents, subscribeToSlot, clearAllSlots]);
/**
* SlotContext를 전역에 노출
*
* SlotContainer 등 외부 컴포넌트에서 G7Core.getSlotContext()로 접근할 수 있도록 합니다.
* G7Core 존재 여부와 관계없이 __slotContextValue를 설정합니다.
*
* 중요: useLayoutEffect 사용 (useEffect가 아님)
* - 자식 컴포넌트의 useEffect(슬롯 등록)보다 먼저 실행되어야 함
* - React effect 실행 순서: useLayoutEffect(자식→부모) → paint → useEffect(자식→부모)
* - useLayoutEffect는 모든 useEffect보다 먼저 실행되므로, 부모의 useLayoutEffect →
* 자식의 useEffect 순서가 보장됨
*
* 중요: cleanup에서 null로 설정하지 않음
* - React의 리렌더링/Strict Mode에서 cleanup → new effect 사이에 다른 컴포넌트가
* isEnabled를 확인하면 false가 되는 타이밍 이슈 방지
* - 새 SlotProvider가 마운트되면 새 contextValue로 덮어씀
* - 진짜 언마운트 시에만 페이지 이동 등으로 자연스럽게 정리됨
*/
useLayoutEffect(() => {
if (typeof window !== 'undefined') {
// 전역에 현재 SlotContext 값에 접근하는 getter 저장
// G7Core 존재 여부와 관계없이 설정 (SlotContainer에서 직접 접근 가능)
(window as any).__slotContextValue = contextValue;
logger.log('SlotContext exposed to window.__slotContextValue');
}
// cleanup에서 null로 설정하지 않음 - 타이밍 이슈 방지
// 새 SlotProvider가 마운트되면 자동으로 새 값으로 덮어씀
}, [contextValue]);
return (
<SlotContext.Provider value={contextValue}>
{children}
</SlotContext.Provider>
);
};
/**
* 슬롯 컨텍스트 Hook
*
* @returns 슬롯 컨텍스트 값
*/
export const useSlotContext = (): SlotContextValue => {
return useContext(SlotContext);
};
/**
* 슬롯에 등록된 컴포넌트 목록을 구독하는 Hook
*
* 슬롯 내용이 변경되면 컴포넌트를 리렌더링합니다.
*
* @param slotId 슬롯 ID
* @returns 등록된 컴포넌트 목록
*/
export const useSlotComponents = (slotId: string): SlotRegistration[] => {
const { getSlotComponents, subscribeToSlot, isEnabled } = useSlotContext();
const [, forceUpdate] = React.useState({});
// 슬롯 변경 구독
React.useEffect(() => {
if (!isEnabled) return;
const unsubscribe = subscribeToSlot(slotId, () => {
forceUpdate({});
});
return unsubscribe;
}, [slotId, subscribeToSlot, isEnabled]);
return getSlotComponents(slotId);
};
export default SlotContext;
@@ -0,0 +1,175 @@
/**
* SystemBannerManager.ts
*
* 시스템 배너 관리자
*
* 프리뷰 모드, 유지보수 모드 등 시스템 상태를 사용자에게 알리는
* 고정 배너를 관리합니다.
*
* @module SystemBannerManager
* @since engine-v1.26.1
*/
import { createLogger } from '../utils/Logger';
const logger = createLogger('SystemBannerManager');
/**
* 시스템 배너 옵션
*/
export interface SystemBannerOptions {
/** 배너 고유 ID */
id: string;
/** 표시할 메시지 (다국어: { ko, en } 객체 또는 단일 string) */
message: string | Record<string, string>;
/** 배너 배경색 (CSS gradient 또는 단색) */
background?: string;
/** 배너 텍스트 색 */
color?: string;
/** 배너 순서 (낮을수록 위에 표시, 기본: 0) */
order?: number;
}
/**
* 시스템 배너 관리자
*
* 프리뷰 모드, 유지보수 모드 등 시스템 상태를 사용자에게 알리는
* 고정 배너를 관리합니다.
*
* @since engine-v1.26.1
*/
export class SystemBannerManager {
private static banners: Map<string, SystemBannerOptions> = new Map();
private static containerId = 'g7-system-banners';
/**
* 시스템 배너를 추가합니다.
*
* @param options 배너 옵션
*/
static show(options: SystemBannerOptions): void {
this.banners.set(options.id, options);
this.render();
logger.log(`Banner shown: ${options.id}`);
}
/**
* 배너를 제거합니다.
*
* @param id 배너 고유 ID
*/
static hide(id: string): void {
if (this.banners.delete(id)) {
this.render();
logger.log(`Banner hidden: ${id}`);
}
}
/**
* 모든 배너를 제거합니다.
*/
static hideAll(): void {
this.banners.clear();
this.render();
logger.log('All banners hidden');
}
/**
* 현재 브라우저 로케일을 감지합니다.
*
* @returns 로케일 코드 (ko, en 등)
*/
private static detectLocale(): string {
// G7Core에서 로케일 가져오기
// G7Core.locale은 객체: { current(), supported(), change() }
try {
const G7Core = (window as any).G7Core;
if (G7Core?.locale?.current) {
return G7Core.locale.current();
}
} catch {
// ignore
}
// fallback: 브라우저 언어 감지
const lang = navigator.language || 'ko';
return lang.split('-')[0];
}
/**
* 메시지를 로케일에 따라 해석합니다.
*
* @param message 단일 문자열 또는 다국어 객체
* @param locale 로케일 코드
* @returns 해석된 메시지 문자열
*/
private static resolveMessage(message: string | Record<string, string>, locale: string): string {
if (typeof message === 'string') {
return message;
}
return message[locale] || message['en'] || message['ko'] || Object.values(message)[0] || '';
}
/**
* 모든 배너를 DOM에 렌더링합니다.
*/
private static render(): void {
if (typeof document === 'undefined') {
return;
}
let container = document.getElementById(this.containerId);
// 배너가 없으면 컨테이너 제거
if (this.banners.size === 0) {
if (container) {
container.remove();
this.adjustAppPadding(0);
}
return;
}
// 컨테이너 생성 (없으면)
if (!container) {
container = document.createElement('div');
container.id = this.containerId;
container.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:99999;';
document.body.prepend(container);
}
// 배너를 order 기준으로 정렬
const sortedBanners = Array.from(this.banners.values()).sort(
(a, b) => (a.order ?? 0) - (b.order ?? 0)
);
const locale = this.detectLocale();
// HTML 렌더링
container.innerHTML = sortedBanners.map(banner => {
const msg = this.resolveMessage(banner.message, locale);
const bg = banner.background || '#f59e0b';
const color = banner.color || 'white';
return `<div data-banner-id="${banner.id}" style="background:${bg};color:${color};text-align:center;padding:8px 16px;font-size:14px;font-weight:500;">${msg}</div>`;
}).join('');
// #app 컨테이너에 paddingTop 적용 (배너 높이만큼)
// requestAnimationFrame으로 렌더링 후 높이 측정
requestAnimationFrame(() => {
if (container) {
this.adjustAppPadding(container.offsetHeight);
}
});
}
/**
* #app 컨테이너의 paddingTop을 조정합니다.
*
* @param height 배너 컨테이너 높이 (px)
*/
private static adjustAppPadding(height: number): void {
const app = document.getElementById('app');
if (app) {
app.style.paddingTop = height > 0 ? `${height}px` : '';
}
}
}
@@ -0,0 +1,168 @@
import type { TranslationContext } from '../template-engine/TranslationEngine';
/**
* 템플릿 엔진 에러 기본 클래스
*/
export class TemplateEngineError extends Error {
public readonly code: string;
public readonly userMessageKey: string;
public readonly showStack: boolean;
public readonly icon: string;
public readonly recoverable: boolean;
constructor(
code: string,
userMessageKey: string,
options: {
showStack?: boolean;
icon?: string;
recoverable?: boolean;
} = {}
) {
super(userMessageKey);
this.name = 'TemplateEngineError';
this.code = code;
this.userMessageKey = userMessageKey;
this.showStack = options.showStack ?? true;
this.icon = options.icon ?? 'fa-circle-exclamation';
this.recoverable = options.recoverable ?? true;
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
/**
* 다국어가 적용된 사용자 메시지를 반환합니다.
*
* @param context 번역 컨텍스트
* @param translationEngine 번역 엔진 (선택)
*/
getUserMessage(
context?: TranslationContext,
translationEngine?: { translate: (key: string, context: TranslationContext) => string }
): string {
// 번역 엔진이 없거나 컨텍스트가 없으면 키를 그대로 반환
if (!translationEngine || !context) {
return this.userMessageKey;
}
try {
return translationEngine.translate(this.userMessageKey, context);
} catch (e) {
// 번역 실패 시 키를 그대로 반환
return this.userMessageKey;
}
}
}
/**
* 템플릿을 찾을 수 없을 때 발생하는 에러
*/
export class TemplateNotFoundError extends TemplateEngineError {
constructor() {
super(
'TEMPLATE_NOT_FOUND',
'$t:core.errors.template_not_found',
{
showStack: false,
icon: 'fa-paint-brush',
recoverable: false,
}
);
this.name = 'TemplateNotFoundError';
}
}
/**
* 레이아웃 로딩 실패 에러
*/
export class LayoutLoadError extends TemplateEngineError {
constructor(layoutId?: string) {
const messageKey = layoutId
? '$t:core.errors.layout_load_failed_with_id|layoutId=' + layoutId
: '$t:core.errors.layout_load_failed';
super('LAYOUT_LOAD_FAILED', messageKey, {
showStack: true,
icon: 'fa-file-circle-xmark',
recoverable: true,
});
this.name = 'LayoutLoadError';
}
}
/**
* 컴포넌트 레지스트리 에러
*/
export class ComponentRegistryError extends TemplateEngineError {
constructor(componentName?: string) {
const messageKey = componentName
? '$t:core.errors.component_load_failed_with_name|componentName=' + componentName
: '$t:core.errors.component_load_failed';
super('COMPONENT_REGISTRY_FAILED', messageKey, {
showStack: true,
icon: 'fa-cubes',
recoverable: true,
});
this.name = 'ComponentRegistryError';
}
}
/**
* 번역 파일 로딩 에러
*/
export class TranslationLoadError extends TemplateEngineError {
constructor(locale?: string) {
const messageKey = locale
? '$t:core.errors.translation_load_failed_with_locale|locale=' + locale
: '$t:core.errors.translation_load_failed';
super('TRANSLATION_LOAD_FAILED', messageKey, {
showStack: false,
icon: 'fa-language',
recoverable: true,
});
this.name = 'TranslationLoadError';
}
}
/**
* 일반 Error를 TemplateEngineError로 변환
*/
export function toTemplateEngineError(error: Error | unknown): TemplateEngineError {
// 이미 TemplateEngineError인 경우 그대로 반환
if (error instanceof TemplateEngineError) {
return error;
}
// Error 객체인 경우
if (error instanceof Error) {
// 원본 에러 메시지를 그대로 사용 (다국어 키가 아님)
const tempError = new TemplateEngineError(
'TEMPLATE_INIT_ERROR',
error.message || '$t:core.errors.template_init_error',
{
showStack: true,
icon: 'fa-circle-exclamation',
recoverable: true,
}
);
// 원본 스택을 보존
tempError.stack = error.stack;
return tempError;
}
// 기타 타입인 경우
return new TemplateEngineError(
'TEMPLATE_INIT_ERROR',
'$t:core.errors.template_init_error',
{
showStack: false,
icon: 'fa-circle-exclamation',
recoverable: true,
}
);
}
Loaded 100 of 3967 files, more files were not shown because too many files have changed in this diff. Show more