v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -15,6 +15,7 @@ import { evaluateRenderCondition } from './template-engine/helpers/RenderHelpers
|
||||
import { ComponentRegistry } from './template-engine/ComponentRegistry';
|
||||
import { DataSourceManager } from './template-engine/DataSourceManager';
|
||||
import { initTemplateEngine, renderTemplate, destroyTemplate, getState, updateTemplateData } from './template-engine';
|
||||
import { checkLayoutEditorMode } from './template-engine/layout-editor/hooks/useEditorMode';
|
||||
import { ErrorDisplay } from './template-engine/ErrorDisplay';
|
||||
import { toTemplateEngineError } from './template-engine/TemplateEngineError';
|
||||
import { ErrorPageHandler } from './template-engine/ErrorPageHandler';
|
||||
@@ -237,8 +238,17 @@ export class TemplateApp {
|
||||
private globalStateListeners: Set<(state: GlobalState) => void> = new Set();
|
||||
/** 현재 진행 중인 라우트 변경 요청 ID (새 요청 시 이전 요청 무시용) */
|
||||
private currentRouteChangeId: number = 0;
|
||||
/** 현재 레이아웃의 데이터 소스 정의 (refetch용) */
|
||||
/** 현재 레이아웃의 데이터 소스 정의 (if 조건으로 필터링된 결과 — refetch용) */
|
||||
private currentDataSources: any[] = [];
|
||||
/**
|
||||
* 현재 레이아웃의 원본 데이터 소스 정의 (if 필터링 전 전체).
|
||||
*
|
||||
* replace:true navigate(탭 전환/필터 변경)로 진입하는 updateQueryParams 경로는
|
||||
* 변경된 query 컨텍스트로 데이터소스 if 를 재평가해야 한다. currentDataSources(필터링된
|
||||
* 스냅샷)만으로는 직전 진입 시점 조건에 고정되어, 탭 전환 시 다른 탭의 데이터소스가
|
||||
* 잘못 선택되는 회귀가 발생한다. 원본을 보존해 재평가 가능하게 한다.
|
||||
*/
|
||||
private currentRawDataSources: any[] = [];
|
||||
/** 현재 라우트 파라미터 (refetch용) */
|
||||
private currentRouteParams: Record<string, string> = {};
|
||||
/** 현재 쿼리 파라미터 (refetch용) */
|
||||
@@ -675,6 +685,32 @@ export class TemplateApp {
|
||||
// 8.5 routeNotFound 이벤트 핸들러 등록 (404 에러 페이지 처리)
|
||||
this.router.on('routeNotFound', (path: string) => this.handleRouteNotFound(path));
|
||||
|
||||
// 8.6 레이아웃 편집기 모드 가드
|
||||
//
|
||||
// URL 이 `/admin/layout-editor/:identifier` 패턴이면 라우터 매칭을 건너뛰고
|
||||
// 직접 renderTemplate 호출 — template-engine.ts 의 checkLayoutEditorMode 분기가
|
||||
// LayoutEditorChrome 을 같은 reactRoot + 코어 컨텍스트 안에서 렌더한다.
|
||||
//
|
||||
// 이 가드가 없으면 `/admin/layout-editor/...` 가 일반 라우트에 매칭되지 않아
|
||||
// routeNotFound → 404 페이지 렌더 흐름을 타게 되고, 그 안의 renderTemplate
|
||||
// 호출에서야 비로소 편집기 분기가 작동한다. 결과적으로 화면은 정상이지만
|
||||
// 콘솔에 `[Router] No route matched` 워닝 + 불필요한 `/api/layouts/.../404.json`
|
||||
// fetch 가 발생하며, 후속 Phase 에서 라우트 의존 기능 도입 시 회귀 위험이 있다.
|
||||
if (typeof window !== 'undefined' && checkLayoutEditorMode(window.location.pathname)) {
|
||||
logger.log('Layout editor mode detected — skipping router match');
|
||||
await renderTemplate({
|
||||
containerId: 'app',
|
||||
layoutJson: { components: [] } as any,
|
||||
dataContext: {},
|
||||
translationContext: {
|
||||
templateId: this.config.templateId,
|
||||
locale: this.config.locale,
|
||||
},
|
||||
});
|
||||
logger.log('Template App initialized in layout editor mode');
|
||||
return;
|
||||
}
|
||||
|
||||
// 9. 초기 라우트 처리
|
||||
this.router.navigateToCurrentPath();
|
||||
|
||||
@@ -941,6 +977,8 @@ export class TemplateApp {
|
||||
|
||||
// 현재 데이터 소스 정보 저장 (refetch용)
|
||||
this.currentDataSources = dataSources;
|
||||
// 원본(if 필터링 전) 보존 — updateQueryParams(replace:true) 의 if 재평가용
|
||||
this.currentRawDataSources = rawDataSources;
|
||||
this.currentRouteParams = route.params || {};
|
||||
this.currentQueryParams = queryParams;
|
||||
|
||||
@@ -2114,7 +2152,22 @@ export class TemplateApp {
|
||||
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}`;
|
||||
// cssText 일괄 설정 대신 개별 속성으로 — backdrop-filter 같은 미지원 프로퍼티가
|
||||
// 한 선언 블록에 섞이면 일부 CSS 파서(jsdom 테스트 환경)가 그 블록 전체를 거부해
|
||||
// 앞선 background 까지 무효화한다. 개별 setProperty 는 미지원 속성만 무시되고
|
||||
// background 등 나머지는 보존된다(실제 브라우저 동작은 cssText 일괄과 동일).
|
||||
overlay.style.position = 'fixed';
|
||||
overlay.style.inset = '0';
|
||||
overlay.style.zIndex = '9999';
|
||||
overlay.style.pointerEvents = 'none';
|
||||
overlay.style.background = bgCss;
|
||||
// blur 스타일의 backdrop-filter — `prop:value;` 쌍을 분해해 개별 적용(브라우저에선
|
||||
// 적용, 미지원 파서에선 무시되어도 background 보존).
|
||||
for (const decl of extraCss.split(';')) {
|
||||
const idx = decl.indexOf(':');
|
||||
if (idx === -1) continue;
|
||||
overlay.style.setProperty(decl.slice(0, idx).trim(), decl.slice(idx + 1).trim());
|
||||
}
|
||||
document.body.appendChild(overlay);
|
||||
this.transitionOverlayEl = overlay;
|
||||
}
|
||||
@@ -2517,7 +2570,7 @@ export class TemplateApp {
|
||||
private showRouteError(error: Error): void {
|
||||
// 레이아웃 fetch 401 가드: 토큰 만료 등으로 권한이 사라진 상태에서
|
||||
// 레이아웃을 받지 못하면 코어가 로그인 페이지로 자동 리다이렉트한다.
|
||||
// (Issue #301 — 사용자 인식 문제 해결: 시스템 장애 화면 대신 안내 토스트)
|
||||
// ( — 사용자 인식 문제 해결: 시스템 장애 화면 대신 안내 토스트)
|
||||
//
|
||||
// hadToken 판정 (reason='session_expired' 부여 여부):
|
||||
// - 현재 apiClient 가 토큰을 보유했거나
|
||||
@@ -3699,10 +3752,28 @@ export class TemplateApp {
|
||||
this.currentQueryParams = newQueryParams;
|
||||
logger.log('currentQueryParams updated:', Object.fromEntries(newQueryParams.entries()));
|
||||
|
||||
// 3. auto_fetch: true인 데이터 소스들 refetch
|
||||
// 3. 데이터소스 if 재평가
|
||||
// replace:true navigate(탭 전환/필터 변경)는 query 컨텍스트가 바뀌므로, 직전 진입 시점에
|
||||
// 필터링된 currentDataSources 스냅샷을 재사용하면 다른 탭의 데이터소스가 잘못 선택된다.
|
||||
// 원본(currentRawDataSources)을 변경된 query + 최신 _global 로 다시 filterByCondition 한다.
|
||||
// 원본 미보존(구버전 캐시 등) 시 기존 currentDataSources 로 안전 폴백.
|
||||
const reevalManager = new DataSourceManager();
|
||||
const latestGlobal = getState().currentDataContext?._global || this.globalState || {};
|
||||
const reevalContext = {
|
||||
route: this.currentRouteParams || {},
|
||||
query: parseQueryParams(this.currentQueryParams),
|
||||
_global: latestGlobal,
|
||||
};
|
||||
const reevaluatedSources = Array.isArray(this.currentRawDataSources) && this.currentRawDataSources.length > 0
|
||||
? reevalManager.filterByCondition(this.currentRawDataSources, reevalContext as any)
|
||||
: this.currentDataSources;
|
||||
// 재평가 결과를 현재 데이터소스로 갱신 (이후 wait_for 판정/refetchDataSource 가 참조)
|
||||
this.currentDataSources = reevaluatedSources;
|
||||
|
||||
// 4. auto_fetch: true인 데이터 소스들 refetch
|
||||
// WebSocket 소스는 이벤트 리스너(실시간 알림)이지 fetch 대상이 아님 (engine-v1.32.2 정책)
|
||||
// handleRouteChange progressive 경로와 동일하게 호출 전에 필터링하여 계약 일관성 확보
|
||||
const autoFetchDataSources = this.currentDataSources.filter(
|
||||
const autoFetchDataSources = reevaluatedSources.filter(
|
||||
(ds: any) => ds.auto_fetch !== false && ds.type !== 'websocket'
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* @file TemplateApp.updateQueryParams.condition.test.ts
|
||||
* @description replace:true navigate(탭 전환/필터 변경) 경로의 데이터소스 if 재평가 회귀 (#415)
|
||||
*
|
||||
* 버그:
|
||||
* updateQueryParams(replace:true navigate 진입점)가 직전 진입 시점에 if 로 필터링된
|
||||
* currentDataSources 스냅샷을 그대로 refetch 했다. 탭 전환으로 query 컨텍스트가 바뀌어도
|
||||
* if 를 재평가하지 않아, 다른 탭의 데이터소스가 잘못 선택되었다.
|
||||
* (예: 본인인증 탭→언어팩 탭 클릭 전환 시, 언어팩 데이터소스가 fetch 되지 않고
|
||||
* 정책 데이터소스가 계속 fetch 됨)
|
||||
*
|
||||
* 수정:
|
||||
* currentRawDataSources(if 필터링 전 원본)를 보존하고, updateQueryParams 에서 변경된 query +
|
||||
* 최신 _global 로 filterByCondition 을 재평가하여 fetch 대상을 다시 산정한다.
|
||||
*
|
||||
* 검증:
|
||||
* fetchDataSourcesWithResults 를 spy 로 가로채, updateQueryParams 호출 시 전달된 데이터소스
|
||||
* 목록이 새 query.tab 기준으로 재평가되었는지 확인.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
|
||||
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,
|
||||
currentDataContext: { _global: { activeSettingsTab: 'language_packs' } },
|
||||
bindingEngine: { invalidateCacheByKeys: vi.fn() },
|
||||
}),
|
||||
}));
|
||||
|
||||
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([]);
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../template-engine/LayoutLoader', () => ({
|
||||
LayoutLoader: vi.fn(function (this: any) {
|
||||
this.loadLayout = vi.fn().mockResolvedValue({ components: [] });
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../template-engine/ComponentRegistry', () => {
|
||||
const mockInstance: any = {
|
||||
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) } };
|
||||
});
|
||||
|
||||
import { TemplateApp } from '../TemplateApp';
|
||||
import { DataSourceManager } from '../template-engine/DataSourceManager';
|
||||
|
||||
/** 정책/언어팩/공통 데이터소스 원본 (admin_settings.json 구조 축약) */
|
||||
const RAW_SOURCES = [
|
||||
{ id: 'settings', type: 'api', endpoint: '/api/admin/settings', auto_fetch: true },
|
||||
{
|
||||
id: 'policies',
|
||||
type: 'api',
|
||||
endpoint: '/api/admin/identity/policies',
|
||||
auto_fetch: true,
|
||||
if: "{{(query.tab || _global.activeSettingsTab) === 'identity'}}",
|
||||
},
|
||||
{
|
||||
id: 'language_packs',
|
||||
type: 'api',
|
||||
endpoint: '/api/admin/language-packs',
|
||||
auto_fetch: true,
|
||||
if: "{{(query.tab || _global.activeSettingsTab) === 'language_packs'}}",
|
||||
},
|
||||
];
|
||||
|
||||
describe('updateQueryParams 데이터소스 if 재평가 (#415)', () => {
|
||||
let app: TemplateApp;
|
||||
let fetchSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '<div id="app"></div>';
|
||||
window.history.replaceState(null, '', '/admin/settings?tab=identity');
|
||||
(window as any).G7Core = {};
|
||||
|
||||
app = new TemplateApp({ templateId: 'sirsoft-admin_basic', locale: 'ko' } as any);
|
||||
|
||||
// 직전 진입(본인인증 탭) 시점 스냅샷 모사: policies 만 선택된 상태
|
||||
const dm = new DataSourceManager();
|
||||
const initialSelected = dm.filterByCondition(RAW_SOURCES as any, {
|
||||
query: { tab: 'identity' },
|
||||
route: {},
|
||||
_global: { activeSettingsTab: 'identity' },
|
||||
} as any);
|
||||
(app as any).currentRawDataSources = RAW_SOURCES;
|
||||
(app as any).currentDataSources = initialSelected;
|
||||
(app as any).currentRouteParams = {};
|
||||
(app as any).currentQueryParams = new URLSearchParams('tab=identity');
|
||||
(app as any).currentFetchedData = {};
|
||||
(app as any).globalState = { activeSettingsTab: 'language_packs' };
|
||||
(app as any).currentGlobalHeaders = [];
|
||||
|
||||
// fetch 를 가로채 빈 결과 반환 — 실제 네트워크 없이 "어떤 소스로 호출됐는지"만 검사
|
||||
fetchSpy = vi
|
||||
.spyOn(DataSourceManager.prototype, 'fetchDataSourcesWithResults')
|
||||
.mockResolvedValue([] as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
delete (window as any).G7Core;
|
||||
});
|
||||
|
||||
it('본인인증→언어팩 탭 전환 시 language_packs 가 재선택되어 fetch 되고 policies 는 제외된다', async () => {
|
||||
await app.updateQueryParams('/admin/settings?tab=language_packs');
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalled();
|
||||
const fetchedSources = (fetchSpy.mock.calls[0][0] as any[]).map((s) => s.id);
|
||||
|
||||
expect(fetchedSources).toContain('language_packs');
|
||||
expect(fetchedSources).not.toContain('policies');
|
||||
// if 없는 공통 소스는 항상 포함
|
||||
expect(fetchedSources).toContain('settings');
|
||||
});
|
||||
|
||||
it('재평가 결과가 currentDataSources 에도 반영된다 (이후 refetchDataSource/wait_for 참조용)', async () => {
|
||||
await app.updateQueryParams('/admin/settings?tab=language_packs');
|
||||
|
||||
const currentIds = (app as any).currentDataSources.map((s: any) => s.id);
|
||||
expect(currentIds).toContain('language_packs');
|
||||
expect(currentIds).not.toContain('policies');
|
||||
});
|
||||
|
||||
it('언어팩→본인인증 탭 전환 시 policies 가 재선택되어 fetch 되고 language_packs 는 제외된다', async () => {
|
||||
// 직전 진입(언어팩 탭) 스냅샷으로 재설정
|
||||
const dm = new DataSourceManager();
|
||||
(app as any).currentDataSources = dm.filterByCondition(RAW_SOURCES as any, {
|
||||
query: { tab: 'language_packs' },
|
||||
route: {},
|
||||
_global: { activeSettingsTab: 'language_packs' },
|
||||
} as any);
|
||||
(app as any).currentQueryParams = new URLSearchParams('tab=language_packs');
|
||||
|
||||
await app.updateQueryParams('/admin/settings?tab=identity');
|
||||
|
||||
const fetchedSources = (fetchSpy.mock.calls.at(-1)![0] as any[]).map((s) => s.id);
|
||||
expect(fetchedSources).toContain('policies');
|
||||
expect(fetchedSources).not.toContain('language_packs');
|
||||
});
|
||||
});
|
||||
@@ -91,11 +91,23 @@ function showTransitionOverlay(config: TransitionOverlayConfig): HTMLElement | n
|
||||
document.head.appendChild(style);
|
||||
return style;
|
||||
} else {
|
||||
// DOM 오버레이 방식 (폴백)
|
||||
// DOM 오버레이 방식 (폴백) — TemplateApp.showTransitionOverlay 와 동일하게 개별 속성으로
|
||||
// 설정한다. cssText 일괄 설정은 backdrop-filter(jsdom 미지원) 가 섞이면 그 선언 블록 전체가
|
||||
// 거부되어 앞선 background 까지 무효화된다. 개별 setProperty 는 미지원 속성만 무시되고
|
||||
// background 는 보존된다(실제 브라우저 동작은 cssText 일괄과 동일).
|
||||
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}`;
|
||||
overlay.style.position = 'fixed';
|
||||
overlay.style.inset = '0';
|
||||
overlay.style.zIndex = '9999';
|
||||
overlay.style.pointerEvents = 'none';
|
||||
overlay.style.background = bgCss;
|
||||
for (const decl of extraCss.split(';')) {
|
||||
const idx = decl.indexOf(':');
|
||||
if (idx === -1) continue;
|
||||
overlay.style.setProperty(decl.slice(0, idx).trim(), decl.slice(idx + 1).trim());
|
||||
}
|
||||
document.body.appendChild(overlay);
|
||||
return overlay;
|
||||
}
|
||||
@@ -177,9 +189,9 @@ describe('transition_overlay', () => {
|
||||
|
||||
it('blur 스타일 시 backdrop-filter를 적용해야 한다', () => {
|
||||
const el = showTransitionOverlay({ enabled: true, style: 'blur' }) as HTMLDivElement;
|
||||
// happy-dom은 backdrop-filter를 CSS 프로퍼티로 인식하지 않으므로
|
||||
// DOM 오버레이 폴백의 blur는 배경색만 검증하고,
|
||||
// backdrop-filter는 CSS <style> 주입 모드 테스트에서 검증
|
||||
// jsdom 은 backdrop-filter 를 CSS 프로퍼티로 인식하지 않는다. 개별 속성 설정이라
|
||||
// backdrop-filter 는 빈 값이 되지만 background 는 보존된다(cssText 일괄이면 동반 무효화).
|
||||
// backdrop-filter 적용 자체는 CSS <style> 주입 모드 테스트(css.toContain)에서 검증.
|
||||
expect(el.style.background).toBe('rgba(255, 255, 255, 0.3)');
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
|
||||
import { AuthManager } from '../auth/AuthManager';
|
||||
import { createLogger } from '../utils/Logger';
|
||||
import { IdentityGuardInterceptor } from '../identity/IdentityGuardInterceptor';
|
||||
import type { G7DevToolsCore } from '../devtools/G7DevToolsCore';
|
||||
|
||||
const logger = createLogger('ApiClient');
|
||||
@@ -21,6 +22,12 @@ function getDevTools(): G7DevToolsCore | null {
|
||||
interface AxiosConfigWithDevTools extends InternalAxiosRequestConfig {
|
||||
_devToolsRequestId?: string | null;
|
||||
_retry?: boolean;
|
||||
/**
|
||||
* IDV 428 인터셉트 시 challenge 에 사용할 인증 대상(이메일·전화).
|
||||
* axios(G7Core.api) 직접 호출 경로에서 호출자가 config 에 실어 보내면 인터셉터가 launcher 로 전달.
|
||||
* apiCall(handleApiCall) 경로의 `identity_target` 액션 속성과 동일한 역할.
|
||||
*/
|
||||
identity_target?: { email?: string; phone?: string };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -246,6 +253,71 @@ class ApiClient {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
// 428 본인인증 필요 처리 (IDV) — apiCall(handleApiCall, native fetch) 경로는
|
||||
// ActionDispatcher 가 IdentityGuardInterceptor 로 자동 인터셉트하지만, G7Core.api(axios)
|
||||
// 직접 호출 경로(입금확인/주문취소 등 모듈 JS 핸들러)는 이 인터셉터를 거치지 않아 모듈마다
|
||||
// 428 분기를 수동 추가해야 했고 누락 위험이 있었다(취소 핸들러 미노출 회귀). 여기서 중앙
|
||||
// 처리하면 axios 를 쓰는 모든 호출이 본인인증 모달 → verify → 원 요청 재실행을 자동 수행한다.
|
||||
if (IdentityGuardInterceptor.isIdentityRequired(error.response?.status, error.response?.data)) {
|
||||
this.completeDevToolsRequest(originalRequest, error);
|
||||
|
||||
// 원 요청 헤더(Authorization 포함)/body 를 재실행에 그대로 재사용 — 누락 시 백엔드가
|
||||
// 인증 실패(401) 또는 빈 body(422)로 응답할 수 있다.
|
||||
const replayHeaders: Record<string, string> = {};
|
||||
const rawHeaders = (originalRequest?.headers ?? {}) as Record<string, unknown>;
|
||||
for (const [k, v] of Object.entries(rawHeaders)) {
|
||||
if (typeof v === 'string') {
|
||||
replayHeaders[k] = v;
|
||||
}
|
||||
}
|
||||
let replayBody: BodyInit | undefined;
|
||||
if (originalRequest?.data !== undefined && originalRequest?.data !== null) {
|
||||
replayBody = typeof originalRequest.data === 'string'
|
||||
? originalRequest.data
|
||||
: JSON.stringify(originalRequest.data);
|
||||
replayHeaders['Content-Type'] = replayHeaders['Content-Type'] ?? 'application/json';
|
||||
}
|
||||
|
||||
// 호출자가 config.identity_target 으로 선언한 인증 대상(비로그인 흐름) 을 launcher 로 전달.
|
||||
const identityTarget = (originalRequest as AxiosConfigWithDevTools | undefined)
|
||||
?.identity_target;
|
||||
|
||||
const replayed = await IdentityGuardInterceptor.handle(
|
||||
error.response.data,
|
||||
{
|
||||
headers: replayHeaders,
|
||||
body: replayBody,
|
||||
credentials: 'same-origin',
|
||||
},
|
||||
identityTarget
|
||||
);
|
||||
|
||||
// 사용자 취소 / verify 실패 / return_request 없음 → 원 에러 그대로 전파
|
||||
if (!replayed) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
// 재실행 성공 → fetch Response 를 axios 응답 형태로 변환해 정상 흐름으로 반환.
|
||||
let replayData: any = null;
|
||||
try {
|
||||
replayData = await replayed.json();
|
||||
} catch {
|
||||
replayData = null;
|
||||
}
|
||||
if (!replayed.ok) {
|
||||
// 재실행이 또 실패하면 그 응답을 에러로 전파
|
||||
return Promise.reject(Object.assign(new Error('replay failed'), {
|
||||
response: { status: replayed.status, data: replayData },
|
||||
}));
|
||||
}
|
||||
|
||||
return {
|
||||
...error.response,
|
||||
status: replayed.status,
|
||||
data: replayData,
|
||||
} as AxiosResponse;
|
||||
}
|
||||
|
||||
// 403 Forbidden 처리 - onUnauthorized를 호출하지 않고 onError로 처리
|
||||
// 403은 "권한 없음"이므로 로그인 페이지로 리다이렉트하면 안됨
|
||||
if (error.response?.status === 403) {
|
||||
|
||||
@@ -5,11 +5,24 @@
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import ApiClient, { createApiClient, getApiClient } from '../ApiClient';
|
||||
import axios from 'axios';
|
||||
import { IdentityGuardInterceptor } from '../../identity/IdentityGuardInterceptor';
|
||||
|
||||
// Axios 모킹
|
||||
vi.mock('axios');
|
||||
const mockedAxios = axios as any;
|
||||
|
||||
// IdentityGuardInterceptor 모킹 (428 중앙 처리 검증용)
|
||||
vi.mock('../../identity/IdentityGuardInterceptor', () => ({
|
||||
IdentityGuardInterceptor: {
|
||||
isIdentityRequired: vi.fn(),
|
||||
handle: vi.fn(),
|
||||
},
|
||||
}));
|
||||
const mockedGuard = IdentityGuardInterceptor as unknown as {
|
||||
isIdentityRequired: ReturnType<typeof vi.fn>;
|
||||
handle: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
describe('ApiClient', () => {
|
||||
let apiClient: ApiClient;
|
||||
|
||||
@@ -165,4 +178,100 @@ describe('ApiClient', () => {
|
||||
expect(client1).toBe(client2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('428 본인인증 중앙 처리 (IDV)', () => {
|
||||
/**
|
||||
* response 인터셉터의 onRejected 콜백을 캡처해 직접 호출하기 위한 헬퍼.
|
||||
* axios.create 가 use(onFulfilled, onRejected) 로 받은 onRejected 를 보관한다.
|
||||
*/
|
||||
function buildClientCapturingRejected(): { onRejected: (e: any) => Promise<any> } {
|
||||
let captured: ((e: any) => Promise<any>) | null = null;
|
||||
mockedAxios.create.mockReturnValue({
|
||||
interceptors: {
|
||||
request: { use: vi.fn(() => 0) },
|
||||
response: {
|
||||
use: vi.fn((_onFulfilled: any, onRejected: any) => {
|
||||
captured = onRejected;
|
||||
return 0;
|
||||
}),
|
||||
},
|
||||
},
|
||||
get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn(), delete: vi.fn(),
|
||||
});
|
||||
new ApiClient();
|
||||
return { onRejected: captured! };
|
||||
}
|
||||
|
||||
const idv428Error = {
|
||||
config: { url: '/api/x', headers: { Authorization: 'Bearer t' }, data: JSON.stringify({ a: 1 }) },
|
||||
response: {
|
||||
status: 428,
|
||||
data: { error_code: 'identity_verification_required', verification: { return_request: { method: 'POST', url: '/api/x' } } },
|
||||
},
|
||||
};
|
||||
|
||||
it('428 응답을 IdentityGuardInterceptor 로 인터셉트하고 verify 성공 시 재실행 응답을 반환한다', async () => {
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(true);
|
||||
mockedGuard.handle.mockResolvedValue({
|
||||
ok: true, status: 200, json: async () => ({ success: true, data: { confirmed: true } }),
|
||||
} as any);
|
||||
|
||||
const { onRejected } = buildClientCapturingRejected();
|
||||
const result = await onRejected(idv428Error);
|
||||
|
||||
expect(mockedGuard.handle).toHaveBeenCalledOnce();
|
||||
expect(result.status).toBe(200);
|
||||
expect(result.data).toEqual({ success: true, data: { confirmed: true } });
|
||||
});
|
||||
|
||||
it('428 인데 사용자가 본인인증을 취소(handle=null)하면 원 에러를 그대로 전파한다', async () => {
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(true);
|
||||
mockedGuard.handle.mockResolvedValue(null);
|
||||
|
||||
const { onRejected } = buildClientCapturingRejected();
|
||||
await expect(onRejected(idv428Error)).rejects.toBe(idv428Error);
|
||||
});
|
||||
|
||||
it('428 이 아니면 IdentityGuard 를 호출하지 않고 일반 에러로 전파한다', async () => {
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(false);
|
||||
|
||||
const { onRejected } = buildClientCapturingRejected();
|
||||
const err422 = { config: { url: '/api/y' }, response: { status: 422, data: { message: 'invalid' } } };
|
||||
await expect(onRejected(err422)).rejects.toBe(err422);
|
||||
expect(mockedGuard.handle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/**
|
||||
* 신규(engine-v1.51.0) — axios(G7Core.api) 호출 경로도 config.identity_target 을 launcher 로 전달.
|
||||
* apiCall(handleApiCall, native fetch) 경로와 동일하게 모든 API 호출 방식에서 IDV target 지원.
|
||||
*/
|
||||
it('config.identity_target 을 IdentityGuardInterceptor.handle 의 target 인자로 전달한다', async () => {
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(true);
|
||||
mockedGuard.handle.mockResolvedValue({
|
||||
ok: true, status: 200, json: async () => ({ success: true }),
|
||||
} as any);
|
||||
|
||||
const errWithTarget = {
|
||||
config: {
|
||||
url: '/api/orders',
|
||||
headers: {},
|
||||
data: JSON.stringify({ a: 1 }),
|
||||
identity_target: { email: 'guest@example.com', phone: '01099998888' },
|
||||
},
|
||||
response: {
|
||||
status: 428,
|
||||
data: { error_code: 'identity_verification_required', verification: { return_request: { method: 'POST', url: '/api/orders' } } },
|
||||
},
|
||||
};
|
||||
|
||||
const { onRejected } = buildClientCapturingRejected();
|
||||
await onRejected(errWithTarget);
|
||||
|
||||
expect(mockedGuard.handle).toHaveBeenCalledWith(
|
||||
errWithTarget.response.data,
|
||||
expect.any(Object),
|
||||
{ email: 'guest@example.com', phone: '01099998888' },
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,7 @@ const logger = createLogger('IdentityGuardInterceptor');
|
||||
export type {
|
||||
IdentityResponse428,
|
||||
IdentityRedirectStash,
|
||||
IdentityVerificationTarget,
|
||||
ModalLauncher,
|
||||
VerificationPayload,
|
||||
VerificationResult,
|
||||
@@ -52,6 +53,23 @@ export class IdentityGuardInterceptor {
|
||||
| ((result: VerificationResult) => void)
|
||||
| null = null;
|
||||
|
||||
/**
|
||||
* challenge 레이어(모달/launcher)가 이번 IDV 사이클에서 자기 고유의 도메인 안내를
|
||||
* 사용자에게 이미 표출했음을 표시하는 1회성 플래그.
|
||||
*
|
||||
* 배경: 본인확인은 성공했으나 부가 목적(성인인증 등)을 충족하지 못해 challenge 가
|
||||
* 실패로 종료되면, provider 가 "성인 인증이 필요합니다" 같은 고유 사유를 토스트로 표출한다.
|
||||
* 그 직후 코어가 원 428 을 onError 로 흘려보내면 원 요청의 generic 가드 토스트
|
||||
* ("본인 확인이 필요합니다")가 중복으로 뜬다. 이 플래그가 set 되어 있으면 코어 toast 핸들러가
|
||||
* 동일 사이클의 generic IDV 가드 토스트 1건을 skip 한다.
|
||||
*
|
||||
* 일반 본인인증 실패(본인확인 자체 실패/취소)는 이 플래그를 set 하지 않으므로
|
||||
* generic 가드 토스트가 그대로 유지된다 — provider 무지식의 범용 신호다.
|
||||
*
|
||||
* @since engine-v1.52.2
|
||||
*/
|
||||
private static domainNoticeShown = false;
|
||||
|
||||
/**
|
||||
* 모달 launcher 를 등록합니다.
|
||||
*
|
||||
@@ -72,6 +90,34 @@ export class IdentityGuardInterceptor {
|
||||
return this.launcher !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* challenge 레이어가 자기 고유의 도메인 안내(성인인증 실패 등)를 사용자에게 표출했음을 표시한다.
|
||||
*
|
||||
* provider(예: 이니시스 플러그인)가 "본인확인은 성공했으나 부가 목적 미달" 실패를 사용자에게
|
||||
* 안내한 직후 호출한다. 코어 toast 핸들러가 동일 사이클의 generic IDV 가드 토스트를 1회 skip 한다.
|
||||
* 호출 시점은 항상 코어가 원 428 을 onError 로 흘려보내기 직전(resolveIdentityChallenge 통보 전)이어야 한다.
|
||||
*
|
||||
* @since engine-v1.52.2
|
||||
*/
|
||||
static markDomainNoticeShown(): void {
|
||||
this.domainNoticeShown = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 도메인 안내 표출 플래그를 읽고 즉시 소비(해제)한다.
|
||||
*
|
||||
* 코어 toast 핸들러가 generic IDV 가드 토스트를 띄우기 직전 1회 호출한다.
|
||||
* true 면 그 토스트를 skip 하고, 플래그는 소비되어 다음 토스트부터는 정상 표출된다.
|
||||
*
|
||||
* @returns 직전 challenge 가 도메인 안내를 표출했으면 true (그리고 플래그 해제)
|
||||
* @since engine-v1.52.2
|
||||
*/
|
||||
static consumeDomainNoticeShown(): boolean {
|
||||
const shown = this.domainNoticeShown;
|
||||
this.domainNoticeShown = false;
|
||||
return shown;
|
||||
}
|
||||
|
||||
/**
|
||||
* 외부 호출(주로 `resolveIdentityChallenge` 핸들러)이 사용하는 진입점.
|
||||
*
|
||||
@@ -134,20 +180,33 @@ export class IdentityGuardInterceptor {
|
||||
*
|
||||
* @param response 428 JSON 본문
|
||||
* @param originalRequest 원 요청 RequestInit (body, headers, credentials) — 미전달 시 빈 body 로 fallback
|
||||
* @param target 흐름이 선언한 인증 대상(이메일·전화) — apiCall `identity_target` 에서 평가된 값.
|
||||
* launcher 가 challenge 시작 시 사용한다. 비로그인 게스트 흐름의 핵심 (서버는 화면 입력값을 모름).
|
||||
* @returns 재실행 응답 또는 null (사용자 취소 / 실패 / return_request 없음)
|
||||
*/
|
||||
static async handle(
|
||||
response: IdentityResponse428,
|
||||
originalRequest?: Pick<RequestInit, 'body' | 'headers' | 'credentials'>,
|
||||
target?: { email?: string; phone?: string },
|
||||
): Promise<Response | null> {
|
||||
// 새 challenge 진입 — 이전 사이클의 미소비 도메인 안내 플래그를 정리한다.
|
||||
// (이전 사이클에서 onError 가드 토스트가 없어 consume 되지 않은 stale 플래그가
|
||||
// 이번 사이클의 가드 토스트를 잘못 skip 하는 것을 차단)
|
||||
this.domainNoticeShown = false;
|
||||
const launcher = this.launcher ?? defaultLauncher;
|
||||
const result = await launcher(response.verification);
|
||||
// 흐름이 선언한 target 을 payload 에 병합 — launcher 는 payload.target 한 곳에서 읽는다.
|
||||
// email/phone 둘 다 빈 값이면 병합하지 않음(로그인 사용자는 서버 세션 도출).
|
||||
const hasTarget = !!(target && (target.email || target.phone));
|
||||
const verification: VerificationPayload = hasTarget
|
||||
? { ...response.verification, target }
|
||||
: response.verification;
|
||||
const result = await launcher(verification);
|
||||
|
||||
if (result.status !== 'verified') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const returnReq = response.verification.return_request;
|
||||
const returnReq = verification.return_request;
|
||||
if (!returnReq) {
|
||||
return null;
|
||||
}
|
||||
@@ -221,6 +280,7 @@ export class IdentityGuardInterceptor {
|
||||
}
|
||||
}
|
||||
this.launcher = null;
|
||||
this.domainNoticeShown = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,29 @@
|
||||
* @since engine-v1.46.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* 본인인증(IDV) 대상 — 인증 코드/링크를 보낼 이메일·전화번호.
|
||||
*
|
||||
* 비로그인(게스트) 흐름에서 레이아웃의 apiCall `identity_target` 속성으로 선언되어
|
||||
* `IdentityGuardInterceptor.handle()` → launcher 로 전달된다. email / phone 둘 중 하나만
|
||||
* 있어도 충분하며(서버 `RequestChallengeRequest` 가 둘 다 허용), 로그인 사용자는 서버가
|
||||
* 세션에서 자동 도출하므로 비어 있을 수 있다.
|
||||
*
|
||||
* @since engine-v1.51.0
|
||||
*/
|
||||
export interface IdentityVerificationTarget {
|
||||
email?: string;
|
||||
phone?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 백엔드가 428 응답의 `verification` 필드로 내려보내는 페이로드.
|
||||
*
|
||||
* `scope=route`(미들웨어 강제)와 `scope=hook`(이벤트 강제) 모두 동일 형식이며,
|
||||
* `return_request` 만 hook 강제에서 null 일 수 있습니다.
|
||||
*
|
||||
* `target` 은 서버 응답에는 없고, `IdentityGuardInterceptor.handle()` 이 호출자(ActionDispatcher)가
|
||||
* apiCall `identity_target` 으로 선언한 인증 대상을 launcher 에 전달하기 위해 병합하는 런타임 필드입니다.
|
||||
*/
|
||||
export interface VerificationPayload {
|
||||
policy_key: string;
|
||||
@@ -25,6 +43,8 @@ export interface VerificationPayload {
|
||||
url: string;
|
||||
headers_echo?: string[];
|
||||
} | null;
|
||||
/** 흐름이 선언한 인증 대상(이메일·전화) — 인터셉터가 병합. 서버 응답에는 없음. */
|
||||
target?: IdentityVerificationTarget | null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"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": "템플릿 엔진을 초기화하는 중 오류가 발생했습니다"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import { TemplateApp, initTemplateApp } from './TemplateApp';
|
||||
import { createLogger } from './utils/Logger';
|
||||
import { webSocketManager } from './websocket/WebSocketManager';
|
||||
import { initializeG7CoreGlobals, initDevToolsAPI } from './template-engine/G7CoreGlobals';
|
||||
import { checkLayoutEditorMode } from './template-engine/layout-editor/hooks/useEditorMode';
|
||||
import { LayoutEditorChrome } from './template-engine/layout-editor/LayoutEditorChrome';
|
||||
|
||||
const logger = createLogger('TemplateEngine');
|
||||
|
||||
@@ -370,7 +372,6 @@ async function initTemplateEngine(options: InitOptions): Promise<void> {
|
||||
* 템플릿 렌더링
|
||||
*
|
||||
* 레이아웃 JSON을 기반으로 React 컴포넌트를 렌더링합니다.
|
||||
* 편집 모드(URL에 mode=edit 파라미터 존재)인 경우 WysiwygEditor로 래핑하여 렌더링합니다.
|
||||
*
|
||||
* @param options - 렌더링 옵션
|
||||
* @throws {Error} 초기화되지 않은 경우 또는 렌더링 실패 시
|
||||
@@ -420,14 +421,40 @@ async function renderTemplate(options: RenderOptions): Promise<void> {
|
||||
state.reactRoot = ReactDOM.createRoot(container);
|
||||
}
|
||||
|
||||
// 편집 모드 감지 (URL 쿼리 파라미터 확인)
|
||||
const isEditMode = checkEditMode();
|
||||
logger.log('편집 모드:', isEditMode);
|
||||
|
||||
// 편집 모드인 경우 WysiwygEditor로 렌더링
|
||||
if (isEditMode) {
|
||||
await renderWithWysiwygEditor(options);
|
||||
return;
|
||||
// 레이아웃 편집기 모드 분기
|
||||
// URL 이 `/admin/layout-editor/:identifier` 패턴이면 LayoutEditorChrome 을
|
||||
// 같은 state.reactRoot + 같은 코어 컨텍스트 래퍼 안에서 렌더한다.
|
||||
// 별도 createRoot / 별도 DOM 컨테이너 / 별도 컨텍스트 트리 일체 금지.
|
||||
if (typeof window !== 'undefined') {
|
||||
const editorMode = checkLayoutEditorMode(window.location.pathname);
|
||||
if (editorMode) {
|
||||
logger.log('레이아웃 편집기 모드 진입', editorMode);
|
||||
const chrome = React.createElement(LayoutEditorChrome, {
|
||||
templateIdentifier: editorMode.templateIdentifier,
|
||||
initialLocale: state.locale,
|
||||
});
|
||||
state.reactRoot.render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: state.translationEngine!,
|
||||
translationContext: state.translationContext,
|
||||
children: React.createElement(
|
||||
TransitionProvider,
|
||||
{
|
||||
children: React.createElement(
|
||||
ResponsiveProvider,
|
||||
{
|
||||
children: React.createElement(SlotProvider, { children: chrome }),
|
||||
}
|
||||
),
|
||||
}
|
||||
),
|
||||
} as any
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 레이아웃 JSON의 components 배열 가져오기
|
||||
@@ -596,13 +623,6 @@ function updateTemplateData(data: Record<string, any>, options?: UpdateOptions):
|
||||
try {
|
||||
logger.log('템플릿 데이터 업데이트 시작', Object.keys(data));
|
||||
|
||||
// 편집 모드일 때는 일반 렌더링 업데이트 건너뛰기
|
||||
// WysiwygEditor가 자체적으로 상태를 관리하므로 updateTemplateData가 간섭하면 안 됨
|
||||
if (checkEditMode()) {
|
||||
logger.log('편집 모드에서는 updateTemplateData를 건너뜁니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
// 초기화 확인
|
||||
if (!state.isInitialized) {
|
||||
throw new Error('템플릿 엔진이 초기화되지 않았습니다.');
|
||||
@@ -847,125 +867,6 @@ function getActionDispatcher(): ActionDispatcher | null {
|
||||
return state.actionDispatcher;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 위지윅 편집 모드 관련 함수
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* URL 쿼리 파라미터에서 편집 모드 여부를 확인합니다.
|
||||
*
|
||||
* @returns boolean 편집 모드 여부
|
||||
*/
|
||||
function checkEditMode(): boolean {
|
||||
if (typeof window === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const mode = params.get('mode');
|
||||
const template = params.get('template');
|
||||
|
||||
// mode=edit 파라미터와 template 파라미터가 모두 있어야 편집 모드
|
||||
return mode === 'edit' && !!template;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 쿼리 파라미터에서 템플릿 ID를 가져옵니다.
|
||||
*
|
||||
* @returns string | null 템플릿 ID
|
||||
*/
|
||||
function getTemplateIdFromUrl(): string | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
return params.get('template');
|
||||
}
|
||||
|
||||
/**
|
||||
* 위지윅 편집기로 렌더링합니다.
|
||||
* 편집 모드일 때 WysiwygEditor를 동적으로 import하여 렌더링합니다.
|
||||
*
|
||||
* @param options - 렌더링 옵션
|
||||
*/
|
||||
async function renderWithWysiwygEditor(options: RenderOptions): Promise<void> {
|
||||
logger.log('위지윅 편집기 렌더링 시작');
|
||||
|
||||
try {
|
||||
// WysiwygEditor 동적 import
|
||||
const { WysiwygEditor } = await import('./template-engine/wysiwyg');
|
||||
|
||||
// URL에서 템플릿 ID 추출
|
||||
const templateId = getTemplateIdFromUrl() || state.templateId || 'unknown';
|
||||
|
||||
// 편집 모드 닫기 핸들러 (mode 파라미터 제거)
|
||||
const handleClose = () => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.delete('mode');
|
||||
params.delete('template');
|
||||
|
||||
const newUrl = `${window.location.pathname}${params.toString() ? '?' + params.toString() : ''}`;
|
||||
window.location.href = newUrl;
|
||||
};
|
||||
|
||||
// 저장 완료 핸들러
|
||||
const handleSaveComplete = (layoutData: any) => {
|
||||
logger.log('레이아웃 저장 완료:', layoutData);
|
||||
// TODO: API 호출로 레이아웃 저장
|
||||
};
|
||||
|
||||
logger.log('WysiwygEditor 렌더링', { templateId, layoutName: options.layoutJson?.layout_name });
|
||||
|
||||
// WysiwygEditor 렌더링
|
||||
state.reactRoot!.render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: state.translationEngine!,
|
||||
translationContext: state.translationContext,
|
||||
},
|
||||
React.createElement(WysiwygEditor, {
|
||||
layoutData: options.layoutJson,
|
||||
templateId,
|
||||
onClose: handleClose,
|
||||
onSaveComplete: handleSaveComplete,
|
||||
initialEditMode: 'visual',
|
||||
readOnly: false,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
logger.log('위지윅 편집기 렌더링 완료');
|
||||
} catch (error) {
|
||||
logger.error('위지윅 편집기 로드 실패:', error);
|
||||
|
||||
// 편집기 로드 실패 시 에러 메시지 표시
|
||||
state.reactRoot!.render(
|
||||
React.createElement('div', {
|
||||
className: 'flex items-center justify-center h-screen bg-gray-100 dark:bg-gray-900',
|
||||
},
|
||||
React.createElement('div', {
|
||||
className: 'text-center p-8 bg-white dark:bg-gray-800 rounded-lg shadow-lg',
|
||||
},
|
||||
React.createElement('h1', {
|
||||
className: 'text-xl font-bold text-red-600 dark:text-red-400 mb-4',
|
||||
}, '위지윅 편집기 로드 실패'),
|
||||
React.createElement('p', {
|
||||
className: 'text-gray-600 dark:text-gray-400 mb-4',
|
||||
}, '편집기를 불러오는 중 오류가 발생했습니다.'),
|
||||
React.createElement('button', {
|
||||
className: 'px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700',
|
||||
onClick: () => window.location.reload(),
|
||||
}, '새로고침')
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 엔진 공개 API
|
||||
*/
|
||||
|
||||
@@ -201,6 +201,34 @@ export interface ActionDefinition {
|
||||
* - 'optional': 토큰이 있으면 포함, 없으면 미포함
|
||||
*/
|
||||
auth_mode?: 'none' | 'required' | 'optional';
|
||||
/**
|
||||
* 본인인증(IDV) 대상 — apiCall 핸들러 전용 선언적 메타 속성.
|
||||
*
|
||||
* 이 apiCall 이 HTTP 428(identity_verification_required)을 받으면, IdentityGuardInterceptor 가
|
||||
* 인증 challenge 를 시작할 때 사용할 인증 대상(이메일·전화번호)을 흐름이 직접 선언한다.
|
||||
* 비로그인(게스트) 흐름에서 서버는 사용자가 방금 화면에 입력한 값을 알 수 없으므로,
|
||||
* 레이아웃이 이 속성에 표현식으로 대상을 명시하면 launcher 가 흐름 무지식으로 그 값을 받는다.
|
||||
* 로그인 사용자는 서버가 세션에서 자동 도출하므로 빈 값이어도 무방하다.
|
||||
*
|
||||
* email / phone 둘 중 하나만 있어도 충분하며, 우선순위는 표현식 자체가 결정한다
|
||||
* (예: 주문자 정보 우선 → 수취인 정보 폴백).
|
||||
*
|
||||
* @example
|
||||
* ```json
|
||||
* {
|
||||
* "handler": "apiCall",
|
||||
* "target": "/api/.../orders",
|
||||
* "identity_target": {
|
||||
* "email": "{{_local.orderer?.email || ''}}",
|
||||
* "phone": "{{_local.orderer?.phone || _local.shipping?.recipient_phone || ''}}"
|
||||
* },
|
||||
* "params": { "method": "POST", "body": { } }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
identity_target?: { email?: string; phone?: string };
|
||||
/** 조건부 실행 - 표현식이 true일 때만 액션 실행 */
|
||||
if?: string;
|
||||
/**
|
||||
@@ -1666,18 +1694,34 @@ export class ActionDispatcher {
|
||||
|
||||
// 결과를 _local._eventResult에 저장하여 후속 액션에서 접근 가능하게 함
|
||||
if (this.globalStateUpdater) {
|
||||
const currentState = G7Core?.state?.get() || {};
|
||||
const currentGlobalLocal = (G7Core?.state?.get() || {})._local || {};
|
||||
const eventResult = {
|
||||
event: eventName,
|
||||
success: true,
|
||||
data: results.length === 1 ? results[0] : results,
|
||||
listeners: results.length,
|
||||
};
|
||||
// 글로벌 _local 갱신 (기존 동작 유지: 글로벌 _local 기준 머지)
|
||||
this.globalStateUpdater({
|
||||
_local: {
|
||||
...currentState._local,
|
||||
_eventResult: {
|
||||
event: eventName,
|
||||
success: true,
|
||||
data: results.length === 1 ? results[0] : results,
|
||||
listeners: results.length,
|
||||
},
|
||||
},
|
||||
_local: { ...currentGlobalLocal, _eventResult: eventResult },
|
||||
});
|
||||
|
||||
// engine-v1.50.0: sequence 내 emitEvent 결과를 후속 액션이 참조할 수 있도록
|
||||
// __g7SequenceLocalSync 에 병합 스냅샷을 실는다.
|
||||
// 배경: handleSequence 의 currentState 는 setState 핸들러와 setLocal() 이 설정한
|
||||
// __g7SequenceLocalSync 로만 갱신된다(트러블슈팅 사례 24). emitEvent 는 globalStateUpdater
|
||||
// 로만 _local 을 갱신했기에 같은 sequence 의 다음 액션(apiCall body / setState)이
|
||||
// _eventResult 와 리스너가 갱신한 _local(예: form.images)을 보지 못했다.
|
||||
// (FileUploader onUploadComplete 가 업로드 직후 form.images 를 갱신해도 저장 PUT body 의
|
||||
// _local.form 스냅샷에 미반영 → 백엔드 syncImages 가 방금 올린 이미지를 삭제하는 회귀.)
|
||||
//
|
||||
// base 는 시퀀스가 추적 중인 _local(context.state) 우선 — sequence 내 in-flight
|
||||
// setState 변경(예: isSaving)을 보존한다. 시퀀스 밖(standalone emitEvent)에서는
|
||||
// context.state 가 없거나 부분적일 수 있어 글로벌 _local 로 폴백한다.
|
||||
const syncBase = (context.state && typeof context.state === 'object' && !Array.isArray(context.state))
|
||||
? context.state
|
||||
: currentGlobalLocal;
|
||||
(window as any).__g7SequenceLocalSync = { ...syncBase, _eventResult: eventResult };
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`emitEvent: Event "${eventName}" failed`, error);
|
||||
@@ -2122,6 +2166,19 @@ export class ActionDispatcher {
|
||||
// actionRef 해석 - named_actions 참조를 실제 액션 정의로 변환
|
||||
action = this.resolveActionRef(action);
|
||||
|
||||
// 동적 핸들러 이름 해석 — handler 가 `{{...}}` 바인딩이면 컨텍스트로 먼저 해석한다.
|
||||
// 백엔드 응답이 호출할 핸들러 풀네임을 내려주는 provider-agnostic 디스패치
|
||||
// (예: 결제 진입 `handler: "{{response.data.pg_payment_handler}}"`)를 지원한다.
|
||||
// 빌트인 26종은 camelCase 리터럴이라 `{{` 미포함 → 해석 분기 미진입(무영향).
|
||||
// resolveActionRef 직후·프리뷰 억제 체크·switch 보다 앞에 두어 (1) 빌트인 라우팅이
|
||||
// 해석된 이름으로 매칭되고 (2) PREVIEW_SUPPRESSED_HANDLERS 판정도 해석된 이름으로
|
||||
// 이뤄지게 한다(편집기 프리뷰 정합). nested(conditions/sequence)도 동일 executeAction
|
||||
// 경유라 자동 적용. @since engine-v1.50.0
|
||||
if (typeof action.handler === 'string' && action.handler.includes('{{')) {
|
||||
const resolvedHandler = this.evaluateExpression(action.handler, context.data);
|
||||
action = { ...action, handler: resolvedHandler == null ? '' : String(resolvedHandler) };
|
||||
}
|
||||
|
||||
// DevTools 액션 로깅 시작
|
||||
const devTools = getDevTools();
|
||||
const devToolsActionId = devTools?.isEnabled() ? `action_${Date.now()}_${Math.random().toString(36).substring(2, 11)}` : undefined;
|
||||
@@ -2299,11 +2356,19 @@ export class ActionDispatcher {
|
||||
|
||||
// auth_mode 우선, auth_required는 하위 호환
|
||||
const authMode = action.auth_mode ?? (action.auth_required ? 'required' : 'none');
|
||||
// identity_target: IDV 428 인터셉트 시 사용할 인증 대상(이메일·전화). 표현식 평가 후 전달.
|
||||
const resolvedIdentityTarget = action.identity_target
|
||||
? (this.resolveParams(action.identity_target, context.data) as {
|
||||
email?: string;
|
||||
phone?: string;
|
||||
})
|
||||
: undefined;
|
||||
result = await this.handleApiCall(
|
||||
resolvedTarget!,
|
||||
resolvedParams,
|
||||
context,
|
||||
authMode
|
||||
authMode,
|
||||
resolvedIdentityTarget
|
||||
);
|
||||
break;
|
||||
|
||||
@@ -2539,6 +2604,9 @@ export class ActionDispatcher {
|
||||
errors: responseData.errors || apiResponse.errors,
|
||||
data: responseData,
|
||||
statusText: (actionError.originalError as any)?.statusText,
|
||||
// API 응답의 error_code (예: 428 'identity_verification_required') 를 노출 —
|
||||
// 코어 toast 핸들러가 IDV 가드 토스트를 코드로 식별해 중복 억제하는 데 사용.
|
||||
error_code: responseData.error_code ?? apiResponse.error_code,
|
||||
};
|
||||
|
||||
// 에러 핸들링 우선순위:
|
||||
@@ -2814,11 +2882,15 @@ export class ActionDispatcher {
|
||||
finalPath: string,
|
||||
_originalParams: Record<string, any>
|
||||
): { handler: string; params: Record<string, any> } {
|
||||
// 기본값: openWindow
|
||||
// 기본값: openWindow with target '_self' — 같은 탭에서 이동.
|
||||
// 이전 기본값(`'_blank'`)은 admin↔user 교차 이동 시 새 탭이 열려 사용자 흐름이
|
||||
// 끊기는 결함을 유발. 명시적으로 새 탭이
|
||||
// 필요한 호출처는 `params.fallback: { handler: 'openWindow', params: { target: '_blank' } }`
|
||||
// 로 지정.
|
||||
if (fallbackOption == null) {
|
||||
return {
|
||||
handler: 'openWindow',
|
||||
params: { path: finalPath, target: '_blank' },
|
||||
params: { path: finalPath, target: '_self' },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3079,10 +3151,17 @@ export class ActionDispatcher {
|
||||
/**
|
||||
* openWindow 액션을 처리합니다.
|
||||
*
|
||||
* 새 브라우저 창(탭)으로 지정된 경로를 엽니다.
|
||||
* 지정된 경로로 이동합니다. `params.target` 으로 창 동작을 제어:
|
||||
* - `'_blank'`(기본): 새 탭/창 열기 (`window.open(path, '_blank')`)
|
||||
* - `'_self'`: 같은 탭에서 이동 (`window.location.assign(path)`)
|
||||
*
|
||||
* @param target 열 경로
|
||||
* @param params 파라미터 (query 등)
|
||||
* navigate fallback 으로 호출되는 경우(현재 템플릿 라우트에 없는 경로 →
|
||||
* openWindow) 기본값이 `_blank` 라 의도치 않게 새 탭이 열리는 결함이 있다.
|
||||
* fallback 호출 측에서 `params.target: '_self'` 를 명시하거나, 사용자 액션
|
||||
* 정의에서 같은 탭 이동을 원하면 `target: '_self'` 명시.
|
||||
*
|
||||
* @param target 열 경로 (action target)
|
||||
* @param params 파라미터 (query, target 등)
|
||||
*/
|
||||
private async handleOpenWindow(
|
||||
target: string,
|
||||
@@ -3104,9 +3183,14 @@ export class ActionDispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
logger.log('handleOpenWindow:', { target, params, finalPath });
|
||||
const windowTarget = params.target === '_self' ? '_self' : '_blank';
|
||||
logger.log('handleOpenWindow:', { target, params, finalPath, windowTarget });
|
||||
|
||||
window.open(finalPath, '_blank');
|
||||
if (windowTarget === '_self') {
|
||||
window.location.assign(finalPath);
|
||||
} else {
|
||||
window.open(finalPath, '_blank');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3297,24 +3381,34 @@ export class ActionDispatcher {
|
||||
* 현 버전은 POST /api/identity/challenges 로 즉시 challenge 를 시작하고,
|
||||
* IdentityGuardInterceptor.handle 과 동일한 launcher 플로우를 재사용합니다.
|
||||
*
|
||||
* @param params 액션 파라미터 (purpose 필수)
|
||||
* @param params 액션 파라미터 (purpose 필수, target 선택 — 비로그인 흐름의 인증 대상)
|
||||
* @returns 사용자가 verify 에 성공하면 true, 취소 시 false
|
||||
*/
|
||||
private async handleEnsureIdentityVerified(params: Record<string, any>): Promise<boolean> {
|
||||
const purpose = typeof params.purpose === 'string' ? params.purpose : 'sensitive_action';
|
||||
|
||||
const verified = await IdentityGuardInterceptor.handle({
|
||||
success: false,
|
||||
error_code: 'identity_verification_required',
|
||||
message: '',
|
||||
verification: {
|
||||
policy_key: (params.policy_key as string) ?? '',
|
||||
purpose,
|
||||
provider_id: (params.provider_id as string) ?? null,
|
||||
render_hint: (params.render_hint as string) ?? null,
|
||||
return_request: null, // pre-emptive 호출은 재실행할 원 요청 없음
|
||||
// params.target: 선제 가드 호출에서 흐름이 직접 인증 대상을 선언 (apiCall 의 identity_target 과 동일 채널).
|
||||
const target =
|
||||
params.target && typeof params.target === 'object'
|
||||
? (params.target as { email?: string; phone?: string })
|
||||
: undefined;
|
||||
|
||||
const verified = await IdentityGuardInterceptor.handle(
|
||||
{
|
||||
success: false,
|
||||
error_code: 'identity_verification_required',
|
||||
message: '',
|
||||
verification: {
|
||||
policy_key: (params.policy_key as string) ?? '',
|
||||
purpose,
|
||||
provider_id: (params.provider_id as string) ?? null,
|
||||
render_hint: (params.render_hint as string) ?? null,
|
||||
return_request: null, // pre-emptive 호출은 재실행할 원 요청 없음
|
||||
},
|
||||
},
|
||||
});
|
||||
undefined,
|
||||
target
|
||||
);
|
||||
|
||||
return verified !== null;
|
||||
}
|
||||
@@ -3408,12 +3502,14 @@ export class ActionDispatcher {
|
||||
* @param params 요청 파라미터
|
||||
* @param context 액션 컨텍스트
|
||||
* @param authMode 인증 모드 ('none' | 'required' | 'optional')
|
||||
* @param identityTarget IDV 428 인터셉트 시 challenge 에 사용할 인증 대상 (이메일·전화)
|
||||
*/
|
||||
private async handleApiCall(
|
||||
target: string,
|
||||
params: Record<string, any>,
|
||||
_context: ActionContext,
|
||||
authMode: 'none' | 'required' | 'optional' = 'none'
|
||||
authMode: 'none' | 'required' | 'optional' = 'none',
|
||||
identityTarget?: { email?: string; phone?: string }
|
||||
): Promise<any> {
|
||||
const { method = 'GET', body, headers, contentType } = params;
|
||||
|
||||
@@ -3532,11 +3628,15 @@ export class ActionDispatcher {
|
||||
if (IdentityGuardInterceptor.isIdentityRequired(response.status, responseData)) {
|
||||
// retry fetch 가 원 요청의 body/headers/credentials 를 그대로 재사용해야 백엔드가
|
||||
// 빈 body 로 422 를 던지지 않음 (회원가입 등 모든 POST 흐름의 핵심 회귀 방지)
|
||||
const replayed = await IdentityGuardInterceptor.handle(responseData, {
|
||||
body: options.body,
|
||||
headers: options.headers,
|
||||
credentials: options.credentials,
|
||||
});
|
||||
const replayed = await IdentityGuardInterceptor.handle(
|
||||
responseData,
|
||||
{
|
||||
body: options.body,
|
||||
headers: options.headers,
|
||||
credentials: options.credentials,
|
||||
},
|
||||
identityTarget
|
||||
);
|
||||
if (replayed) {
|
||||
response = replayed;
|
||||
try {
|
||||
@@ -3899,6 +3999,39 @@ export class ActionDispatcher {
|
||||
(window as any).__g7PendingLocalState = pendingExpected;
|
||||
logger.log('[handleSetState] __g7PendingLocalState updated:', pendingExpected);
|
||||
|
||||
// engine-v1.50.0: 컴포넌트 setState(target:"_local")를 canonical source(_global._local)에도 동기화.
|
||||
//
|
||||
// 배경: 이 COMPONENT path 는 context.setState(저장소 A: React localDynamicState)만 갱신하고
|
||||
// _global._local(저장소 B)은 갱신하지 않았다. Form 자동바인딩은 이미 양쪽을 동기화하지만
|
||||
// (DynamicRenderer.performStateUpdate → setLocal render:false), 명시적 setState target:"_local"
|
||||
// (필터 라디오/체크박스 등)은 B를 갱신하지 않아 비대칭이 있었다. 그 결과:
|
||||
// - 사용자가 필터 선택 → A만 갱신, B 는 init_actions 기본값 잔존
|
||||
// - 검색(navigate replace:true) → updateQueryParams refetch → updateTemplateData 가
|
||||
// currentDataContext._local 을 stale B(_global._local)로 되돌림 → 선택한 필터가 풀림
|
||||
// - 새로고침은 handleRouteChange 가 query 기반으로 B 를 재구성하므로 정상
|
||||
// GLOBAL STATE UPDATER path(아래 else if)는 이미 globalStateUpdater 로 B 를 갱신하므로,
|
||||
// COMPONENT path 도 동일하게 맞춰 일관성을 확보한다.
|
||||
//
|
||||
// render: false 로 호출하여 추가 React 렌더를 유발하지 않는다 (값만 저장, setGlobalState 라인 ~3211).
|
||||
// context.setState 가 이미 저장소 A 렌더 1회를 트리거하므로 클릭당 렌더 횟수는 변하지 않는다.
|
||||
// scope: 'parent' | 'root' 및 isolated 타깃은 이 분기(scope:'current', isRealComponentContext)에
|
||||
// 도달하기 전에 별도 처리되므로 모달 컨텍스트 오염(트러블슈팅 사례 29)에 영향이 없다.
|
||||
//
|
||||
// [안전성 의존 관계 — 엔진 수정 시 함께 검토할 것]
|
||||
// pendingExpected 의 base 는 currentState = (__g7PendingLocalState ?? context.state) 다.
|
||||
// 이 동기화는 B(_global._local)를 patch 머지가 아니라 통째 교체한다(setGlobalState 가 _local 키를 얕은 병합).
|
||||
// setLocal(G7CoreGlobals)이 fresh globalLocal 을 baseline 으로 addMissingLeafKeys 보호를 쓰는 것과 달리,
|
||||
// 여기서는 그 보호가 없으므로 currentState 가 정합한 _local 전체여야 손실이 없다.
|
||||
// 이 정합성은 DynamicRenderer 의 _localInit pending 사전설정 useLayoutEffect(engine-v1.27.0/v1.49.2)에 의존한다:
|
||||
// context.state(=extendedDataContext._local)가 stale dynamicState overlay 로 오염될 수 있는 구간
|
||||
// (_localInit 미반영 시점)에 __g7PendingLocalState 를 fresh B baseline 으로 미리 채워두므로,
|
||||
// currentState 가 pending(정상)을 우선 사용하여 stale context.state 를 건너뛴다.
|
||||
// 그 사전설정 경로를 변경/제거하면 사례 13/22(stale 배열의 globalLocal 통째 교체 오염) 재발 가능성을 함께 점검해야 한다.
|
||||
if (this.globalStateUpdater) {
|
||||
this.globalStateUpdater({ _local: pendingExpected }, { render: false });
|
||||
logger.log('[handleSetState] _global._local synced (render:false):', pendingExpected);
|
||||
}
|
||||
|
||||
// engine-v1.17.5: dataKey 자동 바인딩이 있는 컴포넌트에서 setState 핸들러 호출 시
|
||||
// dynamicState(Form 자동 바인딩)가 stale 값을 가질 수 있음
|
||||
// extendedDataContext 병합 순서: dataContext._local → dynamicState → __g7ForcedLocalFields
|
||||
@@ -4690,6 +4823,26 @@ export class ActionDispatcher {
|
||||
): Promise<void> {
|
||||
const { type = 'info', message, icon, duration } = params;
|
||||
|
||||
// [IDV 가드 토스트 중복 억제]
|
||||
// 본인확인은 성공했으나 부가 목적(성인인증 등)을 충족하지 못해 challenge 가 실패로 끝나면,
|
||||
// provider 가 "성인 인증이 필요합니다" 같은 고유 사유를 이미 토스트로 표출한다. 그 직후
|
||||
// 원 요청의 onError 가 generic IDV 가드 토스트("본인 확인이 필요합니다")를 중복 발화하는데,
|
||||
// 이 토스트가 (1) error 타입이고 (2) 원인이 IDV 가드 응답(error_code) 이며
|
||||
// (3) provider 가 도메인 안내 표출 신호를 남긴 경우 1회 skip 한다.
|
||||
// 일반 본인인증 실패(본인확인 자체 실패/취소)는 신호가 없어 그대로 표출된다.
|
||||
if (type === 'error') {
|
||||
const errorCtx = (context.data as Record<string, any> | undefined)?.error as
|
||||
| { error_code?: string; data?: { error_code?: string } }
|
||||
| undefined;
|
||||
const isIdentityGuardError =
|
||||
errorCtx?.error_code === 'identity_verification_required' ||
|
||||
errorCtx?.data?.error_code === 'identity_verification_required';
|
||||
if (isIdentityGuardError && IdentityGuardInterceptor.consumeDomainNoticeShown()) {
|
||||
logger.log('[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let resolvedMessage = message;
|
||||
|
||||
// $t: 다국어 구문 처리
|
||||
@@ -5774,6 +5927,20 @@ export class ActionDispatcher {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* IME(한글/일본어/중국어) 조합 중인 keydown 인지 판정합니다.
|
||||
*
|
||||
* 조합 중 Enter 등은 액션 키 필터 매칭에서 제외해야 글자누락/이중제출이 방지됩니다.
|
||||
* isComposing 미지원/false 환경을 위해 legacy keyCode 229 도 함께 검사합니다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
* @param e 판정할 키보드 이벤트
|
||||
* @returns 조합 중이면 true
|
||||
*/
|
||||
private isImeComposing(e: { isComposing?: boolean; keyCode?: number }): boolean {
|
||||
return e?.isComposing === true || e?.keyCode === 229;
|
||||
}
|
||||
|
||||
/**
|
||||
* 임베드용 레이어(오버레이) 요소를 생성합니다.
|
||||
*
|
||||
@@ -5855,6 +6022,8 @@ export class ActionDispatcher {
|
||||
|
||||
// ESC 키로 닫기
|
||||
const handleKeydown = (e: KeyboardEvent) => {
|
||||
// IME 조합 중 ESC keydown 제외 — 공개#54 일관성
|
||||
if (this.isImeComposing(e)) return;
|
||||
if (e.key === 'Escape') {
|
||||
closeLayer();
|
||||
document.removeEventListener('keydown', handleKeydown);
|
||||
@@ -6009,6 +6178,20 @@ export class ActionDispatcher {
|
||||
const handler = this.customHandlers.get(action.handler);
|
||||
|
||||
if (!handler) {
|
||||
// 프리뷰 모드에서는 미등록 핸들러를 throw 하지 않고 silent skip.
|
||||
// 편집기 캔버스에는 ckeditor5 등 플러그인 핸들러가 등록되지 않은 격리
|
||||
// ActionDispatcher 인스턴스가 사용되므로, lifecycle onMount 단계에서
|
||||
// 미등록 핸들러가 호출되면 errorHandling.onError → setState(500) →
|
||||
// ErrorBoundary 트리거 → 캔버스 unmount 로 이어진다. 프리뷰 모드에서는
|
||||
// 외부 효과를 건너뛰는 것이 의도된 동작이므로 warn 후 undefined 반환.
|
||||
// @since engine-v1.50.0
|
||||
if (this.previewMode) {
|
||||
logger.warn(
|
||||
`[Preview] Unknown action handler "${action.handler}" — skipped (preview mode)`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
throw new ActionError(
|
||||
`Unknown action handler: ${action.handler}`,
|
||||
action
|
||||
@@ -6433,6 +6616,23 @@ export class ActionDispatcher {
|
||||
return Array.from(this.customHandlers.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 이름의 커스텀 핸들러 함수를 반환합니다 (격리 dispatcher 복제용).
|
||||
*
|
||||
* 편집기 캔버스의 격리 dispatcher 가 호스트의 활성 플러그인 핸들러(예:
|
||||
* `sirsoft-ckeditor5.initEditor`)를 복제 등록해 위지윅 에디터 등 플러그인
|
||||
* 제공 UI 가 캔버스에 정상 마운트되도록 한다. 핸들러 함수 자체는 호스트와
|
||||
* 동일하지만 격리 dispatcher 의 컨텍스트(격리 store/dispatcher)에서 실행되므로
|
||||
* 호스트 globalState 누수가 없다.
|
||||
*
|
||||
* @param name 핸들러 이름
|
||||
* @returns 등록된 핸들러 함수 또는 undefined (미등록)
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
getHandler(name: string): ActionHandler | undefined {
|
||||
return this.customHandlers.get(name);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Debounce 유틸리티 메서드
|
||||
// ============================================================================
|
||||
@@ -6845,6 +7045,11 @@ export class ActionDispatcher {
|
||||
|
||||
// 키보드 이벤트에서 key 필터링
|
||||
if (isStandardEvent && action.key && 'key' in firstArg) {
|
||||
// IME 조합 중 keydown 은 매칭에서 제외 (글자누락/이중제출 방지) — 공개#54
|
||||
if (this.isImeComposing(firstArg as { isComposing?: boolean; keyCode?: number })) {
|
||||
logger.log('Key filter skipped (IME composing):', action.key);
|
||||
continue;
|
||||
}
|
||||
if (firstArg.key !== action.key) {
|
||||
logger.log('Key filter not matched:', action.key, 'actual:', firstArg.key);
|
||||
continue; // 키가 일치하지 않으면 이 액션 건너뛰기
|
||||
|
||||
@@ -5,6 +5,169 @@
|
||||
>
|
||||
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
|
||||
|
||||
## [engine-v1.50.0] - 2026-06-29
|
||||
|
||||
### Added
|
||||
|
||||
#### 위지윅 레이아웃 편집기 — 인프라 / 진입
|
||||
|
||||
- `/admin/layout-editor/{identifier}` URL 분기 신설 — `template-engine.ts` `renderTemplate()` 가 코어 컨텍스트 래퍼(Translation/Transition/Responsive/Slot) 안에 `LayoutEditorChrome` 셸을 렌더한다. `LayoutEditorContext`(useReducer 도메인 상태) + `EditorToolbar` + `RouteTreePanel`(5그룹: 공통 레이아웃/템플릿/모듈/플러그인/모달, `source` 메타 기반) + `EditEntryFab`(운영 화면 좌측 하단 편집 진입) 구성.
|
||||
- 진입 경로 — 템플릿 관리 화면에 `[코드 편집]`+`[레이아웃 편집]` 2버튼, 운영 화면 FAB(편집 권한자 한정, `?route={path}` 로 보던 화면 선택 진입), `window.G7Config.activeModules`/`activePlugins` 메타 키 신설.
|
||||
- 비활성 템플릿 admin 자산 서빙 — `AdminTemplateAssetController`(getEditorAssets/serveComponents/serveRoutes/serveEditorSpec/serveLanguage) + `core.templates.layouts.edit` 가드 + 활성→`_bundled` 폴백. 비활성 템플릿도 편집/저장 가능.
|
||||
- 편집기 셸 다국어 — `$t:layout_editor.*`(chrome/palette/insertion/overlay/save/preview/device/zoom/access_error 등) ko/en partial + g7-core-ja 번들 동기.
|
||||
- URL ↔ selectedRoute 양방향 동기화(`buildEditorUrl`/`useEditorUrlSync`, popstate 복원), 좌측 패널 접힘 영속화(`localStorage`), 라우트 트리 검색 + 키워드 `<mark>` 강조(다국어 표시 라벨·path 양쪽 매칭).
|
||||
|
||||
#### 프리뷰 캔버스 / 샘플 데이터 / 격리 store
|
||||
|
||||
- `PreviewCanvas` — 백엔드 병합 응답(`with_source_meta=1`)을 `DynamicRenderer` 로 실제 렌더하고, 데이터소스는 네트워크 fetch 없이 `sampleDataProvider`(5단계 우선순위: spec_byId→spec_byEndpoint→core_preset→fallback→inferred, 6종 코어 프리셋)로 채운다. `__source` 출처 네임스페이스로 같은 data_source id 의 확장별 shape 충돌을 해소.
|
||||
- 캔버스↔호스트 격리 store façade(`installPreviewCanvasStore`) — 마운트 동안 `window.__templateApp`/`G7Core.dispatch`/`modal`/`toast` 를 in-memory 격리 인스턴스로 swap, 언마운트 시 복원. `ComponentRegistry.createIsolatedInstance()` + `ActionDispatcher.getHandler()` public 노출로 호스트 싱글톤과 충돌 회피. 라우트 `:param` 토큰은 `deriveSampleRouteParams` 휴리스틱으로 자동 주입.
|
||||
- 출처 메타 옵션 — `LayoutService::getLayout/loadAndMergeLayout` `withSourceMeta` 로 각 노드에 `__source:{kind:base|route|extension,...}` 부여, 편집 응답에만 자식 `lock_version` + `__editor.original`(저장 SSoT) 동봉. 일반 렌더는 응답 100% 동일. `DynamicRenderer` 가 `__` 접두 메타 키를 DOM 전달 직전 일괄 차단.
|
||||
- 반응형 디바이스 미리보기 — 데스크톱/태블릿/모바일 토글 + 줌 슬라이더 + `custom` 폭 입력(320~1920px 클램프). 디바이스 폭이 캔버스보다 넓으면 `transform:scale()` 시각 축소.
|
||||
|
||||
#### 요소 추가 / 드래그앤드롭 / undo·redo
|
||||
|
||||
- 요소 추가 팔레트(`ComponentPalette`) — 카테고리 사이드바 + 검색(영문명·태그·다국어 표시 라벨 매칭) + 그리드 카드. `editorSpec.componentPalette.groups`(템플릿 소유) 정의대로 카테고리 렌더, 미제공 시 components.json type 폴백. `nesting.accepts` 로 부모가 받을 수 있는 컴포넌트만 노출. 신규 노드 골격은 `entries[name].defaultNode`(템플릿 SSoT, 두 번들 템플릿 전수 작성) 우선·`props.default` 폴백, 미정의 시 클릭 비활성 + 배지. audit `editor-spec-i18n-strings`(평문 차단) coverage 등록.
|
||||
- 삽입 어포던스(`InsertionAffordances`/`useInsertionPoints`) — 선택 요소 외곽 4방향 + 버튼, 부모 computed display/flex/grid 로 활성 방향 결정. 잠긴 영역(확장 조각/공통 레이아웃/partial/데이터 반복)에서도 형제 삽입 anchor 기준으로 + 버튼을 노출(잠긴 노드 자체는 무변형).
|
||||
- 드래그앤드롭 재배치(dnd-kit `PointerSensor`, `pointerWithin`) — 명시적 드롭 슬롯 방식(`buildDropSlots`, slot id 에 컨테이너 path+인덱스 인코딩 → 기하 추론 0). gap/nest 슬롯, 조상 체인 + 형제 컨테이너로 레벨 한정, `display:contents` 래퍼 시각 흐름 투명화, `DragOverlay` 고스트는 `cloneNode`+portal(scale 좌표 왜곡 회피). 컨테이너 밖으로 빼낸 요소를 다른/원래/깊은 컨테이너로 재이동, 선택 기준 드래그(자식 영역에서 시작해도 선택 부모 이동), `nestingRules`(canDrop/isDraggableNode/isContainerComponent, 폴백 없음).
|
||||
- undo/redo(`useEditorHistory`) — 추가/삭제/이동/속성/인라인 텍스트 5종 push, Ctrl+Z / Ctrl+Shift+Z·Ctrl+Y(⌘ 동등), input 포커스 중 미가로채기, 툴바 ↶/↷ 동기. 다른 레이아웃으로 붙여넣기(`editorClipboard`, sessionStorage 직렬화).
|
||||
- 단축키 보강 + 단축키 맵 모달 — 중앙 키맵 SSoT(`editorShortcuts.ts`) + 전역 디스패처(`useEditorShortcuts`, 입력칸/모달 포커스 가드), 복사·잘라내기·붙여넣기·속성·삭제·부모 선택·선택 해제·요소 추가·코드 편집·미리보기·다국어·저장·나가기·초기화 등 전수 결선. `ShortcutHelpModal` 플랫폼별 표기.
|
||||
|
||||
#### 선택 / 잠금 / 속성 편집
|
||||
|
||||
- hover/선택 오버레이(`ElementOverlay`/`useElementSelection`) — `data-editor-path` DOM↔노드 매핑, hover 점선·선택 실선, 컨텍스트 메뉴(속성/복사/삭제), 8방향 리사이즈 핸들, base/extension 잠금 어포던스, navigate 기반 "이 화면 편집" 네비. 선택 요소 컴포넌트 타입 식별 라벨(작은 요소는 박스 바깥), 잠금 영역 출처 식별 칩 3종(확장명·공통 레이아웃 파일명·데이터소스 id), 겹친 부모 선택(타입 칩 ↑ 버튼 + 키보드 ↑/Esc).
|
||||
- 속성 편집 모달(`PropertyEditorModal`) — `[설정]`/`[속성]`/`[스타일]`/`[고급]`/`[동작]`/`[표시조건]`/`[번역]` 탭. 레시피 엔진(`recipeEngine`, apply 4종: classToken/styleProp/cssVar/propValue, CSS 프레임워크 비가정)이 컨트롤↔노드 패치를 양방향 변환, 위젯 레지스트리(segmented/slider/select/toggle/color/image/tag-input/dimension/icon-picker/options-list 등) + `reverseResolve` 역해석·고급 값 무손실 보존. 편집 중 캔버스 잠금/딤(선택 외 요소 클릭 차단, 모달 스택 파생 자동 해제), 모달 드래그 이동 + 선택 요소 자동 회피.
|
||||
- 코어 제공 "요소 ID" 속성 일괄 부여(`coreProps.ts`/`CoreIdControl`) — 모든 draggable 컴포넌트의 [속성] 탭 최상단에 표준 `node.props.id` 편집(바인딩식 읽기전용, HTML 안전 문자 sanitize, `coreProps:false` opt-out). 컴포넌트 id passthrough 전수 적용.
|
||||
- 캔버스 모서리/변 드래그 리사이즈(`useResizeHandles`, 경량 포인터, scale 보정) + 가로/세로 자유 입력 `dimension` 위젯(`320px`/`50%`/`auto`, editor-spec options=프리셋 칩) — 속성 모달과 양방향 동기.
|
||||
- 공유 propControl 21종 + icon-picker/options-list 위젯, 신규 스타일 컨트롤 묶음(글자색·boxShadow·borderStyle/Color/Radius·opacity·overflow·fontItalic·textUnderline·whitespace·justify, editor-spec classToken SSoT), 여백 측별 독립 편집(일괄/개별, pt/pr/pb/pl 공존, `recipeEngine.groupPrefixes` + 다중 토큰 tokenTemplate), 정렬 박스(flex) 노드 파생 판정 + 해제 토글.
|
||||
|
||||
#### 색 모드 / 디바이스 분기 / 다크 프리뷰
|
||||
|
||||
- 스타일 탭 색 모드(라이트/다크) × 디바이스 직교 2축 편집 — 하나의 `StyleScope` 로 묶어 `recipeEngine` 이 base `props` 또는 `responsive.{preset|커스텀범위}.props`(다크는 `dark:` classToken)에 무손실 기록·역해석. 다크는 classToken만 편집(인라인 색은 읽기전용 보존), 디바이스 미오버라이드는 base 상속 placeholder, scope별 표시점(●) + "기본값으로 초기화", 디바이스 단일 토큰 편집 시 기본 className 시드로 기본 스타일 유실 방지. 묶음 상단 공용 색모드 탭(`ColorSchemeTabs`, per-control 복제 금지). 툴바 라이트/다크 프리뷰 토글.
|
||||
- 색 컨트롤 템플릿 스타일 라이브러리 대응 — 프리셋 색은 고정 토큰(`apply.tokens`+swatch, 라이트/다크 모두), 자유 HEX는 `tokenTemplate`(`text-[{value}]`) 라이트 전용(다크 탭 자유입력 비활성 안내).
|
||||
- 다크 프리뷰 색 모드 격리 — 템플릿 `darkMode` 스펙(strategy/ancestorSelector/previewIsolation)으로 코어 CSS 서빙 API 가 다크 조상 셀렉터를 프리뷰 마커(`.g7le-preview-dark`)로 치환(일반 페이지 CSS 무영향), `flattenLayers` 로 cascade-layer 평탄화, `usePreviewDarkIsolation`(MutationObserver)로 어드민 `html.dark` 침범 차단, 권한 가드 CSS 는 Bearer fetch→`<style>` 주입.
|
||||
|
||||
#### 디바이스별 별도 구성(반응형 자식 교체)
|
||||
|
||||
- `responsive.{키}.children` 자식 완전 교체형 편집 정합 — 모바일/태블릿 보기에서 보이는 구성 요소가 정확히 선택·수정되고(같은 자리 PC 구성 오선택 차단), 분기 출처 배지(모바일 구성), 구성 경계 이동 차단, ComponentPath 가 디바이스 분기를 1급 표현(`responsive.{키}.children.{N}`). 디바이스 전용 구성 분리/해제(기본 구성 복제 시작, 포함 관계 안내), 디바이스 목록 동적 수집(기본 4종 + portable + 사용자 폭 구간 다수), 다른 디바이스 구성 이동 버튼·전용 구성 안내 배지, portable 구간 스타일 표시, 더 좁은 디바이스 전용 분리.
|
||||
|
||||
#### 다국어 인라인 편집 / 데이터 칩 / 커스텀 키 관리
|
||||
|
||||
- 콘텐츠 로케일 전환(`LocaleSwitcher`, 캔버스 프리뷰만) + 더블클릭 인라인 편집(`useInlineEdit`/`InlineTextEditor`, 평문·기존 `$t:` 키 모두 `$t:custom.*` 자동 생성) + 인라인 서식 툴바(`InlineTextToolbar`, styleControls 선언분만) + 속성 모달 [번역] 탭(`TranslationField`, 전체 로케일 일괄 PUT). 낙관적 즉시 반영(키 생성 왕복 깜빡임 제거) + "모든 언어 편집" 바로가기.
|
||||
- 텍스트(보간) 데이터 연결 — 평문+다국어+데이터 공존: 평문 부분 다국어 키화(param 정규화, 언어별 어순 보존), 데이터는 드래그 가능한 원자 칩(글자 사이 어디로든 이동, 언어별 독립 위치, 캐럿 미리보기), 인라인 `+데이터`(커서 위치 삽입), 삽입=즉시 키화([번역] 탭 활성), 칩 X 로 전 로케일 해제. 대상 컴포넌트 12종 자동 인식 + capability `textBinding` opt-in/out, [번역] 탭 자리표시 보호 가드.
|
||||
- 데이터 칩 전면 확대 — 속성 창 텍스트 칸·선택지 라벨·목록 항목·표 셀·"다국어 키 관리" 화면·컴포넌트 속성 전반·페이지 설정 전 탭의 값 입력칸에서 데이터 칩/표현식을 동일하게 다룬다(값 전용 칸은 번역키 미생성). 칩 파서가 논리식(`||`)·파이프 서식(`| date`/`| 숫자`)·중괄호 객체 처리·다중 데이터를 정확 분리, 칩 이름은 핵심 데이터명만 표시. 설정참조(`$core_settings:`/`$module_settings:`/`$plugin_settings:`)도 친화 칩으로 시각화(공용 `inlineBindingUtils` SSoT).
|
||||
- 커스텀 다국어 키 관리 모달(`CustomTranslationManager`) — 목록·필터(전체/사용중/미사용)·로케일별 일괄 편집(낙관락 PUT, 409 안내)·삭제. 좀비(고아) 키 자동 표시 — 저장 시점 백엔드 리스너(`MarkOrphanedCustomTranslations` + `CustomTranslationUsageScanner`)가 미참조 키를 `orphaned` 전이(런타임 병합 자동 제외), 캔버스 실시간 사용 여부 라이브 배지 병행.
|
||||
- 텍스트 propControl 동적 다국어 인프라 — `widget:"i18n-text"`+`apply:propValue` 컨트롤을 `I18nTextField`(미리보기 + ko/en/ja 펼침 + 바인딩 읽기전용)로 전수 자동 승격. 공통 SSoT(`useCustomTranslation` `commitText`/`classifyCustomText`)로 인라인·목록·propControl·label_key 통일. children 항목 텍스트도 동일 위젯 승격(공용 `nodeTextPath`).
|
||||
|
||||
#### 데이터 바인딩 / 데이터 소스 편집기
|
||||
|
||||
- 데이터형 prop ↔ 데이터소스/상태 바인딩 — capability `dataProps`(shape scalar/array/object) 선언분만 [속성] 탭 "데이터 연결" 영역 노출(구조/수치/enum prop 비대상). 🔍 검색형 데이터 피커(친화 명칭·소스·경로·미리보기값 매칭, shape 일치 후보만) + 순수 후보 빌더(`bindingCandidates`, 편집기 샘플 데이터·`_global`·per-state local/query/route·`_computed` 평탄화) + 상태값 명칭 카탈로그(`stateLabels`, `$t:` 키, 로케일 동적 대응). `parseBindingExpression` 이 안전 바인딩(`?.`/`?? []`)을 정규화 인식, `buildBindingExpression` 이 shape별 안전 형태로 재기입. 양 템플릿 전 컴포넌트 dataProps 전수 선언, 입력/선택 계열 19종 보강, audit `editor-datapropspec-shape-valid`.
|
||||
- 반복(iteration) 데이터 연결 공용 영역(`IterationBindingSection`) — `node.iteration.source` 를 가진 모든 노드의 [속성] 탭 최상단에 "반복 데이터 연결"(array shape 후보, item_var/index_var 읽기전용 힌트).
|
||||
- 데이터 소스 편집기(`DataSourcesPanel`, 페이지 설정 [데이터] 탭) — 현재 레이아웃 data_sources CRUD(id/label_key/type/endpoint/method/auth/loading/params/fallback, JSON 검증). 자체/상속 분리 저장(`patchDocumentRaw`, `__editor.original` SSoT), 신규 소스 즉시 검색 후보 반영. 양 번들 템플릿 134 data_source + 확장 주입 118 data_source 전수 `label_key` 부여 + 확장 출처 배지(모듈/플러그인), audit `data-source-label-key-coverage`.
|
||||
|
||||
#### 노드 에디터(목록 / 표 / 배열)
|
||||
|
||||
- 범용 노드 에디터 슬롯(kind-agnostic) — capability `nodeEditor:{kind,params}`/`canvasOverlay:{kind,params}` + 레지스트리(`nodeEditorRegistry`/`canvasOverlayRegistry`) + `registerCoreEditors`. 코어는 kind 만 알고 디스패치(분기 0, 템플릿 재등록 가능), 미등록 안전 디그레이드. 템플릿 확장점 `G7Core.layoutEditor`(registerWidget/registerNodeEditor/registerCanvasOverlay) + ready 큐(`initLayoutEditorStub`, initTemplate 선등록 유실 방지).
|
||||
- 목록 children 노드 에디터(`ChildrenListControl`) — Ul/Ol/Nav/Form/Li 자식 트리 추가/삭제/정렬, 항목 텍스트 다국어(직접 text + 중첩 텍스트 자손 탐색, 장식 노드 보존), [속성] 탭 배치(스타일 탭=CSS 전용). 폼 항목 라벨+입력칸 묶음 추가·`itemFields`/`childTemplate`/`childLabel` 스펙 선언.
|
||||
- 표 노드 에디터(`TableEditor`) + 캔버스 인플레이스 오버레이(`TableInplaceOverlay`) — 트리↔논리 grid 어댑터(`tableGridModel`, 병합 고려), 행/열 추가·삭제·이동(밴드=병합 블록 단위, 섹션 경계 가드, 이동 불가 시 비활성+사유), 셀 병합/해제, 2단계 선택(표→셀)+Shift 영역 선택, 셀 테두리/배경색/내부 여백 시각 피커(프리셋 토큰+자유 HEX 인라인 SSoT, 라이트/다크 공용 탭, border-collapse 공유 변 보정), 셀 텍스트 다국어(복합 셀 구조 보존)+인라인 서식 툴바, 전용 거터 레일+빈 셀 최소 크기(편집기 전용 CSS), 속성 패널 미니 미리보기 실테두리 반영.
|
||||
- 배열 노드 에디터 — `ArrayItemsEditor`(정적 배열 prop 항목 추가/삭제/정렬/필드편집, 위젯 text/i18n-text/select/boolean/icon/number/color/number-list, 원시 `string[]` 지원, 정적-바인딩 가드, `defaultItems` 시드)·`array-group`(다중 배열 prop, BarChart labels+datasets)·`array-cell-tree`(중첩 cellChildren, CardGrid cardColumns). 템플릿 인플레이스 레퍼런스(`registerCanvasOverlay`, `data-editor-item-path` 마커). TagInput 계열 5종 options 편집기 보완.
|
||||
|
||||
#### 표시조건 / 동작 / 페이지 상태
|
||||
|
||||
- 표시조건 편집(`ConditionBuilder`/`conditionRecipeEngine`) — 친화 조건 카테고리(로그인/권한/데이터 유무·로딩·실패/필드 값/화면 상태/수정·생성/입력 오류) 택1 + "그리고/또는" 결합(단일 표현식 합성). 변종 방어 인프라 4계층(recipe-local alias·specificity 우선 매칭·path-shape 가드+backreference·전역 정규화 위임), audit `condition-recipe-duplicate`.
|
||||
- 동작(액션) 편집(`ActionRecipeEditor`/`actionRecipeEngine`) — 이벤트별 친화 명칭(이동/메시지/상태 바꾸기/새로고침/서버 호출), apiCall onSuccess/onError 중첩 재귀 조립, 올바른 핸들러 규칙(navigate/apiCall/setState/toast/refetchDataSource, top-level target) 생성. 동작 이벤트 친화 명칭 15종 보강(audit `editor-event-label-coverage`).
|
||||
- 동적 핸들러 이름 디스패치 — 액션 `handler` 가 `{{...}}` 바인딩이면 `ActionDispatcher.executeAction` 이 컨텍스트로 먼저 해석한 뒤 라우팅한다(`resolveActionRef` 직후, 프리뷰 억제·switch 앞). 백엔드 응답이 호출할 핸들러 풀네임을 내려주는 provider-agnostic 디스패치(결제 진입 `handler: "{{response.data.pg_payment_handler}}"`)를 지원. 빌트인 26종은 리터럴이라 미진입(무영향), nested(conditions/sequence)도 동일 경유로 자동 적용, 프리뷰 억제 판정·미등록 graceful skip 도 해석 이름 기준. 편집기 "결제 진입" recipe(`requestPgPayment`)로 친화 입력(핸들러·결제 데이터 칩, `chipContext='response'`), `actionRecipeEngine.matchAction` 핸들러 비교를 placeholder-aware 로 보강(리터럴은 정확 일치, `{{key}}` 는 `extractValues` 위임).
|
||||
- 중첩 액션 친화 편집 확대 — apiCall `onSuccess`/`onError` 와 `sequence`/`parallel` 의 actions 를 `advanced` 잠금에서 풀어 친화 중첩 액션 빌더(action-list)로 편집한다(응답 후속·다단 동작을 코드 없이 추가/순서/속성·데이터 칩 편집). 재귀 `ActionListBuilder` 가 동일 recipes·candidatePools 로 펼쳐지며 `summarizeAction` 은 action-list 트리 param 을 카드 요약에서 제외(`[N]` 토큰 누출 방지). `switch.cases` 는 객체맵 구조라 잠금 유지.
|
||||
- `conditions` 핸들러 친화 recipe + `branch-list` 위젯 신설 — 조건 분기(`[{if, then}]`)를 분기별 실행조건(조건식 데이터 칩)·동작(중첩 액션 빌더, 단일/배열 both) + 분기 추가/삭제/순서로 친화 편집. recipe build 는 `conditions` 를 액션 최상위 키(`{handler:'conditions', conditions:'{{branches}}'}`)로 두어 `handleConditions` 와 정합, sole-binding 통째 캡처로 `then` 구조 무손실 왕복. 이 셋이 합쳐져 `sequence → apiCall.onSuccess → conditions → then` 깊이의 결제 진입까지 코드 없이 편집 가능(특정 템플릿/모듈 비의존, 코어 전역).
|
||||
- 동작 입력칸 객체값·경로형 setState 표시 정합 — (1) apiCall `body` 위젯을 `data-chip`(스칼라/표현식)에서 `key-value` 로 바꿔 필드 맵(`{temp_order_id, orderer, ...}`)을 키별 데이터 칩 행으로 편집한다(객체를 단일 칩으로 받아 `[object Object]`·JSON 분해 깨짐이 생기던 문제 제거). (2) setState 의 경로형(`{target:'_local.X', value:V}`)을 인식해 `value` 를 상태 키 이름이 아니라 그 경로에 넣을 단일 값으로 표시(타입 보존 `InitialStateValueEditor`). (3) 컴포넌트 [동작] 탭이 `bindingCandidates` 를 동작 입력칸까지 전달하지 못해 데이터 칩 추가(🔍) 가 안 뜨던 회귀를 수정(`PropertyEditorModal`→`ActionRecipeEditor`).
|
||||
- 페이지 상태 토글 + 시뮬레이션(`PageStateSwitcher`/`pageStateSimulator`) — `editor-spec.states` 의 sampleData 오버라이드·초기 `_local`/`_global`/`query`/`route` 패치·폼 검증 실패를 캔버스에 재시뮬레이션(`_localInit` 권위 주입으로 init_actions 이김). scope 매칭(route glob/base/modal, 실제 path 일치), 번들 템플릿 states.json 전수 작성(profile/edit·settings·users 등). 반복 항목 편집 모드 진입 골격.
|
||||
|
||||
#### 버전 히스토리 / 실데이터 미리보기 / 확장·모달 조각 편집
|
||||
|
||||
- 버전 히스토리 모달(`VersionHistoryModal`/`useLayoutVersions`) — 저장 버전 목록(번호·시각·저장자·변경량 +N/-N/char_diff·최신 배지) 조회·복원(`reload` 캐시 버스트+activeDocument 재로드, 낙관적 잠금 정합) + 버전 비교 diff(`VersionDiffView`/`lineDiff`, 자체 LCS·Unified diff·외부 라이브러리 0). 실데이터 미리보기(`useLayoutPreview`) — 미저장 문서를 저장 마스킹 후 `storePreview`(30분 TTL)→`/preview/{token}` 새 창, `mod+p` 결선.
|
||||
- 확장(주입 조각) 시각 편집 — 호스트 레이아웃 전체를 백엔드 평가 상태 그대로 렌더 + 편집 조각만 역스포트라이트, 모달 안 주입 조각(약관/주소 검색/본인인증)도 모달 열어 편집, 화면 상태 전수 정의(배송지 직접 입력·모바일 드로어·쿠키 배너·이니시스 등), 시각 편집 불가 시 코드 편집 안내 디그레이드. 라우트↔모달/확장 연결 목록(정적 매칭 `host_layouts`, 트리 인라인). 확장 버전 기록·복원·트리 버전 배지(`useExtensionDocument`/`VersionTarget` 일반화 + 백엔드 LayoutExtensionVersion*).
|
||||
- 공통 레이아웃 슬롯 가시화+잠금(점선 "콘텐츠 영역" 라벨, 선택/드롭 전체 잠금), 헤더/푸터 선택 가능(시각적 루트 editorAttrs 전달 + 핸들 클릭 최심 노드 위임).
|
||||
|
||||
#### 저장 / 동시성 / 접근 오류 / devtools
|
||||
|
||||
- 문서 저장·dirty·동시성(`useLayoutDocument`) — `patchLayout`/`save`(`expected_lock_version` PUT, 활성 확장 재검증, 200/409/422/network 분기), 저장 마스킹(`stripInheritedFromLayoutContent`, base/extension/partial+메타 제거), 라우트 전환 세션 캐시 복원 + 트리 dirty 배지(●) + beforeunload 가드, 레이아웃 초기화(`reload`). `SaveFeedbackBanner`(6종 SaveResult, concurrent 모달). 낙관적 잠금 인프라(`lock_version` 컬럼 + `ConcurrentModificationException` + 409 + 백엔드 `UpdateLayoutContentRequest::prepareForValidation` 마스킹 가드).
|
||||
- 접근 오류 패널(`AccessErrorPanel`) — kind별(unauthorized/forbidden/not_found/server_error/network/unknown) 아이콘·톤·필요 권한 칩·액션, 401 자동 로그인 redirect(`AuthManager.getLoginRedirectUrl`), 자산/라우트 실패 통합. `access_error.*` 키 17건.
|
||||
- devtools 트래커 다수 — editor-state/selection/dnd/document/history/sample-data/spec-merge/property-patch/i18n/page-state(메타 키만 적재, 노드 내용물·평문 미적재, 언마운트 clear).
|
||||
- 공용 모달 인프라(`EditorModalContext`/`EditorModalRoot`/`useEditorModal`) — 코어 `_global.modal` 과 분리(격리 store 충돌 회피), 백드롭/ESC 닫기, depth 무제한 스택. 부유 드롭다운 공용화(`FloatingDropdown`, `position:fixed`+anchor rect 로 flip/clamp 자동 보정, 외부 pointerdown/ESC 닫기) — 데이터 검색 피커·검색 드롭다운 전반 적용.
|
||||
|
||||
#### 페이지 설정 모달(8탭)
|
||||
|
||||
- 페이지 설정 모달 — 기본 정보·검색엔진·화면 동작·로딩 화면·자동 계산·초기 상태·에러 처리·데이터 8탭, 탭별 고급 항목 배지, 즉시 반영(영속은 툴바 저장). 켬/끔 하위 설정은 숨기지 않고 비활성(회색) 표시, 공용 토글 스위치, 모달 최대 높이 화면 적응 + 내부 스크롤, ESC 닫힘 차단([닫기]/[✕]만).
|
||||
- 기본 정보 — 페이지 이름·설명·편집기 트리 라벨(다국어+데이터 칩), 메뉴 아이콘 고르개, 접근 권한 태그.
|
||||
- 검색엔진(SEO) — 노출 켬/끔·페이지 종류·연동 확장/데이터·sitemap 우선순위/주기·검색 제목/설명, 소셜 공유(OG/Twitter, 비운 칸 기본값 출처 배지+잠금, 고급 이미지 옵션), 구조화 데이터(직접 지정 토글, 확장 자동값→연결 칩 출발, JSON-LD 미리보기), 검색 변수(자동/값채움/직접 추가 3그룹), 봇 미리보기(서버 권위 계산). 확장 제공 SEO 자동값을 출처 연결 칩 + [다른 데이터로 바꾸기]로 표시(언어팩 키 기반 명칭).
|
||||
- 화면 동작 — 핸들러 카탈로그(코어+확장)에서 골라 순서 배치(드래그 손잡이), 친화 요약+코드 보기+출처 배지+실행 조건, 부모 상속 동작 잠금(읽기 전용). 모든 동작 입력칸 데이터 칩·표현식 친화 입력(저장소 키·상태 값·setState 키–값·navigate query 등), 모달 선택 `modal-picker` 위젯(친화 명칭).
|
||||
- 로딩 화면 — 켬/끔·덮을 범위(전체/특정 영역, 영역 고르개)·표시 방식 5종+옵션·기다릴 데이터, 상속 표시 + [이 화면만 바꾸기], 안내 문구 다국어, 별도 컴포넌트 선택 창.
|
||||
- 자동 계산 — 친화 보기 + "직접 만들기" 3단계 + 샘플 데이터 결과/타입 미리보기, 부모 계산값 덮어쓰기/되돌리기, 모든 값·경로 칸 데이터 칩·표현식, firstOf 후보·배열 인덱스 평문 유지.
|
||||
- 초기 상태 — 로컬/전역/격리 시작값(문자/숫자/예아니오/없음/목록/묶음+중첩 블럭 편집), 종류 선택 추가, [코드로]/[블럭으로] JSON 전환(문법 오류 저장 차단), 값 이름 검증(영문 시작), 부모 상속 표시·덮어쓰기.
|
||||
- 에러 처리 — 상태 코드별 동작 행(표준 401~503 기본 표시, 출처: 이 페이지/상속/템플릿), 7종 동작+오류 정보 데이터 칩, 코드 미리보기, 상속 덮어쓰기 안내.
|
||||
- 데이터 탭 — 데이터 소스 편집을 종류별 섹션(본문 타입·성공/실패 후속·코드별 오류·조건부 로딩·재진입 재요청·실시간 수신)으로 확장 + 전역 헤더·외부 스크립트 읽기전용.
|
||||
|
||||
#### 표현식 분해 트리
|
||||
|
||||
- 조건에 따라 달라지는 제목·설명·값을 조각별 분해 편집 — 조건 분기(`A ? B : C`)·기본값 폴백(`A ?? B`/`A || B`)·이어붙이기(`A + B`)를 트리로 풀어 각 분기를 다국어 입력칸(번역 탭·데이터 칩)으로 편집, 중첩 재귀 표현. 한 줄 미리보기+[수정]/[접기], [원본 식 보기] 토글, 친화 빌더 가능한 단순 조건만(복잡 조건 읽기전용으로 원본 무손상). 조각 손잡이 드래그 순서 변경·추가([+조각]/[+값이 없을 때 대신])·삭제, 일반 이름↔표현식 양방향([표현식으로 바꾸기]/[일반 이름으로], 되돌림 미리보기·경고, 첫 결과 데이터 칩 복구). 페이지 이름·설명에서 검색엔진 값 칸·컴포넌트 속성 전반으로 확대.
|
||||
|
||||
#### 본인인증(IDV) 인증 대상 선언
|
||||
|
||||
- `apiCall` 액션에 **`identity_target`** 선언 속성 신설 — IDV 428 인터셉트 시 인증 코드/링크를 보낼 대상(이메일·전화)을 흐름이 직접 선언한다. `auth_mode`/`errorHandling` 과 동일하게 apiCall 액션 최상위에 두며, `{ email?, phone? }` 형태로 표현식 바인딩을 지원한다. `ActionDispatcher` 가 428 인터셉트 지점에서 이 값을 평가해 `IdentityGuardInterceptor.handle(response, originalRequest, target)` 로 전달하고, launcher 가 `verification.target` 한 곳에서 읽는다. 비로그인(게스트) 흐름의 핵심 — 서버 428 payload 에는 target 이 없고(서버는 화면 입력값을 모름) 흐름이 선언한다. 로그인 사용자는 빈 값이어도 서버 세션이 도출하므로 무방하다. (배경: 비회원 주문 결제 시 본인인증 정책이 켜지면, 주문자·수취인에 이메일·전화를 모두 기재해도 launcher 가 주문자 입력값을 읽지 못해 "인증 대상이 필요합니다" 422 로 막히던 결함. 기존 launcher 는 회원가입/비밀번호 재설정 폼 경로만 하드코딩으로 알았다.)
|
||||
- `G7Core.api`(axios) 호출 경로도 `config.identity_target` 로 동일하게 IDV 대상을 선언할 수 있다 — `apiCall`(fetch) 경로와 axios 경로 양쪽 모두에서 인증 대상 전달을 지원한다.
|
||||
- `ensureIdentityVerified` 액션이 `params.target` 으로 선제 가드 시점의 인증 대상을 선언할 수 있다 (apiCall `identity_target` 과 동일 채널).
|
||||
- 레이아웃 편집기 apiCall 레시피에 `identity_target` email/phone 입력칸 추가([고급] 영역) — 코드 편집 없이 인증 대상 선언을 편집할 수 있다.
|
||||
|
||||
#### 레이아웃 편집기 SEO 다국어 데이터 칩
|
||||
|
||||
- 레이아웃 편집기 검색엔진 탭(페이지 설정)의 데이터 칩 파서가 **SEO 다국어 추출 함수 `$localized(<경로>)`** 를 단일 바인딩으로 인식하도록 확장. 종전엔 `$localized(product.data.meta_title)` 같은 함수 호출이 `bindingCandidates.parseBindingExpression`·`expressionValueTree` 양쪽에서 복합식(raw)으로 떨어져, SEO 메타값을 입력해도 편집기가 친화 데이터 칩 대신 원시 식 문자열을 노출했다. 이제 `parseBindingExpression` 이 `$localized(<단순경로>)` 래핑(인자 1개·단순 경로)을 흡수해 인자 경로를 단일 바인딩으로 인지하고 `localeFn` 으로 함수명을 보존하며(`bindingChipLabel` 이 인자 경로를 친화 라벨로 표시), `expressionValueTree` 파서가 같은 형태를 단일 바인딩 리프(`{{$localized(path)}}`)로 환원해 `meta 우선 ?? name 폴백` 체인도 fallback 트리로 분해한다. `buildBindingExpression(sourceId, path, shape, localeFn)` 에 옵션 인자를 더해 데이터 교체 시에도 `$localized(<src>.<path>)`(옵셔널 체이닝/폴백 없음) 래핑을 보존한다(래핑이 빠지면 다국어 객체가 현재 로케일 문자열로 추출되지 않아 SEO 메타가 깨짐). 다인자·연산·리터럴 인자, 미등록 함수(`Math.max` 등)는 종전대로 복합식(raw) 폴백이라 손상 0. (배경: 상품·카테고리 SEO 제목/설명 다국어화 후, 사용자가 검색엔진 탭에서 설정한 SEO 메타 항목이 편집기 데이터 칩으로 표시되지 않던 결함.)
|
||||
|
||||
### Changed
|
||||
|
||||
- 동작 순서 변경 방식을 표현식 편집기와 통일 — 컴포넌트 [동작] 탭·페이지 설정 [화면 동작] 탭·데이터/에러 처리 동작 목록에서 손잡이 드래그 + 파란 삽입선으로 재배치(▲▼ 버튼 제거, 공통 레이아웃 상속 동작은 잠금).
|
||||
- 코어 JSON 텍스트 편집 입력기를 공용 부품(`JsonBlockField`)으로 통일(데이터 소스 요청 파라미터·확장 주입 속성·초기 상태 [코드로] 동일 동작/오류 안내), 데이터 소스 [기본값]을 중첩 블럭 편집으로 일원화(raw JSON 모드 제거), [요청 파라미터]·[기본값] JSON 미리보기를 [미리보기 ▾] 토글로 전환.
|
||||
- 데이터 검색 선택기를 모든 진입점에서 부유(`FloatingDropdown`) 상태로 통일(자동 위치 보정), 로딩 화면 기다릴 데이터·검색엔진 연동 데이터 목록을 [데이터] 탭과 동일 표기(표시 명칭+id+확장 출처 배지)로 직관화.
|
||||
- 페이지 설정 항목 이름을 편집 중인 화면 단어장 우선 해석(관리자 단어장 폴백)으로 정정, `errors/{code}` layout_name 식별자 통일(`TemplateManager` 자동 부착 제거), `ActionDispatcher.handleOpenWindow`/navigate fallback 기본 `_self`(교차 이동 의도치 않은 새 탭 차단), `recipeEngine.applyRecipe`/`reverseResolve` optional scope 인자(기본 BASE_SCOPE 동일 동작), 편집 모드 nesting 컴포넌트 `editorAttrs` 패스스루(layout/composite 시각적 루트 spread, 사용자 페이지 no-op).
|
||||
- `editorSpecLoader` 가 편집 대상 + 활성 모듈/플러그인 editor-spec 을 단일 병합본으로 합침(record key 병합·palette/states concat·nesting union·sampleData key 병합), `sampleGlobal` 코어 우선 deep merge 체인(충돌 시 코어 값+dev 경고), 라우트 트리 노드에 레이아웃 파일 경로 표시·툴바 템플릿 이름/버전+전환 드롭다운.
|
||||
- `IdentityGuardInterceptor.handle()` 시그니처에 3번째 인자 `target?: { email?, phone? }` 추가(옵셔널, 하위호환). `VerificationPayload` 에 런타임 필드 `target` 추가, `IdentityVerificationTarget` 타입 export.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 페이지 설정 [화면 동작] 탭이 기존 동작을 못 읽어 추가·저장 시 기존 동작이 통째로 사라지던 데이터 손실, "설정 저장하기" 저장할 값이 번역 문구용 읽기전용으로 잘못 배정, "화면 상태 바꾸기" 깊은 중첩 묶음이 `[object Object]` 로만 표시·편집 불가, 실행 조건(if) 칸이 평문이라 데이터·표현식 미연결, ≡/🔍/ƒx/?? 버튼 겹침·행 어긋남 등 동작 입력 결함.
|
||||
- 평문+데이터 칩 혼합 값을 [표현식으로 바꾸기] 승격 시 중괄호 중첩(`{{...'{{route.id}}'...}}`)으로 식이 깨지던 문제 — 데이터 칩을 이어붙이기 식 데이터 항(`'...' + route.id`)으로 보존. [일반 이름으로] 되돌리기 시 첫 결과 데이터 연결이 빈 칸으로 사라지던 문제, 단일 데이터에 불필요한 표현식 편집기 펼침, 검색엔진 데이터 칸 [✓ 완료] 버튼 부재, [✎ 수정] 모드에서 데이터·설정 참조 raw 노출(칩 편집기 유지로 정정).
|
||||
- 자동 계산 "먼저 있는 값 고르기" 후보 소실·깨진 식 저장·데이터 선택 칸 부재, 검색엔진 SEO 동적 변수 그룹 미분류(확장 정보 미전송), 미리보기 샘플 데이터 미반영·출처 표시 미갱신·상속 값 오표기, 로딩 화면 상속 표시·영역 고르개·구조화 데이터 자동 채움, 에러 처리 표준 상태 코드 행 누락·두 번째 입력칸 입력 불가·타이핑 소실(번들 errorRecipes.json setState 스프레드/openModal target/showErrorPage target 정정 포함), 모달 화면 높이 초과·탭 색 줄 잔존 등 페이지 설정 다수.
|
||||
- 데이터가 든 다국어 문구 인라인 편집 시 계산식 일부(`|| []).length}}` 등)가 평문 노출·칩 이름 깨짐(관리자 사용자 관리·대시보드·본인인증·언어팩 등 개수/페이지 정보 화면 전반), 객체 형태 계산식·`{{error.errors ?? {}}}` 빈 객체 fallback 미평가, 모달 화면명 키 노출.
|
||||
- 표 셀·목록 항목에 데이터 칩 끼운 직후 "데이터 영역" 잠금으로 인라인 편집 차단·표 미리보기 격자 키 문자열 노출, 데이터 칩 글자 사이 드래그 시 trailing click 으로 해제·`{p0}` 자리표시 잔존.
|
||||
- 요소 이동 후 undo 시 복제(중복) 발생, 디바이스별 구성 안 요소 추가·이동·undo 미반영, portable 구간 라벨 "모바일" 오표기·스타일 미표시·전용 분리 불가·분리 해제 시 스타일 동반 삭제.
|
||||
- 인라인 편집 중 글자색 classToken 실시간 미반영(폴백 인라인 color 가 토큰 색 가림 — 색 출처 없을 때만 적용), apiCall onSuccess 중첩 동작 추가 불가, 동작 카드 드래그 핸들 무동작, 영역 선택(🎯) 모드에서 편집 표식 미숨김·임시 ID 요소 선택 가능·딤 막 클릭 가로채기·고른 요소 잔류 선택.
|
||||
- flex 노드 파생 판정 stale(DOM computed 고정), 캔버스 잠금 딤이 닫은 뒤 잔존(모달 스택 파생으로 자동 해제), 표시 권한 TagInput 후보 미주입(+추가 영구 비활성), 데이터 바인딩 요소 선택·이동 불가·네비 어포던스 오해 안내, 화살표 함수 `arguments` 부재로 인한 data_source 3번째 인자 판정 결함(단위 테스트 검출).
|
||||
- 서버 응답 캐시 키와 무효화 경로 정규화 불일치로 저장 후 사용자 간 stale 노출(serve `?v` 정수화, 일반/편집기 `.meta` 키 동시 무효화), 편집기 후보 데이터를 admin 전역 broadcast 가 아닌 가드 엔드포인트 fetch 로 한정.
|
||||
- `replace:true` navigate(탭 전환·필터 변경 등 같은 화면 내 URL 교체) 경로에서 데이터소스 `if` 조건이 재평가되지 않던 버그 수정. `updateQueryParams` 가 직전 진입 시점에 `if` 로 필터링된 `currentDataSources` 스냅샷을 그대로 refetch 하여, 탭을 클릭으로 전환하면 변경된 `query` 컨텍스트가 반영되지 않고 직전 탭의 데이터소스가 계속 선택되었다. 이제 원본(`if` 필터링 전) 데이터소스를 보존(`currentRawDataSources`)하고, `updateQueryParams` 에서 변경된 `query` + 최신 `_global` 로 `filterByCondition` 을 재평가하여 현재 탭에 맞는 데이터소스만 fetch 한다. (새로고침/URL 직접 진입 경로는 기존에도 정상 — 본 수정은 SPA 탭 클릭 전환 경로 전용.)
|
||||
- iteration source / if 조건 / 반복 텍스트 바인딩에서 **배열·객체 리터럴**(`{{['a','b']}}`, `{{[{...}]}}`)이 렌더되지 않던 버그 수정. `isComplexExpression`(RenderHelpers.ts) 정규식이 `[`/`]`/`{`/`}` 를 인식하지 못해 리터럴이 "단순 경로"로 오판되어 `resolve()` 경로탐색 → `undefined` 가 되었다. 정규식에 `[]{}` 를 추가하여 리터럴이 `evaluateExpression`(원본 타입 유지) 경로로 라우팅된다. 순수 숫자 대괄호 인덱싱(`items[0]`, `entry[1]`)은 `resolve()`/`evaluateExpression()` 양 경로 결과가 동일함을 회귀 테스트로 입증 — 경로 이동에 따른 동작 변화 없음. (배경: 본인인증 이력 화면의 상태/발생위치 필터 체크박스가 배열 리터럴 source 로 정의되어 전혀 렌더되지 않던 결함.)
|
||||
- `evaluateExpression`(DataBindingEngine.ts) 에서 `new Set(...)` / `new Map(...)` 가 `Set is not a constructor` 로 실패하던 버그 수정. `extractVariablesFromExpression` 의 `reserved` 화이트리스트에 `Set`/`Map`(및 `WeakSet`/`WeakMap`/`Symbol`/`Promise`/`BigInt`/`Error`)이 없어 이들이 컨텍스트 변수로 오인되어 `undefined` 로 가려졌고, `new Function` 본문에서 `new undefined()` 가 되었다. `Math`/`Date`/`Array` 등과 동일하게 표준 내장 객체로 화이트리스트에 추가한다. `eval`/`Function`/`globalThis`/`window` 등 위험 전역은 의도적으로 제외. (배경: 본인인증 이력 화면의 채널 필터가 `Array.from(new Set(...))` 로 후보를 도출하던 결함.)
|
||||
- `ApiClient`(`G7Core.api`) response 인터셉터에 **HTTP 428 본인인증(IDV) 중앙 처리** 추가. 기존에는 `apiCall` 핸들러(`ActionDispatcher.handleApiCall`, native fetch) 경로만 `IdentityGuardInterceptor` 로 428 을 자동 인터셉트했고, `G7Core.api`(axios) 직접 호출 경로(모듈 JS 핸들러: 무통장 입금확인·주문 취소 등)는 401 만 처리해 428 이 와도 본인인증 모달이 뜨지 않았다. 그래서 각 모듈 핸들러가 `G7Core.identity.handle` 분기를 수동으로 복제해야 했고, 누락 시 본인인증 가드가 무력화됐다(주문 취소 핸들러 미노출 회귀). 이제 axios 인터셉터가 `428` + `identity_verification_required` 응답을 감지해 본인인증 모달 → verify → 원 요청(헤더/body 재사용) 자동 재실행을 중앙에서 수행한다. `apiCall`(fetch) 경로와는 별개 HTTP 클라이언트라 이중 처리되지 않는다.
|
||||
- `createChangeEvent`(EventHelpers.ts) 가 checkbox/radio 이벤트의 `target.value` 를 `String(checked)`("true"/"false") 로 문자열화하던 버그 수정. Toggle/Checkbox 가 명시적 `value` 없이 `createChangeEvent({checked})` 로 만든 이벤트가 Form 자동바인딩의 **value 바인딩 경로**(currentValue 가 boolean 이 아닐 때 — 예: 폼 초기값이 아직 채워지지 않은 시점)로 처리되면, boolean 필드에 문자열 `"true"` 가 저장되어 백엔드 boolean 검증이 422 로 거부되었다(예: 이커머스 환경설정 "취소 시 재고 복구" 토글 ON 저장 실패). 이제 checkbox/radio 의 기본 `value` 를 boolean(`checked`) 으로 두어, checked 바인딩 경로(`target.checked`)는 기존과 동일하게 동작하고 value 바인딩 경로도 boolean 을 저장한다. 명시적 `value` 를 받는 호출(PermissionTree, HtmlEditor 의 textarea/multilingual)과 checked 만 읽는 호출(HtmlEditor isHtmlMode)은 영향 없음. (배경: troubleshooting-components-form.md 사례 5 — "엔진이 boolean 을 올바르게 처리, 문자열 변환 우회 불필요" 설계 의도와 정합.)
|
||||
- 컴포넌트 `setState`(`target: "_local"`)가 canonical source(`_global._local`)에 동기화되지 않아, 검색(`navigate replace:true`) 직후 사용자가 선택한 필터가 풀리던 버그 수정. 목록 화면에서 필터(라디오/체크박스 등)를 선택하면 `ActionDispatcher.handleSetState` 의 COMPONENT path 가 컴포넌트 React 상태(저장소 A: `localDynamicState`)만 갱신하고 `_global._local`(저장소 B)은 갱신하지 않았다. 이후 검색 → `updateQueryParams` refetch → `updateTemplateData` 가 `currentDataContext._local` 을 stale 한 `_global._local`(init 기본값)로 되돌려, 선택한 필터 일부가 검색 직후 초기값으로 풀렸다(새로고침은 `handleRouteChange` 가 `query` 기반으로 `_global._local` 을 재구성하므로 정상). Form 자동바인딩은 이미 `setLocal(render:false)` 로 양쪽 저장소를 동기화하지만 명시적 `setState target:"_local"` 은 그렇지 않던 비대칭이 원인. 이제 COMPONENT path 도 GLOBAL STATE UPDATER path 와 동일하게 `globalStateUpdater({ _local }, { render: false })` 로 `_global._local` 을 동기화한다. `render: false` 이므로 추가 React 렌더는 발생하지 않으며(클릭당 렌더 횟수 불변), `scope: 'parent'|'root'` 및 isolated 타깃은 이 분기에 도달하기 전에 분리 처리되어 모달 상태 오염에 영향이 없다. (배경: 쿠폰·주문·배송정책 등 목록 화면 공통 결함.)
|
||||
- `emitEvent` 액션의 결과(`_local._eventResult`)가 **같은 sequence 의 후속 액션에 전파되지 않던** 버그 수정. `handleSequence` 는 비-setState 핸들러 실행 후 `currentState` 를 `__g7SequenceLocalSync`(setLocal 이 설정)에서만 갱신하는데, `emitEvent` 는 `globalStateUpdater` 로만 `_local` 을 갱신해 `__g7SequenceLocalSync` 를 비워둔 채였다. 그 결과 emit 직후의 `setState`/`apiCall` 이 `_eventResult` 와 리스너가 갱신한 `_local`(예: 업로드된 `form.images`)을 보지 못하고 emit 이전 stale 스냅샷을 사용했다. 이제 `emitEvent` 가 `globalStateUpdater` 갱신과 동일한 시점에 `__g7SequenceLocalSync` 에 `_eventResult` 를 병합한 `_local` 스냅샷을 실어, `handleSequence` 가 이를 픽업한다. base 는 sequence 가 추적 중인 `context.state` 우선이라 in-flight `setState` 변경(예: `isSaving`)을 보존하며, sequence 밖(standalone emitEvent)에서는 글로벌 `_local` 로 폴백한다. 글로벌 `_local` 갱신 동작 자체는 종전과 동일하게 유지된다. (배경: 상품 수정 화면에서 이미지를 추가하고 저장하면 — 저장 sequence 가 `emitEvent(업로드)` → `apiCall(PUT)` 순서인데 — 업로드는 성공해도 PUT body 의 `form.images` 가 업로드 전 스냅샷이라 백엔드 `syncImages` 가 방금 올린 이미지를 삭제하던 회귀.)
|
||||
- IME(한글·일본어·중국어) 조합 중 Enter 가 액션 키 필터에 매칭되어 **글자누락·이중제출** 이 발생하던 버그 수정. `ActionDispatcher` 의 key 필터(`action.key` 지정 keydown 액션)는 비교 전에 IME 조합 상태를 전혀 검사하지 않아, 한글 입력 후 Enter 로 조합을 확정하는 순간 그 Enter keydown 이 `key:"Enter"` 액션(검색·제출 등)을 조합 확정 *전* 값으로 발화시켰다. 결과적으로 (1) 조합 중 마지막 글자가 input 에 커밋되기 전 액션이 실행되어 글자가 누락되고, (2) 액션 실행 후 글자가 커밋되며 두 번째 keydown 으로 재실행되어 이중 제출이 일어났다. 이제 `isImeComposing` 헬퍼(`event.isComposing === true` 또는 legacy `event.keyCode === 229` 검사 — 브라우저별 조합 종료 keydown 차이 흡수)로 조합 중 keydown 은 key 필터 매칭에서 제외한다. 가드는 `action.key` 가 지정된 keydown 액션에만 적용되어, key 필터 없는 매 입력 setState 류 액션은 조합 중에도 종전대로 동작한다(회귀 0). 모달 오버레이 ESC 닫기 리스너에도 동일 가드를 적용해 조합 중 ESC 가 모달을 닫지 않도록 일관화했다. (배경: 상품·게시판 검색창에서 한글 검색어 입력 후 Enter 시 마지막 글자가 빠지거나 검색이 두 번 실행되던 결함 — gnuboard/g7 #54.)
|
||||
- 본인인증(IDV) challenge 가 **부가 목적(성인인증 등) 미달**로 실패할 때 토스트가 **2개 중복 표출**되던 버그 수정. 본인확인 자체는 성공했으나 부가 조건(만 19세 이상)을 충족하지 못해 challenge 가 실패하면, provider 가 "성인 인증이 필요합니다" 같은 고유 사유를 토스트로 표출한다. 그 직후 코어가 원 428 응답을 onError 로 흘려보내, 원 요청(글쓰기 등)의 generic 가드 토스트("본인 확인이 필요합니다")가 한 번 더 떴다. 이제 `IdentityGuardInterceptor` 에 1회성 도메인 안내 신호(`markDomainNoticeShown()` / `consumeDomainNoticeShown()`)를 신설하고, provider 가 "본인확인 성공 + 부가목적 미달" 실패를 안내한 직후 이 신호를 남기면, 코어 `handleToast` 가 동일 사이클의 generic IDV 가드 토스트(error 타입 + `error_code='identity_verification_required'`) 1건을 skip 한다. 일반 본인인증 실패/취소(본인확인 자체 실패)는 신호가 없어 가드 토스트가 그대로 유지된다 — provider 무지식의 범용 신호이므로 부가 목적이 추가되어도 코어 수정 없이 동작한다. onError 정리 액션(`setState{isSaving:false}` 등)은 그대로 실행되어 버튼 잠금 해제 등 후속 처리는 보존된다. `handle()` 진입 시 이전 사이클의 미소비 신호를 정리해 stale skip 을 방지한다. `ErrorContext` 에 `error_code` 필드를 추가하고 onError 컨텍스트에 응답의 `error_code` 를 노출한다. (배경: 성인인증이 필요한 게시판 글쓰기에서 미성년자가 인증 시 "성인 인증이 필요한 서비스입니다"와 "본인 확인이 필요합니다"가 동시에 뜨던 결함.)
|
||||
- 레이아웃 편집기 **공통(base) 레이아웃 편집 모드**에서 모듈이 슬롯에 주입한 UI(예: 헤더 통화·배송국가 셀렉터)가 **소비처(SlotContainer) 위치가 아니라 주입 앵커 원위치에 표시**되던 결함 수정. `slot` 노드는 SlotContext 활성 시 원위치에서 렌더되지 않고 SlotContainer 가 떙겨 렌더하는데, base 단독 편집 캔버스는 슬롯이 통째로 사라지는 것을 막으려 모든 `slot` 노드를 표시 마커(`__editorSlotName`)로 치환해 원위치에 렌더했다. 주입 앵커는 보통 헤더 밖 최상단 등 SlotContainer 와 다른 자리라, 통화 셀렉터가 헤더 위 별도 박스로 떠 운영 화면과 어긋났다. 이제 변환 로직(`buildBaseEditorComponents`)이 **같은 base 레이아웃 안에 소비처(`SlotContainer` props.slotId) 가 있는 슬롯은 치환하지 않고 `slot` 키를 보존**해 슬롯 메커니즘에 위임한다 → SlotContainer 가 실제 위치(헤더 안)에서 렌더한다. 소비처가 없는 슬롯(자식 라우트 레이아웃이 채우는 `content` 등)만 종전대로 원위치 마커로 치환해 점선 박스로 표시한다. 동일 슬롯을 쓰는 SlotContainer JSON 노드가 하나라도 있으면(데스크톱/모바일 페어 등) 통짜 TSX 컴포넌트 내부 SlotContainer 도 정상 수신하므로, 어떤 템플릿/모듈이 어떤 슬롯에 주입하든 코어 차원에서 동일하게 동작한다. route 편집 모드는 조기 반환이라 영향 0. (배경: 관리자/사용자 템플릿 공통 레이아웃 편집에서 통화·배송국가 선택기가 헤더 위 별도 박스로 분리 표시되던 결함.)
|
||||
- iteration(반복 렌더링) 안의 노드 `id` 에 쓴 표현식(`id: "item_{{$idx}}"` 등)이 **보간되지 않고 리터럴 그대로 DOM 에 출력**되어, 반복 행마다 같은 HTML id 가 중복되던 결함 수정. 노드의 최상위 `id` 필드는 `props` 가 아니라 props 바인딩 경로를 타지 않아, `DynamicRenderer` 의 두 DOM 출력 지점(Fragment 컨테이너 div / 일반 컴포넌트 props)이 `effectiveComponentDef.id` 를 보간 없이 그대로 내보냈다. 이제 `id` 에 `{{` 가 포함될 때만 iteration 컨텍스트(`$idx`/`item_var` 포함)로 문자열 보간한 `resolvedComponentId` 를 두 DOM 출력 지점이 사용한다(정적 id 는 원본 그대로 — 무영향). slot 등록 키·React remount 키·DevTools 식별자 등 내부 식별에는 원본 `effectiveComponentDef.id` 를 계속 사용해 격리한다. 코드베이스 전역 68개 레이아웃이 id 표현식을 이미 쓰고 있었으나 보간 부재로 깨져 있었고, 본 수정으로 일괄 정상화된다. (배경: 관리자 대시보드의 활동 로그·모듈/플러그인/템플릿 카드 등 반복 목록에서 같은 HTML id 가 행마다 중복 마운트되던 결함.)
|
||||
- 레이아웃 편집기 "요소 ID" 컨트롤(`CoreIdControl`)이 id 값에 데이터바인딩(`{{...}}`)이 있으면 **읽기전용으로 잠가** 편집할 수 없던 동작을, **데이터 칩 편집 허용**으로 변경. iteration 안에서 `id: "item_{{$idx}}"` 처럼 반복 인덱스/행 키를 붙여 항목별 고유 id 를 만들려는 정당한 용도를 막던 제약이었다. 이제 칩 포함 시 평문+칩 혼합 편집기(`BindingChipTextInput`)를 열고, 정적 id 면 후보가 있을 때 `[🔗 데이터]` 진입점을 노출한다. HTML id 안전 문자 제약은 평문 세그먼트에만 적용하고 `{{...}}` 칩 토큰은 보존한다. 데이터 칩 후보 풀(`buildBindingCandidates`)에 **iteration 변수**(`$idx` 등 반복 인덱스·행 데이터 필드)를 추가해, 반복 목록 안의 노드를 편집할 때 `{{$idx}}`/`{{row.id}}` 를 후보로 골라 고유 식별자를 만들 수 있다.
|
||||
- 같은 슬롯 컴포넌트가 **여러 SlotContainer**(헤더 데스크톱/모바일 페어)에서 렌더될 때, 슬롯에 주입된 컴포넌트의 정적 root id 가 컨테이너마다 같은 값으로 중복 출력되어 HTML id 유일성을 위반하던 결함 수정. `SlotContainer` 가 주입 컴포넌트 root id 를 컨테이너 고유 id 로 스코프(`{id}__{containerId}`)해 고유화한다(컨테이너 id 또는 컴포넌트 id 가 없으면 무영향). 이로써 이커머스 헤더 통화·배송국가 셀렉터가 관리자/사용자 헤더의 데스크톱·모바일 SlotContainer 양쪽에 마운트되며 같은 id 로 중복되던 문제가 해소된다.
|
||||
- **placeholder 핸들러 친화 동작(핸들러명을 데이터 칩으로 받는 동작)이 "+동작 추가"·핸들러 변경 시 "알 수 없는 동작"(고급)으로 강등**되던 결함 수정. 핸들러명 자체를 데이터(응답값 등)로 연결하는 동작 레시피(`build.handler` 가 `{{paramKey}}` placeholder)는 빈 값으로 추가하면 `buildAction` 이 그 토큰을 미입력으로 떨궈 `handler` 키 자체가 사라졌고, 핸들러 필드를 다른 데이터 칩으로 바꾸면 구조 식별용 필수 토큰(`params`)까지 함께 사라져 친화 카드 매칭(`matchAction`)이 깨졌다. 그 결과 추가 직후 또는 핸들러를 데이터로 연결한 직후 카드가 [고급]으로 떨어져 코드 편집으로만 수정 가능했다. 이제 `buildAction` 이 ① placeholder 핸들러가 미입력으로 사라지면 build 의 placeholder 토큰을 복원하고 ② placeholder 핸들러 레시피의 **필수(required) 입력 토큰**도 미입력 시 보존하며, `matchAction` 의 placeholder 구조 가드는 **핸들러가 build 의 placeholder 토큰과 글자 그대로 같은 빈 카드**도 인정한다 — 핸들러를 어떤 데이터 칩으로 바꿔도 친화 카드가 유지되고, 저장·새로고침 후에도 친화 카드로 복원된다. 임의의 동적 핸들러 동작(필수 토큰 부재)이 이 레시피로 잘못 흡수되는 것은 그대로 차단된다(greedy 방지 유지). 일반 레시피(리터럴 핸들러)는 무영향(미입력 키 그대로 정리). 데이터/오류/수신 동작 입력의 응답 데이터 칩 후보를 확장 editor-spec(`actionChipCandidates`)이 도메인 응답 필드까지 더할 수 있게 일반화해, apiCall 후속 동작 등에서 확장이 선언한 응답 필드를 데이터 칩으로 연결할 수 있다(코어는 도메인 무지·확장이 선언). (배경: 결제(PG) 진입 동작을 응답이 지정한 핸들러로 dispatch 하도록 만들면서, 핸들러명을 데이터로 연결하는 동작 일반이 편집기에서 친화 편집되지 않던 결함.)
|
||||
|
||||
### Removed
|
||||
|
||||
- MVP 위지윅 잔재 정리 — 캔버스 상단 페이지 제목 배너(더블클릭 인라인 편집·표현식 고급 배지 폐기, 페이지 설정 모달로 진입점 통합), 동작 카드 ▲▼ 순서 버튼(드래그 손잡이로 대체), 데이터 소스 [기본값] raw JSON 직접 입력 모드(블럭 편집으로 통일).
|
||||
- 코어 빌트인 icon-picker 위젯·`IconPickerControl`(라이브러리 종속 → 템플릿 소유로 이양), 코어 색/아이콘 토큰 어휘(전부 템플릿 editor-spec 카탈로그 공급).
|
||||
|
||||
## [engine-v1.49.3] - 2026-05-22
|
||||
|
||||
### Removed
|
||||
|
||||
- (engine-v1.49.3) MVP 위지윅 편집기 제거 — `?mode=edit` 쿼리 기반 편집 모드 분기, `renderWithWysiwygEditor`·`checkEditMode`·`getTemplateIdFromUrl` 헬퍼, `G7Core.wysiwyg` 전역 API(`initWysiwygEditorAPI`) 삭제. 신규 레이아웃 편집기로 대체 예정 (template-engine.ts, G7CoreGlobals.ts)
|
||||
- `?mode=edit` URL 진입 시 일반 렌더로 폴백. `DynamicRenderer` 의 `componentPath`/`data-editor-path` 범용 편집 인프라는 보존
|
||||
|
||||
## [engine-v1.49.2] - 2026-05-07
|
||||
|
||||
### Fixed
|
||||
@@ -46,8 +209,8 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- `TemplateApp.showRouteError` 의 401 가드가 토큰 보유 여부 판정에서 `apiClient.getToken()` 만 사용해 토큰 만료 사용자에게 안내 토스트가 노출되지 않던 문제 수정 — `LayoutLoader` 가 401 시 토큰을 자동 제거하고 재시도하므로 가드 진입 시점에는 항상 토큰이 null. `LayoutLoader` 가 첫 401 시 토큰 보유 상태였음을 `LayoutLoaderError.details.hadToken=true` 로 마킹해 가드로 전달. 가드는 (현재 토큰 보유 OR `details.hadToken === true`) 일 때 `reason='session_expired'` 부여. 익명 방문자 진입은 마킹이 없어 reason 미부여 (정책 유지: 한 번도 로그인하지 않은 사용자에게 "세션 만료" 안내 차단) (Issue #301 후속, LayoutLoader · TemplateApp)
|
||||
- `apiClient.setOnUnauthorized` 콜백이 데이터소스 401 시 로그인 페이지로 redirect 할 때 `reason` 인자를 전달하지 않아 안내 토스트 트리거가 누락되던 문제 수정 — 콜백 발동은 토큰이 서버에서 거부되었음을 의미하므로 항상 `reason='session_expired'` 부여. layout fetch 401 가드와 데이터소스 401 콜백 두 경로 모두 동일한 안내 흐름으로 통일 (Issue #301 후속, TemplateApp)
|
||||
- `TemplateApp.showRouteError` 의 401 가드가 토큰 보유 여부 판정에서 `apiClient.getToken()` 만 사용해 토큰 만료 사용자에게 안내 토스트가 노출되지 않던 문제 수정 — `LayoutLoader` 가 401 시 토큰을 자동 제거하고 재시도하므로 가드 진입 시점에는 항상 토큰이 null. `LayoutLoader` 가 첫 401 시 토큰 보유 상태였음을 `LayoutLoaderError.details.hadToken=true` 로 마킹해 가드로 전달. 가드는 (현재 토큰 보유 OR `details.hadToken === true`) 일 때 `reason='session_expired'` 부여. 익명 방문자 진입은 마킹이 없어 reason 미부여 (정책 유지: 한 번도 로그인하지 않은 사용자에게 "세션 만료" 안내 차단) ( 후속, LayoutLoader · TemplateApp)
|
||||
- `apiClient.setOnUnauthorized` 콜백이 데이터소스 401 시 로그인 페이지로 redirect 할 때 `reason` 인자를 전달하지 않아 안내 토스트 트리거가 누락되던 문제 수정 — 콜백 발동은 토큰이 서버에서 거부되었음을 의미하므로 항상 `reason='session_expired'` 부여. layout fetch 401 가드와 데이터소스 401 콜백 두 경로 모두 동일한 안내 흐름으로 통일 ( 후속, TemplateApp)
|
||||
|
||||
### Notes
|
||||
|
||||
@@ -61,7 +224,7 @@
|
||||
|
||||
### Added
|
||||
|
||||
- 레이아웃 fetch 401 재시도 실패 시 코어가 로그인 페이지로 자동 리다이렉트 (Issue #301) — 토큰 만료/권한 부족으로 레이아웃을 받지 못한 사용자가 "페이지 로딩 실패" 에러 화면 대신 로그인 화면으로 이동하고 `?reason=session_expired` 쿼리로 안내 토스트가 트리거됨. 인증 타입은 `templateId` 또는 pathname 의 `/admin` prefix 로 결정 (TemplateApp.showRouteError)
|
||||
- 레이아웃 fetch 401 재시도 실패 시 코어가 로그인 페이지로 자동 리다이렉트 () — 토큰 만료/권한 부족으로 레이아웃을 받지 못한 사용자가 "페이지 로딩 실패" 에러 화면 대신 로그인 화면으로 이동하고 `?reason=session_expired` 쿼리로 안내 토스트가 트리거됨. 인증 타입은 `templateId` 또는 pathname 의 `/admin` prefix 로 결정 (TemplateApp.showRouteError)
|
||||
- `AuthManager.getLoginRedirectUrl(type, returnUrl, reason?)` 세 번째 옵셔널 인자 — `reason='session_expired'` 등 사유를 쿼리 파라미터로 결합. 기존 호출처는 인자 미지정으로 하위호환 (AuthManager)
|
||||
- `AuthManager.updateConfig(type, partial)` public setter — 템플릿 부트스트랩에서 `loginPath` 등 인증 설정을 사이트 단위로 커스터마이즈 가능. 보안: `loginPath` 는 동일 origin path-only(`/`로 시작, `//` 금지)만 허용 (open redirect 차단 — 외부 origin/protocol-relative URL 은 throw). 모듈/플러그인 호출은 다른 템플릿 침범 위험으로 가이드 문서에서 금지 (AuthManager)
|
||||
|
||||
@@ -98,8 +261,6 @@
|
||||
|
||||
- IdentityGuardInterceptor — HTTP 428 `identity_verification_required` 응답을 감지해 모달 launcher 호출 후 return_request 자동 재실행. launcher 는 S8 공통 모달 레이아웃이 제공. ActionDispatcher.handleApiCall 응답 후처리 한 곳에 정적 메서드로 직접 위임 — 별도 디스패처 인프라 없이 모든 apiCall 의 choke point 효과 (IdentityGuardInterceptor)
|
||||
|
||||
<!-- ⚠️ 버전 재번호 부여 검토 필요 (정책 결정 대기): 아래 v1.43.1 은 시간상 v1.45.0/v1.44.0 보다 늦지만(2026-04-25), develop 브랜치에서 별도 발행되어 버전 번호 모순 발생. v1.45.1 또는 v1.46.0 으로 재번호 검토 필요. -->
|
||||
|
||||
## [engine-v1.43.1] - 2026-04-25
|
||||
|
||||
### Fixed
|
||||
@@ -412,6 +573,15 @@
|
||||
- LayoutLoader: `fetchLayout()`에서 `__preview__/` 접두사 감지 시 프리뷰 전용 API URL 구성
|
||||
- TemplateApp: `__preview__` 레이아웃 감지 시 route params에서 token을 추출하여 layoutPath에 포함
|
||||
|
||||
## [engine-v1.25.1]
|
||||
|
||||
### Fixed
|
||||
|
||||
- blur_until_loaded 래퍼가 CSS Grid 레이아웃을 깨뜨리는 버그 수정 (DynamicRenderer)
|
||||
- blur_until_loaded가 그리드 아이템을 래퍼 div로 감싸면서 col-span-*, row-span-* 등 그리드 클래스가 그리드 컨테이너의 직접 자식이 아니게 되어 적용되지 않음
|
||||
- 그리드 아이템 관련 클래스(col-span-*, row-span-*, self-*, order-* 등)를 blur 래퍼로 자동 전달
|
||||
- 반응형 접두사(sm:, md:, lg:, xl:, 2xl:) 포함 패턴 지원
|
||||
|
||||
## [engine-v1.25.0]
|
||||
|
||||
### Added
|
||||
|
||||
@@ -151,6 +151,23 @@ export class ComponentRegistry {
|
||||
return ComponentRegistry.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 격리 인스턴스 생성 — 싱글톤과 독립된 별도 ComponentRegistry.
|
||||
*
|
||||
* 레이아웃 편집기 캔버스 처럼 한 페이지에서 호스트 템플릿과
|
||||
* 편집 대상 템플릿이 동시에 살아 있어야 하는 케이스용. 싱글톤을 점유 중인
|
||||
* 호스트(`getInstance()`)의 등록 상태와 충돌하지 않도록, 격리 인스턴스는
|
||||
* 정적 manifestCache 만 공유하고 registry/manifest/loadingState 는 자기
|
||||
* 인스턴스 안에만 존재한다.
|
||||
*
|
||||
* `loadComponents()` 등 인스턴스 메서드는 싱글톤과 동일하게 사용 가능.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
public static createIsolatedInstance(): ComponentRegistry {
|
||||
return new ComponentRegistry();
|
||||
}
|
||||
|
||||
/**
|
||||
* 레지스트리 초기화 (테스트용)
|
||||
*/
|
||||
|
||||
@@ -855,6 +855,43 @@ export class DataBindingEngine {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 전체가 단일 `{{...}}` 바인딩인지 판정하고, 그렇다면 내부 식을 반환합니다.
|
||||
*
|
||||
* 종전 `^\{\{([^}]+)\}\}$` 정규식은 식 안에 `}` 가 든 경우(예: 빈 객체 fallback
|
||||
* `{{error.errors ?? {}}}`)를 단일 바인딩으로 인식하지 못해 원본 문자열이 그대로
|
||||
* 새어 나갔다. 본 메서드는 외곽 `{{ }}` 안의 중괄호 균형(depth)을 추적해, 내부에서
|
||||
* 바인딩이 조기 종료(`}}`)되지 않고 끝까지 단일 식으로 닫히는 경우에만 그 식을 반환한다.
|
||||
* `"{{a}} {{b}}"` 처럼 두 개 이상의 바인딩이면 null 을 반환해 문자열 보간 경로로 보낸다.
|
||||
*
|
||||
* @param value 검사할 문자열
|
||||
* @returns 단일 바인딩이면 내부 식 문자열, 아니면 null
|
||||
*/
|
||||
private extractSingleBinding(value: string): string | null {
|
||||
if (!value.startsWith('{{') || !value.endsWith('}}') || value.length < 5) {
|
||||
return null;
|
||||
}
|
||||
const inner = value.slice(2, -2);
|
||||
// inner 를 스캔하며 `}}` 가 깊이 0(외곽 바인딩 종료)에서 등장하면 단일 바인딩 아님.
|
||||
// `{` / `}` 로 깊이를 추적하되, 식 내부의 `{}`(객체 리터럴)는 균형이 맞으므로
|
||||
// 깊이가 음수로 떨어지지 않는 한 단일 바인딩으로 본다.
|
||||
let depth = 0;
|
||||
for (let i = 0; i < inner.length - 1; i++) {
|
||||
const c = inner[i];
|
||||
if (c === '{') {
|
||||
depth++;
|
||||
} else if (c === '}') {
|
||||
if (depth > 0) {
|
||||
depth--;
|
||||
} else if (inner[i + 1] === '}') {
|
||||
// 깊이 0 에서 `}}` 출현 → 외곽 바인딩이 중간에 닫힘 → 다중 바인딩/보간
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
|
||||
/**
|
||||
* 객체 내의 모든 바인딩 표현식을 데이터로 치환
|
||||
*
|
||||
@@ -921,10 +958,13 @@ export class DataBindingEngine {
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
// 전체가 {{variable}} 패턴인 경우 원본 값(배열/객체) 반환
|
||||
const singleBindingMatch = value.match(/^\{\{([^}]+)\}\}$/);
|
||||
if (singleBindingMatch) {
|
||||
const path = singleBindingMatch[1].trim();
|
||||
// 전체가 {{variable}} 패턴인 경우 원본 값(배열/객체) 반환.
|
||||
// `[^}]+` 는 `{{error.errors ?? {}}}` 처럼 식 안에 `}` 가 든 경우(빈 객체 fallback 등)
|
||||
// 첫 `}` 에서 끊겨 매칭에 실패 → 원본 문자열이 그대로 새어 나오던 결함이 있었다.
|
||||
// extractSingleBinding 은 외곽 `{{ }}` 안의 중괄호 균형을 추적해 단일 바인딩 식을 정확히 추출한다.
|
||||
const singleBindingPath = this.extractSingleBinding(value);
|
||||
if (singleBindingPath !== null) {
|
||||
const path = singleBindingPath.trim();
|
||||
|
||||
// raw: 접두사 감지 @since engine-v1.27.0
|
||||
let isRawBinding = false;
|
||||
@@ -1398,6 +1438,11 @@ export class DataBindingEngine {
|
||||
'this', 'super', 'import', 'export', 'default', 'try', 'catch', 'finally', 'throw',
|
||||
// 내장 객체
|
||||
'Math', 'Date', 'JSON', 'Array', 'Object', 'String', 'Number', 'Boolean', 'RegExp',
|
||||
// 컬렉션/표준 내장 객체 (@since engine-v1.50.0)
|
||||
// 이들이 reserved 에 없으면 컨텍스트 변수로 오인되어 undefined 로 가려지고
|
||||
// new Function 본문에서 `new Set(...)` 가 `new undefined()` 가 되어 실패한다.
|
||||
// eval/Function/globalThis/window 등 위험 전역은 의도적으로 제외한다.
|
||||
'Set', 'Map', 'WeakSet', 'WeakMap', 'Symbol', 'Promise', 'BigInt', 'Error',
|
||||
// 전역 함수
|
||||
'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'encodeURI', 'decodeURI',
|
||||
'encodeURIComponent', 'decodeURIComponent',
|
||||
|
||||
@@ -623,6 +623,24 @@ export interface DataSource {
|
||||
* ```
|
||||
*/
|
||||
onSuccess?: OnSuccessHandler;
|
||||
|
||||
/**
|
||||
* 출처 메타 (편집 모드 전용 — engine-v1.50.0+)
|
||||
*
|
||||
* 레이아웃 편집기가 `with_source_meta=1` 로 요청할 때만 백엔드가 부여하는
|
||||
* 소유 확장 식별 메타입니다. 동일 `id` 를 가진 data_source 가 여러 출처
|
||||
* (템플릿/모듈/플러그인)에 정의되어 충돌할 때, 샘플 데이터 해소
|
||||
* (`sampleDataProvider`)가 자기 출처의 샘플을 우선 선택하도록 합니다.
|
||||
*
|
||||
* 일반 렌더 경로에는 부여되지 않으며 저장 시 sanitize 에서 제외되므로
|
||||
* 영속 레이아웃 JSON 에는 포함되지 않습니다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
__source?: {
|
||||
kind: 'template' | 'module' | 'plugin' | 'core' | 'base' | 'route';
|
||||
identifier?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -673,6 +691,55 @@ export interface DataSourceManagerOptions {
|
||||
* 에러 발생 시 호출될 콜백
|
||||
*/
|
||||
onError?: (error: Error, source: DataSource) => void;
|
||||
|
||||
/**
|
||||
* 샘플 데이터 프로바이더 (편집 모드 전용)
|
||||
*
|
||||
* 옵션이 주입되면 `fetchApiDataSource` 가 네트워크 fetch 대신 프로바이더의
|
||||
* `resolve()` 결과를 반환한다. 일반 렌더 모드(편집기 외) 부팅에서는 옵션을
|
||||
* 전달하지 않으므로 기존 동작 100% 보존. 계획서 참조.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
sampleProvider?: SampleDataProvider;
|
||||
|
||||
/**
|
||||
* onSuccess 핸들러 실행에 사용할 ActionDispatcher (편집 모드 전용)
|
||||
*
|
||||
* 옵션이 주입되면 `executeOnSuccessHandler` 가 전역 `getActionDispatcher()` 대신
|
||||
* 본 dispatcher 를 사용한다. 일반 렌더 모드는 옵션 미전달 → 기존 동작 보존.
|
||||
*
|
||||
* 동기: PreviewCanvas 가 자체 DataSourceManager 인스턴스를 만들지만, 그 인스턴스
|
||||
* 의 onSuccess 핸들러가 호스트 ActionDispatcher 를 호출하면 호스트 `setGlobalState`
|
||||
* 가 발화되어 호스트 `#app` 이 통째로 unmount 되는 결함이 발생한다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
actionDispatcher?: import('./ActionDispatcher').ActionDispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* 샘플 데이터 프로바이더 인터페이스 — 편집 모드 캔버스 전용
|
||||
*
|
||||
* `useSampleData` 가 병합 `editorSpec.sampleData`(byDataSourceId / bySource /
|
||||
* byEndpointPattern) 로 구성한 뒤 편집 모드 부팅 시 `DataSourceManager` 옵션으로
|
||||
* 주입한다. 미매칭 데이터소스는 도메인-중립 빈 응답으로 디그레이드한다
|
||||
* (코어 키워드 프리셋 폐기 —-v1.50.0).
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
export interface SampleDataProvider {
|
||||
/**
|
||||
* 데이터소스 ID 가 샘플 모드의 매칭 후보인지 확인.
|
||||
* `false` 면 일반 fetch 경로(네트워크) 로 폴백.
|
||||
*/
|
||||
has(dataSourceId: string): boolean;
|
||||
|
||||
/**
|
||||
* 데이터소스에 대해 샘플 데이터를 동기/비동기로 반환.
|
||||
* 반환값은 일반 API 응답과 같은 shape 이어야 한다(`{ data: [...] }` 등).
|
||||
*/
|
||||
resolve(dataSource: DataSource): unknown | Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -927,8 +994,17 @@ export class DataSourceManager {
|
||||
const results: Record<string, any> = {};
|
||||
|
||||
// auto_fetch가 true인 데이터 소스만 처리 (websocket 타입 제외)
|
||||
//
|
||||
// 샘플 모드(편집기) 예외: auto_fetch:false 인 지연 소스(탭/모달 활성 시 런타임에
|
||||
// fetch)는 정적 시뮬레이션인 편집기 캔버스에서 활성화 액션을 실행할 수 없어, 페이지
|
||||
// 상태로 게이트를 열어도 데이터가 비어 본체가 미렌더된다(myComments
|
||||
// 내댓글 서브탭). 샘플 모드에서는 지연 소스도 샘플 주입 대상에 포함해 게이트 노출 시
|
||||
// 본체가 렌더되게 한다(런타임 동작과 정합 — 런타임은 탭 활성 시 동일 데이터를 fetch).
|
||||
// 일반 렌더 모드(sampleProvider 미주입)는 기존 auto_fetch 필터를 100% 보존한다.
|
||||
const inSampleMode = !!this.options.sampleProvider;
|
||||
const autoFetchSources = sources.filter(
|
||||
(source) => source.auto_fetch !== false && source.type !== 'websocket'
|
||||
(source) =>
|
||||
(inSampleMode || source.auto_fetch !== false) && source.type !== 'websocket'
|
||||
);
|
||||
|
||||
// 병렬 처리
|
||||
@@ -1418,6 +1494,13 @@ export class DataSourceManager {
|
||||
globalState?: Record<string, any>,
|
||||
localState?: Record<string, any>,
|
||||
): Promise<any> {
|
||||
// 샘플 모드 분기 — 편집기 부팅 시에만 옵션이 주입됨.
|
||||
// 일반 렌더 모드는 옵션 미주입이므로 이 분기에 진입하지 않아 기존 fetch 경로 100% 보존.
|
||||
if (this.options.sampleProvider?.has(source.id)) {
|
||||
const sample = await Promise.resolve(this.options.sampleProvider.resolve(source));
|
||||
return sample;
|
||||
}
|
||||
|
||||
if (!source.endpoint) {
|
||||
throw new Error(`API data source ${source.id} has no endpoint`);
|
||||
}
|
||||
@@ -1900,7 +1983,10 @@ export class DataSourceManager {
|
||||
onSuccess: OnSuccessHandler,
|
||||
successContext: SuccessContext
|
||||
): Promise<void> {
|
||||
const actionDispatcher = getActionDispatcher();
|
||||
// 옵션 주입된 dispatcher 우선 (편집기 격리 모드), 없으면 전역 호스트 dispatcher
|
||||
// (편집기 캔버스의 onSuccess setState 가 호스트 globalState
|
||||
// 를 변경해 호스트 #app 이 unmount 되는 결함 방지)
|
||||
const actionDispatcher = this.options.actionDispatcher ?? getActionDispatcher();
|
||||
|
||||
if (!actionDispatcher) {
|
||||
logger.warn('ActionDispatcher not available, skipping onSuccess handler');
|
||||
|
||||
@@ -50,6 +50,44 @@ function getDevTools(): G7DevToolsInterface | undefined {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 값(객체/배열/문자열) 내부의 `$t:` 토큰을 재귀적으로 해석한다.
|
||||
*
|
||||
* `extensionPointProps` 처럼 일반 props 와 별도로 평가되어 자식 컴포넌트의
|
||||
* 핸들러로 전달되는 값에서 `$t:board.form.content_placeholder` 같은 평문 i18n
|
||||
* 키를 풀어준다. 일반 props 의 `resolveTranslationsDeep` 와 동일 의미.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
function resolveTranslationsInValue(
|
||||
value: any,
|
||||
translationEngine: TranslationEngine,
|
||||
translationContext: TranslationContext,
|
||||
dataContext: Record<string, any>,
|
||||
): any {
|
||||
if (typeof value === 'string') {
|
||||
if (/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(value)) {
|
||||
try {
|
||||
return translationEngine.resolveTranslations(value, translationContext, dataContext);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => resolveTranslationsInValue(item, translationEngine, translationContext, dataContext));
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const result: Record<string, any> = {};
|
||||
for (const [k, v] of Object.entries(value)) {
|
||||
result[k] = resolveTranslationsInValue(v, translationEngine, translationContext, dataContext);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
import { responsiveManager } from './ResponsiveManager';
|
||||
import { FormProvider, FormContextValue, useFormContext, getNestedValue, setNestedValue } from './FormContext';
|
||||
import { SlotProvider } from './SlotContext';
|
||||
@@ -1418,6 +1456,11 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
text: override.text ?? baseDef.text,
|
||||
if: override.if ?? baseDef.if,
|
||||
iteration: override.iteration ?? baseDef.iteration,
|
||||
// 편집기 path 발급용 — 자식이 **분기 children 으로 교체**된 경우에만 분기 키를
|
||||
// 남긴다(자식 path 에 `.responsive.{key}` prefix 를 끼워 base children 과 구분).
|
||||
// props-만 오버라이드(override.children 부재)는 base children 그대로라 base path
|
||||
// 유지.
|
||||
__responsiveChildrenKey: override.children !== undefined ? matchedKey : undefined,
|
||||
};
|
||||
}, [componentDef, responsiveWidth]);
|
||||
|
||||
@@ -1672,12 +1715,20 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
// extension_point 컴포넌트의 props가 주입된 컴포넌트에서 {{extensionPointProps.xxx}}로 접근 가능
|
||||
// LayoutExtensionService에서 extension_point의 props를 injectedComponent.extensionPointProps에 추가
|
||||
// @since engine-v1.28.0: resolveObject()로 표현식 재귀 평가 (일반 props와 동일 수준)
|
||||
// @since engine-v1.50.0: **편집 모드 전용** `$t:` 키 2차
|
||||
// 해석 — `extensionPointProps.placeholder: "$t:board.form.content_placeholder"`
|
||||
// 같은 평문 i18n 키를 핸들러(예: ckeditor5 initEditor) 가 받기 전에 풀어
|
||||
// 편집기 캔버스에서 raw 키로 노출되지 않도록 한다. 일반 사이트 렌더는
|
||||
// `isEditMode === false` 라 본 분기 미진입 → 동작 100% 보존.
|
||||
if (componentDef.extensionPointProps) {
|
||||
result.extensionPointProps = bindingEngine.resolveObject(
|
||||
const resolved = bindingEngine.resolveObject(
|
||||
componentDef.extensionPointProps,
|
||||
result,
|
||||
isInsideIteration ? { skipCache: true } : undefined
|
||||
);
|
||||
result.extensionPointProps = isEditMode && translationEngine
|
||||
? resolveTranslationsInValue(resolved, translationEngine, translationContext, result)
|
||||
: resolved;
|
||||
}
|
||||
|
||||
// extensionPointCallbacks가 있으면 데이터 컨텍스트에 추가 (평가 없이 그대로 전달)
|
||||
@@ -1687,6 +1738,28 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
result.extensionPointCallbacks = componentDef.extensionPointCallbacks;
|
||||
}
|
||||
|
||||
// **편집 모드 전용** $templateId / $locale 자동 주입 — `{{삼항 ? '$t:A' : '$t:B'}}`
|
||||
// 같은 표현식의 `$t()` 함수가 templateId 폴백을 위해
|
||||
// `window.__templateApp.getConfig()` 를 호출하지 않고 컨텍스트에서 바로 가져올
|
||||
// 수 있도록 보장.
|
||||
//
|
||||
// 동기: 편집기 캔버스의 격리 `__templateApp` façade 에는 `getConfig` 가 없어
|
||||
// 폴백이 빈 templateId 를 반환 → 사전 조회 실패 → raw key 노출. dataContext 에
|
||||
// `$templateId` 가 미리 있으면 그 값을 우선 사용한다(DataBindingEngine 의
|
||||
// `$t` 함수 line 1145). 일반 사이트 렌더는 `isEditMode === false` 이므로 본
|
||||
// 분기 미진입 → 호스트 `window.__templateApp.getConfig()` fallback 그대로 사용.
|
||||
//
|
||||
// @since engine-v1.50.0 (라우트 10/12 글쓰기/글수정 i18n
|
||||
// `$t:board.write` raw 키 노출 결함 수정. 호스트 사이트 영향 0)
|
||||
if (isEditMode) {
|
||||
if (result.$templateId === undefined && translationContext?.templateId) {
|
||||
result.$templateId = translationContext.templateId;
|
||||
}
|
||||
if (result.$locale === undefined && translationContext?.locale) {
|
||||
result.$locale = translationContext.locale;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
// parentContextHook?.version: $parent._local 변경 시 useMemo 재계산 트리거
|
||||
// effectiveParentDataContext는 동일한 객체 참조를 반환할 수 있으므로
|
||||
@@ -2261,9 +2334,15 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
}
|
||||
|
||||
// 3. 액션 바인딩 (공유 유틸리티 함수 사용)
|
||||
//
|
||||
// 편집 모드에서는 navigate/apiCall/openModal 등 모든 액션을 발동하지
|
||||
// 않는다 — actions 를 undefined 로 넘겨 바인딩 자체를 건너뛴다. 편집 모드의
|
||||
// 클릭은 오직 "요소 선택" 만 의미하며, 액션 발동은 운영 화면에서만 일어난다.
|
||||
// (편집 모드 진입 시 actions JSON 값은 보존된 채 단지 onClick 핸들러로 변환되지
|
||||
// 않을 뿐이므로 무손실. 저장 시 그대로 직렬화됨.)
|
||||
props = bindComponentActions(
|
||||
props,
|
||||
effectiveComponentDef.actions,
|
||||
isEditMode ? undefined : effectiveComponentDef.actions,
|
||||
extendedDataContext,
|
||||
{ componentContext, actionDispatcher }
|
||||
);
|
||||
@@ -2375,6 +2454,27 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
return resolvedProps;
|
||||
}, [resolvedProps]);
|
||||
|
||||
/**
|
||||
* DOM id 표현식 해석 (engine-v1.52.4)
|
||||
*
|
||||
* 노드의 최상위 `id` 필드는 props 가 아니므로 props 바인딩 경로를 타지 않는다.
|
||||
* iteration 내부에서 `id: "item_{{$idx}}"` 처럼 표현식을 쓰면 각 row 마다
|
||||
* 고유 DOM id 가 되어야 하지만, 보간 없이 그대로 출력되면 같은 리터럴이
|
||||
* row 마다 반복되어 W3C HTML id 중복을 유발한다.
|
||||
*
|
||||
* `{{` 가 포함된 경우에만 extendedDataContext($idx 등 iteration 변수 포함)로
|
||||
* 문자열 보간한다. 표현식이 없는 정적 id 는 원본을 그대로 반환하여 비용을 회피한다.
|
||||
* 이 값은 DOM 출력 전용이며, slot 등록·DevTools 등 내부 식별에는 원본 id 를 계속 사용한다.
|
||||
*/
|
||||
const resolvedComponentId = useMemo(() => {
|
||||
const rawId = effectiveComponentDef.id;
|
||||
if (typeof rawId !== 'string' || !rawId.includes('{{')) {
|
||||
return rawId;
|
||||
}
|
||||
const resolved = bindingEngine.resolveBindings(rawId, extendedDataContext, { skipCache: true });
|
||||
return typeof resolved === 'string' ? resolved : rawId;
|
||||
}, [effectiveComponentDef.id, extendedDataContext, bindingEngine]);
|
||||
|
||||
/**
|
||||
* 자식에게 전달할 FormContext
|
||||
*
|
||||
@@ -2544,7 +2644,13 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
// 자식 컴포넌트에도 componentContext와 formContext를 전달하여 상태 공유
|
||||
// extendedDataContext를 전달하여 _local 상태를 자식에게도 공유
|
||||
// componentPath를 누적하여 자식에게 전달 (WYSIWYG 편집기용)
|
||||
const childPath = componentPath ? `${componentPath}.children.${index}` : `${index}`;
|
||||
// 자식이 responsive 분기 children 으로 교체된 경우, 편집 path 에 분기 출처를
|
||||
// 명시한다: `{부모}.responsive.{key}.children.{N}`. 그래야 편집기가 base children
|
||||
// 의 같은 인덱스 노드가 아니라 보이는 분기 노드를 정확히 선택·패치한다.
|
||||
// base children(분기 키 부재)은 종전 `.children.{N}` 형식 유지.
|
||||
const branchKey = (effectiveComponentDef as any).__responsiveChildrenKey as string | undefined;
|
||||
const childrenPathSeg = branchKey ? `responsive.${branchKey}.children` : 'children';
|
||||
const childPath = componentPath ? `${componentPath}.${childrenPathSeg}.${index}` : `${index}`;
|
||||
|
||||
// @since engine-v1.24.8 _fromBase children은 stable key → 보존(update)
|
||||
// non-_fromBase children은 layoutKey suffix로 페이지 전환 시 remount 보장
|
||||
@@ -3569,7 +3675,7 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
|
||||
return (
|
||||
<div
|
||||
id={effectiveComponentDef.id}
|
||||
id={resolvedComponentId}
|
||||
className={containerClass || undefined}
|
||||
{...restProps}
|
||||
>
|
||||
@@ -3596,7 +3702,7 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
const remountKeys = dataContext._global?._remountKeys;
|
||||
const finalProps: Record<string, any> = {
|
||||
...propsWithAutoBinding,
|
||||
id: propsWithAutoBinding.id ?? effectiveComponentDef.id,
|
||||
id: propsWithAutoBinding.id ?? resolvedComponentId,
|
||||
// _remountKeys가 변경되면 React가 props 변경을 감지하여 컴포넌트 리렌더링
|
||||
// cellChildren 내부의 컴포넌트가 새 key를 받을 수 있도록 함
|
||||
...(remountKeys && Object.keys(remountKeys).length > 0 && {
|
||||
@@ -3619,73 +3725,123 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
}
|
||||
}
|
||||
|
||||
// 편집 모드일 때 data-editor-id 속성 추가
|
||||
// 편집 모드일 때 data-editor-* 표식 + 선택/hover 핸들러 주입
|
||||
//
|
||||
// @since engine-v1.50.0 — 주입분을 단일 `editorAttrs` 객체로도 묶어
|
||||
// 전달한다. composite/layout 컴포넌트는 도메인 prop 만 명시 구조분해하고 미명시
|
||||
// props 를 DOM 으로 흘리지 않으므로, 개별 키 주입만으로는 `data-editor-*`/핸들러가
|
||||
// 유실되어 그 노드가 편집기의 드롭 슬롯/선택/드래그 대상에서 누락됐다.
|
||||
// 각 nesting 컴포넌트가 `editorAttrs` 를 받아 시각적 루트에 spread 하면 유실이 해소된다.
|
||||
// basic 컴포넌트(`{...props}` 패스스루)는 아래 개별 키 주입으로 종전대로 동작하며,
|
||||
// `editorAttrs` 객체 키는 basic/layout DOM-safe 필터(아래)에서 제외해 DOM 누출을 막는다.
|
||||
if (isEditMode) {
|
||||
// id가 없는 컴포넌트에 자동 ID 생성 (컴포넌트 타입과 랜덤 문자열 기반)
|
||||
const editorId =
|
||||
effectiveComponentDef.id ||
|
||||
`auto_${effectiveComponentDef.name || effectiveComponentDef.type || 'unknown'}_${Math.random().toString(36).substring(2, 8)}`;
|
||||
|
||||
finalProps['data-editor-id'] = editorId;
|
||||
finalProps['data-editor-name'] = effectiveComponentDef.name;
|
||||
finalProps['data-editor-type'] = effectiveComponentDef.type;
|
||||
// 인덱스 경로 추가 (ID 없는 컴포넌트 편집용)
|
||||
if (componentPath) {
|
||||
finalProps['data-editor-path'] = componentPath;
|
||||
}
|
||||
|
||||
// 편집 모드 클릭 핸들러 (기존 onClick과 병합)
|
||||
const originalOnClick = finalProps.onClick;
|
||||
finalProps.onClick = (e: React.MouseEvent) => {
|
||||
// 편집기 선택 핸들러 호출
|
||||
// 편집 모드 클릭 핸들러
|
||||
// - 편집 모드에서는 그 컴포넌트의 모든 액션이 발동되지 않는다 (위에서
|
||||
// bindComponentActions 에 actions=undefined 전달로 가로채짐).
|
||||
// - 추가로 `<a href>` 의 기본 브라우저 네비게이션을 막기 위해 preventDefault.
|
||||
// - 클릭 의미는 오직 "요소 선택" — onComponentSelect 만 호출.
|
||||
const editorOnClick = (e: React.MouseEvent) => {
|
||||
// <a href> 기본 네비게이션 차단 — 전체 페이지 리로드 방지
|
||||
// (편집 모드에서 전체 화면 리프레시가 일어나서는 안 된다)
|
||||
if (typeof e.preventDefault === 'function') {
|
||||
e.preventDefault();
|
||||
}
|
||||
if (onComponentSelect) {
|
||||
e.stopPropagation();
|
||||
onComponentSelect(editorId, e);
|
||||
}
|
||||
// 기존 onClick도 실행
|
||||
if (typeof originalOnClick === 'function') {
|
||||
originalOnClick(e);
|
||||
}
|
||||
};
|
||||
|
||||
// editorAttrs 단일 객체 — composite/layout 컴포넌트가 명시 수신 후 루트에 spread.
|
||||
const editorAttrs: Record<string, unknown> = {
|
||||
'data-editor-id': editorId,
|
||||
'data-editor-name': effectiveComponentDef.name,
|
||||
'data-editor-type': effectiveComponentDef.type,
|
||||
onClick: editorOnClick,
|
||||
};
|
||||
// 인덱스 경로 추가 (ID 없는 컴포넌트 편집용)
|
||||
if (componentPath) {
|
||||
editorAttrs['data-editor-path'] = componentPath;
|
||||
}
|
||||
// 슬롯 마커 — 공통(base) 레이아웃 편집 시 자식 콘텐츠가 삽입될 슬롯
|
||||
// 위치(`slot: "content"` 등)를 편집기 오버레이/CSS 가 시각화할 수 있도록 슬롯 이름을
|
||||
// DOM 속성으로 노출한다. base 편집 캔버스는 슬롯 노드가 SlotContext 의 원위치 미렌더
|
||||
// (`return null`)에 걸리지 않도록 PreviewCanvas 가 `slot` 키를 표시 마커
|
||||
// `__editorSlotName` 으로 치환해 공급하므로 마커를 우선 읽는다. 편집 모드(editorAttrs
|
||||
// 부여 시)에만 추가 — 운영 렌더 영향 0.
|
||||
const slotMarker =
|
||||
(effectiveComponentDef as { __editorSlotName?: unknown }).__editorSlotName ??
|
||||
(effectiveComponentDef as { slot?: unknown }).slot;
|
||||
if (typeof slotMarker === 'string') {
|
||||
editorAttrs['data-editor-slot'] = slotMarker;
|
||||
}
|
||||
|
||||
// 편집 모드 호버 핸들러
|
||||
// onMouseMove + stopPropagation을 사용하여 가장 안쪽(자식) 컴포넌트가 우선 하이라이트되도록 함
|
||||
if (onComponentHover) {
|
||||
finalProps.onMouseMove = (e: React.MouseEvent) => {
|
||||
editorAttrs.onMouseMove = (e: React.MouseEvent) => {
|
||||
e.stopPropagation(); // 부모 컴포넌트로 이벤트 전파 방지
|
||||
onComponentHover(editorId, e);
|
||||
};
|
||||
finalProps.onMouseLeave = (e: React.MouseEvent) => {
|
||||
editorAttrs.onMouseLeave = (e: React.MouseEvent) => {
|
||||
onComponentHover(null, e);
|
||||
};
|
||||
}
|
||||
|
||||
// 편집 모드 드래그 핸들러 (프리뷰 캔버스에서 드래그 앤 드롭)
|
||||
finalProps.draggable = true;
|
||||
// (1) basic 컴포넌트(`{...props}` 패스스루)용 — 개별 키 주입 유지.
|
||||
Object.assign(finalProps, editorAttrs);
|
||||
// (2) composite/layout 컴포넌트용 — 단일 객체 주입(명시 수신 → 루트 spread).
|
||||
finalProps.editorAttrs = editorAttrs;
|
||||
|
||||
if (onDragStart) {
|
||||
finalProps.onDragStart = (e: React.DragEvent) => {
|
||||
e.stopPropagation(); // 부모 컴포넌트로 이벤트 전파 방지
|
||||
onDragStart(editorId, e);
|
||||
};
|
||||
}
|
||||
|
||||
if (onDragEnd) {
|
||||
finalProps.onDragEnd = (e: React.DragEvent) => {
|
||||
onDragEnd(e);
|
||||
};
|
||||
}
|
||||
// 드래그(draggable/onDragStart/onDragEnd) props 주입은 제거됨.
|
||||
// - 끌어 이동은 `DndCanvasLayer` 가 `[data-editor-path]` 를 DOM 쿼리해 투명 드래그
|
||||
// 핸들 오버레이를 얹고 dnd-kit PointerSensor 로 처리한다.
|
||||
// - `PreviewCanvas` 는 DynamicRenderer 에 onDragStart/onDragEnd 를 전달하지 않으므로
|
||||
// 기존 `if (onDragStart)` 블록은 이미 죽은 경로였고, native `draggable=true` 는
|
||||
// HTML5 drag 와 dnd-kit pointer drag 가 동시에 걸리는 충돌 표면일 뿐이었다.
|
||||
// 호출 그래프 전수 확인 후 제거(engine-regression-code-first 규율). @since engine-v1.50.0
|
||||
}
|
||||
|
||||
// 컴포넌트 렌더링
|
||||
// Basic/Layout 컴포넌트는 HTML 요소를 직접 렌더링하므로
|
||||
// 내부 props(__componentContext 등)를 DOM에 전달하면 [object Object]로 노출됨
|
||||
// Composite 컴포넌트(React 컴포넌트)는 내부 props를 직접 처리하므로 그대로 전달
|
||||
const isBasicOrLayoutComponent = effectiveComponentDef.type === 'basic' || effectiveComponentDef.type === 'layout';
|
||||
//
|
||||
// @since engine-v1.50.0 `__` 시작 키 일괄 차단 안전망.
|
||||
// 백엔드가 `with_source_meta=1` 옵션 응답에 `__source` 메타를 부여할 수 있으며,
|
||||
// 일반 사이트 렌더에도 만일의 누수가 발생해도 React props 로 전달되지 않도록 차단.
|
||||
const isBasicComponent = effectiveComponentDef.type === 'basic';
|
||||
const isLayoutComponent = effectiveComponentDef.type === 'layout';
|
||||
const isBasicOrLayoutComponent = isBasicComponent || isLayoutComponent;
|
||||
const propsForRendering = isBasicOrLayoutComponent
|
||||
? (() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { __componentContext, __componentLayoutDefs, ...domSafeProps } = finalProps;
|
||||
const domSafeProps: Record<string, any> = {};
|
||||
for (const [key, value] of Object.entries(finalProps)) {
|
||||
// `__` 접두사는 G7 내부 메타 전용 약속 — DOM 노출 차단(basic/layout 공통)
|
||||
if (key.startsWith('__')) {
|
||||
continue;
|
||||
}
|
||||
// `editorAttrs` 객체 키 처리 — **타입별로 다르다**:
|
||||
// - **basic**: `{...props}` 패스스루라 `editorAttrs` 가 그대로 DOM 에 흘러
|
||||
// `<div editorAttrs={..}>` 누출 + React 경고 → **제거**. 편집 표식은
|
||||
// 위 Object.assign 으로 주입한 개별 `data-editor-*` 키가 담당(basic 이 spread).
|
||||
// - **layout**: Container/Flex/Grid 등은 도메인 prop 만 명시 구조분해하고
|
||||
// `{...props}` 패스스루를 **안 하므로** 개별 `data-editor-*` 키가 DOM 에
|
||||
// 도달하지 못한다. 대신 `editorAttrs` 를 **명시 수신해 루트에 spread** 하므로
|
||||
// 이 키를 **남겨야** 한다(제거하면 layout 노드가 편집기에서 누락 — 컨테이너
|
||||
// 바깥 드롭존 소실의 원인.). DOM 누출은 컴포넌트가 editorAttrs 만
|
||||
// spread 하고 객체 자체를 DOM 에 안 흘리므로 발생하지 않는다.
|
||||
// @since engine-v1.50.0
|
||||
if (key === 'editorAttrs' && isBasicComponent) {
|
||||
continue;
|
||||
}
|
||||
domSafeProps[key] = value;
|
||||
}
|
||||
return domSafeProps;
|
||||
})()
|
||||
: finalProps;
|
||||
@@ -3866,6 +4022,60 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* blur_until_loaded 래퍼에 전달할 그리드 아이템 클래스 추출
|
||||
*
|
||||
* CSS Grid에서 col-span, row-span 등은 그리드 컨테이너의 직접 자식에만 적용됩니다.
|
||||
* blur_until_loaded가 래퍼 div를 생성하면 그리드 레이아웃이 깨지므로,
|
||||
* 그리드 아이템 관련 클래스를 래퍼로 전달합니다.
|
||||
*
|
||||
* @since engine-v1.17.6
|
||||
*
|
||||
* 중요: Rules of Hooks 준수 — 아래 early return(slot 조건) 보다 먼저 호출되어야 함.
|
||||
* 같은 컴포넌트에서 렌더 경로가 달라지더라도 hook 호출 순서/개수가 일관되어야 한다.
|
||||
*/
|
||||
const getBlurWrapperClasses = useMemo(() => {
|
||||
if (!effectiveComponentDef.blur_until_loaded) {
|
||||
return { wrapperClasses: '', innerClasses: '' };
|
||||
}
|
||||
|
||||
const className = resolvedProps?.className || '';
|
||||
if (!className) {
|
||||
return { wrapperClasses: '', innerClasses: '' };
|
||||
}
|
||||
|
||||
// 그리드 아이템/플렉스 아이템 관련 클래스 패턴
|
||||
// - col-span-*, row-span-*: 그리드 셀 확장
|
||||
// - col-start-*, col-end-*, row-start-*, row-end-*: 그리드 위치
|
||||
// - self-*, place-self-*: 아이템 정렬
|
||||
// - order-*: 순서
|
||||
// - flex-shrink-*, flex-grow-*, flex-*: 플렉스 아이템
|
||||
// 반응형 접두사 포함: sm:, md:, lg:, xl:, 2xl:
|
||||
const gridItemPatterns = [
|
||||
/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,
|
||||
/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,
|
||||
/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/,
|
||||
];
|
||||
|
||||
const classes = className.split(/\s+/).filter(Boolean);
|
||||
const wrapperClassList: string[] = [];
|
||||
const innerClassList: string[] = [];
|
||||
|
||||
for (const cls of classes) {
|
||||
const isGridItemClass = gridItemPatterns.some(pattern => pattern.test(cls));
|
||||
if (isGridItemClass) {
|
||||
wrapperClassList.push(cls);
|
||||
} else {
|
||||
innerClassList.push(cls);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
wrapperClasses: wrapperClassList.join(' '),
|
||||
innerClasses: innerClassList.join(' '),
|
||||
};
|
||||
}, [effectiveComponentDef.blur_until_loaded, resolvedProps?.className]);
|
||||
|
||||
/**
|
||||
* slot 속성이 있는 컴포넌트는 원래 위치에서 렌더링하지 않음
|
||||
*
|
||||
@@ -3887,7 +4097,10 @@ const DynamicRenderer: React.FC<DynamicRendererProps> = memo(
|
||||
componentName={componentDef.name}
|
||||
>
|
||||
{effectiveComponentDef.blur_until_loaded ? (
|
||||
<div className={shouldApplyBlur ? "opacity-50 blur-sm transition-all duration-300 pointer-events-none" : undefined}>
|
||||
<div className={[
|
||||
getBlurWrapperClasses.wrapperClasses,
|
||||
shouldApplyBlur ? "opacity-50 blur-sm transition-all duration-300 pointer-events-none" : undefined
|
||||
].filter(Boolean).join(' ') || undefined}>
|
||||
{renderComponent}
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -157,7 +157,11 @@ export interface G7DevToolsInterface {
|
||||
}): void;
|
||||
|
||||
/** 네트워크 요청 시작 추적 */
|
||||
trackRequest(url: string, method: string): string;
|
||||
trackRequest(
|
||||
url: string,
|
||||
method: string,
|
||||
options?: { requestBody?: any; dataSourceId?: string },
|
||||
): string;
|
||||
|
||||
/** 네트워크 요청 완료 추적 */
|
||||
completeRequest(requestId: string, statusCode: number, response?: any): void;
|
||||
@@ -170,6 +174,10 @@ export interface G7DevToolsInterface {
|
||||
id: string;
|
||||
type: 'api' | 'static' | 'route_params' | 'query_params' | 'websocket';
|
||||
endpoint?: string;
|
||||
method?: string;
|
||||
autoFetch?: boolean;
|
||||
initLocal?: any;
|
||||
initGlobal?: any;
|
||||
}): void;
|
||||
|
||||
/** 데이터소스 로딩 시작 추적 */
|
||||
@@ -737,6 +745,49 @@ function initComponentEventSystem(G7Core: any): void {
|
||||
logger.log('전역 객체 window.G7Core.componentEvent에 노출됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* `G7Core.layoutEditor` 예약 접수함(ready 큐) 초기화 —.
|
||||
*
|
||||
* 레이아웃 편집기 확장점(`registerWidget`/`registerNodeEditor`/`registerCanvasOverlay`)은
|
||||
* 편집기 셸(lazy 번들)이 로드될 때 `exposeLayoutEditorGlobals` 가 **실제 레지스트리 함수**로
|
||||
* 노출한다. 그러나 템플릿 `initTemplate` 은 편집기 로드 **이전**에 실행되므로, 그 시점에
|
||||
* `G7Core.layoutEditor` 가 없으면 등록이 허공으로 사라진다.
|
||||
*
|
||||
* 이를 막기 위해 메인 번들에서 **경량 stub** 을 항상 먼저 노출한다. stub 의 register* 는
|
||||
* 등록 요청을 `__queue` 에 적재만 하고, `onReady(cb)` 는 `__readyCallbacks` 에 예약한다.
|
||||
* 편집기 셸 로드 시 `exposeLayoutEditorGlobals` 가 실제 함수로 교체하면서 `__queue` 를
|
||||
* 일괄 flush + `__readyCallbacks` 호출한다(그 후의 호출은 즉시 등록). 이미 실제 API 가
|
||||
* 노출돼 있으면(편집기 먼저 로드) stub 으로 덮지 않는다.
|
||||
*
|
||||
* 메인 번들 추가분은 함수 3개 + 배열 2개뿐(번들 비대화 ~0). 큐/콜백 공유 상태는 코드
|
||||
* 분할(메인 vs 편집기 번들) 경계를 넘어야 하므로 모듈 변수가 아니라 `G7Core.layoutEditor`
|
||||
* **객체 자체**(`__queue`/`__readyCallbacks`)에 둔다.
|
||||
*/
|
||||
function initLayoutEditorStub(G7Core: any): void {
|
||||
// 편집기 셸이 먼저 로드돼 실제 API 가 이미 있으면 stub 으로 덮지 않는다.
|
||||
if (G7Core.layoutEditor && G7Core.layoutEditor.__isStub !== true) return;
|
||||
if (G7Core.layoutEditor && G7Core.layoutEditor.__isStub === true) return; // 중복 init 멱등
|
||||
|
||||
const queue: Array<[string, ...unknown[]]> = [];
|
||||
const readyCallbacks: Array<() => void> = [];
|
||||
|
||||
G7Core.layoutEditor = {
|
||||
__isStub: true,
|
||||
__queue: queue,
|
||||
__readyCallbacks: readyCallbacks,
|
||||
registerWidget: (name: string, comp: unknown) => queue.push(['widget', name, comp]),
|
||||
registerNodeEditor: (kind: string, comp: unknown) => queue.push(['nodeEditor', kind, comp]),
|
||||
registerCanvasOverlay: (kind: string, overlay: unknown) =>
|
||||
queue.push(['canvasOverlay', kind, overlay]),
|
||||
/** 편집기 ready 시 호출될 콜백 예약. 이미 ready 면(=stub 아님) 즉시 호출은 실제 API 책임 */
|
||||
onReady: (cb: () => void) => {
|
||||
if (typeof cb === 'function') readyCallbacks.push(cb);
|
||||
},
|
||||
};
|
||||
|
||||
logger.log('전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* 번역 관련 API 초기화
|
||||
*/
|
||||
@@ -1776,7 +1827,7 @@ function initStateAPI(G7Core: any): void {
|
||||
// handlerContext.state(버튼 클릭 시점의 componentContext.state)를 사용해야 함.
|
||||
//
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// [모달 scope 제한사항] (Issue #29 분석, 2026-03-25)
|
||||
// [모달 scope 제한사항] ( 분석, 2026-03-25)
|
||||
//
|
||||
// 현재 getLocal()은 항상 페이지의 globalLocal을 반환한다.
|
||||
// modals 섹션의 isolated scope 모달 내부 커스텀 핸들러에서 호출해도
|
||||
@@ -2897,164 +2948,6 @@ function initSlotAPI(G7Core: any, deps: G7CoreDependencies): void {
|
||||
logger.log('전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)');
|
||||
}
|
||||
|
||||
/**
|
||||
* 위지윅 편집기 API 초기화
|
||||
*
|
||||
* 위지윅 레이아웃 편집기 관련 전역 API를 window.G7Core에 노출합니다.
|
||||
*
|
||||
* @since engine-v1.11.0
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // 편집 모드 확인
|
||||
* if (G7Core.wysiwyg.isEditMode()) {
|
||||
* // 편집 모드 전용 로직
|
||||
* }
|
||||
*
|
||||
* // 편집 모드로 진입
|
||||
* G7Core.wysiwyg.enterEditMode('home', 'sirsoft-basic');
|
||||
*
|
||||
* // 편집 모드 종료
|
||||
* G7Core.wysiwyg.exitEditMode();
|
||||
* ```
|
||||
*/
|
||||
function initWysiwygEditorAPI(G7Core: any): void {
|
||||
// 편집 모드 상태 (전역)
|
||||
let editModeEnabled = false;
|
||||
let currentLayoutName: string | null = null;
|
||||
let currentTemplateId: string | null = null;
|
||||
|
||||
G7Core.wysiwyg = {
|
||||
/**
|
||||
* 현재 편집 모드 여부를 반환합니다.
|
||||
*
|
||||
* @returns boolean 편집 모드 여부
|
||||
*/
|
||||
isEditMode: (): boolean => {
|
||||
return editModeEnabled;
|
||||
},
|
||||
|
||||
/**
|
||||
* 편집 모드를 활성화합니다.
|
||||
*
|
||||
* @param layoutName 편집할 레이아웃명
|
||||
* @param templateId 템플릿 ID
|
||||
*/
|
||||
setEditMode: (layoutName: string, templateId: string): void => {
|
||||
editModeEnabled = true;
|
||||
currentLayoutName = layoutName;
|
||||
currentTemplateId = templateId;
|
||||
logger.log(`위지윅 편집 모드 활성화: ${layoutName} (${templateId})`);
|
||||
},
|
||||
|
||||
/**
|
||||
* 편집 모드를 비활성화합니다.
|
||||
*/
|
||||
clearEditMode: (): void => {
|
||||
editModeEnabled = false;
|
||||
currentLayoutName = null;
|
||||
currentTemplateId = null;
|
||||
logger.log('위지윅 편집 모드 비활성화');
|
||||
},
|
||||
|
||||
/**
|
||||
* 현재 편집 중인 레이아웃명을 반환합니다.
|
||||
*
|
||||
* @returns string | null 레이아웃명 또는 null
|
||||
*/
|
||||
getCurrentLayoutName: (): string | null => {
|
||||
return currentLayoutName;
|
||||
},
|
||||
|
||||
/**
|
||||
* 현재 편집 중인 템플릿 ID를 반환합니다.
|
||||
*
|
||||
* @returns string | null 템플릿 ID 또는 null
|
||||
*/
|
||||
getCurrentTemplateId: (): string | null => {
|
||||
return currentTemplateId;
|
||||
},
|
||||
|
||||
/**
|
||||
* URL 쿼리 파라미터에서 편집 모드 여부를 확인합니다.
|
||||
*
|
||||
* @returns boolean 편집 모드 여부
|
||||
*/
|
||||
isEditModeFromUrl: (): boolean => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
return params.get('mode') === 'edit';
|
||||
},
|
||||
|
||||
/**
|
||||
* 편집 모드 URL을 생성합니다.
|
||||
* 라우트 기반 URL 형식: /{route}?mode=edit&template={templateId}
|
||||
*
|
||||
* @param route 라우트 경로 (예: '/', '/shop', '/board/posts')
|
||||
* @param templateId 템플릿 ID (예: 'sirsoft-basic')
|
||||
* @returns string 편집 모드 URL
|
||||
*/
|
||||
getEditModeUrl: (route: string, templateId: string): string => {
|
||||
const baseUrl = window.location.origin;
|
||||
// 라우트가 '/'로 시작하지 않으면 추가
|
||||
const normalizedRoute = route.startsWith('/') ? route : `/${route}`;
|
||||
return `${baseUrl}${normalizedRoute}?mode=edit&template=${encodeURIComponent(templateId)}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* 편집 모드로 진입합니다. (페이지 이동)
|
||||
* 라우트 기반으로 편집 모드에 진입합니다.
|
||||
*
|
||||
* @param route 라우트 경로 (예: '/', '/shop', '/board/posts')
|
||||
* @param templateId 템플릿 ID (예: 'sirsoft-basic')
|
||||
*/
|
||||
enterEditMode: (route: string, templateId: string): void => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const url = G7Core.wysiwyg.getEditModeUrl(route, templateId);
|
||||
window.location.href = url;
|
||||
},
|
||||
|
||||
/**
|
||||
* 편집 모드를 종료하고 일반 페이지로 이동합니다.
|
||||
* mode, template 파라미터를 제거하고 현재 라우트에 머무릅니다.
|
||||
*/
|
||||
exitEditMode: (): void => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.delete('mode');
|
||||
params.delete('template');
|
||||
const newUrl = `${window.location.pathname}${params.toString() ? '?' + params.toString() : ''}`;
|
||||
window.location.href = newUrl;
|
||||
},
|
||||
|
||||
/**
|
||||
* 위지윅 편집기 모듈 버전을 반환합니다.
|
||||
*
|
||||
* @returns string 버전 문자열
|
||||
*/
|
||||
getVersion: (): string => {
|
||||
return '1.0.0';
|
||||
},
|
||||
|
||||
/**
|
||||
* 현재 구현된 Phase를 반환합니다.
|
||||
*
|
||||
* @returns number Phase 번호
|
||||
*/
|
||||
getPhase: (): number => {
|
||||
return 1;
|
||||
},
|
||||
};
|
||||
|
||||
logger.log('전역 객체 window.G7Core 위지윅 편집기 API에 노출됨 (wysiwyg)');
|
||||
}
|
||||
|
||||
/**
|
||||
* G7Core.identity 인터페이스 초기화 (engine-v1.46.0+)
|
||||
*
|
||||
@@ -3076,9 +2969,28 @@ function initIdentityAPI(G7Core: any): void {
|
||||
/** 모달 launcher 등록 (템플릿 부트스트랩에서 호출) */
|
||||
setLauncher: IdentityGuardInterceptor.setLauncher.bind(IdentityGuardInterceptor),
|
||||
|
||||
/**
|
||||
* 428 응답을 처리합니다 (challenge 모달 launcher 호출 후 성공 시 원 요청 재실행).
|
||||
*
|
||||
* ActionDispatcher.handleApiCall 의 자동 인터셉트와 동일한 launcher 플로우를,
|
||||
* 직접 fetch/G7Core.api 로 요청하는 모듈 JS 핸들러(예: 입금확인)가 재사용하기 위한 진입점.
|
||||
* verify 성공 시 재실행 Response 를, 취소/실패/return_request 부재 시 null 을 반환한다.
|
||||
*/
|
||||
handle: IdentityGuardInterceptor.handle.bind(IdentityGuardInterceptor),
|
||||
|
||||
/** 응답이 428 IDV 요구 응답인지 판별 */
|
||||
isIdentityRequired: IdentityGuardInterceptor.isIdentityRequired.bind(IdentityGuardInterceptor),
|
||||
|
||||
/** 등록된 launcher 가 있는지 여부 */
|
||||
hasLauncher: IdentityGuardInterceptor.hasLauncher.bind(IdentityGuardInterceptor),
|
||||
|
||||
/**
|
||||
* challenge 가 자기 고유의 도메인 안내(성인인증 실패 등)를 사용자에게 표출했음을 표시.
|
||||
* 호출 시 코어 toast 핸들러가 동일 사이클의 generic IDV 가드 토스트("본인 확인이 필요합니다") 1건을 skip.
|
||||
* provider 플러그인이 "본인확인 성공 + 부가목적 미달" 실패를 안내한 직후 호출한다.
|
||||
*/
|
||||
markDomainNoticeShown: IdentityGuardInterceptor.markDomainNoticeShown.bind(IdentityGuardInterceptor),
|
||||
|
||||
/** external_redirect 흐름 — sessionStorage stash + window.location 이동 */
|
||||
redirectExternally: IdentityGuardInterceptor.redirectExternally.bind(IdentityGuardInterceptor),
|
||||
|
||||
@@ -3122,6 +3034,8 @@ export function initializeG7CoreGlobals(deps: G7CoreDependencies): void {
|
||||
|
||||
// 각 API 그룹 초기화
|
||||
initComponentEventSystem(G7Core);
|
||||
// 레이아웃 편집기 확장점 예약 접수함(편집기 lazy 로드 전 템플릿 등록을 큐에 보존)
|
||||
initLayoutEditorStub(G7Core);
|
||||
initCoreAPIs(G7Core, deps);
|
||||
initTranslationAPI(G7Core, deps);
|
||||
initHelperAPIs(G7Core, deps);
|
||||
@@ -3137,7 +3051,6 @@ export function initializeG7CoreGlobals(deps: G7CoreDependencies): void {
|
||||
initPluginAPI(G7Core);
|
||||
initModuleAPI(G7Core);
|
||||
initSlotAPI(G7Core, deps);
|
||||
initWysiwygEditorAPI(G7Core);
|
||||
initIdentityAPI(G7Core);
|
||||
|
||||
logger.log('G7Core 전역 객체 초기화 완료');
|
||||
|
||||
@@ -398,6 +398,44 @@ export class TranslationEngine {
|
||||
return typeof current === 'string' ? current : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 번역 키 값을 활성 사전에 낙관적으로 주입합니다.
|
||||
*
|
||||
* 레이아웃 편집기 인라인 편집으로 커스텀 키를 생성/수정한 직후, 서버 lang 을 재fetch 하는
|
||||
* 비동기 동안 캔버스가 그 키를 raw(또는 옛 값)로 렌더하지 않도록, 입력한 값을 즉시 사전에
|
||||
* 반영한다. 점선 경로(`custom.layout.2`)를 중첩 객체로 풀어 set 하며, 사전이 아직 없으면
|
||||
* 생성한다. 이후 `loadTranslations(...,true)` 가 서버 권위 값으로 사전을 원자 교체한다.
|
||||
*
|
||||
* 사용자 페이지(비편집)에는 호출되지 않는다 — 편집기 전용 낙관적 경로.
|
||||
*
|
||||
* @param templateId 템플릿 식별자
|
||||
* @param locale 대상 로케일
|
||||
* @param key 번역 키 (점선 경로, `$t:` 접두 없이)
|
||||
* @param value 주입할 값
|
||||
* @return 없음
|
||||
*/
|
||||
setTranslationValue(
|
||||
templateId: string,
|
||||
locale: string,
|
||||
key: string,
|
||||
value: string
|
||||
): void {
|
||||
const cacheKey = `${templateId}:${locale}`;
|
||||
const dict = this.translations.get(cacheKey) ?? {};
|
||||
const parts = key.split('.');
|
||||
let cursor: Record<string, unknown> = dict as Record<string, unknown>;
|
||||
for (let i = 0; i < parts.length - 1; i += 1) {
|
||||
const seg = parts[i];
|
||||
const existing = cursor[seg];
|
||||
if (existing == null || typeof existing !== 'object' || Array.isArray(existing)) {
|
||||
cursor[seg] = {};
|
||||
}
|
||||
cursor = cursor[seg] as Record<string, unknown>;
|
||||
}
|
||||
cursor[parts[parts.length - 1]] = value;
|
||||
this.translations.set(cacheKey, dict as TranslationDictionary);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파라미터 문자열을 파싱합니다.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* ActionDispatcher 동적 핸들러 이름 해석 테스트
|
||||
*
|
||||
* 액션 `handler` 가 `{{...}}` 바인딩이면 executeAction 이 컨텍스트로 먼저 해석한 뒤
|
||||
* 라우팅하는지 검증. 백엔드 응답이 호출할 핸들러 풀네임을 내려주는 provider-agnostic
|
||||
* 디스패치(결제 진입 `handler: "{{response.data.pg_payment_handler}}"`)의 회귀 잠금.
|
||||
*
|
||||
* 검증 축:
|
||||
* (a) `{{response.data.pg_payment_handler}}` 해석 → 등록 핸들러 호출 (+ params 전달)
|
||||
* (b) 빌트인(navigate 등)·리터럴 커스텀 핸들러는 `{{` 미포함 → 해석 분기 미진입
|
||||
* (c) nested(conditions/sequence) 컨텍스트에서도 동일 적용
|
||||
* (d) 프리뷰 모드: 해석 결과가 PREVIEW_SUPPRESSED_HANDLERS 면 억제 (해석 후 판정)
|
||||
* (e) 프리뷰 모드: 해석 결과가 미등록 핸들러면 graceful skip (throw 안 함)
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { ActionDispatcher, ActionDefinition } from '../ActionDispatcher';
|
||||
import { Logger } from '../../utils/Logger';
|
||||
|
||||
// AuthManager mock
|
||||
vi.mock('../../auth/AuthManager', () => ({
|
||||
AuthManager: {
|
||||
getInstance: vi.fn(() => ({
|
||||
login: vi.fn().mockResolvedValue({ id: 1 }),
|
||||
logout: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
// ApiClient mock
|
||||
vi.mock('../../api/ApiClient', () => ({
|
||||
getApiClient: vi.fn(() => ({ getToken: vi.fn() })),
|
||||
}));
|
||||
|
||||
describe('ActionDispatcher - 동적 핸들러 이름 해석', () => {
|
||||
let dispatcher: ActionDispatcher;
|
||||
let mockNavigate: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockNavigate = vi.fn();
|
||||
dispatcher = new ActionDispatcher({ navigate: mockNavigate });
|
||||
Logger.getInstance().setDebug(false);
|
||||
});
|
||||
|
||||
const baseContext = () => ({ data: {}, state: {}, setState: vi.fn() });
|
||||
|
||||
describe('(a) 응답 바인딩 핸들러명 해석', () => {
|
||||
it('handler 가 `{{response.data.pg_payment_handler}}` 면 응답값이 가리키는 등록 핸들러를 호출', async () => {
|
||||
const paymentHandler = vi.fn().mockResolvedValue({ ok: true });
|
||||
dispatcher.registerHandler('sirsoft-pay_kginicis.requestPayment', paymentHandler);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: '{{response.data.pg_payment_handler}}',
|
||||
params: { pgPaymentData: '{{response.data.pg_payment_data}}' },
|
||||
};
|
||||
|
||||
const context = {
|
||||
...baseContext(),
|
||||
data: {
|
||||
response: {
|
||||
data: {
|
||||
pg_payment_handler: 'sirsoft-pay_kginicis.requestPayment',
|
||||
pg_payment_data: { order_number: 'ORD-1', amount: 1000 },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, context);
|
||||
|
||||
expect(paymentHandler).toHaveBeenCalledTimes(1);
|
||||
// params 의 pgPaymentData 도 응답값으로 해석되어 전달되었는지 (resolveParams)
|
||||
const callArg = paymentHandler.mock.calls[0][0];
|
||||
expect(callArg?.params?.pgPaymentData).toEqual({ order_number: 'ORD-1', amount: 1000 });
|
||||
});
|
||||
|
||||
it('provider 가 다른 핸들러명을 내려주면 그 핸들러로 라우팅 (provider-agnostic)', async () => {
|
||||
const handlerA = vi.fn().mockResolvedValue({ ok: 'A' });
|
||||
const handlerB = vi.fn().mockResolvedValue({ ok: 'B' });
|
||||
dispatcher.registerHandler('vendor-a.pay', handlerA);
|
||||
dispatcher.registerHandler('vendor-b.checkout', handlerB);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: '{{response.data.pg_payment_handler}}',
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, {
|
||||
...baseContext(),
|
||||
data: { response: { data: { pg_payment_handler: 'vendor-b.checkout' } } },
|
||||
});
|
||||
|
||||
expect(handlerA).not.toHaveBeenCalled();
|
||||
expect(handlerB).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('(b) 리터럴 핸들러는 해석 분기 미진입', () => {
|
||||
it('빌트인 navigate 는 `{{` 미포함 → 그대로 라우팅', async () => {
|
||||
const contextNavigate = vi.fn();
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'navigate',
|
||||
target: '/admin/dashboard',
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, { ...baseContext(), navigate: contextNavigate });
|
||||
expect(contextNavigate).toHaveBeenCalledWith('/admin/dashboard', { replace: false });
|
||||
});
|
||||
|
||||
it('리터럴 커스텀 핸들러명(dotted)도 그대로 호출 — `{{` 없으면 바인딩 평가 안 함', async () => {
|
||||
const handler = vi.fn().mockResolvedValue({ ok: true });
|
||||
dispatcher.registerHandler('sirsoft-pay_kginicis.requestPayment', handler);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sirsoft-pay_kginicis.requestPayment',
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, baseContext());
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('(c) nested(conditions/sequence) 컨텍스트 적용', () => {
|
||||
it('conditions then 분기의 동적 핸들러도 해석되어 호출', async () => {
|
||||
const paymentHandler = vi.fn().mockResolvedValue({ ok: true });
|
||||
dispatcher.registerHandler('sirsoft-pay_kginicis.requestPayment', paymentHandler);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'conditions',
|
||||
conditions: [
|
||||
{
|
||||
if: '{{response.data.requires_pg_payment && response.data.pg_payment_handler}}',
|
||||
then: {
|
||||
handler: '{{response.data.pg_payment_handler}}',
|
||||
params: { pgPaymentData: '{{response.data.pg_payment_data}}' },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, {
|
||||
...baseContext(),
|
||||
data: {
|
||||
response: {
|
||||
data: {
|
||||
requires_pg_payment: true,
|
||||
pg_payment_handler: 'sirsoft-pay_kginicis.requestPayment',
|
||||
pg_payment_data: { order_number: 'ORD-2' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(paymentHandler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('sequence 의 동적 핸들러도 해석되어 호출', async () => {
|
||||
const paymentHandler = vi.fn().mockResolvedValue({ ok: true });
|
||||
dispatcher.registerHandler('vendor-x.pay', paymentHandler);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sequence',
|
||||
params: {
|
||||
actions: [{ handler: '{{response.data.pg_payment_handler}}' }],
|
||||
},
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, {
|
||||
...baseContext(),
|
||||
data: { response: { data: { pg_payment_handler: 'vendor-x.pay' } } },
|
||||
});
|
||||
|
||||
expect(paymentHandler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('(d) 프리뷰 모드 — 해석 후 억제 판정', () => {
|
||||
it('동적 핸들러가 navigate 로 해석되면 프리뷰 모드에서 억제 (해석 후 PREVIEW_SUPPRESSED 판정)', async () => {
|
||||
const contextNavigate = vi.fn();
|
||||
dispatcher.setPreviewMode(true);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: '{{response.data.handler_name}}',
|
||||
target: '/somewhere',
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, {
|
||||
...baseContext(),
|
||||
navigate: contextNavigate,
|
||||
data: { response: { data: { handler_name: 'navigate' } } },
|
||||
});
|
||||
|
||||
// 해석 결과 navigate 가 억제 집합에 있으므로 실행 안 됨
|
||||
expect(contextNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('(e) 프리뷰 모드 — 미등록 해석 결과 graceful skip', () => {
|
||||
it('해석 결과가 미등록 핸들러면 throw 하지 않고 success 반환', async () => {
|
||||
dispatcher.setPreviewMode(true);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: '{{response.data.pg_payment_handler}}',
|
||||
};
|
||||
|
||||
const result = await dispatcher.executeAction(action, {
|
||||
...baseContext(),
|
||||
data: { response: { data: { pg_payment_handler: 'vendor-unregistered.pay' } } },
|
||||
});
|
||||
|
||||
expect(result?.success).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
+27
-6
@@ -30,7 +30,9 @@ describe('ActionDispatcher - handleNavigate fallback (engine-v1.40.0)', () => {
|
||||
let mockNavigate: ReturnType<typeof vi.fn>;
|
||||
let mockMatch: ReturnType<typeof vi.fn>;
|
||||
let mockWindowOpen: ReturnType<typeof vi.fn>;
|
||||
let mockLocationAssign: ReturnType<typeof vi.fn>;
|
||||
let originalWindowOpen: typeof window.open;
|
||||
let originalLocationAssign: typeof window.location.assign;
|
||||
|
||||
beforeEach(() => {
|
||||
mockNavigate = vi.fn();
|
||||
@@ -47,10 +49,26 @@ describe('ActionDispatcher - handleNavigate fallback (engine-v1.40.0)', () => {
|
||||
originalWindowOpen = window.open;
|
||||
mockWindowOpen = vi.fn();
|
||||
window.open = mockWindowOpen as any;
|
||||
|
||||
// window.location.assign 모킹 — fallback 기본값(_self)이 `location.assign` 을 호출.
|
||||
// jsdom 의 location 객체는 spyOn/defineProperty 가 모두 잠겨 있으므로
|
||||
// delete + 객체 교체 패턴으로 우회.
|
||||
originalLocationAssign = window.location.assign;
|
||||
mockLocationAssign = vi.fn();
|
||||
delete (window as any).location;
|
||||
(window as any).location = {
|
||||
assign: mockLocationAssign,
|
||||
href: '',
|
||||
pathname: '',
|
||||
search: '',
|
||||
hash: '',
|
||||
origin: 'http://localhost',
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.open = originalWindowOpen;
|
||||
void originalLocationAssign;
|
||||
delete (window as any).__templateApp;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
@@ -69,7 +87,7 @@ describe('ActionDispatcher - handleNavigate fallback (engine-v1.40.0)', () => {
|
||||
expect(mockWindowOpen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('라우트 매칭 실패 + fallback 미지정 → 기본 openWindow', async () => {
|
||||
it('라우트 매칭 실패 + fallback 미지정 → 기본 openWindow target=_self → window.location.assign 호출 (admin↔user 교차 이동 흐름 보존)', async () => {
|
||||
mockMatch.mockReturnValue(null);
|
||||
|
||||
await dispatcher.dispatchAction({
|
||||
@@ -79,7 +97,10 @@ describe('ActionDispatcher - handleNavigate fallback (engine-v1.40.0)', () => {
|
||||
});
|
||||
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
expect(mockWindowOpen).toHaveBeenCalledWith('/shop/orders/123', '_blank');
|
||||
// 기본값 _self 로 같은 탭 이동 (ActionDispatcher.handleOpenWindow + resolveNavigateFallback 본문 주석 참조).
|
||||
// _self 는 window.open 대신 window.location.assign 을 호출한다.
|
||||
expect(mockLocationAssign).toHaveBeenCalledWith('/shop/orders/123');
|
||||
expect(mockWindowOpen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('라우트 매칭 실패 + fallback: false → 기존 동작(navigate 강행)', async () => {
|
||||
@@ -124,7 +145,7 @@ describe('ActionDispatcher - handleNavigate fallback (engine-v1.40.0)', () => {
|
||||
expect(mockWindowOpen).toHaveBeenCalledWith('/shop/orders/123', '_blank');
|
||||
});
|
||||
|
||||
it('쿼리 파라미터가 있는 경로도 fallback pathname만 매칭', async () => {
|
||||
it('쿼리 파라미터가 있는 경로도 fallback pathname만 매칭 → _self 기본값으로 location.assign 호출', async () => {
|
||||
mockMatch.mockReturnValue(null);
|
||||
|
||||
await dispatcher.dispatchAction({
|
||||
@@ -138,9 +159,9 @@ describe('ActionDispatcher - handleNavigate fallback (engine-v1.40.0)', () => {
|
||||
|
||||
expect(mockMatch).toHaveBeenCalledWith('/shop/orders');
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
// query가 병합된 finalPath가 openWindow로 전달됨
|
||||
expect(mockWindowOpen).toHaveBeenCalled();
|
||||
const openedUrl = mockWindowOpen.mock.calls[0][0];
|
||||
// _self 기본값 — query 병합된 finalPath 가 location.assign 으로 전달됨
|
||||
expect(mockLocationAssign).toHaveBeenCalled();
|
||||
const openedUrl = mockLocationAssign.mock.calls[0][0];
|
||||
expect(openedUrl).toContain('/shop/orders?');
|
||||
expect(openedUrl).toContain('id=123');
|
||||
expect(openedUrl).toContain('tab=detail');
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* ActionDispatcher — IDV 가드 토스트 중복 억제 테스트.
|
||||
*
|
||||
* 본인확인은 성공했으나 부가 목적(성인인증 등)을 충족하지 못해 challenge 가 실패하면,
|
||||
* provider 가 "성인 인증이 필요합니다" 같은 고유 사유를 이미 토스트로 표출한다. 그 직후
|
||||
* 원 요청의 onError 가 generic IDV 가드 토스트("본인 확인이 필요합니다")를 중복 발화하는데,
|
||||
* provider 가 markDomainNoticeShown() 신호를 남긴 경우 코어 handleToast 가 그 1건을 skip 한다.
|
||||
*
|
||||
* 일반 본인인증 실패(본인확인 자체 실패/취소)는 신호가 없어 가드 토스트가 그대로 유지된다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { ActionDispatcher } from '../ActionDispatcher';
|
||||
import { IdentityGuardInterceptor } from '../../identity/IdentityGuardInterceptor';
|
||||
|
||||
describe('ActionDispatcher — IDV 가드 토스트 중복 억제', () => {
|
||||
let dispatcher: ActionDispatcher;
|
||||
let toasts: any[];
|
||||
|
||||
beforeEach(() => {
|
||||
dispatcher = new ActionDispatcher();
|
||||
IdentityGuardInterceptor.reset();
|
||||
toasts = [];
|
||||
|
||||
// globalStateUpdater 가 toasts 배열을 누적하도록 모킹
|
||||
dispatcher.setGlobalStateUpdater((updates: any) => {
|
||||
if (updates.toasts) {
|
||||
toasts = updates.toasts;
|
||||
}
|
||||
});
|
||||
|
||||
// handleToast 가 현재 toasts 를 읽기 위해 사용하는 G7Core.state.get() 모킹
|
||||
(window as any).G7Core = {
|
||||
state: { get: () => ({ toasts }) },
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
IdentityGuardInterceptor.reset();
|
||||
delete (window as any).G7Core;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** IDV 가드 응답으로 인한 onError 토스트 컨텍스트를 모사 */
|
||||
const identityGuardErrorContext = {
|
||||
data: {
|
||||
error: {
|
||||
status: 428,
|
||||
message: '본인 확인이 필요합니다.',
|
||||
error_code: 'identity_verification_required',
|
||||
data: { error_code: 'identity_verification_required' },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
it('도메인 안내 신호가 있으면 IDV 가드 error 토스트를 skip', async () => {
|
||||
// provider 가 고유 사유(성인인증 실패)를 표출했음을 신호
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
|
||||
await dispatcher.dispatchAction(
|
||||
{ handler: 'toast', params: { type: 'error', message: '본인 확인이 필요합니다.' } },
|
||||
identityGuardErrorContext as any,
|
||||
);
|
||||
|
||||
// 가드 토스트는 skip 되어 추가되지 않음
|
||||
expect(toasts).toHaveLength(0);
|
||||
// 신호는 소비됨
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(false);
|
||||
});
|
||||
|
||||
it('신호가 없으면 IDV 가드 error 토스트를 그대로 표출 (일반 본인인증 실패)', async () => {
|
||||
// markDomainNoticeShown 미호출 (일반 본인인증 실패류)
|
||||
|
||||
await dispatcher.dispatchAction(
|
||||
{ handler: 'toast', params: { type: 'error', message: '본인 확인이 필요합니다.' } },
|
||||
identityGuardErrorContext as any,
|
||||
);
|
||||
|
||||
// 가드 토스트가 그대로 추가됨
|
||||
expect(toasts).toHaveLength(1);
|
||||
expect(toasts[0].message).toBe('본인 확인이 필요합니다.');
|
||||
});
|
||||
|
||||
it('신호가 있어도 IDV 가드가 아닌 error 토스트는 skip 하지 않음', async () => {
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
|
||||
// error_code 가 IDV 가드가 아닌 일반 에러 토스트
|
||||
await dispatcher.dispatchAction(
|
||||
{
|
||||
handler: 'toast',
|
||||
params: { type: 'error', message: '서버 오류가 발생했습니다.' },
|
||||
},
|
||||
{ data: { error: { status: 500, error_code: 'server_error' } } } as any,
|
||||
);
|
||||
|
||||
// 가드가 아니므로 표출됨 + 신호는 소비되지 않아 다음 가드 토스트용으로 남음
|
||||
expect(toasts).toHaveLength(1);
|
||||
expect(toasts[0].message).toBe('서버 오류가 발생했습니다.');
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(true);
|
||||
});
|
||||
|
||||
it('신호가 있어도 success 토스트는 skip 하지 않음 (error 타입만 대상)', async () => {
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
|
||||
await dispatcher.dispatchAction(
|
||||
{
|
||||
handler: 'toast',
|
||||
params: { type: 'success', message: '저장되었습니다.' },
|
||||
},
|
||||
identityGuardErrorContext as any,
|
||||
);
|
||||
|
||||
expect(toasts).toHaveLength(1);
|
||||
expect(toasts[0].message).toBe('저장되었습니다.');
|
||||
});
|
||||
|
||||
it('skip 은 1회만 — 신호 소비 후 두 번째 가드 토스트는 표출', async () => {
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
|
||||
// 첫 번째 가드 토스트 → skip
|
||||
await dispatcher.dispatchAction(
|
||||
{ handler: 'toast', params: { type: 'error', message: '본인 확인이 필요합니다.' } },
|
||||
identityGuardErrorContext as any,
|
||||
);
|
||||
expect(toasts).toHaveLength(0);
|
||||
|
||||
// 두 번째 가드 토스트 → 신호 소비됨, 표출
|
||||
await dispatcher.dispatchAction(
|
||||
{ handler: 'toast', params: { type: 'error', message: '본인 확인이 필요합니다.' } },
|
||||
identityGuardErrorContext as any,
|
||||
);
|
||||
expect(toasts).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* ActionDispatcher identity_target 기능 테스트.
|
||||
*
|
||||
* apiCall 액션의 `identity_target` 속성이 표현식 평가되어, 428 IDV 인터셉트 시
|
||||
* IdentityGuardInterceptor.handle 의 target 인자로 전달되는지 검증.
|
||||
*
|
||||
* 비회원 주문 등 비로그인 흐름의 핵심 — 서버 428 payload 에는 target 이 없고 흐름이 선언한다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { ActionDispatcher, ActionDefinition } from '../ActionDispatcher';
|
||||
import { IdentityGuardInterceptor } from '../../identity/IdentityGuardInterceptor';
|
||||
import { Logger } from '../../utils/Logger';
|
||||
|
||||
vi.mock('../../api/ApiClient', () => ({
|
||||
getApiClient: vi.fn(() => ({ getToken: vi.fn(() => null) })),
|
||||
}));
|
||||
|
||||
// IdentityGuardInterceptor 의 인터셉트 메서드만 모킹 (handle 호출 인자 검증)
|
||||
vi.mock('../../identity/IdentityGuardInterceptor', () => ({
|
||||
IdentityGuardInterceptor: {
|
||||
isIdentityRequired: vi.fn(),
|
||||
handle: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockedGuard = IdentityGuardInterceptor as unknown as {
|
||||
isIdentityRequired: ReturnType<typeof vi.fn>;
|
||||
handle: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
describe('ActionDispatcher - apiCall identity_target', () => {
|
||||
let dispatcher: ActionDispatcher;
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
let originalFetch: typeof fetch;
|
||||
|
||||
const createMockEvent = () =>
|
||||
({ preventDefault: vi.fn(), type: 'click', target: null }) as unknown as Event;
|
||||
|
||||
beforeEach(() => {
|
||||
dispatcher = new ActionDispatcher({ navigate: vi.fn() });
|
||||
Logger.getInstance().setDebug(false);
|
||||
|
||||
originalFetch = globalThis.fetch;
|
||||
// 기본: 428 응답 (IDV 필요)
|
||||
mockFetch = vi.fn().mockResolvedValue({
|
||||
status: 428,
|
||||
ok: false,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
success: false,
|
||||
error_code: 'identity_verification_required',
|
||||
verification: { return_request: { method: 'POST', url: '/api/orders' } },
|
||||
}),
|
||||
});
|
||||
globalThis.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
Object.defineProperty(document, 'cookie', {
|
||||
value: 'XSRF-TOKEN=test-csrf-token',
|
||||
writable: true,
|
||||
});
|
||||
|
||||
mockedGuard.isIdentityRequired.mockReset();
|
||||
mockedGuard.handle.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Logger.getInstance().setDebug(false);
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('428 인터셉트 시 평가된 identity_target 을 handle 의 target 인자로 전달한다', async () => {
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(true);
|
||||
mockedGuard.handle.mockResolvedValue(null); // 재실행 없이 종료 (인자 검증만)
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'apiCall',
|
||||
target: '/api/orders',
|
||||
identity_target: {
|
||||
email: '{{_local.orderer.email}}',
|
||||
phone: '{{_local.orderer.phone}}',
|
||||
},
|
||||
params: { method: 'POST', body: { x: 1 } },
|
||||
};
|
||||
|
||||
// _local 은 componentContext.state (createHandler 3번째 인자)에서 평가됨
|
||||
const componentContext = {
|
||||
state: { orderer: { email: 'guest@example.com', phone: '01012345678' } },
|
||||
};
|
||||
|
||||
const handler = dispatcher.createHandler(action, {}, componentContext);
|
||||
await handler(createMockEvent());
|
||||
|
||||
expect(mockedGuard.handle).toHaveBeenCalledOnce();
|
||||
const callArgs = mockedGuard.handle.mock.calls[0];
|
||||
// 3번째 인자 = 평가된 identity_target
|
||||
expect(callArgs[2]).toEqual({
|
||||
email: 'guest@example.com',
|
||||
phone: '01012345678',
|
||||
});
|
||||
});
|
||||
|
||||
it('identity_target 미선언 apiCall 은 handle 의 target 인자가 undefined 다 (하위호환)', async () => {
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(true);
|
||||
mockedGuard.handle.mockResolvedValue(null);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'apiCall',
|
||||
target: '/api/orders',
|
||||
params: { method: 'POST', body: { x: 1 } },
|
||||
};
|
||||
|
||||
const handler = dispatcher.createHandler(action, { state: { _global: {}, _local: {} } });
|
||||
await handler(createMockEvent());
|
||||
|
||||
expect(mockedGuard.handle).toHaveBeenCalledOnce();
|
||||
expect(mockedGuard.handle.mock.calls[0][2]).toBeUndefined();
|
||||
});
|
||||
|
||||
it('428 이 아니면 IdentityGuard.handle 을 호출하지 않는다', async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
status: 200,
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ success: true, data: {} }),
|
||||
});
|
||||
mockedGuard.isIdentityRequired.mockReturnValue(false);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'apiCall',
|
||||
target: '/api/orders',
|
||||
identity_target: { email: '{{_local.orderer.email}}' },
|
||||
params: { method: 'POST' },
|
||||
};
|
||||
|
||||
const handler = dispatcher.createHandler(action, {}, { state: { orderer: { email: 'a@b.com' } } });
|
||||
await handler(createMockEvent());
|
||||
|
||||
expect(mockedGuard.handle).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -287,4 +287,103 @@ describe('ActionDispatcher - previewMode', () => {
|
||||
expect(contextNavigate).toHaveBeenCalledWith('/admin/dashboard', { replace: false });
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// S4'' 보완 — handleCustomAction silent skip
|
||||
//
|
||||
// PreviewCanvas 의 격리 ActionDispatcher 인스턴스는 호스트의 customHandlers
|
||||
// (예: sirsoft-ckeditor5.initEditor) 를 공유하지 않으므로, lifecycle onMount
|
||||
// 단계에서 외부 플러그인 핸들러가 호출되면 throw → errorHandling.onError →
|
||||
// setState(500) → ErrorBoundary 발화 → 캔버스 unmount 회귀.
|
||||
//
|
||||
// 본 보완: previewMode 일 때 미등록 핸들러는 throw 대신 warn 후 undefined 반환.
|
||||
// ============================================================================
|
||||
describe("S4'' — 미등록 커스텀 핸들러 silent skip (previewMode)", () => {
|
||||
const mockContext = {
|
||||
data: {},
|
||||
state: {},
|
||||
setState: vi.fn(),
|
||||
};
|
||||
|
||||
it('previewMode=true 일 때 미등록 커스텀 핸들러 호출 시 throw 하지 않음', async () => {
|
||||
dispatcher.setPreviewMode(true);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sirsoft-ckeditor5.initEditor',
|
||||
};
|
||||
|
||||
// 본 보완 전: ActionError("Unknown action handler: sirsoft-ckeditor5.initEditor") throw
|
||||
// 본 보완 후: silent skip — promise 가 reject 되지 않음
|
||||
await expect(dispatcher.executeAction(action, mockContext)).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('previewMode=true 일 때 미등록 핸들러 호출 시 success=true 반환 (errorHandling 미발화)', async () => {
|
||||
dispatcher.setPreviewMode(true);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'someUnknownHandler',
|
||||
};
|
||||
|
||||
const result = await dispatcher.executeAction(action, mockContext);
|
||||
// executeAction 의 반환 형식 — { success: boolean, data?: any, error?: any }
|
||||
// silent skip 시 result.success 는 truthy 여야 한다 (errorHandling 분기 미발화)
|
||||
expect(result?.success).toBeTruthy();
|
||||
});
|
||||
|
||||
it('previewMode=true silent skip 시 콘솔 warn 1회 호출 (로그 디그레이드)', async () => {
|
||||
dispatcher.setPreviewMode(true);
|
||||
// Logger 의 warn 을 spy — 본 보완 코드의 logger.warn 호출 검증
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sirsoft-ckeditor5.initEditor',
|
||||
};
|
||||
|
||||
// debug 모드 활성화 — Logger.warn 이 console.warn 으로 흐르도록
|
||||
Logger.getInstance().setDebug(true);
|
||||
await dispatcher.executeAction(action, mockContext);
|
||||
Logger.getInstance().setDebug(false);
|
||||
|
||||
// warn 호출 메시지에 "Unknown action handler" 또는 "Preview" 포함 확인
|
||||
const warnCalls = warnSpy.mock.calls.flat().map(String).join(' ');
|
||||
expect(warnCalls).toMatch(/sirsoft-ckeditor5\.initEditor|Preview|Unknown/i);
|
||||
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('previewMode=false (일반 라우트) 일 때 미등록 핸들러는 여전히 throw 발생 — 일반 동작 보존', async () => {
|
||||
// previewMode 미설정 (기본값 false)
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sirsoft-ckeditor5.initEditor',
|
||||
};
|
||||
|
||||
// 본 보완은 previewMode=true 분기에만 영향 — false 일 때 기존 throw 동작 그대로
|
||||
// executeAction 가 try/catch 로 감싸 result.error 로 반환할 수 있으므로 양쪽 케이스 허용
|
||||
const result = await dispatcher.executeAction(action, mockContext).catch((e) => ({
|
||||
success: false,
|
||||
error: e,
|
||||
}));
|
||||
expect(result?.success).toBeFalsy();
|
||||
});
|
||||
|
||||
it('previewMode=true 일 때 등록된 커스텀 핸들러는 정상 실행 — silent skip 분기가 등록 핸들러를 가리지 않음', async () => {
|
||||
dispatcher.setPreviewMode(true);
|
||||
|
||||
const handlerSpy = vi.fn().mockResolvedValue({ ok: true });
|
||||
dispatcher.registerHandler('myCustom', handlerSpy);
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'myCustom',
|
||||
params: { x: 1 },
|
||||
};
|
||||
|
||||
await dispatcher.executeAction(action, mockContext);
|
||||
expect(handlerSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -277,6 +277,110 @@ describe('ActionDispatcher', () => {
|
||||
expect(mockSetState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// 공개#54 — IME(한글/일본어/중국어) 조합 중 Enter 글자누락/이중제출 방지
|
||||
describe('IME 조합 가드 (공개#54)', () => {
|
||||
/** KeyboardEvent 에 isComposing/keyCode 를 강제 주입한다 (생성자 옵션 미지원). */
|
||||
const makeKeyEvent = (
|
||||
key: string,
|
||||
opts: { isComposing?: boolean; keyCode?: number } = {},
|
||||
): KeyboardEvent => {
|
||||
const e = new KeyboardEvent('keydown', { key });
|
||||
if (opts.isComposing !== undefined) {
|
||||
Object.defineProperty(e, 'isComposing', { value: opts.isComposing, configurable: true });
|
||||
}
|
||||
if (opts.keyCode !== undefined) {
|
||||
Object.defineProperty(e, 'keyCode', { value: opts.keyCode, configurable: true });
|
||||
}
|
||||
return e;
|
||||
};
|
||||
|
||||
const enterFilterProps = {
|
||||
actions: [
|
||||
{
|
||||
type: 'keydown' as const,
|
||||
key: 'Enter',
|
||||
handler: 'navigate',
|
||||
params: { path: '/search' },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('T1: isComposing=true 인 Enter 는 key 필터 액션을 실행하지 않아야 함', () => {
|
||||
const boundProps = dispatcher.bindActionsToProps(enterFilterProps, {}, { state: {}, setState: vi.fn() });
|
||||
mockNavigate.mockClear();
|
||||
|
||||
boundProps.onKeyDown(makeKeyEvent('Enter', { isComposing: true }));
|
||||
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('T2: keyCode=229 인 Enter(isComposing 미지원)도 실행하지 않아야 함', () => {
|
||||
const boundProps = dispatcher.bindActionsToProps(enterFilterProps, {}, { state: {}, setState: vi.fn() });
|
||||
mockNavigate.mockClear();
|
||||
|
||||
boundProps.onKeyDown(makeKeyEvent('Enter', { keyCode: 229 }));
|
||||
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('T3: isComposing=false 인 일반 Enter 는 정상 실행되어야 함', () => {
|
||||
const boundProps = dispatcher.bindActionsToProps(enterFilterProps, {}, { state: {}, setState: vi.fn() });
|
||||
mockNavigate.mockClear();
|
||||
|
||||
boundProps.onKeyDown(makeKeyEvent('Enter', { isComposing: false }));
|
||||
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/search', { replace: false });
|
||||
});
|
||||
|
||||
it('T4: key 필터 없는 keydown 액션은 조합 중에도 실행되어야 함 (회귀 방지)', () => {
|
||||
const mockSetState = vi.fn();
|
||||
const props = {
|
||||
actions: [
|
||||
{
|
||||
type: 'keydown' as const,
|
||||
handler: 'setState',
|
||||
params: { target: 'local', value: 'typed' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const boundProps = dispatcher.bindActionsToProps(props, {}, { state: {}, setState: mockSetState });
|
||||
|
||||
boundProps.onKeyDown(makeKeyEvent('x', { isComposing: true }));
|
||||
|
||||
expect(mockSetState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('T5: isComposing=true 인 Escape 는 key 필터 액션을 실행하지 않아야 함', () => {
|
||||
const mockSetState = vi.fn();
|
||||
const props = {
|
||||
actions: [
|
||||
{
|
||||
type: 'keydown' as const,
|
||||
key: 'Escape',
|
||||
handler: 'setState',
|
||||
params: { target: 'local', isOpen: false },
|
||||
},
|
||||
],
|
||||
};
|
||||
const boundProps = dispatcher.bindActionsToProps(props, {}, { state: {}, setState: mockSetState });
|
||||
|
||||
boundProps.onKeyDown(makeKeyEvent('Escape', { isComposing: true }));
|
||||
|
||||
expect(mockSetState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('isImeComposing 헬퍼 분기: isComposing/keyCode/둘다 false/undefined', () => {
|
||||
const helper = (dispatcher as unknown as {
|
||||
isImeComposing: (e: { isComposing?: boolean; keyCode?: number }) => boolean;
|
||||
}).isImeComposing.bind(dispatcher);
|
||||
|
||||
expect(helper({ isComposing: true })).toBe(true);
|
||||
expect(helper({ keyCode: 229 })).toBe(true);
|
||||
expect(helper({ isComposing: false, keyCode: 13 })).toBe(false);
|
||||
expect(helper({})).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('admin_user_list.json 시나리오: change와 keydown+Enter 조합', () => {
|
||||
const mockSetState = vi.fn();
|
||||
const componentContext = {
|
||||
@@ -1226,6 +1330,92 @@ describe('ActionDispatcher', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// engine-v1.50.4: 컴포넌트 setState(target:"_local")가 canonical source(_global._local)에도 동기화되어야 함.
|
||||
// 배경: 검색(navigate replace:true) → updateQueryParams refetch → updateTemplateData 가
|
||||
// currentDataContext._local 을 _global._local 로 되돌리는데, 사용자가 선택한 필터(target:"_local" setState)가
|
||||
// _global._local 에 반영되지 않으면 검색 직후 필터가 init 기본값으로 풀린다(쿠폰/주문/배송정책 공통 결함).
|
||||
// GLOBAL STATE UPDATER path 와 동일하게 COMPONENT path 도 globalStateUpdater 로 _global._local 을 동기화하되,
|
||||
// render:false 로 호출하여 추가 React 렌더를 유발하지 않는다.
|
||||
it('컴포넌트 컨텍스트의 setState(target:"local")가 _global._local을 render:false로 동기화해야 함 (검색 후 필터 보존 회귀)', () => {
|
||||
const mockSetState = vi.fn();
|
||||
const globalStateUpdater = vi.fn();
|
||||
dispatcher.setGlobalStateUpdater(globalStateUpdater);
|
||||
|
||||
// 전역 pending 스냅샷 격리: 런타임에서는 렌더 후 useLayoutEffect 가 null 로 클리어하지만
|
||||
// 단위 테스트에서는 이전 테스트 잔여값이 base 를 오염시키므로 명시적으로 비운다.
|
||||
(window as any).__g7PendingLocalState = null;
|
||||
(window as any).__g7ForcedLocalFields = undefined;
|
||||
|
||||
const componentContext = {
|
||||
state: { filter: { targetType: 'all', issueStatus: 'all' } },
|
||||
setState: mockSetState,
|
||||
};
|
||||
|
||||
const props = {
|
||||
actions: [
|
||||
{
|
||||
type: 'change' as const,
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'local',
|
||||
'filter.issueStatus': 'issuing',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const boundProps = dispatcher.bindActionsToProps(props, {}, componentContext);
|
||||
boundProps.onChange({ target: { value: 'issuing' } });
|
||||
|
||||
// 저장소 A: 컴포넌트 React 상태 (변경 필드만)
|
||||
expect(mockSetState).toHaveBeenCalledWith({
|
||||
filter: { issueStatus: 'issuing' },
|
||||
});
|
||||
|
||||
// 저장소 B: _global._local 동기화 — render:false (추가 렌더 없음)
|
||||
// 기존 필드(filter.targetType)는 base(context.state)에서 보존되어야 함
|
||||
expect(globalStateUpdater).toHaveBeenCalledWith(
|
||||
{
|
||||
_local: expect.objectContaining({
|
||||
filter: expect.objectContaining({
|
||||
targetType: 'all',
|
||||
issueStatus: 'issuing',
|
||||
}),
|
||||
}),
|
||||
},
|
||||
{ render: false }
|
||||
);
|
||||
});
|
||||
|
||||
it('globalStateUpdater가 없으면 setState(target:"local")는 컴포넌트 상태만 갱신하고 조용히 넘어가야 함', () => {
|
||||
// _global 동기화는 globalStateUpdater 유무에 가드되어 있어야 함 (모달/단독 렌더 안전)
|
||||
const mockSetState = vi.fn();
|
||||
// globalStateUpdater 설정하지 않음
|
||||
(window as any).__g7PendingLocalState = null;
|
||||
(window as any).__g7ForcedLocalFields = undefined;
|
||||
|
||||
const componentContext = {
|
||||
state: { filter: { issueStatus: 'all' } },
|
||||
setState: mockSetState,
|
||||
};
|
||||
|
||||
const props = {
|
||||
actions: [
|
||||
{
|
||||
type: 'change' as const,
|
||||
handler: 'setState',
|
||||
params: { target: 'local', 'filter.issueStatus': 'issuing' },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const boundProps = dispatcher.bindActionsToProps(props, {}, componentContext);
|
||||
|
||||
// globalStateUpdater 미설정 상태에서도 에러 없이 컴포넌트 setState 가 호출되어야 함
|
||||
expect(() => boundProps.onChange({ target: { value: 'issuing' } })).not.toThrow();
|
||||
expect(mockSetState).toHaveBeenCalledWith({ filter: { issueStatus: 'issuing' } });
|
||||
});
|
||||
|
||||
it('표준 DOM 이벤트와 커스텀 콜백 이벤트를 구분해야 함', () => {
|
||||
const mockSetState = vi.fn();
|
||||
const globalStateUpdater = vi.fn();
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* ComponentRegistry 격리 인스턴스 가드
|
||||
*
|
||||
* 회귀 원인: 레이아웃 편집기 캔버스(`PreviewCanvas`) 가 호스트 페이지의
|
||||
* ComponentRegistry 싱글톤을 점유한 채 다른 템플릿(`sirsoft-basic`) 을 렌더
|
||||
* 하려고 해 `Header`/`Footer` 컴포넌트 미발견 회귀. 본 테스트는 격리 인스턴스
|
||||
* 가 싱글톤과 독립적으로 동작함을 가드.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ComponentRegistry } from '../ComponentRegistry';
|
||||
|
||||
describe('ComponentRegistry.createIsolatedInstance', () => {
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.resetInstance();
|
||||
});
|
||||
|
||||
it('격리 인스턴스는 싱글톤과 다른 객체', () => {
|
||||
const singleton = ComponentRegistry.getInstance();
|
||||
const isolated = ComponentRegistry.createIsolatedInstance();
|
||||
|
||||
expect(isolated).not.toBe(singleton);
|
||||
});
|
||||
|
||||
it('격리 인스턴스를 두 번 호출하면 매번 새 인스턴스', () => {
|
||||
const a = ComponentRegistry.createIsolatedInstance();
|
||||
const b = ComponentRegistry.createIsolatedInstance();
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it('싱글톤 getInstance() 는 동일 인스턴스 (격리 호출이 영향 주지 않음)', () => {
|
||||
const singletonBefore = ComponentRegistry.getInstance();
|
||||
ComponentRegistry.createIsolatedInstance();
|
||||
ComponentRegistry.createIsolatedInstance();
|
||||
const singletonAfter = ComponentRegistry.getInstance();
|
||||
expect(singletonBefore).toBe(singletonAfter);
|
||||
});
|
||||
|
||||
it('격리 인스턴스의 registry/manifest 초기 상태는 비어 있고 loadingState 는 idle', () => {
|
||||
const isolated = ComponentRegistry.createIsolatedInstance();
|
||||
expect(isolated.getComponentMap()).toEqual({});
|
||||
expect(isolated.getLoadingState()).toBe('idle');
|
||||
expect(isolated.getTemplateId()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { DataBindingEngine } from '../DataBindingEngine';
|
||||
|
||||
/**
|
||||
* 단일 바인딩 식 안에 `}` 가 든 경우(빈 객체 fallback 등)의 파싱 회귀.
|
||||
*
|
||||
* 종전 `^\{\{([^}]+)\}\}$` 정규식은 `{{error.errors ?? {}}}` 같은 표현식을 단일 바인딩으로
|
||||
* 인식하지 못해 원본 문자열이 그대로 컴포넌트로 새어 나갔다. extractSingleBinding 으로
|
||||
* 중괄호 균형을 추적해 정확히 단일 식을 추출하도록 수정.
|
||||
*/
|
||||
describe('DataBindingEngine — {}}} 닫기 모호성 (단일 바인딩 내부 중괄호)', () => {
|
||||
it('{{error.errors ?? {}}} 는 빈 객체 fallback 으로 평가된다 (raw 문자열 누출 금지)', () => {
|
||||
const eng = new DataBindingEngine();
|
||||
const ctx: any = { error: {} }; // error.errors === undefined → ?? {} fallback
|
||||
const out: any = eng.resolveObject({ addressErrors: '{{error.errors ?? {}}}' }, ctx, {});
|
||||
expect(out.addressErrors).toEqual({});
|
||||
expect(out.addressErrors).not.toBe('{{error.errors ?? {}}}');
|
||||
});
|
||||
|
||||
it('{{$error.errors ?? { _general: $error.message }}} 객체 리터럴 fallback 평가', () => {
|
||||
const eng = new DataBindingEngine();
|
||||
const ctx: any = { $error: { errors: undefined, message: '오류' } };
|
||||
const out: any = eng.resolveObject(
|
||||
{ optionErrors: '{{$error.errors ?? { _general: $error.message }}}' },
|
||||
ctx,
|
||||
{},
|
||||
);
|
||||
expect(out.optionErrors).toEqual({ _general: '오류' });
|
||||
});
|
||||
|
||||
it('값이 있으면 그대로 객체 반환 (fallback 미발동)', () => {
|
||||
const eng = new DataBindingEngine();
|
||||
const ctx: any = { error: { errors: { name: 'required' } } };
|
||||
const out: any = eng.resolveObject({ e: '{{error.errors ?? {}}}' }, ctx, {});
|
||||
expect(out.e).toEqual({ name: 'required' });
|
||||
});
|
||||
|
||||
it('단순 바인딩 {{error.errors}} 회귀 없음', () => {
|
||||
const eng = new DataBindingEngine();
|
||||
const ctx: any = { error: { errors: { x: 1 } } };
|
||||
const out: any = eng.resolveObject({ e: '{{error.errors}}' }, ctx, {});
|
||||
expect(out.e).toEqual({ x: 1 });
|
||||
});
|
||||
|
||||
it('다중 바인딩 "{{a}} {{b}}" 는 단일 바인딩으로 오인하지 않고 문자열 보간', () => {
|
||||
const eng = new DataBindingEngine();
|
||||
const ctx: any = { a: 'X', b: 'Y' };
|
||||
const out: any = eng.resolveObject({ s: '{{a}} {{b}}' }, ctx, {});
|
||||
expect(out.s).toBe('X Y');
|
||||
});
|
||||
});
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* DataBindingEngine.translationTokens.test.ts
|
||||
*
|
||||
* 표현식 결과 문자열의 `$t:` 토큰 2차 해석 회귀 가드.
|
||||
*
|
||||
* 결함: `{{route.id ? '$t:board.edit' : '$t:board.write'}}` 형태의 삼항 표현식 평가
|
||||
* 결과 문자열이 `$t:board.write` 같은 raw 키로 노출되던 결함. 원인은 `$t` 함수가
|
||||
* `context.$templateId` 미존재 시 `window.__templateApp.getConfig()` 로 fallback
|
||||
* 하는데, 편집기 격리 store 의 façade 에는 `getConfig` 가 없어 templateId 가
|
||||
* 빈 문자열로 떨어져 사전 조회 실패.
|
||||
*
|
||||
* 본 테스트는 4단계 절차의 1단계(재현) — 수정 전 fail, 수정 후 green.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { DataBindingEngine } from '../DataBindingEngine';
|
||||
import { TranslationEngine } from '../TranslationEngine';
|
||||
|
||||
describe('DataBindingEngine — 표현식 결과 $t: 토큰 2차 해석', () => {
|
||||
let bindingEngine: DataBindingEngine;
|
||||
let translationEngine: TranslationEngine;
|
||||
|
||||
beforeEach(() => {
|
||||
bindingEngine = new DataBindingEngine();
|
||||
TranslationEngine.resetInstance();
|
||||
translationEngine = TranslationEngine.getInstance();
|
||||
|
||||
// 편집 대상 템플릿 사전 누적 (편집기에서 useEditorTemplateAssets 가 하는 동작 시뮬레이션)
|
||||
(translationEngine as any).translations.set('sirsoft-basic:ko', {
|
||||
board: {
|
||||
write: '글쓰기',
|
||||
edit: '글 수정',
|
||||
form: { submit: '등록' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TranslationEngine.resetInstance();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('context.$templateId 가 명시되면 삼항 표현식의 `$t:` 토큰이 정확히 해석된다', () => {
|
||||
// 글쓰기 라우트: route.id 미존재 → false 분기 → $t:board.write → "글쓰기"
|
||||
const expr = "route.id ? '$t:board.edit' : '$t:board.write'";
|
||||
const context = {
|
||||
route: {},
|
||||
$templateId: 'sirsoft-basic',
|
||||
$locale: 'ko',
|
||||
};
|
||||
const result = bindingEngine.evaluateExpression(expr, context);
|
||||
expect(result).toBe('글쓰기');
|
||||
});
|
||||
|
||||
it('글 수정 라우트: route.id 존재 → true 분기 → $t:board.edit → "글 수정"', () => {
|
||||
const expr = "route.id ? '$t:board.edit' : '$t:board.write'";
|
||||
const context = {
|
||||
route: { id: '42' },
|
||||
$templateId: 'sirsoft-basic',
|
||||
$locale: 'ko',
|
||||
};
|
||||
const result = bindingEngine.evaluateExpression(expr, context);
|
||||
expect(result).toBe('글 수정');
|
||||
});
|
||||
|
||||
it('window.__templateApp.getConfig() 가 없는 격리 환경에서도 context.$templateId 우선 사용 (회귀 가드)', () => {
|
||||
// 편집기 격리 store 환경: getConfig 미제공
|
||||
const originalTemplateApp = (window as any).__templateApp;
|
||||
(window as any).__templateApp = {
|
||||
// getConfig 의도적 미제공 — 격리 façade 시뮬레이션
|
||||
getGlobalState: () => ({}),
|
||||
};
|
||||
try {
|
||||
const expr = "true ? '$t:board.form.submit' : 'fallback'";
|
||||
const context = {
|
||||
$templateId: 'sirsoft-basic',
|
||||
$locale: 'ko',
|
||||
};
|
||||
const result = bindingEngine.evaluateExpression(expr, context);
|
||||
expect(result).toBe('등록');
|
||||
} finally {
|
||||
(window as any).__templateApp = originalTemplateApp;
|
||||
}
|
||||
});
|
||||
|
||||
it('context.$templateId 미제공 + getConfig 도 없는 경우: raw key 반환 (현재 동작)', () => {
|
||||
// 격리 환경에서 $templateId 도 안 들어가면 폴백 실패 — 본 케이스는 PreviewCanvas
|
||||
// 가 dataContext 에 $templateId 명시 주입으로 해소되어야 함
|
||||
const originalTemplateApp = (window as any).__templateApp;
|
||||
(window as any).__templateApp = {};
|
||||
try {
|
||||
const expr = "true ? '$t:board.write' : 'fallback'";
|
||||
const context = {};
|
||||
const result = bindingEngine.evaluateExpression(expr, context);
|
||||
// $templateId 도 없고 getConfig 도 없으면 templateId = '' → 사전 미발견 → key 반환
|
||||
expect(result).toBe('board.write');
|
||||
} finally {
|
||||
(window as any).__templateApp = originalTemplateApp;
|
||||
}
|
||||
});
|
||||
|
||||
it('일반 사이트 렌더 경로(window.__templateApp.getConfig 제공): 종전과 동일하게 풀린다 (회귀 가드)', () => {
|
||||
const originalTemplateApp = (window as any).__templateApp;
|
||||
(window as any).__templateApp = {
|
||||
getConfig: () => ({ templateId: 'sirsoft-basic', locale: 'ko' }),
|
||||
};
|
||||
try {
|
||||
const expr = "true ? '$t:board.write' : 'fallback'";
|
||||
const context = {}; // $templateId 미명시 — fallback 경로
|
||||
const result = bindingEngine.evaluateExpression(expr, context);
|
||||
expect(result).toBe('글쓰기');
|
||||
} finally {
|
||||
(window as any).__templateApp = originalTemplateApp;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* DataSourceManager.sampleMode.test.ts
|
||||
*
|
||||
* DataSourceManager 의 샘플 모드 주입점 검증.
|
||||
*
|
||||
* - sampleProvider 옵션이 주입되지 않은 경우(일반 렌더 모드): 분기 진입 0,
|
||||
* fetch 100% 보존 (회귀 가드).
|
||||
* - sampleProvider 옵션이 주입된 경우(편집 모드): fetch 호출 없이 프로바이더
|
||||
* resolve() 결과를 반환.
|
||||
* - sampleProvider 가 has() 로 false 반환 시 일반 fetch 경로로 폴백.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import { DataSourceManager, type DataSource, type SampleDataProvider } from '../DataSourceManager';
|
||||
|
||||
describe('DataSourceManager — 샘플 모드 주입점 ', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = vi.fn(async () =>
|
||||
new Response(JSON.stringify({ success: true, data: { data: [] } }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
);
|
||||
global.fetch = fetchMock as any;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('일반 렌더 모드(옵션 미주입): API 데이터소스가 네트워크 fetch 를 호출한다 (회귀 가드)', async () => {
|
||||
const manager = new DataSourceManager();
|
||||
const source: DataSource = {
|
||||
id: 'recent-posts',
|
||||
type: 'api',
|
||||
endpoint: '/api/posts',
|
||||
method: 'GET',
|
||||
} as any;
|
||||
|
||||
await (manager as any).fetchApiDataSource(
|
||||
source,
|
||||
{},
|
||||
new URLSearchParams(),
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const calledUrl = fetchMock.mock.calls[0][0];
|
||||
expect(calledUrl).toContain('/api/posts');
|
||||
});
|
||||
|
||||
it('편집 모드(옵션 주입 + has=true): fetch 호출 없이 sampleProvider.resolve() 결과 반환', async () => {
|
||||
const sampleResponse = { data: [{ id: 1, title: '샘플 게시물' }] };
|
||||
const sampleProvider: SampleDataProvider = {
|
||||
has: vi.fn(() => true),
|
||||
resolve: vi.fn(() => sampleResponse),
|
||||
};
|
||||
|
||||
const manager = new DataSourceManager({ sampleProvider });
|
||||
const source: DataSource = {
|
||||
id: 'recent-posts',
|
||||
type: 'api',
|
||||
endpoint: '/api/posts',
|
||||
method: 'GET',
|
||||
} as any;
|
||||
|
||||
const result = await (manager as any).fetchApiDataSource(
|
||||
source,
|
||||
{},
|
||||
new URLSearchParams(),
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(sampleProvider.resolve).toHaveBeenCalledWith(source);
|
||||
expect(result).toBe(sampleResponse);
|
||||
});
|
||||
|
||||
it('편집 모드 (옵션 주입 + has=false): 폴백으로 일반 fetch 경로 진입', async () => {
|
||||
const sampleProvider: SampleDataProvider = {
|
||||
has: vi.fn(() => false),
|
||||
resolve: vi.fn(() => ({ data: [] })),
|
||||
};
|
||||
|
||||
const manager = new DataSourceManager({ sampleProvider });
|
||||
const source: DataSource = {
|
||||
id: 'unsupported-source',
|
||||
type: 'api',
|
||||
endpoint: '/api/foo',
|
||||
method: 'GET',
|
||||
} as any;
|
||||
|
||||
await (manager as any).fetchApiDataSource(
|
||||
source,
|
||||
{},
|
||||
new URLSearchParams(),
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(sampleProvider.has).toHaveBeenCalledWith('unsupported-source');
|
||||
expect(sampleProvider.resolve).not.toHaveBeenCalled();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('actionDispatcher 옵션 주입 시: onSuccess 가 옵션 dispatcher 사용 (호스트 globalState 누수 방지)', async () => {
|
||||
// 라우트 12 글 수정 등 onSuccess 에 setState 가 있는 layout 의 호스트 #app
|
||||
// unmount 결함 회귀 가드. 옵션 dispatcher 가 주입되면 전역 getActionDispatcher()
|
||||
// 대신 본 dispatcher 가 사용되어야 한다.
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ success: true, data: { posts: [{ id: 1 }] } }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
|
||||
const dispatchAction = vi.fn().mockResolvedValue(undefined);
|
||||
const isolatedDispatcher = { dispatchAction } as any;
|
||||
|
||||
const manager = new DataSourceManager({ actionDispatcher: isolatedDispatcher });
|
||||
const source = {
|
||||
id: 'form_data',
|
||||
type: 'api',
|
||||
endpoint: '/api/form-data',
|
||||
method: 'GET',
|
||||
auto_fetch: true,
|
||||
onSuccess: {
|
||||
handler: 'setState',
|
||||
params: { target: 'local', form: '{{response.data.posts}}' },
|
||||
},
|
||||
} as any;
|
||||
|
||||
await manager.fetchDataSources([source]);
|
||||
|
||||
// 옵션 dispatcher 의 dispatchAction 이 호출되어야 함
|
||||
expect(dispatchAction).toHaveBeenCalledTimes(1);
|
||||
expect(dispatchAction.mock.calls[0][0]).toMatchObject({ handler: 'setState' });
|
||||
});
|
||||
|
||||
it('actionDispatcher 옵션 미주입 시: onSuccess 가 전역 getActionDispatcher() 사용 (일반 렌더 보존)', async () => {
|
||||
// 옵션 미전달 시 기존 동작 100% 보존 — 본 케이스는 ActionDispatcher 전역
|
||||
// 인스턴스가 미초기화일 수 있는 단위 환경에서 silent skip 으로 떨어지는 것을 확인.
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ success: true, data: { posts: [] } }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
|
||||
const manager = new DataSourceManager(); // 옵션 없음
|
||||
const source = {
|
||||
id: 'form_data',
|
||||
type: 'api',
|
||||
endpoint: '/api/form-data',
|
||||
method: 'GET',
|
||||
auto_fetch: true,
|
||||
onSuccess: {
|
||||
handler: 'setState',
|
||||
params: { target: 'local', form: '{{response.data.posts}}' },
|
||||
},
|
||||
} as any;
|
||||
|
||||
// 에러 없이 완료되어야 함 (전역 dispatcher 미초기화 시 warn 후 스킵)
|
||||
await expect(manager.fetchDataSources([source])).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('sampleProvider.resolve 가 Promise 를 반환해도 await 으로 정상 처리', async () => {
|
||||
const sampleResponse = { data: [{ id: 99 }] };
|
||||
const sampleProvider: SampleDataProvider = {
|
||||
has: () => true,
|
||||
resolve: () => Promise.resolve(sampleResponse),
|
||||
};
|
||||
|
||||
const manager = new DataSourceManager({ sampleProvider });
|
||||
const source: DataSource = {
|
||||
id: 'async-source',
|
||||
type: 'api',
|
||||
endpoint: '/api/anything',
|
||||
method: 'GET',
|
||||
} as any;
|
||||
|
||||
const result = await (manager as any).fetchApiDataSource(
|
||||
source,
|
||||
{},
|
||||
new URLSearchParams(),
|
||||
);
|
||||
|
||||
expect(result).toBe(sampleResponse);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// 지연 소스(auto_fetch:false) 샘플 주입.
|
||||
// 편집기 캔버스는 정적 시뮬레이션이라 탭/모달 활성 액션을 실행할 수 없어, 페이지 상태로
|
||||
// 게이트를 열어도 지연 소스 데이터가 비어 본체가 미렌더된다(myComments 내댓글 서브탭).
|
||||
// 샘플 모드에서는 지연 소스도 fetchDataSources 처리 대상에 포함해 샘플을 주입한다.
|
||||
describe('지연 소스(auto_fetch:false) — 단계 E 게이트 본체 노출', () => {
|
||||
it('샘플 모드: auto_fetch:false 소스도 샘플이 주입된다(결과 맵에 포함)', async () => {
|
||||
const sampleResponse = { data: { data: [{ id: 1, content: '내 댓글' }] } };
|
||||
const sampleProvider: SampleDataProvider = {
|
||||
has: (id: string) => id === 'myComments',
|
||||
resolve: () => sampleResponse,
|
||||
};
|
||||
const manager = new DataSourceManager({ sampleProvider });
|
||||
const lazySource: DataSource = {
|
||||
id: 'myComments',
|
||||
type: 'api',
|
||||
endpoint: '/api/me/my-comments',
|
||||
method: 'GET',
|
||||
auto_fetch: false,
|
||||
} as any;
|
||||
|
||||
const results = await manager.fetchDataSources([lazySource]);
|
||||
|
||||
expect(results).toHaveProperty('myComments');
|
||||
expect(results.myComments).toBe(sampleResponse);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('일반 렌더 모드(옵션 미주입): auto_fetch:false 소스는 fetch 대상에서 제외된다(회귀 가드)', async () => {
|
||||
const manager = new DataSourceManager();
|
||||
const lazySource: DataSource = {
|
||||
id: 'myComments',
|
||||
type: 'api',
|
||||
endpoint: '/api/me/my-comments',
|
||||
method: 'GET',
|
||||
auto_fetch: false,
|
||||
} as any;
|
||||
|
||||
const results = await manager.fetchDataSources([lazySource]);
|
||||
|
||||
// 런타임은 지연 소스를 초기 fetch 하지 않는다(탭 활성 시 refetch) — 기존 동작 보존.
|
||||
expect(results).not.toHaveProperty('myComments');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* DynamicRenderer.iterationId.test.tsx — iteration 노드 id 표현식 보간
|
||||
*
|
||||
* 노드의 최상위 `id` 필드는 props 가 아니라 props 바인딩 경로를 타지 않는다. iteration
|
||||
* 안에서 `id: "item_{{$idx}}"` 처럼 표현식을 쓰면 각 row 마다 고유 DOM id 가 되어야 하지만,
|
||||
* 보간 없이 출력되면 같은 리터럴이 row 마다 반복되어 W3C HTML id 중복을 유발한다.
|
||||
*
|
||||
* engine-v1.52.4 수정: DOM 출력 지점이 effectiveComponentDef.id 를 iteration 컨텍스트로
|
||||
* 보간한 resolvedComponentId 를 쓴다. slot 등록·React key 등 내부 식별은 원본 id 유지(격리).
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import DynamicRenderer, { ComponentDefinition } from '../DynamicRenderer';
|
||||
import { ComponentRegistry } from '../ComponentRegistry';
|
||||
import { DataBindingEngine } from '../DataBindingEngine';
|
||||
import { TranslationEngine, TranslationContext } from '../TranslationEngine';
|
||||
import { ActionDispatcher } from '../ActionDispatcher';
|
||||
|
||||
// id 를 실제 DOM 속성으로 출력하는 테스트 컴포넌트.
|
||||
const IdDiv: React.FC<{ id?: string; children?: React.ReactNode }> = ({ id, children }) => (
|
||||
<div id={id}>{children}</div>
|
||||
);
|
||||
|
||||
describe('DynamicRenderer - iteration id 표현식 보간', () => {
|
||||
let registry: ComponentRegistry;
|
||||
let bindingEngine: DataBindingEngine;
|
||||
let translationEngine: TranslationEngine;
|
||||
let actionDispatcher: ActionDispatcher;
|
||||
let translationContext: TranslationContext;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: { component: IdDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
};
|
||||
bindingEngine = new DataBindingEngine();
|
||||
translationEngine = new TranslationEngine();
|
||||
actionDispatcher = new ActionDispatcher({ navigate: vi.fn() });
|
||||
translationContext = { templateId: 'test-template', locale: 'ko' };
|
||||
});
|
||||
|
||||
function renderNode(componentDef: ComponentDefinition, dataContext: Record<string, unknown> = {}) {
|
||||
return render(
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={dataContext}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
it('index_var 를 쓴 id 가 row 별 고유 DOM id 로 보간된다', () => {
|
||||
const def: ComponentDefinition = {
|
||||
id: 'item_{{$idx}}',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: { source: 'rows', item_var: 'row', index_var: '$idx' },
|
||||
} as unknown as ComponentDefinition;
|
||||
|
||||
const { container } = renderNode(def, { rows: [{ n: 'a' }, { n: 'b' }, { n: 'c' }] });
|
||||
|
||||
const ids = Array.from(container.querySelectorAll('[id]')).map((el) => el.id);
|
||||
expect(ids).toEqual(['item_0', 'item_1', 'item_2']);
|
||||
// 중복 0
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
|
||||
it('item_var 의 필드를 쓴 id 도 row 값으로 보간된다', () => {
|
||||
const def: ComponentDefinition = {
|
||||
id: 'row_{{row.id}}',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: { source: 'rows', item_var: 'row' },
|
||||
} as unknown as ComponentDefinition;
|
||||
|
||||
const { container } = renderNode(def, { rows: [{ id: 7 }, { id: 42 }] });
|
||||
|
||||
const ids = Array.from(container.querySelectorAll('[id]')).map((el) => el.id);
|
||||
expect(ids).toEqual(['row_7', 'row_42']);
|
||||
});
|
||||
|
||||
it('표현식이 없는 정적 id 는 그대로 출력된다(무영향)', () => {
|
||||
const def: ComponentDefinition = {
|
||||
id: 'static_box',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
} as unknown as ComponentDefinition;
|
||||
|
||||
const { container } = renderNode(def);
|
||||
expect(container.querySelector('#static_box')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('index 0 도 빈 문자열이 아니라 정상 보간된다', () => {
|
||||
const def: ComponentDefinition = {
|
||||
id: 'cell_{{$i}}',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: { source: 'rows', item_var: 'r', index_var: '$i' },
|
||||
} as unknown as ComponentDefinition;
|
||||
|
||||
const { container } = renderNode(def, { rows: [{}] });
|
||||
expect(container.querySelector('#cell_0')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1057,4 +1057,69 @@ describe('DynamicRenderer - Responsive 오버라이드', () => {
|
||||
expect(screen.getByText('데스크톱')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// 편집기가 만든 responsive 산출물이 실제 렌더되는지 round-trip 증명.
|
||||
// applyRecipe(node, control, value, {breakpoint:'mobile'}) 가 만드는 형태
|
||||
// (responsive.mobile.props.className) 를 그대로 넣어 모바일 폭에서 병합 honor 확인.
|
||||
describe('편집기 scope 산출물 round-trip', () => {
|
||||
it('편집기가 만든 responsive.mobile.props.className 이 모바일 폭에서 적용된다', () => {
|
||||
setWidth(390); // 모바일
|
||||
|
||||
// applyRecipe(scope:mobile) 산출 형태 — base className + responsive.mobile override
|
||||
const componentDef: ComponentDefinition = {
|
||||
id: 'editor-scope-1',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'bg-white' },
|
||||
responsive: {
|
||||
mobile: { props: { className: 'bg-slate-800' } },
|
||||
},
|
||||
};
|
||||
|
||||
render(
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>
|
||||
);
|
||||
|
||||
const div = screen.getByTestId('test-div');
|
||||
expect(div).toHaveClass('bg-slate-800'); // 모바일 override 적용
|
||||
});
|
||||
|
||||
it('데스크톱 폭에서는 base className(편집기 공통 scope) 사용', () => {
|
||||
setWidth(1280); // 데스크톱
|
||||
|
||||
const componentDef: ComponentDefinition = {
|
||||
id: 'editor-scope-2',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'bg-white' },
|
||||
responsive: {
|
||||
mobile: { props: { className: 'bg-slate-800' } },
|
||||
},
|
||||
};
|
||||
|
||||
render(
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>
|
||||
);
|
||||
|
||||
const div = screen.getByTestId('test-div');
|
||||
expect(div).toHaveClass('bg-white'); // 공통(base) 적용
|
||||
expect(div).not.toHaveClass('bg-slate-800');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* 슬롯 마커(data-editor-slot) 테스트
|
||||
*
|
||||
* 공통(base) 레이아웃의 슬롯 노드(`slot: "content"` 등)를 편집기 오버레이/CSS 가
|
||||
* 시각화할 수 있도록, 편집 모드에서만 `data-editor-slot` DOM 속성을 부여한다.
|
||||
* 운영 렌더(isEditMode=false)에는 속성이 없어야 한다.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import DynamicRenderer, { ComponentDefinition } from '../DynamicRenderer';
|
||||
import { ComponentRegistry } from '../ComponentRegistry';
|
||||
import { DataBindingEngine } from '../DataBindingEngine';
|
||||
import { TranslationEngine, TranslationContext } from '../TranslationEngine';
|
||||
import { ActionDispatcher } from '../ActionDispatcher';
|
||||
|
||||
const TestDiv: React.FC<Record<string, unknown>> = (props) => {
|
||||
const { children, ...rest } = props as { children?: React.ReactNode };
|
||||
return <div {...(rest as Record<string, never>)}>{children}</div>;
|
||||
};
|
||||
|
||||
describe('data-editor-slot 마커', () => {
|
||||
let registry: ComponentRegistry;
|
||||
let bindingEngine: DataBindingEngine;
|
||||
let translationEngine: TranslationEngine;
|
||||
let actionDispatcher: ActionDispatcher;
|
||||
let translationContext: TranslationContext;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
};
|
||||
bindingEngine = new DataBindingEngine();
|
||||
translationEngine = new TranslationEngine();
|
||||
actionDispatcher = new ActionDispatcher({ navigate: vi.fn() });
|
||||
translationContext = { templateId: 'test-template', locale: 'ko' };
|
||||
});
|
||||
|
||||
const slotDef: ComponentDefinition = {
|
||||
id: 'main_content',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
slot: 'content',
|
||||
props: { 'data-testid': 'slot-node' },
|
||||
children: [],
|
||||
} as unknown as ComponentDefinition;
|
||||
|
||||
it('편집 모드 — 슬롯 노드에 data-editor-slot="<슬롯명>" 이 부여된다', () => {
|
||||
const { container } = render(
|
||||
<DynamicRenderer
|
||||
componentDef={slotDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
isEditMode
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelector('[data-editor-slot="content"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('운영 렌더(isEditMode=false) — data-editor-slot 미부여 (운영 영향 0)', () => {
|
||||
const { container } = render(
|
||||
<DynamicRenderer
|
||||
componentDef={slotDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelector('[data-editor-slot]')).toBeNull();
|
||||
});
|
||||
|
||||
it('편집 모드 — base 편집 표시 마커(__editorSlotName)로도 부여된다 (PreviewCanvas slot 치환 경로)', () => {
|
||||
const markerDef: ComponentDefinition = {
|
||||
id: 'main_content',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
__editorSlotName: 'content',
|
||||
props: {},
|
||||
children: [],
|
||||
} as unknown as ComponentDefinition;
|
||||
const { container } = render(
|
||||
<DynamicRenderer
|
||||
componentDef={markerDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
isEditMode
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelector('[data-editor-slot="content"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('편집 모드 — slot 키가 없는 노드에는 부여하지 않는다', () => {
|
||||
const plainDef: ComponentDefinition = {
|
||||
id: 'plain',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: {},
|
||||
};
|
||||
const { container } = render(
|
||||
<DynamicRenderer
|
||||
componentDef={plainDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
isEditMode
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelector('[data-editor-slot]')).toBeNull();
|
||||
});
|
||||
});
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* DynamicRenderer.sourceMetaFiltering.test.tsx
|
||||
*
|
||||
* 출처 메타 키 React props 필터링 안전망 검증.
|
||||
*
|
||||
* 백엔드가 `with_source_meta=1` 옵션 응답에 `__source` 메타를 부여할 수 있고,
|
||||
* 일반 사이트 렌더 응답에 누수가 발생하더라도 React props 로 DOM 에 전달되지
|
||||
* 않도록 차단되어야 한다. `__` 접두사를 가진 모든 메타 키는 Basic/Layout
|
||||
* 컴포넌트의 DOM 전달 직전에 일괄 차단된다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { vi } from 'vitest';
|
||||
import DynamicRenderer, { ComponentDefinition } from '../DynamicRenderer';
|
||||
import { ComponentRegistry } from '../ComponentRegistry';
|
||||
import { DataBindingEngine } from '../DataBindingEngine';
|
||||
import { TranslationEngine, TranslationContext } from '../TranslationEngine';
|
||||
import { ActionDispatcher } from '../ActionDispatcher';
|
||||
|
||||
const TestDiv: React.FC<{
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
'data-testid'?: string;
|
||||
}> = ({ className, children, 'data-testid': testId, ...rest }) => (
|
||||
<div data-testid={testId || 'test-div'} className={className} {...rest}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
describe('DynamicRenderer — `__` 시작 메타 키 React props 필터링', () => {
|
||||
let registry: ComponentRegistry;
|
||||
let bindingEngine: DataBindingEngine;
|
||||
let translationEngine: TranslationEngine;
|
||||
let actionDispatcher: ActionDispatcher;
|
||||
let translationContext: TranslationContext;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: {
|
||||
component: TestDiv,
|
||||
metadata: { name: 'Div', type: 'basic' },
|
||||
},
|
||||
};
|
||||
|
||||
bindingEngine = new DataBindingEngine();
|
||||
translationEngine = new TranslationEngine();
|
||||
actionDispatcher = new ActionDispatcher({ navigate: vi.fn() });
|
||||
translationContext = { templateId: 'test-template', locale: 'ko' };
|
||||
});
|
||||
|
||||
it('Basic 컴포넌트의 DOM 에 `__source` 메타가 노출되지 않는다', () => {
|
||||
// 백엔드 with_source_meta=1 응답에 `__source` 가 포함된 노드를 시뮬레이션
|
||||
const componentDef: ComponentDefinition & { __source?: any } = {
|
||||
id: 'test-basic-meta',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { 'data-testid': 'basic-target', className: 'visible-class' },
|
||||
__source: { kind: 'base', layout: '_admin_base' },
|
||||
} as any;
|
||||
|
||||
render(
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>
|
||||
);
|
||||
|
||||
const el = screen.getByTestId('basic-target');
|
||||
// 일반 props 는 그대로 노출
|
||||
expect(el.className).toContain('visible-class');
|
||||
// `__source` 메타는 DOM 에 노출되지 않음 (data-__source, __source 어느 형태로도)
|
||||
expect(el.outerHTML).not.toContain('__source');
|
||||
expect(el.outerHTML).not.toContain('base');
|
||||
expect(el.outerHTML).not.toContain('_admin_base');
|
||||
});
|
||||
|
||||
it('`__` 접두사를 가진 임의 키는 모두 차단된다', () => {
|
||||
const componentDef: ComponentDefinition & {
|
||||
__source?: any;
|
||||
__anyOtherMeta?: any;
|
||||
} = {
|
||||
id: 'test-arbitrary',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { 'data-testid': 'arbitrary-target' },
|
||||
__source: { kind: 'extension', extensionId: 42 },
|
||||
__anyOtherMeta: 'secret-internal-value',
|
||||
} as any;
|
||||
|
||||
render(
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>
|
||||
);
|
||||
|
||||
const el = screen.getByTestId('arbitrary-target');
|
||||
expect(el.outerHTML).not.toContain('__source');
|
||||
expect(el.outerHTML).not.toContain('__anyOtherMeta');
|
||||
expect(el.outerHTML).not.toContain('secret-internal-value');
|
||||
expect(el.outerHTML).not.toContain('extensionId');
|
||||
});
|
||||
|
||||
it('일반 `data-*` 속성은 통과한다 (regression 가드)', () => {
|
||||
const componentDef: ComponentDefinition = {
|
||||
id: 'test-data-attr',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: {
|
||||
'data-testid': 'data-attr-target',
|
||||
'data-foo': 'bar',
|
||||
'aria-label': 'sample',
|
||||
},
|
||||
};
|
||||
|
||||
render(
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={{}}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>
|
||||
);
|
||||
|
||||
const el = screen.getByTestId('data-attr-target');
|
||||
expect(el.getAttribute('data-foo')).toBe('bar');
|
||||
expect(el.getAttribute('aria-label')).toBe('sample');
|
||||
});
|
||||
});
|
||||
@@ -160,6 +160,53 @@ describe('IdentityGuardInterceptor', () => {
|
||||
const result = await IdentityGuardInterceptor.handle(response);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
/**
|
||||
* 신규(engine-v1.51.0) — 흐름이 선언한 인증 대상(target)이 launcher payload 에 병합되어야 함.
|
||||
* 비회원 주문 등 비로그인 흐름의 핵심 — 서버 428 payload 에는 target 이 없고 흐름이 선언한다.
|
||||
*/
|
||||
it('merges declared target into launcher payload (email + phone)', async () => {
|
||||
let receivedPayload: any = null;
|
||||
IdentityGuardInterceptor.setLauncher(async (payload) => {
|
||||
receivedPayload = payload;
|
||||
return { status: 'cancelled' };
|
||||
});
|
||||
|
||||
await IdentityGuardInterceptor.handle(makeResponse(), undefined, {
|
||||
email: 'guest@example.com',
|
||||
phone: '01012345678',
|
||||
});
|
||||
|
||||
expect(receivedPayload?.target).toEqual({
|
||||
email: 'guest@example.com',
|
||||
phone: '01012345678',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not merge target when both email and phone are empty', async () => {
|
||||
let receivedPayload: any = null;
|
||||
IdentityGuardInterceptor.setLauncher(async (payload) => {
|
||||
receivedPayload = payload;
|
||||
return { status: 'cancelled' };
|
||||
});
|
||||
|
||||
await IdentityGuardInterceptor.handle(makeResponse(), undefined, { email: '', phone: '' });
|
||||
|
||||
// 빈 target 은 병합하지 않음 — 로그인 사용자는 서버 세션이 도출
|
||||
expect(receivedPayload?.target).toBeUndefined();
|
||||
});
|
||||
|
||||
it('omits target entirely when not provided (backward compatible)', async () => {
|
||||
let receivedPayload: any = null;
|
||||
IdentityGuardInterceptor.setLauncher(async (payload) => {
|
||||
receivedPayload = payload;
|
||||
return { status: 'cancelled' };
|
||||
});
|
||||
|
||||
await IdentityGuardInterceptor.handle(makeResponse());
|
||||
|
||||
expect(receivedPayload?.target).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createDeferred / resolveDeferred', () => {
|
||||
@@ -186,6 +233,51 @@ describe('IdentityGuardInterceptor', () => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 도메인 안내 표출 신호 (engine-v1.52.0) — 부가 목적(성인인증 등) 실패 시 provider 가
|
||||
* 고유 안내를 표출했음을 표시하면, 코어 toast 핸들러가 동일 사이클의 generic IDV 가드
|
||||
* 토스트("본인 확인이 필요합니다") 1건을 skip 한다. 일반 본인인증 실패는 무영향.
|
||||
*/
|
||||
describe('markDomainNoticeShown / consumeDomainNoticeShown', () => {
|
||||
it('기본값은 false — 신호 미설정 시 consume 은 false', () => {
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(false);
|
||||
});
|
||||
|
||||
it('mark 후 consume 은 1회만 true (소비 후 해제)', () => {
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(true);
|
||||
// 1회 소비 후에는 다시 false — 다음 토스트는 정상 표출
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(false);
|
||||
});
|
||||
|
||||
it('handle() 진입 시 이전 사이클의 미소비 신호를 정리한다 (stale skip 방지)', async () => {
|
||||
// 이전 사이클에서 신호만 set 되고 가드 토스트가 없어 미소비로 남은 상황
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
|
||||
// 새 challenge 진입 — handle() 이 flag 를 정리해야 함
|
||||
IdentityGuardInterceptor.setLauncher(async () => ({ status: 'cancelled' }));
|
||||
await IdentityGuardInterceptor.handle({
|
||||
success: false,
|
||||
error_code: 'identity_verification_required',
|
||||
message: 'verify',
|
||||
verification: {
|
||||
policy_key: 'k',
|
||||
purpose: 'sensitive_action',
|
||||
return_request: { method: 'POST', url: '/api/x' },
|
||||
},
|
||||
});
|
||||
|
||||
// 정리되어 false 여야 함
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(false);
|
||||
});
|
||||
|
||||
it('reset() 이 신호를 해제한다', () => {
|
||||
IdentityGuardInterceptor.markDomainNoticeShown();
|
||||
IdentityGuardInterceptor.reset();
|
||||
expect(IdentityGuardInterceptor.consumeDomainNoticeShown()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('redirectExternally', () => {
|
||||
it('writes stash to sessionStorage and assigns window.location.href', () => {
|
||||
// window.location.href 할당 모킹 (jsdom)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import {
|
||||
TranslationEngine,
|
||||
TranslationContext,
|
||||
TranslationDictionary,
|
||||
} from '../TranslationEngine';
|
||||
|
||||
/**
|
||||
* 코어 프론트엔드 다국어 인프라 회귀 가드.
|
||||
*
|
||||
* `TemplateService::getLanguageDataWithModules` 가 코어 `lang/{locale}.json` 을
|
||||
* 베이스 레이어로 병합한 응답을 보낸다. 본 테스트는 응답에 포함된 `core.*` 키가
|
||||
* `translate()` 로 해석되는지 검증한다.
|
||||
*
|
||||
* 시나리오:
|
||||
* - 응답에 `core.errors.*` 키 포함 → 해석 성공
|
||||
* - 응답에 코어 키 부재 (구 버전 백엔드) → 키 자체 반환 (fallback 동작 보존)
|
||||
* - 템플릿이 코어 키 덮어쓰기 → 템플릿 값 우선 (병합 순서 검증은 백엔드 책임이므로
|
||||
* 본 테스트는 dictionary 가 이미 병합된 상태로 들어옴을 가정)
|
||||
*/
|
||||
describe('TranslationEngine — 코어 프론트엔드 키 해석', () => {
|
||||
let engine: TranslationEngine;
|
||||
|
||||
beforeEach(() => {
|
||||
engine = new TranslationEngine({
|
||||
defaultLocale: 'ko',
|
||||
fallbackLocale: 'en',
|
||||
cacheTTL: 1000,
|
||||
});
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
const koWithCore: TranslationDictionary = {
|
||||
core: {
|
||||
errors: {
|
||||
template_not_found: '활성화된 템플릿이 없습니다',
|
||||
layout_load_failed: '레이아웃을 불러오는데 실패했습니다',
|
||||
layout_load_failed_with_id: '레이아웃({layoutId})을 불러오는데 실패했습니다',
|
||||
},
|
||||
},
|
||||
auth: { login: '로그인' },
|
||||
};
|
||||
|
||||
const enWithCore: TranslationDictionary = {
|
||||
core: {
|
||||
errors: {
|
||||
template_not_found: 'No active template found',
|
||||
layout_load_failed: 'Failed to load layout',
|
||||
},
|
||||
},
|
||||
auth: { login: 'Login' },
|
||||
};
|
||||
|
||||
const setupFetchMock = (ko: TranslationDictionary, en: TranslationDictionary) => {
|
||||
(global.fetch as any).mockImplementation((url: string) => {
|
||||
if (url.includes('/lang/ko')) {
|
||||
return Promise.resolve({ ok: true, json: async () => ko });
|
||||
}
|
||||
if (url.includes('/lang/en')) {
|
||||
return Promise.resolve({ ok: true, json: async () => en });
|
||||
}
|
||||
return Promise.resolve({ ok: false, statusText: 'Not Found' });
|
||||
});
|
||||
};
|
||||
|
||||
it('응답에 포함된 코어 키를 해석한다 (ko)', async () => {
|
||||
setupFetchMock(koWithCore, enWithCore);
|
||||
await engine.loadTranslations('template-1', 'ko');
|
||||
await engine.loadTranslations('template-1', 'en');
|
||||
|
||||
const ctx: TranslationContext = { templateId: 'template-1', locale: 'ko' };
|
||||
expect(engine.translate('core.errors.template_not_found', ctx)).toBe('활성화된 템플릿이 없습니다');
|
||||
expect(engine.translate('core.errors.layout_load_failed', ctx)).toBe('레이아웃을 불러오는데 실패했습니다');
|
||||
});
|
||||
|
||||
it('응답에 포함된 코어 키를 해석한다 (en)', async () => {
|
||||
setupFetchMock(koWithCore, enWithCore);
|
||||
await engine.loadTranslations('template-1', 'ko');
|
||||
await engine.loadTranslations('template-1', 'en');
|
||||
|
||||
const ctx: TranslationContext = { templateId: 'template-1', locale: 'en' };
|
||||
expect(engine.translate('core.errors.template_not_found', ctx)).toBe('No active template found');
|
||||
});
|
||||
|
||||
it('코어 키에서 파라미터 치환이 동작한다', async () => {
|
||||
setupFetchMock(koWithCore, enWithCore);
|
||||
await engine.loadTranslations('template-1', 'ko');
|
||||
await engine.loadTranslations('template-1', 'en');
|
||||
|
||||
const ctx: TranslationContext = { templateId: 'template-1', locale: 'ko' };
|
||||
const result = engine.translate('core.errors.layout_load_failed_with_id', ctx, '|layoutId=admin_login');
|
||||
expect(result).toBe('레이아웃(admin_login)을 불러오는데 실패했습니다');
|
||||
});
|
||||
|
||||
it('응답에 코어 키가 없으면 키 자체를 반환한다 (구버전 백엔드 fallback)', async () => {
|
||||
const koWithoutCore: TranslationDictionary = { auth: { login: '로그인' } };
|
||||
const enWithoutCore: TranslationDictionary = { auth: { login: 'Login' } };
|
||||
|
||||
setupFetchMock(koWithoutCore, enWithoutCore);
|
||||
await engine.loadTranslations('template-1', 'ko');
|
||||
await engine.loadTranslations('template-1', 'en');
|
||||
|
||||
const ctx: TranslationContext = { templateId: 'template-1', locale: 'ko' };
|
||||
// 키 부재 시 키 자체 반환 (TranslationEngine 의 표준 폴백)
|
||||
expect(engine.translate('core.errors.template_not_found', ctx)).toBe('core.errors.template_not_found');
|
||||
});
|
||||
});
|
||||
@@ -615,6 +615,47 @@ describe('TranslationEngine', () => {
|
||||
expect(result).toBe('페이지 정보: 총 500명 중 1-25명 표시');
|
||||
});
|
||||
|
||||
// 데이터 칩 param 은 개수 임의(0/1/N), 위치 임의(맨앞/중간/맨끝)일 수 있다.
|
||||
// param 정의(`|pN={{소스}}`)가 있으면 모든 조합에서 전 param 이 정확히 치환되어야 한다
|
||||
// (이전 "두 번째 파라미터 누락" 결함 재발 금지). param 정의가 없는 경우(desync)에는
|
||||
// 키 값의 raw `{pN}` 을 그대로 노출한다.
|
||||
describe('데이터 칩 param 임의 개수·위치 치환', () => {
|
||||
const ctx: TranslationContext = { templateId: 'template-1', locale: 'ko' };
|
||||
const dc = {
|
||||
current_user: { data: { uuid: 'UU', email: 'a@b.com', name: '홍길동', id: 7 } },
|
||||
};
|
||||
const run = (keyValue: string, paramsStr: string): string => {
|
||||
engine.setTranslationValue('template-1', 'ko', 'custom.t', keyValue);
|
||||
return engine.translate('custom.t', ctx, paramsStr, dc);
|
||||
};
|
||||
|
||||
it('맨 끝 1개', () => {
|
||||
expect(run('회원 {p0}', "|p0={{current_user?.data?.id ?? ''}}")).toBe('회원 7');
|
||||
});
|
||||
it('맨 앞 1개', () => {
|
||||
expect(run('{p0} 님', "|p0={{current_user?.data?.name ?? ''}}")).toBe('홍길동 님');
|
||||
});
|
||||
it('중간 1개', () => {
|
||||
expect(run('회 {p0} 원', "|p0={{current_user?.data?.uuid ?? ''}}")).toBe('회 UU 원');
|
||||
});
|
||||
it('2개(앞+뒤) — 둘 다 치환(두 번째 누락 금지)', () => {
|
||||
const r = run('회 {p0} 원 {p1} 끝', "|p0={{current_user?.data?.uuid ?? ''}}|p1={{current_user?.data?.email ?? ''}}");
|
||||
expect(r).toBe('회 UU 원 a@b.com 끝');
|
||||
expect(r).not.toContain('{p1}');
|
||||
});
|
||||
it('3개(앞·중간·끝) 전수 치환', () => {
|
||||
const r = run('{p0}-{p1}-{p2}', "|p0={{current_user?.data?.id ?? ''}}|p1={{current_user?.data?.uuid ?? ''}}|p2={{current_user?.data?.name ?? ''}}");
|
||||
expect(r).toBe('7-UU-홍길동');
|
||||
});
|
||||
it('불연속 번호(p0,p2 — p1 없음)도 각 자리 치환', () => {
|
||||
const r = run('{p0} {p2}', "|p0={{current_user?.data?.id ?? ''}}|p2={{current_user?.data?.name ?? ''}}");
|
||||
expect(r).toBe('7 홍길동');
|
||||
});
|
||||
it('param 0개(키화만, 평문) — 그대로', () => {
|
||||
expect(run('순수 평문', '')).toBe('순수 평문');
|
||||
});
|
||||
});
|
||||
|
||||
it('앰퍼샌드(&)로 구분된 파라미터도 처리', () => {
|
||||
const result = engine.translate(
|
||||
'pagination.info',
|
||||
@@ -1253,4 +1294,34 @@ describe('TranslationEngine', () => {
|
||||
expect(engine.translate('admin.modules.activate_success', context)).toBe('모듈 활성화 성공');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setTranslationValue (낙관적 즉시 반영)', () => {
|
||||
const context: TranslationContext = { templateId: 'tpl', locale: 'ko' };
|
||||
|
||||
// translate() 는 bare 키(`custom.home.2`)를 받는다($t: 접두 해석은 resolveTranslations 의 책임).
|
||||
it('빈 사전에 점선 키를 주입하면 즉시 해석된다', () => {
|
||||
engine.setTranslationValue('tpl', 'ko', 'custom.home.2', '환영합니다');
|
||||
expect(engine.translate('custom.home.2', context)).toBe('환영합니다');
|
||||
});
|
||||
|
||||
it('기존 사전의 다른 키를 보존하며 한 키만 덮어쓴다', async () => {
|
||||
(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ nav: { home: '홈' }, custom: { home: { 1: '옛값' } } }),
|
||||
});
|
||||
await engine.loadTranslations('tpl', 'ko', '/api');
|
||||
engine.setTranslationValue('tpl', 'ko', 'custom.home.1', '새값');
|
||||
// 덮어쓴 키.
|
||||
expect(engine.translate('custom.home.1', context)).toBe('새값');
|
||||
// 다른 키 보존.
|
||||
expect(engine.translate('nav.home', context)).toBe('홈');
|
||||
});
|
||||
|
||||
it('중간 경로가 문자열이어도 객체로 승격해 주입한다(충돌 방지)', () => {
|
||||
engine.setTranslationValue('tpl', 'ko', 'custom', '문자열');
|
||||
// 이후 하위 키 주입 — custom 이 문자열이지만 객체로 승격.
|
||||
engine.setTranslationValue('tpl', 'ko', 'custom.home.3', '값');
|
||||
expect(engine.translate('custom.home.3', context)).toBe('값');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { DataBindingEngine } from '../DataBindingEngine';
|
||||
import { resolveIterationSource } from '../helpers/RenderHelpers';
|
||||
|
||||
/**
|
||||
* 회귀 테스트 — iteration source / evaluateExpression 의 리터럴·내장객체 처리
|
||||
*
|
||||
* 배경: 본인인증 이력 화면(admin_identity_logs)의 상태/발생위치 필터가
|
||||
* `{{['requested','sent',...]}}` 형태의 배열 리터럴을 iteration source 로
|
||||
* 사용했으나 체크박스가 전혀 렌더되지 않았다. 채널 필터는
|
||||
* `{{Array.from(new Set((...).flatMap(...)))}}` 가 빈 배열로 평가되었다.
|
||||
*
|
||||
* 근본 원인 2종:
|
||||
* ① isComplexExpression 정규식이 `[`/`]`/`{`/`}` 를 인식하지 못해
|
||||
* 배열/객체 리터럴이 "단순 경로" 로 오판 → resolve() 경로탐색 → undefined
|
||||
* ② extractVariablesFromExpression 의 reserved 화이트리스트에 Set/Map 누락
|
||||
* → Set 이 컨텍스트 변수로 오인되어 undefined 로 전역 가림 → new undefined() 에러
|
||||
*/
|
||||
describe('iteration source / evaluateExpression - 리터럴 및 내장객체 회귀', () => {
|
||||
let engine: DataBindingEngine;
|
||||
|
||||
beforeEach(() => {
|
||||
engine = new DataBindingEngine();
|
||||
});
|
||||
|
||||
describe('resolveIterationSource - 배열/객체 리터럴 (결함 #1/#2)', () => {
|
||||
it('문자열 배열 리터럴을 그대로 배열로 반환해야 함', () => {
|
||||
const source = "{{['requested','sent','verified','failed','expired','cancelled','policy_violation_logged']}}";
|
||||
const result = resolveIterationSource(source, {}, engine);
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
expect(result).toEqual([
|
||||
'requested',
|
||||
'sent',
|
||||
'verified',
|
||||
'failed',
|
||||
'expired',
|
||||
'cancelled',
|
||||
'policy_violation_logged',
|
||||
]);
|
||||
});
|
||||
|
||||
it('숫자 배열 리터럴을 그대로 배열로 반환해야 함', () => {
|
||||
const result = resolveIterationSource('{{[1, 2, 3, 4, 5]}}', {}, engine);
|
||||
expect(result).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('발생위치(origin_type) 문자열 배열 리터럴을 반환해야 함', () => {
|
||||
const source = "{{['route','hook','policy','middleware','api','custom','system']}}";
|
||||
const result = resolveIterationSource(source, {}, engine);
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
expect(result).toHaveLength(7);
|
||||
expect(result[0]).toBe('route');
|
||||
});
|
||||
|
||||
it('객체 리터럴 배열도 그대로 반환해야 함', () => {
|
||||
const source = "{{[{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }]}}";
|
||||
const result = resolveIterationSource(source, {}, engine);
|
||||
expect(result).toEqual([
|
||||
{ id: 'a', label: 'A' },
|
||||
{ id: 'b', label: 'B' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('기존 동작 회귀 방지 - 단순 경로는 그대로 resolve', () => {
|
||||
const context = { items: { data: [{ id: 1 }, { id: 2 }] } };
|
||||
const result = resolveIterationSource('{{items.data}}', context, engine);
|
||||
expect(result).toEqual([{ id: 1 }, { id: 2 }]);
|
||||
});
|
||||
|
||||
it('기존 동작 회귀 방지 - 복잡한 표현식(?? [])은 그대로 평가', () => {
|
||||
const context = { roles: { data: [{ id: 1 }] } };
|
||||
expect(resolveIterationSource('{{roles?.data ?? []}}', context, engine)).toEqual([{ id: 1 }]);
|
||||
expect(resolveIterationSource('{{missing?.data ?? []}}', {}, engine)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('evaluateExpression - Set/Map 내장객체 (결함 #3)', () => {
|
||||
it('Array.from(new Set([...])) 로 중복 제거 배열을 반환해야 함', () => {
|
||||
const result = engine.evaluateExpression(
|
||||
"Array.from(new Set(['sms', 'email', 'sms', 'app']))",
|
||||
{},
|
||||
);
|
||||
expect(result).toEqual(['sms', 'email', 'app']);
|
||||
});
|
||||
|
||||
it('컨텍스트 데이터에서 flatMap + Set 으로 채널 후보를 도출해야 함', () => {
|
||||
const context = {
|
||||
identityProviders: {
|
||||
data: [
|
||||
{ id: 'mail', channels: ['email'] },
|
||||
{ id: 'kginicis', channels: ['sms', 'app'] },
|
||||
{ id: 'dup', channels: ['email', 'sms'] },
|
||||
],
|
||||
},
|
||||
};
|
||||
const result = engine.evaluateExpression(
|
||||
'Array.from(new Set((identityProviders?.data ?? []).flatMap(p => Array.isArray(p.channels) ? p.channels : [])))',
|
||||
context,
|
||||
);
|
||||
expect(result).toEqual(['email', 'sms', 'app']);
|
||||
});
|
||||
|
||||
it('new Map() 도 평가 가능해야 함', () => {
|
||||
const result = engine.evaluateExpression(
|
||||
"new Map([['a', 1], ['b', 2]]).get('b')",
|
||||
{},
|
||||
);
|
||||
expect(result).toBe(2);
|
||||
});
|
||||
|
||||
it('기존 내장객체(Array/Object/Math) 동작 회귀 방지', () => {
|
||||
expect(engine.evaluateExpression('Array.isArray([1,2])', {})).toBe(true);
|
||||
expect(engine.evaluateExpression('Object.keys({ a: 1, b: 2 }).length', {})).toBe(2);
|
||||
expect(engine.evaluateExpression('Math.max(3, 7, 1)', {})).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 전수조사 회귀 방지 — 순수 숫자 대괄호 인덱싱 (`items[0]`, `entry[1]`)
|
||||
*
|
||||
* 정규식에 `[` 를 추가하면 `?.`/`&&` 등 다른 연산자 없이 대괄호만 가진
|
||||
* 순수 인덱싱 표현식이 resolve() 경로에서 evaluateExpression 경로로 이동한다.
|
||||
* 코드베이스 전수조사에서 발견한 실제 사용 패턴(_isolated.selectedCategories[0],
|
||||
* nameEntry[1], $args[0].url)이 변경 전후 동일 결과를 내야 한다.
|
||||
*
|
||||
* 따옴표 키 인덱싱(`obj['key']`)은 현재 resolve() 의 PATH_SEGMENT_PATTERN
|
||||
* (`\[(\d+)\]`, 숫자 인덱스만 매칭)으로 처리 불가하므로 if/source 에
|
||||
* 순수 단독으로는 존재하지 않는다(존재 시 이미 깨져 있음). 따라서 본
|
||||
* 회귀 테스트는 실제로 동작 중이던 숫자 인덱싱을 보호한다.
|
||||
*/
|
||||
describe('전수조사 회귀 - 순수 대괄호 인덱싱 경로 이동 무영향', () => {
|
||||
it('변수[숫자] - resolve 경로와 evaluateExpression 경로 결과 일치', () => {
|
||||
const context = {
|
||||
rows: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
|
||||
};
|
||||
// resolve 경로 (변경 전 동작)
|
||||
const viaResolve = engine.resolve('rows[1]', context, { skipCache: true });
|
||||
// evaluateExpression 경로 (변경 후 동작)
|
||||
const viaEval = engine.evaluateExpression('rows[1]', context);
|
||||
expect(viaResolve).toEqual({ id: 'b' });
|
||||
expect(viaEval).toEqual({ id: 'b' });
|
||||
expect(viaEval).toEqual(viaResolve);
|
||||
});
|
||||
|
||||
it('중첩 대괄호 인덱싱 (selectedCategories[0]) 결과 일치', () => {
|
||||
const context = {
|
||||
_isolated: { selectedCategories: [{ children: [1, 2] }, { children: [] }] },
|
||||
};
|
||||
expect(engine.resolve('_isolated.selectedCategories[0]', context, { skipCache: true })).toEqual({
|
||||
children: [1, 2],
|
||||
});
|
||||
expect(engine.evaluateExpression('_isolated.selectedCategories[0]', context)).toEqual({
|
||||
children: [1, 2],
|
||||
});
|
||||
});
|
||||
|
||||
it('대괄호 인덱싱 후 속성 접근 ($args[0].url) 결과 일치', () => {
|
||||
const context = { $args: [{ url: '/admin/home' }] };
|
||||
expect(engine.resolve('$args[0].url', context, { skipCache: true })).toBe('/admin/home');
|
||||
expect(engine.evaluateExpression('$args[0].url', context)).toBe('/admin/home');
|
||||
});
|
||||
|
||||
it('Object.entries 결과 항목 인덱싱 (nameEntry[1]) if 조건 평가', () => {
|
||||
// _panel_view.json 의 "if": "{{nameEntry[1]}}" 실제 패턴
|
||||
const context = { nameEntry: ['ko', '한국어'] };
|
||||
// if 조건은 Boolean 캐스팅 — 값이 truthy 면 렌더
|
||||
expect(Boolean(engine.evaluateExpression('nameEntry[1]', context))).toBe(true);
|
||||
const emptyContext = { nameEntry: ['ko', ''] };
|
||||
expect(Boolean(engine.evaluateExpression('nameEntry[1]', emptyContext))).toBe(false);
|
||||
});
|
||||
|
||||
it('범위 밖 인덱스는 양 경로 모두 undefined', () => {
|
||||
const context = { rows: [{ id: 'a' }] };
|
||||
expect(engine.resolve('rows[5]', context, { skipCache: true })).toBeUndefined();
|
||||
expect(engine.evaluateExpression('rows[5]', context)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('스프레드 + 배열 리터럴 결합 (의존성 병합) iteration source', () => {
|
||||
// _tab_user.json 의 "source": "{{[...(row.dependencies?.modules || []), ...(row.dependencies?.plugins || [])]}}"
|
||||
const context = {
|
||||
row: { dependencies: { modules: ['m1', 'm2'], plugins: ['p1'] } },
|
||||
};
|
||||
const source =
|
||||
'{{[...(row.dependencies?.modules || []), ...(row.dependencies?.plugins || [])]}}';
|
||||
const result = resolveIterationSource(source, context, engine);
|
||||
expect(result).toEqual(['m1', 'm2', 'p1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveIterationSource + Set 결합 (채널 필터 실제 경로)', () => {
|
||||
it('Set 기반 채널 후보 배열을 iteration source 로 반환해야 함', () => {
|
||||
const context = {
|
||||
identityProviders: {
|
||||
data: [
|
||||
{ id: 'mail', channels: ['email'] },
|
||||
{ id: 'kginicis', channels: ['sms', 'app', 'email'] },
|
||||
],
|
||||
},
|
||||
};
|
||||
const source =
|
||||
'{{Array.from(new Set((identityProviders?.data ?? []).flatMap(p => Array.isArray(p.channels) ? p.channels : [])))}}';
|
||||
const result = resolveIterationSource(source, context, engine);
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
expect(result).toEqual(['email', 'sms', 'app']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -463,4 +463,123 @@ describe('sequence 내 커스텀 핸들러 상태 동기화', () => {
|
||||
expect(pendingState.status).toBe('processing');
|
||||
});
|
||||
});
|
||||
|
||||
// 상품 수정 모드 이미지 업로드 후 저장 시 백엔드가 방금 올린 이미지를 삭제하는 회귀.
|
||||
// 원인: emitEvent(업로드)의 결과(_eventResult)가 같은 sequence 의 후속 액션에 전파되지 않아
|
||||
// apiCall body 의 form.images 가 업로드 전 stale 스냅샷이었음.
|
||||
// 수정(engine-v1.51.1): emitEvent 가 __g7SequenceLocalSync 에 _eventResult 를 실어
|
||||
// handleSequence 가 currentState 를 갱신 → 후속 setState 가 _eventResult.allFiles 를 본다.
|
||||
describe('emitEvent 결과의 sequence 전파', () => {
|
||||
it('emitEvent 후 setState 가 _eventResult.data.allFiles 를 form.images 로 반영해야 함', async () => {
|
||||
const initialState = {
|
||||
form: { name: '상품', images: [] },
|
||||
isSaving: false,
|
||||
};
|
||||
|
||||
const uploadedImages = [
|
||||
{ id: 1250, hash: 'aaa', order: 1 },
|
||||
{ id: 1251, hash: 'bbb', order: 2 },
|
||||
];
|
||||
|
||||
const mockG7Core = {
|
||||
state: {
|
||||
get: () => ({ _local: initialState }),
|
||||
},
|
||||
componentEvent: {
|
||||
// 업로드 listener 가 allFiles(기존+신규, 순서반영)를 반환하는 것을 시뮬레이션
|
||||
emit: vi.fn().mockResolvedValue([
|
||||
{
|
||||
uploadedAttachments: uploadedImages,
|
||||
existingFiles: [],
|
||||
allFiles: uploadedImages,
|
||||
},
|
||||
]),
|
||||
},
|
||||
};
|
||||
(window as any).G7Core = mockG7Core;
|
||||
|
||||
const sequenceAction: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sequence',
|
||||
actions: [
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'setState',
|
||||
params: { target: 'local', isSaving: true },
|
||||
},
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'emitEvent',
|
||||
params: { event: 'upload:product_images' },
|
||||
},
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'local',
|
||||
'form.images': '{{_local._eventResult?.data?.allFiles ?? (_local.form?.images ?? [])}}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const handler = dispatcher.createHandler(sequenceAction);
|
||||
await handler({
|
||||
preventDefault: vi.fn(),
|
||||
type: 'click',
|
||||
target: null,
|
||||
} as unknown as Event);
|
||||
|
||||
// emit 이 호출되었는지 확인
|
||||
expect(mockG7Core.componentEvent.emit).toHaveBeenCalledWith(
|
||||
'upload:product_images',
|
||||
expect.anything()
|
||||
);
|
||||
|
||||
// 최종 setState 가 업로드된 이미지를 form.images 로 반영해야 함
|
||||
const lastCall = globalStateUpdater.mock.calls[globalStateUpdater.mock.calls.length - 1][0];
|
||||
expect(lastCall._local.form.images).toHaveLength(2);
|
||||
expect(lastCall._local.form.images.map((i: any) => i.id)).toEqual([1250, 1251]);
|
||||
// in-flight setState(isSaving) 도 보존
|
||||
expect(lastCall._local.isSaving).toBe(true);
|
||||
});
|
||||
|
||||
it('emitEvent 가 __g7SequenceLocalSync 에 _eventResult 를 실어야 함', async () => {
|
||||
const initialState = { form: { images: [] } };
|
||||
const mockG7Core = {
|
||||
state: { get: () => ({ _local: initialState }) },
|
||||
componentEvent: {
|
||||
emit: vi.fn().mockResolvedValue([{ allFiles: [{ id: 9, hash: 'z' }] }]),
|
||||
},
|
||||
};
|
||||
(window as any).G7Core = mockG7Core;
|
||||
|
||||
const sequenceAction: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'sequence',
|
||||
actions: [
|
||||
{ type: 'click', handler: 'emitEvent', params: { event: 'upload:x' } },
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'setState',
|
||||
params: {
|
||||
target: 'local',
|
||||
capturedListeners: '{{_local._eventResult?.listeners ?? 0}}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const handler = dispatcher.createHandler(sequenceAction);
|
||||
await handler({
|
||||
preventDefault: vi.fn(),
|
||||
type: 'click',
|
||||
target: null,
|
||||
} as unknown as Event);
|
||||
|
||||
const lastCall = globalStateUpdater.mock.calls[globalStateUpdater.mock.calls.length - 1][0];
|
||||
// 후속 setState 가 _eventResult.listeners(=1) 를 읽을 수 있어야 함
|
||||
expect(lastCall._local.capturedListeners).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,35 @@ describe('트러블슈팅 회귀 테스트 - DataGrid 컴포넌트', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('[사례 4] expandContext 객체 리터럴 fallback(|| {})이 단일 바인딩 정규식을 깨뜨림', () => {
|
||||
/**
|
||||
* 증상: expandContext 표현식에 `|| {}` 가 있으면 확장 영역이 항상 빈 값
|
||||
* (예: 데이터가 있어도 "연결 거래 없음" 고정)
|
||||
* 원인: renderExpandContent 의 단일 바인딩 판별 정규식 /^\{\{([^}]+)\}\}$/ 은
|
||||
* `}` 를 허용하지 않아 `{{... || {} }}` 가 매칭 실패 → 평가 없이 원본 문자열 전달
|
||||
* 해결: expandContext 값에서 객체 리터럴 fallback 제거 (`{{_local.x}}` 형태)
|
||||
*/
|
||||
// renderExpandContent 의 단일 바인딩 판별 정규식 (G7CoreGlobals.ts 와 동일)
|
||||
const SINGLE_BINDING_RE = /^\{\{([^}]+)\}\}$/;
|
||||
|
||||
it('객체 리터럴 fallback(|| {})이 있는 expandContext 표현식은 단일 바인딩으로 인식되지 않는다', () => {
|
||||
const broken = '{{_local.linkedTransactions || {} }}';
|
||||
// 내부 `}` 때문에 정규식 매칭 실패 → 평가되지 못하고 문자열로 전달되는 버그 조건
|
||||
expect(SINGLE_BINDING_RE.test(broken)).toBe(false);
|
||||
});
|
||||
|
||||
it('fallback 없는 단일 바인딩 표현식은 정상 매칭되어 평가된다', () => {
|
||||
const fixed = '{{_local.linkedTransactions}}';
|
||||
expect(SINGLE_BINDING_RE.test(fixed)).toBe(true);
|
||||
expect(fixed.match(SINGLE_BINDING_RE)?.[1].trim()).toBe('_local.linkedTransactions');
|
||||
});
|
||||
|
||||
it('배열 fallback(?? [])은 `}` 가 없어 정상 매칭된다 (객체 fallback 만 함정)', () => {
|
||||
const arrayFallback = '{{_local.items ?? []}}';
|
||||
expect(SINGLE_BINDING_RE.test(arrayFallback)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('[동적 컬럼 사례 1] 동적 컬럼 체크해제가 즉시 다시 체크됨', () => {
|
||||
/**
|
||||
* 증상: ColumnSelector에서 컬럼 체크해제 시 즉시 다시 체크됨
|
||||
@@ -1085,6 +1114,133 @@ describe('트러블슈팅 회귀 테스트 - 렌더링 구조', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('[슬롯 사례 5] slot 컴포넌트 포함 페이지 새로고침 시 React Hook 규칙 위반', () => {
|
||||
/**
|
||||
* 증상: 상품관리/주문관리/쿠폰관리 등 _partial_filter_section.json을 사용하는 페이지에서
|
||||
* 새로고침으로 직접 진입 시 "컴포넌트 로드 실패" 배너 (React error #300 / hook count mismatch)
|
||||
* navigate 진입 시에는 정상 동작
|
||||
*
|
||||
* 근본 원인: DynamicRenderer.tsx의 getBlurWrapperClasses useMemo가 early return 뒤에 위치
|
||||
* → slot 속성이 있는 컴포넌트는 early return으로 useMemo 미호출
|
||||
* → slot 속성이 없는 상위 컴포넌트는 useMemo 호출
|
||||
* → 렌더 사이클 간 hook 호출 개수 불일치 → React "Rendered fewer hooks" 에러
|
||||
*
|
||||
* 해결: useMemo를 early return(slot context 검사) 이전으로 이동
|
||||
* Rules of Hooks: Hook은 컴포넌트 함수 최상위에서 매 렌더마다 같은 순서로 호출
|
||||
*/
|
||||
|
||||
/**
|
||||
* DynamicRenderer 렌더 로직 시뮬레이션
|
||||
*
|
||||
* @param hasSlotAttr slot 속성 유무
|
||||
* @param slotContextEnabled globalSlotContextForRender.isEnabled 여부
|
||||
* @param hookOrder hook 호출 순서 추적용 배열 (side-effect)
|
||||
* @returns early return 여부
|
||||
*/
|
||||
function simulateRenderBadOrder(
|
||||
hasSlotAttr: boolean,
|
||||
slotContextEnabled: boolean,
|
||||
hookOrder: string[]
|
||||
): { returned: 'early' | 'normal' } {
|
||||
// ❌ 잘못된 구조: early return이 useMemo보다 앞에 있음
|
||||
if (hasSlotAttr && slotContextEnabled) {
|
||||
// useMemo 미호출 → hook count 감소
|
||||
return { returned: 'early' };
|
||||
}
|
||||
// useMemo 호출 시뮬레이션
|
||||
hookOrder.push('useMemo:getBlurWrapperClasses');
|
||||
return { returned: 'normal' };
|
||||
}
|
||||
|
||||
function simulateRenderGoodOrder(
|
||||
hasSlotAttr: boolean,
|
||||
slotContextEnabled: boolean,
|
||||
hookOrder: string[]
|
||||
): { returned: 'early' | 'normal' } {
|
||||
// ✅ 올바른 구조: useMemo가 early return보다 앞
|
||||
hookOrder.push('useMemo:getBlurWrapperClasses');
|
||||
if (hasSlotAttr && slotContextEnabled) {
|
||||
return { returned: 'early' };
|
||||
}
|
||||
return { returned: 'normal' };
|
||||
}
|
||||
|
||||
it('잘못된 구조: slot 유/무 컴포넌트 간 hook 호출 개수 불일치', () => {
|
||||
// 상위 Div: slot 없음 → useMemo 호출 (hook count 1)
|
||||
const parentHooks: string[] = [];
|
||||
const parent = simulateRenderBadOrder(false, true, parentHooks);
|
||||
|
||||
// 자식 Div: slot 속성 있음 → early return → useMemo 미호출 (hook count 0)
|
||||
const childHooks: string[] = [];
|
||||
const child = simulateRenderBadOrder(true, true, childHooks);
|
||||
|
||||
expect(parent.returned).toBe('normal');
|
||||
expect(child.returned).toBe('early');
|
||||
|
||||
// 같은 컴포넌트 함수인데 hook 호출 개수가 다름 → React Rules of Hooks 위반
|
||||
expect(parentHooks.length).not.toBe(childHooks.length);
|
||||
expect(parentHooks.length).toBe(1);
|
||||
expect(childHooks.length).toBe(0);
|
||||
});
|
||||
|
||||
it('올바른 구조: slot 유/무 컴포넌트 모두 hook 호출 개수 일정', () => {
|
||||
// 상위 Div: slot 없음 → useMemo 호출 → 정상 렌더
|
||||
const parentHooks: string[] = [];
|
||||
const parent = simulateRenderGoodOrder(false, true, parentHooks);
|
||||
|
||||
// 자식 Div: slot 속성 있음 → useMemo 호출 → early return
|
||||
const childHooks: string[] = [];
|
||||
const child = simulateRenderGoodOrder(true, true, childHooks);
|
||||
|
||||
expect(parent.returned).toBe('normal');
|
||||
expect(child.returned).toBe('early');
|
||||
|
||||
// 양쪽 모두 hook count 동일 → Rules of Hooks 준수
|
||||
expect(parentHooks.length).toBe(childHooks.length);
|
||||
expect(parentHooks.length).toBe(1);
|
||||
expect(childHooks.length).toBe(1);
|
||||
});
|
||||
|
||||
it('slot context 비활성 시에도 hook 호출 순서 일관성 유지', () => {
|
||||
// slotContext.isEnabled = false → early return 미발생
|
||||
const hooks1: string[] = [];
|
||||
simulateRenderGoodOrder(true, false, hooks1);
|
||||
|
||||
const hooks2: string[] = [];
|
||||
simulateRenderGoodOrder(false, false, hooks2);
|
||||
|
||||
// 두 경로 모두 useMemo 호출
|
||||
expect(hooks1).toEqual(['useMemo:getBlurWrapperClasses']);
|
||||
expect(hooks2).toEqual(['useMemo:getBlurWrapperClasses']);
|
||||
});
|
||||
|
||||
it('새로고침(초기 마운트) vs navigate(재렌더) 시 hook 카운트 동일', () => {
|
||||
// 초기 마운트 시 hook count 기록
|
||||
const initialHooks: string[] = [];
|
||||
simulateRenderGoodOrder(true, true, initialHooks);
|
||||
|
||||
// 리렌더 시 hook count 기록
|
||||
const rerenderHooks: string[] = [];
|
||||
simulateRenderGoodOrder(true, true, rerenderHooks);
|
||||
|
||||
// 두 렌더 사이 hook count 동일해야 React가 안정적으로 동작
|
||||
expect(initialHooks.length).toBe(rerenderHooks.length);
|
||||
});
|
||||
|
||||
it('머지 방어 가이드: DynamicRenderer의 useMemo는 모든 early return보다 앞에 위치해야 함', () => {
|
||||
// DynamicRenderer.tsx 소스에서 getBlurWrapperClasses useMemo 위치 검증
|
||||
// Rules of Hooks: "Hooks must be called at the top level"
|
||||
//
|
||||
// 자동 머지 시 feat 측 useMemo 블록이 main 측 early return 블록 뒤로 밀릴 수 있음
|
||||
// → 코드 리뷰 시 반드시 hook 위치 검증
|
||||
const sourceStructure = {
|
||||
hookLine: 3738, // getBlurWrapperClasses useMemo 시작 라인 (가변 — 대략)
|
||||
earlyReturnLine: 3806, // globalSlotContextForRender return null 라인 (가변 — 대략)
|
||||
};
|
||||
expect(sourceStructure.hookLine).toBeLessThan(sourceStructure.earlyReturnLine);
|
||||
});
|
||||
});
|
||||
|
||||
describe('[사례 7-1] cellChildren 표현식 결과 $t: 키가 번역되지 않고 그대로 노출', () => {
|
||||
/**
|
||||
* 증상: DataGrid cellChildren에서 삼항 연산자 결과 $t: 키가 번역되지 않음
|
||||
|
||||
@@ -75,12 +75,23 @@ export function createChangeEvent(
|
||||
): React.ChangeEvent<HTMLInputElement> {
|
||||
const { checked, value, name, type = 'checkbox' } = options;
|
||||
|
||||
// checkbox/radio 의 value 기본값은 boolean(checked) 그대로 둔다.
|
||||
// 명시적 value 가 없을 때 String(checked)("true"/"false") 로 문자열화하면,
|
||||
// Form 자동바인딩이 value 바인딩 경로로 처리될 경우 boolean 필드에 문자열이 저장되어
|
||||
// 백엔드 boolean 검증(예: order_settings.stock_restore_on_cancel)이 422 로 거부한다.
|
||||
// checked 바인딩 경로는 target.checked(boolean)를 쓰므로 무관하지만, value 경로까지
|
||||
// boolean 으로 안전하게 만든다. text/textarea 등은 명시 value 를 받으므로 영향 없다.
|
||||
const isCheckable = type === 'checkbox' || type === 'radio';
|
||||
const resolvedValue = value !== undefined
|
||||
? value
|
||||
: (isCheckable ? (checked ?? false) : String(checked ?? ''));
|
||||
|
||||
const target = {
|
||||
checked: checked ?? false,
|
||||
value: value ?? String(checked ?? ''),
|
||||
value: resolvedValue,
|
||||
name: name ?? '',
|
||||
type,
|
||||
} as HTMLInputElement;
|
||||
} as unknown as HTMLInputElement;
|
||||
|
||||
return {
|
||||
target,
|
||||
|
||||
@@ -115,14 +115,25 @@ export interface RenderItemChildrenOptions {
|
||||
/**
|
||||
* 복잡한 표현식 여부 감지
|
||||
*
|
||||
* 삼항 연산자(?:), 논리 연산자(&&, ||), 비교 연산자, 함수 호출 등이 포함된 경우 true 반환
|
||||
* 삼항 연산자(?:), 논리 연산자(&&, ||), 비교 연산자, 함수 호출,
|
||||
* 배열/객체 리터럴 등이 포함된 경우 true 반환
|
||||
*
|
||||
* true 인 경우 evaluateExpression(JS 평가)로, false 인 경우 resolve(dot/bracket
|
||||
* path 탐색)로 라우팅된다.
|
||||
*
|
||||
* `[`/`]`/`{`/`}` 포함 (@since engine-v1.50.0):
|
||||
* `{{['a','b']}}` 같은 배열 리터럴이나 `{{[{...}]}}` 같은 객체 리터럴이
|
||||
* "단순 경로"로 오판되어 resolve() 경로탐색 → undefined 가 되던 문제를 해결한다.
|
||||
* 순수 숫자 대괄호 인덱싱(`items[0]`, `entry[1]`)은 resolve()/evaluateExpression()
|
||||
* 양 경로의 결과가 동일하므로(회귀 테스트로 입증) 경로 이동에 따른 동작 변화가 없다.
|
||||
*
|
||||
* @param expr - 검사할 표현식
|
||||
* @returns 복잡한 표현식 여부
|
||||
*/
|
||||
function isComplexExpression(expr: string): boolean {
|
||||
// () 추가: $localized(menu.name) 같은 함수 호출 표현식도 복잡한 표현식으로 처리
|
||||
return /[?:|&!+\-*/<>=()]/.test(expr);
|
||||
// []{} 추가: 배열/객체 리터럴(`['a','b']`, `[{...}]`)을 evaluateExpression 으로 라우팅
|
||||
return /[?:|&!+\-*/<>=()[\]{}]/.test(expr);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* EventHelpers 단위 테스트
|
||||
*
|
||||
* createChangeEvent 의 checkbox/radio value 직렬화 회귀 가드.
|
||||
* 배경: Toggle 이 createChangeEvent({checked}) 로 만든 이벤트가 Form 자동바인딩 value
|
||||
* 경로로 처리될 때 value 가 "true"/"false"(문자열)이면 백엔드 boolean 검증이 422 로
|
||||
* 거부하던 결함(설정 "취소 시 재고 복구" 토글 ON 저장 422). checkbox/radio 의 value 는
|
||||
* boolean(checked)으로 두어 어느 바인딩 경로로 가도 boolean 이 저장되도록 한다.
|
||||
*
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createChangeEvent } from '../EventHelpers';
|
||||
|
||||
describe('createChangeEvent — value 직렬화', () => {
|
||||
it('checkbox(기본 type) — checked=true 면 value 가 boolean true', () => {
|
||||
const e = createChangeEvent({ checked: true, name: 'order_settings.stock_restore_on_cancel' });
|
||||
|
||||
expect(e.target.checked).toBe(true);
|
||||
// 문자열 "true" 가 아니라 boolean true 여야 한다 (백엔드 boolean 검증 통과)
|
||||
expect(e.target.value as unknown).toBe(true);
|
||||
expect(typeof (e.target.value as unknown)).toBe('boolean');
|
||||
});
|
||||
|
||||
it('checkbox — checked=false 면 value 가 boolean false', () => {
|
||||
const e = createChangeEvent({ checked: false, name: 'flag' });
|
||||
|
||||
expect(e.target.checked).toBe(false);
|
||||
expect(e.target.value as unknown).toBe(false);
|
||||
expect(typeof (e.target.value as unknown)).toBe('boolean');
|
||||
});
|
||||
|
||||
it('type: checkbox 명시 — value 가 boolean', () => {
|
||||
const e = createChangeEvent({ checked: true, name: 'flag', type: 'checkbox' });
|
||||
|
||||
expect(e.target.value as unknown).toBe(true);
|
||||
});
|
||||
|
||||
it('type: radio — value 가 boolean', () => {
|
||||
const e = createChangeEvent({ checked: true, name: 'r', type: 'radio' });
|
||||
|
||||
expect(e.target.value as unknown).toBe(true);
|
||||
});
|
||||
|
||||
it('명시적 value 전달 시 그 값을 그대로 사용 (checkbox 라도)', () => {
|
||||
const e = createChangeEvent({ checked: true, value: 'apple', name: 'r', type: 'checkbox' });
|
||||
|
||||
expect(e.target.value).toBe('apple');
|
||||
});
|
||||
|
||||
it('text 입력 — value 를 그대로 문자열로 사용', () => {
|
||||
const e = createChangeEvent({ value: 'hello', name: 'title', type: 'text' });
|
||||
|
||||
expect(e.target.value).toBe('hello');
|
||||
});
|
||||
|
||||
it('text 입력 — value 미지정 + checked 미지정이면 빈 문자열', () => {
|
||||
const e = createChangeEvent({ name: 'title', type: 'text' });
|
||||
|
||||
expect(e.target.value).toBe('');
|
||||
});
|
||||
|
||||
it('event 표면 형태 — change 타입 + name 보존', () => {
|
||||
const e = createChangeEvent({ checked: true, name: 'foo' });
|
||||
|
||||
expect(e.type).toBe('change');
|
||||
expect(e.target.name).toBe('foo');
|
||||
expect(e.currentTarget).toBe(e.target);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,618 @@
|
||||
// e2e:allow(기반 인프라) — spec/엔진/훅/공용 부품만 변경, 브라우저 가시
|
||||
// UI 미연결(페이지 설정 탭·셸·진입점은 세션 D). Playwright E2E 는 세션 D 에서 추가.
|
||||
/**
|
||||
* EditorModalContext.tsx — 편집기 전용 모달 스택 컨텍스트
|
||||
*
|
||||
* 결정 사항:
|
||||
* - 위치: layout-editor 도메인 하위. 코어 글로벌 `_global.modal` 시스템과 분리 —
|
||||
* 편집기 캔버스의 격리 store/facade(installPreviewCanvasStore) 와 충돌 회피.
|
||||
* - 백드롭 클릭 / ESC = 닫기 (대다수 편집기 패턴).
|
||||
* - 스택 depth 무제한 — 속성 편집 모달 위에 sub-picker, 그 위에 confirm 등 가능.
|
||||
*
|
||||
* 편집기 안에서 모달이 자주 쓰일 예정이므로 (요소 추가 / 속성 편집 / 409 충돌
|
||||
* 안내 / 미리보기 / dirty 가드 등) 공용 인프라로 둠. 호출자는 `useEditorModal()`
|
||||
* 의 `open(node)` / `close(id)` / `closeTop()` / `closeAll()` 만 다룸.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React, {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
/**
|
||||
* 모달 표시 옵션 — 호출자가 `open(...)` 에 전달.
|
||||
*/
|
||||
export interface EditorModalOptions {
|
||||
/** 모달 식별자 — 미지정 시 자동 생성. 같은 id 재오픈은 idempotent (덮어쓰기) */
|
||||
id?: string;
|
||||
/** 모달 본문 (header/footer 포함 — EditorModal 컴포넌트가 dialog frame 만 제공) */
|
||||
content: React.ReactNode;
|
||||
/** ARIA label — 스크린리더용 */
|
||||
ariaLabel?: string;
|
||||
/**
|
||||
* 백드롭 클릭 시 닫힘 여부. 기본 true.
|
||||
* false 로 두면 명시적 close 호출만 닫음 (정보성 모달 / 강제 확인).
|
||||
*/
|
||||
closeOnBackdrop?: boolean;
|
||||
/**
|
||||
* ESC 키로 닫힘 여부. 기본 true.
|
||||
* false 로 두면 ESC 무시 (격리 입력 모드 등).
|
||||
*/
|
||||
closeOnEscape?: boolean;
|
||||
/**
|
||||
* 모달 width — px 또는 'auto'. 기본 'auto'.
|
||||
* 큰 모달(팔레트/속성 편집)은 명시 픽셀 권장.
|
||||
*/
|
||||
width?: number | string;
|
||||
/**
|
||||
* 모달 height — px 또는 'auto'. 기본 'auto'.
|
||||
*/
|
||||
height?: number | string;
|
||||
/**
|
||||
* 모달 max-height — viewport 비율 (0~1) 또는 px. 기본 0.85 (viewport 의 85%).
|
||||
*/
|
||||
maxHeightRatio?: number;
|
||||
/**
|
||||
* 헤더 드래그로 모달 위치를 옮길 수 있는지. 기본 false.
|
||||
* true 면 (1) 헤더(`g7le-modal__drag-handle` 또는 모달 상단 영역) pointerdown 으로
|
||||
* 이동, (2) 백드롭은 `pointerEvents:none` 으로 두어 캔버스 결과를 보며 이동,
|
||||
* (3) 초기 위치는 `avoidRect`(선택 요소) 를 피해 좌/우 빈 공간 중 넓은 쪽.
|
||||
*/
|
||||
draggable?: boolean;
|
||||
/**
|
||||
* draggable 모달이 가리지 말아야 할 영역 — 선택 요소의 viewport 좌표.
|
||||
* 좌/우 빈 공간 중 모달 폭이 들어가는 넓은 쪽에 초기 배치한다. 양쪽 다 좁으면
|
||||
* 중앙 유지(요청 사양). 미지정 시 중앙.
|
||||
*/
|
||||
avoidRect?: { left: number; top: number; width: number; height: number };
|
||||
/** 모달이 닫힐 때 호출 (백드롭/ESC/명시 close 모두) */
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
interface InternalEntry
|
||||
extends Required<
|
||||
Omit<
|
||||
EditorModalOptions,
|
||||
'id' | 'onClose' | 'width' | 'height' | 'maxHeightRatio' | 'avoidRect'
|
||||
>
|
||||
> {
|
||||
id: string;
|
||||
onClose?: () => void;
|
||||
width: number | string;
|
||||
height: number | string;
|
||||
maxHeightRatio: number;
|
||||
draggable: boolean;
|
||||
avoidRect?: { left: number; top: number; width: number; height: number };
|
||||
}
|
||||
|
||||
export interface EditorModalContextValue {
|
||||
/** 모달 열기 — id 반환 (호출자가 나중에 close 호출 시 사용) */
|
||||
open: (options: EditorModalOptions) => string;
|
||||
/** 특정 id 모달 닫기 */
|
||||
close: (id: string) => void;
|
||||
/** 스택 최상위 모달 닫기 (ESC/백드롭의 기본 동작과 동일) */
|
||||
closeTop: () => void;
|
||||
/** 전체 모달 닫기 */
|
||||
closeAll: () => void;
|
||||
/** 현재 열려 있는 모달 스택 (디버그/테스트용) */
|
||||
stack: ReadonlyArray<InternalEntry>;
|
||||
/**
|
||||
* 모달을 최소화한다. **언마운트하지 않고** display:none +
|
||||
* 하단 바로 접는다 — 모달 내부 입력값·활성 탭·picker 진행 상태가 전부 보존된다. picker 가
|
||||
* 캔버스를 선택하려면 그 위 모달이 비켜야 하므로(범용 기능 — picker 전용 아님).
|
||||
*
|
||||
* @param id 최소화할 모달 id
|
||||
* @param label 하단 바에 표시할 라벨(미지정 시 ariaLabel)
|
||||
*/
|
||||
minimize: (id: string, label?: string) => void;
|
||||
/**
|
||||
* 최소화된 모달을 복원한다.
|
||||
*
|
||||
* @param id 복원할 모달 id
|
||||
*/
|
||||
restore: (id: string) => void;
|
||||
/** 최소화된 모달 id 목록 (하단 바 렌더용) */
|
||||
minimizedStack: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const EditorModalContext = createContext<EditorModalContextValue | null>(null);
|
||||
|
||||
let nextAutoId = 1;
|
||||
|
||||
export interface EditorModalProviderProps {
|
||||
children: React.ReactNode;
|
||||
/**
|
||||
* 다국어 해석 함수 — 최소화 바의 사용자 대면 문구(복원/기본 라벨) 해석용.
|
||||
* 미지정 시 키 폴백(identity). LayoutEditorChrome 이 `t` 를 전달한다.
|
||||
*/
|
||||
t?: (key: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider — LayoutEditorChrome 의 최상단에서 한 번만 마운트.
|
||||
*
|
||||
* Provider 자체는 모달 DOM 을 렌더하지 않는다 — `EditorModalRoot` 가 분리
|
||||
* 마운트되어 portal-style 로 caller subtree 최상위에 표시. 두 컴포넌트는
|
||||
* 같은 Context 인스턴스를 공유해 state 가 단일 진실 공급원.
|
||||
*/
|
||||
export function EditorModalProvider({ children, t }: EditorModalProviderProps): React.ReactElement {
|
||||
const [stack, setStack] = useState<InternalEntry[]>([]);
|
||||
const stackRef = useRef<InternalEntry[]>([]);
|
||||
// 최소화 상태 — id → 하단 바 라벨. 언마운트 X(display:none + 하단 바).
|
||||
const [minimized, setMinimized] = useState<Record<string, string>>({});
|
||||
|
||||
const open = useCallback((options: EditorModalOptions): string => {
|
||||
const id = options.id ?? `editor-modal-${nextAutoId++}`;
|
||||
const entry: InternalEntry = {
|
||||
id,
|
||||
content: options.content,
|
||||
ariaLabel: options.ariaLabel ?? '',
|
||||
closeOnBackdrop: options.closeOnBackdrop ?? true,
|
||||
closeOnEscape: options.closeOnEscape ?? true,
|
||||
width: options.width ?? 'auto',
|
||||
height: options.height ?? 'auto',
|
||||
maxHeightRatio: options.maxHeightRatio ?? 0.85,
|
||||
draggable: options.draggable ?? false,
|
||||
avoidRect: options.avoidRect,
|
||||
onClose: options.onClose,
|
||||
};
|
||||
setStack((prev) => {
|
||||
// 같은 id 재오픈은 덮어쓰기 (idempotent)
|
||||
const filtered = prev.filter((e) => e.id !== id);
|
||||
const next = [...filtered, entry];
|
||||
stackRef.current = next;
|
||||
return next;
|
||||
});
|
||||
return id;
|
||||
}, []);
|
||||
|
||||
const close = useCallback((id: string): void => {
|
||||
setStack((prev) => {
|
||||
const target = prev.find((e) => e.id === id);
|
||||
const next = prev.filter((e) => e.id !== id);
|
||||
stackRef.current = next;
|
||||
// setState 이후 비동기로 onClose 호출 — 콜백 안에서 다시 open/close 호출 시
|
||||
// 안전성 보장 (현재 reducer 가 끝난 후 실행)
|
||||
if (target?.onClose) {
|
||||
queueMicrotask(() => target.onClose?.());
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const closeTop = useCallback((): void => {
|
||||
const top = stackRef.current[stackRef.current.length - 1];
|
||||
if (top) close(top.id);
|
||||
}, [close]);
|
||||
|
||||
const closeAll = useCallback((): void => {
|
||||
setStack((prev) => {
|
||||
// 닫히는 순서대로 onClose 호출 (top → bottom)
|
||||
for (let i = prev.length - 1; i >= 0; i--) {
|
||||
const entry = prev[i];
|
||||
if (entry?.onClose) {
|
||||
queueMicrotask(() => entry.onClose?.());
|
||||
}
|
||||
}
|
||||
stackRef.current = [];
|
||||
return [];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const minimize = useCallback((id: string, label?: string): void => {
|
||||
setMinimized((prev) => {
|
||||
const entry = stackRef.current.find((e) => e.id === id);
|
||||
const text = label ?? entry?.ariaLabel ?? '';
|
||||
return { ...prev, [id]: text };
|
||||
});
|
||||
}, []);
|
||||
|
||||
const restore = useCallback((id: string): void => {
|
||||
setMinimized((prev) => {
|
||||
if (!(id in prev)) return prev;
|
||||
const next = { ...prev };
|
||||
delete next[id];
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// close/closeAll 시 최소화 상태도 함께 정리(잔존 하단 바 방지).
|
||||
const closeAndUnminimize = useCallback(
|
||||
(id: string): void => {
|
||||
restore(id);
|
||||
close(id);
|
||||
},
|
||||
[restore, close],
|
||||
);
|
||||
|
||||
const closeAllAndClear = useCallback((): void => {
|
||||
setMinimized({});
|
||||
closeAll();
|
||||
}, [closeAll]);
|
||||
|
||||
const minimizedStack = useMemo<string[]>(() => Object.keys(minimized), [minimized]);
|
||||
|
||||
const value = useMemo<EditorModalContextValue>(
|
||||
() => ({
|
||||
open,
|
||||
close: closeAndUnminimize,
|
||||
closeTop,
|
||||
closeAll: closeAllAndClear,
|
||||
stack,
|
||||
minimize,
|
||||
restore,
|
||||
minimizedStack,
|
||||
}),
|
||||
[open, closeAndUnminimize, closeTop, closeAllAndClear, stack, minimize, restore, minimizedStack]
|
||||
);
|
||||
|
||||
return React.createElement(
|
||||
EditorModalContext.Provider,
|
||||
{ value },
|
||||
children,
|
||||
React.createElement(MinimizedBar, { minimized, onRestore: restore, t, key: '__min_bar' }),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 호출자가 모달을 열고 닫는 진입점.
|
||||
*
|
||||
* Provider 외부에서 호출 시 throw — 마운트 순서가 잘못된 경우 fail-fast.
|
||||
*/
|
||||
export function useEditorModal(): EditorModalContextValue {
|
||||
const ctx = useContext(EditorModalContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useEditorModal must be used within EditorModalProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* EditorModalRoot — 모달 스택을 실제 DOM 으로 렌더.
|
||||
*
|
||||
* Provider 와 같은 Context 인스턴스를 공유하며, 호출자가 LayoutEditorChrome 최상위
|
||||
* (Provider 안쪽 + 본문보다 뒤) 에 1회 마운트. portal 없이 자식으로 그리되,
|
||||
* `position: fixed` + 최상위 z-index 로 모든 콘텐츠 위에 표시.
|
||||
*
|
||||
* ESC 키는 가장 위 모달의 closeOnEscape 옵션에 따라 처리. input/textarea 포커스
|
||||
* 중에도 ESC 는 모달 닫기로 가로챔 (편집기 입력은 인라인 텍스트 등 별도 흐름).
|
||||
*/
|
||||
export function EditorModalRoot(): React.ReactElement | null {
|
||||
const ctx = useContext(EditorModalContext);
|
||||
if (!ctx) {
|
||||
// Provider 없는 환경(테스트 등)에서는 단순 null 렌더
|
||||
return null;
|
||||
}
|
||||
const { stack, close, minimizedStack } = ctx;
|
||||
const minimizedSet = useMemo(() => new Set(minimizedStack), [minimizedStack]);
|
||||
|
||||
// ESC 키 전역 핸들러 — 가장 위(최소화 안 된) 모달이 closeOnEscape=true 면 닫기.
|
||||
useEffect(() => {
|
||||
if (stack.length === 0) return;
|
||||
const handler = (e: KeyboardEvent): void => {
|
||||
if (e.key !== 'Escape' && e.key !== 'Esc') return;
|
||||
// 최소화된 모달은 ESC 대상에서 제외(화면에 없음).
|
||||
const visible = stack.filter((s) => !minimizedSet.has(s.id));
|
||||
const top = visible[visible.length - 1];
|
||||
if (!top?.closeOnEscape) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
close(top.id);
|
||||
};
|
||||
window.addEventListener('keydown', handler, true);
|
||||
return () => window.removeEventListener('keydown', handler, true);
|
||||
}, [stack, close, minimizedSet]);
|
||||
|
||||
if (stack.length === 0) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{stack.map((entry, index) => (
|
||||
<ModalLayer
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
depth={index}
|
||||
// 최소화된 모달은 display:none 으로 숨기되 언마운트하지 않는다(상태 보존).
|
||||
hidden={minimizedSet.has(entry.id)}
|
||||
onClose={() => close(entry.id)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* MinimizedBar — 화면 하단의 최소화된 모달 복원 바.
|
||||
*
|
||||
* Provider 가 children 뒤에 렌더한다. 최소화된 모달이 없으면 null. 각 항목 클릭 시 복원.
|
||||
*
|
||||
* @param minimized id → 라벨 맵
|
||||
* @param onRestore 복원 콜백
|
||||
*/
|
||||
function MinimizedBar({
|
||||
minimized,
|
||||
onRestore,
|
||||
t,
|
||||
}: {
|
||||
minimized: Record<string, string>;
|
||||
onRestore: (id: string) => void;
|
||||
t?: (key: string) => string;
|
||||
}): React.ReactElement | null {
|
||||
const tr = t ?? ((k: string) => k);
|
||||
const ids = Object.keys(minimized);
|
||||
if (ids.length === 0) return null;
|
||||
return (
|
||||
<div
|
||||
className="g7le-minimized-bar"
|
||||
data-testid="g7le-minimized-bar"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: 16,
|
||||
bottom: 16,
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
zIndex: 9300,
|
||||
}}
|
||||
>
|
||||
{ids.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
data-testid={`g7le-minimized-${id}`}
|
||||
onClick={() => onRestore(id)}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
padding: '8px 12px',
|
||||
background: '#1e293b',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 8px 24px rgba(15, 23, 42, 0.3)',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">🗗</span>
|
||||
<span>{minimized[id] || tr('layout_editor.modal.minimized_default')}</span>
|
||||
<span style={{ opacity: 0.7 }}>{tr('layout_editor.modal.restore')}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ModalLayerProps {
|
||||
entry: InternalEntry;
|
||||
depth: number;
|
||||
/** 최소화 시 display:none (언마운트 X — 상태 보존) */
|
||||
hidden?: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* draggable 모달의 초기 위치를 계산.
|
||||
*
|
||||
* `avoidRect`(선택 요소 viewport 좌표) 의 좌/우 빈 공간 중 모달 폭이 들어가는
|
||||
* 넓은 쪽에 배치한다. 양쪽 다 모달 폭보다 좁으면 null(중앙 유지 — 요청 사양).
|
||||
* 세로는 선택 요소 상단에 맞추되 viewport 안으로 클램프.
|
||||
*
|
||||
* @param avoidRect 피할 선택 요소 영역
|
||||
* @param modalWidth 모달 폭(px 추정)
|
||||
* @param modalHeight 모달 높이(px 추정)
|
||||
* @return {left, top} viewport 좌표 또는 null(중앙)
|
||||
*/
|
||||
function computeAvoidPosition(
|
||||
avoidRect: { left: number; top: number; width: number; height: number } | undefined,
|
||||
modalWidth: number,
|
||||
modalHeight: number,
|
||||
): { left: number; top: number } | null {
|
||||
if (!avoidRect || typeof window === 'undefined') return null;
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const gap = 16;
|
||||
const leftSpace = avoidRect.left; // 선택 요소 왼쪽 빈 공간
|
||||
const rightSpace = vw - (avoidRect.left + avoidRect.width); // 오른쪽 빈 공간
|
||||
const needed = modalWidth + gap;
|
||||
|
||||
let left: number;
|
||||
if (rightSpace >= leftSpace && rightSpace >= needed) {
|
||||
// 오른쪽 빈 공간이 넓고 충분 — 선택 요소 오른쪽에 배치
|
||||
left = avoidRect.left + avoidRect.width + gap;
|
||||
} else if (leftSpace >= needed) {
|
||||
// 왼쪽 빈 공간에 배치 (모달 우측 끝이 선택 요소 좌측 - gap)
|
||||
left = Math.max(gap, avoidRect.left - gap - modalWidth);
|
||||
} else {
|
||||
// 양쪽 다 좁음 — 중앙 유지
|
||||
return null;
|
||||
}
|
||||
// viewport 가로 클램프
|
||||
left = Math.min(Math.max(gap, left), Math.max(gap, vw - modalWidth - gap));
|
||||
// 세로 — 선택 요소 상단에 맞추되 viewport 안으로 클램프
|
||||
let top = avoidRect.top;
|
||||
top = Math.min(Math.max(gap, top), Math.max(gap, vh - modalHeight - gap));
|
||||
return { left, top };
|
||||
}
|
||||
|
||||
/**
|
||||
* 비-draggable 모달의 상단 고정 여백. 상단 정렬 + 이 여백으로 탭이 바뀌어도
|
||||
* 모달 top 이 고정된다. maxHeight 도 이 여백의 2배(상·하)를 빼 화면 안에 들어오게 한다.
|
||||
*/
|
||||
const MODAL_TOP_GAP = 'clamp(16px, 6vh, 56px)';
|
||||
|
||||
function ModalLayer({ entry, depth, hidden, onClose }: ModalLayerProps): React.ReactElement {
|
||||
// 최상위 z-index 베이스 9100 — LayoutEditorChrome 의 z-index 9000 보다 위.
|
||||
// depth 별로 10씩 증가해 스택 위 모달이 항상 아래 모달 위에 표시.
|
||||
const zIndex = 9100 + depth * 10;
|
||||
|
||||
// viewport 기준 max-height — vh/calc 문자열로 둔다(픽셀 고정 금지).
|
||||
// 픽셀로 한 번 계산해 박으면(마운트 시점 window.innerHeight) 창을 줄여도 재계산되지 않아
|
||||
// 모달이 화면을 넘쳐 백드롭이 스크롤되고 상단 탭/제목이 사라진다.
|
||||
// 비-draggable 모달은 상단 정렬 + 상단 여백(MODAL_TOP_GAP)을 쓰므로, 그 여백과 같은 크기의
|
||||
// 하단 여백을 함께 빼 모달이 화면(제목·탭 포함) 안에 항상 들어오게 한다. ratio 는 상한으로만.
|
||||
const ratioCap = entry.maxHeightRatio > 0 ? `${entry.maxHeightRatio * 100}vh` : undefined;
|
||||
// 비-draggable 모달은 상단 정렬 + 상단 여백을 쓰므로 그 여백의 2배(상·하)를 빼 화면(제목·탭
|
||||
// 포함) 안에 항상 들어오게 한다. min()/clamp() 복합값은 jsdom 인라인 style 이 떨구므로 calc
|
||||
// 하나로만 표현(브라우저는 calc 안에서 vh·px 혼합을 리사이즈마다 자동 재계산 — 픽셀 고정 회피).
|
||||
// draggable 모달은 종전대로 ratio vh 상한(자유 배치라 화면맞춤 calc 불필요).
|
||||
const maxHeight = entry.draggable
|
||||
? ratioCap
|
||||
: `calc(100vh - (${MODAL_TOP_GAP}) * 2)`;
|
||||
|
||||
// draggable 모달 위치 상태 — null = 미배치(중앙) / {left,top} = 자유 위치.
|
||||
const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
|
||||
const modalElRef = useRef<HTMLDivElement | null>(null);
|
||||
const dragRef = useRef<{ startX: number; startY: number; baseLeft: number; baseTop: number } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
// 초기 자동 회피 위치 계산 — 모달이 실제로 마운트돼 크기를 알게 된 직후 1회.
|
||||
// draggable 이 아니면 position 을 두지 않아 종전 중앙 정렬 그대로(회귀 0).
|
||||
useEffect(() => {
|
||||
if (!entry.draggable) return;
|
||||
const el = modalElRef.current;
|
||||
if (!el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const pos = computeAvoidPosition(entry.avoidRect, rect.width, rect.height);
|
||||
if (pos) setPosition(pos);
|
||||
// entry.id 가 바뀌면(다른 모달) 재계산. avoidRect 는 open 시점 고정값.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [entry.id, entry.draggable]);
|
||||
|
||||
// 헤더 드래그 — 경량 포인터 핸들러(useResizeHandles 패턴 답습, dnd-kit 비사용).
|
||||
const onHeaderPointerDown = useCallback(
|
||||
(e: React.PointerEvent): void => {
|
||||
if (!entry.draggable) return;
|
||||
const target = e.target as HTMLElement;
|
||||
// 드래그 시작점은 헤더 드래그 핸들(`data-modal-drag-handle`) 영역만 —
|
||||
// 모달 본문(탭/컨트롤)에서 시작한 포인터는 이동 트리거 아님.
|
||||
const handle = target.closest('[data-modal-drag-handle]');
|
||||
if (!handle) return;
|
||||
// 핸들 안이라도 닫기 버튼/입력 등 인터랙티브 요소는 제외.
|
||||
if (target.closest('button, a, input, textarea, select')) return;
|
||||
const el = modalElRef.current;
|
||||
const rect = el?.getBoundingClientRect();
|
||||
const baseLeft = position?.left ?? rect?.left ?? 0;
|
||||
const baseTop = position?.top ?? rect?.top ?? 0;
|
||||
dragRef.current = { startX: e.clientX, startY: e.clientY, baseLeft, baseTop };
|
||||
|
||||
const onMove = (ev: PointerEvent): void => {
|
||||
const d = dragRef.current;
|
||||
if (!d) return;
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const w = el?.offsetWidth ?? 0;
|
||||
const h = el?.offsetHeight ?? 0;
|
||||
let nextLeft = d.baseLeft + (ev.clientX - d.startX);
|
||||
let nextTop = d.baseTop + (ev.clientY - d.startY);
|
||||
// viewport 클램프 — 모달이 화면 밖으로 완전히 나가지 않도록
|
||||
nextLeft = Math.min(Math.max(0, nextLeft), Math.max(0, vw - w));
|
||||
nextTop = Math.min(Math.max(0, nextTop), Math.max(0, vh - h));
|
||||
setPosition({ left: nextLeft, top: nextTop });
|
||||
};
|
||||
const onUp = (): void => {
|
||||
dragRef.current = null;
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
};
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
},
|
||||
[entry.draggable, position],
|
||||
);
|
||||
|
||||
const handleBackdropClick = (e: React.MouseEvent): void => {
|
||||
if (!entry.closeOnBackdrop) return;
|
||||
// draggable 모달은 백드롭이 pointerEvents:none 이라 이 핸들러가 호출되지 않지만,
|
||||
// 안전상 currentTarget 일치 검사 유지.
|
||||
if (e.target !== e.currentTarget) return;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const positioned = entry.draggable && position !== null;
|
||||
|
||||
// draggable 모달 — 백드롭을 pointerEvents:none 으로 두어 캔버스 결과를 보며 이동.
|
||||
// 모달 본문만 pointerEvents:auto. 비-draggable 모달은 종전 중앙 정렬 + 어둡게(회귀 0).
|
||||
const backdropStyle: React.CSSProperties = entry.draggable
|
||||
? {
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'transparent',
|
||||
pointerEvents: 'none',
|
||||
zIndex,
|
||||
// 최소화 시 숨김(언마운트 X — 상태 보존). draggable 의 flex 미사용.
|
||||
...(hidden ? { display: 'none' } : {}),
|
||||
}
|
||||
: {
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(15, 23, 42, 0.45)',
|
||||
display: hidden ? 'none' : 'flex',
|
||||
// 상단 정렬(flex-start) — 세로 중앙 정렬이면 탭마다 모달 높이가 바뀔 때 중앙 기준
|
||||
// top 이 출렁이고(위치가 자꾸 바뀜), 콘텐츠가 maxHeight 에 닿으면 위로 밀려 제목·탭이
|
||||
// 화면 밖으로 잘린다. 상단 고정 여백을 두면 탭이 바뀌어도 top 이 고정되고
|
||||
// 높이는 아래로만 늘며, maxHeight(vh)가 화면 초과를 막아 제목·탭이 항상 보인다.
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'center',
|
||||
paddingTop: MODAL_TOP_GAP,
|
||||
boxSizing: 'border-box',
|
||||
zIndex,
|
||||
};
|
||||
|
||||
const modalStyle: React.CSSProperties = {
|
||||
background: '#fff',
|
||||
borderRadius: 10,
|
||||
boxShadow: '0 20px 60px rgba(15, 23, 42, 0.25)',
|
||||
width: entry.width,
|
||||
height: entry.height,
|
||||
maxHeight,
|
||||
maxWidth: '92vw',
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
...(entry.draggable
|
||||
? {
|
||||
position: 'absolute',
|
||||
pointerEvents: 'auto',
|
||||
// 자동 회피 위치가 정해지기 전(초기 1프레임)은 중앙 유지
|
||||
left: positioned ? position!.left : '50%',
|
||||
top: positioned ? position!.top : '50%',
|
||||
transform: positioned ? undefined : 'translate(-50%, -50%)',
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="g7le-modal-backdrop"
|
||||
role="presentation"
|
||||
data-testid={`g7le-modal-backdrop-${entry.id}`}
|
||||
data-draggable={entry.draggable ? 'true' : 'false'}
|
||||
onClick={handleBackdropClick}
|
||||
style={backdropStyle}
|
||||
>
|
||||
<div
|
||||
ref={modalElRef}
|
||||
className="g7le-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={entry.ariaLabel || undefined}
|
||||
data-testid={`g7le-modal-${entry.id}`}
|
||||
data-positioned={positioned ? 'true' : 'false'}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={entry.draggable ? onHeaderPointerDown : undefined}
|
||||
style={modalStyle}
|
||||
>
|
||||
{entry.content}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* LayoutDocumentContext.tsx — useLayoutDocument 결과 공유 컨텍스트
|
||||
*
|
||||
* useLayoutDocument 를 LayoutEditorChrome 에서 호출해 결과를 Context 로 내려주고,
|
||||
* PreviewCanvas / Toolbar / Overlay 들이 모두 동일 인스턴스를 공유한다. 두 곳
|
||||
* 에서 같은 hook 을 부르면 두 인스턴스가 되어 patch/save 가 서로 보이지 않는
|
||||
* 결함이 생기므로 단일 진입점이 필수.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import type { UseLayoutDocumentResult } from './hooks/useLayoutDocument';
|
||||
|
||||
const LayoutDocumentContext = createContext<UseLayoutDocumentResult | null>(null);
|
||||
|
||||
export interface LayoutDocumentProviderProps {
|
||||
value: UseLayoutDocumentResult;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function LayoutDocumentProvider({ value, children }: LayoutDocumentProviderProps): React.ReactElement {
|
||||
return React.createElement(LayoutDocumentContext.Provider, { value }, children);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider 마운트 전에 호출되면 fallback (자체 useLayoutDocument 호출) 을 위해
|
||||
* null 반환. 호출자가 그 경우를 분기 처리한다.
|
||||
*/
|
||||
export function useLayoutDocumentContext(): UseLayoutDocumentResult | null {
|
||||
return useContext(LayoutDocumentContext);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,479 @@
|
||||
/**
|
||||
* LayoutEditorContext.tsx
|
||||
*
|
||||
* 레이아웃 편집기 도메인 상태.
|
||||
*
|
||||
* 본 Context 는 코어 컨텍스트 래퍼(TranslationProvider/TransitionProvider/
|
||||
* ResponsiveProvider/SlotProvider) **안쪽** 에 마운트된다. 코어
|
||||
* 컨텍스트는 항상 상속하며, 편집기 도메인 상태만 별도 useReducer 로 격리.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext, useEffect, useMemo, useReducer } from 'react';
|
||||
import { trackEditorState } from './devtools/editorTrackers';
|
||||
import type { EditorAccessError } from './types/editorErrors';
|
||||
import type { EditorStateItemSpec } from './spec/specTypes';
|
||||
|
||||
/**
|
||||
* 라우트 트리 접힘 상태 영속화 키 (localStorage). 편집 세션/새로고침/템플릿 전환
|
||||
* 간에도 사용자가 접어둔 상태가 유지되도록 한다.
|
||||
*/
|
||||
const ROUTE_TREE_COLLAPSED_STORAGE_KEY = 'g7le.routeTree.collapsed';
|
||||
|
||||
/**
|
||||
* localStorage 에서 라우트 트리 접힘 상태를 읽는다. 미설정/접근 불가 시 false(펼침).
|
||||
*
|
||||
* @returns 접힘 여부
|
||||
*/
|
||||
function readPersistedRouteTreeCollapsed(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
try {
|
||||
return window.localStorage?.getItem(ROUTE_TREE_COLLAPSED_STORAGE_KEY) === '1';
|
||||
} catch {
|
||||
// 프라이빗 모드/스토리지 차단 환경 — 기본값(펼침)으로 디그레이드
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 라우트 트리 접힘 상태를 localStorage 에 기록한다. 접근 불가 시 조용히 무시.
|
||||
*
|
||||
* @param collapsed 접힘 여부
|
||||
*/
|
||||
function writePersistedRouteTreeCollapsed(collapsed: boolean): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
window.localStorage?.setItem(ROUTE_TREE_COLLAPSED_STORAGE_KEY, collapsed ? '1' : '0');
|
||||
} catch {
|
||||
// 스토리지 쓰기 실패 — 영속화만 포기(런타임 동작엔 영향 없음)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 타입 정의
|
||||
// ============================================================================
|
||||
|
||||
export type EditMode = 'route' | 'base' | 'modal' | 'extension' | 'iteration_item';
|
||||
|
||||
/**
|
||||
* 프리뷰 디바이스 키.
|
||||
*
|
||||
* 프리셋(`desktop`/`tablet`/`mobile`) + `custom`(사용자 지정 폭) + 레이아웃이 선언한
|
||||
* 동적 breakpoint 키(`portable`, 커스텀 범위 `"600-900"` 등)를 모두 허용한다(
|
||||
* 디바이스 목록 동적 수집). 명명 프리셋은 자동완성·특례(custom 의 previewCustomWidth) 를
|
||||
* 위해 유지하되, 그 외 임의 키를 widen 으로 허용한다(리듀서는 키를 그대로 저장하므로 무영향).
|
||||
* 디바이스별 캔버스 폭은 `resolveDeviceWidth`(deviceList.ts)가 산출한다.
|
||||
*/
|
||||
export type PreviewDevice = 'desktop' | 'tablet' | 'mobile' | 'custom' | (string & {});
|
||||
|
||||
/** 프리뷰 색상 테마 — 캔버스 프레임 `.dark` 래퍼 토글 */
|
||||
export type PreviewColorScheme = 'light' | 'dark';
|
||||
|
||||
export interface RouteTreeNode {
|
||||
/** 라우트 경로 또는 식별자 (모달/base 는 별도) */
|
||||
path: string;
|
||||
/** 레이아웃 이름 */
|
||||
layoutName: string | null;
|
||||
/** 표시 라벨 ($t: 키 또는 평문 — 렌더 시 해석) */
|
||||
label: string;
|
||||
/** 라벨 출처 */
|
||||
labelSource: 'editor_label' | 'title' | 'path';
|
||||
/** 아이콘 (meta.icon) */
|
||||
icon?: string | null;
|
||||
/** 출처 — getRoutesDataWithModules source 메타 */
|
||||
source: { kind: 'template' | 'module' | 'plugin' | 'core'; identifier: string | null };
|
||||
/** 리다이렉트 라우트 여부 */
|
||||
isRedirect?: boolean;
|
||||
/** 숨김 라우트 여부 (meta.hidden) */
|
||||
isHidden?: boolean;
|
||||
/** 노드 종류 — 라우트/모달/base/확장 */
|
||||
kind: 'route' | 'modal' | 'base' | 'extension';
|
||||
/** 모달 노드: 모달 id */
|
||||
modalId?: string;
|
||||
/** 모달 노드: 호스트 레이아웃 이름 */
|
||||
modalHostLayout?: string;
|
||||
/** 확장 노드: 확장 식별자 (PK 문자열) */
|
||||
extensionId?: string;
|
||||
/** 확장 노드: 확장 타입 (확장점/오버레이) — 배지 */
|
||||
extensionType?: 'extension_point' | 'overlay';
|
||||
/** 확장 노드: 우선순위 — 배지 */
|
||||
extensionPriority?: number;
|
||||
/** 확장 노드: 주입 대상 이름 (extension_point 이름 / overlay target_layout) */
|
||||
extensionTargetName?: string;
|
||||
/** 확장/모달/base 노드: 수정됨 배지 표시 여부 */
|
||||
isModified?: boolean;
|
||||
/** 확장/base 노드: 비활성(흐림) 여부 */
|
||||
isInactive?: boolean;
|
||||
/**
|
||||
* 연결 자식(모달/확장) 노드: 이 항목이 속한 호스트 라우트의 path.
|
||||
* 자식 클릭으로 별도 편집 모드(modal/extension) 에 진입하면 selectedRoute 가 가상 path 로
|
||||
* 바뀌어 호스트 라우트 노드 강조가 풀리므로, RouteTreePanel 이 이 값으로 호스트 라우트를
|
||||
* 계속 강조한다.
|
||||
*/
|
||||
connectedHostRoutePath?: string;
|
||||
/** 중첩 자식 */
|
||||
children?: RouteTreeNode[];
|
||||
}
|
||||
|
||||
export interface LayoutEditorState {
|
||||
/** 편집 대상 템플릿 식별자 */
|
||||
templateIdentifier: string;
|
||||
/** 라우트 트리 (구성 후) */
|
||||
routeTree: RouteTreeNode[];
|
||||
/**
|
||||
* 라우트 트리 fetch 실패 정보 — null = 정상.
|
||||
* useEditorRoutes 가 셋팅하고 LayoutEditorChrome 이 AccessErrorPanel 로 분기 렌더.
|
||||
* (Phase 2 후속 — routes 로드 실패도 자산/레이아웃 에러와 같은 풍성 UI 사용)
|
||||
*/
|
||||
routesError: EditorAccessError | null;
|
||||
/** 선택된 라우트 (path + layoutName) */
|
||||
selectedRoute: { path: string; layoutName: string | null } | null;
|
||||
/** 라우트 트리 패널 접힘 상태 */
|
||||
isRouteTreeCollapsed: boolean;
|
||||
/** 현재 편집 모드 */
|
||||
editMode: EditMode;
|
||||
/** 별도 편집 모드 진입 직전 라우트 (종료 시 복귀) */
|
||||
returnRoute: { path: string; layoutName: string | null } | null;
|
||||
/**
|
||||
* 별도 편집 모드 진입 직전 편집 모드 (종료 시 복귀) — 중첩 진입 지원.
|
||||
* 예: 확장 편집 모드 안에서 반복 항목 편집에 진입했다가 종료하면 확장 편집 모드로 복귀.
|
||||
* 진입 시 직전 editMode 를 보관하고, 종료 시 이 값으로 복귀(미보관 시 'route').
|
||||
*/
|
||||
returnEditMode: EditMode | null;
|
||||
/** 콘텐츠 로케일 (Phase 6 에서 사용 — Phase 1 은 초기값만 보유) */
|
||||
locale: string;
|
||||
/** 프리뷰 디바이스 (Phase 2 에서 사용) */
|
||||
previewDevice: PreviewDevice;
|
||||
/** 프리뷰 줌 (Phase 2 에서 사용) */
|
||||
previewZoom: number;
|
||||
/**
|
||||
* custom 디바이스 선택 시 적용할 프레임 폭(px).
|
||||
* previewDevice === 'custom' 일 때만 의미. 320~1920 클램프.
|
||||
*/
|
||||
previewCustomWidth: number;
|
||||
/**
|
||||
* 프리뷰 색상 테마. 캔버스 프레임 `.dark` 래퍼 토글 —
|
||||
* 디바이스 토글과 동격(미리보기 전용). 속성 모달 열 때 색 모드 세부탭 기본값으로 스냅샷.
|
||||
*/
|
||||
previewColorScheme: PreviewColorScheme;
|
||||
/** 이력 가용 플래그 (Phase 3 에서 연결) */
|
||||
history: { canUndo: boolean; canRedo: boolean };
|
||||
/** 글로벌 요소 추가 팔레트 열림 상태 (toolbar "+ 요소 추가" →) */
|
||||
isPaletteOpen: boolean;
|
||||
/**
|
||||
* 현재 편집 대상에 매칭되는 페이지 상태 목록.
|
||||
* LayoutEditorChrome 이 editor-spec.states + 현재 scope 로 도출해 SET_AVAILABLE_STATES
|
||||
* 로 셋팅. 0~1개면 PageStateSwitcher 가 토글을 미표시(디그레이드).
|
||||
*/
|
||||
availableStates: EditorStateItemSpec[];
|
||||
/**
|
||||
* 활성 페이지 상태 id. 기본 상태(default:true/첫 항목)로 진입.
|
||||
* PageStateSwitcher 토글 변경 시 SET_ACTIVE_STATE 로 갱신 → 캔버스 즉시 재시뮬레이션.
|
||||
* availableStates 가 비면 null.
|
||||
*/
|
||||
activeStateId: string | null;
|
||||
/**
|
||||
* 레이아웃 이름 → 현재(최신) 저장 버전 번호.
|
||||
* useEditorRoutes 가 편집기 routes 응답의 `layout_versions` 로 일괄 셋팅하고,
|
||||
* 저장/버전 복원 성공 시 SET_LAYOUT_VERSION 으로 해당 레이아웃만 동기화한다.
|
||||
* 버전 이력이 없는(한 번도 저장 안 된 원본) 레이아웃은 맵에 없음 → 배지 미표시.
|
||||
*/
|
||||
layoutVersions: Record<string, number>;
|
||||
/**
|
||||
* 확장 ID(문자열) → 현재(최신) 저장 버전 번호.
|
||||
* useEditorRoutes 가 layout-extensions 응답의 확장별 `current_version` 으로 일괄 셋팅하고,
|
||||
* 확장 저장/버전 복원 성공 시 SET_EXTENSION_VERSION 으로 해당 확장만 동기화한다.
|
||||
* 버전 이력이 없는(한 번도 저장 안 된 원본) 확장은 맵에 없음 → 배지 미표시.
|
||||
*/
|
||||
extensionVersions: Record<string, number>;
|
||||
}
|
||||
|
||||
export type LayoutEditorAction =
|
||||
| { type: 'SET_ROUTE_TREE'; tree: RouteTreeNode[] }
|
||||
| { type: 'SET_ROUTES_ERROR'; error: EditorAccessError | null }
|
||||
| { type: 'SELECT_ROUTE'; route: { path: string; layoutName: string | null } | null }
|
||||
| { type: 'TOGGLE_ROUTE_TREE' }
|
||||
| { type: 'SET_LOCALE'; locale: string }
|
||||
| { type: 'ENTER_BASE_EDIT'; layoutName: string; returnRoute?: { path: string; layoutName: string | null } | null }
|
||||
| { type: 'EXIT_BASE_EDIT' }
|
||||
| { type: 'ENTER_MODAL_EDIT'; modalId: string; hostLayout: string; returnRoute?: { path: string; layoutName: string | null } | null }
|
||||
| { type: 'EXIT_MODAL_EDIT' }
|
||||
| { type: 'ENTER_EXTENSION_EDIT'; extensionId: string; extensionHost?: string; returnRoute?: { path: string; layoutName: string | null } | null }
|
||||
| { type: 'SET_RETURN_ROUTE'; route: { path: string; layoutName: string | null } }
|
||||
| { type: 'EXIT_EXTENSION_EDIT' }
|
||||
| { type: 'ENTER_ITERATION_ITEM_EDIT'; sourcePath: string; hostLayout?: string; returnRoute?: { path: string; layoutName: string | null } | null }
|
||||
| { type: 'EXIT_ITERATION_ITEM_EDIT' }
|
||||
| { type: 'SET_PREVIEW_DEVICE'; device: PreviewDevice }
|
||||
| { type: 'SET_PREVIEW_ZOOM'; zoom: number }
|
||||
| { type: 'SET_PREVIEW_CUSTOM_WIDTH'; width: number }
|
||||
| { type: 'SET_PREVIEW_COLOR_SCHEME'; scheme: PreviewColorScheme }
|
||||
| { type: 'TOGGLE_PALETTE' }
|
||||
| { type: 'SET_PALETTE_OPEN'; open: boolean }
|
||||
| { type: 'SET_AVAILABLE_STATES'; states: EditorStateItemSpec[]; activeStateId: string | null }
|
||||
| { type: 'SET_ACTIVE_STATE'; activeStateId: string | null }
|
||||
| { type: 'SET_LAYOUT_VERSIONS'; versions: Record<string, number> }
|
||||
| { type: 'SET_LAYOUT_VERSION'; layoutName: string; version: number }
|
||||
| { type: 'SET_EXTENSION_VERSIONS'; versions: Record<string, number> }
|
||||
| { type: 'SET_EXTENSION_VERSION'; extensionId: string; version: number };
|
||||
|
||||
function createInitialState(templateIdentifier: string, locale: string): LayoutEditorState {
|
||||
return {
|
||||
templateIdentifier,
|
||||
routeTree: [],
|
||||
routesError: null,
|
||||
selectedRoute: null,
|
||||
// 접힘 상태는 localStorage 에서 복원
|
||||
isRouteTreeCollapsed: readPersistedRouteTreeCollapsed(),
|
||||
editMode: 'route',
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
locale,
|
||||
previewDevice: 'desktop',
|
||||
previewZoom: 1,
|
||||
previewCustomWidth: 1024,
|
||||
previewColorScheme: 'light',
|
||||
history: { canUndo: false, canRedo: false },
|
||||
isPaletteOpen: false,
|
||||
availableStates: [],
|
||||
activeStateId: null,
|
||||
layoutVersions: {},
|
||||
extensionVersions: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function layoutEditorReducer(state: LayoutEditorState, action: LayoutEditorAction): LayoutEditorState {
|
||||
switch (action.type) {
|
||||
case 'SET_ROUTE_TREE':
|
||||
// 새 트리가 들어오면 이전 에러는 자동 해제 (재시도 성공 케이스).
|
||||
return { ...state, routeTree: action.tree, routesError: null };
|
||||
case 'SET_ROUTES_ERROR':
|
||||
return { ...state, routesError: action.error };
|
||||
case 'SELECT_ROUTE':
|
||||
// 라우트를 선택하면 어떤 별도 편집 모드(modal/extension/base/iteration_item)에 있든
|
||||
// route 모드로 복원한다. 그렇지 않으면 editMode 가 'extension' 등으로
|
||||
// 남아 캔버스가 빈 확장 조각 문서를 계속 공급해 "표시할 컴포넌트가 없습니다" 가 뜬다.
|
||||
// 별도 편집 모드 복귀 상태(returnRoute/returnEditMode)도 함께 초기화한다.
|
||||
return {
|
||||
...state,
|
||||
editMode: 'route',
|
||||
selectedRoute: action.route,
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
};
|
||||
case 'TOGGLE_ROUTE_TREE':
|
||||
return { ...state, isRouteTreeCollapsed: !state.isRouteTreeCollapsed };
|
||||
case 'SET_LOCALE':
|
||||
return { ...state, locale: action.locale };
|
||||
case 'ENTER_BASE_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: 'base',
|
||||
// URL 다이렉트 진입/새로고침 복원은 selectedRoute 가 아직 null 이므로 호출자가 host 로
|
||||
// 부터 도출한 returnRoute 를 명시 전달한다(미전달=클릭 진입 시 selectedRoute 사용).
|
||||
returnRoute: action.returnRoute !== undefined ? action.returnRoute : state.selectedRoute,
|
||||
selectedRoute: { path: `__base__/${action.layoutName}`, layoutName: action.layoutName },
|
||||
};
|
||||
case 'EXIT_BASE_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: 'route',
|
||||
selectedRoute: state.returnRoute,
|
||||
returnRoute: null,
|
||||
};
|
||||
case 'ENTER_MODAL_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: 'modal',
|
||||
// URL 복원 시 호출자가 host 기반 returnRoute 명시 전달(미전달=클릭 진입).
|
||||
returnRoute: action.returnRoute !== undefined ? action.returnRoute : state.selectedRoute,
|
||||
selectedRoute: { path: `__modal__/${action.modalId}`, layoutName: action.hostLayout },
|
||||
};
|
||||
case 'EXIT_MODAL_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: 'route',
|
||||
selectedRoute: state.returnRoute,
|
||||
returnRoute: null,
|
||||
};
|
||||
case 'ENTER_EXTENSION_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: 'extension',
|
||||
// URL 복원 시 호출자가 host 기반 returnRoute 명시 전달(미전달=클릭 진입).
|
||||
returnRoute: action.returnRoute !== undefined ? action.returnRoute : state.selectedRoute,
|
||||
// 호스트가 진입 시점에 확정되면(라우트 하위 진입·overlay) layoutName 에 담아 picker 를
|
||||
// 생략한다. 미확정(출처 그룹 진입·복수 호스트)이면 null → picker.
|
||||
selectedRoute: {
|
||||
path: `__extension__/${action.extensionId}`,
|
||||
layoutName: action.extensionHost ?? null,
|
||||
},
|
||||
};
|
||||
case 'SET_RETURN_ROUTE':
|
||||
// 별도 편집 모드 진입 후 복귀 라우트 후행 합성.
|
||||
// `?edit=__extension__/{id}` 단독 진입은 진입 시점에 호스트가 미확정이라 returnRoute 가
|
||||
// null 로 남는다(종료 시 라우트 선택 화면). 호스트가 picker 선택/단일 호스트 자동 확정된
|
||||
// 시점에 LayoutEditorChrome 이 본 액션으로 복귀 라우트를 보충한다. 클릭 진입 등으로 이미
|
||||
// returnRoute 가 있으면 덮지 않고, route 모드(복귀 상태 무의미)에서는 무시한다.
|
||||
if (state.editMode === 'route' || state.returnRoute !== null) return state;
|
||||
return { ...state, returnRoute: action.route };
|
||||
case 'EXIT_EXTENSION_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: 'route',
|
||||
selectedRoute: state.returnRoute,
|
||||
returnRoute: null,
|
||||
};
|
||||
case 'ENTER_ITERATION_ITEM_EDIT':
|
||||
// 반복 항목 편집 모드 진입 — base/extension 모드와 동형.
|
||||
// 가상 path `__iteration__/{sourcePath}` 에 편집 대상 iteration 원본 노드의
|
||||
// 에디터 path 를 담아, 항목 템플릿 단독 편집 세션이 출처를 식별한다.
|
||||
// 진입 직전 라우트/편집모드를 보존하고 종료 시 복귀한다(확장 편집 모드 안에서
|
||||
// 진입한 경우 종료 시 확장 편집 모드로 복귀 — 중첩 진입 지원).
|
||||
return {
|
||||
...state,
|
||||
editMode: 'iteration_item',
|
||||
// URL 다이렉트 진입 시 selectedRoute 가 null 이라 클릭 진입과 달리 returnRoute 가
|
||||
// 비어 종료 시 "라우트 선택" 화면으로 떨어졌다. 호출자가 host(layoutName)로부터 도출한
|
||||
// returnRoute 를 명시 전달하면 그것을 사용(미전달=클릭 진입 시 selectedRoute 사용).
|
||||
returnRoute: action.returnRoute !== undefined ? action.returnRoute : state.selectedRoute,
|
||||
returnEditMode: state.editMode,
|
||||
selectedRoute: {
|
||||
path: `__iteration__/${action.sourcePath}`,
|
||||
// 호스트 레이아웃명 — 클릭 진입은 현재 selectedRoute.layoutName 을 유지하고, URL 직접
|
||||
// 진입(새로고침/주소창)은 action.hostLayout(`?host=`)으로 복원한다. 둘 다 없으면 null
|
||||
// (그 경우 useLayoutDocument 가 빈 문서 → 진입 불가, URL 에 host 누락 시 방지).
|
||||
layoutName: action.hostLayout ?? state.selectedRoute?.layoutName ?? null,
|
||||
},
|
||||
};
|
||||
case 'EXIT_ITERATION_ITEM_EDIT':
|
||||
return {
|
||||
...state,
|
||||
editMode: state.returnEditMode ?? 'route',
|
||||
selectedRoute: state.returnRoute,
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
};
|
||||
case 'SET_PREVIEW_DEVICE':
|
||||
return { ...state, previewDevice: action.device };
|
||||
case 'SET_PREVIEW_ZOOM':
|
||||
return { ...state, previewZoom: action.zoom };
|
||||
case 'SET_PREVIEW_CUSTOM_WIDTH':
|
||||
return { ...state, previewCustomWidth: action.width };
|
||||
case 'SET_PREVIEW_COLOR_SCHEME':
|
||||
return { ...state, previewColorScheme: action.scheme };
|
||||
case 'TOGGLE_PALETTE':
|
||||
return { ...state, isPaletteOpen: !state.isPaletteOpen };
|
||||
case 'SET_PALETTE_OPEN':
|
||||
return { ...state, isPaletteOpen: action.open };
|
||||
case 'SET_AVAILABLE_STATES':
|
||||
return { ...state, availableStates: action.states, activeStateId: action.activeStateId };
|
||||
case 'SET_ACTIVE_STATE':
|
||||
return { ...state, activeStateId: action.activeStateId };
|
||||
case 'SET_LAYOUT_VERSIONS':
|
||||
// 편집기 routes 응답의 레이아웃별 최신 버전 맵 일괄 셋팅.
|
||||
return { ...state, layoutVersions: action.versions };
|
||||
case 'SET_LAYOUT_VERSION':
|
||||
// 저장/버전 복원 성공 — 해당 레이아웃 버전만 동기화.
|
||||
return {
|
||||
...state,
|
||||
layoutVersions: { ...state.layoutVersions, [action.layoutName]: action.version },
|
||||
};
|
||||
case 'SET_EXTENSION_VERSIONS':
|
||||
// layout-extensions 응답의 확장별 최신 버전 맵 일괄 셋팅.
|
||||
return { ...state, extensionVersions: action.versions };
|
||||
case 'SET_EXTENSION_VERSION':
|
||||
// 확장 저장/버전 복원 성공 — 해당 확장 버전만 동기화.
|
||||
return {
|
||||
...state,
|
||||
extensionVersions: { ...state.extensionVersions, [action.extensionId]: action.version },
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 대상(라우트 path / 편집 모드)이 바뀌면 이전 페이지 상태가 stale 로 남지 않도록
|
||||
* availableStates/activeStateId 를 리셋한다. LayoutEditorChrome 이 새 대상에 매칭되는
|
||||
* states 를 다시 SET_AVAILABLE_STATES 로 셋팅한다(scope 재매칭).
|
||||
*
|
||||
* 본 래퍼가 리셋만 담당하고 셋팅은 Chrome effect 가 담당해, 같은 라우트 안에서의 상태
|
||||
* 토글(SET_ACTIVE_STATE)은 보존하면서 라우트/모드 전환 시에만 초기화된다.
|
||||
*/
|
||||
function reducerWithStateScopeReset(
|
||||
state: LayoutEditorState,
|
||||
action: LayoutEditorAction,
|
||||
): LayoutEditorState {
|
||||
const next = layoutEditorReducer(state, action);
|
||||
if (
|
||||
(next.selectedRoute?.path ?? null) !== (state.selectedRoute?.path ?? null) ||
|
||||
next.editMode !== state.editMode
|
||||
) {
|
||||
const needsStateReset = next.availableStates.length > 0 || next.activeStateId !== null;
|
||||
if (needsStateReset) {
|
||||
return { ...next, availableStates: [], activeStateId: null };
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Context
|
||||
// ============================================================================
|
||||
|
||||
export interface LayoutEditorContextValue {
|
||||
state: LayoutEditorState;
|
||||
dispatch: React.Dispatch<LayoutEditorAction>;
|
||||
}
|
||||
|
||||
const LayoutEditorContext = createContext<LayoutEditorContextValue | null>(null);
|
||||
|
||||
export interface LayoutEditorProviderProps {
|
||||
templateIdentifier: string;
|
||||
initialLocale: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* reducer 호출마다 devtools `editor-state` 카테고리에 스냅샷 적재.
|
||||
* devtools 비활성 환경에서는 no-op 이므로 회귀 위험 없음.
|
||||
*/
|
||||
function reducerWithDevtools(state: LayoutEditorState, action: LayoutEditorAction): LayoutEditorState {
|
||||
const next = reducerWithStateScopeReset(state, action);
|
||||
trackEditorState(next, action.type);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function LayoutEditorProvider({
|
||||
templateIdentifier,
|
||||
initialLocale,
|
||||
children,
|
||||
}: LayoutEditorProviderProps): React.ReactElement {
|
||||
const [state, dispatch] = useReducer(
|
||||
reducerWithDevtools,
|
||||
undefined,
|
||||
() => {
|
||||
const initial = createInitialState(templateIdentifier, initialLocale);
|
||||
trackEditorState(initial, undefined);
|
||||
return initial;
|
||||
}
|
||||
);
|
||||
|
||||
// 접힘 상태가 바뀔 때마다 localStorage 에 영속화.
|
||||
useEffect(() => {
|
||||
writePersistedRouteTreeCollapsed(state.isRouteTreeCollapsed);
|
||||
}, [state.isRouteTreeCollapsed]);
|
||||
|
||||
const value = useMemo(() => ({ state, dispatch }), [state]);
|
||||
|
||||
return React.createElement(LayoutEditorContext.Provider, { value }, children);
|
||||
}
|
||||
|
||||
export function useLayoutEditor(): LayoutEditorContextValue {
|
||||
const ctx = useContext(LayoutEditorContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useLayoutEditor must be used within LayoutEditorProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
/**
|
||||
* EditorModalContext 단위 테스트 — open / close / 스택 / 백드롭 / ESC 분기 검증
|
||||
*
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import {
|
||||
EditorModalProvider,
|
||||
EditorModalRoot,
|
||||
useEditorModal,
|
||||
} from '../EditorModalContext';
|
||||
|
||||
function Host({ children }: { children?: React.ReactNode }): React.ReactElement {
|
||||
return (
|
||||
<EditorModalProvider>
|
||||
{children}
|
||||
<EditorModalRoot />
|
||||
</EditorModalProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function OpenButton({
|
||||
ariaLabel,
|
||||
content,
|
||||
closeOnBackdrop,
|
||||
closeOnEscape,
|
||||
}: {
|
||||
ariaLabel?: string;
|
||||
content: React.ReactNode;
|
||||
closeOnBackdrop?: boolean;
|
||||
closeOnEscape?: boolean;
|
||||
}): React.ReactElement {
|
||||
const modal = useEditorModal();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="trigger"
|
||||
onClick={() =>
|
||||
modal.open({ ariaLabel, content, closeOnBackdrop, closeOnEscape })
|
||||
}
|
||||
>
|
||||
open
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditorModal — 기본 open / close', () => {
|
||||
it('open() 호출 시 모달 본문이 렌더되고 close 시 사라진다', () => {
|
||||
render(
|
||||
<Host>
|
||||
<OpenButton ariaLabel="palette" content={<span data-testid="content">hello</span>} />
|
||||
</Host>
|
||||
);
|
||||
expect(screen.queryByTestId('content')).toBeNull();
|
||||
fireEvent.click(screen.getByTestId('trigger'));
|
||||
expect(screen.getByTestId('content')).toBeTruthy();
|
||||
// 백드롭 클릭으로 닫기 (기본값 true)
|
||||
const backdrop = screen.getByRole('presentation');
|
||||
fireEvent.click(backdrop);
|
||||
expect(screen.queryByTestId('content')).toBeNull();
|
||||
});
|
||||
|
||||
it('closeOnBackdrop=false 면 백드롭 클릭이 무시된다', () => {
|
||||
render(
|
||||
<Host>
|
||||
<OpenButton
|
||||
ariaLabel="palette"
|
||||
content={<span data-testid="content">x</span>}
|
||||
closeOnBackdrop={false}
|
||||
/>
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('trigger'));
|
||||
fireEvent.click(screen.getByRole('presentation'));
|
||||
expect(screen.queryByTestId('content')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('모달 본문 클릭은 닫기를 트리거하지 않는다 (e.target !== e.currentTarget)', () => {
|
||||
render(
|
||||
<Host>
|
||||
<OpenButton ariaLabel="palette" content={<span data-testid="content">x</span>} />
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('trigger'));
|
||||
fireEvent.click(screen.getByTestId('content'));
|
||||
expect(screen.queryByTestId('content')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorModal — ESC 키', () => {
|
||||
it('ESC 누르면 가장 위 모달이 닫힌다', () => {
|
||||
render(
|
||||
<Host>
|
||||
<OpenButton ariaLabel="palette" content={<span data-testid="content">x</span>} />
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('trigger'));
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
});
|
||||
expect(screen.queryByTestId('content')).toBeNull();
|
||||
});
|
||||
|
||||
it('closeOnEscape=false 면 ESC 가 무시된다', () => {
|
||||
render(
|
||||
<Host>
|
||||
<OpenButton
|
||||
ariaLabel="palette"
|
||||
content={<span data-testid="content">x</span>}
|
||||
closeOnEscape={false}
|
||||
/>
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('trigger'));
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
});
|
||||
expect(screen.queryByTestId('content')).toBeTruthy();
|
||||
});
|
||||
|
||||
// closeOnEscape=false 모달(페이지 설정)은 ESC 로 안 닫히되, ESC 이벤트를
|
||||
// 삼키지 않아야 한다(모달 안 플로팅 드롭다운·인라인 입력 모드 등 하위 ESC 핸들러가 동작). 핸들러가
|
||||
// preventDefault/stopPropagation 을 호출하지 않음을 검증(하위 ESC 탈출 유지 회귀 잠금).
|
||||
it('closeOnEscape=false 면 ESC 가 하위로 전파된다(삼키지 않음)', () => {
|
||||
render(
|
||||
<Host>
|
||||
<OpenButton
|
||||
ariaLabel="palette"
|
||||
content={<span data-testid="content">x</span>}
|
||||
closeOnEscape={false}
|
||||
/>
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('trigger'));
|
||||
let defaultPrevented = false;
|
||||
let propagationStopped = false;
|
||||
const ev = new KeyboardEvent('keydown', { key: 'Escape', cancelable: true, bubbles: true });
|
||||
const origStop = ev.stopPropagation.bind(ev);
|
||||
ev.stopPropagation = () => { propagationStopped = true; origStop(); };
|
||||
act(() => {
|
||||
window.dispatchEvent(ev);
|
||||
defaultPrevented = ev.defaultPrevented;
|
||||
});
|
||||
// 모달은 그대로 열려 있고, ESC 는 삼켜지지 않는다.
|
||||
expect(screen.queryByTestId('content')).toBeTruthy();
|
||||
expect(defaultPrevented).toBe(false);
|
||||
expect(propagationStopped).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorModal — 스택 (depth 무제한)', () => {
|
||||
it('두 모달이 동시 표시되며 ESC 는 최상위만 닫는다', () => {
|
||||
function NestedTrigger(): React.ReactElement {
|
||||
const modal = useEditorModal();
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
data-testid="trigger-a"
|
||||
onClick={() =>
|
||||
modal.open({
|
||||
ariaLabel: 'a',
|
||||
content: (
|
||||
<div data-testid="content-a">
|
||||
<button
|
||||
data-testid="trigger-b"
|
||||
onClick={() =>
|
||||
modal.open({
|
||||
ariaLabel: 'b',
|
||||
content: <div data-testid="content-b">b</div>,
|
||||
})
|
||||
}
|
||||
>
|
||||
open b
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
open a
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
render(
|
||||
<Host>
|
||||
<NestedTrigger />
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('trigger-a'));
|
||||
fireEvent.click(screen.getByTestId('trigger-b'));
|
||||
expect(screen.getByTestId('content-a')).toBeTruthy();
|
||||
expect(screen.getByTestId('content-b')).toBeTruthy();
|
||||
|
||||
// ESC → b 만 닫힘
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
});
|
||||
expect(screen.queryByTestId('content-b')).toBeNull();
|
||||
expect(screen.queryByTestId('content-a')).toBeTruthy();
|
||||
|
||||
// 다시 ESC → a 닫힘
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
});
|
||||
expect(screen.queryByTestId('content-a')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorModal — closeAll', () => {
|
||||
it('closeAll 호출 시 스택의 모든 모달이 닫힌다', () => {
|
||||
function Trigger(): React.ReactElement {
|
||||
const modal = useEditorModal();
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
data-testid="open-x"
|
||||
onClick={() => {
|
||||
modal.open({ content: <span data-testid="x1">1</span> });
|
||||
modal.open({ content: <span data-testid="x2">2</span> });
|
||||
}}
|
||||
>
|
||||
open
|
||||
</button>
|
||||
<button data-testid="close-all" onClick={() => modal.closeAll()}>
|
||||
close all
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
render(
|
||||
<Host>
|
||||
<Trigger />
|
||||
</Host>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-x'));
|
||||
expect(screen.getByTestId('x1')).toBeTruthy();
|
||||
expect(screen.getByTestId('x2')).toBeTruthy();
|
||||
fireEvent.click(screen.getByTestId('close-all'));
|
||||
expect(screen.queryByTestId('x1')).toBeNull();
|
||||
expect(screen.queryByTestId('x2')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// draggable 모달 + 선택 요소 자동 회피(avoidRect)
|
||||
// ============================================================================
|
||||
describe('EditorModal — draggable + avoidRect', () => {
|
||||
function DraggableHost({ avoidRect }: { avoidRect?: { left: number; top: number; width: number; height: number } }): React.ReactElement {
|
||||
const modal = useEditorModal();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-draggable"
|
||||
onClick={() =>
|
||||
modal.open({
|
||||
id: 'drag1',
|
||||
draggable: true,
|
||||
avoidRect,
|
||||
width: 420,
|
||||
content: (
|
||||
<div data-modal-drag-handle data-testid="drag-handle" style={{ padding: 8 }}>
|
||||
헤더
|
||||
</div>
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
open
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
it('draggable 모달은 백드롭이 pointerEvents:none (캔버스 결과 보며 이동)', () => {
|
||||
render(
|
||||
<Host>
|
||||
<DraggableHost />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-draggable'));
|
||||
const backdrop = screen.getByTestId('g7le-modal-backdrop-drag1');
|
||||
expect(backdrop.getAttribute('data-draggable')).toBe('true');
|
||||
expect((backdrop as HTMLElement).style.pointerEvents).toBe('none');
|
||||
});
|
||||
|
||||
it('헤더 드래그 핸들 pointerdown→move 로 모달 위치 이동', () => {
|
||||
render(
|
||||
<Host>
|
||||
<DraggableHost />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-draggable'));
|
||||
const handle = screen.getByTestId('drag-handle');
|
||||
const modalEl = screen.getByTestId('g7le-modal-drag1') as HTMLElement;
|
||||
fireEvent.pointerDown(handle, { clientX: 100, clientY: 100 });
|
||||
fireEvent.pointerMove(window, { clientX: 160, clientY: 140 });
|
||||
fireEvent.pointerUp(window, { clientX: 160, clientY: 140 });
|
||||
// 이동 후 left/top 이 px 좌표로 박힌다(중앙 50% 가 아님)
|
||||
expect(modalEl.style.left.endsWith('px')).toBe(true);
|
||||
expect(modalEl.style.position).toBe('absolute');
|
||||
});
|
||||
|
||||
it('avoidRect 미지정 → 중앙 정렬 유지(transform translate)', () => {
|
||||
render(
|
||||
<Host>
|
||||
<DraggableHost />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-draggable'));
|
||||
const modalEl = screen.getByTestId('g7le-modal-drag1') as HTMLElement;
|
||||
// jsdom 은 getBoundingClientRect 가 0 → computeAvoidPosition 이 null(중앙 유지)
|
||||
expect(modalEl.getAttribute('data-positioned')).toBe('false');
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorModal — 최소화 / 복원', () => {
|
||||
function MinimizeHost(): React.ReactElement {
|
||||
const modal = useEditorModal();
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open"
|
||||
onClick={() => modal.open({ id: 'm1', ariaLabel: '페이지 설정', content: <span data-testid="body">본문</span> })}
|
||||
>
|
||||
open
|
||||
</button>
|
||||
<button type="button" data-testid="min" onClick={() => modal.minimize('m1', '영역 선택 중…')}>
|
||||
min
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
it('최소화 시 모달 본문은 언마운트되지 않고 하단 바가 나타난다', () => {
|
||||
render(
|
||||
<Host>
|
||||
<MinimizeHost />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open'));
|
||||
expect(screen.getByTestId('body')).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByTestId('min'));
|
||||
});
|
||||
// 본문은 DOM 에 남는다(상태 보존 — display:none).
|
||||
expect(screen.getByTestId('body')).toBeInTheDocument();
|
||||
const backdrop = screen.getByTestId('g7le-modal-backdrop-m1') as HTMLElement;
|
||||
expect(backdrop.style.display).toBe('none');
|
||||
// 하단 바 + 라벨.
|
||||
expect(screen.getByTestId('g7le-minimized-bar')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-minimized-m1')).toHaveTextContent('영역 선택 중…');
|
||||
});
|
||||
|
||||
it('하단 바 클릭 시 모달이 복원된다', () => {
|
||||
render(
|
||||
<Host>
|
||||
<MinimizeHost />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open'));
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByTestId('min'));
|
||||
});
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByTestId('g7le-minimized-m1'));
|
||||
});
|
||||
const backdrop = screen.getByTestId('g7le-modal-backdrop-m1') as HTMLElement;
|
||||
expect(backdrop.style.display).not.toBe('none');
|
||||
expect(screen.queryByTestId('g7le-minimized-bar')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorModal — maxHeight 뷰포트 추종', () => {
|
||||
function MaxHeightHost({ ratio }: { ratio?: number }): React.ReactElement {
|
||||
const modal = useEditorModal();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-mh"
|
||||
onClick={() =>
|
||||
modal.open({
|
||||
id: 'mh1',
|
||||
ariaLabel: '페이지 설정',
|
||||
maxHeightRatio: ratio,
|
||||
content: <span data-testid="mh-body">본문</span>,
|
||||
})
|
||||
}
|
||||
>
|
||||
open
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// 페이지 설정 모달이 화면 높이를 넘쳐 백드롭이 스크롤되고
|
||||
// 상단 탭/제목이 화면 밖으로 사라졌다. 창을 줄여도 모달이 함께 줄지 않았다.
|
||||
// 근본 원인 — maxHeight 를 모달 마운트 시점의 window.innerHeight 픽셀로 한 번
|
||||
// 계산해 박아 두어, resize 시 재계산되지 않았다(stale 픽셀). vh 문자열로 주면
|
||||
// 브라우저가 리사이즈마다 자동 재계산해 항상 화면에 맞는다.
|
||||
// 비-draggable 모달은 상단 정렬 + 상단 여백(MODAL_TOP_GAP)을 쓰므로 maxHeight 가
|
||||
// calc(100vh - 여백*2) 다(상·하 여백 제외해 제목·탭 포함 화면 안에, 리사이즈 추종).
|
||||
// jsdom 의 cssstyle 은 calc() 는 받지만 min()/clamp() 복합값은 떨군다 → maxHeight 는 calc 단독.
|
||||
it('비-draggable maxHeight 는 calc(100vh - …) 화면맞춤(픽셀 고정 금지 — 리사이즈 추종)', () => {
|
||||
render(
|
||||
<Host>
|
||||
<MaxHeightHost ratio={0.85} />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-mh'));
|
||||
const mh = (screen.getByTestId('g7le-modal-mh1') as HTMLElement).style.maxHeight;
|
||||
expect(mh).toContain('calc(100vh');
|
||||
// 'NNNpx' 같은 픽셀 고정값이면 리사이즈 추종 불가 → 실패.
|
||||
expect(/^\d+px$/.test(mh)).toBe(false);
|
||||
});
|
||||
|
||||
it('maxHeightRatio 기본값에서도 비-draggable 은 calc 화면맞춤', () => {
|
||||
render(
|
||||
<Host>
|
||||
<MaxHeightHost />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-mh'));
|
||||
const mh = (screen.getByTestId('g7le-modal-mh1') as HTMLElement).style.maxHeight;
|
||||
expect(mh).toContain('calc(100vh');
|
||||
});
|
||||
|
||||
it('ratio=0 이어도 비-draggable 은 calc 화면맞춤(픽셀 아님)', () => {
|
||||
render(
|
||||
<Host>
|
||||
<MaxHeightHost ratio={0} />
|
||||
</Host>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('open-mh'));
|
||||
const mh = (screen.getByTestId('g7le-modal-mh1') as HTMLElement).style.maxHeight;
|
||||
expect(mh).toContain('calc(100vh');
|
||||
expect(/^\d+px$/.test(mh)).toBe(false);
|
||||
});
|
||||
});
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
// e2e:allow 순수 reducer 단위 테스트 — DOM/네트워크 영향 없음.
|
||||
/**
|
||||
* layoutEditorReducer — 반복 항목 편집 모드(iteration_item) 진입/종료
|
||||
*
|
||||
* base/extension 모드와 동형으로 ENTER 시 가상 path `__iteration__/{sourcePath}` 로
|
||||
* 전환하고 returnRoute 를 보존, EXIT 시 route 모드로 복귀하는지 검증한다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { layoutEditorReducer, type LayoutEditorState } from '../LayoutEditorContext';
|
||||
|
||||
function baseState(overrides: Partial<LayoutEditorState> = {}): LayoutEditorState {
|
||||
return {
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
routeTree: [],
|
||||
routesError: null,
|
||||
selectedRoute: { path: '/', layoutName: 'home' },
|
||||
isRouteTreeCollapsed: false,
|
||||
editMode: 'route',
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
locale: 'ko',
|
||||
previewDevice: 'desktop',
|
||||
previewZoom: 1,
|
||||
previewCustomWidth: 1024,
|
||||
history: { canUndo: false, canRedo: false },
|
||||
isPaletteOpen: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('layoutEditorReducer — iteration_item 모드', () => {
|
||||
it('ENTER_ITERATION_ITEM_EDIT → editMode=iteration_item + 가상 path + returnRoute 보존', () => {
|
||||
const start = baseState();
|
||||
const next = layoutEditorReducer(start, {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '2.children.5.children.0',
|
||||
});
|
||||
expect(next.editMode).toBe('iteration_item');
|
||||
expect(next.selectedRoute?.path).toBe('__iteration__/2.children.5.children.0');
|
||||
// layoutName 은 진입 직전 라우트의 것을 유지 (단독 렌더 세션이 사용)
|
||||
expect(next.selectedRoute?.layoutName).toBe('home');
|
||||
// 종료 시 복귀할 라우트 보존
|
||||
expect(next.returnRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
});
|
||||
|
||||
it('EXIT_ITERATION_ITEM_EDIT → route 모드 복귀 + returnRoute 초기화', () => {
|
||||
const entered = layoutEditorReducer(baseState(), {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '2.children.5.children.0',
|
||||
});
|
||||
const exited = layoutEditorReducer(entered, { type: 'EXIT_ITERATION_ITEM_EDIT' });
|
||||
expect(exited.editMode).toBe('route');
|
||||
expect(exited.selectedRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
expect(exited.returnRoute).toBeNull();
|
||||
});
|
||||
|
||||
it('selectedRoute 가 null 이어도 진입 안전 (layoutName null 폴백)', () => {
|
||||
const next = layoutEditorReducer(baseState({ selectedRoute: null }), {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '0',
|
||||
});
|
||||
expect(next.editMode).toBe('iteration_item');
|
||||
expect(next.selectedRoute?.path).toBe('__iteration__/0');
|
||||
expect(next.selectedRoute?.layoutName).toBeNull();
|
||||
});
|
||||
|
||||
// 회귀: 확장 편집 모드 안에서 반복 항목 편집에 진입했다가 종료하면
|
||||
// route 가 아니라 확장 편집 모드로 복귀해야 한다(중첩 진입). 종전엔 EXIT 가 editMode='route'
|
||||
// 를 강제해 확장 컨텍스트를 잃고 "라우트 선택" 화면으로 떨어졌다.
|
||||
it('확장 편집 모드 안에서 진입 → 종료 시 확장 편집 모드로 복귀 (중첩, returnEditMode)', () => {
|
||||
const inExtension = baseState({
|
||||
editMode: 'extension',
|
||||
selectedRoute: { path: '__extension__/9', layoutName: null },
|
||||
});
|
||||
const entered = layoutEditorReducer(inExtension, {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '0.children.2',
|
||||
});
|
||||
expect(entered.editMode).toBe('iteration_item');
|
||||
expect(entered.returnEditMode).toBe('extension');
|
||||
expect(entered.returnRoute).toEqual({ path: '__extension__/9', layoutName: null });
|
||||
|
||||
const exited = layoutEditorReducer(entered, { type: 'EXIT_ITERATION_ITEM_EDIT' });
|
||||
// route 가 아니라 진입 직전 모드(extension)로 복귀.
|
||||
expect(exited.editMode).toBe('extension');
|
||||
expect(exited.selectedRoute).toEqual({ path: '__extension__/9', layoutName: null });
|
||||
expect(exited.returnEditMode).toBeNull();
|
||||
expect(exited.returnRoute).toBeNull();
|
||||
});
|
||||
|
||||
it('route 모드에서 진입 시 returnEditMode=route → 종료 시 route 복귀(기존 동작 유지)', () => {
|
||||
const entered = layoutEditorReducer(baseState(), {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '1',
|
||||
});
|
||||
expect(entered.returnEditMode).toBe('route');
|
||||
const exited = layoutEditorReducer(entered, { type: 'EXIT_ITERATION_ITEM_EDIT' });
|
||||
expect(exited.editMode).toBe('route');
|
||||
});
|
||||
|
||||
// URL 다이렉트 진입: selectedRoute 가 null 이어도 호출자가 host 로부터 도출한
|
||||
// returnRoute 를 명시 전달하면 종료 시 그 호스트 라우트로 복귀한다("라우트 선택" 화면 회귀 방지).
|
||||
it('selectedRoute=null 이라도 returnRoute 명시 전달 시 종료 후 그 라우트로 복귀', () => {
|
||||
const entered = layoutEditorReducer(baseState({ selectedRoute: null }), {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '2.children.5.children.0',
|
||||
returnRoute: { path: '/boards/popular', layoutName: 'board/popular' },
|
||||
});
|
||||
expect(entered.editMode).toBe('iteration_item');
|
||||
expect(entered.returnRoute).toEqual({ path: '/boards/popular', layoutName: 'board/popular' });
|
||||
// 진입 시 layoutName 은 hostLayout 미전달이라 selectedRoute(null) 폴백이지만, returnRoute 는 합성됨.
|
||||
const exited = layoutEditorReducer(entered, { type: 'EXIT_ITERATION_ITEM_EDIT' });
|
||||
expect(exited.editMode).toBe('route');
|
||||
expect(exited.selectedRoute).toEqual({ path: '/boards/popular', layoutName: 'board/popular' });
|
||||
});
|
||||
|
||||
// returnRoute 를 명시 전달하지 않으면(클릭 진입) 종전대로 selectedRoute 를 보존한다(회귀 없음).
|
||||
it('returnRoute 미전달(클릭 진입) 시 selectedRoute 보존', () => {
|
||||
const entered = layoutEditorReducer(baseState(), {
|
||||
type: 'ENTER_ITERATION_ITEM_EDIT',
|
||||
sourcePath: '1',
|
||||
});
|
||||
expect(entered.returnRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
});
|
||||
});
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* layoutEditorReducer — 레이아웃 버전 맵 액션 테스트
|
||||
*
|
||||
* SET_LAYOUT_VERSIONS(routes 응답 일괄)와 SET_LAYOUT_VERSION(저장/복원 단건 동기화)이
|
||||
* layoutVersions 맵을 정확히 갱신하고 다른 상태를 건드리지 않음을 가드한다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { layoutEditorReducer, type LayoutEditorState } from '../LayoutEditorContext';
|
||||
|
||||
function makeState(overrides: Partial<LayoutEditorState> = {}): LayoutEditorState {
|
||||
return {
|
||||
templateIdentifier: 'test-tpl',
|
||||
routeTree: [],
|
||||
routesError: null,
|
||||
selectedRoute: null,
|
||||
isRouteTreeCollapsed: false,
|
||||
editMode: 'route',
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
locale: 'ko',
|
||||
previewDevice: 'desktop',
|
||||
previewZoom: 1,
|
||||
previewCustomWidth: 1024,
|
||||
previewColorScheme: 'light',
|
||||
history: { canUndo: false, canRedo: false },
|
||||
isPaletteOpen: false,
|
||||
availableStates: [],
|
||||
activeStateId: null,
|
||||
layoutVersions: {},
|
||||
extensionVersions: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('layoutEditorReducer — layoutVersions', () => {
|
||||
it('SET_LAYOUT_VERSIONS — routes 응답 맵으로 일괄 교체', () => {
|
||||
const state = makeState({ layoutVersions: { stale: 1 } });
|
||||
const next = layoutEditorReducer(state, {
|
||||
type: 'SET_LAYOUT_VERSIONS',
|
||||
versions: { home: 3, 'auth/login': 7 },
|
||||
});
|
||||
expect(next.layoutVersions).toEqual({ home: 3, 'auth/login': 7 });
|
||||
});
|
||||
|
||||
it('SET_LAYOUT_VERSION — 해당 레이아웃만 갱신하고 나머지 항목 보존 (저장/복원 동기화)', () => {
|
||||
const state = makeState({ layoutVersions: { home: 3, 'auth/login': 7 } });
|
||||
const next = layoutEditorReducer(state, {
|
||||
type: 'SET_LAYOUT_VERSION',
|
||||
layoutName: 'home',
|
||||
version: 4,
|
||||
});
|
||||
expect(next.layoutVersions).toEqual({ home: 4, 'auth/login': 7 });
|
||||
});
|
||||
|
||||
it('SET_LAYOUT_VERSION — 맵에 없던 레이아웃(첫 저장)도 추가된다', () => {
|
||||
const state = makeState();
|
||||
const next = layoutEditorReducer(state, {
|
||||
type: 'SET_LAYOUT_VERSION',
|
||||
layoutName: 'board/index',
|
||||
version: 2,
|
||||
});
|
||||
expect(next.layoutVersions).toEqual({ 'board/index': 2 });
|
||||
});
|
||||
|
||||
it('버전 액션은 selectedRoute/editMode 등 다른 상태를 변경하지 않는다', () => {
|
||||
const state = makeState({
|
||||
selectedRoute: { path: '/', layoutName: 'home' },
|
||||
editMode: 'modal',
|
||||
});
|
||||
const next = layoutEditorReducer(state, {
|
||||
type: 'SET_LAYOUT_VERSION',
|
||||
layoutName: 'home',
|
||||
version: 5,
|
||||
});
|
||||
expect(next.selectedRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
expect(next.editMode).toBe('modal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('layoutEditorReducer — extensionVersions', () => {
|
||||
it('SET_EXTENSION_VERSIONS — layout-extensions 응답 맵으로 일괄 교체', () => {
|
||||
const state = makeState({ extensionVersions: { '99': 1 } });
|
||||
const next = layoutEditorReducer(state, {
|
||||
type: 'SET_EXTENSION_VERSIONS',
|
||||
versions: { '7': 3, '12': 5 },
|
||||
});
|
||||
expect(next.extensionVersions).toEqual({ '7': 3, '12': 5 });
|
||||
});
|
||||
|
||||
it('SET_EXTENSION_VERSION — 해당 확장만 갱신 + 레이아웃 맵은 불변 (저장/복원 동기화)', () => {
|
||||
const state = makeState({
|
||||
layoutVersions: { home: 3 },
|
||||
extensionVersions: { '7': 3, '12': 5 },
|
||||
});
|
||||
const next = layoutEditorReducer(state, {
|
||||
type: 'SET_EXTENSION_VERSION',
|
||||
extensionId: '7',
|
||||
version: 4,
|
||||
});
|
||||
expect(next.extensionVersions).toEqual({ '7': 4, '12': 5 });
|
||||
expect(next.layoutVersions).toEqual({ home: 3 });
|
||||
});
|
||||
|
||||
it('SET_EXTENSION_VERSION — 맵에 없던 확장(첫 저장)도 추가된다', () => {
|
||||
const next = layoutEditorReducer(makeState(), {
|
||||
type: 'SET_EXTENSION_VERSION',
|
||||
extensionId: '21',
|
||||
version: 2,
|
||||
});
|
||||
expect(next.extensionVersions).toEqual({ '21': 2 });
|
||||
});
|
||||
});
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
// e2e:allow 순수 reducer 단위 테스트 — DOM/네트워크 영향 없음.
|
||||
/**
|
||||
* layoutEditorReducer — SELECT_ROUTE 가 별도 편집 모드(modal/extension/base/iteration_item)를
|
||||
* route 모드로 복원하는지 검증.
|
||||
*
|
||||
* 회귀 배경: 확장/모달 편집 모드에서 트리의 일반 라우트를 클릭하면 SELECT_ROUTE 만 dispatch
|
||||
* 되어 selectedRoute 는 라우트로 바뀌지만 editMode 가 'extension'/'modal' 인 채 남았다. 그러면
|
||||
* LayoutEditorChrome 의 documentProviderValue 가 여전히 extensionDocument(빈 조각)를 공급해
|
||||
* 캔버스에 "이 레이아웃에는 표시할 컴포넌트가 없습니다" 가 떴다(라우트 화면 편집 불가).
|
||||
* 라우트를 선택하면 어떤 편집 모드에 있든 route 모드로 복원되어야 한다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { layoutEditorReducer, type LayoutEditorState } from '../LayoutEditorContext';
|
||||
|
||||
function baseState(overrides: Partial<LayoutEditorState> = {}): LayoutEditorState {
|
||||
return {
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
routeTree: [],
|
||||
routesError: null,
|
||||
selectedRoute: { path: '/', layoutName: 'home' },
|
||||
isRouteTreeCollapsed: false,
|
||||
editMode: 'route',
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
locale: 'ko',
|
||||
previewDevice: 'desktop',
|
||||
previewZoom: 1,
|
||||
previewCustomWidth: 1024,
|
||||
previewColorScheme: 'light',
|
||||
history: { canUndo: false, canRedo: false },
|
||||
isPaletteOpen: false,
|
||||
availableStates: [],
|
||||
activeStateId: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('layoutEditorReducer — SELECT_ROUTE 가 별도 편집 모드를 종료', () => {
|
||||
it('extension 편집 모드 → SELECT_ROUTE → editMode=route 복원 + 라우트 선택', () => {
|
||||
const start = baseState({
|
||||
editMode: 'extension',
|
||||
selectedRoute: { path: '__extension__/6', layoutName: null },
|
||||
returnRoute: { path: '/shop/cart', layoutName: 'shop/cart' },
|
||||
});
|
||||
const next = layoutEditorReducer(start, {
|
||||
type: 'SELECT_ROUTE',
|
||||
route: { path: '/shop/checkout', layoutName: 'shop/checkout' },
|
||||
});
|
||||
expect(next.editMode).toBe('route');
|
||||
expect(next.selectedRoute).toEqual({ path: '/shop/checkout', layoutName: 'shop/checkout' });
|
||||
// 별도 편집 모드 복귀 상태는 깨끗이 초기화(다음 진입에 stale 잔존 방지)
|
||||
expect(next.returnRoute).toBeNull();
|
||||
expect(next.returnEditMode).toBeNull();
|
||||
});
|
||||
|
||||
it('modal 편집 모드 → SELECT_ROUTE → editMode=route 복원', () => {
|
||||
const start = baseState({
|
||||
editMode: 'modal',
|
||||
selectedRoute: { path: '__modal__/delete_confirm', layoutName: 'admin_user_list' },
|
||||
});
|
||||
const next = layoutEditorReducer(start, {
|
||||
type: 'SELECT_ROUTE',
|
||||
route: { path: '/admin/orders', layoutName: 'admin_order_list' },
|
||||
});
|
||||
expect(next.editMode).toBe('route');
|
||||
expect(next.selectedRoute?.path).toBe('/admin/orders');
|
||||
});
|
||||
|
||||
it('base 편집 모드 → SELECT_ROUTE → editMode=route 복원', () => {
|
||||
const start = baseState({
|
||||
editMode: 'base',
|
||||
selectedRoute: { path: '__base__/_user_base', layoutName: '_user_base' },
|
||||
});
|
||||
const next = layoutEditorReducer(start, {
|
||||
type: 'SELECT_ROUTE',
|
||||
route: { path: '/', layoutName: 'home' },
|
||||
});
|
||||
expect(next.editMode).toBe('route');
|
||||
});
|
||||
|
||||
it('이미 route 모드면 동작 변화 없음 (라우트만 교체)', () => {
|
||||
const start = baseState({ editMode: 'route' });
|
||||
const next = layoutEditorReducer(start, {
|
||||
type: 'SELECT_ROUTE',
|
||||
route: { path: '/about', layoutName: 'about' },
|
||||
});
|
||||
expect(next.editMode).toBe('route');
|
||||
expect(next.selectedRoute?.path).toBe('/about');
|
||||
});
|
||||
|
||||
it('SELECT_ROUTE route=null (선택 해제) 도 route 모드로 복원', () => {
|
||||
const start = baseState({
|
||||
editMode: 'extension',
|
||||
selectedRoute: { path: '__extension__/6', layoutName: null },
|
||||
});
|
||||
const next = layoutEditorReducer(start, { type: 'SELECT_ROUTE', route: null });
|
||||
expect(next.editMode).toBe('route');
|
||||
expect(next.selectedRoute).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
// e2e:allow 순수 reducer 단위 테스트 — DOM/네트워크 영향 없음.
|
||||
/**
|
||||
* layoutEditorReducer — SET_RETURN_ROUTE (host 미지정 확장 URL 직접 진입 종료 복귀 보강)
|
||||
*
|
||||
* `?edit=__extension__/{id}` 단독(host 미지정) 진입은 진입 시점에 호스트가 미확정이라
|
||||
* returnRoute 가 null 로 남아 종료 시 "라우트 선택" 화면으로 떨어졌다.
|
||||
* 호스트 확정 시점(picker 선택/단일 호스트 자동 확정)에 LayoutEditorChrome 이
|
||||
* SET_RETURN_ROUTE 로 복귀 라우트를 후행 합성한다. 본 테스트는 reducer 의
|
||||
* 합성/보존/무시 분기를 잠근다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { layoutEditorReducer, type LayoutEditorState } from '../LayoutEditorContext';
|
||||
|
||||
function baseState(overrides: Partial<LayoutEditorState> = {}): LayoutEditorState {
|
||||
return {
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
routeTree: [],
|
||||
routesError: null,
|
||||
selectedRoute: { path: '/', layoutName: 'home' },
|
||||
isRouteTreeCollapsed: false,
|
||||
editMode: 'route',
|
||||
returnRoute: null,
|
||||
returnEditMode: null,
|
||||
locale: 'ko',
|
||||
previewDevice: 'desktop',
|
||||
previewZoom: 1,
|
||||
previewCustomWidth: 1024,
|
||||
previewColorScheme: 'light',
|
||||
history: { canUndo: false, canRedo: false },
|
||||
isPaletteOpen: false,
|
||||
availableStates: [],
|
||||
activeStateId: null,
|
||||
layoutVersions: {},
|
||||
extensionVersions: {},
|
||||
...overrides,
|
||||
} as LayoutEditorState;
|
||||
}
|
||||
|
||||
describe('layoutEditorReducer — SET_RETURN_ROUTE (호스트 확정 후 복귀 라우트 합성)', () => {
|
||||
it('확장 편집 모드 + returnRoute null → 합성 적용', () => {
|
||||
// host 미지정 URL 직접 진입: ENTER_EXTENSION_EDIT 가 returnRoute null 로 진입한 상태.
|
||||
const entered = layoutEditorReducer(baseState({ selectedRoute: null }), {
|
||||
type: 'ENTER_EXTENSION_EDIT',
|
||||
extensionId: '38',
|
||||
returnRoute: null,
|
||||
});
|
||||
expect(entered.returnRoute).toBeNull();
|
||||
|
||||
const synthesized = layoutEditorReducer(entered, {
|
||||
type: 'SET_RETURN_ROUTE',
|
||||
route: { path: 'auth/register', layoutName: 'auth/register' },
|
||||
});
|
||||
expect(synthesized.returnRoute).toEqual({ path: 'auth/register', layoutName: 'auth/register' });
|
||||
|
||||
// 종료 시 합성된 라우트로 복귀 (종전: null → 라우트 선택 화면).
|
||||
const exited = layoutEditorReducer(synthesized, { type: 'EXIT_EXTENSION_EDIT' });
|
||||
expect(exited.editMode).toBe('route');
|
||||
expect(exited.selectedRoute).toEqual({ path: 'auth/register', layoutName: 'auth/register' });
|
||||
});
|
||||
|
||||
it('기존 returnRoute(클릭 진입) 가 있으면 덮지 않음', () => {
|
||||
const entered = layoutEditorReducer(baseState(), {
|
||||
type: 'ENTER_EXTENSION_EDIT',
|
||||
extensionId: '38',
|
||||
});
|
||||
// 클릭 진입 — 진입 직전 selectedRoute 가 returnRoute 로 보존됨.
|
||||
expect(entered.returnRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
|
||||
const next = layoutEditorReducer(entered, {
|
||||
type: 'SET_RETURN_ROUTE',
|
||||
route: { path: 'other/path', layoutName: 'other' },
|
||||
});
|
||||
expect(next.returnRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
expect(next).toBe(entered); // 상태 객체 불변(no-op)
|
||||
});
|
||||
|
||||
it('route 모드(복귀 상태 무의미)에서는 무시', () => {
|
||||
const start = baseState();
|
||||
const next = layoutEditorReducer(start, {
|
||||
type: 'SET_RETURN_ROUTE',
|
||||
route: { path: 'auth/register', layoutName: 'auth/register' },
|
||||
});
|
||||
expect(next).toBe(start);
|
||||
expect(next.returnRoute).toBeNull();
|
||||
});
|
||||
|
||||
it('모달/반복 항목 등 다른 별도 편집 모드에서도 returnRoute null 이면 합성 허용', () => {
|
||||
const inIteration = baseState({
|
||||
editMode: 'iteration_item',
|
||||
selectedRoute: { path: '__iteration__/0', layoutName: 'home' },
|
||||
returnRoute: null,
|
||||
});
|
||||
const next = layoutEditorReducer(inIteration, {
|
||||
type: 'SET_RETURN_ROUTE',
|
||||
route: { path: '/', layoutName: 'home' },
|
||||
});
|
||||
expect(next.returnRoute).toEqual({ path: '/', layoutName: 'home' });
|
||||
});
|
||||
});
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* AccessErrorPanel 테스트
|
||||
*
|
||||
* 다음 시나리오를 검증:
|
||||
* - kind 별 제목/아이콘/액션 버튼 분기 (401/403/404/5xx/network/unknown)
|
||||
* - 401 감지 시 AuthManager.getLoginRedirectUrl 호출 + setTimeout 후 location.href 변경
|
||||
* - 403 일 때 requiredPermissions 칩 노출
|
||||
* - 에러 메시지 details 영역에 원본 메시지 노출 (디버깅)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { render, screen, cleanup } from '@testing-library/react';
|
||||
import type { EditorAccessError } from '../../types/editorErrors';
|
||||
import { AuthManager } from '../../../../auth/AuthManager';
|
||||
|
||||
// useTranslation 을 vi.mock — TranslationProvider 없이도 키 자체를 텍스트로 반환.
|
||||
vi.mock('../../../TranslationContext', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => key,
|
||||
translationEngine: null,
|
||||
translationContext: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
// 위 mock 보다 import 가 먼저 되도록 lazy import.
|
||||
async function importPanel() {
|
||||
const mod = await import('../../components/AccessErrorPanel');
|
||||
return mod.AccessErrorPanel;
|
||||
}
|
||||
|
||||
async function renderPanel(error: EditorAccessError) {
|
||||
const AccessErrorPanel = await importPanel();
|
||||
return render(<AccessErrorPanel error={error} />);
|
||||
}
|
||||
|
||||
describe('AccessErrorPanel — kind 별 분기 렌더', () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('401 unauthorized — 제목 + 로그인 버튼', async () => {
|
||||
await renderPanel({
|
||||
kind: 'unauthorized',
|
||||
status: 401,
|
||||
message: '로그인이 필요한 레이아웃입니다.',
|
||||
requiredPermissions: 'core.templates.layouts.edit',
|
||||
});
|
||||
expect(screen.getByTestId('g7le-access-error')).toHaveAttribute('data-error-kind', 'unauthorized');
|
||||
expect(screen.getByTestId('g7le-access-error-title')).toHaveTextContent(
|
||||
'layout_editor.access_error.unauthorized.title',
|
||||
);
|
||||
expect(screen.getByTestId('g7le-access-error-action-signin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('403 forbidden — 권한 칩 + 홈으로 버튼', async () => {
|
||||
await renderPanel({
|
||||
kind: 'forbidden',
|
||||
status: 403,
|
||||
message: '권한이 없습니다',
|
||||
requiredPermissions: 'core.templates.layouts.edit',
|
||||
});
|
||||
expect(screen.getByTestId('g7le-access-error')).toHaveAttribute('data-error-kind', 'forbidden');
|
||||
expect(screen.getByTestId('g7le-access-error-permissions')).toHaveTextContent(
|
||||
'core.templates.layouts.edit',
|
||||
);
|
||||
expect(screen.getByTestId('g7le-access-error-action-home')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('404 not_found — 권한 칩 없음, 다시 시도 + 홈 버튼', async () => {
|
||||
await renderPanel({
|
||||
kind: 'not_found',
|
||||
status: 404,
|
||||
message: '레이아웃 없음',
|
||||
});
|
||||
expect(screen.getByTestId('g7le-access-error')).toHaveAttribute('data-error-kind', 'not_found');
|
||||
expect(screen.queryByTestId('g7le-access-error-permissions')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-access-error-action-retry')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-access-error-action-home-secondary')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('5xx server_error — 다시 시도 가능', async () => {
|
||||
await renderPanel({ kind: 'server_error', status: 500, message: 'Internal Server Error' });
|
||||
expect(screen.getByTestId('g7le-access-error-action-retry')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('network — 다시 시도 가능 + 디버그 메시지 노출', async () => {
|
||||
await renderPanel({ kind: 'network', status: 0, message: 'fetch failed' });
|
||||
expect(screen.getByTestId('g7le-access-error-action-retry')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-access-error-detail')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('unknown — fallback 분기', async () => {
|
||||
await renderPanel({ kind: 'unknown', status: 418, message: "I'm a teapot" });
|
||||
expect(screen.getByTestId('g7le-access-error')).toHaveAttribute('data-error-kind', 'unknown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AccessErrorPanel — 401 자동 redirect (AccessRedirectGate)', () => {
|
||||
let originalHref: string;
|
||||
let hrefSetter: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
originalHref = window.location.href;
|
||||
hrefSetter = vi.fn();
|
||||
// window.location.href setter 가로채기 — jsdom 은 기본적으로 navigation 미지원이라
|
||||
// defineProperty 로 setter 만 spy 한다.
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: new Proxy(window.location, {
|
||||
set(_target, prop, value) {
|
||||
if (prop === 'href') {
|
||||
hrefSetter(value);
|
||||
return true;
|
||||
}
|
||||
(_target as any)[prop] = value;
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
// location 복원은 jsdom 환경 한정이라 무시 — 다음 테스트는 새로 defineProperty.
|
||||
});
|
||||
|
||||
it('401 마운트 → setTimeout 후 AuthManager.getLoginRedirectUrl 결과로 location 이동', async () => {
|
||||
const getLoginRedirectUrlSpy = vi
|
||||
.spyOn(AuthManager.getInstance(), 'getLoginRedirectUrl')
|
||||
.mockReturnValue('/admin/login?redirect=%2Fadmin%2Flayout-editor%2Fx&reason=session_expired');
|
||||
|
||||
await renderPanel({ kind: 'unauthorized', status: 401, message: 'session expired' });
|
||||
|
||||
// 마운트 직후에는 아직 redirect 발화 안 됨
|
||||
expect(hrefSetter).not.toHaveBeenCalled();
|
||||
|
||||
// 600ms 후 redirect
|
||||
vi.advanceTimersByTime(700);
|
||||
|
||||
expect(getLoginRedirectUrlSpy).toHaveBeenCalledWith(
|
||||
'admin',
|
||||
expect.any(String),
|
||||
'session_expired',
|
||||
);
|
||||
expect(hrefSetter).toHaveBeenCalledWith(
|
||||
'/admin/login?redirect=%2Fadmin%2Flayout-editor%2Fx&reason=session_expired',
|
||||
);
|
||||
});
|
||||
|
||||
it('401 가 아닌 경우 redirect 발화하지 않음', async () => {
|
||||
await renderPanel({ kind: 'forbidden', status: 403, message: '권한 없음' });
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(hrefSetter).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* ArrayGroupAndCellTreeEditor.test.tsx — `array-group` / `array-cell-tree` 노드 에디터 RTL
|
||||
*
|
||||
* 검증:
|
||||
* - ArrayGroupEditor: 여러 배열 prop(BarChart labels+datasets)을 그룹마다 ArrayItemsEditor
|
||||
* 로 렌더, 한 그룹 패치가 다른 그룹 값 보존, groups 미선언 misconfigured.
|
||||
* - ArrayCellTreeEditor: cardColumns 컬럼 추가/삭제/정렬 + id 편집, 컬럼 펼침 시
|
||||
* cellChildren 트리를 ChildrenListControl 로 편집(자식 추가가 컬럼 cellChildren 패치로
|
||||
* 되돌아감), 정적-바인딩 가드, arrayProp 미선언 misconfigured.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
// 시나리오 매니페스트(tests/scenarios/layout-editor-data-builtins.yaml) cross product 15 케이스
|
||||
// (data_surface × aspect) 전수 마킹(test-scenario-coverage 룰). single_object_array(DonutChart)/
|
||||
// flat_typed_array(DynamicFieldList)/primitive_enum_array(SocialLoginButtons)의 capability_attach·
|
||||
// field_widget·structure_op 회귀는 ArrayItemsEditor.test.tsx + dataBuiltinCapabilityShape.test.ts
|
||||
// 가, multi_array(BarChart array-group)/cell_tree(CardGrid array-cell-tree)는 본 파일이 잠근다.
|
||||
// @scenario aspect=capability_attach, data_surface=single_object_array
|
||||
// @scenario aspect=field_widget, data_surface=single_object_array
|
||||
// @scenario aspect=structure_op, data_surface=single_object_array
|
||||
// @scenario aspect=binding_guard, data_surface=single_object_array
|
||||
// @scenario aspect=capability_attach, data_surface=multi_array
|
||||
// @scenario aspect=field_widget, data_surface=multi_array
|
||||
// @scenario aspect=structure_op, data_surface=multi_array
|
||||
// @scenario aspect=capability_attach, data_surface=cell_tree
|
||||
// @scenario aspect=structure_op, data_surface=cell_tree
|
||||
// @scenario aspect=binding_guard, data_surface=cell_tree
|
||||
// @scenario aspect=capability_attach, data_surface=primitive_enum_array
|
||||
// @scenario aspect=structure_op, data_surface=primitive_enum_array
|
||||
// @scenario aspect=capability_attach, data_surface=flat_typed_array
|
||||
// @scenario aspect=field_widget, data_surface=flat_typed_array
|
||||
// @scenario aspect=structure_op, data_surface=flat_typed_array
|
||||
/**
|
||||
* @effects data_builtin_capability_attached_to_8a_targets_both_templates,
|
||||
* array_group_editor_registered_via_registercoreeditors_kind_agnostic,
|
||||
* array_cell_tree_editor_registered_via_registercoreeditors_kind_agnostic,
|
||||
* property_modal_dispatches_data_builtin_node_editor_in_props_tab_by_kind,
|
||||
* array_editor_number_widget_writes_numeric_value,
|
||||
* array_editor_color_widget_writes_hex_string,
|
||||
* array_editor_number_list_widget_parses_comma_separated_into_number_array,
|
||||
* array_editor_newitem_shape_matches_component_read_shape,
|
||||
* array_group_renders_multiple_array_editors_per_group,
|
||||
* array_group_patch_one_group_preserves_other_group_value,
|
||||
* array_group_misconfigured_when_no_groups,
|
||||
* cell_tree_column_add_remove_move_with_id_edit,
|
||||
* cell_tree_expand_edits_cellchildren_via_children_control,
|
||||
* cell_tree_binding_expression_degrades_to_bound_notice,
|
||||
* cell_tree_missing_array_prop_shows_misconfigured_notice,
|
||||
* review_group_chipcheckbox_value_covered_by_propcontrol_not_dataprop,
|
||||
* data_prop_static_nodeeditor_coexists_with_binding_dataprops,
|
||||
* live_donut_data_item_edit_save_persists_to_user_page,
|
||||
* live_barchart_dataset_edit_save_persists_to_user_page
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
|
||||
vi.mock('../../LayoutEditorContext', () => ({
|
||||
useLayoutEditor: () => ({
|
||||
state: {
|
||||
templateIdentifier: 'sirsoft-admin_basic',
|
||||
locale: 'ko',
|
||||
selectedRoute: { path: '/admin', layoutName: 'admin' },
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
const createCustomKey = vi.fn();
|
||||
const updateCustomKeyValue = vi.fn();
|
||||
const findCustomKeyRow = vi.fn();
|
||||
const bustTranslationCache = vi.fn().mockResolvedValue(undefined);
|
||||
vi.mock('../../hooks/useInlineEdit', () => ({
|
||||
createCustomKey: (...a: unknown[]) => createCustomKey(...a),
|
||||
updateCustomKeyValue: (...a: unknown[]) => updateCustomKeyValue(...a),
|
||||
findCustomKeyRow: (...a: unknown[]) => findCustomKeyRow(...a),
|
||||
bustTranslationCache: (...a: unknown[]) => bustTranslationCache(...a),
|
||||
EDITOR_TRANSLATIONS_REFRESHED_EVENT: 'g7le:editor-translations-refreshed',
|
||||
}));
|
||||
vi.mock('../../../TranslationEngine', () => ({
|
||||
TranslationEngine: { getInstance: () => ({ translate: (k: string) => k }) },
|
||||
}));
|
||||
vi.mock('../../components/LocaleSwitcher', () => ({
|
||||
readSupportedLocales: () => ['ko', 'en', 'ja'],
|
||||
localeDisplayLabel: (loc: string) => loc,
|
||||
}));
|
||||
vi.mock('../../utils/authToken', () => ({ buildAuthHeaders: (h: Record<string, string>) => h }));
|
||||
|
||||
import { ArrayGroupEditor } from '../../components/property-controls/ArrayGroupEditor';
|
||||
import { ArrayCellTreeEditor } from '../../components/property-controls/ArrayCellTreeEditor';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
const t = (k: string, p?: Record<string, string | number>) =>
|
||||
p ? `${k}:${Object.values(p).join(',')}` : k;
|
||||
|
||||
const baseProps = {
|
||||
spec: null as never,
|
||||
manifest: null as never,
|
||||
t,
|
||||
templateIdentifier: 'sirsoft-admin_basic',
|
||||
};
|
||||
|
||||
afterEach(() => cleanup());
|
||||
beforeEach(() => {
|
||||
createCustomKey.mockReset();
|
||||
updateCustomKeyValue.mockReset();
|
||||
findCustomKeyRow.mockReset();
|
||||
});
|
||||
|
||||
describe('ArrayGroupEditor — 다중 배열 그룹(BarChart labels+datasets)', () => {
|
||||
const groupParams = {
|
||||
groups: [
|
||||
{
|
||||
arrayProp: 'labels',
|
||||
title: '항목 라벨',
|
||||
newItem: '',
|
||||
fields: [{ key: 'value', widget: 'text', label: '라벨', primary: true }],
|
||||
},
|
||||
{
|
||||
arrayProp: 'datasets',
|
||||
title: '데이터 계열',
|
||||
newItem: { label: '', data: [], backgroundColor: '#7C3AED' },
|
||||
fields: [
|
||||
{ key: 'label', widget: 'text', label: '계열', primary: true },
|
||||
{ key: 'data', widget: 'number-list', label: '값 목록' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const barNode = (): EditorNode =>
|
||||
({
|
||||
type: 'composite',
|
||||
name: 'BarChart',
|
||||
props: {
|
||||
labels: ['Jan', 'Feb'],
|
||||
datasets: [{ label: 'Sales', data: [1, 2], backgroundColor: '#7C3AED' }],
|
||||
},
|
||||
}) as EditorNode;
|
||||
|
||||
it('그룹마다 ArrayItemsEditor 섹션을 렌더한다', () => {
|
||||
render(<ArrayGroupEditor {...baseProps} node={barNode()} params={groupParams} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-array-group-labels')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-array-group-datasets')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('한 그룹(labels) 편집이 다른 그룹(datasets) 값을 보존한다', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayGroupEditor {...baseProps} node={barNode()} params={groupParams} onPatchNode={onPatchNode} />);
|
||||
// labels 그룹의 첫 항목(primary text) 편집.
|
||||
fireEvent.change(screen.getByTestId('g7le-array-field-0-value'), { target: { value: 'Mar' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.labels).toEqual(['Mar', 'Feb']);
|
||||
// datasets 는 그대로 보존.
|
||||
expect(patched.props!.datasets).toEqual([{ label: 'Sales', data: [1, 2], backgroundColor: '#7C3AED' }]);
|
||||
});
|
||||
|
||||
it('groups 미선언 → misconfigured 안내', () => {
|
||||
render(<ArrayGroupEditor {...baseProps} node={barNode()} params={{}} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-array-group-misconfigured')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ArrayCellTreeEditor — 중첩 셀 트리(CardGrid cardColumns)', () => {
|
||||
const cellParams = {
|
||||
arrayProp: 'cardColumns',
|
||||
idField: 'id',
|
||||
cellChildrenProp: 'cellChildren',
|
||||
cellChildComponent: 'Div',
|
||||
newItem: { id: '', cellChildren: [] },
|
||||
};
|
||||
const cardNode = (cols: unknown): EditorNode =>
|
||||
({ type: 'composite', name: 'CardGrid', props: { cardColumns: cols } }) as EditorNode;
|
||||
|
||||
it('컬럼 추가 시 newItem 골격(id/cellChildren)을 push', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayCellTreeEditor {...baseProps} node={cardNode([])} params={cellParams} onPatchNode={onPatchNode} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-tree-add'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.cardColumns).toEqual([{ id: '', cellChildren: [] }]);
|
||||
});
|
||||
|
||||
it('컬럼 id 편집이 해당 컬럼만 패치', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayCellTreeEditor
|
||||
{...baseProps}
|
||||
node={cardNode([{ id: 'a', cellChildren: [] }, { id: 'b', cellChildren: [] }])}
|
||||
params={cellParams}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
fireEvent.change(screen.getByTestId('g7le-cell-tree-id-1'), { target: { value: 'beta' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.cardColumns).toEqual([
|
||||
{ id: 'a', cellChildren: [] },
|
||||
{ id: 'beta', cellChildren: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('컬럼 삭제는 해당 인덱스만 제거', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayCellTreeEditor
|
||||
{...baseProps}
|
||||
node={cardNode([{ id: 'a', cellChildren: [] }, { id: 'b', cellChildren: [] }])}
|
||||
params={cellParams}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-tree-remove-0'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.cardColumns).toEqual([{ id: 'b', cellChildren: [] }]);
|
||||
});
|
||||
|
||||
it('컬럼 펼침 → cellChildren 트리 편집기(ChildrenListControl) 노출', () => {
|
||||
render(
|
||||
<ArrayCellTreeEditor
|
||||
{...baseProps}
|
||||
node={cardNode([{ id: 'a', cellChildren: [{ type: 'basic', name: 'Span', text: '내용' }] }])}
|
||||
params={cellParams}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-tree-toggle-0'));
|
||||
expect(screen.getByTestId('g7le-cell-tree-cells-0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-children-editor')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('펼친 셀에 자식 추가 시 그 컬럼의 cellChildren 으로 되돌아 패치', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayCellTreeEditor
|
||||
{...baseProps}
|
||||
node={cardNode([{ id: 'a', cellChildren: [] }])}
|
||||
params={cellParams}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-tree-toggle-0'));
|
||||
fireEvent.click(screen.getByTestId('g7le-children-add'));
|
||||
const patched = onPatchNode.mock.calls.at(-1)![0] as EditorNode;
|
||||
const cols = patched.props!.cardColumns as Array<{ id: string; cellChildren: unknown[] }>;
|
||||
expect(cols[0].id).toBe('a');
|
||||
expect(cols[0].cellChildren.length).toBe(1);
|
||||
});
|
||||
|
||||
it('정적-바인딩 가드: cardColumns 가 {{...}} → 디그레이드', () => {
|
||||
render(
|
||||
<ArrayCellTreeEditor
|
||||
{...baseProps}
|
||||
node={cardNode('{{modules?.data ?? []}}')}
|
||||
params={cellParams}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-cell-tree-bound')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-cell-tree-add')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('arrayProp 미선언 → misconfigured 안내', () => {
|
||||
render(<ArrayCellTreeEditor {...baseProps} node={cardNode([])} params={{}} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-cell-tree-misconfigured')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+544
@@ -0,0 +1,544 @@
|
||||
/**
|
||||
* ArrayItemsEditor.test.tsx — `array` 노드 에디터 RTL
|
||||
*
|
||||
* 검증:
|
||||
* - node.props[arrayProp] 항목을 행으로 렌더(필드 스키마=params.fields)
|
||||
* - 항목 추가(params.newItem/fields 골격) → onPatchNode({...node, props}) (노드 전체 교체)
|
||||
* - 삭제/정렬 → props 배열 패치(PATCH_LAYOUT 생존)
|
||||
* - text/select/boolean/icon 필드 즉시 반영
|
||||
* - i18n-text 평문 blur → createCustomKey → 항목 필드가 `$t:custom.*` 로 치환
|
||||
* - 기존 커스텀 키 blur → updateCustomKeyValue(현재 로케일 값만, 키 유지)
|
||||
* - 정적-바인딩 가드: props[arrayProp] 가 `{{...}}`/비-배열 → "바인딩됨" 디그레이드
|
||||
* - arrayProp 미선언 capability → misconfigured 안내
|
||||
* - 원시 string[] 항목 — primary 필드로 값 자체 편집
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
// 시나리오 매니페스트(tests/scenarios/layout-editor-array-editor.yaml) cross product 18 케이스
|
||||
// 전수 마킹(test-scenario-coverage 룰). 구조 연산(add/remove/move)은 field_widget 무관 → text 대표,
|
||||
// 필드 편집(edit_*)은 위젯별 분기. 바인딩/비-배열/빈 배열의 CRUD 는 manifest exclusions 로 제외.
|
||||
// @scenario array_value=static_array, field_widget=text, operation=add, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario array_value=empty, field_widget=text, operation=add, template=sirsoft-basic
|
||||
// @scenario array_value=empty, field_widget=text, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=remove, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=remove, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=move, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=move, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=edit_text_field, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=text, operation=edit_text_field, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=i18n_text, operation=edit_i18n_field, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=i18n_text, operation=edit_i18n_field, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=select, operation=edit_select, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=select, operation=edit_select, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=boolean, operation=edit_boolean, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=boolean, operation=edit_boolean, template=sirsoft-admin_basic
|
||||
// @scenario array_value=static_array, field_widget=icon, operation=edit_icon, template=sirsoft-basic
|
||||
// @scenario array_value=static_array, field_widget=icon, operation=edit_icon, template=sirsoft-admin_basic
|
||||
//
|
||||
// effects 검증 마킹은 아래 jsdoc 블록(@effects 연속 라인) — 매니페스트 effects 전수 커버.
|
||||
/**
|
||||
* @scenario array_value=static_array, field_widget=text, operation=add, template=sirsoft-basic
|
||||
* @effects array_capability_declared_on_p1_components_both_templates,
|
||||
* array_editor_registered_via_registercoreeditors_kind_agnostic,
|
||||
* property_modal_dispatches_array_node_editor_in_props_tab_by_kind,
|
||||
* binding_expression_array_prop_degrades_to_bound_notice,
|
||||
* non_array_prop_value_degrades_to_bound_notice,
|
||||
* missing_array_prop_capability_shows_misconfigured_notice,
|
||||
* add_item_appends_newitem_skeleton_patches_whole_node,
|
||||
* add_item_synthesizes_empty_item_from_fields_when_no_newitem,
|
||||
* remove_item_drops_only_that_index,
|
||||
* move_up_down_swaps_adjacent_with_boundary_guard,
|
||||
* text_field_updates_item_immediately,
|
||||
* icon_field_updates_item_with_icon_name_string,
|
||||
* select_field_updates_item_with_chosen_value,
|
||||
* boolean_field_toggles_item_flag,
|
||||
* i18n_text_plain_blur_creates_custom_key_and_writes_dollar_t_custom,
|
||||
* existing_custom_key_blur_updates_current_locale_value_keeps_key,
|
||||
* primitive_string_item_edits_value_via_primary_field,
|
||||
* node_prop_change_clears_draft_buffer_no_stale
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
|
||||
|
||||
vi.mock('../../LayoutEditorContext', () => ({
|
||||
useLayoutEditor: () => ({
|
||||
state: {
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
locale: 'ko',
|
||||
selectedRoute: { path: '/login', layoutName: 'login' },
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
const createCustomKey = vi.fn();
|
||||
const updateCustomKeyValue = vi.fn();
|
||||
const findCustomKeyRow = vi.fn();
|
||||
const bustTranslationCache = vi.fn().mockResolvedValue(undefined);
|
||||
// i18n-text 필드는 공통 위젯 I18nTextField(useCustomTranslation SSoT)를 거친다(7-b 통일).
|
||||
vi.mock('../../hooks/useInlineEdit', () => ({
|
||||
createCustomKey: (...a: unknown[]) => createCustomKey(...a),
|
||||
updateCustomKeyValue: (...a: unknown[]) => updateCustomKeyValue(...a),
|
||||
findCustomKeyRow: (...a: unknown[]) => findCustomKeyRow(...a),
|
||||
bustTranslationCache: (...a: unknown[]) => bustTranslationCache(...a),
|
||||
EDITOR_TRANSLATIONS_REFRESHED_EVENT: 'g7le:editor-translations-refreshed',
|
||||
}));
|
||||
|
||||
vi.mock('../../../TranslationEngine', () => ({
|
||||
TranslationEngine: {
|
||||
getInstance: () => ({
|
||||
translate: (key: string) => (key === 'custom.login.1' ? '기존 라벨' : key),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../components/LocaleSwitcher', () => ({
|
||||
readSupportedLocales: () => ['ko', 'en', 'ja'],
|
||||
localeDisplayLabel: (loc: string) => ({ ko: '한국어', en: 'English', ja: '日本語' }[loc] ?? loc),
|
||||
}));
|
||||
vi.mock('../../utils/authToken', () => ({ buildAuthHeaders: (h: Record<string, string>) => h }));
|
||||
|
||||
import { ArrayItemsEditor } from '../../components/property-controls/ArrayItemsEditor';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
const t = (k: string, p?: Record<string, string | number>) =>
|
||||
p ? `${k}:${Object.values(p).join(',')}` : k;
|
||||
|
||||
const baseProps = {
|
||||
spec: null as never,
|
||||
manifest: null as never,
|
||||
t,
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
};
|
||||
|
||||
/** tabs 필드 스키마 (TabNavigation 패턴). */
|
||||
const tabsParams = {
|
||||
arrayProp: 'tabs',
|
||||
itemLabel: '탭',
|
||||
newItem: { id: '', label: '' },
|
||||
fields: [
|
||||
{ key: 'label', widget: 'i18n-text', label: '라벨', primary: true },
|
||||
{ key: 'id', widget: 'text', label: 'ID' },
|
||||
{ key: 'iconName', widget: 'icon', label: '아이콘' },
|
||||
{ key: 'disabled', widget: 'boolean', label: '비활성' },
|
||||
],
|
||||
};
|
||||
|
||||
function tabNode(tabs: unknown): EditorNode {
|
||||
return { type: 'composite', name: 'TabNavigation', props: { tabs } } as EditorNode;
|
||||
}
|
||||
|
||||
afterEach(() => cleanup());
|
||||
beforeEach(() => {
|
||||
createCustomKey.mockReset();
|
||||
updateCustomKeyValue.mockReset();
|
||||
findCustomKeyRow.mockReset();
|
||||
bustTranslationCache.mockClear();
|
||||
});
|
||||
|
||||
/** i18n-text 필드(idx, key)의 I18nTextField 미리보기 입력칸. */
|
||||
function i18nPreview(idx: number, key: string): HTMLInputElement {
|
||||
return screen.getByTestId(`g7le-array-field-${idx}-${key}-i18n-preview`) as HTMLInputElement;
|
||||
}
|
||||
|
||||
describe('ArrayItemsEditor — props 배열 항목 편집', () => {
|
||||
it('정적 배열 항목을 행으로 렌더한다(필드 스키마)', () => {
|
||||
const node = tabNode([
|
||||
{ id: 'a', label: '첫째' },
|
||||
{ id: 'b', label: '둘째' },
|
||||
]);
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={tabsParams} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-array-row-0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-array-row-1')).toBeInTheDocument();
|
||||
expect(i18nPreview(0, 'label').value).toBe('첫째'); // i18n-text 라벨 = I18nTextField 미리보기
|
||||
expect((screen.getByTestId('g7le-array-field-0-id') as HTMLInputElement).value).toBe('a');
|
||||
});
|
||||
|
||||
it('필드 행은 가로 스크롤 대신 자연 wrap 한다 (fieldRow flexWrap) —', () => {
|
||||
const node = tabNode([{ id: 'a', label: '첫째' }]);
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={tabsParams} onPatchNode={vi.fn()} />);
|
||||
// id 필드(text)를 감싼 <label style={fieldRow}> 가 wrap 가능해야(좁은 폭에서 라벨+입력 줄바꿈).
|
||||
const fieldRow = (screen.getByTestId('g7le-array-field-0-id').closest('label')) as HTMLElement;
|
||||
expect(fieldRow.style.flexWrap).toBe('wrap');
|
||||
});
|
||||
|
||||
it('빈 배열 → 안내 표시', () => {
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([])} params={tabsParams} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-array-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('"추가" → newItem 골격을 끝에 append (노드 전체 교체)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([{ id: 'a', label: '첫째' }])} params={tabsParams} onPatchNode={onPatchNode} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-add'));
|
||||
expect(onPatchNode).toHaveBeenCalledTimes(1);
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.tabs as unknown[]).length).toBe(2);
|
||||
expect((patched.props!.tabs as Array<Record<string, unknown>>)[1]).toEqual({ id: '', label: '' });
|
||||
});
|
||||
|
||||
describe('params.defaultItems — prop 미정의 시 스펙 선언 기본 목록 시드', () => {
|
||||
// IconSelect 류: 컴포넌트가 prop 미지정 시 내장 기본 목록으로 렌더 → 빈 목록에서 1개
|
||||
// 추가하면 prop 이 [추가분] 으로 기록되어 내장 목록 전체가 교체되던 함정 차단.
|
||||
const defaults = [
|
||||
{ value: 'Home', label: 'Home', faIcon: 'home' },
|
||||
{ value: 'User', label: 'User', faIcon: 'user' },
|
||||
];
|
||||
const seededParams = {
|
||||
arrayProp: 'options',
|
||||
newItem: { value: '', label: '', faIcon: '' },
|
||||
defaultItems: defaults,
|
||||
fields: [{ key: 'label', widget: 'text', label: '라벨', primary: true }],
|
||||
};
|
||||
const iconNode = (props: Record<string, unknown>): EditorNode =>
|
||||
({ type: 'composite', name: 'IconSelect', props } as EditorNode);
|
||||
|
||||
it('prop 미정의(undefined) → defaultItems 가 시작 목록으로 렌더', () => {
|
||||
render(
|
||||
<ArrayItemsEditor {...baseProps} node={iconNode({})} params={seededParams} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getAllByTestId(/^g7le-array-row-/)).toHaveLength(2);
|
||||
expect((screen.getByTestId('g7le-array-field-0-label') as HTMLInputElement).value).toBe('Home');
|
||||
});
|
||||
|
||||
it('시드 상태에서 "추가" → 기본 목록 전체 + 새 항목이 함께 커밋(내장 목록 교체 함정 차단)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayItemsEditor {...baseProps} node={iconNode({})} params={seededParams} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-add'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
const options = patched.props!.options as Array<Record<string, unknown>>;
|
||||
expect(options).toHaveLength(3);
|
||||
expect(options[0]).toEqual(defaults[0]);
|
||||
expect(options[1]).toEqual(defaults[1]);
|
||||
expect(options[2]).toEqual({ value: '', label: '', faIcon: '' });
|
||||
});
|
||||
|
||||
it('명시적 빈 배열([]) → 시드하지 않음(작성자 의도 존중)', () => {
|
||||
render(
|
||||
<ArrayItemsEditor {...baseProps} node={iconNode({ options: [] })} params={seededParams} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-array-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('prop 이 정적 배열이면 그 값이 우선(시드 미적용)', () => {
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={iconNode({ options: [{ value: 'X', label: '커스텀', faIcon: 'star' }] })}
|
||||
params={seededParams}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getAllByTestId(/^g7le-array-row-/)).toHaveLength(1);
|
||||
expect((screen.getByTestId('g7le-array-field-0-label') as HTMLInputElement).value).toBe('커스텀');
|
||||
});
|
||||
|
||||
it('바인딩({{...}}) prop 은 종전대로 디그레이드(시드 무관)', () => {
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={iconNode({ options: '{{icons.data}}' })}
|
||||
params={seededParams}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-array-editor-bound')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('defaultItems 미선언 capability 는 종전 동작 그대로(빈 목록 안내)', () => {
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={iconNode({})}
|
||||
params={{ arrayProp: 'options', fields: [{ key: 'label', widget: 'text', label: '라벨', primary: true }] }}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-array-empty')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('삭제 → 해당 인덱스만 제거', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([{ id: 'a' }, { id: 'b' }])} params={tabsParams} onPatchNode={onPatchNode} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-remove-0'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.tabs).toEqual([{ id: 'b' }]);
|
||||
});
|
||||
|
||||
it('위/아래 이동 → 인접 항목 스왑(경계 가드)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([{ id: 'a' }, { id: 'b' }])} params={tabsParams} onPatchNode={onPatchNode} />);
|
||||
// 0행 위로 = 비활성
|
||||
expect((screen.getByTestId('g7le-array-up-0') as HTMLButtonElement).disabled).toBe(true);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-down-0'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.tabs).toEqual([{ id: 'b' }, { id: 'a' }]);
|
||||
});
|
||||
|
||||
it('text 필드 즉시 반영', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([{ id: 'a', label: 'x' }])} params={tabsParams} onPatchNode={onPatchNode} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-array-field-0-id'), { target: { value: 'home' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.tabs as Array<Record<string, unknown>>)[0].id).toBe('home');
|
||||
});
|
||||
|
||||
it('boolean 필드 토글 즉시 반영', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([{ id: 'a' }])} params={tabsParams} onPatchNode={onPatchNode} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-field-0-disabled'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.tabs as Array<Record<string, unknown>>)[0].disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('select 필드 선택 즉시 반영', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const params = {
|
||||
arrayProp: 'items',
|
||||
fields: [
|
||||
{ key: 'label', widget: 'i18n-text', label: '라벨', primary: true },
|
||||
{ key: 'variant', widget: 'select', label: '스타일', options: [{ value: 'danger', label: '위험' }] },
|
||||
],
|
||||
};
|
||||
const node = { type: 'composite', name: 'ActionMenu', props: { items: [{ label: 'x' }] } } as EditorNode;
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={params} onPatchNode={onPatchNode} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-array-field-0-variant'), { target: { value: 'danger' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.items as Array<Record<string, unknown>>)[0].variant).toBe('danger');
|
||||
});
|
||||
|
||||
it('i18n-text 평문 blur → createCustomKey 후 필드가 $t:custom.* 로 치환(공통 위젯)', async () => {
|
||||
createCustomKey.mockResolvedValue({ kind: 'ok', resource: { translation_key: 'custom.login.7' } });
|
||||
const onPatchNode = vi.fn();
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([{ id: 'a', label: '' }])} params={tabsParams} onPatchNode={onPatchNode} />);
|
||||
const preview = i18nPreview(0, 'label');
|
||||
fireEvent.change(preview, { target: { value: '새 라벨' } });
|
||||
fireEvent.blur(preview);
|
||||
await waitFor(() => expect(createCustomKey).toHaveBeenCalledWith('sirsoft-basic', 'login', 'ko', '새 라벨'));
|
||||
await waitFor(() => expect(onPatchNode).toHaveBeenCalled());
|
||||
const last = onPatchNode.mock.calls.at(-1)![0] as EditorNode;
|
||||
expect((last.props!.tabs as Array<Record<string, unknown>>)[0].label).toBe('$t:custom.login.7');
|
||||
});
|
||||
|
||||
it('기존 커스텀 키 blur → updateCustomKeyValue(현재 로케일만, 키 유지)', async () => {
|
||||
updateCustomKeyValue.mockResolvedValue({ kind: 'ok' });
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={tabNode([{ id: 'a', label: '$t:custom.login.1' }])}
|
||||
params={tabsParams}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
const input = i18nPreview(0, 'label');
|
||||
expect(input.value).toBe('기존 라벨'); // 키 → 현재 로케일 해석값(raw 미노출)
|
||||
fireEvent.change(input, { target: { value: '수정 라벨' } });
|
||||
fireEvent.blur(input);
|
||||
await waitFor(() => expect(updateCustomKeyValue).toHaveBeenCalledWith('sirsoft-basic', 'custom.login.1', 'ko', '수정 라벨'));
|
||||
expect(createCustomKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('정적-바인딩 가드: props[arrayProp] 가 {{...}} → 디그레이드', () => {
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode('{{(roles?.data ?? []).map(r => r)}}')} params={tabsParams} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-array-editor-bound')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-array-add')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('arrayProp 미선언 → misconfigured 안내', () => {
|
||||
render(<ArrayItemsEditor {...baseProps} node={tabNode([])} params={{}} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-array-editor-misconfigured')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('원시 string[] 항목 — primary 필드로 값 자체 편집', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const params = { arrayProp: 'options', fields: [{ key: 'value', widget: 'text', label: '값', primary: true }] };
|
||||
const node = { type: 'basic', name: 'Select', props: { options: ['ko', 'en'] } } as EditorNode;
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={params} onPatchNode={onPatchNode} />);
|
||||
expect((screen.getByTestId('g7le-array-field-0-value') as HTMLInputElement).value).toBe('ko');
|
||||
fireEvent.change(screen.getByTestId('g7le-array-field-1-value'), { target: { value: 'ja' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.options).toEqual(['ko', 'ja']);
|
||||
});
|
||||
|
||||
/**
|
||||
* 원시 배열(BarChart labels 등)에 "추가" 시, newItem 이 원시값(빈 문자열)이면
|
||||
* 객체 합성 없이 원시값을 push 해 배열 형태가 보존돼야 한다. (이전엔 newItem 이 falsy 라
|
||||
* fields 기반 `{ value: '' }` 객체가 섞이는 회귀 — string[] 에 객체 혼입.)
|
||||
* @scenario unit=primitive_array_capability
|
||||
* @effects array_editor_primitive_newitem_pushes_raw_value_not_object, primitive_array_add_then_edit_keeps_raw_shape, barchart_labels_array_capability_static_literal_only
|
||||
*/
|
||||
it('원시 string[] — "추가" 시 원시값(빈 문자열) 골격을 push (객체 합성 안 함)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const params = {
|
||||
arrayProp: 'labels',
|
||||
newItem: '',
|
||||
fields: [{ key: 'value', widget: 'text', label: '항목', primary: true }],
|
||||
};
|
||||
const node = { type: 'composite', name: 'BarChart', props: { labels: ['Jan', 'Feb'] } } as EditorNode;
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={params} onPatchNode={onPatchNode} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-add'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.labels).toEqual(['Jan', 'Feb', '']);
|
||||
});
|
||||
|
||||
it('원시 string[] — 추가 후 primary 편집으로 값 채움 (원시 형태 유지)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const params = {
|
||||
arrayProp: 'labels',
|
||||
newItem: '',
|
||||
fields: [{ key: 'value', widget: 'text', label: '항목', primary: true }],
|
||||
};
|
||||
// 이미 빈 항목이 추가된 상태에서 그 항목을 편집.
|
||||
const node = { type: 'composite', name: 'BarChart', props: { labels: ['Jan', ''] } } as EditorNode;
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={params} onPatchNode={onPatchNode} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-array-field-1-value'), { target: { value: 'Mar' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.props!.labels).toEqual(['Jan', 'Mar']);
|
||||
});
|
||||
|
||||
// 차트/데이터 정의용 신규 필드 위젯(number/color/number-list).
|
||||
// 부록8 (E) #4 — DonutChart.data(name/value/color) / BarChart.datasets(label/data:number[]/bg).
|
||||
describe('number/color/number-list 필드 위젯', () => {
|
||||
/** DonutChart data 필드 스키마(name/value/color). */
|
||||
const donutParams = {
|
||||
arrayProp: 'data',
|
||||
newItem: { name: '', value: 0, color: '#7C3AED' },
|
||||
fields: [
|
||||
{ key: 'name', widget: 'i18n-text', label: '항목', primary: true },
|
||||
{ key: 'value', widget: 'number', label: '값' },
|
||||
{ key: 'color', widget: 'color', label: '색상' },
|
||||
],
|
||||
};
|
||||
const donutNode = (data: unknown): EditorNode =>
|
||||
({ type: 'composite', name: 'DonutChart', props: { data } }) as EditorNode;
|
||||
|
||||
/**
|
||||
* @scenario unit=number_widget
|
||||
* @effects array_editor_number_widget_writes_numeric_value
|
||||
*/
|
||||
it('number 위젯: 입력값을 Number 로 기록(빈 입력은 undefined)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={donutNode([{ name: 'A', value: 10, color: '#fff' }])}
|
||||
params={donutParams}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
const input = screen.getByTestId('g7le-array-field-0-value') as HTMLInputElement;
|
||||
expect(input.value).toBe('10');
|
||||
fireEvent.change(input, { target: { value: '42' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.data as Array<{ value: unknown }>)[0].value).toBe(42);
|
||||
});
|
||||
|
||||
/**
|
||||
* @scenario unit=color_widget
|
||||
* @effects array_editor_color_widget_writes_hex_string
|
||||
*/
|
||||
it('color 위젯: 색 피커 + 텍스트 입력 둘 다 HEX 문자열 기록', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={donutNode([{ name: 'A', value: 10, color: '#7C3AED' }])}
|
||||
params={donutParams}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
const text = screen.getByTestId('g7le-array-field-0-color') as HTMLInputElement;
|
||||
expect(text.value).toBe('#7C3AED');
|
||||
fireEvent.change(text, { target: { value: '#EC4899' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.data as Array<{ color: unknown }>)[0].color).toBe('#EC4899');
|
||||
});
|
||||
|
||||
/**
|
||||
* @scenario unit=number_list_widget
|
||||
* @effects array_editor_number_list_widget_parses_comma_separated_into_number_array
|
||||
*/
|
||||
it('number-list 위젯: 콤마 구분 입력 ↔ number[] (비-수치 토큰 제거)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const params = {
|
||||
arrayProp: 'datasets',
|
||||
newItem: { label: '', data: [], backgroundColor: '#7C3AED' },
|
||||
fields: [
|
||||
{ key: 'label', widget: 'text', label: '계열', primary: true },
|
||||
{ key: 'data', widget: 'number-list', label: '값 목록' },
|
||||
],
|
||||
};
|
||||
const node = {
|
||||
type: 'composite',
|
||||
name: 'BarChart',
|
||||
props: { datasets: [{ label: 'Sales', data: [1, 2, 3], backgroundColor: '#7C3AED' }] },
|
||||
} as EditorNode;
|
||||
render(<ArrayItemsEditor {...baseProps} node={node} params={params} onPatchNode={onPatchNode} />);
|
||||
const input = screen.getByTestId('g7le-array-field-0-data') as HTMLInputElement;
|
||||
expect(input.value).toBe('1, 2, 3');
|
||||
fireEvent.change(input, { target: { value: '10, 20, x, 30' } });
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.props!.datasets as Array<{ data: unknown }>)[0].data).toEqual([10, 20, 30]);
|
||||
});
|
||||
|
||||
/**
|
||||
* @scenario unit=donut_add_shape
|
||||
* @effects array_editor_newitem_shape_matches_component_read_shape
|
||||
*/
|
||||
it('추가 시 newItem shape(name/value/color)이 컴포넌트 읽기 shape 와 일치', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ArrayItemsEditor {...baseProps} node={donutNode([])} params={donutParams} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-array-add'));
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
const item = (patched.props!.data as Array<Record<string, unknown>>)[0];
|
||||
expect(item).toEqual({ name: '', value: 0, color: '#7C3AED' });
|
||||
});
|
||||
});
|
||||
|
||||
// (라이브 실측 발견) — ArrayItemsEditor 가 NodeEditorProps.candidates 를
|
||||
// 항목 i18n-text 필드의 I18nTextField 로 **전달**해야 `+데이터` 칩 삽입(키화) 입구가 뜬다. 종전엔
|
||||
// 전달이 끊겨(후보 0) 평문 라벨에 `+데이터` 버튼이 안 떴다(라이브 — TabNavigation.label 칸).
|
||||
describe('항목 i18n-text 필드 후보 풀 전달', () => {
|
||||
const scalarCandidate = {
|
||||
expression: '{{user.name}}', source: 'data_source' as const, sourceId: 'user',
|
||||
path: 'name', shape: 'scalar' as const, preview: '홍길동',
|
||||
};
|
||||
|
||||
it('candidates 전달 시 평문 라벨 항목에 +데이터 버튼 노출', () => {
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={tabNode([{ id: 'a', label: '평문 라벨' }])}
|
||||
params={tabsParams}
|
||||
onPatchNode={vi.fn()}
|
||||
candidates={[scalarCandidate]}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.getByTestId('g7le-array-field-0-label-i18n-plus-data-btn'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('candidates 미전달 시 +데이터 버튼 미노출(디그레이드)', () => {
|
||||
render(
|
||||
<ArrayItemsEditor
|
||||
{...baseProps}
|
||||
node={tabNode([{ id: 'a', label: '평문 라벨' }])}
|
||||
params={tabsParams}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('g7le-array-field-0-label-i18n-plus-data-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
// e2e:allow 레이아웃 편집기 캔버스 오버레이/속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(T1~T8) 실측 + 단위/레이아웃 렌더링 테스트로 검증
|
||||
/**
|
||||
* CellBorderControl.test.tsx — 셀 테두리 시각 피커
|
||||
*
|
||||
* 검증: 카탈로그 기반 두께/변/색 버튼 렌더 + className 합성(border 토큰만 교체, 나머지 보존)
|
||||
* + 역해석(현재 className → 활성 두께/변/색) + 카탈로그 미공급 시 null(중립 폴백).
|
||||
*
|
||||
* @scenario cell_border_visual_picker
|
||||
* @effects cell_border_visual_picker_replaces_raw_classname_input, cell_border_compose_preserves_non_border_classes, cell_border_reverse_resolves_active_state, cell_border_library_neutral_catalog_supplied
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { CellBorderControl, type CellBorderCatalog } from '../../components/property-controls/CellBorderControl';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
const catalog: CellBorderCatalog = {
|
||||
sides: [
|
||||
{ value: 'all', prefix: 'border' },
|
||||
{ value: 'top', prefix: 'border-t' },
|
||||
{ value: 'bottom', prefix: 'border-b' },
|
||||
{ value: 'left', prefix: 'border-l' },
|
||||
{ value: 'right', prefix: 'border-r' },
|
||||
],
|
||||
widths: [
|
||||
{ value: 'none' },
|
||||
{ value: 'thin', suffix: '' },
|
||||
{ value: 'medium', suffix: '-2' },
|
||||
{ value: 'thick', suffix: '-4' },
|
||||
],
|
||||
colors: [
|
||||
{ value: 'gray-300', swatch: '#d1d5db', token: 'border-gray-300' },
|
||||
{ value: 'blue-500', swatch: '#3b82f6', token: 'border-blue-500' },
|
||||
],
|
||||
};
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('CellBorderControl — 렌더/디그레이드', () => {
|
||||
it('카탈로그 미공급 → null(중립 폴백)', () => {
|
||||
const { container } = render(<CellBorderControl className="" catalog={null} t={t} onChange={vi.fn()} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('카탈로그 공급 → 두께 버튼 렌더, 두께 none 이면 변/색 미표시', () => {
|
||||
render(<CellBorderControl className="" catalog={catalog} t={t} onChange={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-cell-border-width-thin')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-border-width-thick')).toBeTruthy();
|
||||
// 두께 미선택(none) → 변/색 영역 숨김.
|
||||
expect(screen.queryByTestId('g7le-cell-border-sides')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-cell-border-colors')).toBeNull();
|
||||
});
|
||||
|
||||
it('두께 선택 시 변/색 노출', () => {
|
||||
render(<CellBorderControl className="border border-gray-300" catalog={catalog} t={t} onChange={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-cell-border-sides')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-border-colors')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellBorderControl — className 합성(border 토큰만 교체)', () => {
|
||||
it('두께 thin 선택 → 비어있으면 all 변 + border 추가', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CellBorderControl className="px-4 py-2" catalog={catalog} t={t} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-border-width-thin'));
|
||||
const next = onChange.mock.calls[0][0] as string;
|
||||
expect(next).toContain('px-4');
|
||||
expect(next).toContain('py-2'); // 비-테두리 클래스 보존
|
||||
expect(next.split(/\s+/)).toContain('border');
|
||||
});
|
||||
|
||||
it('두께 medium → border-2, 기존 border 두께 토큰 교체', () => {
|
||||
const onChange = vi.fn();
|
||||
// 색은 인라인 SSoT 라 className 에서 제외 — 두께 변경은 width/side 토큰만, 색 토큰 미포함.
|
||||
render(<CellBorderControl className="border px-2" catalog={catalog} t={t} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-border-width-medium'));
|
||||
const next = (onChange.mock.calls[0][0] as string).split(/\s+/);
|
||||
expect(next).toContain('border-2');
|
||||
expect(next).not.toContain('border'); // 기존 두께 교체
|
||||
expect(next).toContain('px-2'); // 비-테두리 보존
|
||||
expect(next.some((tk) => /gray|blue|red/.test(tk))).toBe(false); // 색 토큰은 className 에 없음
|
||||
});
|
||||
|
||||
it('프리셋 색 클릭 → onPresetToken(토큰) 호출(부모가 활성 스킴 토큰으로 적용)', () => {
|
||||
const onPresetToken = vi.fn();
|
||||
const onChange = vi.fn();
|
||||
render(<CellBorderControl className="border" catalog={catalog} t={t} onChange={onChange} onPresetToken={onPresetToken} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-border-color-blue-500'));
|
||||
expect(onPresetToken).toHaveBeenCalledWith('border-blue-500');
|
||||
});
|
||||
|
||||
it('두께 none → 두께 토큰만 제거(색 토큰은 보존 — 4차: 색=토큰 SSoT 독립), 나머지 보존', () => {
|
||||
// 4차: 색은 className 토큰 SSoT(스킴별)라 두께 변경과 독립 — 두께 none 은 width/side 토큰만
|
||||
// 제거하고 색 토큰(border-gray-300)은 보존(두께 0이라 시각상 안 보이나 색 설정은 유지).
|
||||
const onChange = vi.fn();
|
||||
render(<CellBorderControl className="border border-gray-300 rounded px-2" catalog={catalog} t={t} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-border-width-none'));
|
||||
const next = (onChange.mock.calls[0][0] as string).split(/\s+/).filter(Boolean);
|
||||
expect(next).not.toContain('border'); // 두께 토큰 제거
|
||||
expect(next).toContain('border-gray-300'); // 색 토큰은 보존
|
||||
expect(next).toContain('rounded');
|
||||
expect(next).toContain('px-2');
|
||||
});
|
||||
|
||||
it('자유 색 컬러 피커 → onColorStyle(HEX) 호출', () => {
|
||||
const onColorStyle = vi.fn();
|
||||
render(<CellBorderControl className="border border-gray-300" catalog={catalog} t={t} onChange={vi.fn()} colorStyle="" onColorStyle={onColorStyle} />);
|
||||
const picker = screen.getByTestId('g7le-cell-border-color-picker') as HTMLInputElement;
|
||||
fireEvent.input(picker, { target: { value: '#ff8800' } });
|
||||
expect(onColorStyle).toHaveBeenCalledWith('#ff8800');
|
||||
});
|
||||
|
||||
it('라이트 탭: 프리셋 색 토큰(border-gray-300) 활성 + 자유 색(인라인)은 별도 활성', () => {
|
||||
// 4차: 프리셋=className 토큰, 자유=인라인 — 두 SSoT 가 분리되어 공존 가능.
|
||||
render(<CellBorderControl className="border border-gray-300" catalog={catalog} t={t} onChange={vi.fn()} colorStyle="#123456" onColorStyle={vi.fn()} />);
|
||||
// 프리셋 토큰이 className 에 있으면 그 프리셋 활성(토큰 경로).
|
||||
expect((screen.getByTestId('g7le-cell-border-color-gray-300') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
|
||||
// ── colorScheme prop (단일 공용 탭은 부모 ColorSchemeTabs — 컨트롤은 표시만) ──
|
||||
it('스킴 탭은 컨트롤 내부에 없음(부모 단일 탭으로 이동)', () => {
|
||||
render(<CellBorderControl className="border border-gray-300" catalog={catalog} t={t} onChange={vi.fn()} colorScheme="light" onPresetToken={vi.fn()} onColorStyle={vi.fn()} />);
|
||||
expect(screen.queryByTestId('g7le-cell-border-scheme-tabs')).toBeNull();
|
||||
});
|
||||
|
||||
it('colorScheme=dark: dark:border-* 토큰 활성, 자유 색 컬러피커 비활성', () => {
|
||||
render(<CellBorderControl className="border dark:border-blue-500" catalog={catalog} t={t} onChange={vi.fn()} colorScheme="dark" onPresetToken={vi.fn()} colorStyle="#123456" onColorStyle={vi.fn()} />);
|
||||
// 다크 색 토큰(blue-500) 활성.
|
||||
expect((screen.getByTestId('g7le-cell-border-color-blue-500') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
// 자유 색 컬러피커 비활성(다크는 프리셋만).
|
||||
expect((screen.getByTestId('g7le-cell-border-color-picker') as HTMLInputElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('colorScheme=dark: 라이트 색 토큰(border-gray-300)은 비활성(스킴 분리)', () => {
|
||||
render(<CellBorderControl className="border border-gray-300" catalog={catalog} t={t} onChange={vi.fn()} colorScheme="dark" onPresetToken={vi.fn()} onColorStyle={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-border-color-gray-300') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('변 토글 → 개별 변(top) 선택 시 border-t, all 해제', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CellBorderControl className="border border-gray-300" catalog={catalog} t={t} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-border-side-top'));
|
||||
const next = (onChange.mock.calls[0][0] as string).split(/\s+/);
|
||||
expect(next).toContain('border-t');
|
||||
expect(next).not.toContain('border'); // all 해제
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellBorderControl — 역해석(현재 className → 활성 상태)', () => {
|
||||
it('border border-blue-500 → 두께 thin·변 all·색 blue 활성', () => {
|
||||
render(<CellBorderControl className="border border-blue-500" catalog={catalog} t={t} onChange={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-border-width-thin') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-cell-border-side-all') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-cell-border-color-blue-500') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
|
||||
it('border-t-2 → 두께 medium·변 top 활성', () => {
|
||||
render(<CellBorderControl className="border-t-2 border-gray-300" catalog={catalog} t={t} onChange={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-border-width-medium') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-cell-border-side-top') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-cell-border-side-all') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
});
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
// e2e:allow 레이아웃 편집기 캔버스 오버레이/속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(T1~T8) 실측 + 단위/레이아웃 렌더링 테스트로 검증
|
||||
/**
|
||||
* CellFillControl.test.tsx — 셀 배경색 시각 피커
|
||||
*
|
||||
* 검증: 프리셋 스와치(token 경로) + 없음(투명) + 자유 컬러피커(인라인, 라이트 전용) 렌더,
|
||||
* 라이트/다크 탭, 토큰 역해석 활성 표시, 다크 탭 자유 색 비활성 + token 없는 프리셋 비활성,
|
||||
* 카탈로그 미공급 시 자유 색만.
|
||||
*
|
||||
* @scenario cell_fill_visual_picker_light_dark
|
||||
* @effects cell_fill_preset_applies_classtoken_per_scheme, cell_fill_custom_inline_light_only, cell_fill_none_clears, cell_fill_dark_disables_custom
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { CellFillControl, type CellFillCatalog } from '../../components/property-controls/CellFillControl';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
const catalog: CellFillCatalog = {
|
||||
colors: [
|
||||
{ value: 'white', swatch: '#ffffff', token: 'bg-white' },
|
||||
{ value: 'yellow-100', swatch: '#fef9c3', token: 'bg-yellow-100' },
|
||||
{ value: 'blue-100', swatch: '#dbeafe', token: 'bg-blue-100' },
|
||||
],
|
||||
};
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('CellFillControl — 렌더', () => {
|
||||
it('카탈로그 공급 → 없음 + 프리셋 스와치 + 자유 색 피커 렌더', () => {
|
||||
render(<CellFillControl catalog={catalog} t={t} onCustomColor={vi.fn()} onClear={vi.fn()} onPresetToken={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-cell-fill-none')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-fill-color-yellow-100')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-fill-color-picker')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('카탈로그 미공급 → 없음 + 자유 색만(프리셋 부재)', () => {
|
||||
render(<CellFillControl catalog={null} t={t} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-cell-fill-none')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-fill-color-picker')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-cell-fill-color-yellow-100')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellFillControl — 적용(프리셋=토큰, 자유=인라인)', () => {
|
||||
it('프리셋(token 보유) 클릭 → onPresetToken(token)', () => {
|
||||
const onPresetToken = vi.fn();
|
||||
render(<CellFillControl catalog={catalog} t={t} onPresetToken={onPresetToken} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-fill-color-yellow-100'));
|
||||
expect(onPresetToken).toHaveBeenCalledWith('bg-yellow-100');
|
||||
});
|
||||
|
||||
it('없음 클릭 → onClear()', () => {
|
||||
const onClear = vi.fn();
|
||||
render(<CellFillControl catalog={catalog} colorStyle="#fef9c3" t={t} onClear={onClear} onCustomColor={vi.fn()} onPresetToken={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-fill-none'));
|
||||
expect(onClear).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('자유 컬러 피커 → onCustomColor(HEX) (라이트)', () => {
|
||||
const onCustomColor = vi.fn();
|
||||
render(<CellFillControl catalog={catalog} t={t} onCustomColor={onCustomColor} onClear={vi.fn()} onPresetToken={vi.fn()} />);
|
||||
fireEvent.input(screen.getByTestId('g7le-cell-fill-color-picker'), { target: { value: '#ff8800' } });
|
||||
expect(onCustomColor).toHaveBeenCalledWith('#ff8800');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellFillControl — 역해석(활성 표시)', () => {
|
||||
it('라이트: className 에 프리셋 토큰 → 그 프리셋 활성', () => {
|
||||
render(<CellFillControl catalog={catalog} className="bg-yellow-100" colorScheme="light" t={t} onPresetToken={vi.fn()} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-fill-color-yellow-100') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
|
||||
it('라이트: 인라인 자유 HEX(프리셋 swatch 불일치) → 프리셋 비활성', () => {
|
||||
render(<CellFillControl catalog={catalog} colorStyle="#123456" colorScheme="light" t={t} onPresetToken={vi.fn()} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-fill-color-yellow-100') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
expect((screen.getByTestId('g7le-cell-fill-none') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('라이트: 색 토큰/인라인 모두 없음 → 없음(투명) 활성', () => {
|
||||
render(<CellFillControl catalog={catalog} colorStyle="" colorScheme="light" t={t} onPresetToken={vi.fn()} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-fill-none') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellFillControl — colorScheme prop (단일 공용 탭은 부모)', () => {
|
||||
it('스킴 탭은 컨트롤 내부에 없음(부모 ColorSchemeTabs 로 이동)', () => {
|
||||
render(<CellFillControl catalog={catalog} t={t} colorScheme="light" onPresetToken={vi.fn()} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect(screen.queryByTestId('g7le-cell-fill-scheme-tabs')).toBeNull();
|
||||
});
|
||||
|
||||
it('colorScheme=dark: dark:bg-* 토큰 활성, 자유 색 비활성', () => {
|
||||
render(<CellFillControl catalog={catalog} className="dark:bg-blue-100" colorScheme="dark" t={t} onPresetToken={vi.fn()} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-fill-color-blue-100') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-cell-fill-color-picker') as HTMLInputElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('colorScheme=dark: 프리셋 클릭 → onPresetToken(token) (부모가 dark: 적용)', () => {
|
||||
const onPresetToken = vi.fn();
|
||||
render(<CellFillControl catalog={catalog} colorScheme="dark" t={t} onPresetToken={onPresetToken} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-fill-color-blue-100'));
|
||||
expect(onPresetToken).toHaveBeenCalledWith('bg-blue-100');
|
||||
});
|
||||
|
||||
it('colorScheme=dark: 라이트 색 토큰(bg-yellow-100)은 비활성(스킴 분리)', () => {
|
||||
render(<CellFillControl catalog={catalog} className="bg-yellow-100" colorScheme="dark" t={t} onPresetToken={vi.fn()} onCustomColor={vi.fn()} onClear={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-fill-color-yellow-100') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
});
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
// e2e:allow 레이아웃 편집기 캔버스 오버레이/속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(T1~T8) 실측 + 단위/레이아웃 렌더링 테스트로 검증
|
||||
/**
|
||||
* CellPaddingControl.test.tsx — 셀 내부 여백 시각 피커
|
||||
*
|
||||
* 검증: 프리셋 단계 칩 + 자유 px 입력 렌더, 단계 클릭 시 px 인라인 콜백(없음=빈값),
|
||||
* 자유 px 입력 후 blur/Enter 적용, 현재 padding 에 따른 활성 표시.
|
||||
*
|
||||
* @scenario cell_padding_visual_picker
|
||||
* @effects cell_padding_step_applies_inline_px, cell_padding_none_clears, cell_padding_free_px_input, cell_padding_reverse_resolves_active
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, act } from '@testing-library/react';
|
||||
import { CellPaddingControl, type CellPaddingCatalog } from '../../components/property-controls/CellPaddingControl';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
const catalog: CellPaddingCatalog = {
|
||||
steps: [
|
||||
{ value: 'none' },
|
||||
{ value: 'narrow', px: 4 },
|
||||
{ value: 'normal', px: 8 },
|
||||
{ value: 'wide', px: 16 },
|
||||
],
|
||||
};
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('CellPaddingControl — 렌더', () => {
|
||||
it('카탈로그 공급 → 단계 칩 + 자유 px 입력 렌더', () => {
|
||||
render(<CellPaddingControl catalog={catalog} t={t} onChange={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-cell-padding-step-none')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-padding-step-wide')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-cell-padding-free')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellPaddingControl — 적용(인라인 px SSoT)', () => {
|
||||
it('단계 normal(8px) 클릭 → onChange("8px")', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CellPaddingControl catalog={catalog} t={t} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-padding-step-normal'));
|
||||
expect(onChange).toHaveBeenCalledWith('8px');
|
||||
});
|
||||
|
||||
it('단계 none 클릭 → onChange("")', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CellPaddingControl catalog={catalog} paddingStyle="8px" t={t} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-cell-padding-step-none'));
|
||||
expect(onChange).toHaveBeenCalledWith('');
|
||||
});
|
||||
|
||||
it('자유 px 입력 후 blur → onChange("20px")', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CellPaddingControl catalog={catalog} t={t} onChange={onChange} />);
|
||||
const input = screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '20' } });
|
||||
fireEvent.blur(input);
|
||||
expect(onChange).toHaveBeenCalledWith('20px');
|
||||
});
|
||||
|
||||
it('자유 px 0 입력 → onChange("")(여백 제거)', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CellPaddingControl catalog={catalog} t={t} onChange={onChange} />);
|
||||
const input = screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '0' } });
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(onChange).toHaveBeenCalledWith('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CellPaddingControl — 역해석(활성 표시)', () => {
|
||||
it('현재 8px → normal 단계 활성', () => {
|
||||
render(<CellPaddingControl catalog={catalog} paddingStyle="8px" t={t} onChange={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-padding-step-normal') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-cell-padding-step-narrow') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('빈 padding → none 단계 활성', () => {
|
||||
render(<CellPaddingControl catalog={catalog} paddingStyle="" t={t} onChange={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-padding-step-none') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
|
||||
it('프리셋에 없는 자유값(20px) → 자유 입력칸에 표시, 모든 단계 비활성', () => {
|
||||
render(<CellPaddingControl catalog={catalog} paddingStyle="20px" t={t} onChange={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement).value).toBe('20');
|
||||
expect((screen.getByTestId('g7le-cell-padding-step-normal') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
// 회귀: 다른 셀 선택 시 paddingStyle prop 이 바뀌면 자유 px
|
||||
// 입력칸이 그 셀 값으로 재동기화돼야 한다. 종전엔 useState 초기값이 마운트 1회뿐이라 셀을
|
||||
// 바꿔도 이전 셀의 자유 px(예 20)가 입력칸에 stale 하게 남았다.
|
||||
it('paddingStyle prop 변화(셀 전환) → 자유 입력칸 재동기화', () => {
|
||||
const { rerender } = render(<CellPaddingControl catalog={catalog} paddingStyle="20px" t={t} onChange={vi.fn()} />);
|
||||
expect((screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement).value).toBe('20');
|
||||
// 무스타일 셀(빈 padding)로 전환 → 자유 입력칸 비워짐.
|
||||
act(() => { rerender(<CellPaddingControl catalog={catalog} paddingStyle="" t={t} onChange={vi.fn()} />); });
|
||||
expect((screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement).value).toBe('');
|
||||
// 프리셋 값(8px) 셀로 전환 → 자유 입력칸도 비워짐(프리셋 활성).
|
||||
act(() => { rerender(<CellPaddingControl catalog={catalog} paddingStyle="8px" t={t} onChange={vi.fn()} />); });
|
||||
expect((screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement).value).toBe('');
|
||||
expect((screen.getByTestId('g7le-cell-padding-step-normal') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
// 다른 자유값(32px) 셀로 전환 → 자유 입력칸 32 로 갱신.
|
||||
act(() => { rerender(<CellPaddingControl catalog={catalog} paddingStyle="32px" t={t} onChange={vi.fn()} />); });
|
||||
expect((screen.getByTestId('g7le-cell-padding-free') as HTMLInputElement).value).toBe('32');
|
||||
});
|
||||
});
|
||||
+651
@@ -0,0 +1,651 @@
|
||||
/**
|
||||
* ChildrenListControl.test.tsx — `children` 노드 에디터 RTL
|
||||
*
|
||||
* 검증:
|
||||
* - node.children 항목 행 렌더(텍스트 입력 = I18nTextField 미리보기 / 구조 자식 라벨)
|
||||
* - 항목 추가(params.childComponent defaultNode) → onPatchNode({...node, children})
|
||||
* - 삭제/정렬 → children 배열 패치(PATCH_LAYOUT 생존: 노드 전체 교체)
|
||||
* - 항목 텍스트 평문 입력(I18nTextField) → createCustomKey → 항목 text 가 `$t:custom.*` 로 치환
|
||||
* - 기존 커스텀 키 입력 → updateCustomKeyValue(현재 로케일 값만, text 유지)
|
||||
* - 기존 커스텀 키 → 🌐 펼침 시 ko/en/ja 일괄 편집 폼(I18nTextField B) 노출
|
||||
* - childComponent 미선언 capability → 안내(misconfigured)
|
||||
*
|
||||
* 7-b: 항목 텍스트 편집은 속성 패널 propControl 과 **동일 공통 위젯**(I18nTextField)·동일
|
||||
* `$t:custom.*` SSoT(useCustomTranslation → useInlineEdit CRUD)로 일원화됐다. 따라서 본 스위트는
|
||||
* I18nTextField 미리보기 입력칸(`*-preview`)·🌐 토글(`*-toggle`)·펼침 폼(`*-expand`)을 대상으로 한다.
|
||||
*
|
||||
* @effects children_capability_declared_on_ul_ol_nav_form_li_both_templates, children_editor_registered_via_registercoreeditors_kind_agnostic, property_modal_dispatches_children_node_editor_in_props_tab_by_kind_not_name, add_item_appends_childcomponent_defaultnode_to_children, add_item_patches_whole_node_so_props_survive_patch_layout, remove_item_drops_only_that_child_from_children, move_up_down_swaps_adjacent_children_with_boundary_guard, canvas_drag_drop_and_list_editor_share_same_children_array, plain_item_blur_creates_custom_key_and_replaces_text_with_dollar_t_custom, existing_custom_key_blur_updates_current_locale_value_keeps_key, existing_custom_key_expand_shows_ko_en_ja_bulk_form, structural_child_without_text_shows_component_name_label_only, unchanged_blur_is_noop_no_crud_call, missing_child_component_capability_shows_misconfigured_notice, live_add_li_edit_text_reorder_save_persists_to_user_page
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
|
||||
|
||||
// useLayoutEditor — layoutName/locale/templateIdentifier 공급 모킹.
|
||||
// I18nTextField/useCustomTranslation 도 동일 컨텍스트를 읽으므로 한 곳에서 공급한다.
|
||||
vi.mock('../../LayoutEditorContext', () => ({
|
||||
useLayoutEditor: () => ({
|
||||
state: {
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
locale: 'ko',
|
||||
selectedRoute: { path: '/login', layoutName: 'login' },
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// 커스텀 키 CRUD — 네트워크 없이 결과 주입. useCustomTranslation(7-a SSoT)·I18nTextField·
|
||||
// ChildrenListControl 가 모두 이 모듈을 통해 키를 생성/갱신한다.
|
||||
const createCustomKey = vi.fn();
|
||||
const updateCustomKeyValue = vi.fn();
|
||||
const bustTranslationCache = vi.fn().mockResolvedValue(undefined);
|
||||
const findCustomKeyRow = vi.fn();
|
||||
vi.mock('../../hooks/useInlineEdit', () => ({
|
||||
createCustomKey: (...a: unknown[]) => createCustomKey(...a),
|
||||
updateCustomKeyValue: (...a: unknown[]) => updateCustomKeyValue(...a),
|
||||
bustTranslationCache: (...a: unknown[]) => bustTranslationCache(...a),
|
||||
findCustomKeyRow: (...a: unknown[]) => findCustomKeyRow(...a),
|
||||
// I18nTextField 펼침=통합 TranslationField. 그 동기화 구독이 읽는 이벤트명 export.
|
||||
EDITOR_TRANSLATIONS_REFRESHED_EVENT: 'g7le:editor-translations-refreshed',
|
||||
}));
|
||||
|
||||
// TranslationEngine — `$t:custom.*` 키를 현재 로케일 값으로 해석(시작값 표시).
|
||||
vi.mock('../../../TranslationEngine', () => ({
|
||||
TranslationEngine: {
|
||||
getInstance: () => ({
|
||||
translate: (key: string) => (key === 'custom.login.1' ? '기존 항목' : key),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
// LocaleSwitcher — 활성 로케일 목록/라벨(펼침 폼 ko/en/ja).
|
||||
vi.mock('../../components/LocaleSwitcher', () => ({
|
||||
readSupportedLocales: () => ['ko', 'en', 'ja'],
|
||||
localeDisplayLabel: (loc: string) => ({ ko: '한국어', en: 'English', ja: '日本語' }[loc] ?? loc),
|
||||
}));
|
||||
|
||||
// authToken — 펼침 폼 저장 헤더(네트워크 미발생 — fetch 미사용 경로만 테스트).
|
||||
vi.mock('../../utils/authToken', () => ({
|
||||
buildAuthHeaders: (h: Record<string, string>) => h,
|
||||
}));
|
||||
|
||||
import { ChildrenListControl } from '../../components/property-controls/ChildrenListControl';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
const t = (k: string, p?: Record<string, string | number>) =>
|
||||
p ? `${k}:${Object.values(p).join(',')}` : k;
|
||||
|
||||
const baseProps = {
|
||||
spec: {
|
||||
componentPalette: {
|
||||
entries: { Li: { defaultNode: { type: 'basic', name: 'Li', text: '' } } },
|
||||
},
|
||||
} as never,
|
||||
manifest: { components: { basic: [{ name: 'Li', type: 'basic', props: {} }] } } as never,
|
||||
t,
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
};
|
||||
|
||||
afterEach(() => cleanup());
|
||||
beforeEach(() => {
|
||||
createCustomKey.mockReset();
|
||||
updateCustomKeyValue.mockReset();
|
||||
bustTranslationCache.mockClear();
|
||||
findCustomKeyRow.mockReset();
|
||||
});
|
||||
|
||||
function ulNode(children: EditorNode[]): EditorNode {
|
||||
return { type: 'basic', name: 'Ul', children };
|
||||
}
|
||||
|
||||
/** 항목 idx 의 I18nTextField 미리보기 입력칸. */
|
||||
function previewInput(idx: number): HTMLInputElement {
|
||||
return screen.getByTestId(`g7le-children-i18n-${idx}-preview`) as HTMLInputElement;
|
||||
}
|
||||
|
||||
describe('ChildrenListControl — 구조 자식 편집', () => {
|
||||
it('children 텍스트 항목을 I18nTextField 미리보기 행으로 렌더한다', () => {
|
||||
const node = ulNode([
|
||||
{ type: 'basic', name: 'Li', text: '첫째' },
|
||||
{ type: 'basic', name: 'Li', text: '둘째' },
|
||||
]);
|
||||
render(
|
||||
<ChildrenListControl
|
||||
{...baseProps}
|
||||
node={node}
|
||||
params={{ childComponent: 'Li' }}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
// 행 래퍼 존재 + 위젯 미리보기 시작값 = 평문 그대로.
|
||||
expect(screen.getByTestId('g7le-children-text-0')).toBeInTheDocument();
|
||||
expect(previewInput(0).value).toBe('첫째');
|
||||
expect(previewInput(1).value).toBe('둘째');
|
||||
});
|
||||
|
||||
it('빈 children → 안내 표시', () => {
|
||||
render(
|
||||
<ChildrenListControl
|
||||
{...baseProps}
|
||||
node={ulNode([])}
|
||||
params={{ childComponent: 'Li' }}
|
||||
onPatchNode={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('"추가" → params.childComponent defaultNode 가 children 끝에 append (노드 전체 교체)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '첫째' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-add'));
|
||||
expect(onPatchNode).toHaveBeenCalledTimes(1);
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect(patched.name).toBe('Ul');
|
||||
const kids = patched.children as EditorNode[];
|
||||
expect(kids).toHaveLength(2);
|
||||
expect(kids[1].name).toBe('Li');
|
||||
expect(kids[1].text).toBe('layout_editor.list_editor.new_item');
|
||||
});
|
||||
|
||||
it('text 미선언 defaultNode(Input 등 void 컴포넌트) → 기본 텍스트 시드 금지 — React #137 회귀', () => {
|
||||
// Form→Input: Input defaultNode 는 text 를 선언하지 않는다(void element).
|
||||
// 시드를 강제하면 <input>새 항목</input> 렌더 → React error #137 크래시.
|
||||
const onPatchNode = vi.fn();
|
||||
const spec = {
|
||||
componentPalette: {
|
||||
entries: {
|
||||
Input: {
|
||||
defaultNode: { type: 'basic', name: 'Input', props: { type: 'text' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never;
|
||||
const formNode: EditorNode = { type: 'basic', name: 'Form', children: [] };
|
||||
render(
|
||||
<ChildrenListControl
|
||||
{...baseProps}
|
||||
spec={spec}
|
||||
node={formNode}
|
||||
params={{ childComponent: 'Input' }}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-add'));
|
||||
const kids = (onPatchNode.mock.calls[0][0] as EditorNode).children as EditorNode[];
|
||||
expect(kids).toHaveLength(1);
|
||||
expect(kids[0].name).toBe('Input');
|
||||
expect(kids[0].text).toBeUndefined();
|
||||
});
|
||||
|
||||
it('manifest 폴백(스펙 defaultNode 부재)도 text 미선언이면 시드 금지', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const spec = { componentPalette: { entries: {} } } as never;
|
||||
const manifest = {
|
||||
components: { basic: [{ name: 'Input', type: 'basic', props: {} }] },
|
||||
} as never;
|
||||
const formNode: EditorNode = { type: 'basic', name: 'Form', children: [] };
|
||||
render(
|
||||
<ChildrenListControl
|
||||
{...baseProps}
|
||||
spec={spec}
|
||||
manifest={manifest}
|
||||
node={formNode}
|
||||
params={{ childComponent: 'Input' }}
|
||||
onPatchNode={onPatchNode}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-add'));
|
||||
const kids = (onPatchNode.mock.calls[0][0] as EditorNode).children as EditorNode[];
|
||||
expect(kids[0].text).toBeUndefined();
|
||||
});
|
||||
|
||||
it('삭제 → 해당 항목 제거된 children 으로 패치', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const node = ulNode([
|
||||
{ type: 'basic', name: 'Li', text: '첫째' },
|
||||
{ type: 'basic', name: 'Li', text: '둘째' },
|
||||
]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-remove-0'));
|
||||
const kids = (onPatchNode.mock.calls[0][0] as EditorNode).children as EditorNode[];
|
||||
expect(kids).toHaveLength(1);
|
||||
expect(kids[0].text).toBe('둘째');
|
||||
});
|
||||
|
||||
it('아래로 이동 → 항목 순서 교환', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
const node = ulNode([
|
||||
{ type: 'basic', name: 'Li', text: 'A' },
|
||||
{ type: 'basic', name: 'Li', text: 'B' },
|
||||
]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-down-0'));
|
||||
const kids = (onPatchNode.mock.calls[0][0] as EditorNode).children as EditorNode[];
|
||||
expect(kids.map((k) => k.text)).toEqual(['B', 'A']);
|
||||
});
|
||||
|
||||
it('행은 2줄 구조다 (입력 윗줄 / 액션 버튼 아랫줄) — 겹침·가로 스크롤 차단', () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: 'A' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
const row = screen.getByTestId('g7le-children-row-0');
|
||||
expect(row.style.flexDirection).toBe('column');
|
||||
// 텍스트 입력과 액션 버튼은 서로 다른 줄(부모)에 있어 겹치지 않는다.
|
||||
const textLine = (screen.getByTestId('g7le-children-text-0').parentElement) as HTMLElement;
|
||||
const actionLine = (screen.getByTestId('g7le-children-up-0').parentElement) as HTMLElement;
|
||||
expect(actionLine).not.toBe(textLine);
|
||||
expect(actionLine.style.justifyContent).toBe('flex-end');
|
||||
expect(actionLine).toContainElement(screen.getByTestId('g7le-children-remove-0'));
|
||||
});
|
||||
|
||||
it('경계 가드 — 첫 행 위로/마지막 행 아래로 비활성', () => {
|
||||
const node = ulNode([
|
||||
{ type: 'basic', name: 'Li', text: 'A' },
|
||||
{ type: 'basic', name: 'Li', text: 'B' },
|
||||
]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-up-0')).toBeDisabled();
|
||||
expect(screen.getByTestId('g7le-children-down-1')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('텍스트 없는 구조 자식(자손도 텍스트 없음) → 컴포넌트명 라벨(정렬/삭제만)', () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Div', children: [{ type: 'basic', name: 'Img', props: { src: 'x' } }] }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-label-0').textContent).toBe('Div');
|
||||
expect(screen.queryByTestId('g7le-children-i18n-0-preview')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('자손에 텍스트가 있는 항목(Li > [Span("•"), Span("텍스트")]) → 의미 텍스트 자손을 편집 대상으로', () => {
|
||||
const node = ulNode([
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Li',
|
||||
children: [
|
||||
{ type: 'basic', name: 'Span', text: '•' },
|
||||
{ type: 'basic', name: 'Span', text: 'Respectful conversations' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
// 장식용 '•'(1글자)는 건너뛰고 의미 텍스트를 위젯 미리보기 시작값으로.
|
||||
expect(previewInput(0).value).toBe('Respectful conversations');
|
||||
expect(screen.queryByTestId('g7le-children-label-0')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('자손 텍스트 편집 평문 입력 → createCustomKey 후 **그 자손** text 만 `$t:custom.*` 로 치환', async () => {
|
||||
createCustomKey.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
resource: { id: 5, translation_key: 'custom.login.3', values: { ko: '새 규칙' }, lock_version: 0 },
|
||||
});
|
||||
const onPatchNode = vi.fn();
|
||||
const node = ulNode([
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Li',
|
||||
children: [
|
||||
{ type: 'basic', name: 'Span', text: '•' },
|
||||
{ type: 'basic', name: 'Span', text: 'Old rule' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
const input = previewInput(0);
|
||||
fireEvent.change(input, { target: { value: '새 규칙' } });
|
||||
fireEvent.blur(input);
|
||||
await waitFor(() => expect(createCustomKey).toHaveBeenCalled());
|
||||
await waitFor(() => expect(onPatchNode).toHaveBeenCalled());
|
||||
const patched = onPatchNode.mock.calls[onPatchNode.mock.calls.length - 1][0] as EditorNode;
|
||||
const li = (patched.children as EditorNode[])[0];
|
||||
const spans = li.children as EditorNode[];
|
||||
// 불릿 Span 은 그대로, 텍스트 Span 만 키 토큰으로 치환.
|
||||
expect(spans[0].text).toBe('•');
|
||||
expect(spans[1].text).toBe('$t:custom.login.3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChildrenListControl — 항목 다국어(I18nTextField SSoT)', () => {
|
||||
it('평문 항목 입력(변경) → createCustomKey 후 항목 text 를 `$t:custom.*` 로 치환', async () => {
|
||||
createCustomKey.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
resource: { id: 7, translation_key: 'custom.login.9', values: { ko: '바뀐값' }, lock_version: 0 },
|
||||
});
|
||||
const onPatchNode = vi.fn();
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '원래값' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
const input = previewInput(0);
|
||||
fireEvent.change(input, { target: { value: '바뀐값' } });
|
||||
fireEvent.blur(input);
|
||||
// useCustomTranslation 은 layoutName('login') 을 컨텍스트에서 자체 해석.
|
||||
await waitFor(() => expect(createCustomKey).toHaveBeenCalledWith('sirsoft-basic', 'login', 'ko', '바뀐값'));
|
||||
await waitFor(() => expect(onPatchNode).toHaveBeenCalled());
|
||||
const lastCall = onPatchNode.mock.calls[onPatchNode.mock.calls.length - 1][0] as EditorNode;
|
||||
const kids = lastCall.children as EditorNode[];
|
||||
expect(kids[0].text).toBe('$t:custom.login.9');
|
||||
});
|
||||
|
||||
it('기존 커스텀 키 항목 입력(변경) → updateCustomKeyValue(현재 로케일), text 키 유지', async () => {
|
||||
updateCustomKeyValue.mockResolvedValue({ kind: 'ok' });
|
||||
const onPatchNode = vi.fn();
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '$t:custom.login.1' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
const input = previewInput(0);
|
||||
// 시작값 = TranslationEngine 해석값 '기존 항목'(raw 키 미노출).
|
||||
expect(input.value).toBe('기존 항목');
|
||||
fireEvent.change(input, { target: { value: '수정값' } });
|
||||
fireEvent.blur(input);
|
||||
await waitFor(() =>
|
||||
expect(updateCustomKeyValue).toHaveBeenCalledWith('sirsoft-basic', 'custom.login.1', 'ko', '수정값'),
|
||||
);
|
||||
// 커스텀 키는 그대로 — createCustomKey 미호출, 노드 text(키) 불변(onPatchNode 가 와도 동일 토큰).
|
||||
expect(createCustomKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('기존 커스텀 키 → 🌐 펼침 시 ko/en/ja 일괄 편집 폼 노출(I18nTextField B)', async () => {
|
||||
findCustomKeyRow.mockResolvedValue({
|
||||
id: 1,
|
||||
lock_version: 0,
|
||||
values: { ko: '기존 항목', en: 'Existing', ja: '' },
|
||||
});
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '$t:custom.login.1' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-i18n-0-toggle'));
|
||||
// 펼침=통합 TranslationField. 펼침부 testid 는 `g7le-translation-*`(고정).
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-translation-field')).toBeInTheDocument());
|
||||
expect(screen.getByTestId('g7le-translation-input-ko')).toHaveValue('기존 항목');
|
||||
expect(screen.getByTestId('g7le-translation-input-en')).toHaveValue('Existing');
|
||||
// ja 미번역 → 마크 표시.
|
||||
expect(screen.getByTestId('g7le-translation-missing-ja')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('변경 없는 blur → CRUD 미호출(no-op)', async () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '그대로' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
const input = previewInput(0);
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: '그대로' } });
|
||||
fireEvent.blur(input);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(createCustomKey).not.toHaveBeenCalled();
|
||||
expect(updateCustomKeyValue).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('바인딩식 항목 → 읽기전용 디그레이드(편집 차단)', () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '{{post.title}}' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
// I18nTextField C — 바인딩 배지(미리보기 입력칸 미노출).
|
||||
expect(screen.getByTestId('g7le-children-i18n-0-binding')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-children-i18n-0-preview')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChildrenListControl — 잘못된 capability', () => {
|
||||
it('childComponent 미선언 → 안내(misconfigured)', () => {
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={ulNode([])} params={{}} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-editor-misconfigured')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChildrenListControl — 스펙 주도 childTemplate/itemFields', () => {
|
||||
// Form 의 "라벨+입력칸 묶음" 행 — 양 템플릿 capability 가 선언하는 형태.
|
||||
const bundleParams = {
|
||||
childComponent: 'Input',
|
||||
childLabel: '입력 항목',
|
||||
childTemplate: {
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Label',
|
||||
children: [{ type: 'basic', name: 'Span', text: '' }],
|
||||
},
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Input',
|
||||
props: { type: 'text', placeholder: '$t:layout_editor.palette.input.default_placeholder' },
|
||||
},
|
||||
],
|
||||
},
|
||||
itemFields: [
|
||||
{ kind: 'text', label: '라벨' },
|
||||
{ kind: 'prop', prop: 'placeholder', label: '안내 문구' },
|
||||
],
|
||||
};
|
||||
|
||||
function formNode(children: EditorNode[]): EditorNode {
|
||||
return { type: 'basic', name: 'Form', children };
|
||||
}
|
||||
|
||||
it('"추가" → childTemplate 골격(라벨+입력칸 묶음)이 append, 라벨 Span 에만 기본 텍스트 시드', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={formNode([])} params={bundleParams} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-children-add'));
|
||||
const kids = (onPatchNode.mock.calls[0][0] as EditorNode).children as EditorNode[];
|
||||
expect(kids).toHaveLength(1);
|
||||
const bundle = kids[0]!;
|
||||
expect(bundle.name).toBe('Div');
|
||||
const label = (bundle.children as EditorNode[])[0]!;
|
||||
const input = (bundle.children as EditorNode[])[1]!;
|
||||
// 라벨 Span(text:"") → "새 항목" 시드. Input 은 text 미선언 그대로(React #137 차단).
|
||||
expect((label.children as EditorNode[])[0]!.text).toBe('layout_editor.list_editor.new_item');
|
||||
expect(input.text).toBeUndefined();
|
||||
expect((input.props as Record<string, unknown>).placeholder).toBe(
|
||||
'$t:layout_editor.palette.input.default_placeholder',
|
||||
);
|
||||
});
|
||||
|
||||
it('추가 버튼 명칭 = childLabel (childComponent 폴백 아님)', () => {
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={formNode([])} params={bundleParams} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-add').textContent).toBe(
|
||||
'layout_editor.list_editor.add_child:입력 항목',
|
||||
);
|
||||
});
|
||||
|
||||
it('itemFields 선언 항목 행 → 라벨 + 안내 문구 두 필드(캡션 포함) 렌더', () => {
|
||||
const item: EditorNode = {
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
children: [
|
||||
{ type: 'basic', name: 'Label', children: [{ type: 'basic', name: 'Span', text: '이메일' }] },
|
||||
{ type: 'basic', name: 'Input', props: { placeholder: '이메일을 입력하세요' } },
|
||||
],
|
||||
};
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={formNode([item])} params={bundleParams} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
// 라벨 필드(텍스트 자손) + 캡션.
|
||||
expect(screen.getByTestId('g7le-children-i18n-0-preview')).toHaveValue('이메일');
|
||||
expect(screen.getByTestId('g7le-children-caption-text-0').textContent).toBe('라벨');
|
||||
// 안내 문구 필드(prop 자손) + 캡션.
|
||||
expect(screen.getByTestId('g7le-children-prop-placeholder-0-preview')).toHaveValue('이메일을 입력하세요');
|
||||
expect(screen.getByTestId('g7le-children-caption-prop-placeholder-0').textContent).toBe('안내 문구');
|
||||
});
|
||||
|
||||
it('prop 필드 평문 입력 → createCustomKey 후 그 자손의 props[prop] 만 키 토큰으로 치환', async () => {
|
||||
createCustomKey.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
resource: { id: 9, translation_key: 'custom.login.11', values: { ko: '새 안내' }, lock_version: 0 },
|
||||
});
|
||||
const onPatchNode = vi.fn();
|
||||
const item: EditorNode = {
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
children: [
|
||||
{ type: 'basic', name: 'Label', children: [{ type: 'basic', name: 'Span', text: '이메일' }] },
|
||||
{ type: 'basic', name: 'Input', props: { type: 'email', placeholder: '옛 안내' } },
|
||||
],
|
||||
};
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={formNode([item])} params={bundleParams} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
const input = screen.getByTestId('g7le-children-prop-placeholder-0-preview') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '새 안내' } });
|
||||
fireEvent.blur(input);
|
||||
await waitFor(() => expect(createCustomKey).toHaveBeenCalled());
|
||||
await waitFor(() => expect(onPatchNode).toHaveBeenCalled());
|
||||
const patched = onPatchNode.mock.calls[onPatchNode.mock.calls.length - 1][0] as EditorNode;
|
||||
const row0 = (patched.children as EditorNode[])[0]!;
|
||||
const labelSpan = ((row0.children as EditorNode[])[0]!.children as EditorNode[])[0]!;
|
||||
const inputNode = (row0.children as EditorNode[])[1]!;
|
||||
// 라벨 텍스트는 불변, placeholder 만 키 토큰.
|
||||
expect(labelSpan.text).toBe('이메일');
|
||||
expect((inputNode.props as Record<string, unknown>).placeholder).toBe('$t:custom.login.11');
|
||||
expect((inputNode.props as Record<string, unknown>).type).toBe('email');
|
||||
});
|
||||
|
||||
it('placeholder 없는 항목(체크박스 행 등) → 라벨 필드만 렌더(안내 문구 필드 미노출)', () => {
|
||||
const item: EditorNode = {
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
children: [{ type: 'basic', name: 'Label', children: [{ type: 'basic', name: 'Span', text: '약관 동의' }] }],
|
||||
};
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={formNode([item])} params={bundleParams} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-i18n-0-preview')).toHaveValue('약관 동의');
|
||||
expect(screen.queryByTestId('g7le-children-prop-placeholder-0-preview')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('편집 가능 필드가 전무한 구조 자식(text·placeholder 모두 없음) → 컴포넌트명 라벨만', () => {
|
||||
const item: EditorNode = { type: 'basic', name: 'Input', props: { type: 'checkbox' } };
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={formNode([item])} params={bundleParams} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-label-0').textContent).toBe('Input');
|
||||
});
|
||||
|
||||
it('itemFields 미선언 → 종전 동작(텍스트 1필드, 캡션 없음) 그대로', () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '첫째' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-i18n-0-preview')).toHaveValue('첫째');
|
||||
expect(screen.queryByTestId('g7le-children-caption-text-0')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// (목록 칸 결선 회귀) — ChildrenListControl 은 NodeEditorProps.candidates 를 항목
|
||||
// 텍스트의 I18nTextField 로 흘려야 `+데이터` 칩 삽입(키화) 입구가 뜬다. ArrayCellTreeEditor 가
|
||||
// 본 컨트롤에 {...props} 통째 위임하므로 셀 트리 항목까지 동일 경로로 후보가 닿는다.
|
||||
describe('ChildrenListControl — 항목 후보 풀 전달', () => {
|
||||
const scalarCandidate = {
|
||||
expression: '{{user.name}}', source: 'data_source' as const, sourceId: 'user',
|
||||
path: 'name', shape: 'scalar' as const, preview: '홍길동',
|
||||
};
|
||||
|
||||
it('candidates 전달 시 평문 항목 텍스트 칸에 +데이터 버튼 노출', () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '첫째' }]);
|
||||
render(
|
||||
<ChildrenListControl
|
||||
{...baseProps}
|
||||
node={node}
|
||||
params={{ childComponent: 'Li' }}
|
||||
onPatchNode={vi.fn()}
|
||||
candidates={[scalarCandidate]}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-children-i18n-0-plus-data-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('candidates 미전달 시 +데이터 버튼 미노출 (디그레이드)', () => {
|
||||
const node = ulNode([{ type: 'basic', name: 'Li', text: '첫째' }]);
|
||||
render(
|
||||
<ChildrenListControl {...baseProps} node={node} params={{ childComponent: 'Li' }} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-children-i18n-0-plus-data-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
/*
|
||||
* 시나리오 cross-product 커버리지 마킹 — test-scenario-coverage 룰용.
|
||||
* 본 단위 스위트(ChildrenListControl)가 control 로직을, coverage 스위트가 컴포넌트별 capability
|
||||
* 선언을, children-list-editor.spec.ts(E2E)가 라이브 영속을 잠근다. 아래 마킹은 axes cross
|
||||
* product 와 effects 를 그 테스트군에 귀속시킨다.
|
||||
*/
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=add, template=sirsoft-basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=remove, template=sirsoft-basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=remove, template=sirsoft-admin_basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=move_up, template=sirsoft-basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=move_up, template=sirsoft-admin_basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=move_down, template=sirsoft-basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=move_down, template=sirsoft-admin_basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Ul, item_text_kind=plain_new, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Ul, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Ul, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Ol, item_text_kind=plain_new, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario component=Ol, item_text_kind=plain_new, operation=remove, template=sirsoft-admin_basic
|
||||
// @scenario component=Ol, item_text_kind=plain_new, operation=move_up, template=sirsoft-admin_basic
|
||||
// @scenario component=Ol, item_text_kind=plain_new, operation=move_down, template=sirsoft-admin_basic
|
||||
// @scenario component=Ol, item_text_kind=plain_new, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Ol, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=add, template=sirsoft-basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=remove, template=sirsoft-basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=remove, template=sirsoft-admin_basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=move_up, template=sirsoft-basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=move_up, template=sirsoft-admin_basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=move_down, template=sirsoft-basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=move_down, template=sirsoft-admin_basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Nav, item_text_kind=plain_new, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Nav, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Nav, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=add, template=sirsoft-basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=remove, template=sirsoft-basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=remove, template=sirsoft-admin_basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=move_up, template=sirsoft-basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=move_up, template=sirsoft-admin_basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=move_down, template=sirsoft-basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=move_down, template=sirsoft-admin_basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Form, item_text_kind=plain_new, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Form, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Form, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=add, template=sirsoft-basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=add, template=sirsoft-admin_basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=remove, template=sirsoft-basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=remove, template=sirsoft-admin_basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=move_up, template=sirsoft-basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=move_up, template=sirsoft-admin_basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=move_down, template=sirsoft-basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=move_down, template=sirsoft-admin_basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Li, item_text_kind=plain_new, operation=edit_text, template=sirsoft-admin_basic
|
||||
// @scenario component=Li, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-basic
|
||||
// @scenario component=Li, item_text_kind=existing_custom_key, operation=edit_text, template=sirsoft-admin_basic
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
// e2e:allow 레이아웃 편집기 캔버스 오버레이/속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(T1~T8) 실측 + 단위/레이아웃 렌더링 테스트로 검증
|
||||
/**
|
||||
* ColorSchemeTabs.test.tsx — 셀 색 라이트/다크 단일 공용 탭
|
||||
*
|
||||
* 검증: 라이트/다크 단일 탭 렌더 + i18n, 클릭 시 onChange, 활성 표시, 다크 안내.
|
||||
* 탭은 테두리색·배경색 컨트롤에 각각 두지 않고 색상 섹션 상단 단일 1개.
|
||||
*
|
||||
* @scenario cell_color_single_scheme_tab
|
||||
* @effects cell_color_scheme_tab_shared_across_border_and_fill
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { ColorSchemeTabs } from '../../components/property-controls/ColorSchemeTabs';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('ColorSchemeTabs', () => {
|
||||
it('라이트/다크 단일 탭 렌더 + i18n', () => {
|
||||
render(<ColorSchemeTabs colorScheme="light" onChange={vi.fn()} t={t} />);
|
||||
expect(screen.getByTestId('g7le-color-scheme-tabs')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-color-scheme-light').textContent).toBe('layout_editor.property_modal.scope.scheme_light');
|
||||
expect(screen.getByTestId('g7le-color-scheme-dark').textContent).toBe('layout_editor.property_modal.scope.scheme_dark');
|
||||
});
|
||||
|
||||
it('라이트 활성 표시(다크 비활성)', () => {
|
||||
render(<ColorSchemeTabs colorScheme="light" onChange={vi.fn()} t={t} />);
|
||||
expect((screen.getByTestId('g7le-color-scheme-light') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('true');
|
||||
expect((screen.getByTestId('g7le-color-scheme-dark') as HTMLButtonElement).getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('다크 탭 클릭 → onChange("dark")', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ColorSchemeTabs colorScheme="light" onChange={onChange} t={t} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-color-scheme-dark'));
|
||||
expect(onChange).toHaveBeenCalledWith('dark');
|
||||
});
|
||||
|
||||
it('라이트 탭 클릭 → onChange("light")', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ColorSchemeTabs colorScheme="dark" onChange={onChange} t={t} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-color-scheme-light'));
|
||||
expect(onChange).toHaveBeenCalledWith('light');
|
||||
});
|
||||
|
||||
it('다크 스킴이면 안내 노출, 라이트면 미노출', () => {
|
||||
const { rerender } = render(<ColorSchemeTabs colorScheme="dark" onChange={vi.fn()} t={t} />);
|
||||
expect(screen.getByTestId('g7le-color-scheme-dark-hint')).toBeTruthy();
|
||||
rerender(<ColorSchemeTabs colorScheme="light" onChange={vi.fn()} t={t} />);
|
||||
expect(screen.queryByTestId('g7le-color-scheme-dark-hint')).toBeNull();
|
||||
});
|
||||
});
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* ComponentContextMenu 컴포넌트 테스트
|
||||
*
|
||||
* 메뉴 항목은 정확히 3가지: 속성 설정 / 컴포넌트 복사 / 삭제.
|
||||
* 목록·표·이미지 삽입 등 다른 항목은 메뉴에 없어야 함 (회귀 가드).
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { ComponentContextMenu } from '../../components/ComponentContextMenu';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function withTranslation(node: React.ReactElement): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
{node}
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ComponentContextMenu — 항목 구성', () => {
|
||||
it('open=true 이면 정확히 3 항목만 렌더', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const menu = screen.getByTestId('g7le-context-menu');
|
||||
const items = menu.querySelectorAll('[role="menuitem"]');
|
||||
expect(items.length).toBe(3);
|
||||
expect(screen.getByTestId('g7le-context-menu-edit-props')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-context-menu-duplicate')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-context-menu-delete')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('open=false 또는 anchor=null 이면 렌더 자체를 안 함', () => {
|
||||
const { rerender, container } = render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={null}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(container.querySelector('[data-testid="g7le-context-menu"]')).toBeNull();
|
||||
|
||||
rerender(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={false}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(container.querySelector('[data-testid="g7le-context-menu"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentContextMenu — 디바이스 분리 항목', () => {
|
||||
it('onSeparateBranch 제공 시 분리 생성 항목 추가(삭제 앞)', () => {
|
||||
const onSeparateBranch = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onSeparateBranch={onSeparateBranch}
|
||||
separateBranchLabel="이 영역을 모바일 전용으로 분리"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const menu = screen.getByTestId('g7le-context-menu');
|
||||
expect(menu.querySelectorAll('[role="menuitem"]').length).toBe(4);
|
||||
const sep = screen.getByTestId('g7le-context-menu-separate-branch');
|
||||
expect(sep.textContent).toContain('모바일');
|
||||
// 삭제 항목이 마지막(분리 항목 뒤)
|
||||
const items = Array.from(menu.querySelectorAll('[role="menuitem"]'));
|
||||
expect(items[items.length - 1]?.getAttribute('data-testid')).toBe('g7le-context-menu-delete');
|
||||
fireEvent.click(sep);
|
||||
expect(onSeparateBranch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onMergeBranch 제공 시 분리 해제 항목 추가', () => {
|
||||
const onMergeBranch = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onMergeBranch={onMergeBranch}
|
||||
mergeBranchLabel="모바일 전용 분리 해제"
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-context-menu-merge-branch')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-context-menu-separate-branch')).toBeNull();
|
||||
fireEvent.click(screen.getByTestId('g7le-context-menu-merge-branch'));
|
||||
expect(onMergeBranch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('둘 다 미제공이면 분리 항목 없음(기본 3항목 — 회귀 가드)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-context-menu-separate-branch')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-context-menu-merge-branch')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentContextMenu — 클릭 콜백', () => {
|
||||
it('각 항목 클릭 → 콜백 + onClose 동시 호출', () => {
|
||||
const onClose = vi.fn();
|
||||
const onEditProps = vi.fn();
|
||||
const onDuplicate = vi.fn();
|
||||
const onDelete = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={onClose}
|
||||
onEditProps={onEditProps}
|
||||
onDuplicate={onDuplicate}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-context-menu-edit-props'));
|
||||
expect(onEditProps).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-context-menu-duplicate'));
|
||||
expect(onDuplicate).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-context-menu-delete'));
|
||||
expect(onDelete).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentContextMenu — 금지 항목 부재 (회귀 가드)', () => {
|
||||
it('목록/표/이미지 삽입 등 별도 항목이 메뉴에 없음', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// 미지정 testid 패턴이 발생하지 않아야 함
|
||||
expect(screen.queryByTestId('g7le-context-menu-insert-list')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-context-menu-insert-table')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-context-menu-insert-image')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentContextMenu — pointer-events 회귀 가드 (engine-v1.50.0)', () => {
|
||||
/**
|
||||
* 증상: 메뉴 컨테이너/항목이 EditorCanvasOverlay/ElementOverlay 의
|
||||
* `pointer-events: none` 상속으로 hit-test 에서 투명해져 마우스가 통과 → 클릭/hover 미반응.
|
||||
* 해결: 컨테이너와 각 항목 button 에 inline `pointer-events: auto` 명시.
|
||||
*/
|
||||
it('메뉴 컨테이너 inline style 에 pointer-events: auto 가 명시되어 있음', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const menu = screen.getByTestId('g7le-context-menu') as HTMLElement;
|
||||
expect(menu.style.pointerEvents).toBe('auto');
|
||||
});
|
||||
|
||||
it('각 메뉴 항목 button inline style 에 pointer-events: auto 가 명시되어 있음', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
for (const tid of [
|
||||
'g7le-context-menu-edit-props',
|
||||
'g7le-context-menu-duplicate',
|
||||
'g7le-context-menu-delete',
|
||||
]) {
|
||||
const btn = screen.getByTestId(tid) as HTMLElement;
|
||||
expect(btn.style.pointerEvents).toBe('auto');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentContextMenu — hover 강조 (engine-v1.50.0)', () => {
|
||||
/**
|
||||
* 증상: inline style 에는 :hover 의사클래스를 표현할 수 없어 마우스를 올려도
|
||||
* 시각 강조가 없음.
|
||||
* 해결: 내부 state `hoverIndex` + onMouseEnter/Leave/Focus 로 background/color 토글.
|
||||
*/
|
||||
it('onMouseEnter 시 background 가 transparent 에서 색상으로 변함', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const item = screen.getByTestId('g7le-context-menu-duplicate') as HTMLElement;
|
||||
expect(item.style.background).toBe('transparent');
|
||||
fireEvent.mouseEnter(item);
|
||||
expect(item.style.background).not.toBe('transparent');
|
||||
});
|
||||
|
||||
it('hoverIndex 가 상호 배타 — 한 번에 한 항목만 강조', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const edit = screen.getByTestId('g7le-context-menu-edit-props') as HTMLElement;
|
||||
const dup = screen.getByTestId('g7le-context-menu-duplicate') as HTMLElement;
|
||||
fireEvent.mouseEnter(dup);
|
||||
expect(dup.style.background).not.toBe('transparent');
|
||||
expect(edit.style.background).toBe('transparent');
|
||||
fireEvent.mouseEnter(edit);
|
||||
expect(edit.style.background).not.toBe('transparent');
|
||||
expect(dup.style.background).toBe('transparent');
|
||||
});
|
||||
|
||||
it('삭제 항목은 hover 시 별도 색상 계열 사용 (danger)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentContextMenu
|
||||
anchor={{ left: 0, top: 0 }}
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const del = screen.getByTestId('g7le-context-menu-delete') as HTMLElement;
|
||||
fireEvent.mouseEnter(del);
|
||||
// danger 계열 색상 — 본 테스트는 hover bg 가 일반 항목과 달라야 함을 검증
|
||||
const dup = screen.getByTestId('g7le-context-menu-duplicate') as HTMLElement;
|
||||
fireEvent.mouseEnter(dup);
|
||||
fireEvent.mouseEnter(del); // 다시 delete 로 — 색상 검증
|
||||
expect(del.style.background).not.toBe(dup.style.background);
|
||||
});
|
||||
});
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
/**
|
||||
* ComponentPalette 컴포넌트 테스트
|
||||
*
|
||||
* 검증 매트릭스:
|
||||
* - 디자인/DB 그룹 렌더
|
||||
* - accepts 필터 — 부모 컨테이너의 accepts 외 컴포넌트 비표시
|
||||
* - spec 미제공 → spec_missing 안내
|
||||
* - 검색 — name/description 부분 일치 필터
|
||||
* - 클릭 → onInsert 호출 (parentPath / index / 신규 노드 골격)
|
||||
* - defaultNode — components.json props.default 값으로 골격 생성, id 미부여
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import {
|
||||
ComponentPalette,
|
||||
buildDefaultNode,
|
||||
type ComponentManifest,
|
||||
} from '../../components/ComponentPalette';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import type { NestingSpec } from '../../spec/specTypes';
|
||||
|
||||
function withTranslation(node: React.ReactElement): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
{node}
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const manifest: ComponentManifest = {
|
||||
templateId: 'test',
|
||||
components: {
|
||||
basic: [
|
||||
{
|
||||
name: 'Div',
|
||||
type: 'basic',
|
||||
description: '컨테이너',
|
||||
props: { className: { type: 'string', default: 'p-4' } },
|
||||
},
|
||||
{
|
||||
name: 'Button',
|
||||
type: 'basic',
|
||||
description: '버튼',
|
||||
props: { variant: { type: 'string', default: 'primary' } },
|
||||
},
|
||||
{
|
||||
name: 'Img',
|
||||
type: 'basic',
|
||||
description: '이미지',
|
||||
},
|
||||
],
|
||||
composite: [
|
||||
{
|
||||
name: 'DataGrid',
|
||||
type: 'composite',
|
||||
description: '데이터 그리드',
|
||||
bindingType: 'value',
|
||||
},
|
||||
{
|
||||
name: 'Pagination',
|
||||
type: 'composite',
|
||||
description: '페이지네이션',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const nesting: NestingSpec = {
|
||||
draggable: ['Div', 'Button', 'Img', 'DataGrid', 'Pagination'],
|
||||
containers: {
|
||||
Div: { accepts: ['Div', 'Button', 'Img', 'DataGrid', 'Pagination'] },
|
||||
Img: { accepts: [] }, // leaf
|
||||
},
|
||||
};
|
||||
|
||||
describe('ComponentPalette — 폴백 카테고리 (componentPalette 미제공)', () => {
|
||||
it('전체 카테고리 활성 시 basic / composite 모든 컴포넌트 노출', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// 'all' 이 초기 active — 컨테이너 testid 는 active 카테고리 키 사용
|
||||
expect(screen.getByTestId('g7le-palette-group-all')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-Div')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-Button')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-Img')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-DataGrid')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-Pagination')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('사이드바에 폴백 카테고리(all/basic/composite) 노출 + 각 카테고리 카운트', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-category-all')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-category-basic')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-category-composite')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('카드에 type 뱃지 표시 (basic/composite)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-item-Button-badge').textContent).toBe('basic');
|
||||
expect(screen.getByTestId('g7le-palette-item-DataGrid-badge').textContent).toBe('composite');
|
||||
});
|
||||
|
||||
// 결함 8 — 실제 렌더 컴포넌트 태그 배지 (React 컴포넌트명 형식)
|
||||
it('카드에 React 컴포넌트명 형식의 태그 배지 표시 (<Div>, <Button>)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-item-Div-tag').textContent).toBe('<Div>');
|
||||
expect(screen.getByTestId('g7le-palette-item-Button-tag').textContent).toBe('<Button>');
|
||||
expect(screen.getByTestId('g7le-palette-item-DataGrid-tag').textContent).toBe('<DataGrid>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentPalette — componentPalette.groups 소비 ', () => {
|
||||
it('스펙 그룹 정의가 있으면 그 라벨/매핑대로 사이드바 + 카드 노출', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
componentPalette={{
|
||||
groups: [
|
||||
{
|
||||
label: '$t:layout_editor.palette.group.design',
|
||||
kind: 'design',
|
||||
components: ['Div', 'Button', 'Img'],
|
||||
},
|
||||
{
|
||||
label: '$t:layout_editor.palette.group.db',
|
||||
kind: 'data',
|
||||
components: ['DataGrid', 'Pagination'],
|
||||
},
|
||||
],
|
||||
}}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-category-design')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-category-data')).toBeTruthy();
|
||||
// 폴백 카테고리(basic/composite) 는 노출되지 않아야 함 — 스펙 정의가 덮어씀
|
||||
expect(screen.queryByTestId('g7le-palette-category-basic')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-palette-category-composite')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentPalette — accepts 필터', () => {
|
||||
it('targetContainerName=Img → accepts=[] 이므로 모든 항목 숨김 + empty 안내', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={[0]}
|
||||
targetContainerName="Img"
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-empty')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-palette-item-Div')).toBeNull();
|
||||
});
|
||||
|
||||
it('targetContainerName=Div → Div/Button/Img/DataGrid/Pagination 모두 허용', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={[0]}
|
||||
targetContainerName="Div"
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-item-Div')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-Button')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-palette-item-DataGrid')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentPalette — spec 미제공', () => {
|
||||
it('nesting=null 이면 spec_missing 안내 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={null}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-palette-spec-missing')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentPalette — 검색', () => {
|
||||
it('검색어 입력 시 name/description 부분 일치만 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const search = screen.getByTestId('g7le-palette-search') as HTMLInputElement;
|
||||
fireEvent.change(search, { target: { value: 'Btn' } });
|
||||
// 'Button' 의 name 에 'Btn' 이 포함되지 않으므로 0건, 'Button' 의 description '버튼' 검색
|
||||
fireEvent.change(search, { target: { value: '버튼' } });
|
||||
expect(screen.getByTestId('g7le-palette-item-Button')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-palette-item-Div')).toBeNull();
|
||||
});
|
||||
|
||||
it('표시 라벨(다국어 해석)로 검색 — entrySpec.label 해석값 매칭', () => {
|
||||
// 회귀 배경: 카드에 "박스"/"인라인 텍스트" 등 다국어 라벨이 보이는데
|
||||
// 검색은 name(Div)/description 만 매칭해 표시 명칭으로는 안 잡혔다. 이제 카드에
|
||||
// 보이는 해석 라벨로도 검색된다.
|
||||
const engine = new TranslationEngine();
|
||||
(engine as any).translations.set('tpl-x:ko', {
|
||||
layout_editor: {
|
||||
palette: {
|
||||
entry: {
|
||||
div: { label: '박스' },
|
||||
button: { label: '버튼요소' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'admin-host', locale: 'ko' }}
|
||||
>
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
componentPalette={{
|
||||
entries: {
|
||||
Div: { label: '$t:layout_editor.palette.entry.div.label' },
|
||||
Button: { label: '$t:layout_editor.palette.entry.button.label' },
|
||||
},
|
||||
}}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
editorTemplateId="tpl-x"
|
||||
editorLocale="ko"
|
||||
/>
|
||||
</TranslationProvider>
|
||||
);
|
||||
const search = screen.getByTestId('g7le-palette-search') as HTMLInputElement;
|
||||
// 표시 라벨 "박스" 로 검색 → Div 만 (name 은 'Div' 라 종전엔 미매칭)
|
||||
fireEvent.change(search, { target: { value: '박스' } });
|
||||
expect(screen.getByTestId('g7le-palette-item-Div')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-palette-item-Button')).toBeNull();
|
||||
});
|
||||
|
||||
it('영문 컴포넌트명 검색은 그대로 동작 (회귀 가드)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const search = screen.getByTestId('g7le-palette-search') as HTMLInputElement;
|
||||
fireEvent.change(search, { target: { value: 'Pagination' } });
|
||||
expect(screen.getByTestId('g7le-palette-item-Pagination')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-palette-item-Div')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentPalette — 클릭 → onInsert (defaultNode 정식 발효)', () => {
|
||||
it('entry 의 defaultNode 가 정의되면 그 골격을 그대로 사용 (코어 폴백 우회)', () => {
|
||||
const onInsert = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
componentPalette={{
|
||||
entries: {
|
||||
Div: {
|
||||
label: '$t:layout_editor.palette.div.label',
|
||||
requiresDefaultNode: true,
|
||||
defaultNode: {
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'min-h-[40px] p-2 border border-dashed border-slate-300' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
targetParentPath={[2]}
|
||||
targetContainerName="Div"
|
||||
insertionIndex={3}
|
||||
onInsert={onInsert}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-palette-item-Div'));
|
||||
expect(onInsert).toHaveBeenCalledTimes(1);
|
||||
const [node, parentPath, index] = onInsert.mock.calls[0];
|
||||
expect(node.name).toBe('Div');
|
||||
expect(node.id).toBeUndefined();
|
||||
// 템플릿 defaultNode 가 그대로 적용 — 코어가 minHeight/minWidth 부여하지 않음
|
||||
expect(node.props?.className).toBe('min-h-[40px] p-2 border border-dashed border-slate-300');
|
||||
expect(node.props?.style).toBeUndefined();
|
||||
expect(parentPath).toEqual([2]);
|
||||
expect(index).toBe(3);
|
||||
});
|
||||
|
||||
it('entry 가 없으면 components.json props.default 폴백 — 코어는 시각 단서 부여하지 않음', () => {
|
||||
const onInsert = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
targetParentPath={[2]}
|
||||
targetContainerName="Div"
|
||||
insertionIndex={3}
|
||||
onInsert={onInsert}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-palette-item-Div'));
|
||||
expect(onInsert).toHaveBeenCalledTimes(1);
|
||||
const [node] = onInsert.mock.calls[0];
|
||||
expect(node.props?.className).toBe('p-4');
|
||||
// 코어는 더 이상 minHeight/minWidth 임시 강제하지 않음
|
||||
expect(node.props?.style).toBeUndefined();
|
||||
});
|
||||
|
||||
it('requiresDefaultNode: true 인데 defaultNode 미정의 → 클릭 차단(onInsert 미호출)', () => {
|
||||
const onInsert = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
componentPalette={{
|
||||
entries: {
|
||||
Button: {
|
||||
label: '$t:layout_editor.palette.button.label',
|
||||
requiresDefaultNode: true,
|
||||
// defaultNode 의도적으로 누락
|
||||
},
|
||||
},
|
||||
}}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={onInsert}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const button = screen.getByTestId('g7le-palette-item-Button') as HTMLButtonElement;
|
||||
expect(button.disabled).toBe(true);
|
||||
expect(button.getAttribute('data-blocked')).toBe('true');
|
||||
fireEvent.click(button);
|
||||
expect(onInsert).not.toHaveBeenCalled();
|
||||
// 비활성 + 안내 배지 표시
|
||||
expect(screen.getByTestId('g7le-palette-item-Button-default-missing-badge')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('entry 에 defaultNode 미정의지만 requiresDefaultNode 도 미설정이면 추가 허용 + 안내 배지 표시', () => {
|
||||
const onInsert = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ComponentPalette
|
||||
manifest={manifest}
|
||||
nesting={nesting}
|
||||
componentPalette={{
|
||||
entries: {
|
||||
Img: {
|
||||
label: '$t:layout_editor.palette.img.label',
|
||||
// requiresDefaultNode 미설정 → 차단 안 함
|
||||
},
|
||||
},
|
||||
}}
|
||||
targetParentPath={null}
|
||||
targetContainerName={null}
|
||||
insertionIndex={0}
|
||||
onInsert={onInsert}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const img = screen.getByTestId('g7le-palette-item-Img') as HTMLButtonElement;
|
||||
expect(img.disabled).toBe(false);
|
||||
expect(img.getAttribute('data-blocked')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-palette-item-Img-default-missing-badge')).toBeTruthy();
|
||||
fireEvent.click(img);
|
||||
expect(onInsert).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildDefaultNode — 폴백 경로 (코어는 시각 단서 부여 안 함)', () => {
|
||||
it('props.default 가 있는 prop 만 골격에 포함, id 는 없음, style 미부여', () => {
|
||||
const node = buildDefaultNode({
|
||||
name: 'Button',
|
||||
type: 'basic',
|
||||
props: {
|
||||
variant: { type: 'string', default: 'primary' },
|
||||
label: { type: 'string' },
|
||||
},
|
||||
});
|
||||
expect(node.id).toBeUndefined();
|
||||
expect(node.name).toBe('Button');
|
||||
expect(node.props?.variant).toBe('primary');
|
||||
expect(node.props?.style).toBeUndefined();
|
||||
expect((node.props as Record<string, unknown>)?.minHeight).toBeUndefined();
|
||||
});
|
||||
|
||||
it('props.default 가 전혀 없으면 props 자체가 부재 (코어 시각 단서 회수)', () => {
|
||||
const node = buildDefaultNode({ name: 'Img', type: 'basic' });
|
||||
expect(node.props).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* ComponentTargetPicker.test.tsx — 컴포넌트 영역 picker 위젯 + 캔버스 pick 핸드셰이크
|
||||
*
|
||||
*
|
||||
* 검증:
|
||||
* - 직접 입력칸(항상 동작): ID 타이핑 → onChange.
|
||||
* - 🎯 영역 선택: pick-request 이벤트 발사(모달 최소화) + picked 이벤트(같은 requestId) 수신
|
||||
* 시 onChange. cancelled 회신은 onChange 미발화. requestId 불일치 회신 무시.
|
||||
*
|
||||
* EditorCanvasOverlay 가 pick-request 를 수신해 노드 id 를 picked 로 회신하는 결선의 짝
|
||||
* 계약(이벤트명/detail 형태)을 잠근다.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
|
||||
const minimizeSpy = vi.fn();
|
||||
const restoreSpy = vi.fn();
|
||||
let mockStack: Array<{ id: string }> = [{ id: 'host-modal' }];
|
||||
vi.mock('../../EditorModalContext', () => ({
|
||||
useEditorModal: () => ({
|
||||
stack: mockStack,
|
||||
minimize: minimizeSpy,
|
||||
restore: restoreSpy,
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
ComponentTargetPicker,
|
||||
COMPONENT_TARGET_PICK_REQUEST_EVENT,
|
||||
COMPONENT_TARGET_PICKED_EVENT,
|
||||
} from '../../components/property-controls/ComponentTargetPicker';
|
||||
import type { EditorControlSpec } from '../../spec/specTypes';
|
||||
|
||||
const control: EditorControlSpec = { widget: 'component-target-picker', label: 'target' };
|
||||
const t = (k: string) => k;
|
||||
|
||||
function renderPicker(value: unknown, onChange = vi.fn()) {
|
||||
render(<ComponentTargetPicker control={control} value={value} onChange={onChange} t={t} />);
|
||||
return onChange;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
cleanup();
|
||||
minimizeSpy.mockClear();
|
||||
restoreSpy.mockClear();
|
||||
mockStack = [{ id: 'host-modal' }];
|
||||
});
|
||||
|
||||
describe('ComponentTargetPicker — 직접 입력 + 캔버스 pick 핸드셰이크', () => {
|
||||
it('직접 입력칸 타이핑 → onChange', () => {
|
||||
const onChange = renderPicker('');
|
||||
const input = screen.getByTestId('g7le-component-target-input') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: 'main-form' } });
|
||||
expect(onChange).toHaveBeenCalledWith('main-form');
|
||||
});
|
||||
|
||||
it('빈 입력 → onChange(undefined)', () => {
|
||||
const onChange = renderPicker('x');
|
||||
const input = screen.getByTestId('g7le-component-target-input') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
expect(onChange).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('🎯 클릭 → pick-request 발사 + 호스트 모달 최소화', () => {
|
||||
let requestDetail: { requestId?: string } | null = null;
|
||||
const onReq = (e: Event): void => {
|
||||
requestDetail = (e as CustomEvent).detail;
|
||||
};
|
||||
window.addEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
renderPicker('');
|
||||
fireEvent.click(screen.getByTestId('g7le-component-target-pick'));
|
||||
expect(requestDetail).not.toBeNull();
|
||||
expect(typeof requestDetail!.requestId).toBe('string');
|
||||
// 호스트 모달(스택 top) 최소화 호출.
|
||||
expect(minimizeSpy).toHaveBeenCalledWith('host-modal', expect.any(String));
|
||||
window.removeEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
});
|
||||
|
||||
it('picked 회신(같은 requestId) → onChange(id) + 모달 복원', () => {
|
||||
let requestId = '';
|
||||
const onReq = (e: Event): void => {
|
||||
requestId = (e as CustomEvent).detail?.requestId ?? '';
|
||||
};
|
||||
window.addEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
const onChange = renderPicker('');
|
||||
fireEvent.click(screen.getByTestId('g7le-component-target-pick'));
|
||||
// 캔버스가 노드 id 회신.
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMPONENT_TARGET_PICKED_EVENT, { detail: { requestId, id: 'picked-node' } }),
|
||||
);
|
||||
expect(onChange).toHaveBeenCalledWith('picked-node');
|
||||
expect(restoreSpy).toHaveBeenCalledWith('host-modal');
|
||||
window.removeEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
});
|
||||
|
||||
it('cancelled 회신 → onChange 미발화(복원만)', () => {
|
||||
let requestId = '';
|
||||
const onReq = (e: Event): void => {
|
||||
requestId = (e as CustomEvent).detail?.requestId ?? '';
|
||||
};
|
||||
window.addEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
const onChange = renderPicker('');
|
||||
fireEvent.click(screen.getByTestId('g7le-component-target-pick'));
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMPONENT_TARGET_PICKED_EVENT, { detail: { requestId, cancelled: true } }),
|
||||
);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
expect(restoreSpy).toHaveBeenCalledWith('host-modal');
|
||||
window.removeEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
});
|
||||
|
||||
it('다른 requestId 회신은 무시(onChange 미발화)', () => {
|
||||
const onReq = (): void => {};
|
||||
window.addEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
const onChange = renderPicker('');
|
||||
fireEvent.click(screen.getByTestId('g7le-component-target-pick'));
|
||||
// 엉뚱한 requestId 회신.
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMPONENT_TARGET_PICKED_EVENT, { detail: { requestId: 'other', id: 'x' } }),
|
||||
);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
window.removeEventListener(COMPONENT_TARGET_PICK_REQUEST_EVENT, onReq);
|
||||
});
|
||||
});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* CoreDataKeyControl.test.tsx — 코어 "폼 데이터 연결점(dataKey)" 위젯
|
||||
*
|
||||
* 가드: (1) 식별자 안전 문자 sanitize(점 경로 허용), (2) 바인딩(`{{...}}`) 디그레이드,
|
||||
* (3) 빈 값 → onChange(undefined).
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { CoreDataKeyControl, sanitizeDataKey } from '../../components/property-controls/CoreDataKeyControl';
|
||||
import type { EditorControlSpec } from '../../spec/specTypes';
|
||||
|
||||
const control: EditorControlSpec = { widget: 'core-datakey', label: 'dataKey' };
|
||||
const t = (k: string) => k;
|
||||
|
||||
function renderControl(value: unknown, onChange = vi.fn()) {
|
||||
render(<CoreDataKeyControl control={control} value={value} onChange={onChange} t={t} />);
|
||||
return onChange;
|
||||
}
|
||||
|
||||
describe('sanitizeDataKey (점 경로 허용)', () => {
|
||||
it('점/언더스코어/하이픈은 통과(점 경로 — _global.formData)', () => {
|
||||
expect(sanitizeDataKey('_global.formData')).toBe('_global.formData');
|
||||
expect(sanitizeDataKey('form')).toBe('form');
|
||||
expect(sanitizeDataKey('user-data_1')).toBe('user-data_1');
|
||||
});
|
||||
|
||||
it('공백/한글/중괄호 등 식별자 비허용 문자 제거', () => {
|
||||
expect(sanitizeDataKey('폼 데이터')).toBe('');
|
||||
expect(sanitizeDataKey('form {data}')).toBe('formdata');
|
||||
expect(sanitizeDataKey('a b.c')).toBe('ab.c');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CoreDataKeyControl 위젯', () => {
|
||||
it('정적 값 입력 시 안전 문자만 onChange 로 전달', () => {
|
||||
const onChange = renderControl('');
|
||||
const input = screen.getByTestId('g7le-widget-core-datakey') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '폼 form.x' } });
|
||||
expect(onChange).toHaveBeenCalledWith('form.x');
|
||||
});
|
||||
|
||||
it('빈 입력은 onChange(undefined) — 노드 키 삭제', () => {
|
||||
const onChange = renderControl('form');
|
||||
const input = screen.getByTestId('g7le-widget-core-datakey') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
expect(onChange).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('정적 기존 값을 그대로 표시(읽기/편집 가능) + 힌트', () => {
|
||||
renderControl('form');
|
||||
const input = screen.getByTestId('g7le-widget-core-datakey') as HTMLInputElement;
|
||||
expect(input.value).toBe('form');
|
||||
expect(input.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('바인딩(`{{...}}`) 값이면 디그레이드(읽기전용 + 안내)', () => {
|
||||
const onChange = renderControl('{{_global.formData}}');
|
||||
expect(screen.getByTestId('g7le-core-datakey-bound')).toBeTruthy();
|
||||
const input = screen.getByTestId('g7le-widget-core-datakey') as HTMLInputElement;
|
||||
expect(input.value).toBe('{{_global.formData}}');
|
||||
expect(input.disabled).toBe(true);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* CoreIdControl.test.tsx — 코어 "요소 ID" 위젯
|
||||
*
|
||||
* 가드:
|
||||
* (1) HTML 안전 문자 sanitize — 평문 세그먼트 한정(칩 보존)
|
||||
* (2) 데이터 칩(`{{...}}`) 연동 — 칩 포함 시 칩 편집기, 정적 id + 후보 시 [+데이터] 진입점
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { CoreIdControl, sanitizeElementId } from '../../components/property-controls/CoreIdControl';
|
||||
import type { EditorControlSpec } from '../../spec/specTypes';
|
||||
import type { BindingCandidate } from '../../spec/bindingCandidates';
|
||||
|
||||
const control: EditorControlSpec = { widget: 'core-id', label: 'id' };
|
||||
const t = (k: string) => k;
|
||||
|
||||
const CANDIDATES: BindingCandidate[] = [
|
||||
{
|
||||
expression: '{{row.id}}',
|
||||
source: 'data_source' as BindingCandidate['source'],
|
||||
sourceId: 'list',
|
||||
path: 'row.id',
|
||||
shape: 'scalar',
|
||||
preview: '1',
|
||||
},
|
||||
];
|
||||
|
||||
function renderControl(value: unknown, onChange = vi.fn(), bindingCandidates?: BindingCandidate[]) {
|
||||
render(
|
||||
<CoreIdControl
|
||||
control={control}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
t={t}
|
||||
bindingCandidates={bindingCandidates}
|
||||
/>,
|
||||
);
|
||||
return onChange;
|
||||
}
|
||||
|
||||
describe('sanitizeElementId (HTML 안전 문자)', () => {
|
||||
it('한글/공백 등 불허 문자를 제거한다(평문)', () => {
|
||||
expect(sanitizeElementId('으로으로')).toBe('');
|
||||
expect(sanitizeElementId('main 콘텐츠 area')).toBe('mainarea');
|
||||
expect(sanitizeElementId('헤더_header 1')).toBe('_header1');
|
||||
});
|
||||
|
||||
it('영문자/숫자/-/_/:/. 는 통과시킨다', () => {
|
||||
expect(sanitizeElementId('main-content_2:tab.1')).toBe('main-content_2:tab.1');
|
||||
expect(sanitizeElementId('Header123')).toBe('Header123');
|
||||
});
|
||||
|
||||
it('`{{...}}` 칩 토큰은 보존하고 평문 세그먼트만 정리한다', () => {
|
||||
// 칩은 그대로, 평문 "item_" / "_x" 만 안전화
|
||||
expect(sanitizeElementId('item_{{$idx}}')).toBe('item_{{$idx}}');
|
||||
expect(sanitizeElementId('행 {{row.id}} 끝')).toBe('{{row.id}}');
|
||||
expect(sanitizeElementId('a{{ x ?? 0 }}b')).toBe('a{{ x ?? 0 }}b');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CoreIdControl 위젯 — 정적 id', () => {
|
||||
it('정적 값 입력 시 안전 문자만 onChange 로 전달', () => {
|
||||
const onChange = renderControl('');
|
||||
const input = screen.getByTestId('g7le-widget-core-id') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: 'my 헤더 id!' } });
|
||||
expect(onChange).toHaveBeenCalledWith('myid');
|
||||
});
|
||||
|
||||
it('빈 입력은 onChange(undefined) — prop 삭제', () => {
|
||||
const onChange = renderControl('existing');
|
||||
const input = screen.getByTestId('g7le-widget-core-id') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
expect(onChange).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('정적 기존 값을 그대로 표시(편집 가능)', () => {
|
||||
renderControl('main-content');
|
||||
const input = screen.getByTestId('g7le-widget-core-id') as HTMLInputElement;
|
||||
expect(input.value).toBe('main-content');
|
||||
expect(input.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('후보가 없으면 [+데이터] 진입점을 숨긴다', () => {
|
||||
renderControl('main-content');
|
||||
expect(screen.queryByTestId('g7le-core-id-add-data')).toBeNull();
|
||||
});
|
||||
|
||||
it('후보가 있으면 [+데이터] 진입점을 노출한다', () => {
|
||||
renderControl('main-content', vi.fn(), CANDIDATES);
|
||||
expect(screen.getByTestId('g7le-core-id-add-data')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CoreIdControl 위젯 — 데이터 칩 연동', () => {
|
||||
it('바인딩(`{{...}}`) 값이면 칩 편집기로 노출(읽기전용 아님)', () => {
|
||||
renderControl('item_{{$idx}}', vi.fn(), CANDIDATES);
|
||||
// 칩 편집기 컨테이너가 뜬다(이전 디그레이드 g7le-core-id-bound 아님)
|
||||
expect(screen.getByTestId('g7le-core-id-chip')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-core-id-bound')).toBeNull();
|
||||
});
|
||||
|
||||
it('정적 id 에서 [+데이터] 클릭 시 칩 편집기로 전환', () => {
|
||||
renderControl('main-content', vi.fn(), CANDIDATES);
|
||||
fireEvent.click(screen.getByTestId('g7le-core-id-add-data'));
|
||||
expect(screen.getByTestId('g7le-core-id-chip')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
+351
@@ -0,0 +1,351 @@
|
||||
/**
|
||||
* CustomTranslationManager.test.tsx —
|
||||
*
|
||||
* 검증 대상: 커스텀 다국어 키 관리 모달
|
||||
* - 목록/빈/에러 상태
|
||||
* - orphaned 배지 표시
|
||||
* - 상태 필터(전체/사용중/미사용)
|
||||
* - 번역 편집(PUT, lock_version) + 409 충돌
|
||||
* - 개별 삭제 + 일괄 삭제 + 미사용 전체 삭제
|
||||
* - 모든 fetch 에 Authorization: Bearer 첨부
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
|
||||
import { CustomTranslationManager } from '../../components/property-controls/CustomTranslationManager';
|
||||
import { collectReferencedCustomKeys } from '../../utils/customTranslations';
|
||||
|
||||
const t = (k: string, params?: Record<string, string | number>) =>
|
||||
params ? `${k}(${JSON.stringify(params)})` : k;
|
||||
|
||||
const sampleList = [
|
||||
{
|
||||
id: 1,
|
||||
template_id: 1,
|
||||
layout_name: 'home',
|
||||
translation_key: 'custom.home.1',
|
||||
values: { ko: '안녕', en: 'Hi' },
|
||||
status: 'active' as const,
|
||||
lock_version: 0,
|
||||
updated_at: '2026-06-01T00:00:00+00:00',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
template_id: 1,
|
||||
layout_name: 'home',
|
||||
translation_key: 'custom.home.2',
|
||||
values: { ko: '버려짐', en: 'orphan' },
|
||||
status: 'orphaned' as const,
|
||||
lock_version: 1,
|
||||
updated_at: '2026-06-02T00:00:00+00:00',
|
||||
},
|
||||
];
|
||||
|
||||
function mockFetch(handler: (url: string, init?: RequestInit) => unknown) {
|
||||
const fn = vi.fn(async (url: string, init?: RequestInit) => handler(url, init));
|
||||
vi.stubGlobal('fetch', fn);
|
||||
return fn;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: (k: string) => (k === 'auth_token' ? 'TESTTOKEN' : null),
|
||||
setItem: () => {},
|
||||
removeItem: () => {},
|
||||
} as unknown as Storage);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function listOk() {
|
||||
return { ok: true, json: async () => ({ success: true, data: sampleList }) };
|
||||
}
|
||||
|
||||
describe('collectReferencedCustomKeys (TS 스캐너 — 백엔드 트윈)', () => {
|
||||
it('중첩 노드 text/props 에서 custom 키 수집 + dedup', () => {
|
||||
const content = {
|
||||
components: [
|
||||
{ type: 'Span', text: '$t:custom.home.1' },
|
||||
{ type: 'Div', children: [{ text: '$t:custom.home.2' }, { props: { label: '$t:custom.home.1' } }] },
|
||||
],
|
||||
};
|
||||
const keys = collectReferencedCustomKeys(content);
|
||||
expect([...keys].sort()).toEqual(['custom.home.1', 'custom.home.2']);
|
||||
});
|
||||
|
||||
it('custom 아닌 $t: 키 제외', () => {
|
||||
const keys = collectReferencedCustomKeys([{ text: '$t:common.save' }, { text: '$t:custom.home.3' }]);
|
||||
expect([...keys]).toEqual(['custom.home.3']);
|
||||
});
|
||||
|
||||
it('참조 없으면 빈 Set', () => {
|
||||
expect(collectReferencedCustomKeys([{ text: 'plain' }]).size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CustomTranslationManager', () => {
|
||||
it('마운트 시 목록 GET → 행 렌더 + Bearer 토큰 첨부', async () => {
|
||||
const fn = mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
await screen.findByTestId('g7le-translation-row-2');
|
||||
const [, init] = fn.mock.calls[0]!;
|
||||
expect((init as RequestInit).headers).toMatchObject({ Authorization: 'Bearer TESTTOKEN' });
|
||||
});
|
||||
|
||||
it('orphaned 행 → "미사용/연결 끊김" 배지 노출', async () => {
|
||||
mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-badge-orphaned-2');
|
||||
// active 행에는 배지 없음
|
||||
expect(screen.queryByTestId('g7le-translation-badge-orphaned-1')).toBeNull();
|
||||
});
|
||||
|
||||
it('목록은 최근 업데이트 순(updated_at desc)으로 정렬', async () => {
|
||||
mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-list');
|
||||
const rows = Array.from(document.querySelectorAll('[data-testid^="g7le-translation-row-"]'));
|
||||
// row-2(2026-06-02) 가 row-1(2026-06-01) 보다 먼저 와야 한다.
|
||||
expect(rows.map((r) => r.getAttribute('data-testid'))).toEqual([
|
||||
'g7le-translation-row-2',
|
||||
'g7le-translation-row-1',
|
||||
]);
|
||||
});
|
||||
|
||||
it('빈 목록 → empty 안내', async () => {
|
||||
mockFetch(() => ({ ok: true, json: async () => ({ success: true, data: [] }) }));
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-manager-empty');
|
||||
});
|
||||
|
||||
it('로드 에러 → error 바', async () => {
|
||||
mockFetch(() => ({ ok: false, status: 500, json: async () => ({ message: 'boom' }) }));
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-manager-error');
|
||||
});
|
||||
|
||||
it('미사용 필터 → orphaned 행만 표시', async () => {
|
||||
mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-filter-orphaned'));
|
||||
expect(screen.queryByTestId('g7le-translation-row-1')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-translation-row-2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('번역 편집 → PUT(values + expected_lock_version) + Bearer', async () => {
|
||||
let putBody: unknown = null;
|
||||
const fn = mockFetch((_url, init) => {
|
||||
if ((init as RequestInit)?.method === 'PUT') {
|
||||
putBody = JSON.parse(String((init as RequestInit).body));
|
||||
return { ok: true, json: async () => ({ success: true, data: { ...sampleList[0], lock_version: 1, values: { ko: '수정', en: 'Hi' } } }) };
|
||||
}
|
||||
return listOk();
|
||||
});
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
fireEvent.change(screen.getByTestId('g7le-translation-input-1-ko'), { target: { value: '수정' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-save-1'));
|
||||
await vi.waitFor(() => expect(putBody).not.toBeNull());
|
||||
expect(putBody).toMatchObject({ values: { ko: '수정', en: 'Hi' }, expected_lock_version: 0 });
|
||||
const putCall = fn.mock.calls.find((c) => (c[1] as RequestInit)?.method === 'PUT');
|
||||
expect((putCall![1] as RequestInit).headers).toMatchObject({ Authorization: 'Bearer TESTTOKEN' });
|
||||
});
|
||||
|
||||
// 칩 이동/추가는 즉시 PUT 하지 않고 저장-지연 버퍼(pending)에만 기록한다.
|
||||
// 본 모달이 서버 값만 보면 레이아웃 [저장] 전까지 `{pN}` 누락된 stale 값을 보여 준다
|
||||
// 서버 값 위에 pending 을 덮어
|
||||
// 캔버스/엔진과 동일한 라이브 값을 표시해야 한다.
|
||||
it('pending 버퍼가 있으면 서버 값 대신 버퍼 값(칩 위치 반영)을 표시', async () => {
|
||||
const { setPendingValue, clearPending } = await import('../../hooks/pendingCustomTranslations');
|
||||
clearPending();
|
||||
// 서버 값은 {p0} 없는 plainBase, pending 버퍼엔 칩 이동된 {p0} 위치 문장.
|
||||
const serverList = [
|
||||
{
|
||||
id: 7,
|
||||
template_id: 1,
|
||||
layout_name: 'home',
|
||||
translation_key: 'custom.home.7',
|
||||
values: { ko: '발 행일:', en: 'Published:', ja: '発行:' },
|
||||
status: 'active' as const,
|
||||
lock_version: 0,
|
||||
updated_at: '2026-06-09T00:00:00+00:00',
|
||||
},
|
||||
];
|
||||
setPendingValue('sirsoft-basic', 'custom.home.7', 'ko', '발{p0}행일:');
|
||||
setPendingValue('sirsoft-basic', 'custom.home.7', 'en', 'Published: {p0}');
|
||||
setPendingValue('sirsoft-basic', 'custom.home.7', 'ja', '発行: {p0}');
|
||||
mockFetch(() => ({ ok: true, json: async () => ({ success: true, data: serverList }) }));
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-7');
|
||||
// `{p0}` 자리표시가 든 키 값은 raw textarea 가 아니라 **칩 합성 위젯**으로
|
||||
// 렌더된다(평문 input 아님). 전 로케일 행이 pending 값({p0} 포함)을 칩으로 보여야 한다.
|
||||
expect(screen.queryByTestId('g7le-translation-input-7-ko')).toBeNull(); // 평문 textarea 아님.
|
||||
expect(screen.getByTestId('g7le-translation-chip-7-ko')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-translation-chip-7-en')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-translation-chip-7-ja')).toBeTruthy();
|
||||
// {p0} 자리표시는 원자 칩으로 렌더(전 로케일).
|
||||
expect(screen.getByTestId('g7le-chip-7-ko-p0')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-chip-7-en-p0')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-chip-7-ja-p0')).toBeTruthy();
|
||||
clearPending();
|
||||
});
|
||||
|
||||
// 평문 값은 textarea, `{pN}` 자리표시 값은 칩. 한 행에 평문 로케일과
|
||||
// param 로케일이 섞여 있어도 각 로케일별로 위젯을 분기한다(혼합 안전).
|
||||
it('평문 로케일=textarea / {pN} 로케일=칩 (로케일별 분기)', async () => {
|
||||
const { clearPending } = await import('../../hooks/pendingCustomTranslations');
|
||||
clearPending();
|
||||
const serverList = [
|
||||
{
|
||||
id: 9, template_id: 1, layout_name: 'home', translation_key: 'custom.home.9',
|
||||
// ko 는 평문, en 은 {p0} 자리표시.
|
||||
values: { ko: '안녕하세요', en: 'Hi {p0}' },
|
||||
status: 'active' as const, lock_version: 0, updated_at: '2026-06-09T00:00:00+00:00',
|
||||
},
|
||||
];
|
||||
mockFetch(() => ({ ok: true, json: async () => ({ success: true, data: serverList }) }));
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-9');
|
||||
// ko 평문 → textarea, en {p0} → 칩 위젯.
|
||||
expect((screen.getByTestId('g7le-translation-input-9-ko') as HTMLTextAreaElement).value).toBe('안녕하세요');
|
||||
expect(screen.queryByTestId('g7le-translation-chip-9-ko')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-translation-input-9-en')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-translation-chip-9-en')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-chip-9-en-p0')).toBeTruthy();
|
||||
clearPending();
|
||||
});
|
||||
|
||||
it('번역 편집 409 → 충돌 메시지 표시', async () => {
|
||||
mockFetch((_url, init) => {
|
||||
if ((init as RequestInit)?.method === 'PUT') {
|
||||
return { ok: false, status: 409, json: async () => ({ message: 'conflict' }) };
|
||||
}
|
||||
return listOk();
|
||||
});
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-save-1'));
|
||||
const err = await screen.findByTestId('g7le-translation-row-error-1');
|
||||
expect(err.textContent).toContain('layout_editor.translation_manager.conflict');
|
||||
});
|
||||
|
||||
it('개별 삭제 confirm 승인 → DELETE + 행 제거', async () => {
|
||||
let deleted = false;
|
||||
mockFetch((url, init) => {
|
||||
if ((init as RequestInit)?.method === 'DELETE' && /custom-translations\/1$/.test(url)) {
|
||||
deleted = true;
|
||||
return { ok: true, json: async () => ({ success: true }) };
|
||||
}
|
||||
return listOk();
|
||||
});
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-delete-1'));
|
||||
await vi.waitFor(() => expect(deleted).toBe(true));
|
||||
await vi.waitFor(() => expect(screen.queryByTestId('g7le-translation-row-1')).toBeNull());
|
||||
});
|
||||
|
||||
it('선택 후 일괄 삭제 → DELETE(body ids) + 행 제거', async () => {
|
||||
let bulkBody: unknown = null;
|
||||
mockFetch((url, init) => {
|
||||
const method = (init as RequestInit)?.method;
|
||||
if (method === 'DELETE' && /custom-translations$/.test(url)) {
|
||||
bulkBody = JSON.parse(String((init as RequestInit).body));
|
||||
return { ok: true, json: async () => ({ success: true, data: { deleted: 2 } }) };
|
||||
}
|
||||
return listOk();
|
||||
});
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-select-1'));
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-select-2'));
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-bulk-delete'));
|
||||
await vi.waitFor(() => expect(bulkBody).not.toBeNull());
|
||||
expect((bulkBody as { ids: number[] }).ids.sort()).toEqual([1, 2]);
|
||||
await vi.waitFor(() => expect(screen.queryByTestId('g7le-translation-row-1')).toBeNull());
|
||||
});
|
||||
|
||||
it('로케일 라벨 → 언어 명칭(해석) + 식별자 표시', async () => {
|
||||
// 언어 명칭 키를 실제 명칭으로 해석하는 t 더블 — 라벨 = "명칭 (식별자)" 형태 검증
|
||||
const tLocale = (k: string, params?: Record<string, string | number>) => {
|
||||
const names: Record<string, string> = {
|
||||
'layout_editor.locale.ko': '한국어',
|
||||
'layout_editor.locale.en': 'English',
|
||||
'layout_editor.locale.ja': '日本語',
|
||||
};
|
||||
if (names[k]) return names[k];
|
||||
return params ? `${k}(${JSON.stringify(params)})` : k;
|
||||
};
|
||||
mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={tLocale} onClose={vi.fn()} />);
|
||||
const field = await screen.findByTestId('g7le-translation-field-1-ko');
|
||||
const label = field.querySelector('label');
|
||||
// 언어 명칭 + 식별자 둘 다 노출
|
||||
expect(label?.textContent).toContain('한국어');
|
||||
expect(label?.textContent).toContain('(ko)');
|
||||
});
|
||||
|
||||
it('referencedKeys 전달 → 현재 캔버스 사용중/미사용 라이브 배지 표시', async () => {
|
||||
mockFetch(() => listOk());
|
||||
// custom.home.1(id=1) 은 캔버스 참조, custom.home.2(id=2) 는 미참조.
|
||||
const referencedKeys = new Set<string>(['custom.home.1']);
|
||||
render(
|
||||
<CustomTranslationManager
|
||||
templateIdentifier="sirsoft-basic"
|
||||
layoutName="home"
|
||||
t={t}
|
||||
referencedKeys={referencedKeys}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
// id=1 → 라이브 사용중 배지, id=2 → 라이브 미사용 배지
|
||||
expect(screen.getByTestId('g7le-translation-badge-live-inuse-1')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-translation-badge-live-unused-1')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-translation-badge-live-unused-2')).toBeInTheDocument();
|
||||
// 저장된 status 배지(영속)는 별개로 유지 — id=2 는 orphaned status 라 둘 다 노출
|
||||
expect(screen.getByTestId('g7le-translation-badge-orphaned-2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('referencedKeys 미전달 → 라이브 배지 생략(저장 status 배지만)', async () => {
|
||||
mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-row-1');
|
||||
expect(screen.queryByTestId('g7le-translation-badge-live-inuse-1')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-translation-badge-live-unused-2')).toBeNull();
|
||||
});
|
||||
|
||||
it('번역 입력은 textarea (긴 텍스트 세로 확장 대응)', async () => {
|
||||
mockFetch(() => listOk());
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
const input = await screen.findByTestId('g7le-translation-input-1-ko');
|
||||
expect(input.tagName).toBe('TEXTAREA');
|
||||
});
|
||||
|
||||
it('미사용 전체 삭제 → orphaned id 만 bulkDelete', async () => {
|
||||
let bulkBody: unknown = null;
|
||||
mockFetch((url, init) => {
|
||||
const method = (init as RequestInit)?.method;
|
||||
if (method === 'DELETE' && /custom-translations$/.test(url)) {
|
||||
bulkBody = JSON.parse(String((init as RequestInit).body));
|
||||
return { ok: true, json: async () => ({ success: true, data: { deleted: 1 } }) };
|
||||
}
|
||||
return listOk();
|
||||
});
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
render(<CustomTranslationManager templateIdentifier="sirsoft-basic" layoutName="home" t={t} onClose={vi.fn()} />);
|
||||
await screen.findByTestId('g7le-translation-purge-orphaned');
|
||||
fireEvent.click(screen.getByTestId('g7le-translation-purge-orphaned'));
|
||||
await vi.waitFor(() => expect(bulkBody).not.toBeNull());
|
||||
// orphaned 행(id=2)만 대상
|
||||
expect((bulkBody as { ids: number[] }).ids).toEqual([2]);
|
||||
});
|
||||
});
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
// e2e:allow 레이아웃 편집기 데이터 연결 속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(6-b 캔버스 라이브 §공통 검증) + 단위/레이아웃 렌더링 테스트로 검증 (specTypes.ts L1 과 동일 정책)
|
||||
/**
|
||||
* DataBindingSection.test.tsx — 데이터 연결 영역 RTL
|
||||
*
|
||||
* 검증:
|
||||
* - dataProps 행 렌더(scalar/array shape 배지 + 필수 배지)
|
||||
* - 미연결 → 검색 피커 → 후보 선택 → `{{...}}` 를 props[propKey] 기입(round-trip)
|
||||
* - 연결됨 → 표현식 표시 + [해제] → prop 삭제
|
||||
* - 복합 바인딩(`{{a ? b : c}}` 삼항 등) → 디그레이드(코드 편집) 읽기전용, 검색 피커 미노출
|
||||
* (단 `{{a?.b ?? []}}` 같은 G7 표준 안전 바인딩은에서 파싱·변경 가능)
|
||||
* - shape 필터: array 행은 배열 후보만 노출
|
||||
* - 회귀 가드(1차 결함): 구조/수치 prop(dataProps 미선언)은 데이터 연결 행 0
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { DataBindingSection } from '../../components/property-controls/DataBindingSection';
|
||||
import type { DataPropSpec } from '../../spec/specTypes';
|
||||
import type { BindingCandidate } from '../../spec/bindingCandidates';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
const candidates: BindingCandidate[] = [
|
||||
{
|
||||
expression: '{{products.data.data}}',
|
||||
source: 'data_source',
|
||||
sourceId: 'products',
|
||||
path: 'data.data',
|
||||
shape: 'array',
|
||||
groupLabelKey: 'editor.ds.products',
|
||||
preview: '[3]',
|
||||
itemFields: ['name', 'price'],
|
||||
},
|
||||
{
|
||||
expression: '{{_local.keyword}}',
|
||||
source: '_local',
|
||||
sourceId: '_local',
|
||||
path: 'keyword',
|
||||
shape: 'scalar',
|
||||
preview: '노트북',
|
||||
},
|
||||
];
|
||||
|
||||
describe('DataBindingSection — 렌더', () => {
|
||||
it('dataProps 행을 shape 배지 + 필수 배지와 렌더한다', () => {
|
||||
const node: EditorNode = { name: 'CardGrid', props: {} };
|
||||
const dataProps: DataPropSpec[] = [
|
||||
{ propKey: 'data', shape: 'array', label: '데이터', itemFields: ['name'], required: true },
|
||||
];
|
||||
render(
|
||||
<DataBindingSection node={node} dataProps={dataProps} candidates={candidates} t={t} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-data-binding-section')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-binding-row-data')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-binding-required-data')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-binding-empty-data')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('dataProps 가 비면 null 렌더(영역 비노출)', () => {
|
||||
const node: EditorNode = { name: 'Div', props: {} };
|
||||
const { container } = render(
|
||||
<DataBindingSection node={node} dataProps={[]} candidates={candidates} t={t} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataBindingSection — 연결 round-trip', () => {
|
||||
it('검색 → array 후보 선택 → {{...}} 를 props[propKey] 기입', () => {
|
||||
const node: EditorNode = { name: 'CardGrid', props: {} };
|
||||
const dataProps: DataPropSpec[] = [{ propKey: 'data', shape: 'array' }];
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<DataBindingSection node={node} dataProps={dataProps} candidates={candidates} t={t} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-binding-search-toggle-data'));
|
||||
// array 행이라 배열 후보만 — products.data.data 노출, _local.keyword(scalar) 미노출
|
||||
expect(screen.getByTestId('g7le-binding-candidate-{{products.data.data}}')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-binding-candidate-{{_local.keyword}}')).toBeNull();
|
||||
fireEvent.click(screen.getByTestId('g7le-binding-candidate-{{products.data.data}}'));
|
||||
// 선택 시 G7 표준 안전 형태(`?.` 체이닝 + shape 별 폴백)로 기입.
|
||||
expect(onPatchNode).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ props: { data: '{{products?.data?.data ?? []}}' } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('연결됨 → 표현식 표시 + [해제] → prop 삭제', () => {
|
||||
const node: EditorNode = { name: 'CardGrid', props: { data: '{{products.data.data}}' } };
|
||||
const dataProps: DataPropSpec[] = [{ propKey: 'data', shape: 'array' }];
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<DataBindingSection node={node} dataProps={dataProps} candidates={candidates} t={t} onPatchNode={onPatchNode} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-binding-expr-data').textContent).toBe('{{products.data.data}}');
|
||||
fireEvent.click(screen.getByTestId('g7le-binding-clear-data'));
|
||||
expect(onPatchNode).toHaveBeenCalledWith(expect.objectContaining({ props: {} }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataBindingSection — 복합 바인딩 디그레이드', () => {
|
||||
it('단일 경로가 아닌 복합식은 코드편집 디그레이드 + 검색 피커 미노출', () => {
|
||||
const node: EditorNode = { name: 'Input', props: { value: '{{a ? b : c}}' } };
|
||||
const dataProps: DataPropSpec[] = [{ propKey: 'value', shape: 'scalar' }];
|
||||
render(
|
||||
<DataBindingSection node={node} dataProps={dataProps} candidates={candidates} t={t} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-binding-complex-value')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-binding-search-toggle-value')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataBindingSection — scalar 행 shape 필터', () => {
|
||||
it('scalar 행은 스칼라 후보만 노출', () => {
|
||||
const node: EditorNode = { name: 'Input', props: {} };
|
||||
const dataProps: DataPropSpec[] = [{ propKey: 'value', shape: 'scalar' }];
|
||||
render(
|
||||
<DataBindingSection node={node} dataProps={dataProps} candidates={candidates} t={t} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-binding-search-toggle-value'));
|
||||
expect(screen.getByTestId('g7le-binding-candidate-{{_local.keyword}}')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-binding-candidate-{{products.data.data}}')).toBeNull();
|
||||
});
|
||||
});
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
// e2e:allow DataSourcesPanel 보강 필드 단위(RTL) — 종류분기/onSuccess/errorHandling/websocket, Chrome MCP 매트릭스(세션 D)로 보강.
|
||||
/**
|
||||
* DataSourcesPanel.enrich.test.tsx — 편집 폼 보강 RTL
|
||||
*
|
||||
* 검증(기존 CRUD 회귀는 DataSourcesPanel.test.tsx 가 커버 — 본 파일은 보강 필드만):
|
||||
* ① contentType select(type=api) → 저장
|
||||
* ② refetchOnMount 토글 → 저장
|
||||
* ③ onSuccess/onError 다중 액션 빌더 섹션 렌더
|
||||
* ④ errorHandling 코드 추가 → 행 생성
|
||||
* ⑤ websocket 종류 → 채널/이벤트/채널타입/타겟소스/onReceive 섹션 분기
|
||||
* ⑥ 종류 전환 시 무관 필드 보존(__source)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
|
||||
// I18nTextField 경량 모킹(label_key 위젯 — 컨텍스트 회피).
|
||||
vi.mock('../../components/property-controls/I18nTextField', () => ({
|
||||
I18nTextField: ({ value, onChange }: { value: string; onChange: (v: string | undefined) => void }) => (
|
||||
<input data-testid="ds-label-mock" value={value ?? ''} onChange={(e) => onChange(e.target.value)} />
|
||||
),
|
||||
}));
|
||||
// ConditionBuilder 경량 모킹(StyleScope 등 의존 회피 — 조건부 로딩 섹션 존재만 확인).
|
||||
vi.mock('../../components/property-controls/ConditionBuilder', () => ({
|
||||
ConditionBuilder: () => <div data-testid="condition-builder-mock" />,
|
||||
}));
|
||||
|
||||
import { DataSourcesPanel } from '../../components/property-controls/DataSourcesPanel';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
beforeEach(() => cleanup());
|
||||
|
||||
describe('DataSourcesPanel — 보강', () => {
|
||||
it('편집 폼에 contentType/refetchOnMount/onSuccess/onError/errorHandling/조건부 섹션 렌더', () => {
|
||||
const raw = { data_sources: [{ id: 'products', type: 'api', endpoint: '/api/products' }] };
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
expect(screen.getByTestId('g7le-ds-contenttype')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-refetch')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-onsuccess')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-onerror')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-errorhandling')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-loadcondition')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('contentType/refetchOnMount 저장 라운드트립', () => {
|
||||
const onChange = vi.fn();
|
||||
const raw = { data_sources: [{ id: 'products', type: 'api', endpoint: '/api/products' }] };
|
||||
render(<DataSourcesPanel raw={raw} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
fireEvent.change(screen.getByTestId('g7le-ds-contenttype'), { target: { value: 'multipart/form-data' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-ds-refetch'));
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const merged = onChange.mock.calls.at(-1)![0];
|
||||
expect(merged[0]).toMatchObject({ contentType: 'multipart/form-data', refetchOnMount: true });
|
||||
});
|
||||
|
||||
it('errorHandling 코드 추가 → 행 생성', () => {
|
||||
const raw = { data_sources: [{ id: 'products', type: 'api', endpoint: '/api/products' }] };
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
fireEvent.click(screen.getByTestId('g7le-ds-errorhandling-add'));
|
||||
expect(screen.getByTestId('g7le-ds-eh-row-403')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('websocket 종류 → 채널/이벤트/채널타입/타겟소스/onReceive 섹션 분기', () => {
|
||||
const raw = { data_sources: [{ id: 'live', type: 'websocket' }] };
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
expect(screen.getByTestId('g7le-ds-ws-channel')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-ws-event')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-ws-channeltype')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-ws-target')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-ws-onreceive')).toBeInTheDocument();
|
||||
// contentType 은 api 전용 — websocket 에선 부재.
|
||||
expect(screen.queryByTestId('g7le-ds-contenttype')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('종류 전환 시 무관 필드(__source) 보존', () => {
|
||||
const onChange = vi.fn();
|
||||
const raw = { data_sources: [{ id: 'products', type: 'api', endpoint: '/api/products', __source: { kind: 'route' } }] };
|
||||
render(<DataSourcesPanel raw={raw} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-type'), { target: { value: 'static' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const merged = onChange.mock.calls.at(-1)![0];
|
||||
expect(merged[0].__source).toEqual({ kind: 'route' });
|
||||
expect(merged[0].type).toBe('static');
|
||||
});
|
||||
});
|
||||
+672
@@ -0,0 +1,672 @@
|
||||
// e2e:allow 부록7 7-a label_key I18nTextField 승격 반영(단위). 브라우저 검증은 7-b 세션 귀속.
|
||||
/**
|
||||
* DataSourcesPanel.test.tsx —
|
||||
*
|
||||
* 페이지 설정 · 데이터 소스 CRUD 모달 검증:
|
||||
* - splitSources: 자체(__editor.original.data_sources) / 상속(merged 중 자체 외) 분리
|
||||
* - 추가/편집/삭제 → onChange(merged, own) 정확 호출
|
||||
* - label_key 보존/설정/해제
|
||||
* - 검증: id 필수/형식/중복, params/fallback JSON 파싱 오류
|
||||
* - 상속 소스 읽기전용 표시(편집/삭제 버튼 없음)
|
||||
*
|
||||
* 시나리오 매니페스트: tests/scenarios/layout-editor-data-sources.yaml
|
||||
*
|
||||
* @effects split_sources_own_from_editor_original_inherited_from_merged,
|
||||
* add_source_appends_to_own_and_merged_preserves_inherited,
|
||||
* edit_source_preserves_unedited_fields_like_source_meta,
|
||||
* remove_source_drops_from_own_and_merged,
|
||||
* inherited_sources_render_readonly_no_edit_remove_buttons,
|
||||
* id_required_invalid_format_duplicate_rejected_with_error,
|
||||
* params_fallback_invalid_json_rejected_with_error,
|
||||
* params_binding_expression_preserved_as_object,
|
||||
* label_key_saved_and_removed_on_empty
|
||||
*/
|
||||
|
||||
// 시나리오 cross product (operation × source_origin × ds_type × template) 마킹 —
|
||||
// 라인 주석 형태(전역 매칭). DataSourcesPanel 단위가 add/edit/remove × 자체 소스를
|
||||
// 커버하고, ds_type 별 add 폼 필드 노출/저장(api·static·route_params·query_params·
|
||||
// websocket)을 동일 폼 경로로 검증한다.
|
||||
// @scenario operation=add, source_origin=own, ds_type=api, template=sirsoft-basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=api, template=sirsoft-admin_basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=static, template=sirsoft-basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=static, template=sirsoft-admin_basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=route_params, template=sirsoft-basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=route_params, template=sirsoft-admin_basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=query_params, template=sirsoft-basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=query_params, template=sirsoft-admin_basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=websocket, template=sirsoft-basic
|
||||
// @scenario operation=add, source_origin=own, ds_type=websocket, template=sirsoft-admin_basic
|
||||
// @scenario operation=edit, source_origin=own, ds_type=api, template=sirsoft-basic
|
||||
// @scenario operation=edit, source_origin=own, ds_type=api, template=sirsoft-admin_basic
|
||||
// @scenario operation=remove, source_origin=own, ds_type=api, template=sirsoft-basic
|
||||
// @scenario operation=remove, source_origin=own, ds_type=api, template=sirsoft-admin_basic
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react';
|
||||
|
||||
// useLayoutEditor — label_key 입력의 I18nTextField(부록7 7-a)가 공통 hook 으로 읽는 컨텍스트 모킹.
|
||||
vi.mock('../../LayoutEditorContext', () => ({
|
||||
useLayoutEditor: () => ({
|
||||
state: {
|
||||
templateIdentifier: 'sirsoft-basic',
|
||||
locale: 'ko',
|
||||
selectedRoute: { path: '/home', layoutName: 'home' },
|
||||
},
|
||||
}),
|
||||
}));
|
||||
// TranslationEngine — label_key 토큰 해석(미리보기 시작값). raw 키/평문은 빈 해석.
|
||||
vi.mock('../../../TranslationEngine', () => ({
|
||||
TranslationEngine: { getInstance: () => ({ translate: (k: string) => k }) },
|
||||
}));
|
||||
|
||||
import { DataSourcesPanel } from '../../components/property-controls/DataSourcesPanel';
|
||||
|
||||
// 테스트용 t — 키 그대로 반환(파라미터는 무시). UI 텍스트 검증이 아닌 동작 검증이므로 충분.
|
||||
const t = (key: string): string => key;
|
||||
|
||||
function rawWithOwn(own: Array<Record<string, unknown>>, merged?: Array<Record<string, unknown>>) {
|
||||
return {
|
||||
components: [],
|
||||
data_sources: merged ?? own,
|
||||
__editor: { original: { data_sources: own } },
|
||||
};
|
||||
}
|
||||
|
||||
describe('DataSourcesPanel — splitSources', () => {
|
||||
it('__editor.original.data_sources 를 자체로 분리한다', () => {
|
||||
const raw = rawWithOwn([{ id: 'products', endpoint: '/api/p' }]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const items = screen.getAllByTestId('g7le-data-sources-item');
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].getAttribute('data-ds-id')).toBe('products');
|
||||
});
|
||||
|
||||
it('merged 중 자체에 없는 id 는 상속으로 분리(읽기전용)', () => {
|
||||
const raw = rawWithOwn(
|
||||
[{ id: 'products' }],
|
||||
[{ id: 'parent_user' }, { id: 'products' }], // merged = 상속 + 자체
|
||||
);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
expect(screen.getAllByTestId('g7le-data-sources-item')).toHaveLength(1);
|
||||
const inh = screen.getAllByTestId('g7le-data-sources-inherited-item');
|
||||
expect(inh).toHaveLength(1);
|
||||
expect(inh[0].getAttribute('data-ds-id')).toBe('parent_user');
|
||||
});
|
||||
|
||||
it('__editor 부재(레거시) 시 최상위 data_sources 로 폴백', () => {
|
||||
const raw = { components: [], data_sources: [{ id: 'legacy' }] };
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const items = screen.getAllByTestId('g7le-data-sources-item');
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].getAttribute('data-ds-id')).toBe('legacy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 추가', () => {
|
||||
it('신규 소스 추가 → onChange(merged=상속∪자체, own=자체)', () => {
|
||||
const onChange = vi.fn();
|
||||
const raw = rawWithOwn([{ id: 'existing' }], [{ id: 'inh' }, { id: 'existing' }]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'newSrc' } });
|
||||
fireEvent.change(screen.getByTestId('g7le-ds-endpoint-input'), { target: { value: '/api/new' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
const [merged, own] = onChange.mock.calls[0];
|
||||
expect(own.map((d: any) => d.id)).toEqual(['existing', 'newSrc']);
|
||||
// merged 에 상속(inh) 이 보존되어야 함
|
||||
expect(merged.map((d: any) => d.id)).toEqual(['inh', 'existing', 'newSrc']);
|
||||
const added = own.find((d: any) => d.id === 'newSrc');
|
||||
expect(added.endpoint).toBe('/api/new');
|
||||
expect(added.type).toBe('api');
|
||||
expect(added.auto_fetch).toBe(true);
|
||||
});
|
||||
|
||||
it('label_key 입력은 동적 다국어 필드(부록7 7-a) — 기존 토큰 보존, 빈 값이면 제거', () => {
|
||||
// 부록7 7-a: label_key 입력은 raw `$t:` 직접 입력칸이 아니라 I18nTextField(평문→키 자동생성).
|
||||
// 기존 `$t:custom.*` 토큰을 가진 소스를 편집 → 라벨 미수정 submit 시 토큰이 보존된다.
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 'products', label_key: '$t:custom.home.3' }])}
|
||||
onChange={onChange}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
// I18nTextField 가 라벨 입력 자리에 렌더된다(평문 input 직접 노출 아님).
|
||||
expect(screen.getByTestId('g7le-data-sources-field-label-preview')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect(own[0].label_key).toBe('$t:custom.home.3');
|
||||
});
|
||||
|
||||
it('label_key 빈 값(평문/토큰 모두 없음) → 저장 시 제거', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'products' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect(own[0].label_key).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 편집/삭제', () => {
|
||||
it('편집 시 기존 필드 보존(__source 등) + 변경 필드만 갱신', () => {
|
||||
const onChange = vi.fn();
|
||||
const raw = rawWithOwn([
|
||||
{ id: 'products', endpoint: '/api/old', __source: { kind: 'route' }, method: 'GET' },
|
||||
]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
fireEvent.change(screen.getByTestId('g7le-ds-endpoint-input'), { target: { value: '/api/new' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect(own[0].endpoint).toBe('/api/new');
|
||||
// __source 보존
|
||||
expect(own[0].__source).toEqual({ kind: 'route' });
|
||||
});
|
||||
|
||||
it('삭제 → 해당 소스 제거, merged 에서도 제거', () => {
|
||||
const onChange = vi.fn();
|
||||
const raw = rawWithOwn([{ id: 'a' }, { id: 'b' }]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
const items = screen.getAllByTestId('g7le-data-sources-item');
|
||||
fireEvent.click(within(items[0]).getByTestId('g7le-data-sources-remove'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect(own.map((d: any) => d.id)).toEqual(['b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 검증', () => {
|
||||
function openAddForm() {
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
}
|
||||
|
||||
it('id 빈 값 → 에러, onChange 미호출', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
openAddForm();
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-form-error')).toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('id 형식 오류(숫자 시작) → 에러', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
openAddForm();
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: '1bad' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-form-error')).toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('id 중복(자체) → 에러', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([{ id: 'dup' }])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
openAddForm();
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'dup' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-form-error')).toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('id 중복(상속) → 에러 (ValidDataSourceMerge 사전 차단)', () => {
|
||||
const onChange = vi.fn();
|
||||
const raw = rawWithOwn([{ id: 'own' }], [{ id: 'parent' }, { id: 'own' }]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
openAddForm();
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'parent' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-form-error')).toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('params raw 모드(코드 편집) JSON 파싱 오류 → 에러 (①)', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
openAddForm();
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'src' } });
|
||||
// 블럭 → 코드(raw JSON) 모드 전환 후 잘못된 JSON 입력.
|
||||
fireEvent.click(screen.getByTestId('g7le-ds-params-mode-toggle'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-params'), { target: { value: '{ not json' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-form-error')).toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('params raw 모드 유효 JSON(바인딩 표현식 포함) → 객체로 저장 (①)', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
openAddForm();
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'src' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-ds-params-mode-toggle'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-params'), {
|
||||
target: { value: '{ "page": "{{query.page ?? 1}}" }' },
|
||||
});
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect(own[0].params).toEqual({ page: '{{query.page ?? 1}}' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 상속 소스 읽기전용', () => {
|
||||
it('상속 소스에는 편집/삭제 버튼이 없다', () => {
|
||||
const raw = rawWithOwn([{ id: 'own' }], [{ id: 'inh' }, { id: 'own' }]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const inh = screen.getByTestId('g7le-data-sources-inherited-item');
|
||||
expect(within(inh).queryByTestId('g7le-data-sources-edit')).toBeNull();
|
||||
expect(within(inh).queryByTestId('g7le-data-sources-remove')).toBeNull();
|
||||
});
|
||||
|
||||
it('상속 소스 토글 클릭 시 정보(endpoint/method 등) 펼침/접힘', () => {
|
||||
const raw = rawWithOwn(
|
||||
[{ id: 'own' }],
|
||||
[
|
||||
{ id: 'inh', type: 'api', endpoint: '/api/inh', method: 'GET', __source: { kind: 'base' } },
|
||||
{ id: 'own' },
|
||||
],
|
||||
);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const inh = screen.getByTestId('g7le-data-sources-inherited-item');
|
||||
// 초기엔 접힘 — 정보 미노출
|
||||
expect(inh.getAttribute('data-expanded')).toBe('false');
|
||||
expect(within(inh).queryByTestId('g7le-data-sources-inherited-info')).toBeNull();
|
||||
// 토글 펼침
|
||||
fireEvent.click(within(inh).getByTestId('g7le-data-sources-inherited-toggle'));
|
||||
expect(inh.getAttribute('data-expanded')).toBe('true');
|
||||
const info = within(inh).getByTestId('g7le-data-sources-inherited-info');
|
||||
expect(info.textContent).toContain('/api/inh');
|
||||
expect(info.textContent).toContain('GET');
|
||||
// 다시 접힘
|
||||
fireEvent.click(within(inh).getByTestId('g7le-data-sources-inherited-toggle'));
|
||||
expect(inh.getAttribute('data-expanded')).toBe('false');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — label_key 친화 명칭 표시', () => {
|
||||
// resolveLabel 가 친화 명칭을 돌려주는 가짜 사전
|
||||
const resolveLabel = (key: string): string => {
|
||||
const map: Record<string, string> = {
|
||||
'editor.data_source.products': '상품 목록',
|
||||
'editor.data_source.categories': '카테고리',
|
||||
};
|
||||
return map[key] ?? key;
|
||||
};
|
||||
|
||||
it('label_key 해석 성공 시 친화 명칭이 제목, id 는 보조 표시', () => {
|
||||
const raw = rawWithOwn([{ id: 'products', label_key: '$t:editor.data_source.products' }]);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} resolveLabel={resolveLabel} onClose={vi.fn()} />);
|
||||
const title = screen.getByTestId('g7le-data-sources-item-title');
|
||||
expect(title.textContent).toContain('상품 목록');
|
||||
expect(within(title).getByTestId('g7le-data-sources-item-id').textContent).toBe('products');
|
||||
});
|
||||
|
||||
it('label_key 미해석/미지정 시 id 가 제목(보조 id 없음)', () => {
|
||||
const raw = rawWithOwn([{ id: 'unknownSrc' }]); // label_key 없음
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} resolveLabel={resolveLabel} onClose={vi.fn()} />);
|
||||
const title = screen.getByTestId('g7le-data-sources-item-title');
|
||||
expect(title.textContent).toBe('unknownSrc');
|
||||
expect(within(title).queryByTestId('g7le-data-sources-item-id')).toBeNull();
|
||||
});
|
||||
|
||||
it('resolveLabel 미전달 시 t 폴백(키 그대로면 id 표시)', () => {
|
||||
const raw = rawWithOwn([{ id: 'products', label_key: '$t:editor.data_source.products' }]);
|
||||
// t 는 키 그대로 반환 → 해석 실패 → id 폴백
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const title = screen.getByTestId('g7le-data-sources-item-title');
|
||||
expect(title.textContent).toBe('products');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 확장 출처 배지', () => {
|
||||
it('확장 주입 소스(__source.kind=extension)는 모듈/플러그인 + 식별자 배지 표시', () => {
|
||||
const raw = rawWithOwn(
|
||||
[{ id: 'own' }],
|
||||
[
|
||||
{
|
||||
id: 'gdprMyConsent',
|
||||
__source: { kind: 'extension', extensionSourceType: 'plugin', extensionIdentifier: 'sirsoft-gdpr', extensionName: 'GDPR' },
|
||||
},
|
||||
{ id: 'own' },
|
||||
],
|
||||
);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const inh = screen.getByTestId('g7le-data-sources-inherited-item');
|
||||
const badge = within(inh).getByTestId('g7le-data-sources-ext-badge');
|
||||
// t 는 키 그대로 반환 → "layout_editor.data_sources.source.plugin: GDPR (sirsoft-gdpr)"
|
||||
expect(badge.textContent).toContain('plugin');
|
||||
expect(badge.textContent).toContain('GDPR');
|
||||
expect(badge.textContent).toContain('sirsoft-gdpr');
|
||||
});
|
||||
|
||||
it('모듈 출처는 module 배지, 비-확장(route)은 배지 없음', () => {
|
||||
const raw = rawWithOwn(
|
||||
[{ id: 'own' }],
|
||||
[
|
||||
{ id: 'products', __source: { kind: 'extension', extensionSourceType: 'module', extensionIdentifier: 'sirsoft-ecommerce' } },
|
||||
{ id: 'boards', __source: { kind: 'route', identifier: null } },
|
||||
{ id: 'own' },
|
||||
],
|
||||
);
|
||||
render(<DataSourcesPanel raw={raw} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
const items = screen.getAllByTestId('g7le-data-sources-inherited-item');
|
||||
const prod = items.find((e) => e.getAttribute('data-ds-id') === 'products')!;
|
||||
const board = items.find((e) => e.getAttribute('data-ds-id') === 'boards')!;
|
||||
expect(within(prod).getByTestId('g7le-data-sources-ext-badge').textContent).toContain('module');
|
||||
expect(within(prod).getByTestId('g7le-data-sources-ext-badge').textContent).toContain('sirsoft-ecommerce');
|
||||
expect(within(board).queryByTestId('g7le-data-sources-ext-badge')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 헤더/푸터 고정 구조', () => {
|
||||
it('헤더(타이틀/설명)는 본문과 분리, 폼 진입 시 푸터(취소/저장) 분리', () => {
|
||||
const { container } = render(
|
||||
<DataSourcesPanel raw={rawWithOwn([])} onChange={vi.fn()} t={t} onClose={vi.fn()} />,
|
||||
);
|
||||
// 헤더 존재
|
||||
expect(container.querySelector('.g7le-data-sources__header')).toBeTruthy();
|
||||
// 본문(스크롤 영역) 존재
|
||||
expect(container.querySelector('.g7le-data-sources__body')).toBeTruthy();
|
||||
// 폼 미진입 시 푸터 없음
|
||||
expect(container.querySelector('.g7le-data-sources__footer')).toBeNull();
|
||||
// 추가 폼 진입 → 푸터(취소/저장)가 본문 밖에 렌더
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
const footer = container.querySelector('.g7le-data-sources__footer');
|
||||
expect(footer).toBeTruthy();
|
||||
expect(within(footer as HTMLElement).getByTestId('g7le-data-sources-form-submit')).toBeTruthy();
|
||||
expect(within(footer as HTMLElement).getByTestId('g7le-data-sources-form-cancel')).toBeTruthy();
|
||||
// 폼 필드(id)는 본문에 렌더
|
||||
const body = container.querySelector('.g7le-data-sources__body') as HTMLElement;
|
||||
expect(within(body).getByTestId('g7le-data-sources-field-id')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 불러오기 조건 conditionSpec 전달', () => {
|
||||
// 최소 conditionRecipes — operators 1건이면 ConditionBuilder 가 빌더를 렌더한다.
|
||||
const conditionSpec = {
|
||||
conditionRecipes: {
|
||||
operators: [
|
||||
{ value: 'logged_in', label: '로그인 상태', expr: '{{currentUser?.uuid}}', params: [] },
|
||||
],
|
||||
},
|
||||
} as never;
|
||||
|
||||
it('conditionSpec 미전달 시 불러오기 조건이 "표시 조건 없음" 안내로 가린다(종전 결함 재현)', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 'products', endpoint: '/api/p' }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
// 편집 진입 — 불러오기 조건 섹션이 폼 하단에 노출.
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
expect(screen.getByTestId('g7le-ds-loadcondition')).toBeInTheDocument();
|
||||
// conditionSpec 미전달 → operators 0 → no_recipes 안내(빌더 미렌더).
|
||||
expect(screen.getByTestId('g7le-condition-no-recipes')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-condition-builder')).toBeNull();
|
||||
});
|
||||
|
||||
it('conditionSpec 전달 시 불러오기 조건이 조건 빌더로 렌더된다(③ 수정)', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 'products', endpoint: '/api/p' }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
conditionSpec={conditionSpec}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
expect(screen.getByTestId('g7le-ds-loadcondition')).toBeInTheDocument();
|
||||
// operators 1건 → 빌더 렌더(no_recipes 안내가 사라짐).
|
||||
expect(screen.getByTestId('g7le-condition-builder')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-condition-no-recipes')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 요청 파라미터 블럭(키-값)', () => {
|
||||
/** 블럭 모드 첫 행의 키/값 input 을 testid prefix 로 찾는다(rowId 동적). */
|
||||
function firstParamKeyInput(): HTMLElement {
|
||||
return document.querySelector('[data-testid^="g7le-ds-params-kv-key-"]') as HTMLElement;
|
||||
}
|
||||
function firstParamValueInput(): HTMLElement {
|
||||
return document.querySelector('[data-testid^="g7le-ds-params-kv-value-"][data-testid$="-input"]') as HTMLElement;
|
||||
}
|
||||
|
||||
it('편집 시 기존 params 객체가 키-값 행으로 노출(raw textarea 아님)', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 'memos', params: { page: '{{query.page}}', per_page: 10 } }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
// 블럭 모드(키-값 칩 에디터)가 기본 — raw textarea 가 아니다.
|
||||
expect(document.querySelector('[data-testid="g7le-ds-params-kv"]')).toBeTruthy();
|
||||
const keys = Array.from(document.querySelectorAll('[data-testid^="g7le-ds-params-kv-key-"]')).map(
|
||||
(el) => (el as HTMLInputElement).value,
|
||||
);
|
||||
expect(keys).toEqual(['page', 'per_page']);
|
||||
});
|
||||
|
||||
it('블럭 모드 키-값 입력 → params 객체로 저장(숫자 리터럴 복원)', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={onChange} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'src' } });
|
||||
// 행 추가 → 키/값 입력.
|
||||
fireEvent.click(screen.getByTestId('g7le-ds-params-kv-add'));
|
||||
fireEvent.change(firstParamKeyInput(), { target: { value: 'per_page' } });
|
||||
fireEvent.change(firstParamValueInput(), { target: { value: '10' } });
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect(own[0].params).toEqual({ per_page: 10 });
|
||||
});
|
||||
|
||||
it('중첩 객체 값 params 는 raw(코드) 모드로 시작', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 'nested', params: { filter: { a: 1 } } }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
// 중첩값 → 평탄화 불가 → raw JSON textarea(키-값 블럭 아님).
|
||||
const params = screen.getByTestId('g7le-data-sources-field-params') as HTMLTextAreaElement;
|
||||
expect(params.tagName).toBe('TEXTAREA');
|
||||
expect(params.value).toContain('filter');
|
||||
});
|
||||
});
|
||||
|
||||
// 기본값(fallback) — 재귀 블럭 편집기(InitialStateValueEditor) 재사용 (중첩도
|
||||
// 블럭으로, raw JSON 모드 제거, 레이아웃 편집기 블럭 전면 도입 맥락). 중복 컴포넌트 0 — 초기 상태 탭과
|
||||
// 동일 위젯. 문자열 리프는 DataChipValueInput(표현식·데이터칩). testid 접두 = g7le-initstate-*-fallback*.
|
||||
describe('DataSourcesPanel — 기본값(fallback) 재귀 블럭', () => {
|
||||
it('fallback 미지정 → 추가 버튼, 클릭 시 재귀 블럭 편집기 노출', () => {
|
||||
render(<DataSourcesPanel raw={rawWithOwn([{ id: 's' }])} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-field-fallback-add')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-field-fallback-add'));
|
||||
// 재귀 블럭 편집기(InitialStateValueEditor) — 값 종류 select + 하위 키 추가. raw JSON textarea 없음.
|
||||
expect(screen.getByTestId('g7le-data-sources-field-fallback')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-initstate-type-fallback')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-ds-fallback-raw')).toBeNull();
|
||||
expect(document.querySelector('[data-testid="g7le-ds-fallback-kv"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('[회귀] 중첩 객체 fallback 은 raw JSON 아니라 재귀 블럭(중첩 키)으로 노출', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 's', fallback: { reviews: { data: [], meta: { total: 0 } } } }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
// raw JSON textarea 가 더 이상 없다(중첩이라도 블럭으로).
|
||||
expect(screen.queryByTestId('g7le-ds-fallback-raw')).toBeNull();
|
||||
// 루트 객체 + 중첩 키가 재귀 블럭으로 — fallback.reviews, fallback.reviews.data, ...meta.total.
|
||||
expect(screen.getByTestId('g7le-initstate-type-fallback')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-initstate-type-fallback.reviews')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-initstate-type-fallback.reviews.data')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-initstate-type-fallback.reviews.meta.total')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('[회귀] 중첩 객체 fallback 저장 → 구조 보존(블럭 편집이 raw 와 동등)', () => {
|
||||
const onChange = vi.fn();
|
||||
const fallback = { reviews: { data: [], meta: { total: 0 } } };
|
||||
render(
|
||||
<DataSourcesPanel raw={rawWithOwn([{ id: 's', fallback }])} onChange={onChange} t={t} onClose={vi.fn()} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
// 편집 없이 저장 → 중첩 구조 무손실 라운드트립.
|
||||
expect(own[0].fallback).toEqual(fallback);
|
||||
});
|
||||
|
||||
it('문자열 리프는 데이터칩 입력기(표현식/데이터칩 1급)', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 's', fallback: { status: 'ready' } }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
// status 리프(문자열) = DataChipValueInput(평문 input testid).
|
||||
expect(screen.getByTestId('g7le-initstate-value-fallback.status-input')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('제거 시 저장 페이로드에서 fallback 키 삭제', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 's', fallback: { data: [] } }])}
|
||||
onChange={onChange}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
expect(screen.getByTestId('g7le-data-sources-field-fallback')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-field-fallback-clear'));
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[0][1];
|
||||
expect('fallback' in own[0]).toBe(false);
|
||||
});
|
||||
|
||||
it('JSON 미리보기는 [미리보기 ▾] 토글(기본 접힘)', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 's', fallback: { data: { data: [], meta: { total: 0 } } } }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
const toggle = screen.getByTestId('g7le-ds-fallback-preview-toggle');
|
||||
expect(toggle).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-ds-fallback-preview')).toBeNull();
|
||||
fireEvent.click(toggle);
|
||||
const preview = screen.getByTestId('g7le-ds-fallback-preview');
|
||||
expect(preview).toBeInTheDocument();
|
||||
expect(preview.textContent).toContain('meta');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 요청 파라미터 JSON 프리뷰', () => {
|
||||
it('params 행이 있으면 결과 JSON 프리뷰가 노출된다', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([{ id: 's', params: { page: '{{query.page}}' } }])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-edit'));
|
||||
// 미리보기는 [미리보기 ▾] 토글로.
|
||||
const toggle = screen.getByTestId('g7le-ds-params-preview-toggle');
|
||||
expect(toggle).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-ds-params-preview')).toBeNull();
|
||||
fireEvent.click(toggle);
|
||||
const preview = screen.getByTestId('g7le-ds-params-preview');
|
||||
expect(preview).toBeInTheDocument();
|
||||
expect(preview.textContent).toContain('{{query.page}}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 엔드포인트 데이터칩 입력', () => {
|
||||
it('엔드포인트는 평문 input 이 아니라 데이터칩 입력기로 렌더', () => {
|
||||
render(<DataSourcesPanel raw={rawWithOwn([])} onChange={vi.fn()} t={t} onClose={vi.fn()} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
// DataChipValueInput 컨테이너 + 평문 입력 leaf 존재(검색 피커 포함).
|
||||
expect(screen.getByTestId('g7le-data-sources-field-endpoint')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-ds-endpoint-input')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DataSourcesPanel — 신규 추가 시 불러오기 조건 저장', () => {
|
||||
const conditionSpec = {
|
||||
conditionRecipes: {
|
||||
operators: [{ value: 'logged_in', label: '로그인', expr: '{{currentUser?.uuid}}', params: [] }],
|
||||
},
|
||||
} as never;
|
||||
|
||||
it('신규 추가 폼에서도 불러오기 조건 빌더가 동작(draft.if 일원화)', () => {
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([])}
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
conditionSpec={conditionSpec}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
// 신규(add) 상태에서도 조건 빌더가 렌더되고(종전엔 own[index] 없어 빈 채로),
|
||||
// 절 추가 버튼이 존재한다(draft.if 로 저장 경로 확보).
|
||||
expect(screen.getByTestId('g7le-ds-loadcondition')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-condition-builder')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-condition-add-and')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('신규 추가 시 조건 절을 추가하면 if 가 entry 에 저장', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<DataSourcesPanel
|
||||
raw={rawWithOwn([])}
|
||||
onChange={onChange}
|
||||
t={t}
|
||||
onClose={vi.fn()}
|
||||
conditionSpec={conditionSpec}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-add'));
|
||||
fireEvent.change(screen.getByTestId('g7le-data-sources-field-id'), { target: { value: 'gated' } });
|
||||
// 조건 절 추가 → draft.if 채워짐.
|
||||
fireEvent.click(screen.getByTestId('g7le-condition-add-and'));
|
||||
fireEvent.click(screen.getByTestId('g7le-data-sources-form-submit'));
|
||||
const own = onChange.mock.calls[onChange.mock.calls.length - 1][1];
|
||||
const saved = own.find((d: any) => d.id === 'gated');
|
||||
expect(typeof saved.if).toBe('string');
|
||||
expect(saved.if).toContain('currentUser');
|
||||
});
|
||||
});
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* DndCanvasLayer.modalConfine.test.tsx — 모달/반복항목 편집 모드 드래그 핸들 편집루트 confine
|
||||
*
|
||||
*
|
||||
* 모달 편집은 호스트 전체를 인플레이스로 렌더하되 모달 노드(editableRootPath)와 그 자손만
|
||||
* 편집 가능하다. modal 모드의 호스트 노드는 classifyLockKind 가 none(확장만 잠금)이라 종전엔
|
||||
* 딤(잠긴 호스트) 영역까지 드래그 핸들이 만들어졌다.
|
||||
* 편집 루트 confine 으로 딤 노드 핸들 생성을 차단한다.
|
||||
*
|
||||
* 별도 파일로 둔 이유: 공유 describe 블록의 getBoundingClientRect 스파이 상호 간섭으로 nested
|
||||
* path 핸들 측정이 불안정했다(같은 시나리오가 격리 파일에선 통과). getComputedStyle 을 명시
|
||||
* 모킹해 측정 안정화.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import { DndCanvasLayer } from '../../components/DndCanvasLayer';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
import type { NestingSpec } from '../../spec/specTypes';
|
||||
|
||||
const NESTING: NestingSpec = {
|
||||
draggable: ['Div', 'Span', 'Button'],
|
||||
containers: { Div: { accepts: ['Div', 'Span', 'Button'] } },
|
||||
};
|
||||
|
||||
interface Rect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
function domRect(r: Rect): DOMRect {
|
||||
return {
|
||||
...r,
|
||||
right: r.left + r.width,
|
||||
bottom: r.top + r.height,
|
||||
x: r.left,
|
||||
y: r.top,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect;
|
||||
}
|
||||
|
||||
function buildFrame(children: Array<{ path: string; rect: Rect }>): HTMLElement {
|
||||
const frame = document.createElement('div');
|
||||
vi.spyOn(frame, 'getBoundingClientRect').mockReturnValue(
|
||||
domRect({ left: 0, top: 0, width: 400, height: 400 })
|
||||
);
|
||||
for (const c of children) {
|
||||
const el = document.createElement('div');
|
||||
el.dataset.editorPath = c.path;
|
||||
el.setAttribute('data-editor-path', c.path);
|
||||
vi.spyOn(el, 'getBoundingClientRect').mockReturnValue(domRect(c.rect));
|
||||
frame.appendChild(el);
|
||||
}
|
||||
// jsdom 은 레이아웃 엔진이 없어 getComputedStyle 기본값이 노드별 차이를 못 줘 nested 핸들
|
||||
// 측정이 불안정 — block 으로 명시 모킹(measureOverlay/boxIntersectsFrame 안정화).
|
||||
vi.spyOn(window, 'getComputedStyle').mockReturnValue({
|
||||
display: 'block',
|
||||
flexDirection: '',
|
||||
flexWrap: '',
|
||||
} as unknown as CSSStyleDeclaration);
|
||||
document.body.appendChild(frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
function handleIds(): string[] {
|
||||
return Array.from(document.querySelectorAll('[data-testid^="g7le-dnd-handle"]')).map((h) =>
|
||||
h.getAttribute('data-testid')!
|
||||
);
|
||||
}
|
||||
|
||||
describe('DndCanvasLayer — 모달 편집 편집루트 confine', () => {
|
||||
it('딤(편집루트 밖 호스트) 노드는 핸들 미렌더, 모달 노드 자손만 핸들', () => {
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'host_dim', children: [{ name: 'Span', id: 'dim_child' }] }, // path 0 = 딤
|
||||
{ name: 'Div', id: 'modal', children: [{ name: 'Button', id: 'modal_btn' }] }, // path 1 = 모달(편집 대상)
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '0.children.0', rect: { left: 0, top: 0, width: 400, height: 50 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
{ path: '1.children.0', rect: { left: 0, top: 100, width: 400, height: 50 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="modal"
|
||||
editableRootPath={[1]}
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
const ids = handleIds();
|
||||
// 딤(호스트, path 0) 및 그 자식 → 핸들 없음(편집 루트 밖).
|
||||
expect(ids).not.toContain('g7le-dnd-handle-0');
|
||||
expect(ids).not.toContain('g7le-dnd-handle-0.children.0');
|
||||
// 모달 노드 자손(path 1.children.0) → 핸들 있음(편집 루트 내부 — 개별 편집 대상).
|
||||
expect(ids).toContain('g7le-dnd-handle-1.children.0');
|
||||
});
|
||||
|
||||
it('route 모드는 confine 미적용 — 전 노드 핸들 (회귀 가드)', () => {
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'a', children: [{ name: 'Span', id: 'a_child' }] },
|
||||
{ name: 'Div', id: 'b' },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '0.children.0', rect: { left: 0, top: 0, width: 400, height: 50 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
const ids = handleIds();
|
||||
expect(ids).toContain('g7le-dnd-handle-0');
|
||||
expect(ids).toContain('g7le-dnd-handle-1');
|
||||
});
|
||||
});
|
||||
+435
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* DndCanvasLayer.test.tsx — 드래그 핸들 렌더 가드
|
||||
*
|
||||
* - draggable + 비잠금 노드만 드래그 핸들 렌더
|
||||
* - data_bound / base 출처 노드는 핸들 미렌더
|
||||
* - 핸들 클릭 시 onSelectPath 위임
|
||||
*
|
||||
* dnd-kit DndContext 마운트 + frame DOM 기하 모킹.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { DndCanvasLayer } from '../../components/DndCanvasLayer';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
import type { NestingSpec } from '../../spec/specTypes';
|
||||
|
||||
const NESTING: NestingSpec = {
|
||||
draggable: ['Div', 'Span'],
|
||||
containers: { Div: { accepts: ['Div', 'Span'] } },
|
||||
};
|
||||
|
||||
interface Rect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
function domRect(r: Rect): DOMRect {
|
||||
return {
|
||||
...r,
|
||||
right: r.left + r.width,
|
||||
bottom: r.top + r.height,
|
||||
x: r.left,
|
||||
y: r.top,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect;
|
||||
}
|
||||
|
||||
function buildFrame(children: Array<{ path: string; rect: Rect }>): HTMLElement {
|
||||
const frame = document.createElement('div');
|
||||
vi.spyOn(frame, 'getBoundingClientRect').mockReturnValue(
|
||||
domRect({ left: 0, top: 0, width: 400, height: 400 })
|
||||
);
|
||||
for (const c of children) {
|
||||
const el = document.createElement('div');
|
||||
el.dataset.editorPath = c.path;
|
||||
el.setAttribute('data-editor-path', c.path);
|
||||
vi.spyOn(el, 'getBoundingClientRect').mockReturnValue(domRect(c.rect));
|
||||
frame.appendChild(el);
|
||||
}
|
||||
document.body.appendChild(frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
describe('DndCanvasLayer — 드래그 핸들 렌더 가드', () => {
|
||||
it('draggable 노드에만 핸들 렌더', () => {
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'a' },
|
||||
{ name: 'Form', id: 'f' }, // not draggable
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('핸들 더블클릭 → onRequestInlineEdit(path) forward', () => {
|
||||
// 드래그 핸들이 노드 박스를 pointerEvents:auto 로 덮으므로 실제 마우스 더블클릭은
|
||||
// 핸들에 먼저 맞는다. 핸들이 더블클릭을 인라인 편집 진입점으로 forward 해야 한다.
|
||||
const components: EditorNode[] = [{ name: 'Div', id: 'h', text: '제목' }];
|
||||
const frame = buildFrame([{ path: '0', rect: { left: 0, top: 0, width: 400, height: 40 } }]);
|
||||
const onRequestInlineEdit = vi.fn();
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
onRequestInlineEdit={onRequestInlineEdit}
|
||||
/>
|
||||
);
|
||||
const handle = screen.getByTestId('g7le-dnd-handle-0');
|
||||
fireEvent.doubleClick(handle);
|
||||
expect(onRequestInlineEdit).toHaveBeenCalledWith('0');
|
||||
});
|
||||
|
||||
it('data_bound 노드도 드래그 핸들 렌더 — 선택/이동 허용', () => {
|
||||
// 명세: data_bound 노드는 인라인 텍스트 편집만 불가하고 선택·드래그·구조
|
||||
// 편집은 허용. 자신이 데이터 바인딩(`{{}}`)인 노드(상품 이미지 갤러리 등 composite
|
||||
// 포함)도 위치 이동은 정당한 구조 편집이므로 핸들이 렌더되어야 한다.
|
||||
// (종전: data_bound 를 잠금 취급해 핸들 미렌더 → 선택/이동 불가 결함.)
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'a', text: '{{user.name}}' }, // 자신 바인딩 = data_bound
|
||||
{ name: 'Div', id: 'b' },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
// data_bound 노드(0)도 핸들 렌더 — 드래그/선택 가능.
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('반복(iteration) 인스턴스 내부 노드는 핸들 미렌더 — 개별 인스턴스 직접 편집 금지', () => {
|
||||
// 자신 바인딩 data_bound 는 허용하되, **조상이 iteration** 인 펼침 인스턴스 내부
|
||||
// 노드는 핸들 미렌더(묶음 단위 편집은 가상 묶음/iteration_item 모드).
|
||||
// 트리: List(iteration 정의) → 펼침 인스턴스(.iteration.0)는 DOM 에서 List 자식으로
|
||||
// 렌더되며 조상에 iteration 노드가 있다.
|
||||
const components: EditorNode[] = [
|
||||
{
|
||||
name: 'Div',
|
||||
id: 'list',
|
||||
iteration: { source: '{{items}}' } as EditorNode['iteration'],
|
||||
children: [{ name: 'Span', id: 'cell' }],
|
||||
},
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 200 } },
|
||||
]);
|
||||
// 펼침 인스턴스 + 그 내부 자식을 DOM 에 추가 (DynamicRenderer 가 .iteration.N 으로 펼침)
|
||||
const listEl = frame.querySelector('[data-editor-path="0"]')!;
|
||||
for (const [p, top] of [['0.iteration.0', 0], ['0.iteration.1', 50]] as const) {
|
||||
const inst = document.createElement('div');
|
||||
inst.dataset.editorPath = p;
|
||||
inst.setAttribute('data-editor-path', p);
|
||||
vi.spyOn(inst, 'getBoundingClientRect').mockReturnValue(domRect({ left: 0, top, width: 400, height: 50 }));
|
||||
listEl.appendChild(inst);
|
||||
const cell = document.createElement('span');
|
||||
cell.dataset.editorPath = `${p}.children.0`;
|
||||
cell.setAttribute('data-editor-path', `${p}.children.0`);
|
||||
vi.spyOn(cell, 'getBoundingClientRect').mockReturnValue(domRect({ left: 5, top: top + 5, width: 200, height: 20 }));
|
||||
inst.appendChild(cell);
|
||||
}
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
// 펼침 인스턴스(0.iteration.0) 및 그 내부 자식 — 개별 핸들 미렌더(조상 iteration).
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0.iteration.0')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0.iteration.0.children.0')).not.toBeInTheDocument();
|
||||
// 대신 **이터레이션 원본 노드(0)** 의 가상 묶음 핸들이 1개 생성.
|
||||
const groupHandle = screen.queryByTestId('g7le-dnd-handle-0');
|
||||
expect(groupHandle, '이터레이션 가상 묶음 핸들이 원본 path 로 생성되어야 함').toBeInTheDocument();
|
||||
expect(groupHandle?.getAttribute('data-dnd-iteration-group')).toBe('true');
|
||||
// 묶음 box = 인스턴스 union (top 0~100) — height 100(인스턴스 2개 × 50).
|
||||
expect(groupHandle?.style.height).toBe('100px');
|
||||
});
|
||||
|
||||
it('frame 밖으로 클리핑된 노드(닫힌 모바일 드로어 등)는 핸들 미렌더', () => {
|
||||
// 닫힌 모바일 드로어(`fixed translate-x-full`)는 frame 밖으로 밀려 overflow:hidden
|
||||
// 으로 시각적으로 가려지지만 getBoundingClientRect 좌표는 그대로다. 가려진 노드
|
||||
// 자리에 드래그 핸들/점선이 편집기 회색 배경에 노출되던 회귀를 잠근다.
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'visible' },
|
||||
{ name: 'Div', id: 'clipped-right' }, // frame(width 400) 우측 밖
|
||||
{ name: 'Div', id: 'clipped-below' }, // frame(height 400) 하단 밖
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '1', rect: { left: 460, top: 0, width: 320, height: 400 } }, // left ≥ 400 → 우측 밖
|
||||
{ path: '2', rect: { left: 0, top: 460, width: 400, height: 100 } }, // top ≥ 400 → 하단 밖
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-2')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('실제 잠금(base 출처) 노드는 여전히 핸들 미렌더', () => {
|
||||
// data_bound 와 달리 base/partial/extension 출처 잠금은 핸들 미렌더 유지(회귀 가드).
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'base', __source: { kind: 'base' } },
|
||||
{ name: 'Div', id: 'own', __source: { kind: 'route' } },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('base 출처 노드는 route 모드에서 핸들 미렌더', () => {
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'base', __source: { kind: 'base' } },
|
||||
{ name: 'Div', id: 'own', __source: { kind: 'route' } },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-0')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-dnd-handle-1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('핸들 클릭 시 onSelectPath 위임', () => {
|
||||
const onSelect = vi.fn();
|
||||
const components: EditorNode[] = [{ name: 'Div', id: 'a' }];
|
||||
const frame = buildFrame([{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } }]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={onSelect}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-dnd-handle-0'));
|
||||
expect(onSelect).toHaveBeenCalledWith('0');
|
||||
});
|
||||
|
||||
it('모든 핸들은 드래그 가능(grab) + z 깊이순 — 클릭/드래그 시작 모두 깊은 핸들 우선 (결함 2)', () => {
|
||||
// 부모 Div(0) 안에 자식 Div(0.children.0). 둘 다 draggable.
|
||||
// 핸들 비활성화로 선택 기준 드래그를 구현하면 자손이 덮은 영역에서 부모 드래그가
|
||||
// 막히므로, 모든 핸들은 드래그 가능(grab)하게 둔다. "선택 기준 드래그"는
|
||||
// useCanvasDnd.onDragStart 의 드래그 path 치환으로 처리(별도 hook 테스트).
|
||||
// z 는 깊이순 — 깊은(자식) 핸들이 위여야 클릭/드래그 시작이 가장 구체적 요소에 도달.
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'parent', children: [{ name: 'Div', id: 'child' }] },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 200 } },
|
||||
]);
|
||||
const parentEl = frame.querySelector('[data-editor-path="0"]')!;
|
||||
const childEl = document.createElement('div');
|
||||
childEl.dataset.editorPath = '0.children.0';
|
||||
childEl.setAttribute('data-editor-path', '0.children.0');
|
||||
vi.spyOn(childEl, 'getBoundingClientRect').mockReturnValue(
|
||||
domRect({ left: 20, top: 20, width: 200, height: 60 })
|
||||
);
|
||||
parentEl.appendChild(childEl);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
selectedPath="0"
|
||||
/>
|
||||
);
|
||||
const parentHandle = screen.getByTestId('g7le-dnd-handle-0');
|
||||
const childHandle = screen.getByTestId('g7le-dnd-handle-0.children.0');
|
||||
// 선택 여부와 무관하게 둘 다 드래그 가능(grab) — 핸들 비활성화 안 함.
|
||||
expect(parentHandle.style.cursor).toBe('grab');
|
||||
expect(childHandle.style.cursor).toBe('grab');
|
||||
// z 는 깊이순 — 자식(depth1=21)이 부모(depth0=20)보다 위.
|
||||
expect(Number(parentHandle.style.zIndex)).toBe(20);
|
||||
expect(Number(childHandle.style.zIndex)).toBe(21);
|
||||
expect(Number(childHandle.style.zIndex)).toBeGreaterThan(Number(parentHandle.style.zIndex));
|
||||
expect(parentHandle.style.pointerEvents).toBe('auto');
|
||||
expect(childHandle.style.pointerEvents).toBe('auto');
|
||||
});
|
||||
|
||||
it('자손 핸들 클릭 시 자손 path 로 재선택 위임 (자식 재선택 가능)', () => {
|
||||
const onSelect = vi.fn();
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'parent', children: [{ name: 'Div', id: 'child' }] },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 200 } },
|
||||
]);
|
||||
const parentEl = frame.querySelector('[data-editor-path="0"]')!;
|
||||
const childEl = document.createElement('div');
|
||||
childEl.dataset.editorPath = '0.children.0';
|
||||
childEl.setAttribute('data-editor-path', '0.children.0');
|
||||
vi.spyOn(childEl, 'getBoundingClientRect').mockReturnValue(
|
||||
domRect({ left: 20, top: 20, width: 200, height: 60 })
|
||||
);
|
||||
parentEl.appendChild(childEl);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={onSelect}
|
||||
selectedPath="0"
|
||||
/>
|
||||
);
|
||||
// 부모가 선택된 상태에서 자손 핸들 클릭 → 자손 재선택 (드래그 비활성이어도 클릭은 발화)
|
||||
fireEvent.click(screen.getByTestId('g7le-dnd-handle-0.children.0'));
|
||||
expect(onSelect).toHaveBeenCalledWith('0.children.0');
|
||||
});
|
||||
|
||||
it('선택이 없으면 모든 draggable 핸들이 활성(첫 클릭/드래그 가능)', () => {
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'parent', children: [{ name: 'Div', id: 'child' }] },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 200 } },
|
||||
]);
|
||||
const parentEl = frame.querySelector('[data-editor-path="0"]')!;
|
||||
const childEl = document.createElement('div');
|
||||
childEl.dataset.editorPath = '0.children.0';
|
||||
childEl.setAttribute('data-editor-path', '0.children.0');
|
||||
vi.spyOn(childEl, 'getBoundingClientRect').mockReturnValue(
|
||||
domRect({ left: 20, top: 20, width: 200, height: 60 })
|
||||
);
|
||||
parentEl.appendChild(childEl);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
// 선택 없음 → 둘 다 drag 활성(grab). 자손도 dragDisabled 아님.
|
||||
expect(screen.getByTestId('g7le-dnd-handle-0').style.cursor).toBe('grab');
|
||||
expect(screen.getByTestId('g7le-dnd-handle-0.children.0').style.cursor).toBe('grab');
|
||||
});
|
||||
|
||||
it('자손이 아닌 형제는 선택 무관하게 드래그 활성', () => {
|
||||
// 선택='0' 일 때 형제 '1' 은 자손이 아니므로 드래그 가능해야.
|
||||
const components: EditorNode[] = [
|
||||
{ name: 'Div', id: 'a' },
|
||||
{ name: 'Div', id: 'b' },
|
||||
];
|
||||
const frame = buildFrame([
|
||||
{ path: '0', rect: { left: 0, top: 0, width: 400, height: 100 } },
|
||||
{ path: '1', rect: { left: 0, top: 100, width: 400, height: 100 } },
|
||||
]);
|
||||
render(
|
||||
<DndCanvasLayer
|
||||
frameEl={frame}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={components}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
selectedPath="0"
|
||||
/>
|
||||
);
|
||||
expect(screen.getByTestId('g7le-dnd-handle-1').style.cursor).toBe('grab');
|
||||
});
|
||||
|
||||
it('frameEl 이 null 이면 렌더 안 함', () => {
|
||||
const { container } = render(
|
||||
<DndCanvasLayer
|
||||
frameEl={null}
|
||||
nesting={NESTING}
|
||||
editMode="route"
|
||||
components={[{ name: 'Div', id: 'a' }]}
|
||||
patchLayout={vi.fn()}
|
||||
pushHistory={vi.fn()}
|
||||
onSelectPath={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* EditEntryFab 컴포넌트 테스트
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { EditEntryFab } from '../../components/EditEntryFab';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function renderWithTranslation(ui: React.ReactElement): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
{ui}
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditEntryFab — 표시 조건', () => {
|
||||
it('인증 + 권한 보유 → 일반 렌더 URL 에서 렌더', () => {
|
||||
renderWithTranslation(
|
||||
<EditEntryFab
|
||||
templateIdentifier="sirsoft-basic"
|
||||
pathname="/"
|
||||
isAuthenticated
|
||||
hasLayoutEditPermission
|
||||
currentRoutePath="/"
|
||||
openWindow={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-edit-entry-fab')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('비로그인 → 미렌더', () => {
|
||||
renderWithTranslation(
|
||||
<EditEntryFab
|
||||
templateIdentifier="sirsoft-basic"
|
||||
pathname="/"
|
||||
isAuthenticated={false}
|
||||
hasLayoutEditPermission
|
||||
currentRoutePath="/"
|
||||
openWindow={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-edit-entry-fab')).toBeNull();
|
||||
});
|
||||
|
||||
it('권한 없음 → 미렌더', () => {
|
||||
renderWithTranslation(
|
||||
<EditEntryFab
|
||||
templateIdentifier="sirsoft-basic"
|
||||
pathname="/"
|
||||
isAuthenticated
|
||||
hasLayoutEditPermission={false}
|
||||
currentRoutePath="/"
|
||||
openWindow={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-edit-entry-fab')).toBeNull();
|
||||
});
|
||||
|
||||
it('편집 모드 URL → 권한 보유자도 미렌더', () => {
|
||||
renderWithTranslation(
|
||||
<EditEntryFab
|
||||
templateIdentifier="sirsoft-basic"
|
||||
pathname="/admin/layout-editor/sirsoft-basic"
|
||||
isAuthenticated
|
||||
hasLayoutEditPermission
|
||||
currentRoutePath="/"
|
||||
openWindow={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-edit-entry-fab')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditEntryFab — 클릭 동작', () => {
|
||||
it('클릭 → openWindow 가 진입 URL 로 호출됨', () => {
|
||||
const openWindow = vi.fn();
|
||||
renderWithTranslation(
|
||||
<EditEntryFab
|
||||
templateIdentifier="sirsoft-basic"
|
||||
pathname="/board/list"
|
||||
isAuthenticated
|
||||
hasLayoutEditPermission
|
||||
currentRoutePath="/board/list"
|
||||
openWindow={openWindow}
|
||||
/>,
|
||||
);
|
||||
|
||||
const fab = screen.getByTestId('g7le-edit-entry-fab');
|
||||
fireEvent.click(fab);
|
||||
|
||||
expect(openWindow).toHaveBeenCalledOnce();
|
||||
expect(openWindow).toHaveBeenCalledWith(
|
||||
'/admin/layout-editor/sirsoft-basic?route=%2Fboard%2Flist',
|
||||
);
|
||||
});
|
||||
});
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* EditorCanvasOverlay — undo/redo 이력 통합 회귀 테스트
|
||||
*
|
||||
*
|
||||
* 결함 회고:
|
||||
* - handleInsert/handleDuplicate/handleDelete 가 "변경 *전* 스냅샷" 을 push
|
||||
* - 문서 로드 시 baseline push 없음 → 첫 변경 후 cursor=0 → canUndo 영구 false
|
||||
*
|
||||
* 본 테스트는 useEditorHistory 를 spy/mock 으로 감싸 EditorCanvasOverlay 의
|
||||
* push 호출 페이로드가 "변경 *후* 컴포넌트 트리" 인지 직접 검증한다. 또한
|
||||
* window.__g7LayoutEditorHistory 가 canUndo=true 로 노출되어 Toolbar 가 활성됨을
|
||||
* 보장한다.
|
||||
*
|
||||
* 본 테스트는 DOM frame 없이 (frameEl=null) overlay 의 hook 동작만 검증한다 —
|
||||
* frameEl null 일 때도 useEditorHistory baseline push + handleInsert 경로는 그대로
|
||||
* 동작해야 한다 (overlay 가 return null 이라도 hook 들은 그 위에서 호출됨).
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, act, waitFor } from '@testing-library/react';
|
||||
import { EditorCanvasOverlay } from '../../components/EditorCanvasOverlay';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { LayoutDocumentProvider } from '../../LayoutDocumentContext';
|
||||
import { EditorModalProvider } from '../../EditorModalContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import type { UseLayoutDocumentResult, LoadedLayoutDocument } from '../../hooks/useLayoutDocument';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
function buildDocCtx(initialComponents: EditorNode[]): {
|
||||
ctx: UseLayoutDocumentResult;
|
||||
getCurrentComponents: () => EditorNode[];
|
||||
} {
|
||||
let document: LoadedLayoutDocument = {
|
||||
layoutName: 'home',
|
||||
raw: { components: initialComponents },
|
||||
lockVersion: 1,
|
||||
};
|
||||
const ctx: UseLayoutDocumentResult = {
|
||||
document,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
isDirty: false,
|
||||
saveSuccessCounter: 0,
|
||||
reload: async () => {},
|
||||
patchLayout: (patcher) => {
|
||||
const current = (document.raw.components as EditorNode[]) ?? [];
|
||||
const next = patcher(current);
|
||||
document = { ...document, raw: { ...document.raw, components: next } };
|
||||
// 후속 read 가 동일 객체 참조이도록 ctx.document 도 업데이트
|
||||
(ctx as any).document = document;
|
||||
},
|
||||
setLayoutComponents: (next) => {
|
||||
document = { ...document, raw: { ...document.raw, components: next } };
|
||||
(ctx as any).document = document;
|
||||
},
|
||||
save: async () => ({ kind: 'success', newLockVersion: 2 }),
|
||||
};
|
||||
return {
|
||||
ctx,
|
||||
getCurrentComponents: () => (document.raw.components as EditorNode[]) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function RouteSeeder({ children }: { children: React.ReactNode }): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: '/', layoutName: 'home' } });
|
||||
}, [dispatch]);
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function mountOverlay(initialComponents: EditorNode[]) {
|
||||
const { ctx, getCurrentComponents } = buildDocCtx(initialComponents);
|
||||
const engine = new TranslationEngine();
|
||||
|
||||
// 최소한의 ComponentManifest — handleInsert 호출 시 nesting 검증을 통과시키기 위한 더미.
|
||||
// 본 테스트는 외부에서 handleInsertRef 를 직접 호출하지 않고 hook 사이클만 검증하므로
|
||||
// 매니페스트 내용은 중요하지 않다.
|
||||
const manifest = { components: {} } as any;
|
||||
|
||||
const utils = render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<EditorModalProvider>
|
||||
<RouteSeeder>
|
||||
<LayoutDocumentProvider value={ctx}>
|
||||
<EditorCanvasOverlay
|
||||
frameEl={null}
|
||||
manifest={manifest}
|
||||
nesting={null}
|
||||
componentPalette={null}
|
||||
/>
|
||||
</LayoutDocumentProvider>
|
||||
</RouteSeeder>
|
||||
</EditorModalProvider>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
|
||||
return { utils, ctx, getCurrentComponents };
|
||||
}
|
||||
|
||||
describe('EditorCanvasOverlay — 이력 baseline + after 스냅샷 패턴 회귀', () => {
|
||||
beforeEach(() => {
|
||||
delete (window as any).__g7LayoutEditorHistory;
|
||||
});
|
||||
|
||||
it('문서 로드 시 baseline 이 push 되어 __g7LayoutEditorHistory 가 노출됨', async () => {
|
||||
mountOverlay([{ name: 'Header', type: 'basic' }]);
|
||||
await waitFor(() => {
|
||||
expect((window as any).__g7LayoutEditorHistory).toBeTruthy();
|
||||
});
|
||||
// baseline 만 있으면 canUndo 는 false (cursor=0) — 변경이 발생해야 true 가 된다
|
||||
expect((window as any).__g7LayoutEditorHistory?.canUndo).toBe(false);
|
||||
});
|
||||
|
||||
it('라우트 변경 시 baseline 재push (이력 라우트 단위 격리)', async () => {
|
||||
// 본 테스트는 EditorCanvasOverlay 내부 useEffect 의 layoutName 가드 회귀 방지.
|
||||
// 라우트 A → B 전환 시 history.clear + 새 baseline push 가 실행되어
|
||||
// 이전 라우트의 변경 이력이 새 라우트로 누수되지 않아야 한다.
|
||||
const { ctx, utils } = mountOverlay([{ name: 'Header', type: 'basic' }]);
|
||||
await waitFor(() => {
|
||||
expect((window as any).__g7LayoutEditorHistory).toBeTruthy();
|
||||
});
|
||||
|
||||
// ctx.document.layoutName 을 외부에서 직접 바꿔도 EditorCanvasOverlay 는
|
||||
// docCtx.document.layoutName 변화를 감지해 useEffect 가 다시 실행되어야 한다.
|
||||
act(() => {
|
||||
(ctx as any).document = {
|
||||
...ctx.document,
|
||||
layoutName: 'login',
|
||||
raw: { components: [{ name: 'LoginForm', type: 'composite' }] },
|
||||
};
|
||||
// 강제 리렌더 — Provider value 가 같은 객체라 React 재렌더가 보장되지 않으므로
|
||||
// unmount/remount 방식이 더 견고하나 본 테스트는 ctx mutation 만으로는 검증 불가.
|
||||
// 라우트 격리는 hook 단위 테스트로 검증 완료.
|
||||
});
|
||||
|
||||
// 본 케이스의 실질 검증 가치는 useEditorHistory.afterSnapshotPattern 으로 위임.
|
||||
// 본 통합 테스트는 baseline push 가 일어나 window 노출까지 도달함을 보장.
|
||||
expect(utils.container.querySelector('[data-testid="g7le-editor-canvas-overlay"]')).toBeNull();
|
||||
// frameEl=null 이므로 overlay 자체는 null 반환 — 그러나 hook 들은 모두 호출됐다는 것이
|
||||
// window.__g7LayoutEditorHistory 노출로 증명.
|
||||
});
|
||||
});
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* EditorCanvasOverlay.pick.test.tsx — 컴포넌트 영역 pick 모드 캔버스 수신부 회귀
|
||||
*
|
||||
*
|
||||
* ComponentTargetPicker.test.tsx 는 **위젯 측**(pick-request 발사 + picked 회신 수신)을
|
||||
* 잠근다. 본 테스트는 그 짝인 **캔버스 측**(EditorCanvasOverlay)을 잠근다 — D-J 결함의
|
||||
* 실제 무대는 캔버스 수신부다:
|
||||
*
|
||||
* ① pick-request 수신 → pick 모드 진입(`g7le-canvas-pick-banner` 배너 렌더).
|
||||
* ② pick 모드 중 캔버스의 id 보유 노드 클릭 → 그 노드 id 를 picked 이벤트로 회신 + 모드 종료.
|
||||
* ③ id 미부여 노드 클릭 → 회신 없음(모드 유지) — 사용자가 다른 노드를 다시 고를 수 있어야 함.
|
||||
* ④ Esc → cancelled 회신 + 모드 종료.
|
||||
* ⑤ 취소 배너 버튼 → cancelled 회신 + 모드 종료.
|
||||
* ⑥ node.props.id 와 node.id 양쪽에서 id 추출(우선순위 props.id).
|
||||
*
|
||||
* 합성 이벤트 false-negative 주의([[feedback_chrome_mcp_synthetic_events_false_negative...]]) —
|
||||
* 본 단위는 캔버스 수신 **결선 계약**(리스너 등록 위치/회신 형태/모드 전이)을 잠그고,
|
||||
* 실제 사용자 클릭 좌표 도달·핸들 가림은 라이브(Chrome MCP)가 본령으로 검증한다.
|
||||
*
|
||||
* @since engine-v1.50.0 — 캔버스 수신부 가드 (세션 D 보강)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, act, waitFor, fireEvent } from '@testing-library/react';
|
||||
import { EditorCanvasOverlay } from '../../components/EditorCanvasOverlay';
|
||||
import {
|
||||
COMPONENT_TARGET_PICK_REQUEST_EVENT,
|
||||
COMPONENT_TARGET_PICKED_EVENT,
|
||||
} from '../../components/property-controls/ComponentTargetPicker';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { LayoutDocumentProvider } from '../../LayoutDocumentContext';
|
||||
import { EditorModalProvider } from '../../EditorModalContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import type { UseLayoutDocumentResult, LoadedLayoutDocument } from '../../hooks/useLayoutDocument';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
function buildDocCtx(initialComponents: EditorNode[]): UseLayoutDocumentResult {
|
||||
let document: LoadedLayoutDocument = {
|
||||
layoutName: 'home',
|
||||
raw: { components: initialComponents },
|
||||
lockVersion: 1,
|
||||
};
|
||||
const ctx: UseLayoutDocumentResult = {
|
||||
document,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
isDirty: false,
|
||||
saveSuccessCounter: 0,
|
||||
reload: async () => {},
|
||||
patchLayout: (patcher) => {
|
||||
const current = (document.raw.components as EditorNode[]) ?? [];
|
||||
const next = patcher(current);
|
||||
document = { ...document, raw: { ...document.raw, components: next } };
|
||||
(ctx as any).document = document;
|
||||
},
|
||||
setLayoutComponents: (next) => {
|
||||
document = { ...document, raw: { ...document.raw, components: next } };
|
||||
(ctx as any).document = document;
|
||||
},
|
||||
save: async () => ({ kind: 'success', newLockVersion: 2 }),
|
||||
};
|
||||
return ctx;
|
||||
}
|
||||
|
||||
function RouteSeeder({ children }: { children: React.ReactNode }): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: '/', layoutName: 'home' } });
|
||||
}, [dispatch]);
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 실제 frame DOM 을 만들어 EditorCanvasOverlay 에 주입한다. frame 안에 `data-editor-path`
|
||||
* 노드를 심어, 그 위에서 click 을 fire 하면 overlay 의 capture 리스너(wrapper 등록)가 잡는다.
|
||||
* components prop 과 path 가 일치해야 id 추출이 동작한다(findNodeByPath(root, parseEditorPath)).
|
||||
*/
|
||||
function mountWithFrame(components: EditorNode[]): {
|
||||
frameEl: HTMLElement;
|
||||
nodeEl: (path: string) => HTMLElement;
|
||||
unmount: () => void;
|
||||
rerender: () => void;
|
||||
} {
|
||||
const ctx = buildDocCtx(components);
|
||||
const engine = new TranslationEngine();
|
||||
const manifest = { components: {} } as any;
|
||||
|
||||
// wrapper(g7le-preview-frame-wrapper) > frame(g7le-preview-frame) > 노드들.
|
||||
// overlay 는 frameEl.parentElement(=wrapper) 에 capture 리스너를 등록한다.
|
||||
const wrapper = window.document.createElement('div');
|
||||
wrapper.className = 'g7le-preview-frame-wrapper';
|
||||
const frame = window.document.createElement('div');
|
||||
frame.className = 'g7le-preview-frame';
|
||||
wrapper.appendChild(frame);
|
||||
window.document.body.appendChild(wrapper);
|
||||
|
||||
// components 의 각 인덱스를 data-editor-path 노드로 렌더(루트 직계 = "0","1",...).
|
||||
components.forEach((_, idx) => {
|
||||
const el = window.document.createElement('div');
|
||||
el.setAttribute('data-editor-path', String(idx));
|
||||
el.setAttribute('data-editor-id', String(idx));
|
||||
el.textContent = `node-${idx}`;
|
||||
frame.appendChild(el);
|
||||
});
|
||||
|
||||
let rerenderFn: () => void = () => {};
|
||||
function Harness(): React.ReactElement {
|
||||
const [, force] = React.useState(0);
|
||||
rerenderFn = () => force((v) => v + 1);
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<EditorModalProvider>
|
||||
<RouteSeeder>
|
||||
<LayoutDocumentProvider value={ctx}>
|
||||
<EditorCanvasOverlay
|
||||
frameEl={frame}
|
||||
manifest={manifest}
|
||||
nesting={null}
|
||||
componentPalette={null}
|
||||
/>
|
||||
</LayoutDocumentProvider>
|
||||
</RouteSeeder>
|
||||
</EditorModalProvider>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const utils = render(<Harness />);
|
||||
|
||||
return {
|
||||
frameEl: frame,
|
||||
nodeEl: (path: string) =>
|
||||
frame.querySelector(`[data-editor-path="${path}"]`) as HTMLElement,
|
||||
unmount: () => {
|
||||
utils.unmount();
|
||||
wrapper.remove();
|
||||
},
|
||||
rerender: () => act(() => rerenderFn()),
|
||||
};
|
||||
}
|
||||
|
||||
function fireRequest(): { requestId: string; received: Array<{ id?: string; cancelled?: boolean }> } {
|
||||
const received: Array<{ id?: string; cancelled?: boolean }> = [];
|
||||
const requestId = `pick-test-${received.length}-${'x'}`;
|
||||
const onPicked = (e: Event): void => {
|
||||
const d = (e as CustomEvent).detail;
|
||||
if (d?.requestId === requestId) received.push(d);
|
||||
};
|
||||
window.addEventListener(COMPONENT_TARGET_PICKED_EVENT, onPicked);
|
||||
act(() => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMPONENT_TARGET_PICK_REQUEST_EVENT, { detail: { requestId } }),
|
||||
);
|
||||
});
|
||||
// 핸들러 정리는 각 it 에서 검증 후 자연 GC — received 캡처가 목적.
|
||||
return { requestId, received };
|
||||
}
|
||||
|
||||
describe('EditorCanvasOverlay — 컴포넌트 영역 pick 캔버스 수신부 (D-J)', () => {
|
||||
beforeEach(() => {
|
||||
delete (window as any).__g7LayoutEditorHistory;
|
||||
window.document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('① pick-request 수신 → pick 배너 렌더', async () => {
|
||||
const h = mountWithFrame([{ name: 'Form', props: { id: 'main-form' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('② id 보유 노드 클릭 → 그 id 를 picked 회신 + 배너 사라짐(모드 종료)', async () => {
|
||||
const h = mountWithFrame([{ name: 'Form', props: { id: 'main-form' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
const { received } = fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
// 캔버스 노드(path "0") 클릭 — wrapper capture 리스너가 잡아 picked 회신.
|
||||
act(() => fireEvent.click(h.nodeEl('0')));
|
||||
expect(received.at(-1)).toMatchObject({ id: 'main-form' });
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeNull(),
|
||||
);
|
||||
// pick 회신 후 캔버스에 부수 선택이 남지 않는다("선택한 컴포넌트가
|
||||
// 선택되어 버림"). finishPick 의 clearSelection 으로 선택 오버레이(ⓘ)가 뜨지 않아야 한다.
|
||||
expect(window.document.querySelector('[data-testid="g7le-overlay-info-button"]')).toBeNull();
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('③ id 미부여 노드 클릭 → 회신 없음(모드 유지, 배너 잔존)', async () => {
|
||||
const h = mountWithFrame([{ name: 'Div' }]); // id 없음(props.id/id 둘 다 부재)
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
const { received } = fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
act(() => fireEvent.click(h.nodeEl('0')));
|
||||
// id 없는 노드 → 회신 안 함.
|
||||
expect(received.length).toBe(0);
|
||||
// 모드 유지 — 배너 잔존.
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy();
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('③-b 자동 부여 id(auto_*) 노드 클릭 → 회신 없음(직접 부여 id 만 선택 가능)', async () => {
|
||||
// 편집기/렌더러가 자동 부여한 auto_ id 는 "유저 직접 부여"가 아니므로 선택 대상에서 제외.
|
||||
const h = mountWithFrame([{ name: 'Span', props: { id: 'auto_Span_ab12cd' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
const { received } = fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
act(() => fireEvent.click(h.nodeEl('0')));
|
||||
// auto_ id → 회신 안 함(모드 유지).
|
||||
expect(received.length).toBe(0);
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy();
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('④ Esc → cancelled 회신 + 모드 종료', async () => {
|
||||
const h = mountWithFrame([{ name: 'Form', props: { id: 'main-form' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
const { received } = fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
});
|
||||
expect(received.at(-1)).toMatchObject({ cancelled: true });
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeNull(),
|
||||
);
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('⑤ 취소 배너 버튼 → cancelled 회신 + 모드 종료', async () => {
|
||||
const h = mountWithFrame([{ name: 'Form', props: { id: 'main-form' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
const { received } = fireRequest();
|
||||
const cancelBtn = await waitFor(() => {
|
||||
const b = window.document.querySelector('[data-testid="g7le-canvas-pick-cancel"]');
|
||||
expect(b).toBeTruthy();
|
||||
return b as HTMLElement;
|
||||
});
|
||||
act(() => fireEvent.click(cancelBtn));
|
||||
expect(received.at(-1)).toMatchObject({ cancelled: true });
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeNull(),
|
||||
);
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('⑥ node.id(레거시 위치)에서도 id 추출 — props.id 부재 시 폴백', async () => {
|
||||
const h = mountWithFrame([{ name: 'Form', id: 'legacy-id' } as never]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
const { received } = fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
act(() => fireEvent.click(h.nodeEl('0')));
|
||||
expect(received.at(-1)).toMatchObject({ id: 'legacy-id' });
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
// ── pick 모드 시각 분리 ──
|
||||
// pick 모드에서는 일반 선택 어포던스(ⓘ/리사이즈/+요소추가/↑타입칩/선택 실선)를 숨기고,
|
||||
// pick 전용 hover(id 보유=강조, id 없음=불가 안내)만 둔다.
|
||||
|
||||
it('⑦ pick 모드 중에는 일반 선택 어포던스(ⓘ·+요소추가)가 DOM 에 없다(영역 선택 전용)', async () => {
|
||||
// ElementOverlay/InsertionAffordances 를 pick 모드면 `!pickRequestId` 가드로 통째 미렌더.
|
||||
// jsdom 에선 일반 모드에서도 selectedBox 측정(rect=0)이 안 돼 어포던스가 안 뜨므로, 본 단위는
|
||||
// "pick 모드에서 어포던스 컨테이너가 확실히 없음"을 잠그고, "선택돼 있던 어포던스가 pick 진입 시
|
||||
// 사라짐"의 시각 확인은 라이브가 담당한다.
|
||||
const h = mountWithFrame([{ name: 'Form', props: { id: 'main-form' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
expect(window.document.querySelector('[data-testid="g7le-overlay-info-button"]')).toBeNull();
|
||||
expect(window.document.querySelector('[data-testid="g7le-insertion-affordances"]')).toBeNull();
|
||||
h.unmount();
|
||||
});
|
||||
|
||||
it('⑧ pick 종료(취소) 후 일반 선택 어포던스 컨테이너(InsertionAffordances)가 복귀한다', async () => {
|
||||
// pick 모드 가드(`!pickRequestId`)가 모드 종료 시 풀려 일반 편집 UI 가 돌아오는지(영구 숨김
|
||||
// 아님) 확인. InsertionAffordances 는 points 가 있을 때만 렌더되나, pick 모드 동안 강제
|
||||
// 미렌더 → 종료 후엔 일반 조건으로 복귀(컨테이너 가드가 pickRequestId 에만 의존).
|
||||
const h = mountWithFrame([{ name: 'Form', props: { id: 'main-form' } }]);
|
||||
await waitFor(() => expect((window as any).__g7LayoutEditorHistory).toBeTruthy());
|
||||
fireRequest();
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeTruthy(),
|
||||
);
|
||||
// 취소 → pick 모드 종료.
|
||||
const cancelBtn = window.document.querySelector('[data-testid="g7le-canvas-pick-cancel"]') as HTMLElement;
|
||||
act(() => fireEvent.click(cancelBtn));
|
||||
await waitFor(() =>
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-banner"]')).toBeNull(),
|
||||
);
|
||||
// 모드 종료 후 pick hover 박스도 사라짐(잔존 금지).
|
||||
expect(window.document.querySelector('[data-testid="g7le-canvas-pick-hover"]')).toBeNull();
|
||||
h.unmount();
|
||||
});
|
||||
});
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* EditorToolbar.pageSettings.test.tsx —
|
||||
*
|
||||
* ⚙ 페이지 설정 버튼 회귀 가드(종전 ⚙데이터 버튼을 대체 — 데이터 진입은 [데이터] 탭 흡수):
|
||||
* - onPageSettings 미제공 또는 라우트 미선택 시 disabled
|
||||
* - route 모드 + onPageSettings 제공 시 활성 + 클릭 시 호출
|
||||
* - extension/iteration_item 모드 시 disabled(페이지 메타 없음)
|
||||
* - 종전 ⚙데이터 버튼(g7le-toolbar-data-sources) 부재 확인(진입점 단일화)
|
||||
*/
|
||||
|
||||
import React, { useEffect } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { EditorToolbar } from '../../components/EditorToolbar';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function SelectRoute({ layoutName }: { layoutName: string }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: `/${layoutName}`, layoutName } });
|
||||
}, [dispatch, layoutName]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function EnterMode({ mode }: { mode: 'extension' | 'iteration_item' }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: '/home', layoutName: 'home' } });
|
||||
if (mode === 'extension') dispatch({ type: 'ENTER_EXTENSION_EDIT', extensionId: '44' });
|
||||
else dispatch({ type: 'ENTER_ITERATION_ITEM_EDIT', sourcePath: '0.children.1', hostLayout: 'home' });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return null;
|
||||
}
|
||||
|
||||
function wrap(node: React.ReactElement, withRoute = false): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'sirsoft-basic', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
|
||||
{withRoute ? <SelectRoute layoutName="home" /> : null}
|
||||
{node}
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditorToolbar — ⚙ 페이지 설정 버튼', () => {
|
||||
it('onPageSettings 미제공 시 disabled', () => {
|
||||
render(wrap(<EditorToolbar />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-page-settings') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 미선택 시 disabled (핸들러 제공해도)', () => {
|
||||
render(wrap(<EditorToolbar onPageSettings={vi.fn()} />, false));
|
||||
const btn = screen.getByTestId('g7le-toolbar-page-settings') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('route 모드 + 핸들러 제공 시 활성 + 클릭 시 호출', () => {
|
||||
const onPageSettings = vi.fn();
|
||||
render(wrap(<EditorToolbar onPageSettings={onPageSettings} />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-page-settings') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(false);
|
||||
fireEvent.click(btn);
|
||||
expect(onPageSettings).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('extension 모드 → disabled(페이지 메타 없음)', async () => {
|
||||
render(
|
||||
wrap(
|
||||
<>
|
||||
<EnterMode mode="extension" />
|
||||
<EditorToolbar onPageSettings={vi.fn()} />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
await screen.findByTestId('g7le-toolbar-exit-alt-mode');
|
||||
const btn = screen.getByTestId('g7le-toolbar-page-settings') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('iteration_item 모드 → disabled', async () => {
|
||||
render(
|
||||
wrap(
|
||||
<>
|
||||
<EnterMode mode="iteration_item" />
|
||||
<EditorToolbar onPageSettings={vi.fn()} />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
await screen.findByTestId('g7le-toolbar-exit-alt-mode');
|
||||
const btn = screen.getByTestId('g7le-toolbar-page-settings') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('종전 ⚙데이터 버튼 부재(진입점 [데이터] 탭 단일화)', () => {
|
||||
render(wrap(<EditorToolbar onPageSettings={vi.fn()} />, true));
|
||||
expect(screen.queryByTestId('g7le-toolbar-data-sources')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* EditorToolbar 컴포넌트 테스트
|
||||
*
|
||||
* 결함 4/5/6 회귀 가드:
|
||||
* - 나가기 버튼: onExit 제공 시 활성 + 클릭 시 호출 / 미제공 시 disabled
|
||||
* - 코드편집 버튼: onEditCode 제공 시 활성 + 클릭 시 호출 / 미제공 시 disabled
|
||||
* - 저장 버튼: onSave 가 Promise 면 진행 중 스피너 노출 + disabled, 완료 후 복원
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import { EditorToolbar } from '../../components/EditorToolbar';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function wrap(node: React.ReactElement): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'sirsoft-basic', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
|
||||
{node}
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditorToolbar — 나가기 버튼 (결함 4)', () => {
|
||||
it('onExit 미제공 시 나가기 버튼 disabled', () => {
|
||||
render(wrap(<EditorToolbar />));
|
||||
const exit = screen.getByTestId('g7le-toolbar-exit') as HTMLButtonElement;
|
||||
expect(exit.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('onExit 제공 시 활성 + 클릭하면 onExit 호출', () => {
|
||||
const onExit = vi.fn();
|
||||
render(wrap(<EditorToolbar onExit={onExit} />));
|
||||
const exit = screen.getByTestId('g7le-toolbar-exit') as HTMLButtonElement;
|
||||
expect(exit.disabled).toBe(false);
|
||||
fireEvent.click(exit);
|
||||
expect(onExit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorToolbar — 코드편집 버튼 (결함 5)', () => {
|
||||
it('onEditCode 미제공 시 disabled', () => {
|
||||
render(wrap(<EditorToolbar />));
|
||||
const code = screen.getByTestId('g7le-toolbar-edit-code') as HTMLButtonElement;
|
||||
expect(code.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('onEditCode 제공 시 활성 + 클릭하면 호출', () => {
|
||||
const onEditCode = vi.fn();
|
||||
render(wrap(<EditorToolbar onEditCode={onEditCode} />));
|
||||
const code = screen.getByTestId('g7le-toolbar-edit-code') as HTMLButtonElement;
|
||||
expect(code.disabled).toBe(false);
|
||||
fireEvent.click(code);
|
||||
expect(onEditCode).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorToolbar — 버튼 잔류 테두리 (추가 결함: hover/focus 후 검정 테두리 유지)', () => {
|
||||
it('base/hover 스타일이 longhand(borderColor/backgroundColor)만 사용한다 (shorthand 혼용 금지)', () => {
|
||||
// 회귀 가드: base 가 `border` shorthand 이고 hover 가 `borderColor` longhand 이면,
|
||||
// hover 해제 시 React 가 borderColor 만 제거하고 border-width/style 을 남겨 테두리가
|
||||
// color(텍스트색)로 폴백되며 검정 테두리가 잔류한다.
|
||||
render(wrap(<EditorToolbar onExit={vi.fn()} onEditCode={vi.fn()} />));
|
||||
const exit = screen.getByTestId('g7le-toolbar-exit') as HTMLButtonElement;
|
||||
const raw = exit.getAttribute('style') ?? '';
|
||||
|
||||
expect(raw).toContain('border-color');
|
||||
expect(raw).toContain('background-color');
|
||||
// shorthand `border:` / `background:` (longhand 가 아닌 단독) 부재 — 혼용 시 잔류 발생
|
||||
expect(/(^|;)\s*border\s*:/.test(raw)).toBe(false);
|
||||
expect(/(^|;)\s*background\s*:/.test(raw)).toBe(false);
|
||||
});
|
||||
|
||||
it('마우스 올렸다 치우면 hover 스타일이 원복되어 잔류 테두리 없음', () => {
|
||||
render(wrap(<EditorToolbar onExit={vi.fn()} onEditCode={vi.fn()} />));
|
||||
const exit = screen.getByTestId('g7le-toolbar-exit') as HTMLButtonElement;
|
||||
const baseBorder = exit.style.borderColor;
|
||||
|
||||
fireEvent.mouseEnter(exit);
|
||||
// hover 중에는 테두리색이 hover 값으로 바뀜
|
||||
fireEvent.mouseLeave(exit);
|
||||
|
||||
// 치운 뒤에는 base 테두리색으로 복귀 (잔류 없음)
|
||||
expect(exit.style.borderColor).toBe(baseBorder);
|
||||
});
|
||||
|
||||
it('클릭(focus)된 뒤에도 브라우저 기본 검정 outline 이 노출되지 않음 (outline:none)', () => {
|
||||
render(wrap(<EditorToolbar onExit={vi.fn()} onEditCode={vi.fn()} />));
|
||||
const code = screen.getByTestId('g7le-toolbar-edit-code') as HTMLButtonElement;
|
||||
|
||||
act(() => {
|
||||
code.focus();
|
||||
});
|
||||
|
||||
// 브라우저 기본 outline 을 제거해 클릭 후 검정 테두리 잔류를 방지한다.
|
||||
expect(code.style.outline).toBe('none');
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorToolbar — 저장 스피너 (결함 6)', () => {
|
||||
it('onSave 가 Promise 면 저장 중 스피너 노출 + disabled, 완료 후 복원', async () => {
|
||||
let resolveSave: () => void = () => {};
|
||||
const onSave = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((res) => {
|
||||
resolveSave = res;
|
||||
}),
|
||||
);
|
||||
render(wrap(<EditorToolbar onSave={onSave} isDirty />));
|
||||
const save = screen.getByTestId('g7le-toolbar-save') as HTMLButtonElement;
|
||||
|
||||
// 저장 전: 스피너 없음
|
||||
expect(screen.queryByTestId('g7le-toolbar-save-spinner')).toBeNull();
|
||||
|
||||
fireEvent.click(save);
|
||||
|
||||
// 저장 중: 스피너 노출 + disabled
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-toolbar-save-spinner')).toBeInTheDocument();
|
||||
});
|
||||
expect((screen.getByTestId('g7le-toolbar-save') as HTMLButtonElement).disabled).toBe(true);
|
||||
|
||||
// 저장 완료
|
||||
resolveSave();
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('g7le-toolbar-save-spinner')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('onSave 미제공 시 저장 버튼 disabled', () => {
|
||||
render(wrap(<EditorToolbar />));
|
||||
const save = screen.getByTestId('g7le-toolbar-save') as HTMLButtonElement;
|
||||
expect(save.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorToolbar — 템플릿 이름/버전 표시 + 전환 드롭다운', () => {
|
||||
const others = [
|
||||
{ identifier: 'sirsoft-basic', name: '심플 유저', version: '1.2.0', type: 'user' as const },
|
||||
{ identifier: 'sirsoft-admin_basic', name: '관리자 베이직', version: '2.0.1', type: 'admin' as const },
|
||||
];
|
||||
|
||||
it('templateName/templateVersion 제공 시 이름과 버전을 함께 표시', () => {
|
||||
render(
|
||||
wrap(<EditorToolbar templateName="심플 유저" templateVersion="1.2.0" />),
|
||||
);
|
||||
expect(screen.getByTestId('g7le-toolbar-template-name').textContent).toBe('심플 유저');
|
||||
expect(screen.getByTestId('g7le-toolbar-template-version').textContent).toBe('v1.2.0');
|
||||
});
|
||||
|
||||
it('templateName 미제공 시 식별자로 폴백', () => {
|
||||
render(wrap(<EditorToolbar />));
|
||||
// wrap 의 templateIdentifier 는 sirsoft-basic
|
||||
expect(screen.getByTestId('g7le-toolbar-template-name').textContent).toBe('sirsoft-basic');
|
||||
});
|
||||
|
||||
it('전환 후보(자기 자신 제외)가 없으면 드롭다운 토글 비활성', () => {
|
||||
render(
|
||||
wrap(
|
||||
<EditorToolbar
|
||||
templateList={[{ identifier: 'sirsoft-basic', name: '심플 유저', version: '1.0.0', type: 'user' }]}
|
||||
onSwitchTemplate={vi.fn()}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
const label = screen.getByTestId('g7le-toolbar-template-label') as HTMLButtonElement;
|
||||
expect(label.disabled).toBe(true);
|
||||
expect(label.getAttribute('data-can-switch')).toBe('false');
|
||||
});
|
||||
|
||||
it('다른 템플릿 후보가 있으면 클릭 시 메뉴 열림 + 현재 템플릿도 함께 노출', () => {
|
||||
render(
|
||||
wrap(<EditorToolbar templateList={others} onSwitchTemplate={vi.fn()} />),
|
||||
);
|
||||
const label = screen.getByTestId('g7le-toolbar-template-label') as HTMLButtonElement;
|
||||
expect(label.disabled).toBe(false);
|
||||
// 처음엔 메뉴 닫힘
|
||||
expect(screen.queryByTestId('g7le-toolbar-template-menu')).toBeNull();
|
||||
fireEvent.click(label);
|
||||
expect(screen.getByTestId('g7le-toolbar-template-menu')).toBeInTheDocument();
|
||||
const items = screen.getAllByTestId('g7le-toolbar-template-menu-item');
|
||||
// 현재 선택된 템플릿(sirsoft-basic)도 함께 노출 → 2개
|
||||
expect(items).toHaveLength(2);
|
||||
const ids = items.map((el) => el.getAttribute('data-identifier'));
|
||||
expect(ids).toContain('sirsoft-basic');
|
||||
expect(ids).toContain('sirsoft-admin_basic');
|
||||
// 현재 항목은 data-current=true 로 표시
|
||||
const current = items.find((el) => el.getAttribute('data-identifier') === 'sirsoft-basic');
|
||||
expect(current?.getAttribute('data-current')).toBe('true');
|
||||
expect(current?.getAttribute('aria-selected')).toBe('true');
|
||||
});
|
||||
|
||||
it('현재 선택 항목 클릭 시 이동 없이 메뉴만 닫힘(onSwitch 미호출)', () => {
|
||||
const onSwitch = vi.fn();
|
||||
render(
|
||||
wrap(<EditorToolbar templateList={others} onSwitchTemplate={onSwitch} />),
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-toolbar-template-label'));
|
||||
const current = screen
|
||||
.getAllByTestId('g7le-toolbar-template-menu-item')
|
||||
.find((el) => el.getAttribute('data-identifier') === 'sirsoft-basic')!;
|
||||
fireEvent.click(current);
|
||||
expect(onSwitch).not.toHaveBeenCalled();
|
||||
expect(screen.queryByTestId('g7le-toolbar-template-menu')).toBeNull();
|
||||
});
|
||||
|
||||
it('다른 템플릿 항목 클릭 시 onSwitchTemplate 가 해당 식별자로 호출 + 메뉴 닫힘', () => {
|
||||
const onSwitch = vi.fn();
|
||||
render(
|
||||
wrap(<EditorToolbar templateList={others} onSwitchTemplate={onSwitch} />),
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-toolbar-template-label'));
|
||||
const other = screen
|
||||
.getAllByTestId('g7le-toolbar-template-menu-item')
|
||||
.find((el) => el.getAttribute('data-identifier') === 'sirsoft-admin_basic')!;
|
||||
fireEvent.click(other);
|
||||
expect(onSwitch).toHaveBeenCalledTimes(1);
|
||||
expect(onSwitch).toHaveBeenCalledWith('sirsoft-admin_basic');
|
||||
expect(screen.queryByTestId('g7le-toolbar-template-menu')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// 별도 편집 모드(확장/반복/공통레이아웃/모달)에서도 툴바 본체가 모두 표시되어야 한다.
|
||||
// 종전엔 `!isAltMode` 게이트로 별도 모드에서 본체를 통째로 숨겨 "← 종료" 버튼만 남았다.
|
||||
describe('EditorToolbar — 별도 편집 모드 풀 툴바', () => {
|
||||
// provider 안에서 별도 편집 모드로 진입시키는 헬퍼.
|
||||
function EnterMode({ mode }: { mode: 'extension' | 'iteration_item' | 'base' }): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
act(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: '/x', layoutName: 'home' } });
|
||||
if (mode === 'extension') dispatch({ type: 'ENTER_EXTENSION_EDIT', extensionId: '44' });
|
||||
else if (mode === 'iteration_item')
|
||||
dispatch({ type: 'ENTER_ITERATION_ITEM_EDIT', sourcePath: '0.children.1', hostLayout: 'home' });
|
||||
else dispatch({ type: 'ENTER_BASE_EDIT', layoutName: '_user_base' });
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return <></>;
|
||||
}
|
||||
|
||||
const BODY_BUTTONS = [
|
||||
'g7le-toolbar-add-element',
|
||||
'g7le-toolbar-preview',
|
||||
'g7le-toolbar-versions',
|
||||
'g7le-toolbar-edit-code',
|
||||
'g7le-toolbar-page-settings',
|
||||
'g7le-toolbar-save',
|
||||
'g7le-toolbar-exit',
|
||||
];
|
||||
|
||||
for (const mode of ['extension', 'iteration_item', 'base'] as const) {
|
||||
it(`${mode} 모드: 툴바 본체 + 모드 종료 버튼이 모두 렌더`, async () => {
|
||||
render(
|
||||
wrap(
|
||||
<>
|
||||
<EnterMode mode={mode} />
|
||||
<EditorToolbar onSave={vi.fn()} onEditCode={vi.fn()} />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
// EnterMode 의 useEffect dispatch 가 반영돼 별도 모드 종료 버튼이 나타날 때까지 대기.
|
||||
await screen.findByTestId('g7le-toolbar-exit-alt-mode');
|
||||
// 본체 버튼 전수 노출
|
||||
for (const id of BODY_BUTTONS) {
|
||||
expect(screen.getByTestId(id)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* EditorToolbar.translations.test.tsx —
|
||||
*
|
||||
* 🌐 다국어 버튼 회귀 가드:
|
||||
* - onManageTranslations 미제공 또는 라우트 미선택 시 disabled
|
||||
* - 라우트 선택 + onManageTranslations 제공 시 활성 + 클릭 시 호출
|
||||
*/
|
||||
|
||||
import React, { useEffect } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { EditorToolbar } from '../../components/EditorToolbar';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
/** 마운트 시 라우트를 선택해 state.selectedRoute 를 채우는 하네스 */
|
||||
function SelectRoute({ layoutName }: { layoutName: string }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: `/${layoutName}`, layoutName } });
|
||||
}, [dispatch, layoutName]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function wrap(node: React.ReactElement, withRoute = false): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'sirsoft-basic', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
|
||||
{withRoute ? <SelectRoute layoutName="home" /> : null}
|
||||
{node}
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditorToolbar — 🌐 다국어 버튼', () => {
|
||||
it('onManageTranslations 미제공 시 disabled', () => {
|
||||
render(wrap(<EditorToolbar />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-translations') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 미선택 시 disabled (핸들러 제공해도)', () => {
|
||||
render(wrap(<EditorToolbar onManageTranslations={vi.fn()} />, false));
|
||||
const btn = screen.getByTestId('g7le-toolbar-translations') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 선택 + 핸들러 제공 시 활성 + 클릭 시 호출', () => {
|
||||
const onManageTranslations = vi.fn();
|
||||
render(wrap(<EditorToolbar onManageTranslations={onManageTranslations} />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-translations') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(false);
|
||||
fireEvent.click(btn);
|
||||
expect(onManageTranslations).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* EditorToolbar.versionPreview.test.tsx —
|
||||
*
|
||||
* 👁 미리보기 / 🕘 버전 기록 버튼 회귀 가드:
|
||||
* - onPreview 미제공 또는 라우트 미선택(layoutName 없음) 시 disabled
|
||||
* - 라우트 선택 + onPreview 제공 시 활성 + 클릭 시 호출
|
||||
* - onShowVersions 동일 규칙
|
||||
* - 미리보기 Promise 진행 중 스피너 + disabled (재진입 방지)
|
||||
*
|
||||
* @effects preview_button_disabled_when_no_layout_name, preview_button_enabled_when_layout_selected,
|
||||
* preview_button_shows_spinner_while_pending_then_restores, version_button_disabled_when_no_layout_name
|
||||
*/
|
||||
|
||||
import React, { useEffect } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { EditorToolbar } from '../../components/EditorToolbar';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
/** 마운트 시 라우트를 선택해 state.selectedRoute 를 채우는 하네스 */
|
||||
function SelectRoute({ layoutName }: { layoutName: string }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: `/${layoutName}`, layoutName } });
|
||||
}, [dispatch, layoutName]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function wrap(node: React.ReactElement, withRoute = false): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'sirsoft-basic', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
|
||||
{withRoute ? <SelectRoute layoutName="home" /> : null}
|
||||
{node}
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditorToolbar — 👁 미리보기 버튼', () => {
|
||||
it('onPreview 미제공 시 disabled', () => {
|
||||
render(wrap(<EditorToolbar />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-preview') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 미선택 시 disabled (핸들러 제공해도)', () => {
|
||||
render(wrap(<EditorToolbar onPreview={vi.fn()} />, false));
|
||||
const btn = screen.getByTestId('g7le-toolbar-preview') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 선택 + 핸들러 제공 시 활성 + 클릭 시 호출', () => {
|
||||
const onPreview = vi.fn();
|
||||
render(wrap(<EditorToolbar onPreview={onPreview} />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-preview') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(false);
|
||||
fireEvent.click(btn);
|
||||
expect(onPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('Promise 진행 중 스피너 표시 + disabled (재진입 방지)', async () => {
|
||||
let resolve: () => void = () => {};
|
||||
const onPreview = vi.fn(() => new Promise<void>((r) => { resolve = r; }));
|
||||
render(wrap(<EditorToolbar onPreview={onPreview} />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-preview') as HTMLButtonElement;
|
||||
fireEvent.click(btn);
|
||||
await screen.findByTestId('g7le-toolbar-preview-spinner');
|
||||
expect(btn.disabled).toBe(true);
|
||||
// 진행 중 재클릭은 무시 (disabled)
|
||||
fireEvent.click(btn);
|
||||
expect(onPreview).toHaveBeenCalledTimes(1);
|
||||
resolve();
|
||||
await waitFor(() => expect(btn.disabled).toBe(false));
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorToolbar — 🕘 버전 기록 버튼', () => {
|
||||
it('onShowVersions 미제공 시 disabled', () => {
|
||||
render(wrap(<EditorToolbar />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-versions') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 미선택 시 disabled (핸들러 제공해도)', () => {
|
||||
render(wrap(<EditorToolbar onShowVersions={vi.fn()} />, false));
|
||||
const btn = screen.getByTestId('g7le-toolbar-versions') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('라우트 선택 + 핸들러 제공 시 활성 + 클릭 시 호출', () => {
|
||||
const onShowVersions = vi.fn();
|
||||
render(wrap(<EditorToolbar onShowVersions={onShowVersions} />, true));
|
||||
const btn = screen.getByTestId('g7le-toolbar-versions') as HTMLButtonElement;
|
||||
expect(btn.disabled).toBe(false);
|
||||
fireEvent.click(btn);
|
||||
expect(onShowVersions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+807
@@ -0,0 +1,807 @@
|
||||
/**
|
||||
* ElementOverlay 컴포넌트 테스트
|
||||
*
|
||||
* - hoverBox 만 있으면 점선 박스만 렌더
|
||||
* - selectedBox 가 있으면 실선 박스 + ⓘ + 8방향 핸들 자리 (none 일 때만)
|
||||
* - lockKind=base → '공통 레이아웃 편집' 어포던스 + 8방향 핸들 미렌더
|
||||
* - lockKind=extension → '확장 편집' 어포던스
|
||||
* - lockKind=data_bound → 안내 라벨 (pointer-events: none)
|
||||
* - navAffordance=route_in_tree → '→ 이 화면 편집' 버튼
|
||||
* - navAffordance=external_url / route_not_in_tree / dynamic_path → 비활성 안내
|
||||
* - onSelectParent 제공 → 타입 칩이 클릭 가능한 부모 선택(↑) 버튼 / 미제공 → 클릭 불가 라벨
|
||||
*
|
||||
* @effects overlapping_child_selected_type_chip_escalates_to_parent, root_node_type_chip_degrades_to_non_clickable_label
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { ElementOverlay } from '../../components/ElementOverlay';
|
||||
import { OVERLAY_AFFORDANCE } from '../../utils/overlayZIndex';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function withTranslation(node: React.ReactElement): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
{node}
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const box = (overrides = {}) => ({
|
||||
left: 10,
|
||||
top: 20,
|
||||
width: 100,
|
||||
height: 50,
|
||||
scale: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('ElementOverlay — 박스 렌더', () => {
|
||||
it('hoverBox 만 있으면 hover 점선만 렌더', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={box()}
|
||||
selectedBox={null}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-overlay-hover')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-overlay-selected')).toBeNull();
|
||||
});
|
||||
|
||||
// 선택된 경우에 한해 요소 위에 컴포넌트 타입(Div/Table 등)을 흐린 오버레이로 표시.
|
||||
it('selectedName 제공 → 큰 박스는 안쪽 좌상단 타입 라벨 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })} // inside placement
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="Table"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const label = screen.getByTestId('g7le-overlay-type-label');
|
||||
expect(label.textContent).toBe('Table');
|
||||
expect(label.getAttribute('data-placement')).toBe('inside');
|
||||
// pointerEvents none — 클릭/리사이즈 비방해
|
||||
expect(getComputedStyle(label).pointerEvents).toBe('none');
|
||||
});
|
||||
|
||||
// 너무 작은 엘리먼트는 라벨이 콘텐츠를 가리므로 박스 바깥 좌상단에 표시.
|
||||
it('작은 박스(outside placement) → 타입 라벨을 박스 바깥에 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 30, height: 18 })} // 작은 박스 → outside
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="Span"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const label = screen.getByTestId('g7le-overlay-type-label');
|
||||
expect(label.textContent).toBe('Span');
|
||||
expect(label.getAttribute('data-placement')).toBe('outside');
|
||||
});
|
||||
|
||||
// 겹친 부모 선택. onSelectParent 제공 시 타입 칩이 클릭 가능한
|
||||
// "부모 선택"(↑) 버튼이 된다(부모/자식 크기 같아 자식만 잡히는 경우 상위 escalation).
|
||||
it('onSelectParent 제공 → 타입 칩이 클릭 가능한 부모 선택 버튼(↑ + 클릭→콜백)', () => {
|
||||
const onSelectParent = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="Li"
|
||||
onSelectParent={onSelectParent}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const chip = screen.getByTestId('g7le-overlay-type-label');
|
||||
expect(chip.tagName).toBe('BUTTON');
|
||||
expect(chip.textContent).toContain('↑');
|
||||
expect(chip.textContent).toContain('Li');
|
||||
// 클릭 가능(pointerEvents auto) — 부모 선택 콜백 발동.
|
||||
expect(getComputedStyle(chip).pointerEvents).toBe('auto');
|
||||
fireEvent.click(chip);
|
||||
expect(onSelectParent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onSelectParent 미제공(루트 등) → 타입 칩은 클릭 불가 라벨(span, pointerEvents none)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="Div"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const chip = screen.getByTestId('g7le-overlay-type-label');
|
||||
expect(chip.tagName).toBe('SPAN');
|
||||
expect(chip.textContent).toBe('Div');
|
||||
expect(getComputedStyle(chip).pointerEvents).toBe('none');
|
||||
});
|
||||
|
||||
it('hover 만(선택 없음) → 타입 라벨 미표시 (선택된 경우에 한함)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={box()}
|
||||
selectedBox={null}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="표"
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-overlay-type-label')).toBeNull();
|
||||
});
|
||||
|
||||
it('selectedName 미제공 → 타입 라벨 미렌더', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-overlay-type-label')).toBeNull();
|
||||
});
|
||||
|
||||
it('selectedBox + lockKind=none + 양축 활성 → 실선 박스 + ⓘ + 8방향 핸들 ', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
resizeEnabledAxes={{ width: true, height: true }}
|
||||
onResizeHandlePointerDown={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-overlay-selected')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-overlay-info-button')).toBeTruthy();
|
||||
// 양축 활성 → 8방향 핸들 모두 표시 + 활성(pointer-events)
|
||||
for (const key of ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']) {
|
||||
const handle = screen.getByTestId(`g7le-resize-handle-${key}`);
|
||||
expect(handle).toBeTruthy();
|
||||
expect(handle.getAttribute('data-resize-handle-active')).toBe('true');
|
||||
}
|
||||
});
|
||||
|
||||
it('ⓘ 버튼 + 리사이즈 핸들은 드래그 핸들 위 어포던스 밴드(z-index) — 클릭 가로채기 회귀 차단', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
resizeEnabledAxes={{ width: true, height: true }}
|
||||
onResizeHandlePointerDown={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// S5b 드래그 핸들이 z-index 미지정(≈0) ⓘ/리사이즈 핸들 위로 올라와 클릭이 이동
|
||||
// 포인터에 가로채이던 회귀. 모두 OVERLAY_AFFORDANCE z-index 로 핸들 위에 와야 한다.
|
||||
expect(screen.getByTestId('g7le-overlay-info-button').style.zIndex).toBe(String(OVERLAY_AFFORDANCE));
|
||||
for (const key of ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']) {
|
||||
expect(screen.getByTestId(`g7le-resize-handle-${key}`).style.zIndex).toBe(
|
||||
String(OVERLAY_AFFORDANCE)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('큰 박스(inside)에서 ⓘ 버튼이 코너/ne 핸들 바깥 여백으로 밀려난다', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })} // inside placement
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
resizeEnabledAxes={{ width: true, height: true }}
|
||||
onResizeHandlePointerDown={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const info = screen.getByTestId('g7le-overlay-info-button');
|
||||
expect(info.dataset.placement).toBe('inside');
|
||||
// 종전 -20 은 ne 핸들(-4)·코너와 겹쳤다. -30 으로 박스 밖 대각 여백 확보.
|
||||
expect(info.style.right).toBe('-30px');
|
||||
expect(info.style.top).toBe('-30px');
|
||||
});
|
||||
|
||||
it('스펙이 width/height 컨트롤 미선언(axes 미제공) → 핸들 미표시 ', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-overlay-selected')).toBeTruthy();
|
||||
// 활성 축 없음 → 8방향 핸들 모두 미표시
|
||||
for (const key of ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']) {
|
||||
expect(screen.queryByTestId(`g7le-resize-handle-${key}`)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('가로만 선언(width 축) → 좌우 변 핸들만, 모서리/상하 변 핸들 미표시 ', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
resizeEnabledAxes={{ width: true, height: false }}
|
||||
onResizeHandlePointerDown={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// 가로 변(e/w)만 표시 — 모서리(양축)·세로 변(n/s)은 height 미선언이라 미표시
|
||||
expect(screen.getByTestId('g7le-resize-handle-e')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-resize-handle-w')).toBeTruthy();
|
||||
for (const key of ['nw', 'n', 'ne', 'se', 's', 'sw']) {
|
||||
expect(screen.queryByTestId(`g7le-resize-handle-${key}`)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('ElementOverlay — 잠금 어포던스', () => {
|
||||
it('lockKind=base → 공통 레이아웃 편집 어포던스 + 핸들 미렌더', () => {
|
||||
const onEditBase = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="base"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onEditBase={onEditBase}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const editBase = screen.getByTestId('g7le-overlay-edit-base');
|
||||
fireEvent.click(editBase);
|
||||
expect(onEditBase).toHaveBeenCalledTimes(1);
|
||||
// base 잠금 시 8방향 핸들 자리 미렌더 (lockKind=none 일 때만 렌더)
|
||||
expect(screen.queryByTestId('g7le-resize-handle-nw')).toBeNull();
|
||||
// base 잠금 시 ⓘ 속성 메뉴 미표시
|
||||
expect(screen.queryByTestId('g7le-overlay-info-button')).toBeNull();
|
||||
});
|
||||
|
||||
it('lockKind=extension → 확장 편집 어포던스', () => {
|
||||
const onEditExtension = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="extension"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onEditExtension={onEditExtension}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-overlay-edit-extension'));
|
||||
expect(onEditExtension).toHaveBeenCalledTimes(1);
|
||||
// 확장 잠금 시 ⓘ 속성 메뉴 미표시 — 속성 편집/복사/삭제 차단, 확장 편집 어포던스만
|
||||
expect(screen.queryByTestId('g7le-overlay-info-button')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-overlay-edit-props')).toBeNull();
|
||||
// extensionLabel 미제공 시 식별자 칩은 렌더되지 않는다.
|
||||
expect(screen.queryByTestId('g7le-overlay-extension-label')).toBeNull();
|
||||
});
|
||||
|
||||
it('lockKind=extension + extensionLabel → 확장 편집 버튼에 어느 확장인지 식별자 칩 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="extension"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onEditExtension={vi.fn()}
|
||||
extensionLabel="sirsoft-board"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const chip = screen.getByTestId('g7le-overlay-extension-label');
|
||||
expect(chip).toHaveTextContent('sirsoft-board');
|
||||
// 칩은 확장 편집 어포던스 버튼 내부에 위치(어느 확장인지를 그 버튼에 명시).
|
||||
expect(screen.getByTestId('g7le-overlay-edit-extension')).toContainElement(chip);
|
||||
});
|
||||
|
||||
it('lockKind=base + baseLayoutLabel → 공통 레이아웃 편집 버튼에 레이아웃 파일명 칩 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="base"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onEditBase={vi.fn()}
|
||||
baseLayoutLabel="_user_base"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const chip = screen.getByTestId('g7le-overlay-base-layout-label');
|
||||
expect(chip).toHaveTextContent('_user_base');
|
||||
expect(screen.getByTestId('g7le-overlay-edit-base')).toContainElement(chip);
|
||||
});
|
||||
|
||||
it('lockKind=data_bound → ⓘ 속성 메뉴는 허용 (텍스트만 편집 불가)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="data_bound"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// 데이터 결정 노드는 스타일/배치 편집이 허용되므로 ⓘ 표시
|
||||
expect(screen.getByTestId('g7le-overlay-info-button')).toBeTruthy();
|
||||
// 안내 라벨도 함께 표시
|
||||
expect(screen.getByTestId('g7le-overlay-data-bound-notice')).toBeTruthy();
|
||||
// dataSourceLabel 미제공 시 데이터소스 칩은 렌더되지 않는다.
|
||||
expect(screen.queryByTestId('g7le-overlay-data-source-label')).toBeNull();
|
||||
});
|
||||
|
||||
it('lockKind=data_bound + dataSourceLabel → 안내에 어느 데이터소스인지 칩 표시', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="data_bound"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
dataSourceLabel="recent_posts"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const chip = screen.getByTestId('g7le-overlay-data-source-label');
|
||||
expect(chip).toHaveTextContent('recent_posts');
|
||||
expect(screen.getByTestId('g7le-overlay-data-bound-notice')).toContainElement(chip);
|
||||
// onEditIteration 미제공(비-반복 data_bound) 시 반복 항목 편집 어포던스 미표시
|
||||
expect(screen.queryByTestId('g7le-overlay-edit-iteration')).toBeNull();
|
||||
});
|
||||
|
||||
it('data_bound + onEditIteration(반복) → "↳ 반복 항목 편집" 어포던스 표시 + 클릭 시 콜백', () => {
|
||||
const onEditIteration = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="data_bound"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
dataSourceLabel="recent_posts"
|
||||
onEditIteration={onEditIteration}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const btn = screen.getByTestId('g7le-overlay-edit-iteration');
|
||||
fireEvent.click(btn);
|
||||
expect(onEditIteration).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('data_bound + 작은 박스(outside) + 타입 라벨 → 안내 라벨을 타입 표식 위로 올려 겹침 회피', () => {
|
||||
// 작은 박스(width/height < 44)면 타입 표식이 박스 바깥 좌상단(bottom:100%)에 떠
|
||||
// 안내 라벨(top:-28)과 겹친다. 이때 안내 라벨 top 을 더 올린다.
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 30, height: 18 })}
|
||||
lockKind="data_bound"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="Input"
|
||||
dataSourceLabel="profile"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const notice = screen.getByTestId('g7le-overlay-data-bound-notice');
|
||||
// 타입 표식 위로 올라간 위치(-50). 기본(-28)이 아니어야 한다.
|
||||
expect(notice.style.top).toBe('-50px');
|
||||
// 타입 표식도 outside 로 렌더(겹침 전제 성립 확인)
|
||||
expect(screen.getByTestId('g7le-overlay-type-label').getAttribute('data-placement')).toBe('outside');
|
||||
});
|
||||
|
||||
it('data_bound + 큰 박스(inside) → 안내 라벨은 기본 위치(-28) 유지', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 80 })}
|
||||
lockKind="data_bound"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
selectedName="Input"
|
||||
dataSourceLabel="profile"
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-overlay-data-bound-notice').style.top).toBe('-28px');
|
||||
});
|
||||
|
||||
it('lockKind=extension → ⓘ 클릭으로도 컨텍스트 메뉴가 열리지 않음(메뉴 자체 미마운트)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="extension"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onEditExtension={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// ⓘ 버튼 자체가 없으므로 컨텍스트 메뉴(속성 설정/복사/삭제) 진입 경로가 차단됨
|
||||
expect(screen.queryByTestId('g7le-overlay-info-button')).toBeNull();
|
||||
});
|
||||
|
||||
it('lockKind=data_bound → 안내 라벨', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="data_bound"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-overlay-data-bound-notice')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ElementOverlay — 네비게이션 어포던스', () => {
|
||||
it('navAffordance=route_in_tree → 활성 버튼, 클릭 시 콜백', () => {
|
||||
const onLink = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="route_in_tree"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={onLink}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-overlay-link-edit-destination'));
|
||||
expect(onLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['external_url', 'route_not_in_tree', 'dynamic_path'] as const)(
|
||||
'navAffordance=%s → 어포던스 미표시',
|
||||
(kind) => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance={kind}
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// "⊘ 이동할 수 없습니다" 안내도, "이 화면 편집" 버튼도 모두 미표시.
|
||||
expect(screen.queryByTestId('g7le-overlay-destination-unreachable')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-overlay-link-edit-destination')).toBeNull();
|
||||
// 선택 박스 자체는 정상 — 일반 노드처럼 선택·편집 가능.
|
||||
expect(screen.getByTestId('g7le-overlay-selected')).toBeTruthy();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('ElementOverlay — ⓘ 메뉴 토글 → ContextMenu 노출', () => {
|
||||
it('초기 메뉴 미표시, ⓘ 클릭 시 메뉴 표시, 메뉴 항목 3개', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box()}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-context-menu')).toBeNull();
|
||||
fireEvent.click(screen.getByTestId('g7le-overlay-info-button'));
|
||||
expect(screen.getByTestId('g7le-context-menu')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-context-menu-edit-props')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-context-menu-duplicate')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-context-menu-delete')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ElementOverlay — 디바이스 분리 버튼(안 A ③④)', () => {
|
||||
it('onSeparateBranch 제공 → 하단 별도 분리 버튼 표시 + 클릭 콜백', () => {
|
||||
const onSeparateBranch = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onSeparateBranch={onSeparateBranch}
|
||||
separateBranchLabel="이 영역을 모바일 전용으로 분리"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const btn = screen.getByTestId('g7le-overlay-separate-branch');
|
||||
expect(btn.textContent).toContain('모바일');
|
||||
expect(btn.style.pointerEvents).toBe('auto');
|
||||
fireEvent.click(btn);
|
||||
expect(onSeparateBranch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onMergeBranch 제공 → 분리 해제 버튼 표시 + 클릭 콜백', () => {
|
||||
const onMergeBranch = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
onMergeBranch={onMergeBranch}
|
||||
mergeBranchLabel="모바일 전용 분리 해제"
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-overlay-separate-branch')).toBeNull();
|
||||
const btn = screen.getByTestId('g7le-overlay-merge-branch');
|
||||
fireEvent.click(btn);
|
||||
expect(onMergeBranch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('둘 다 미제공이면 분리 버튼 부재(회귀 가드 — 일반 노드 영향 0)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-overlay-separate-branch')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-overlay-merge-branch')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ElementOverlay — 정의된 디바이스 구성 점프 버튼군', () => {
|
||||
it('definedDeviceBranches 제공 → 각 디바이스 점프 버튼 표시 + 클릭 콜백(키 전달)', () => {
|
||||
const onJumpToDevice = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
definedDeviceBranches={[
|
||||
{ key: 'portable', label: '모바일' },
|
||||
{ key: '600-900', label: '600-900' },
|
||||
]}
|
||||
onJumpToDevice={onJumpToDevice}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// 다중 디바이스 구성(커스텀 포함)마다 키별 고유 testid 버튼이 렌더된다.
|
||||
const b1 = screen.getByTestId('g7le-overlay-jump-device-portable');
|
||||
const b2 = screen.getByTestId('g7le-overlay-jump-device-600-900');
|
||||
expect(b1.style.pointerEvents).toBe('auto');
|
||||
expect(b2.style.pointerEvents).toBe('auto');
|
||||
// 클릭 시 해당 디바이스 키가 콜백으로 전달된다.
|
||||
fireEvent.click(b1);
|
||||
expect(onJumpToDevice).toHaveBeenCalledWith('portable');
|
||||
fireEvent.click(b2);
|
||||
expect(onJumpToDevice).toHaveBeenCalledWith('600-900');
|
||||
});
|
||||
|
||||
it('definedDeviceBranches 미제공 → 점프 버튼 부재(회귀 가드)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-overlay-jump-device-portable')).toBeNull();
|
||||
});
|
||||
|
||||
// 이동+분리 버튼이 동시에 뜰 때 가로 겹침 금지 → 세로 스택 컨테이너에
|
||||
// 함께 담겨 여러 줄로 쌓인다(개별 절대위치 금지). 컨테이너 1개 + 자식 버튼들 구조 가드.
|
||||
it('점프 + 분리 버튼 공존 시 한 세로 스택 컨테이너에 담긴다(겹침 방지)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<ElementOverlay
|
||||
hoverBox={null}
|
||||
selectedBox={box({ width: 200, height: 120 })}
|
||||
lockKind="none"
|
||||
navAffordance="none"
|
||||
onEditProps={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
onLinkEditDestination={vi.fn()}
|
||||
definedDeviceBranches={[{ key: 'portable', label: '모바일+태블릿' }]}
|
||||
onJumpToDevice={vi.fn()}
|
||||
onSeparateBranch={vi.fn()}
|
||||
separateBranchLabel="이 영역을 모바일 전용으로 분리"
|
||||
/>
|
||||
)
|
||||
);
|
||||
const container = screen.getByTestId('g7le-overlay-branch-affordances');
|
||||
expect(container).toBeInTheDocument();
|
||||
// column flow — 자식 버튼은 개별 absolute 가 아니라 컨테이너 흐름에 쌓인다.
|
||||
expect(container.style.flexDirection).toBe('column');
|
||||
const jump = screen.getByTestId('g7le-overlay-jump-device-portable');
|
||||
const sep = screen.getByTestId('g7le-overlay-separate-branch');
|
||||
// 둘 다 같은 컨테이너의 자식이어야 한다(겹침 방지 — 별도 absolute 레인 금지).
|
||||
expect(container.contains(jump)).toBe(true);
|
||||
expect(container.contains(sep)).toBe(true);
|
||||
// 자식 버튼은 자체 absolute 위치를 갖지 않는다(컨테이너가 위치 담당).
|
||||
expect(jump.style.position).not.toBe('absolute');
|
||||
expect(sep.style.position).not.toBe('absolute');
|
||||
});
|
||||
});
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
// e2e:allow 레이아웃 편집기 텍스트 데이터 연결 속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(§공통 검증) + 단위/레이아웃 렌더링 테스트로 검증 (DataBindingSection.test.tsx L1 과 동일 정책)
|
||||
/**
|
||||
* InlineBindingSection.test.tsx — 텍스트 데이터 연결 영역 RTL
|
||||
*
|
||||
* 재설계:
|
||||
* - 비키화 노드(평문/레거시 raw 보간) → "+데이터" 삽입 시 **즉시 param 키화**(POST 후 node.text=$t:K|pN=).
|
||||
* → 번역 탭 즉시 활성. 레거시 raw 보간 행은 읽기 표시(교체/해제는 키화 후).
|
||||
* - param 키 노드 → param 값 행(교체) + [해제](전 로케일 자리표시 제거) + 신규 추가(끝).
|
||||
*
|
||||
* 컴포넌트가 useLayoutEditor()(편집 컨텍스트)를 사용하므로 LayoutEditorProvider 로 감싼다.
|
||||
* 키화·해제·추가는 custom-translations API(fetch)를 호출하므로 fetch 를 mock 한다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
|
||||
import { LayoutEditorProvider } from '../../LayoutEditorContext';
|
||||
import { LayoutDocumentProvider } from '../../LayoutDocumentContext';
|
||||
import { InlineBindingSection } from '../../components/property-controls/InlineBindingSection';
|
||||
import type { BindingCandidate } from '../../spec/bindingCandidates';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
import type { UseLayoutDocumentResult, LoadedLayoutDocument } from '../../hooks/useLayoutDocument';
|
||||
import { clearPending } from '../../hooks/pendingCustomTranslations';
|
||||
|
||||
const t = (k: string) => k;
|
||||
afterEach(() => { cleanup(); vi.restoreAllMocks(); clearPending(); });
|
||||
beforeEach(() => { localStorage.setItem('auth_token', 'test-token'); clearPending(); });
|
||||
|
||||
const candidates: BindingCandidate[] = [
|
||||
{ expression: '{{user.name}}', source: 'data_source', sourceId: 'user', path: 'name', shape: 'scalar', groupLabelKey: 'editor.ds.user', preview: '홍길동' },
|
||||
{ expression: '{{_local.keyword}}', source: '_local', sourceId: '_local', path: 'keyword', shape: 'scalar', preview: '노트북' },
|
||||
{ expression: '{{products.data}}', source: 'data_source', sourceId: 'products', path: 'data', shape: 'array', preview: '[3]' },
|
||||
];
|
||||
|
||||
/** 최소 docCtx — 키화 후 node.text 패치 검증용은 onPatchNode 로 받는다. */
|
||||
function buildDocCtx(): UseLayoutDocumentResult {
|
||||
let document: LoadedLayoutDocument = { layoutName: 'home', raw: { components: [] }, lockVersion: 1 };
|
||||
const ctx: UseLayoutDocumentResult = {
|
||||
document, isLoading: false, error: null, isDirty: false, saveSuccessCounter: 0,
|
||||
reload: async () => {},
|
||||
patchLayout: (p) => { document = { ...document, raw: { ...document.raw, components: p((document.raw.components as EditorNode[]) ?? []) } }; (ctx as unknown as { document: LoadedLayoutDocument }).document = document; },
|
||||
setLayoutComponents: (n) => { document = { ...document, raw: { ...document.raw, components: n } }; (ctx as unknown as { document: LoadedLayoutDocument }).document = document; },
|
||||
save: async () => ({ kind: 'success', newLockVersion: 2 }),
|
||||
};
|
||||
return ctx;
|
||||
}
|
||||
|
||||
function renderSection(node: EditorNode, onPatchNode = vi.fn()) {
|
||||
const ctx = buildDocCtx();
|
||||
const utils = render(
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<LayoutDocumentProvider value={ctx}>
|
||||
<InlineBindingSection node={node} candidates={candidates} t={t} onPatchNode={onPatchNode} templateIdentifier="test-tpl" />
|
||||
</LayoutDocumentProvider>
|
||||
</LayoutEditorProvider>,
|
||||
);
|
||||
return { utils, onPatchNode };
|
||||
}
|
||||
|
||||
/** createCustomKey POST → 응답 키 mock + 호출 캡처. */
|
||||
function stubKeyifyFetch(): { calls: Array<{ url: string; method?: string; body: any }> } {
|
||||
const calls: Array<{ url: string; method?: string; body: any }> = [];
|
||||
let seq = 0;
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
|
||||
const body = init?.body ? JSON.parse(init.body as string) : null;
|
||||
calls.push({ url, method: init?.method, body });
|
||||
if (typeof url === 'string' && url.includes('/custom-translations') && init?.method === 'POST') {
|
||||
seq += 1;
|
||||
return { ok: true, status: 201, json: async () => ({ data: { id: seq, translation_key: `custom.home.${seq}`, values: { ko: body?.value ?? '' }, lock_version: 0 } }) } as unknown as Response;
|
||||
}
|
||||
if (typeof url === 'string' && url.includes('/custom-translations') && (!init?.method || init?.method === 'GET')) {
|
||||
// findCustomKeyRow index
|
||||
return { ok: true, status: 200, json: async () => ({ data: [{ id: 7, translation_key: 'custom.home.5', values: { ko: '{p0} 작성', en: '' }, lock_version: 1 }] }) } as unknown as Response;
|
||||
}
|
||||
if (typeof url === 'string' && url.includes('/custom-translations/') && init?.method === 'PUT') {
|
||||
return { ok: true, status: 200, json: async () => ({ data: { id: 7, lock_version: 2 } }) } as unknown as Response;
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ data: { cache_version: 1 } }) } as unknown as Response;
|
||||
}));
|
||||
return { calls };
|
||||
}
|
||||
|
||||
describe('InlineBindingSection — 비키화 노드: 데이터 삽입 = 즉시 키화', () => {
|
||||
it('보간 없는 평문 → none 안내 + 삽입 피커', () => {
|
||||
renderSection({ name: 'Span', text: '안녕하세요' });
|
||||
expect(screen.getByTestId('g7le-inline-binding-section')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-inline-binding-none')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-inline-binding-append')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('+데이터 삽입 → 키화(POST=평문, 자리표시는 버퍼) → node.text=param 키', async () => {
|
||||
const { calls } = stubKeyifyFetch();
|
||||
const onPatch = vi.fn();
|
||||
renderSection({ name: 'Span', text: '안녕' }, onPatch);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-search-toggle-append'));
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}'));
|
||||
// POST 초기값은 자리표시 없는 평문(desync 차단 — 미저장 시 raw {p0} 없음). 자리표시는 버퍼.
|
||||
await waitFor(() => expect(calls.some((c) => c.method === 'POST')).toBe(true));
|
||||
const post = calls.find((c) => c.method === 'POST');
|
||||
expect(post!.body.value).toBe('안녕');
|
||||
// node.text = $t:custom.home.1|p0={{user?.name ?? ''}} (param 정의 — 레이아웃 저장 시 영속)
|
||||
await waitFor(() => expect(onPatch).toHaveBeenCalled());
|
||||
const patched = onPatch.mock.calls.at(-1)![0];
|
||||
expect(patched.text).toBe("$t:custom.home.1|p0={{user?.name ?? ''}}");
|
||||
});
|
||||
|
||||
it('삽입 피커는 scalar 후보만(array 미노출)', () => {
|
||||
renderSection({ name: 'Span', text: '' });
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-search-toggle-append'));
|
||||
expect(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-inline-binding-candidate-{{products.data}}')).toBeNull();
|
||||
});
|
||||
|
||||
it('레거시 raw 보간 노드 → 보간 읽기 표시(교체/해제 버튼 없음 — 키화 후 가능)', () => {
|
||||
renderSection({ name: 'P', text: '작성자 {{user.name}}' });
|
||||
expect(screen.getByTestId('g7le-inline-binding-expr-0')).toHaveTextContent('{{user.name}}');
|
||||
// 재설계: 비키화 노드는 읽기 표시만 — 교체/해제 미노출.
|
||||
expect(screen.queryByTestId('g7le-inline-binding-clear-0')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-inline-binding-search-toggle-replace-0')).toBeNull();
|
||||
// 삽입 입구는 항상 제공.
|
||||
expect(screen.getByTestId('g7le-inline-binding-append')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('InlineBindingSection — param 키 노드', () => {
|
||||
it('param 값 행 + [해제] + 신규 추가 입구 노출', () => {
|
||||
const node: EditorNode = { name: 'Span', text: '$t:custom.home.5|p0={{user.name}}|p1={{_local.keyword}}' };
|
||||
renderSection(node);
|
||||
expect(screen.getByTestId('g7le-inline-binding-param-p0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-inline-binding-param-p1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-inline-binding-param-expr-p0')).toHaveTextContent('{{user.name}}');
|
||||
expect(screen.getByTestId('g7le-inline-binding-param-clear-p0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-inline-binding-param-append')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('param 값 교체 → 해당 |pN= 만 새 소스로(키·다른 param 보존)', () => {
|
||||
const onPatch = vi.fn();
|
||||
const node: EditorNode = { name: 'Span', text: '$t:custom.home.5|p0={{user.name}}|p1={{old.x}}' };
|
||||
renderSection(node, onPatch);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-search-toggle-param-p1'));
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-candidate-{{_local.keyword}}'));
|
||||
expect(onPatch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ text: "$t:custom.home.5|p0={{user.name}}|p1={{_local?.keyword ?? ''}}" }),
|
||||
);
|
||||
});
|
||||
|
||||
it('데이터 연결 해제 → node.text 의 |pN= 제거', () => {
|
||||
stubKeyifyFetch();
|
||||
const onPatch = vi.fn();
|
||||
const node: EditorNode = { name: 'Span', text: '$t:custom.home.5|p0={{user.name}}|p1={{old.x}}' };
|
||||
renderSection(node, onPatch);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-param-clear-p0'));
|
||||
expect(onPatch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ text: '$t:custom.home.5|p1={{old.x}}' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('복합 param 은 읽기전용(교체 피커 미노출)', () => {
|
||||
const node: EditorNode = { name: 'Span', text: '$t:custom.home.5|p0={{a ? b : c}}' };
|
||||
renderSection(node);
|
||||
expect(screen.getByTestId('g7le-inline-binding-param-complex-p0')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-inline-binding-search-toggle-param-p0')).toBeNull();
|
||||
});
|
||||
|
||||
it('S9-N4: 미키화 lang **named-param** 노드(`$t:user.*|count={{}}`)는 param 키로 오판 금지 → 비키화 취급(데이터 추가=신규 키화)', () => {
|
||||
// 결함: `isParamized = isParamizedKeyText(text) ||...` 가
|
||||
// lang named-param(`$t:user.identity.challenge.remaining_attempts|count={{Math.max(...)}}`)도
|
||||
// true 로 판정해(PARAMIZED_KEY_RE 가 custom/lang 키 미구분), 속성 탭이 그 노드를 "이미 키화된
|
||||
// param 키"로 취급한다. 그러면 데이터 추가 시 appendParam(=insertBindingIntoParamKey)이 lang
|
||||
// 키(`user.identity...`)에 `|pN=` 을 붙이려 해 키화가 안 되고 lang 키가 오염된다. 수정: lang
|
||||
// named-param 은 **비키화 노드**로 취급 → 데이터 추가 시 insertDataKeyify(신규 custom 키화).
|
||||
const node: EditorNode = {
|
||||
name: 'Span',
|
||||
text: '$t:user.identity.challenge.remaining_attempts|count={{Math.max(0, (_local.maxAttempts ?? 0) - (_local.attempts ?? 0))}}',
|
||||
};
|
||||
renderSection(node);
|
||||
// param 키 행(`g7le-inline-binding-param-*`)이 **노출되지 않아야** 한다(키화 안 된 노드).
|
||||
expect(screen.queryByTestId('g7le-inline-binding-param-count')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-inline-binding-param-p0')).toBeNull();
|
||||
// 대신 비키화 노드 표면(읽기 표시 + 신규 삽입 입구 = 키화 경로)이 노출된다.
|
||||
expect(screen.getByTestId('g7le-inline-binding-append')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('S9-N4: lang named-param 노드 데이터 추가 → insertDataKeyify(신규 custom 키 POST) — lang 키 미오염', async () => {
|
||||
const { calls } = stubKeyifyFetch();
|
||||
const onPatch = vi.fn();
|
||||
const node: EditorNode = {
|
||||
name: 'Span',
|
||||
text: '$t:user.identity.challenge.remaining_attempts|count={{Math.max(0, (_local.maxAttempts ?? 0) - (_local.attempts ?? 0))}}',
|
||||
};
|
||||
renderSection(node, onPatch);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-search-toggle-append'));
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}'));
|
||||
// 신규 custom 키 생성(POST) — appendParam(PUT to lang key)이 아니라 키화 경로.
|
||||
await waitFor(() => expect(calls.some((c) => c.method === 'POST')).toBe(true));
|
||||
// node.text 가 새 custom 키로 치환(lang 키를 키 토큰으로 쓰지 않음).
|
||||
await waitFor(() => expect(onPatch).toHaveBeenCalled());
|
||||
const patched = onPatch.mock.calls.at(-1)![0];
|
||||
expect(patched.text).toContain('$t:custom.home.');
|
||||
expect(patched.text).not.toContain('$t:user.identity');
|
||||
});
|
||||
});
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
// e2e:allow 레이아웃 편집기 인라인 칩 편집 오버레이 — contentEditable/드래그 의존, Chrome MCP + 단위로 검증
|
||||
/**
|
||||
* InlineParamChipEditor.test.tsx — param 키 인라인 칩 편집 오버레이 RTL
|
||||
*
|
||||
* - 현재 로케일 키 값 fetch → 칩+평문 렌더(칩=드래그 뱃지)
|
||||
* - 평문 변경 후 저장 → 단일 로케일 키 값 PUT(다른 로케일 보존)
|
||||
* - 변경 없음 → PUT 미발생(onCommit)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
|
||||
import { InlineParamChipEditor } from '../../components/InlineParamChipEditor';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
import type { OverlayBox } from '../../utils/overlayGeometry';
|
||||
import { getPendingValue, clearPending } from '../../hooks/pendingCustomTranslations';
|
||||
|
||||
const t = (k: string) => k;
|
||||
const box: OverlayBox = { top: 0, left: 0, width: 100, height: 20, scale: 1 } as OverlayBox;
|
||||
afterEach(() => { cleanup(); vi.restoreAllMocks(); clearPending(); });
|
||||
beforeEach(() => { localStorage.setItem('auth_token', 'tok'); clearPending(); });
|
||||
|
||||
function stub(rowValues: Record<string, string>) {
|
||||
const calls: Array<{ url: string; method: string; body: any }> = [];
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
|
||||
const method = init?.method ?? 'GET';
|
||||
const body = init?.body ? JSON.parse(init.body as string) : null;
|
||||
calls.push({ url, method, body });
|
||||
if (url.includes('/custom-translations') && method === 'GET') {
|
||||
return { ok: true, status: 200, json: async () => ({ data: [{ id: 7, translation_key: 'custom.home.5', values: rowValues, lock_version: 1 }] }) } as Response;
|
||||
}
|
||||
if (url.includes('/custom-translations/') && method === 'PUT') {
|
||||
return { ok: true, status: 200, json: async () => ({ data: { id: 7, lock_version: 2 } }) } as Response;
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ data: { cache_version: 1 } }) } as Response;
|
||||
}));
|
||||
return { calls };
|
||||
}
|
||||
|
||||
const node: EditorNode = { name: 'Span', text: '$t:custom.home.5|p0={{user.name}}' };
|
||||
|
||||
describe('InlineParamChipEditor', () => {
|
||||
it('현재 로케일 키 값 fetch → 칩(드래그 뱃지) + 평문 렌더', async () => {
|
||||
stub({ ko: '{p0} 님 환영', en: '' });
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-inline-param-chip-editor')).toBeTruthy());
|
||||
// 칩(드래그 가능 원자) 렌더.
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
const chip = screen.getByTestId('g7le-chip-inline-p0');
|
||||
expect(chip).toHaveAttribute('contenteditable', 'false');
|
||||
// 포인터 기반 드래그 — grab 커서로 드래그 어포던스.
|
||||
expect(chip).toHaveStyle({ cursor: 'grab' });
|
||||
});
|
||||
|
||||
it('평문 변경 후 저장 → 단일 로케일 버퍼 기록(즉시 PUT 아님, 다른 로케일 미기록)', async () => {
|
||||
const { calls } = stub({ ko: '{p0} 님 환영', en: 'Welcome {p0}' });
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
// 슬롯 [text(""), chip, text(" 님 환영")] — 칩 뒤 평문 = 인덱스 2.
|
||||
const span = document.querySelector('[data-testid="g7le-chip-text-inline-2"]') as HTMLElement;
|
||||
span.textContent = ' 님 안녕';
|
||||
fireEvent.input(span);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-param-chip-save'));
|
||||
// 즉시 PUT 없음 — 버퍼 기록(레이아웃 저장 시 flush). 자리표시 보존.
|
||||
await waitFor(() => expect(getPendingValue('custom.home.5', 'ko')).toContain('{p0}'));
|
||||
expect(calls.some((c) => c.method === 'PUT')).toBe(false);
|
||||
expect(getPendingValue('custom.home.5', 'en')).toBeUndefined(); // 다른 로케일 미기록
|
||||
await waitFor(() => expect(onCommit).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it('외부 클릭 시 닫힘(commit) — 편집 중 다른 엘리먼트 클릭', async () => {
|
||||
stub({ ko: '{p0} 님 환영', en: '' });
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<div>
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t} onCommit={onCommit} onCancel={vi.fn()} />
|
||||
<button data-testid="outside-el">바깥</button>
|
||||
</div>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
// 편집기 바깥 엘리먼트 pointerdown(캡처) → 닫힘(commit) 발화.
|
||||
const outside = screen.getByTestId('outside-el');
|
||||
outside.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
|
||||
await waitFor(() => expect(onCommit).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it('변경 없음 → PUT 미발생 + onCommit', async () => {
|
||||
const { calls } = stub({ ko: '{p0} 님 환영', en: '' });
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-param-chip-save'));
|
||||
await waitFor(() => expect(onCommit).toHaveBeenCalled());
|
||||
expect(calls.some((c) => c.method === 'PUT')).toBe(false);
|
||||
});
|
||||
|
||||
// === '+데이터' 커서 위치 삽입 =========================================
|
||||
// PlaceholderChipInput 의 '+데이터' 버튼은 onInsertBinding 이 주입됐을 때만 노출되고, 클릭하면
|
||||
// 커서 위치 피커가 열린다(InlineBindingScalarPicker, defaultOpen). 후보 선택 시 onInsertBinding 이
|
||||
// 커서 charIndex + 후보로 호출되고, 반환된 키 값으로 칩 문장이 즉시 갱신된다.
|
||||
const candidates = [
|
||||
{ expression: '{{user.name}}', source: 'data_source', sourceId: 'user', path: 'name', shape: 'scalar', preview: '샘플', labelKey: undefined, groupLabelKey: undefined } as any,
|
||||
];
|
||||
|
||||
it('onInsertBinding 미전달 → +데이터 버튼 숨김', async () => {
|
||||
stub({ ko: '{p0} 님 환영', en: '' });
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
expect(screen.queryByTestId('g7le-chip-insert-inline')).toBeNull();
|
||||
});
|
||||
|
||||
it('onInsertBinding 전달 → +데이터 버튼 노출 + 클릭 시 피커 열림', async () => {
|
||||
stub({ ko: '{p0} 님 환영', en: '' });
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t}
|
||||
candidates={candidates} onInsertBinding={vi.fn(async () => null)} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
const insertBtn = screen.getByTestId('g7le-chip-insert-inline');
|
||||
expect(insertBtn).toBeTruthy();
|
||||
fireEvent.click(insertBtn);
|
||||
// 피커가 defaultOpen 으로 즉시 결과 목록을 보여준다.
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-inline-param-chip-insert-picker')).toBeTruthy());
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-inline-binding-picker-inline-insert')).toBeTruthy());
|
||||
});
|
||||
|
||||
it('후보 선택 → onInsertBinding(커서 charIndex, 후보) 호출 + 반환 키 값으로 칩 문장 갱신', async () => {
|
||||
stub({ ko: '{p0} 님 환영', en: '' });
|
||||
// 끝(charIndex=키값 길이)에 새 칩 삽입 → 키 값 `{p0} 님 환영{p1}` 반환 시뮬레이션.
|
||||
const onInsertBinding = vi.fn(async (_charIndex: number, _c: any) => '{p0} 님 환영{p1}');
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t}
|
||||
candidates={candidates} onInsertBinding={onInsertBinding} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
fireEvent.click(screen.getByTestId('g7le-chip-insert-inline'));
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}')).toBeTruthy());
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}'));
|
||||
// onInsertBinding 이 커서 charIndex(selection 없으면 키 값 길이=끝) + 후보로 호출됨.
|
||||
await waitFor(() => expect(onInsertBinding).toHaveBeenCalled());
|
||||
// 피커가 resolvedLabel 을 덧붙여 넘기므로 객체 동일성이 아닌 식별 필드로 대조.
|
||||
expect(onInsertBinding.mock.calls[0][1].expression).toBe('{{user.name}}');
|
||||
expect(onInsertBinding.mock.calls[0][1].path).toBe('name');
|
||||
// charIndex 는 selection 부재 시 키 값 길이(끝). 끝 삽입 → number.
|
||||
expect(typeof onInsertBinding.mock.calls[0][0]).toBe('number');
|
||||
// 반환 키 값으로 두 번째 칩(p1) 이 추가 렌더 — 칩 문장 즉시 갱신(라이브).
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p1')).toBeTruthy());
|
||||
// 삽입 후 피커는 닫힌다(insertAt=null).
|
||||
await waitFor(() => expect(screen.queryByTestId('g7le-inline-param-chip-insert-picker')).toBeNull());
|
||||
});
|
||||
|
||||
it('S9-N2 회귀: 미커밋 로컬 변경(칩 드래그/평문) 후 +데이터 → 삽입 전 선커밋(이동 소실 방지)', async () => {
|
||||
// 결함 — 칩 드래그 이동은 위젯 로컬 state(onChange)에만 있고 commit 시점에 버퍼 기록되는데,
|
||||
// '+데이터' 삽입(insertBindingIntoParamKey)은 pending/서버 값 기준으로 키 값을 재구성한다.
|
||||
// 선커밋 없이는 드래그 직후 '+데이터' 시 그 이동이 통째로 소실된다(라이브 .70 4칩 실측 —
|
||||
// ③-C/④-A 이동이 ④-B 추가 시 DB 저장값 순서로 되돌아감). 삽입 전 로컬 변경을 버퍼에
|
||||
// 먼저 커밋해야 onInsertBinding 이 최신 문장 기반으로 삽입한다.
|
||||
stub({ ko: '{p0} 님 환영', en: '' });
|
||||
let pendingAtInsert: string | undefined;
|
||||
const onInsertBinding = vi.fn(async (_charIndex: number, _c: any) => {
|
||||
pendingAtInsert = getPendingValue('custom.home.5', 'ko'); // 호출 시점의 버퍼 상태 캡처.
|
||||
return '{p0} 님 환영함{p1}';
|
||||
});
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={node} customKey="custom.home.5" templateIdentifier="tpl" locale="ko" t={t}
|
||||
candidates={candidates} onInsertBinding={onInsertBinding} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
// 로컬 변경(커밋 전) — 평문 수정. 칩 드래그도 동일 onChange 경로라 등가.
|
||||
const span = document.querySelector('[data-testid="g7le-chip-text-inline-2"]') as HTMLElement;
|
||||
span.textContent = ' 님 환영함';
|
||||
fireEvent.input(span);
|
||||
// 커밋 없이 곧바로 '+데이터' → 후보 선택.
|
||||
fireEvent.click(screen.getByTestId('g7le-chip-insert-inline'));
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}')).toBeTruthy());
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-binding-candidate-{{user.name}}'));
|
||||
await waitFor(() => expect(onInsertBinding).toHaveBeenCalled());
|
||||
// 핵심: onInsertBinding 호출 **시점**에 로컬 변경이 이미 버퍼에 선커밋되어 있어야 한다.
|
||||
expect(pendingAtInsert).toBe('{p0} 님 환영함');
|
||||
});
|
||||
|
||||
// === 미키화 데이터 노드 — 칩 온 엔트리 ============================
|
||||
// 데이터 든 미키화 노드(plain_with_binding)는 customKey 가 없다. initialChipValue(파생 자리표시
|
||||
// 문장) + chipParamLabels 로 칩을 첫 진입부터 렌더하고, 내용 변경 시 onKeyify 로 키화한다.
|
||||
const unkeyedNode: EditorNode = { name: 'Span', text: '$t:policy.published_at: {{termsContent?.data?.published_at | date}}' };
|
||||
|
||||
it('미키화 노드: customKey=null + initialChipValue → fetch 없이 즉시 칩 렌더(데이터 칩)', async () => {
|
||||
const { calls } = stub({});
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={unkeyedNode} customKey={null}
|
||||
initialChipValue="발행일: {p0}" chipParamLabels={{ p0: 'published_at' }}
|
||||
onKeyify={vi.fn(async () => 'custom.home.9')}
|
||||
templateIdentifier="tpl" locale="ko" t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-inline-param-chip-editor')).toBeTruthy());
|
||||
// 데이터 칩 즉시 렌더(키 없이 파생 값에서).
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
// 키가 없으므로 custom-translations GET fetch 미발생(파생 값 사용).
|
||||
expect(calls.some((c) => c.url.includes('/custom-translations') && c.method === 'GET')).toBe(false);
|
||||
// 칩 라벨 = chipParamLabels 의 친화명.
|
||||
expect(screen.getByTestId('g7le-chip-inline-p0').textContent).toContain('published_at');
|
||||
});
|
||||
|
||||
it('미키화 노드: 평문 변경 후 저장 → onKeyify(편집된 키 값) 호출 (내용 변경 시 키 생성)', async () => {
|
||||
stub({});
|
||||
const onKeyify = vi.fn(async () => 'custom.home.9');
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={unkeyedNode} customKey={null}
|
||||
initialChipValue="발행일: {p0}" chipParamLabels={{ p0: 'published_at' }}
|
||||
onKeyify={onKeyify} templateIdentifier="tpl" locale="ko" t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
// 슬롯 [text("발행일: "), chip, text("")] — 앞 평문(인덱스 0) 변경.
|
||||
const span = document.querySelector('[data-testid="g7le-chip-text-inline-0"]') as HTMLElement;
|
||||
span.textContent = '발행일자: ';
|
||||
fireEvent.input(span);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-param-chip-save'));
|
||||
// 내용 변경됨 → onKeyify 호출(키 생성). 편집된 키 값 전달.
|
||||
await waitFor(() => expect(onKeyify).toHaveBeenCalled());
|
||||
expect(onKeyify.mock.calls[0][0]).toContain('{p0}'); // 자리표시 보존된 키 값
|
||||
await waitFor(() => expect(onCommit).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it('미키화 노드: 변경 없이 저장 → onKeyify 미호출 (내용 변경 시에만 키 생성)', async () => {
|
||||
stub({});
|
||||
const onKeyify = vi.fn(async () => 'custom.home.9');
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineParamChipEditor box={box} node={unkeyedNode} customKey={null}
|
||||
initialChipValue="발행일: {p0}" chipParamLabels={{ p0: 'published_at' }}
|
||||
onKeyify={onKeyify} templateIdentifier="tpl" locale="ko" t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId('g7le-chip-inline-p0')).toBeTruthy());
|
||||
// 변경 없이 바로 저장.
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-param-chip-save'));
|
||||
await waitFor(() => expect(onCommit).toHaveBeenCalled());
|
||||
expect(onKeyify).not.toHaveBeenCalled(); // 키 생성 안 함.
|
||||
});
|
||||
});
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* InlineTextEditor.test.tsx — 더블클릭 인라인 텍스트 편집 RTL
|
||||
*
|
||||
* - 마운트 시 초기값 주입 + 포커스.
|
||||
* - Enter → onCommit(편집값), Escape → onCancel, blur → onCommit.
|
||||
* - 커스텀 키 노드 vs 평문 노드의 힌트 배지 분기.
|
||||
* - 빈값 경고 표시.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { InlineTextEditor } from '../../components/InlineTextEditor';
|
||||
import type { OverlayBox } from '../../utils/overlayGeometry';
|
||||
|
||||
const t = (k: string) => k;
|
||||
const box: OverlayBox = { left: 10, top: 20, width: 100, height: 24, scale: 1 };
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('InlineTextEditor', () => {
|
||||
it('초기값을 contentEditable 에 주입한다', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="환영합니다" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-inline-text-editable').textContent).toBe('환영합니다');
|
||||
});
|
||||
|
||||
it('Enter → onCommit(현재값)', () => {
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="old" isCustomKey={false} t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
el.textContent = 'new value';
|
||||
fireEvent.keyDown(el, { key: 'Enter' });
|
||||
expect(onCommit).toHaveBeenCalledWith('new value');
|
||||
});
|
||||
|
||||
it('Escape → onCancel (onCommit 미발화)', () => {
|
||||
const onCommit = vi.fn();
|
||||
const onCancel = vi.fn();
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={onCommit} onCancel={onCancel} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
fireEvent.keyDown(el, { key: 'Escape' });
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
expect(onCommit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('blur → onCommit', () => {
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="hello" isCustomKey={false} t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
fireEvent.blur(el);
|
||||
expect(onCommit).toHaveBeenCalledWith('hello');
|
||||
});
|
||||
|
||||
it('Enter 후 blur 가 와도 onCommit 은 1회만 (중복 가드)', () => {
|
||||
const onCommit = vi.fn();
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="a" isCustomKey={false} t={t} onCommit={onCommit} onCancel={vi.fn()} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
fireEvent.keyDown(el, { key: 'Enter' });
|
||||
fireEvent.blur(el);
|
||||
expect(onCommit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('커스텀 키 노드 → "기존 키" 힌트, 평문 → "신규 키" 힌트', () => {
|
||||
const { rerender } = render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-inline-text-editor').dataset.customKey).toBe('true');
|
||||
expect(screen.getByText(/existing_key_hint/)).toBeTruthy();
|
||||
|
||||
rerender(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByText(/new_key_hint/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('onOpenTranslations 제공 시 힌트 배지가 클릭형 버튼 → 클릭 시 콜백', () => {
|
||||
const onOpenTranslations = vi.fn();
|
||||
render(
|
||||
<InlineTextEditor
|
||||
box={box}
|
||||
initialValue="x"
|
||||
isCustomKey={false}
|
||||
t={t}
|
||||
onCommit={vi.fn()}
|
||||
onCancel={vi.fn()}
|
||||
onOpenTranslations={onOpenTranslations}
|
||||
/>,
|
||||
);
|
||||
const btn = screen.getByTestId('g7le-inline-text-editor-open-translations');
|
||||
expect(btn.tagName).toBe('BUTTON');
|
||||
// "모든 언어 편집" 진입 라벨 노출.
|
||||
expect(btn.textContent).toContain('open_translations');
|
||||
fireEvent.click(btn);
|
||||
expect(onOpenTranslations).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onOpenTranslations 미제공 시 배지는 정적 안내(버튼 아님)', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-inline-text-editor-open-translations')).toBeNull();
|
||||
// 안내 텍스트는 여전히 표시.
|
||||
expect(screen.getByText(/new_key_hint/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('빈값일 때 경고 표시', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-inline-text-editor-empty-warn')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('mirrorClassName/Style 을 contentEditable 에 명령형 반영', () => {
|
||||
const { rerender } = render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorClassName="text-lg font-semibold" mirrorStyle={{ color: 'rgb(10, 20, 30)' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.className).toBe('text-lg font-semibold');
|
||||
expect(el.style.color).toBe('rgb(10, 20, 30)');
|
||||
// 서식 변경(굵기 토글) 미러 — mirrorClassName 갱신 시 contentEditable className 즉시 반영.
|
||||
rerender(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorClassName="text-lg font-bold" mirrorStyle={{ color: 'rgb(10, 20, 30)' }} />,
|
||||
);
|
||||
expect(el.className).toBe('text-lg font-bold');
|
||||
});
|
||||
|
||||
it('classToken 색(text-blue-600)이 인라인 폴백색에 가려지지 않는다 — 인라인 color 미설정', () => {
|
||||
// mirrorClassName 에 색 토큰이 있고 mirrorStyle.color 가 없으면, 편집 오버레이는 인라인 color 를
|
||||
// 깔지 않아야 한다(template CSS 의 색 토큰이 적용되도록). 종전엔 항상 '#0f172a' 폴백을 깔아
|
||||
// classToken 색이 인라인 우선순위에 가려 편집 중 색 변경이 안 보였다.
|
||||
render(
|
||||
<InlineTextEditor
|
||||
box={box}
|
||||
initialValue="x"
|
||||
isCustomKey={false}
|
||||
t={t}
|
||||
onCommit={vi.fn()}
|
||||
onCancel={vi.fn()}
|
||||
mirrorClassName="text-2xl font-bold text-blue-600"
|
||||
/>,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.className).toContain('text-blue-600');
|
||||
// 인라인 color 가 비어 있어야 className 색 토큰이 우선한다.
|
||||
expect(el.style.color).toBe('');
|
||||
});
|
||||
|
||||
it('styleProp 색(mirrorStyle.color)은 그대로 적용 (className 무관)', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: 'rgb(220, 38, 38)' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.color).toBe('rgb(220, 38, 38)');
|
||||
});
|
||||
|
||||
it('색 출처가 전혀 없으면 가독성 폴백색(#0f172a) 적용', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.color).toBe('rgb(15, 23, 42)');
|
||||
});
|
||||
|
||||
it('흰 글자색(mirrorStyle.color) → 오버레이 배경을 어둡게 전환 (흰 배경 위 흰 글자 묻힘 회귀)', () => {
|
||||
// 글자색이 흰색인 노드(원래 어두운 배경 위라 캔버스에선 보임)를 인라인 편집할 때,
|
||||
// 오버레이가 흰 배경을 깔면 흰 글자 + 흰 배경으로 타이핑 텍스트가 안 보인다.
|
||||
// 글자색 밝기를 측정해 밝은 글자면 오버레이 배경을 어둡게 전환해 대비를 보장한다.
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="흰색 텍스트" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: 'rgb(255, 255, 255)' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
// 글자색은 흰색 그대로(색 출처 존중).
|
||||
expect(el.style.color).toBe('rgb(255, 255, 255)');
|
||||
// 배경은 흰색이 아니라 어두운 색으로 전환되어야 한다.
|
||||
expect(el.style.background).not.toBe('#ffffff');
|
||||
expect(el.style.background).not.toBe('rgb(255, 255, 255)');
|
||||
expect(el.style.background).toBe('rgb(15, 23, 42)');
|
||||
});
|
||||
|
||||
it('어두운 글자색(mirrorStyle.color) → 오버레이 배경은 흰색 유지', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: 'rgb(15, 23, 42)' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(255, 255, 255)');
|
||||
});
|
||||
|
||||
it('색 출처가 없으면 오버레이 배경은 흰색 유지(폴백 글자색이 어두우므로)', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(255, 255, 255)');
|
||||
});
|
||||
|
||||
it('#rrggbb 흰색 글자색도 어두운 배경으로 전환 (hex 색 파싱)', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: '#ffffff' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(15, 23, 42)');
|
||||
});
|
||||
|
||||
it('밝은 회색(#e5e7eb) 글자색도 어두운 배경으로 전환 (밝기 임계값)', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: '#e5e7eb' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(15, 23, 42)');
|
||||
});
|
||||
|
||||
it('중간 명도 회색(#6b7280) 글자색은 흰 배경 유지 (대비 확보)', () => {
|
||||
// 다크 모드에서 흔한 중간 회색. 임계값(180) 미만이라 어둡다고 판정 → 흰 배경(대비 OK).
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: '#6b7280' }} />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(255, 255, 255)');
|
||||
});
|
||||
|
||||
it('nodeEffectiveColor(흰색) → 어두운 배경 + 그 색을 명시 글자색으로 적용 (다크 컨텍스트 패리티)', () => {
|
||||
// 다크 모드에서 dark:text-white 노드는 캔버스에선 흰 글자지만, 오버레이는 다크 컨텍스트 밖이라
|
||||
// 자체 computed 로는 색이 어긋난다. EditorCanvasOverlay 가 측정한 nodeEffectiveColor 를 받아
|
||||
// ① 어두운 배경 ② 캔버스와 같은 흰 글자색을 적용한다.
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="회원가입" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorClassName="text-2xl font-bold text-gray-900 dark:text-white"
|
||||
nodeEffectiveColor="rgb(255, 255, 255)" />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(15, 23, 42)');
|
||||
expect(el.style.color).toBe('rgb(255, 255, 255)');
|
||||
});
|
||||
|
||||
it('nodeEffectiveColor(oklch 밝은 L) → 어두운 배경 (Tailwind v4 oklch 파싱)', () => {
|
||||
// 이 템플릿(Tailwind v4)은 oklch 색을 쓴다. rgb 파싱이 안 되던 결함 — oklch L 값으로 판정.
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
nodeEffectiveColor="oklch(0.985 0.002 247.839)" />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(15, 23, 42)');
|
||||
expect(el.style.color).toBe('oklch(0.985 0.002 247.839)');
|
||||
});
|
||||
|
||||
it('nodeEffectiveColor(oklch 어두운 L) → 흰 배경 유지', () => {
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
nodeEffectiveColor="oklch(0.21 0.034 264.665)" />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(255, 255, 255)');
|
||||
});
|
||||
|
||||
it('nodeEffectiveColor 가 mirrorStyle.color 보다 우선 (대상 노드 측정값 신뢰)', () => {
|
||||
// mirror 는 어두운 인라인색이라도, 대상 노드의 캔버스 측정색(흰색)이 우선 → 어두운 배경.
|
||||
render(
|
||||
<InlineTextEditor box={box} initialValue="x" isCustomKey={false} t={t} onCommit={vi.fn()} onCancel={vi.fn()}
|
||||
mirrorStyle={{ color: 'rgb(15, 23, 42)' }}
|
||||
nodeEffectiveColor="rgb(255, 255, 255)" />,
|
||||
);
|
||||
const el = screen.getByTestId('g7le-inline-text-editable');
|
||||
expect(el.style.background).toBe('rgb(15, 23, 42)');
|
||||
expect(el.style.color).toBe('rgb(255, 255, 255)');
|
||||
});
|
||||
});
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* InlineTextToolbar.test.tsx — 인라인 편집 서식 툴바 RTL
|
||||
*
|
||||
* - 스펙 기반 버튼 노출: componentCapabilities[name].styleControls 의 텍스트 서식만.
|
||||
* - styleControls 미선언 컴포넌트 → 툴바 부재(null).
|
||||
* - 목록·표·이미지 버튼 부재(서식 툴바는 props/style 변경만).
|
||||
* - 클릭 → applyRecipe 와 동일 패치 호출(컨트롤 동일성 — 속성 모달과 같은 엔진).
|
||||
* - 서식이 텍스트 컴포넌트 전체에 적용(substring 부분 서식 미지원 — 노드 props/className).
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { InlineTextToolbar } from '../../components/InlineTextToolbar';
|
||||
import type { EditorSpec } from '../../spec/specTypes';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
import type { OverlayBox } from '../../utils/overlayGeometry';
|
||||
|
||||
const t = (k: string) => k;
|
||||
const box: OverlayBox = { left: 0, top: 60, width: 120, height: 24, scale: 1 };
|
||||
|
||||
const spec: EditorSpec = {
|
||||
controls: {
|
||||
fontWeight: {
|
||||
widget: 'segmented',
|
||||
group: 'font-weight',
|
||||
// 실제 번들 스펙과 동일한 3지 세그먼트(normal/semibold/bold) — 'B' 버튼은 옵션 순환이
|
||||
// 아니라 bold 전용 토글이어야 한다.
|
||||
options: [
|
||||
{ value: 'font-normal', apply: { type: 'classToken', tokens: ['font-normal'] } },
|
||||
{ value: 'font-semibold', apply: { type: 'classToken', tokens: ['font-semibold'] } },
|
||||
{ value: 'font-bold', apply: { type: 'classToken', tokens: ['font-bold'] } },
|
||||
],
|
||||
},
|
||||
textAlign: {
|
||||
widget: 'segmented',
|
||||
group: 'text-align',
|
||||
options: [
|
||||
{ value: 'left', apply: { type: 'classToken', tokens: ['text-left'] } },
|
||||
{ value: 'center', apply: { type: 'classToken', tokens: ['text-center'] } },
|
||||
],
|
||||
},
|
||||
fontSize: { widget: 'dimension', apply: { type: 'styleProp', prop: 'fontSize' } },
|
||||
textColor: { widget: 'color', group: 'text-color', apply: { type: 'styleProp', prop: 'color' } },
|
||||
},
|
||||
componentCapabilities: {
|
||||
H1: { styleControls: ['fontWeight', 'textAlign', 'fontSize', 'textColor'] },
|
||||
Span: { styleControls: ['fontWeight'] },
|
||||
Icon: {}, // styleControls 미선언
|
||||
},
|
||||
} as unknown as EditorSpec;
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('InlineTextToolbar', () => {
|
||||
it('styleControls 에 선언된 서식 버튼만 노출', () => {
|
||||
const node: EditorNode = { name: 'H1', text: '제목' };
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={vi.fn()} box={box} />);
|
||||
expect(screen.getByTestId('g7le-inline-format-fontWeight')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-inline-format-textAlign')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-inline-format-fontSize')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-inline-format-textColor')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Span 은 fontWeight 만 선언 → 굵기 버튼만, 나머지 부재', () => {
|
||||
const node: EditorNode = { name: 'Span', text: '글' };
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={vi.fn()} box={box} />);
|
||||
expect(screen.getByTestId('g7le-inline-format-fontWeight')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-inline-format-textAlign')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-inline-format-fontSize')).toBeNull();
|
||||
});
|
||||
|
||||
it('styleControls 미선언 컴포넌트 → 툴바 자체 부재(null)', () => {
|
||||
const node: EditorNode = { name: 'Icon' };
|
||||
const { container } = render(
|
||||
<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={vi.fn()} box={box} />,
|
||||
);
|
||||
expect(container.querySelector('[data-testid="g7le-inline-toolbar"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('목록/표/이미지 같은 요소-추가 버튼은 노출하지 않는다', () => {
|
||||
const node: EditorNode = { name: 'H1', text: '제목' };
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={vi.fn()} box={box} />);
|
||||
expect(screen.queryByTestId('g7le-inline-format-list')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-inline-format-table')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-inline-format-image')).toBeNull();
|
||||
});
|
||||
|
||||
it('굵기 버튼 클릭 → applyFn 을 fresh 노드에 적용 시 font-bold 토큰 (substring 아님)', () => {
|
||||
const node: EditorNode = { name: 'Span', text: '글' };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-fontWeight'));
|
||||
expect(onApplyControl).toHaveBeenCalledTimes(1);
|
||||
const [controlKey, applyFn] = onApplyControl.mock.calls[0];
|
||||
expect(controlKey).toBe('fontWeight');
|
||||
// applyFn 을 fresh 노드(미적용 상태)에 적용 → 첫 적용 옵션(bold) → font-bold 토큰.
|
||||
const patched = applyFn(node);
|
||||
expect((patched.props?.className as string) ?? '').toContain('font-bold');
|
||||
});
|
||||
|
||||
it('연속 토글 — applyFn 이 매번 fresh 노드 기준 (켜기 → 끄기)', () => {
|
||||
const node: EditorNode = { name: 'Span', text: '글' };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-fontWeight'));
|
||||
const applyFn = onApplyControl.mock.calls[0][1] as (n: EditorNode) => EditorNode;
|
||||
// 1차: 미적용 → bold
|
||||
const bolded = applyFn(node);
|
||||
expect((bolded.props?.className as string) ?? '').toContain('font-bold');
|
||||
// 2차: 이미 bold 인 fresh 노드 → 다음 옵션(normal=clearGroup) → font-bold 제거
|
||||
const unbolded = applyFn(bolded);
|
||||
expect((unbolded.props?.className as string) ?? '').not.toContain('font-bold');
|
||||
});
|
||||
|
||||
it('3지 세그먼트(normal/semibold/bold)에서 B 버튼은 bold 로 직행(semibold 거치지 않음) + 재클릭 해제', () => {
|
||||
// 미적용 노드에서 B 클릭 → font-bold (옵션 순환으로 font-normal 이 되면 안 됨).
|
||||
const node: EditorNode = { name: 'Span', text: '글' };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-fontWeight'));
|
||||
const applyFn = onApplyControl.mock.calls[0][1] as (n: EditorNode) => EditorNode;
|
||||
const bolded = applyFn(node);
|
||||
const boldedCls = (bolded.props?.className as string) ?? '';
|
||||
expect(boldedCls).toContain('font-bold');
|
||||
expect(boldedCls).not.toContain('font-normal');
|
||||
expect(boldedCls).not.toContain('font-semibold');
|
||||
// 이미 bold 인 노드에서 B 재클릭 → 해제(font-bold 제거).
|
||||
const unbolded = applyFn(bolded);
|
||||
expect((unbolded.props?.className as string) ?? '').not.toContain('font-bold');
|
||||
});
|
||||
|
||||
it('이미 semibold 인 노드에서 B 클릭 → bold 로 전환(semibold 교체) — 옵션 순환 아님', () => {
|
||||
const node: EditorNode = { name: 'Span', text: '글', props: { className: 'font-semibold' } };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-fontWeight'));
|
||||
const applyFn = onApplyControl.mock.calls[0][1] as (n: EditorNode) => EditorNode;
|
||||
const patched = applyFn(node);
|
||||
const cls = (patched.props?.className as string) ?? '';
|
||||
expect(cls).toContain('font-bold');
|
||||
expect(cls).not.toContain('font-semibold');
|
||||
});
|
||||
|
||||
it('정렬 버튼 클릭 → popover 열림(단순 토글/순환 아님), 옵션 선택 시 그 값 적용', () => {
|
||||
const node: EditorNode = { name: 'H1', text: '제목' };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
|
||||
// 버튼 클릭 자체는 적용을 발화하지 않고 popover 만 연다(토글/순환 아님).
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-textAlign'));
|
||||
expect(onApplyControl).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId('g7le-inline-popover-textAlign')).toBeInTheDocument();
|
||||
|
||||
// popover 에서 center 옵션 선택 → 그 값으로 적용(fresh 노드 기준).
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-option-textAlign-center'));
|
||||
expect(onApplyControl).toHaveBeenCalledTimes(1);
|
||||
const applyFn = onApplyControl.mock.calls[0][1] as (n: EditorNode) => EditorNode;
|
||||
const patched = applyFn(node);
|
||||
expect((patched.props?.className as string) ?? '').toContain('text-center');
|
||||
});
|
||||
|
||||
it('크기 버튼(옵션 없는 dimension) 클릭 → popover 열림, 자유값 입력칸 + Enter 적용 (단순 토글 아님)', () => {
|
||||
const node: EditorNode = { name: 'H1', text: '제목' };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-fontSize'));
|
||||
expect(onApplyControl).not.toHaveBeenCalled();
|
||||
const popover = screen.getByTestId('g7le-inline-popover-fontSize');
|
||||
expect(popover).toBeInTheDocument();
|
||||
|
||||
// fontSize 는 dimension(옵션 없음) → 자유값 입력칸으로 폴백. 값 입력 후 Enter → 적용.
|
||||
const input = screen.getByTestId('g7le-inline-freeinput-fontSize') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '24px' } });
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(onApplyControl).toHaveBeenCalledTimes(1);
|
||||
const applyFn = onApplyControl.mock.calls[0][1] as (n: EditorNode) => EditorNode;
|
||||
const patched = applyFn(node);
|
||||
expect((patched.props?.style as Record<string, unknown> | undefined)?.fontSize).toBe('24px');
|
||||
});
|
||||
|
||||
it('선택형(정렬/크기/색) 옵션 재선택 시 해제(toggle off) — 같은 값 클릭', () => {
|
||||
// 이미 text-center 인 노드.
|
||||
const node: EditorNode = { name: 'H1', text: '제목', props: { className: 'text-center' } };
|
||||
const onApplyControl = vi.fn();
|
||||
render(<InlineTextToolbar node={node} spec={spec} t={t} onApplyControl={onApplyControl} box={box} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-format-textAlign'));
|
||||
fireEvent.click(screen.getByTestId('g7le-inline-option-textAlign-center'));
|
||||
const applyFn = onApplyControl.mock.calls[0][1] as (n: EditorNode) => EditorNode;
|
||||
const patched = applyFn(node);
|
||||
// 현재값(center)과 같은 값 선택 → 해제 → text-center 제거.
|
||||
expect((patched.props?.className as string) ?? '').not.toContain('text-center');
|
||||
});
|
||||
});
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* InsertionAffordances 컴포넌트 테스트
|
||||
*
|
||||
* - 4방향 버튼 렌더 (활성/비활성)
|
||||
* - 비활성 + 버튼 클릭은 onAddRequest 미호출
|
||||
* - 활성 + 버튼 클릭은 해당 point 가 onAddRequest 로 전달
|
||||
* - selectedBox 가 null 이면 미렌더
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { InsertionAffordances } from '../../components/InsertionAffordances';
|
||||
import { buildPoints } from '../../hooks/useInsertionPoints';
|
||||
import { OVERLAY_AFFORDANCE } from '../../utils/overlayZIndex';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function withTranslation(node: React.ReactElement): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
{node}
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedBox = { left: 10, top: 20, width: 100, height: 50, scale: 1 };
|
||||
|
||||
describe('InsertionAffordances — block 부모', () => {
|
||||
it('상/하 활성, 좌/우 비활성', () => {
|
||||
const onAdd = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={selectedBox}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={onAdd}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-insertion-above').getAttribute('data-disabled')).toBe('false');
|
||||
expect(screen.getByTestId('g7le-insertion-below').getAttribute('data-disabled')).toBe('false');
|
||||
expect(screen.getByTestId('g7le-insertion-left').getAttribute('data-disabled')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-insertion-right').getAttribute('data-disabled')).toBe('true');
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-insertion-above'));
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
expect(onAdd.mock.calls[0][0].direction).toBe('above');
|
||||
|
||||
onAdd.mockClear();
|
||||
fireEvent.click(screen.getByTestId('g7le-insertion-left'));
|
||||
expect(onAdd).not.toHaveBeenCalled(); // 비활성 클릭은 콜백 무호출
|
||||
});
|
||||
});
|
||||
|
||||
describe('InsertionAffordances — flex_row_single', () => {
|
||||
it('좌/우 활성, 상/하 비활성', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={selectedBox}
|
||||
points={buildPoints('flex_row_single', [], 1)}
|
||||
onAddRequest={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-insertion-above').getAttribute('data-disabled')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-insertion-below').getAttribute('data-disabled')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-insertion-left').getAttribute('data-disabled')).toBe('false');
|
||||
expect(screen.getByTestId('g7le-insertion-right').getAttribute('data-disabled')).toBe('false');
|
||||
});
|
||||
});
|
||||
|
||||
describe('InsertionAffordances — 작은 박스 십자 배치', () => {
|
||||
const smallBox = { left: 200, top: 20, width: 6, height: 20, scale: 1 };
|
||||
|
||||
it('작은 박스(44px 미만)는 + 버튼이 박스 중심 기준 십자로 벌어짐 (data-placement=outside)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={smallBox}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const above = screen.getByTestId('g7le-insertion-above');
|
||||
const below = screen.getByTestId('g7le-insertion-below');
|
||||
const left = screen.getByTestId('g7le-insertion-left');
|
||||
const right = screen.getByTestId('g7le-insertion-right');
|
||||
expect(above.getAttribute('data-placement')).toBe('outside');
|
||||
// above/below 는 가로 중앙 동일 left, 세로로 분리(top 다름)
|
||||
expect(above.style.left).toBe(below.style.left);
|
||||
expect(above.style.top).not.toBe(below.style.top);
|
||||
// left/right 는 세로 중앙 동일 top, 가로로 분리(left 다름)
|
||||
expect(left.style.top).toBe(right.style.top);
|
||||
expect(left.style.left).not.toBe(right.style.left);
|
||||
});
|
||||
|
||||
it('큰 박스는 기존 inside 배치 유지 (data-placement=inside)', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={selectedBox}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-insertion-above').getAttribute('data-placement')).toBe('inside');
|
||||
});
|
||||
|
||||
it('큰 박스(inside)에서 + 버튼이 박스 변 바깥 30px 여백으로 밀려 핸들/코너와 겹치지 않음', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={selectedBox}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// 종전 -12 는 24px 버튼이 변에 절반 걸쳐 모서리 리사이즈 핸들(±-4)과 겹쳤다.
|
||||
// INSERTION_GAP=30 으로 박스 바깥으로 완전히 밀어낸다.
|
||||
expect(screen.getByTestId('g7le-insertion-above').style.top).toBe('-30px');
|
||||
expect(screen.getByTestId('g7le-insertion-below').style.bottom).toBe('-30px');
|
||||
expect(screen.getByTestId('g7le-insertion-left').style.left).toBe('-30px');
|
||||
expect(screen.getByTestId('g7le-insertion-right').style.right).toBe('-30px');
|
||||
});
|
||||
|
||||
it('십자 배치에서도 활성/비활성 + 클릭 콜백은 동일 동작', () => {
|
||||
const onAdd = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={smallBox}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={onAdd}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-insertion-above'));
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
expect(onAdd.mock.calls[0][0].direction).toBe('above');
|
||||
});
|
||||
});
|
||||
|
||||
describe('InsertionAffordances — z-index 회귀', () => {
|
||||
it('+ 버튼은 드래그 핸들 위 어포던스 밴드(z-index) 로 렌더 — 클릭 가로채기 차단', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={selectedBox}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
// S5b 드래그 핸들이 z-index 미지정(≈0) 버튼 위로 올라와 +/ⓘ 클릭이 이동 포인터에
|
||||
// 가로채이던 회귀. 모든 + 버튼은 OVERLAY_AFFORDANCE z-index 로 핸들 위에 와야 한다.
|
||||
for (const dir of ['above', 'below', 'left', 'right']) {
|
||||
const btn = screen.getByTestId(`g7le-insertion-${dir}`);
|
||||
expect(btn.style.zIndex).toBe(String(OVERLAY_AFFORDANCE));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('InsertionAffordances — selectedBox null', () => {
|
||||
it('null 이면 렌더 자체를 안 함', () => {
|
||||
const { container } = render(
|
||||
withTranslation(
|
||||
<InsertionAffordances
|
||||
selectedBox={null}
|
||||
points={buildPoints('block', [], 0)}
|
||||
onAddRequest={vi.fn()}
|
||||
/>
|
||||
)
|
||||
);
|
||||
expect(container.querySelector('[data-testid="g7le-insertion-affordances"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
// e2e:allow 레이아웃 편집기 반복 데이터 연결 속성패널 UI — dnd-kit/합성 이벤트 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스 + 단위/레이아웃 렌더링 테스트로 검증 (DataBindingSection.test.tsx L1 과 동일 정책)
|
||||
/**
|
||||
* IterationBindingSection.test.tsx — 반복(iteration) 데이터 연결 영역 RTL
|
||||
*
|
||||
* 검증:
|
||||
* - iteration 노드 → "반복 데이터 연결" 영역 렌더(array 배지 + 힌트)
|
||||
* - iteration 없는 노드 → null(영역 비노출 — 노드 구조 기반 게이트)
|
||||
* - 미연결 → 검색 피커 → array 후보 선택 → node.iteration.source 기입(round-trip),
|
||||
* 다른 iteration 키(item_var) 보존
|
||||
* - 연결됨 → 표현식 + [해제] → source 키만 제거(iteration 객체는 유지)
|
||||
* - 복합 바인딩(`{{x ?? []}}`) → 디그레이드(코드 편집) 읽기전용, 검색 피커 미노출
|
||||
* - shape 필터: 배열 후보만 노출(scalar 후보 미노출)
|
||||
* - item_var/index_var 읽기전용 힌트 표시
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { IterationBindingSection } from '../../components/property-controls/IterationBindingSection';
|
||||
import type { BindingCandidate } from '../../spec/bindingCandidates';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
afterEach(() => cleanup());
|
||||
|
||||
const candidates: BindingCandidate[] = [
|
||||
{
|
||||
expression: '{{products.data.data}}',
|
||||
source: 'data_source',
|
||||
sourceId: 'products',
|
||||
path: 'data.data',
|
||||
shape: 'array',
|
||||
groupLabelKey: 'editor.ds.products',
|
||||
preview: '[3]',
|
||||
itemFields: ['name', 'price'],
|
||||
},
|
||||
{
|
||||
expression: '{{categories.data}}',
|
||||
source: 'data_source',
|
||||
sourceId: 'categories',
|
||||
path: 'data',
|
||||
shape: 'array',
|
||||
preview: '[5]',
|
||||
itemFields: ['id', 'name'],
|
||||
},
|
||||
{
|
||||
expression: '{{_local.keyword}}',
|
||||
source: '_local',
|
||||
sourceId: '_local',
|
||||
path: 'keyword',
|
||||
shape: 'scalar',
|
||||
preview: '노트북',
|
||||
},
|
||||
];
|
||||
|
||||
describe('IterationBindingSection — 게이트', () => {
|
||||
it('iteration 노드면 "반복 데이터 연결" 영역을 렌더한다', () => {
|
||||
const node: EditorNode = { name: 'Div', iteration: { source: '', item_var: 'item' } };
|
||||
render(<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-iteration-binding-section')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-iteration-binding-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('iteration 없는 노드면 null(영역 비노출)', () => {
|
||||
const node: EditorNode = { name: 'Div', props: {} };
|
||||
const { container } = render(
|
||||
<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={vi.fn()} />,
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('IterationBindingSection — 연결 round-trip', () => {
|
||||
it('검색 → array 후보만 노출(scalar 미노출) → 선택 시 iteration.source 기입 + item_var 보존', () => {
|
||||
const node: EditorNode = { name: 'Div', iteration: { source: '', item_var: 'product' } };
|
||||
const onPatchNode = vi.fn();
|
||||
render(<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={onPatchNode} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-iteration-binding-search-toggle'));
|
||||
expect(screen.getByTestId('g7le-iteration-binding-candidate-{{products.data.data}}')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-iteration-binding-candidate-{{categories.data}}')).toBeInTheDocument();
|
||||
// scalar 후보는 반복 소스 대상 아님 — 미노출
|
||||
expect(screen.queryByTestId('g7le-iteration-binding-candidate-{{_local.keyword}}')).toBeNull();
|
||||
fireEvent.click(screen.getByTestId('g7le-iteration-binding-candidate-{{products.data.data}}'));
|
||||
// 반복 소스는 항상 배열 → G7 표준 안전 형태(`?.` + `?? []`)로 기입.
|
||||
expect(onPatchNode).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
iteration: { source: '{{products?.data?.data ?? []}}', item_var: 'product' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('연결됨 → 표현식 표시 + [해제] → source 키만 제거(iteration 객체 유지)', () => {
|
||||
const node: EditorNode = {
|
||||
name: 'Div',
|
||||
iteration: { source: '{{products.data.data}}', item_var: 'product', index_var: 'i' },
|
||||
};
|
||||
const onPatchNode = vi.fn();
|
||||
render(<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={onPatchNode} />);
|
||||
expect(screen.getByTestId('g7le-iteration-binding-expr')).toHaveTextContent('{{products.data.data}}');
|
||||
fireEvent.click(screen.getByTestId('g7le-iteration-binding-clear'));
|
||||
expect(onPatchNode).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ iteration: { item_var: 'product', index_var: 'i' } }),
|
||||
);
|
||||
// source 키만 제거 — item_var/index_var 보존
|
||||
const patched = onPatchNode.mock.calls[0][0] as EditorNode;
|
||||
expect((patched.iteration as Record<string, unknown>).source).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('IterationBindingSection — G7 표준 안전 바인딩 인식', () => {
|
||||
// 실제 레이아웃의 iteration 소스는 전부 `?.` + `?? []` 표준 형태인데,
|
||||
// 이전 파서가 이를 복합식으로 묶어 "코드 편집" 디그레이드 → 검색 피커가 가려져 변경 불가.
|
||||
// 이제 안전 바인딩은 연결됨으로 인식하고 검색 피커로 변경 가능해야 한다.
|
||||
it('`{{products?.data?.data ?? []}}` 는 연결됨으로 인식 + 검색 피커로 변경 가능', () => {
|
||||
const node: EditorNode = {
|
||||
name: 'Div',
|
||||
iteration: { source: '{{products?.data?.data ?? []}}', item_var: 'product' },
|
||||
};
|
||||
const onPatchNode = vi.fn();
|
||||
render(<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={onPatchNode} />);
|
||||
// 복합 디그레이드 아님 — 연결됨 표현식 + 검색 토글 노출.
|
||||
expect(screen.queryByTestId('g7le-iteration-binding-complex')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-iteration-binding-expr')).toHaveTextContent('{{products?.data?.data ?? []}}');
|
||||
expect(screen.getByTestId('g7le-iteration-binding-search-toggle')).toBeInTheDocument();
|
||||
// 다른 소스로 변경 가능 — categories 선택 시 안전 형태로 재기입.
|
||||
fireEvent.click(screen.getByTestId('g7le-iteration-binding-search-toggle'));
|
||||
fireEvent.click(screen.getByTestId('g7le-iteration-binding-candidate-{{categories.data}}'));
|
||||
expect(onPatchNode).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
iteration: { source: '{{categories?.data ?? []}}', item_var: 'product' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('진짜 복합식(삼항·파이프)은 코드 편집 디그레이드 + 검색 피커 미노출', () => {
|
||||
const node: EditorNode = {
|
||||
name: 'Div',
|
||||
iteration: { source: '{{cond ? listA : listB}}', item_var: 'x' },
|
||||
};
|
||||
render(<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={vi.fn()} />);
|
||||
expect(screen.getByTestId('g7le-iteration-binding-complex')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-iteration-binding-search-toggle')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('IterationBindingSection — 반복 변수 힌트', () => {
|
||||
it('item_var/index_var 를 읽기전용 힌트로 표시', () => {
|
||||
const node: EditorNode = {
|
||||
name: 'Div',
|
||||
iteration: { source: '', item_var: 'product', index_var: 'idx' },
|
||||
};
|
||||
render(<IterationBindingSection node={node} candidates={candidates} t={t} onPatchNode={vi.fn()} />);
|
||||
const vars = screen.getByTestId('g7le-iteration-vars');
|
||||
expect(vars).toHaveTextContent('product');
|
||||
expect(vars).toHaveTextContent('idx');
|
||||
});
|
||||
});
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
// e2e:allow JSON 텍스트 편집 공용 부품 단위(RTL) — 파싱/검증/재시드 로직, 라이브는 초기 상태/데이터 탭 Chrome MCP 매트릭스로 보강.
|
||||
/**
|
||||
* JsonBlockField.test.tsx — 임의 JSON 값 텍스트 편집 공용 부품 RTL
|
||||
*
|
||||
* 검증:
|
||||
* ① value → pretty JSON 시드
|
||||
* ② 유효 JSON 입력 → onChange(파싱값) + validity true
|
||||
* ③ 깨진 JSON → 오류 표시 + onChange 미호출 + validity false (저장 차단)
|
||||
* ④ shape='object' 가드 — 배열/스칼라 입력 거부(validity false)
|
||||
* ⑤ 빈 문자열 → emptyValue
|
||||
* ⑥ 외부 value 재시드(편집 중이 아닐 때)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
import { JsonBlockField } from '../../components/JsonBlockField';
|
||||
|
||||
const t = (k: string) => k;
|
||||
|
||||
beforeEach(() => cleanup());
|
||||
|
||||
describe('JsonBlockField', () => {
|
||||
it('value 를 pretty JSON 으로 시드한다', () => {
|
||||
render(<JsonBlockField value={{ a: 1 }} onChange={vi.fn()} t={t} />);
|
||||
const ta = screen.getByTestId('g7le-json-block') as HTMLTextAreaElement;
|
||||
expect(ta.value).toBe('{\n "a": 1\n}');
|
||||
});
|
||||
|
||||
it('유효 JSON 입력 → onChange(파싱값) + validity true', () => {
|
||||
const onChange = vi.fn();
|
||||
const onValid = vi.fn();
|
||||
render(<JsonBlockField value={{}} onChange={onChange} onValidityChange={onValid} t={t} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-json-block'), { target: { value: '{"x": 2}' } });
|
||||
expect(onChange).toHaveBeenLastCalledWith({ x: 2 });
|
||||
expect(onValid).toHaveBeenLastCalledWith(true);
|
||||
expect(screen.queryByTestId('g7le-json-block-error')).toBeNull();
|
||||
});
|
||||
|
||||
it('깨진 JSON → 오류 표시 + onChange 미호출 + validity false', () => {
|
||||
const onChange = vi.fn();
|
||||
const onValid = vi.fn();
|
||||
render(<JsonBlockField value={{}} onChange={onChange} onValidityChange={onValid} t={t} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-json-block'), { target: { value: '{ broken' } });
|
||||
expect(screen.getByTestId('g7le-json-block-error')).toBeInTheDocument();
|
||||
expect(onValid).toHaveBeenLastCalledWith(false);
|
||||
// 깨진 입력은 흘리지 않는다(저장 차단).
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shape='object' — 배열/스칼라 입력 거부(validity false)", () => {
|
||||
const onChange = vi.fn();
|
||||
const onValid = vi.fn();
|
||||
render(<JsonBlockField value={{}} shape="object" onChange={onChange} onValidityChange={onValid} t={t} />);
|
||||
// 배열 — 거부.
|
||||
fireEvent.change(screen.getByTestId('g7le-json-block'), { target: { value: '[1,2]' } });
|
||||
expect(onValid).toHaveBeenLastCalledWith(false);
|
||||
expect(screen.getByTestId('g7le-json-block-error')).toBeInTheDocument();
|
||||
// 스칼라 — 거부.
|
||||
fireEvent.change(screen.getByTestId('g7le-json-block'), { target: { value: '42' } });
|
||||
expect(onValid).toHaveBeenLastCalledWith(false);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('빈 문자열 → emptyValue', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<JsonBlockField value={{ a: 1 }} emptyValue={{}} onChange={onChange} t={t} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-json-block'), { target: { value: '' } });
|
||||
expect(onChange).toHaveBeenLastCalledWith({});
|
||||
});
|
||||
|
||||
it('외부 value 재시드(편집 중이 아닐 때)', () => {
|
||||
const { rerender } = render(<JsonBlockField value={{ a: 1 }} onChange={vi.fn()} t={t} />);
|
||||
rerender(<JsonBlockField value={{ b: 2 }} onChange={vi.fn()} t={t} />);
|
||||
const ta = screen.getByTestId('g7le-json-block') as HTMLTextAreaElement;
|
||||
expect(ta.value).toBe('{\n "b": 2\n}');
|
||||
});
|
||||
});
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* LayoutEditorChrome 셸 테스트
|
||||
*
|
||||
* 검증:
|
||||
* - 셸이 같은 React tree 안에 마운트됨 (Provider 트리 안에서 동작)
|
||||
* - g7le- CSS 프리픽스 강제 (19.3 격리)
|
||||
* - 툴바 + 디바이스 미리보기 툴바 + 라우트 트리 패널 + 프리뷰 캔버스 통합
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { LayoutEditorChrome } from '../../LayoutEditorChrome';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function renderShell(): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorChrome templateIdentifier="sirsoft-admin_basic" initialLocale="ko" />
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('LayoutEditorChrome', () => {
|
||||
it('셸 + 툴바 + 디바이스 미리보기 툴바 + 라우트 트리 + 프리뷰 캔버스 모두 마운트', () => {
|
||||
renderShell();
|
||||
expect(screen.getByTestId('g7le-chrome')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-toolbar')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-chrome-device-toolbar')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-device-toolbar')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-route-tree-panel')).toBeTruthy();
|
||||
// 라우트 미선택 상태 — PreviewCanvas 의 empty placeholder 가 렌더됨
|
||||
expect(screen.getByTestId('g7le-preview-empty')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('셸 클래스에 g7le- 프리픽스 강제 (CSS 격리 — 19.3)', () => {
|
||||
renderShell();
|
||||
const chrome = screen.getByTestId('g7le-chrome');
|
||||
expect(chrome.className).toContain('g7le-');
|
||||
const toolbar = screen.getByTestId('g7le-toolbar');
|
||||
expect(toolbar.className).toContain('g7le-');
|
||||
const panel = screen.getByTestId('g7le-route-tree-panel');
|
||||
expect(panel.className).toContain('g7le-');
|
||||
});
|
||||
|
||||
it('툴바가 useTranslation 훅을 통해 $t: 키를 전달받음 (자동 해석 통합 경로)', () => {
|
||||
// 본 단위 테스트에서는 translation dictionary 가 비어있어 키가 fallback 으로
|
||||
// 그대로 반환되지만, 그 자체가 useTranslation 훅을 통해 t() 함수로 흐른
|
||||
// 경로를 검증한다. 실제 dictionary 적재 + 해석은 e2e/통합 테스트에서 검증.
|
||||
renderShell();
|
||||
const toolbar = screen.getByTestId('g7le-toolbar');
|
||||
// 적어도 layout_editor.* 키 공간이 사용됨을 증명 (다른 키 공간 오염 차단)
|
||||
expect(toolbar.innerHTML).toContain('layout_editor.chrome.toolbar.');
|
||||
});
|
||||
|
||||
it('템플릿 식별자 라벨 표시', () => {
|
||||
renderShell();
|
||||
expect(screen.getByTestId('g7le-toolbar-template-label').textContent).toBe('sirsoft-admin_basic');
|
||||
});
|
||||
});
|
||||
|
||||
describe('LayoutEditorChrome — 템플릿 메타 fetch 인증 헤더', () => {
|
||||
// 회귀 배경: admin 템플릿 API 는 Sanctum 토큰 인증이라, 메타/목록 fetch 가
|
||||
// Authorization Bearer 토큰을 누락하면 401 → name/version 미수신 → 식별자만 노출
|
||||
// 본 테스트는 두 fetch 가 Bearer 헤더를 첨부하고,
|
||||
// 응답의 name/version 이 툴바에 반영됨을 잠근다.
|
||||
let originalFetch: typeof globalThis.fetch | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
originalFetch = globalThis.fetch;
|
||||
try {
|
||||
window.localStorage.setItem('auth_token', 'test-token-abc');
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalFetch) globalThis.fetch = originalFetch;
|
||||
try {
|
||||
window.localStorage.removeItem('auth_token');
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('메타 fetch 는 Bearer 토큰 첨부 + name/version 을 툴바에 반영', async () => {
|
||||
const calls: Array<{ url: string; auth: string | null }> = [];
|
||||
globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : String(input);
|
||||
const headers = (init?.headers ?? {}) as Record<string, string>;
|
||||
calls.push({ url, auth: headers.Authorization ?? null });
|
||||
|
||||
// show 엔드포인트 — name/version/type
|
||||
if (/\/api\/admin\/templates\/sirsoft-admin_basic$/.test(url)) {
|
||||
return new Response(
|
||||
JSON.stringify({ data: { identifier: 'sirsoft-admin_basic', name: 'Admin Basic', version: '1.0.0-beta.8', type: 'admin' } }),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
}
|
||||
// index 엔드포인트 — 전환 목록
|
||||
if (/\/api\/admin\/templates\/\?/.test(url)) {
|
||||
return new Response(
|
||||
JSON.stringify({ data: { data: [
|
||||
{ identifier: 'sirsoft-admin_basic', name: 'Admin Basic', version: '1.0.0-beta.8', type: 'admin', is_pending: false },
|
||||
{ identifier: 'sirsoft-basic', name: 'Basic', version: '1.0.0-beta.6', type: 'user', is_pending: false },
|
||||
] } }),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
}
|
||||
// routes.json — 유효 routes 응답(없으면 useEditorRoutes 가 routesError 셋팅 → 셸이
|
||||
// AccessErrorPanel 로 분기해 툴바 미마운트). 최소 1개 라우트로 정상 분기 유도.
|
||||
if (/\/editor\/routes\.json/.test(url)) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, data: { routes: [
|
||||
{ path: '/', layout: 'home', source: { kind: 'template', identifier: null }, meta: { title: '홈' } },
|
||||
] } }),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
}
|
||||
// 그 외(components.json, editor-spec 등)는 빈 200
|
||||
return new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });
|
||||
}) as unknown as typeof globalThis.fetch;
|
||||
|
||||
const engine = new TranslationEngine();
|
||||
render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorChrome templateIdentifier="sirsoft-admin_basic" initialLocale="ko" />
|
||||
</TranslationProvider>,
|
||||
);
|
||||
|
||||
// name/version 이 비동기 fetch 후 툴바에 반영될 때까지 대기
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-toolbar-template-name').textContent).toBe('Admin Basic');
|
||||
});
|
||||
expect(screen.getByTestId('g7le-toolbar-template-version').textContent).toBe('v1.0.0-beta.8');
|
||||
|
||||
// show + index fetch 가 모두 Bearer 토큰을 첨부했는지 검증
|
||||
const showCall = calls.find((c) => /\/api\/admin\/templates\/sirsoft-admin_basic$/.test(c.url));
|
||||
const indexCall = calls.find((c) => /\/api\/admin\/templates\/\?/.test(c.url));
|
||||
expect(showCall?.auth).toBe('Bearer test-token-abc');
|
||||
expect(indexCall?.auth).toBe('Bearer test-token-abc');
|
||||
});
|
||||
});
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* LocaleSwitcher.test.tsx — 콘텐츠 로케일 전환 RTL
|
||||
*
|
||||
* - 주입된 로케일 목록을 버튼으로 렌더, 현재 로케일 active.
|
||||
* - 전환 클릭 → SET_LOCALE dispatch (콘텐츠 로케일만 — chrome 로케일 불변).
|
||||
* - 로케일 1개 → 전환 토글 없이 라벨만.
|
||||
* - readSupportedLocales — G7Config.appConfig.supportedLocales 합집합 읽기.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
|
||||
|
||||
// useTranslation 모킹 — 키 자체 반환(TranslationProvider 불필요).
|
||||
vi.mock('../../../TranslationContext', () => ({
|
||||
useTranslation: () => ({ t: (k: string) => k }),
|
||||
}));
|
||||
|
||||
import { LocaleSwitcher, readSupportedLocales, localeDisplayLabel } from '../../components/LocaleSwitcher';
|
||||
import { LayoutEditorProvider } from '../../LayoutEditorContext';
|
||||
|
||||
function renderWith(locales: string[] | undefined, initialLocale = 'ko') {
|
||||
return render(
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale={initialLocale}>
|
||||
<LocaleSwitcher locales={locales} />
|
||||
</LayoutEditorProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
delete (window as unknown as { G7Config?: unknown }).G7Config;
|
||||
});
|
||||
|
||||
describe('LocaleSwitcher', () => {
|
||||
it('주입된 로케일 목록을 버튼으로 렌더, 현재 로케일 active', () => {
|
||||
renderWith(['ko', 'en', 'ja'], 'ko');
|
||||
expect(screen.getByTestId('g7le-locale-ko').getAttribute('aria-pressed')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-locale-en').getAttribute('aria-pressed')).toBe('false');
|
||||
expect(screen.getByTestId('g7le-locale-ja')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('전환 클릭 → 그 로케일이 active 로 변경 (SET_LOCALE 반영)', () => {
|
||||
renderWith(['ko', 'en', 'ja'], 'ko');
|
||||
fireEvent.click(screen.getByTestId('g7le-locale-en'));
|
||||
expect(screen.getByTestId('g7le-locale-en').getAttribute('aria-pressed')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-locale-ko').getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('로케일 1개 → 전환 토글 없이 라벨만', () => {
|
||||
renderWith(['ko'], 'ko');
|
||||
expect(screen.queryByTestId('g7le-locale-switcher')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-locale-switcher-single')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('현재 로케일이 목록에 없으면 앞에 추가해 선택 가능하게', () => {
|
||||
renderWith(['en', 'ja'], 'ko');
|
||||
expect(screen.getByTestId('g7le-locale-ko')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-locale-ko').getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('readSupportedLocales', () => {
|
||||
beforeEach(() => {
|
||||
delete (window as unknown as { G7Config?: unknown }).G7Config;
|
||||
});
|
||||
|
||||
it('G7Config.appConfig.supportedLocales 를 읽는다', () => {
|
||||
(window as unknown as { G7Config?: unknown }).G7Config = {
|
||||
appConfig: { supportedLocales: ['ko', 'en', 'ja'] },
|
||||
};
|
||||
expect(readSupportedLocales()).toEqual(['ko', 'en', 'ja']);
|
||||
});
|
||||
|
||||
it('미주입 시 빈 배열', () => {
|
||||
expect(readSupportedLocales()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('localeDisplayLabel', () => {
|
||||
it('정의된 로케일 라벨 키 해석', () => {
|
||||
expect(localeDisplayLabel('ko', (k) => (k === 'layout_editor.locale.ko' ? '한국어' : k))).toBe('한국어');
|
||||
});
|
||||
it('미정 로케일은 코드 대문자 폴백', () => {
|
||||
expect(localeDisplayLabel('xx', (k) => k)).toBe('XX');
|
||||
});
|
||||
});
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* OptionsListControl.test.tsx — `options-list` 위젯 RTL
|
||||
*
|
||||
* 검증:
|
||||
* - 옵션 배열 행 렌더 (value 입력 + label = 공통 다국어 위젯 I18nTextField)
|
||||
* - 항목 추가/삭제/이동 → onChange(옵션 배열)
|
||||
* - 마지막 항목 삭제 → onChange(undefined) (prop 삭제)
|
||||
* - 정적-바인딩 가드: `{{...}}` 바인딩 값 → 디그레이드 표시(편집 비대상)
|
||||
* - **7-b 옵션 라벨 다국어**: label 이 `$t:` 키면 raw 노출 없이 해석값 미리보기,
|
||||
* 평문 입력 → createCustomKey → `$t:custom.*` 토큰을 label 에 기록.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
|
||||
|
||||
// I18nTextField(라벨 위젯)가 읽는 컨텍스트/CRUD/해석 모킹.
|
||||
vi.mock('../../LayoutEditorContext', () => ({
|
||||
useLayoutEditor: () => ({
|
||||
state: { templateIdentifier: 'sirsoft-basic', locale: 'ko', selectedRoute: { path: '/shop', layoutName: 'shop' } },
|
||||
}),
|
||||
}));
|
||||
const createCustomKey = vi.fn();
|
||||
const updateCustomKeyValue = vi.fn();
|
||||
const findCustomKeyRow = vi.fn();
|
||||
const bustTranslationCache = vi.fn().mockResolvedValue(undefined);
|
||||
vi.mock('../../hooks/useInlineEdit', () => ({
|
||||
createCustomKey: (...a: unknown[]) => createCustomKey(...a),
|
||||
updateCustomKeyValue: (...a: unknown[]) => updateCustomKeyValue(...a),
|
||||
findCustomKeyRow: (...a: unknown[]) => findCustomKeyRow(...a),
|
||||
bustTranslationCache: (...a: unknown[]) => bustTranslationCache(...a),
|
||||
EDITOR_TRANSLATIONS_REFRESHED_EVENT: 'g7le:editor-translations-refreshed',
|
||||
}));
|
||||
vi.mock('../../../TranslationEngine', () => ({
|
||||
TranslationEngine: {
|
||||
getInstance: () => ({
|
||||
translate: (key: string) => (key === 'shop.sort.latest' ? '최신순' : key),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../components/LocaleSwitcher', () => ({
|
||||
readSupportedLocales: () => ['ko', 'en', 'ja'],
|
||||
localeDisplayLabel: (loc: string) => ({ ko: '한국어', en: 'English', ja: '日本語' }[loc] ?? loc),
|
||||
}));
|
||||
vi.mock('../../utils/authToken', () => ({ buildAuthHeaders: (h: Record<string, string>) => h }));
|
||||
|
||||
import { OptionsListControl } from '../../components/property-controls/OptionsListControl';
|
||||
import type { EditorControlSpec } from '../../spec/specTypes';
|
||||
|
||||
const t = (k: string) => k;
|
||||
const ctrl: EditorControlSpec = { widget: 'options-list', apply: { type: 'propValue', propKey: 'options' } };
|
||||
|
||||
afterEach(() => cleanup());
|
||||
beforeEach(() => {
|
||||
createCustomKey.mockReset();
|
||||
updateCustomKeyValue.mockReset();
|
||||
findCustomKeyRow.mockReset();
|
||||
bustTranslationCache.mockClear();
|
||||
});
|
||||
|
||||
const seed = [
|
||||
{ value: 'a', label: 'A' },
|
||||
{ value: 'b', label: 'B' },
|
||||
];
|
||||
|
||||
/** 옵션 idx 의 라벨 I18nTextField 미리보기 입력칸. */
|
||||
function labelPreview(idx: number): HTMLInputElement {
|
||||
return screen.getByTestId(`g7le-options-label-i18n-${idx}-preview`) as HTMLInputElement;
|
||||
}
|
||||
|
||||
describe('OptionsListControl — 정적 옵션 편집', () => {
|
||||
it('옵션 배열을 행으로 렌더한다 (value 입력 + label 다국어 위젯)', () => {
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={vi.fn()} t={t} />);
|
||||
expect(screen.getByTestId('g7le-options-row-0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-options-row-1')).toBeInTheDocument();
|
||||
expect((screen.getByTestId('g7le-options-value-0') as HTMLInputElement).value).toBe('a');
|
||||
// 라벨은 I18nTextField 미리보기(평문 'B' 그대로).
|
||||
expect(labelPreview(1).value).toBe('B');
|
||||
});
|
||||
|
||||
it('행은 3줄 구조다 (value 줄 / label 줄 / 액션 버튼 줄) — 겹침·가로 스크롤·라벨칸 협소 해소', () => {
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={vi.fn()} t={t} />);
|
||||
const row = screen.getByTestId('g7le-options-row-0');
|
||||
// 행은 세로 컨테이너(value 줄 + label 줄 + 액션 줄).
|
||||
expect(row.style.flexDirection).toBe('column');
|
||||
// value 입력 / label 위젯 / 액션 버튼은 서로 다른 줄(부모)에 있어 각 입력이 전폭을 쓴다.
|
||||
const valueLine = (screen.getByTestId('g7le-options-value-0').parentElement) as HTMLElement;
|
||||
const labelLine = (screen.getByTestId('g7le-options-label-0').parentElement) as HTMLElement;
|
||||
const actionLine = (screen.getByTestId('g7le-options-up-0').parentElement) as HTMLElement;
|
||||
expect(labelLine).not.toBe(valueLine); // label 이 value 와 다른 줄(전폭 확보)
|
||||
expect(actionLine).not.toBe(valueLine);
|
||||
expect(actionLine).not.toBe(labelLine);
|
||||
// 액션 줄은 우측 정렬 + 이동/삭제 버튼을 함께 담는다.
|
||||
expect(actionLine.style.justifyContent).toBe('flex-end');
|
||||
expect(actionLine).toContainElement(screen.getByTestId('g7le-options-down-0'));
|
||||
expect(actionLine).toContainElement(screen.getByTestId('g7le-options-remove-0'));
|
||||
});
|
||||
|
||||
it('빈 값이면 안내를 표시한다', () => {
|
||||
render(<OptionsListControl control={ctrl} value={undefined} onChange={vi.fn()} t={t} />);
|
||||
expect(screen.getByTestId('g7le-options-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('"항목 추가" → 빈 옵션이 추가된 배열로 onChange', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={onChange} t={t} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-options-add'));
|
||||
expect(onChange).toHaveBeenCalledWith([...seed, { value: '', label: '' }]);
|
||||
});
|
||||
|
||||
it('value 입력 변경 → 해당 행만 갱신된 배열로 onChange', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={onChange} t={t} />);
|
||||
fireEvent.change(screen.getByTestId('g7le-options-value-0'), { target: { value: 'x' } });
|
||||
expect(onChange).toHaveBeenCalledWith([{ value: 'x', label: 'A' }, { value: 'b', label: 'B' }]);
|
||||
});
|
||||
|
||||
it('삭제 → 해당 항목 제거된 배열로 onChange', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={onChange} t={t} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-options-remove-0'));
|
||||
expect(onChange).toHaveBeenCalledWith([{ value: 'b', label: 'B' }]);
|
||||
});
|
||||
|
||||
it('마지막 항목 삭제 → onChange(undefined) (prop 삭제)', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<OptionsListControl control={ctrl} value={[{ value: 'a', label: 'A' }]} onChange={onChange} t={t} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-options-remove-0'));
|
||||
expect(onChange).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('아래로 이동 → 항목 순서 교환된 배열로 onChange', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={onChange} t={t} />);
|
||||
fireEvent.click(screen.getByTestId('g7le-options-down-0'));
|
||||
expect(onChange).toHaveBeenCalledWith([{ value: 'b', label: 'B' }, { value: 'a', label: 'A' }]);
|
||||
});
|
||||
|
||||
it('첫 행 위로 이동은 비활성 (경계 가드)', () => {
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={vi.fn()} t={t} />);
|
||||
expect(screen.getByTestId('g7le-options-up-0')).toBeDisabled();
|
||||
expect(screen.getByTestId('g7le-options-down-1')).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('OptionsListControl — 라벨 동적 다국어 (7-b)', () => {
|
||||
it('label 이 `$t:` 키면 raw 노출 없이 해석값 미리보기', () => {
|
||||
render(
|
||||
<OptionsListControl control={ctrl} value={[{ value: 'latest', label: '$t:shop.sort.latest' }]} onChange={vi.fn()} t={t} />,
|
||||
);
|
||||
const preview = labelPreview(0);
|
||||
// raw `$t:shop.sort.latest` 가 아니라 해석값 '최신순'.
|
||||
expect(preview.value).toBe('최신순');
|
||||
expect(preview.value).not.toMatch(/^\$t:/);
|
||||
});
|
||||
|
||||
it('평문 라벨 입력 blur → createCustomKey 후 `$t:custom.*` 토큰을 label 에 기록', async () => {
|
||||
createCustomKey.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
resource: { id: 9, translation_key: 'custom.shop.3', values: { ko: '인기순' }, lock_version: 0 },
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
render(<OptionsListControl control={ctrl} value={[{ value: 'sales', label: '' }]} onChange={onChange} t={t} />);
|
||||
const preview = labelPreview(0);
|
||||
fireEvent.change(preview, { target: { value: '인기순' } });
|
||||
fireEvent.blur(preview);
|
||||
await waitFor(() => expect(createCustomKey).toHaveBeenCalledWith('sirsoft-basic', 'shop', 'ko', '인기순'));
|
||||
await waitFor(() => expect(onChange).toHaveBeenCalled());
|
||||
// 마지막 onChange 의 label 이 토큰으로 치환.
|
||||
const last = onChange.mock.calls[onChange.mock.calls.length - 1][0];
|
||||
expect(last[0].label).toBe('$t:custom.shop.3');
|
||||
expect(last[0].value).toBe('sales'); // value 는 식별자 유지
|
||||
});
|
||||
});
|
||||
|
||||
describe('OptionsListControl — 정적-바인딩 가드', () => {
|
||||
it('데이터바인딩 값(`{{...}}`)이면 디그레이드 표시 (편집 비대상)', () => {
|
||||
render(<OptionsListControl control={ctrl} value="{{categories.data}}" onChange={vi.fn()} t={t} />);
|
||||
expect(screen.getByTestId('g7le-widget-options-list-bound')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-options-add')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// (목록 칸 결선 회귀) — OptionsListControl 은 `WidgetProps.bindingCandidates` 를 받아
|
||||
// 각 옵션 라벨의 I18nTextField 로 흘려야 `+데이터` 칩 삽입(키화) 입구가 뜬다. 종전엔 WidgetProps 에
|
||||
// BindingCandidate 경로 자체가 없어 후보 0 → 라벨 칸에 `+데이터` 버튼 미노출(라이브 갭).
|
||||
describe('OptionsListControl — 라벨 후보 풀 전달', () => {
|
||||
const scalarCandidate = {
|
||||
expression: '{{user.name}}', source: 'data_source' as const, sourceId: 'user',
|
||||
path: 'name', shape: 'scalar' as const, preview: '홍길동',
|
||||
};
|
||||
|
||||
it('bindingCandidates 전달 시 평문 라벨 칸에 +데이터 버튼 노출', () => {
|
||||
render(
|
||||
<OptionsListControl control={ctrl} value={seed} onChange={vi.fn()} t={t} bindingCandidates={[scalarCandidate]} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-options-label-i18n-0-plus-data-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('bindingCandidates 미전달 시 +데이터 버튼 미노출 (디그레이드)', () => {
|
||||
render(<OptionsListControl control={ctrl} value={seed} onChange={vi.fn()} t={t} />);
|
||||
expect(screen.queryByTestId('g7le-options-label-i18n-0-plus-data-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* PageStateSwitcher.test.tsx — 캔버스 툴바 페이지 상태 토글 RTL
|
||||
*
|
||||
* - availableStates 2개 이상 → 드롭다운 렌더, 기본 상태 선택.
|
||||
* - 선택 변경 → SET_ACTIVE_STATE 반영(select value 변경).
|
||||
* - availableStates 1개 이하 → 토글 미표시(디그레이드).
|
||||
* - 라벨 `$t:` 해석, description 보조 표시.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, cleanup, act } from '@testing-library/react';
|
||||
|
||||
// useTranslation 모킹 — 키 자체 반환.
|
||||
vi.mock('../../../TranslationContext', () => ({
|
||||
useTranslation: () => ({ t: (k: string) => k }),
|
||||
}));
|
||||
|
||||
import { PageStateSwitcher } from '../../components/PageStateSwitcher';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import type { EditorStateItemSpec } from '../../spec/specTypes';
|
||||
|
||||
/** availableStates 를 dispatch 로 셋팅하는 테스트 하네스 */
|
||||
function Harness({ states, activeId }: { states: EditorStateItemSpec[]; activeId: string | null }) {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
// route 선택 후 상태 셋팅 — reducer 의 scope-reset 가 비우지 않도록 SELECT_ROUTE 후 셋팅
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path: '/login', layoutName: 'auth/login' } });
|
||||
dispatch({ type: 'SET_AVAILABLE_STATES', states, activeStateId: activeId });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return <PageStateSwitcher />;
|
||||
}
|
||||
|
||||
function renderWith(states: EditorStateItemSpec[], activeId: string | null) {
|
||||
return render(
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
|
||||
<Harness states={states} activeId={activeId} />
|
||||
</LayoutEditorProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
delete (window as unknown as { G7Core?: unknown }).G7Core;
|
||||
});
|
||||
|
||||
const TWO_STATES: EditorStateItemSpec[] = [
|
||||
{ id: 'default', label: 'Default', default: true },
|
||||
{ id: 'login_failed', label: 'Login failed', description: 'desc-key' },
|
||||
];
|
||||
|
||||
describe('PageStateSwitcher', () => {
|
||||
it('availableStates 2개 이상 → 드롭다운 렌더, 기본 상태 선택', () => {
|
||||
act(() => {
|
||||
renderWith(TWO_STATES, 'default');
|
||||
});
|
||||
const select = screen.getByTestId('g7le-state-switcher-select') as HTMLSelectElement;
|
||||
expect(select).toBeTruthy();
|
||||
expect(select.value).toBe('default');
|
||||
// 두 옵션 모두 렌더
|
||||
expect(screen.getByText('Default')).toBeTruthy();
|
||||
expect(screen.getByText('Login failed')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('선택 변경 → SET_ACTIVE_STATE 반영 (select value 변경)', () => {
|
||||
act(() => {
|
||||
renderWith(TWO_STATES, 'default');
|
||||
});
|
||||
const select = screen.getByTestId('g7le-state-switcher-select') as HTMLSelectElement;
|
||||
act(() => {
|
||||
fireEvent.change(select, { target: { value: 'login_failed' } });
|
||||
});
|
||||
expect((screen.getByTestId('g7le-state-switcher-select') as HTMLSelectElement).value).toBe('login_failed');
|
||||
expect(screen.getByTestId('g7le-state-switcher').getAttribute('data-active-state')).toBe('login_failed');
|
||||
});
|
||||
|
||||
it('availableStates 1개 → 토글 미표시 (디그레이드)', () => {
|
||||
act(() => {
|
||||
renderWith([{ id: 'only', label: 'Only', default: true }], 'only');
|
||||
});
|
||||
expect(screen.queryByTestId('g7le-state-switcher')).toBeNull();
|
||||
});
|
||||
|
||||
it('availableStates 0개 → 토글 미표시', () => {
|
||||
act(() => {
|
||||
renderWith([], null);
|
||||
});
|
||||
expect(screen.queryByTestId('g7le-state-switcher')).toBeNull();
|
||||
});
|
||||
|
||||
it('description 보조 표시 (활성 상태가 description 보유 시)', () => {
|
||||
act(() => {
|
||||
renderWith(TWO_STATES, 'login_failed');
|
||||
});
|
||||
// description 평문 'desc-key' 가 회색 보조로 표시 ($t: 미접두 → 평문 그대로)
|
||||
expect(screen.getByTestId('g7le-state-switcher-description').textContent).toBe('desc-key');
|
||||
});
|
||||
|
||||
it('label 이 `$t:` 키면 G7Core.t 로 해석', () => {
|
||||
(window as unknown as { G7Core?: { t: (k: string) => string } }).G7Core = {
|
||||
t: (k: string) => (k === 'editor.state.x' ? '비회원' : k),
|
||||
};
|
||||
act(() => {
|
||||
renderWith(
|
||||
[
|
||||
{ id: 'a', label: '$t:editor.state.x', default: true },
|
||||
{ id: 'b', label: 'B' },
|
||||
],
|
||||
'a',
|
||||
);
|
||||
});
|
||||
expect(screen.getByText('비회원')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
// e2e:allow 레이아웃 편집기 자리표시 칩 합성 입력 위젯 — contentEditable/드래그 의존으로 Playwright 자동화 부적합, Chrome MCP 매트릭스(§공통 검증) + 단위(파싱·렌더)로 검증 (InlineBindingSection.test.tsx L1 과 동일 정책)
|
||||
/**
|
||||
* PlaceholderChipInput.test.tsx — 자리표시 칩 합성 입력 RTL + 파싱 단위
|
||||
*
|
||||
* 검증:
|
||||
* - parseChipSegments: 자리표시/평문 무손실 분해(위치 보존)
|
||||
* - 렌더: `{pN}` → 원자 칩(contentEditable=false, draggable) + 평문 span(편집 가능)
|
||||
* - paramLabels 친화명 표시
|
||||
* - 평문 0(칩만) 렌더 허용
|
||||
* - insertChipInValue: 커서 위치 자리표시 삽입(편집 로케일)
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
|
||||
import {
|
||||
PlaceholderChipInput,
|
||||
parseChipSegments,
|
||||
insertChipInValue,
|
||||
buildChipSlots,
|
||||
recomposeChipMove,
|
||||
} from '../../components/property-controls/PlaceholderChipInput';
|
||||
import type { ChipSlot } from '../../components/property-controls/PlaceholderChipInput';
|
||||
|
||||
const t = (k: string) => k;
|
||||
afterEach(() => cleanup());
|
||||
|
||||
describe('buildChipSlots — 칩 양옆·사이·끝 평문 슬롯 보장 (어디서나 타이핑/이동)', () => {
|
||||
it('칩만(`{p0}`) → [text(빈), chip, text(빈)] — 칩 앞뒤 커서 슬롯 보장', () => {
|
||||
const slots = buildChipSlots('{p0}');
|
||||
expect(slots.map((s) => s.kind)).toEqual(['text', 'chip', 'text']);
|
||||
});
|
||||
|
||||
it('인접 칩(`{p0}{p1}`) → 칩 사이에도 빈 평문 슬롯', () => {
|
||||
const slots = buildChipSlots('{p0}{p1}');
|
||||
expect(slots.map((s) => s.kind)).toEqual(['text', 'chip', 'text', 'chip', 'text']);
|
||||
});
|
||||
|
||||
it('칩으로 끝남(`안녕 {p0}`) → 끝에 편집 슬롯(칩 뒤 타이핑 가능)', () => {
|
||||
const slots = buildChipSlots('안녕 {p0}');
|
||||
expect(slots.map((s) => s.kind)).toEqual(['text', 'chip', 'text']);
|
||||
expect(slots[0].text).toBe('안녕 ');
|
||||
expect(slots[2].text).toBe('');
|
||||
});
|
||||
|
||||
it('빈 값 → 편집 슬롯 1개(타이핑 시작점)', () => {
|
||||
expect(buildChipSlots('')).toEqual([{ kind: 'text', text: '' }]);
|
||||
});
|
||||
|
||||
it('멀티 칩 + 평문 혼합 → 모든 칩이 평문으로 둘러싸임', () => {
|
||||
const slots = buildChipSlots('{p0} 작성 {p1} 끝');
|
||||
// text, chip, text(' 작성 '), chip, text(' 끝')
|
||||
expect(slots.map((s) => s.kind)).toEqual(['text', 'chip', 'text', 'chip', 'text']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseChipSegments — 칩/평문 무손실 분해', () => {
|
||||
it('평문만 → text 1개', () => {
|
||||
const segs = parseChipSegments('안녕하세요');
|
||||
expect(segs).toEqual([{ kind: 'text', raw: '안녕하세요', start: 0, end: 5 }]);
|
||||
});
|
||||
|
||||
it('자리표시만 → chip 1개(param 이름)', () => {
|
||||
const segs = parseChipSegments('{p0}');
|
||||
expect(segs).toHaveLength(1);
|
||||
expect(segs[0]).toMatchObject({ kind: 'chip', paramName: 'p0', raw: '{p0}' });
|
||||
});
|
||||
|
||||
it('평문+자리표시 혼합 — 순서/위치 보존, raw 이으면 원문', () => {
|
||||
const v = '{p0} 작성 {p1}';
|
||||
const segs = parseChipSegments(v);
|
||||
expect(segs.map((s) => s.kind)).toEqual(['chip', 'text', 'chip']);
|
||||
expect(segs.map((s) => s.raw).join('')).toBe(v);
|
||||
});
|
||||
|
||||
it('이중 중괄호 {{pN}} 도 인지', () => {
|
||||
const segs = parseChipSegments('{{p0}} 끝');
|
||||
expect(segs[0]).toMatchObject({ kind: 'chip', paramName: 'p0' });
|
||||
});
|
||||
|
||||
it('빈 문자열 → 빈 배열', () => {
|
||||
expect(parseChipSegments('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlaceholderChipInput — 렌더', () => {
|
||||
it('자리표시는 원자 칩(contentEditable=false, 포인터 드래그), 평문은 편집 가능', () => {
|
||||
render(<PlaceholderChipInput value="{p0} 작성 {p1}" onChange={vi.fn()} t={t} testIdSuffix="ko" />);
|
||||
const chip0 = screen.getByTestId('g7le-chip-ko-p0');
|
||||
expect(chip0).toHaveAttribute('contenteditable', 'false');
|
||||
// 포인터 기반 드래그. grab 커서 + touchAction:none 으로 드래그 어포던스.
|
||||
expect(chip0).toHaveStyle({ cursor: 'grab' });
|
||||
// 슬롯: [text(""), chip(p0), text(" 작성 "), chip(p1), text("")]. 가운데 평문 = 인덱스 2.
|
||||
const text = screen.getByTestId('g7le-chip-text-ko-2');
|
||||
expect(text).toHaveAttribute('contenteditable', 'true');
|
||||
// 칩 앞(0)·뒤(4) 평문 슬롯도 존재 — 칩 끝 커서/타이핑 보장.
|
||||
expect(screen.getByTestId('g7le-chip-text-ko-0')).toHaveAttribute('contenteditable', 'true');
|
||||
expect(screen.getByTestId('g7le-chip-text-ko-4')).toHaveAttribute('contenteditable', 'true');
|
||||
});
|
||||
|
||||
it('paramLabels 친화명 표시(없으면 param 이름)', () => {
|
||||
render(
|
||||
<PlaceholderChipInput
|
||||
value="{p0}"
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
testIdSuffix="ko"
|
||||
paramLabels={{ p0: '회원명' }}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-chip-ko-p0')).toHaveTextContent('회원명');
|
||||
});
|
||||
|
||||
it('평문 0(칩만) 렌더 허용 — 칩만 표시', () => {
|
||||
render(<PlaceholderChipInput value="{p0}" onChange={vi.fn()} t={t} testIdSuffix="ko" />);
|
||||
expect(screen.getByTestId('g7le-chip-ko-p0')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('빈 값 → 편집 가능한 빈 평문 span(타이핑 시작점)', () => {
|
||||
render(<PlaceholderChipInput value="" onChange={vi.fn()} t={t} testIdSuffix="ko" />);
|
||||
expect(screen.getByTestId('g7le-chip-text-ko-0')).toHaveAttribute('contenteditable', 'true');
|
||||
});
|
||||
|
||||
it('onRequestInsert 미전달 시 +데이터 버튼 숨김', () => {
|
||||
render(<PlaceholderChipInput value="{p0}" onChange={vi.fn()} t={t} testIdSuffix="ko" />);
|
||||
expect(screen.queryByTestId('g7le-chip-insert-ko')).toBeNull();
|
||||
});
|
||||
|
||||
it('onRequestInsert 전달 시 +데이터 버튼 노출', () => {
|
||||
render(
|
||||
<PlaceholderChipInput
|
||||
value="{p0}"
|
||||
onChange={vi.fn()}
|
||||
t={t}
|
||||
testIdSuffix="ko"
|
||||
onRequestInsert={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-chip-insert-ko')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('칩 우측 X = 데이터 연결 해제', () => {
|
||||
it('onRemoveChip 미전달 시 칩 X 미노출 (키 관리 모달 등 node 미보유 컨텍스트)', () => {
|
||||
render(<PlaceholderChipInput value="{p0} 작성 {p1}" onChange={vi.fn()} t={t} testIdSuffix="ko" />);
|
||||
expect(screen.queryByTestId('g7le-chip-remove-ko-p0')).toBeNull();
|
||||
expect(screen.queryByTestId('g7le-chip-remove-ko-p1')).toBeNull();
|
||||
});
|
||||
|
||||
it('onRemoveChip 전달 시 칩마다 X 노출', () => {
|
||||
render(
|
||||
<PlaceholderChipInput value="{p0} 작성 {p1}" onChange={vi.fn()} t={t} testIdSuffix="ko" onRemoveChip={vi.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-chip-remove-ko-p0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-chip-remove-ko-p1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disabled 시 칩 X 미노출(onRemoveChip 전달돼도)', () => {
|
||||
render(
|
||||
<PlaceholderChipInput value="{p0}" onChange={vi.fn()} t={t} testIdSuffix="ko" onRemoveChip={vi.fn()} disabled />,
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-chip-remove-ko-p0')).toBeNull();
|
||||
});
|
||||
|
||||
it('칩 X 클릭 → 해당 param 으로 onRemoveChip 호출', () => {
|
||||
const onRemoveChip = vi.fn();
|
||||
render(
|
||||
<PlaceholderChipInput value="{p0} 작성 {p1}" onChange={vi.fn()} t={t} testIdSuffix="ko" onRemoveChip={onRemoveChip} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-chip-remove-ko-p1'));
|
||||
expect(onRemoveChip).toHaveBeenCalledWith('p1');
|
||||
expect(onRemoveChip).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('칩 X pointerdown 은 칩 드래그 시작과 분리(stopPropagation) — onChange 미발화', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<PlaceholderChipInput value="{p0}" onChange={onChange} t={t} testIdSuffix="ko" onRemoveChip={vi.fn()} />,
|
||||
);
|
||||
fireEvent.pointerDown(screen.getByTestId('g7le-chip-remove-ko-p0'));
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// (계측 확정): 칩을 드래그해 놓으면 이동한 칩이 커서 아래(드롭 지점)로 와서, 그 칩의
|
||||
// X 가 커서 아래 위치 → pointerup 직후 합성 click 이 X 에 떨어져 onRemoveChip 이 **오발화**(node.text
|
||||
// `|pN=` 제거되고 칩 사라짐). 드래그 직후의 X click 1회는 무시돼야 한다.
|
||||
it('칩 드래그(pointerdown→move→up) 직후 그 칩 X click → onRemoveChip 미발화(드래그 trailing click 차단)', () => {
|
||||
const onRemoveChip = vi.fn();
|
||||
render(
|
||||
<PlaceholderChipInput value="{p0} 작성 {p1}" onChange={vi.fn()} t={t} testIdSuffix="ko" onRemoveChip={onRemoveChip} />,
|
||||
);
|
||||
// jsdom 은 document.elementFromPoint 미구현 — null 반환 mock 으로 drop target=null → pointerup
|
||||
// early-return(throw 없음). 가드 플래그는 pointermove 에서 켜지므로 검증에 영향 없음.
|
||||
const prevEFP = (document as unknown as { elementFromPoint?: unknown }).elementFromPoint;
|
||||
(document as unknown as { elementFromPoint?: unknown }).elementFromPoint = () => null;
|
||||
const chipP0 = screen.getByTestId('g7le-chip-ko-p0');
|
||||
// 칩 본체 드래그(실제 이동) — pointerdown → move(가드 플래그 ON) → up.
|
||||
fireEvent.pointerDown(chipP0, { pointerId: 1, clientX: 100, clientY: 10 });
|
||||
fireEvent.pointerMove(chipP0, { pointerId: 1, clientX: 40, clientY: 10 });
|
||||
fireEvent.pointerUp(chipP0, { pointerId: 1, clientX: 40, clientY: 10 });
|
||||
// 드롭 직후 합성 click 이 (커서 아래로 온) 그 칩의 X 에 떨어짐 → 가드가 무시해야 함.
|
||||
fireEvent.click(screen.getByTestId('g7le-chip-remove-ko-p0'));
|
||||
expect(onRemoveChip).not.toHaveBeenCalled();
|
||||
(document as unknown as { elementFromPoint?: unknown }).elementFromPoint = prevEFP;
|
||||
});
|
||||
|
||||
it('드래그 없이 X 만 click → onRemoveChip 정상 발화(의도적 해제는 유지)', () => {
|
||||
const onRemoveChip = vi.fn();
|
||||
render(
|
||||
<PlaceholderChipInput value="{p0} 작성 {p1}" onChange={vi.fn()} t={t} testIdSuffix="ko" onRemoveChip={onRemoveChip} />,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-chip-remove-ko-p1'));
|
||||
expect(onRemoveChip).toHaveBeenCalledWith('p1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('recomposeChipMove — 칩을 글자 한 자 한 자 사이로 이동 (모든 위치 삽입)', () => {
|
||||
// 슬롯: [text("abcd"), chip(p0), text("")] — "abcd{p0}". p0 를 "abcd" 안 각 글자 사이로.
|
||||
const slots = (text0: string, after = ''): ChipSlot[] => [
|
||||
{ kind: 'text', text: text0 },
|
||||
{ kind: 'chip', paramName: 'p0' },
|
||||
{ kind: 'text', text: after },
|
||||
];
|
||||
|
||||
it('글자 사이 각 위치(0~4)에 칩 삽입 — 모든 offset', () => {
|
||||
expect(recomposeChipMove(slots('abcd'), 'p0', 0, 0)).toBe('{p0}abcd');
|
||||
expect(recomposeChipMove(slots('abcd'), 'p0', 0, 1)).toBe('a{p0}bcd');
|
||||
expect(recomposeChipMove(slots('abcd'), 'p0', 0, 2)).toBe('ab{p0}cd');
|
||||
expect(recomposeChipMove(slots('abcd'), 'p0', 0, 3)).toBe('abc{p0}d');
|
||||
expect(recomposeChipMove(slots('abcd'), 'p0', 0, 4)).toBe('abcd{p0}');
|
||||
});
|
||||
|
||||
it('한글 글자 사이 삽입', () => {
|
||||
expect(recomposeChipMove(slots('하나둘'), 'p0', 0, 1)).toBe('하{p0}나둘');
|
||||
expect(recomposeChipMove(slots('하나둘'), 'p0', 0, 2)).toBe('하나{p0}둘');
|
||||
});
|
||||
|
||||
it('offset clamp(범위 밖) — 끝으로', () => {
|
||||
expect(recomposeChipMove(slots('ab'), 'p0', 0, 99)).toBe('ab{p0}');
|
||||
});
|
||||
|
||||
it('멀티 칩 — 지정 칩만 이동, 다른 칩 위치 불변', () => {
|
||||
// 슬롯: [text("A "), chip(p0), text(" B "), chip(p1), text(" C")] = "A {p0} B {p1} C"
|
||||
const multi: ChipSlot[] = [
|
||||
{ kind: 'text', text: 'A ' }, { kind: 'chip', paramName: 'p0' },
|
||||
{ kind: 'text', text: ' B ' }, { kind: 'chip', paramName: 'p1' },
|
||||
{ kind: 'text', text: ' C' },
|
||||
];
|
||||
// p1 을 첫 슬롯 "A " 의 0 위치로 이동 → p0 는 그대로.
|
||||
expect(recomposeChipMove(multi, 'p1', 0, 0)).toBe('{p1}A {p0} B C');
|
||||
// p0 을 마지막 슬롯 " C" 의 끝으로 이동 → p1 그대로.
|
||||
expect(recomposeChipMove(multi, 'p0', 4, 2)).toBe('A B {p1} C{p0}');
|
||||
});
|
||||
|
||||
it('이동 후 재이동 가능(연속) — 결과가 다시 슬롯화되어 또 이동', () => {
|
||||
// 1차: "ab{p0}" 에서 p0 를 0 으로 → "{p0}ab"
|
||||
const v1 = recomposeChipMove(slots('ab'), 'p0', 0, 0);
|
||||
expect(v1).toBe('{p0}ab');
|
||||
// 2차: v1 을 슬롯화 후 p0 를 끝으로 → "ab{p0}" (재이동 정상)
|
||||
const s2 = buildChipSlots(v1); // [text(""), chip, text("ab")]
|
||||
const dropIdx = s2.findIndex((s) => s.kind === 'text' && s.text === 'ab');
|
||||
expect(recomposeChipMove(s2, 'p0', dropIdx, 2)).toBe('ab{p0}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('insertChipInValue — 커서 위치 자리표시 삽입', () => {
|
||||
it('앞/중/끝 삽입', () => {
|
||||
expect(insertChipInValue('님 환영', 0, 'p0')).toBe('{p0} 님 환영');
|
||||
expect(insertChipInValue('작성함', 2, 'p1')).toBe('작성 {p1} 함');
|
||||
expect(insertChipInValue('작성', 2, 'p0')).toBe('작성 {p0}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('타이핑 안전성 — 비제어 평문(글자 뒤섞임 결함 회귀, PO)', () => {
|
||||
it('평문 타이핑(연속 입력) 시 평문 span 을 React 가 덮어쓰지 않는다(비제어)', () => {
|
||||
// 결함 재현 방지: controlled 였다면 onChange→value 갱신→리렌더로 span textContent 가
|
||||
// 매 입력마다 재설정되어 커서가 튀고 글자 순서가 깨졌다("하나둘"→"퉁둘낭나한하").
|
||||
// 이제 평문 span 은 자식 텍스트를 React 로 렌더하지 않으므로(ref 주입), 구조 동일 타이핑은
|
||||
// DOM 을 보존한다 — 그 증거로 span 에 React text child 가 없음을 확인.
|
||||
// value "{p0} " → 슬롯 [text(""), chip(p0), text(" ")]. 칩 뒤 평문 슬롯 = 인덱스 2.
|
||||
let cur = '{p0} ';
|
||||
const onChange = vi.fn((next: string) => { cur = next; });
|
||||
const { rerender } = render(
|
||||
<PlaceholderChipInput value={cur} onChange={onChange} t={t} testIdSuffix="ko" />,
|
||||
);
|
||||
// 칩 뒤 평문 슬롯(비제어) — DOM 에 직접 타이핑을 시뮬레이션.
|
||||
const span = screen.getByTestId('g7le-chip-text-ko-2');
|
||||
span.textContent = ' 하나둘';
|
||||
span.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
// recompose 가 [빈 텍스트, 칩, " 하나둘"] 을 순서대로 재조립 → "{p0} 하나둘".
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
expect(onChange.mock.calls.at(-1)![0]).toBe('{p0} 하나둘');
|
||||
// 같은 구조 리렌더(타이핑) 시 DOM 평문 보존(스크램블 없음).
|
||||
rerender(<PlaceholderChipInput value={'{p0} 하나둘'} onChange={onChange} t={t} testIdSuffix="ko" />);
|
||||
expect(screen.getByTestId('g7le-chip-text-ko-2').textContent).toBe(' 하나둘');
|
||||
});
|
||||
|
||||
it('칩 구조 변경(삽입) 시에는 평문 textContent 재주입(구조 동기)', () => {
|
||||
const onChange = vi.fn();
|
||||
const { rerender } = render(
|
||||
<PlaceholderChipInput value="안녕" onChange={onChange} t={t} testIdSuffix="ko" />,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-chip-text-ko-0').textContent).toBe('안녕');
|
||||
// 칩이 추가된 새 value(구조 변경) → 평문 재주입 + 칩 등장.
|
||||
rerender(<PlaceholderChipInput value="안녕 {p0}" onChange={onChange} t={t} testIdSuffix="ko" />);
|
||||
expect(screen.getByTestId('g7le-chip-ko-p0')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-chip-text-ko-0').textContent).toBe('안녕 ');
|
||||
});
|
||||
});
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* PreviewCanvas → DynamicRenderer `_computedDefinitions` 주입 회귀 테스트
|
||||
*
|
||||
* 회귀 원인: 편집기 미리보기(`PreviewCanvas`)가 DynamicRenderer 의 dataContext 에
|
||||
* `_computedDefinitions`(레이아웃 `computed` 블록)를 주입하지 않아, 편집기에서는
|
||||
* `_computed.*` 가 항상 undefined 였다. 그 결과 `if: {{_computed.xxx}}` 로 게이트된
|
||||
* 본체(배송정책 수정 폼의 국가별 설정, 부과정책별 조건부 섹션 등)가 캔버스에서
|
||||
* 통째로 비어 렌더됨.
|
||||
*
|
||||
* 런타임 앱은 `TemplateApp.ts` 가 `initialDataContext._computedDefinitions = layoutData.computed`
|
||||
* 로 주입하므로 정상 동작했다. 편집기도 동일하게 `document.raw.computed` 를 주입해 해소.
|
||||
*
|
||||
* 두 계층 가드:
|
||||
* (1) PreviewCanvas 소스가 DynamicRenderer dataContext 에 `_computedDefinitions` 를 전달한다
|
||||
* (정적 가드 — 누락으로 회귀하면 실패).
|
||||
* (2) DynamicRenderer 의 _computed 재계산 블록이 `_computedDefinitions` 로부터 `_local` 기반
|
||||
* `_computed` 를 산출한다(동작 가드 — DataBindingEngine 으로 직접 검증).
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
import { DataBindingEngine } from '../../../DataBindingEngine';
|
||||
|
||||
describe('PreviewCanvas → _computedDefinitions 주입', () => {
|
||||
it('(1) PreviewCanvas 가 document.raw.computed 를 _computedDefinitions 로 주입한다 (정적 가드)', () => {
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const src = readFileSync(path.resolve(here, '../../components/PreviewCanvas.tsx'), 'utf8');
|
||||
// computed 블록을 메모이즈하고
|
||||
expect(src).toMatch(/document\?\.raw\?\.computed/);
|
||||
// DynamicRenderer dataContext 에 _computedDefinitions 로 전달해야 한다.
|
||||
expect(src).toMatch(/_computedDefinitions:\s*computedDefinitions/);
|
||||
});
|
||||
|
||||
it('(2) _computed 재계산이 _computedDefinitions + _local 로 활성국가설정을 산출한다 (동작 가드)', () => {
|
||||
// DynamicRenderer 재계산 블록과 동일한 평가 경로를 직접 재현한다.
|
||||
const engine = new DataBindingEngine();
|
||||
const computedDefinitions: Record<string, string> = {
|
||||
activeCountrySetting: '{{(_local.form?.country_settings ?? [])[_local.activeCountryTab ?? 0]}}',
|
||||
activeCountryCode:
|
||||
"{{(_local.form?.country_settings ?? [])[_local.activeCountryTab ?? 0]?.country_code ?? ''}}",
|
||||
};
|
||||
const dataContext = {
|
||||
_local: {
|
||||
form: {
|
||||
name: { ko: '기본 배송정책' },
|
||||
country_settings: [
|
||||
{ country_code: 'KR', charge_policy: 'conditional_free', base_fee: 3000, free_threshold: 50000 },
|
||||
{ country_code: 'US', charge_policy: 'range_amount' },
|
||||
],
|
||||
},
|
||||
activeCountryTab: 0,
|
||||
},
|
||||
};
|
||||
|
||||
const computed: Record<string, unknown> = {};
|
||||
for (const [key, expr] of Object.entries(computedDefinitions)) {
|
||||
const inner = expr.slice(2, -2).trim();
|
||||
computed[key] = engine.evaluateExpression(inner, dataContext, { skipCache: true });
|
||||
}
|
||||
|
||||
// activeCountrySetting 이 KR 설정으로 resolve → if:{{_computed.activeCountrySetting}} 본체 렌더
|
||||
expect(computed.activeCountrySetting).toMatchObject({ country_code: 'KR', charge_policy: 'conditional_free' });
|
||||
expect(computed.activeCountryCode).toBe('KR');
|
||||
});
|
||||
|
||||
it('(3) _computedDefinitions 미주입 시 _computed 미산출 (회귀 대조)', () => {
|
||||
// 정의가 없으면 DynamicRenderer 의 재계산 블록(Object.keys>0 가드)이 스킵되어
|
||||
// _computed 는 비어 있고, _computed 게이트 본체는 렌더되지 않는다.
|
||||
const computedDefinitions: Record<string, string> = {};
|
||||
expect(Object.keys(computedDefinitions).length).toBe(0);
|
||||
});
|
||||
});
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* PreviewCanvas — `$locales` 엔진 전역 lift 렌더 회귀 테스트
|
||||
*
|
||||
* 결함: 편집기 미리보기는 TemplateApp.init() 을 거치지 않아 런타임의
|
||||
* createGlobalVariables() 가 주입하는 `$locales`(시스템 활성 언어 목록)가 비어
|
||||
* 있었다. 로그인 화면 등의 로케일 선택 드롭다운이 `options="{{$locales}}"` 를
|
||||
* 바인딩하므로 캔버스에서 빈 채로 렌더됐다.
|
||||
*
|
||||
* 수정: editor-spec sampleGlobal 에 `$locale`/`$locales` 를 샘플 데이터로 선언하고
|
||||
* PreviewCanvas 가 병합 시드의 `$`-prefixed 키를 렌더 컨텍스트 최상위로 끌어올린다.
|
||||
*
|
||||
* 본 테스트는 sampleGlobal 소스에 `$locales` 를 주입한 뒤, 캔버스 레이아웃의
|
||||
* `{{$locales}}` 바인딩이 실제로 그 값으로 해석되어 화면에 렌더됨을 검증한다
|
||||
* (사용자 가시 결과 — 데이터/상태 확인만으로 완료 단정 금지 규율).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import React from 'react';
|
||||
import { render, waitFor, cleanup, screen } from '@testing-library/react';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { EditorModalProvider } from '../../EditorModalContext';
|
||||
import { PreviewCanvas } from '../../components/PreviewCanvas';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import { ComponentRegistry } from '../../../ComponentRegistry';
|
||||
|
||||
// 편집 대상 자산 부트로더를 mock — 실제 IIFE 번들 로드 없이 `Span` probe 컴포넌트만
|
||||
// 등록한 격리 registry 를 반환한다. probe 는 children 바인딩 결과를 그대로 렌더하므로
|
||||
// `{{$locales?.length}}` 가 lift 되었는지 화면 텍스트로 검증할 수 있다.
|
||||
vi.mock('../../hooks/useEditorTemplateAssets', () => {
|
||||
return {
|
||||
useEditorTemplateAssets: () => {
|
||||
const registry = ComponentRegistry.createIsolatedInstance();
|
||||
const Span = (props: any) =>
|
||||
React.createElement('span', { 'data-testid': props['data-testid'] }, props.children);
|
||||
(registry as any).registry.Span = { component: Span, metadata: { name: 'Span', type: 'basic' } };
|
||||
return {
|
||||
componentRegistry: registry,
|
||||
translationEngine: TranslationEngine.getInstance(),
|
||||
isReady: true,
|
||||
error: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
function SelectRoute({ path, layoutName }: { path: string; layoutName: string }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path, layoutName } });
|
||||
}, [dispatch, path, layoutName]);
|
||||
return null;
|
||||
}
|
||||
|
||||
describe('PreviewCanvas — $locales 엔진 전역 lift', () => {
|
||||
let originalG7Core: any;
|
||||
|
||||
function installFetchMock() {
|
||||
(global as any).fetch = vi.fn(async (url: string) => {
|
||||
if (url.includes('/editor-assets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: { identifier: 'sirsoft-basic', js: [], css: [], manifest_present: true },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/components.json')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
version: '1.0.0',
|
||||
templateId: 'sirsoft-basic',
|
||||
components: { basic: [], composite: [], layout: [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/lang/')) {
|
||||
return { ok: true, json: async () => ({}) };
|
||||
}
|
||||
if (url.includes('/api/layouts/')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: {
|
||||
// `{{$locales}}` 가 lift 되면 길이 2 가 텍스트로 렌더된다.
|
||||
// Span(코어 basic 컴포넌트)으로 가시 출력 — 로케일 드롭다운과 동일한 최상위 바인딩.
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Span',
|
||||
// text 는 DynamicRenderer 가 바인딩 평가 후 children 으로 전달한다.
|
||||
text: '{{$locales?.length ?? 0}}',
|
||||
props: { 'data-testid': 'locale-count' },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.resetInstance();
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = { t: (k: string) => k };
|
||||
(window as any).SirsoftBasic = {};
|
||||
installFetchMock();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
(window as any).G7Core = originalG7Core;
|
||||
delete (window as any).SirsoftBasic;
|
||||
delete (window as any).__templateApp;
|
||||
ComponentRegistry.resetInstance();
|
||||
});
|
||||
|
||||
// sampleGlobal 에 `$locale`/`$locales` 를 샘플 데이터로 선언한 소스 (런타임에서
|
||||
// Chrome 이 loadEditorSpecBundle 결과로 주입하는 editor-spec.json.sampleGlobal 과 동형).
|
||||
const sampleGlobalSources = [
|
||||
{
|
||||
id: 'sirsoft-basic',
|
||||
kind: 'template' as const,
|
||||
sampleGlobal: {
|
||||
$locale: 'ko',
|
||||
$locales: ['ko', 'en'],
|
||||
currentUser: { uuid: 'u', name: '샘플', is_admin: false },
|
||||
settings: { general: { site_name: '샘플 사이트' } },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function renderCanvas() {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: engine,
|
||||
translationContext: { templateId: 'sirsoft-admin_basic', locale: 'ko' },
|
||||
},
|
||||
React.createElement(
|
||||
LayoutEditorProvider,
|
||||
{ templateIdentifier: 'sirsoft-basic', initialLocale: 'ko' },
|
||||
React.createElement(
|
||||
EditorModalProvider,
|
||||
null,
|
||||
React.createElement(SelectRoute, { path: '/login', layoutName: 'auth/login' }),
|
||||
React.createElement(PreviewCanvas, { sampleGlobalSources }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it('sampleGlobal 의 $locales 가 렌더 컨텍스트 최상위로 lift 되어 {{$locales}} 바인딩이 해석된다', async () => {
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
const el = screen.queryByTestId('locale-count');
|
||||
expect(el).not.toBeNull();
|
||||
// $locales 가 비어 있으면 '0' — lift 성공 시 길이 2 가 렌더된다.
|
||||
expect(el!.textContent).toBe('2');
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* PreviewCanvas — frame 클리핑 컨텍스트 회귀 테스트
|
||||
*
|
||||
* 회귀 원인: 어포던스 오버레이를 frame 의 형제 레이어로 분리하면서
|
||||
* `transform: scale()` 을 새 래퍼 `g7le-preview-frame-wrapper` 로 이동시켰고,
|
||||
* frame 에는 `overflow: hidden` 만 남았다. 모바일 드로어(`mobile_nav_drawer`)는
|
||||
* 닫힌 상태에서 `position: fixed` + `translate-x-full` 로 렌더되는데,
|
||||
* `position: fixed` 자손의 containing block 은 가장 가까운 transform 보유 조상이다.
|
||||
* transform 이 wrapper 로 빠지면서 드로어의 containing block 이 frame → wrapper 로
|
||||
* 바뀌어, frame 의 `overflow: hidden` 이 더 이상 드로어를 클리핑하지 못해
|
||||
* 편집기 모바일 프리뷰 우측에 닫힌 메뉴 드로어가 노출되는 회귀가 발생했다.
|
||||
*
|
||||
* 클리핑이 동작하려면 frame 이 (1) 자체적으로 transform 을 보유해 fixed 자손의
|
||||
* containing block 이 되고 (2) overflow:hidden 으로 frame 밖 자손을 잘라야 한다.
|
||||
* 본 테스트는 frame 요소가 이 두 CSS 계약을 동시에 만족함을 가드한다.
|
||||
* (jsdom 은 레이아웃을 계산하지 않으므로 인라인 스타일 계약으로 검증한다.)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import React from 'react';
|
||||
import { render, waitFor, cleanup } from '@testing-library/react';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { EditorModalProvider } from '../../EditorModalContext';
|
||||
import { PreviewCanvas } from '../../components/PreviewCanvas';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import { ComponentRegistry } from '../../../ComponentRegistry';
|
||||
|
||||
/** 마운트 시 selectedRoute 를 강제 설정하는 테스트 헬퍼 */
|
||||
function SelectRoute({ path, layoutName }: { path: string; layoutName: string }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path, layoutName } });
|
||||
}, [dispatch, path, layoutName]);
|
||||
return null;
|
||||
}
|
||||
|
||||
describe('PreviewCanvas — frame 클리핑 컨텍스트(fixed 드로어 노출 방지)', () => {
|
||||
let originalG7Core: any;
|
||||
|
||||
function installFetchMock() {
|
||||
(global as any).fetch = vi.fn(async (url: string) => {
|
||||
if (url.includes('/editor-assets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: { identifier: 'sirsoft-basic', js: [], css: [], manifest_present: true },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/components.json')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
version: '1.0.0',
|
||||
templateId: 'sirsoft-basic',
|
||||
components: { basic: [], composite: [], layout: [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/lang/')) {
|
||||
return { ok: true, json: async () => ({}) };
|
||||
}
|
||||
if (url.includes('/api/layouts/')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: { components: [{ type: 'basic', name: 'Div', props: {} }] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.resetInstance();
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = { t: (k: string) => k };
|
||||
(window as any).SirsoftBasic = {};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
(window as any).G7Core = originalG7Core;
|
||||
delete (window as any).SirsoftBasic;
|
||||
delete (window as any).__templateApp;
|
||||
ComponentRegistry.resetInstance();
|
||||
});
|
||||
|
||||
function renderCanvas(path: string, layoutName: string) {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: engine,
|
||||
translationContext: { templateId: 'sirsoft-admin_basic', locale: 'ko' },
|
||||
},
|
||||
React.createElement(
|
||||
LayoutEditorProvider,
|
||||
{ templateIdentifier: 'sirsoft-basic', initialLocale: 'ko' },
|
||||
React.createElement(
|
||||
EditorModalProvider,
|
||||
null,
|
||||
React.createElement(SelectRoute, { path, layoutName }),
|
||||
React.createElement(PreviewCanvas),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it('frame 은 overflow:hidden + 자체 transform 을 동시에 보유해 fixed 자손을 클리핑한다', async () => {
|
||||
installFetchMock();
|
||||
const { findByTestId } = renderCanvas('/', 'home');
|
||||
|
||||
const frame = (await findByTestId('g7le-preview-frame')) as HTMLElement;
|
||||
|
||||
await waitFor(() => {
|
||||
expect(frame.style.overflow).toBe('hidden');
|
||||
});
|
||||
|
||||
// frame 자체가 transform 을 보유해야 position:fixed 자손의 containing block 이
|
||||
// 되고, 그래야 frame 의 overflow:hidden 이 닫힌 드로어를 클리핑한다.
|
||||
// transform 이 비어 있거나 'none' 이면 containing block 이 상위 transform 조상
|
||||
// (wrapper)으로 올라가 클리핑이 무력화되는 회귀 상태다.
|
||||
expect(frame.style.transform).toBeTruthy();
|
||||
expect(frame.style.transform).not.toBe('none');
|
||||
});
|
||||
});
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* PreviewCanvas — `window.G7Core.t` fallback wrapper 회귀 테스트
|
||||
*
|
||||
* 회귀 원인: 편집 캔버스 안의 sirsoft-basic 컴포넌트(Header/Footer 등) 가
|
||||
* React Context 가 아닌 전역 `window.G7Core.t()` 로 i18n 키를 해석한다.
|
||||
* 호스트 페이지가 sirsoft-admin_basic 사전을 점유한 채 캔버스 안에서
|
||||
* sirsoft-basic 키(`auth.login`, `nav.home`, `footer.community` 등) 를
|
||||
* 호출하면 호스트 사전에서 풀리지 않아 raw 키가 그대로 표시된다.
|
||||
*
|
||||
* 우선순위 = 편집 대상 우선 → 호스트 폴백 ("편집 대상
|
||||
* 사전으로 해석"). 캔버스는 편집 대상 템플릿(sirsoft-basic)을 그리므로, 편집 대상
|
||||
* 사전을 먼저 풀고 거기 없는 코어/chrome 키(`layout_editor.*` 등)만 호스트로 폴백한다.
|
||||
* 종전 "호스트 우선"은 양쪽에 같은 키가 다른 값으로 있을 때(예: editor.computed.
|
||||
* filter_default = admin "필터 기본값 정하기" vs basic "기본값 채우기") basic 화면에서도
|
||||
* admin 라벨이 떠 와 어긋났다.
|
||||
*
|
||||
* 본 테스트는 PreviewCanvas 가 마운트되면 `window.G7Core.t` 를 편집 대상 → 호스트
|
||||
* fallback 체인으로 감싸고, 언마운트 시 원본 함수를 복원함을 가드한다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import React from 'react';
|
||||
import { render, waitFor, cleanup } from '@testing-library/react';
|
||||
import { LayoutEditorProvider } from '../../LayoutEditorContext';
|
||||
import { PreviewCanvas } from '../../components/PreviewCanvas';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import { ComponentRegistry } from '../../../ComponentRegistry';
|
||||
|
||||
describe('PreviewCanvas — G7Core.t fallback wrapper', () => {
|
||||
let originalG7Core: any;
|
||||
let originalT: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.resetInstance();
|
||||
originalG7Core = (window as any).G7Core;
|
||||
|
||||
// 호스트 사전 — sirsoft-admin_basic 가 점유 중이라고 가정.
|
||||
// `layout_editor.*` 같은 코어 키는 정상 해석, 편집 대상의 `auth.*`/`nav.*` 키는 raw 반환.
|
||||
originalT = vi.fn((key: string) => {
|
||||
if (key.startsWith('layout_editor.')) {
|
||||
return `[host] ${key}`;
|
||||
}
|
||||
// 충돌 키 — 호스트(admin)는 다른 값으로 푼다. 편집 대상 우선이므로 이 값은 채택 안 됨.
|
||||
if (key === 'editor.computed.filter_default.label') {
|
||||
return '필터 기본값 정하기(호스트)';
|
||||
}
|
||||
return key; // 호스트 사전에 없는 키 → 그대로 반환 (fallback 트리거)
|
||||
});
|
||||
|
||||
(window as any).G7Core = { t: originalT };
|
||||
|
||||
// editor-assets API mock
|
||||
(global as any).fetch = vi.fn(async (url: string) => {
|
||||
if (url.includes('/editor-assets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: { identifier: 'sirsoft-basic', js: [], css: [], manifest_present: true },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/components.json')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
version: '1.0.0',
|
||||
templateId: 'sirsoft-basic',
|
||||
components: { basic: [], composite: [], layout: [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/lang/')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
auth: { login: '로그인' },
|
||||
nav: { home: '홈' },
|
||||
footer: { community: '커뮤니티' },
|
||||
// 양쪽(편집 대상 + 호스트)에 같은 키가 다른 값으로 존재하는 충돌 키 —
|
||||
// 편집 대상 우선이므로 편집 대상(basic) 값이 채택돼야 한다.
|
||||
editor: { computed: { filter_default: { label: '기본값 채우기(편집대상)' } } },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/api/layouts/')) {
|
||||
return { ok: true, json: async () => ({ data: { components: [] } }) };
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
});
|
||||
|
||||
// 격리 인스턴스가 사용할 IIFE 번들 전역 변수
|
||||
(window as any).SirsoftBasic = {};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
(window as any).G7Core = originalG7Core;
|
||||
delete (window as any).SirsoftBasic;
|
||||
ComponentRegistry.resetInstance();
|
||||
});
|
||||
|
||||
function renderCanvas() {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: engine,
|
||||
translationContext: { templateId: 'sirsoft-admin_basic', locale: 'ko' },
|
||||
},
|
||||
React.createElement(
|
||||
LayoutEditorProvider,
|
||||
{ templateIdentifier: 'sirsoft-basic', initialLocale: 'ko' },
|
||||
React.createElement(PreviewCanvas),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it('마운트 후 G7Core.t 가 fallback wrapper 로 교체됨 — 편집 대상에 없는 코어 키는 호스트로 폴백', async () => {
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect((window as any).G7Core.t).not.toBe(originalT);
|
||||
});
|
||||
|
||||
// 편집 대상(basic) 사전에 없는 코어/chrome 키(`layout_editor.*`)는 호스트로 폴백.
|
||||
const hostResult = (window as any).G7Core.t('layout_editor.chrome.toolbar.exit');
|
||||
expect(hostResult).toBe('[host] layout_editor.chrome.toolbar.exit');
|
||||
});
|
||||
|
||||
it('편집 대상 사전(translationEngine) 에서 우선 해석 — 호스트에 없는 키', async () => {
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect((window as any).G7Core.t).not.toBe(originalT);
|
||||
});
|
||||
|
||||
// 호스트 사전에는 auth.login 이 없고 편집 대상에는 있음 → 편집 대상 '로그인' 해석.
|
||||
const result = (window as any).G7Core.t('auth.login');
|
||||
expect(result).toBe('로그인');
|
||||
});
|
||||
|
||||
it('충돌 키(양쪽 존재, 값 다름)는 편집 대상 우선 — basic 라벨 채택', async () => {
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect((window as any).G7Core.t).not.toBe(originalT);
|
||||
});
|
||||
|
||||
// editor.computed.filter_default.label 은 편집 대상(basic)·호스트(admin) 양쪽에 있으나 값이 다르다.
|
||||
// 편집 대상 우선이므로 basic 값이 채택돼야 한다(종전 "호스트 우선"이면 admin 값이 떴던 결함).
|
||||
const result = (window as any).G7Core.t('editor.computed.filter_default.label');
|
||||
expect(result).toBe('기본값 채우기(편집대상)');
|
||||
expect(result).not.toBe('필터 기본값 정하기(호스트)');
|
||||
});
|
||||
|
||||
it('언마운트 시 원본 G7Core.t 복원 — 호스트 admin 화면 사이드이펙트 0', async () => {
|
||||
const { unmount } = renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect((window as any).G7Core.t).not.toBe(originalT);
|
||||
});
|
||||
|
||||
unmount();
|
||||
|
||||
expect((window as any).G7Core.t).toBe(originalT);
|
||||
});
|
||||
});
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* PreviewCanvas — guest_only 레이아웃 currentUser 시드 제외 회귀 테스트
|
||||
*
|
||||
* 회귀 원인: 결함 D' 보강에서 도입한 `coreSampleGlobalSeed` 가 편집 모드 격리
|
||||
* store 의 `_global.currentUser` 에 로그인된 샘플 사용자(uuid 보유) 를 무조건
|
||||
* 주입했다. `meta.guest_only: true` 레이아웃(로그인/회원가입/비밀번호 찾기 등)은
|
||||
* `_redirect_if_logged_in` 류 가드 partial 이
|
||||
* `{{_global?.currentUser?.uuid && !_local.isLoginAction}}` 조건으로 onMount 에서
|
||||
* "이미 로그인되어 있습니다" 토스트 + 홈 리다이렉트를 발화한다. 편집기 진입 시
|
||||
* 이 가드가 항상 발화해 비밀번호 찾기 등 게스트 전용 화면 편집이 토스트로
|
||||
* 오염되는 결함이 발생했다.
|
||||
*
|
||||
* 본 테스트는 PreviewCanvas 가 guest_only 레이아웃을 로드하면 격리 store 의
|
||||
* `_global.currentUser` 가 시드되지 않아(비로그인 분기) 가드가 발화하지 않음을
|
||||
* 가드한다. 일반 레이아웃(guest_only 아님)은 currentUser 가 그대로 시드됨도
|
||||
* 함께 검증한다.
|
||||
*
|
||||
* S6-2 정정: 코어 `coreSampleGlobalSeed` 가 빈 객체로 폐기되고
|
||||
* currentUser/settings 시드는 **템플릿 editor-spec.json.sampleGlobal** 이 제공한다.
|
||||
* 따라서 본 테스트는 PreviewCanvas 에 템플릿 sampleGlobal 소스를 주입(런타임에서
|
||||
* Chrome 이 loadEditorSpecBundle 결과로 주입하는 것과 동형)해 currentUser/settings
|
||||
* baseline 을 구성하고, guest_only 가 그 currentUser 를 최종 결과에서 제외함을 검증한다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import React from 'react';
|
||||
import { render, waitFor, cleanup } from '@testing-library/react';
|
||||
import { LayoutEditorProvider, useLayoutEditor } from '../../LayoutEditorContext';
|
||||
import { EditorModalProvider } from '../../EditorModalContext';
|
||||
import { PreviewCanvas } from '../../components/PreviewCanvas';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import { ComponentRegistry } from '../../../ComponentRegistry';
|
||||
|
||||
/** 마운트 시 selectedRoute 를 강제 설정하는 테스트 헬퍼 */
|
||||
function SelectRoute({ path, layoutName }: { path: string; layoutName: string }): null {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SELECT_ROUTE', route: { path, layoutName } });
|
||||
}, [dispatch, path, layoutName]);
|
||||
return null;
|
||||
}
|
||||
|
||||
describe('PreviewCanvas — guest_only currentUser 시드 제외', () => {
|
||||
let originalG7Core: any;
|
||||
|
||||
function installFetchMock(layoutMeta: Record<string, unknown> | undefined) {
|
||||
(global as any).fetch = vi.fn(async (url: string) => {
|
||||
if (url.includes('/editor-assets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: { identifier: 'sirsoft-basic', js: [], css: [], manifest_present: true },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/components.json')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
version: '1.0.0',
|
||||
templateId: 'sirsoft-basic',
|
||||
components: { basic: [], composite: [], layout: [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/lang/')) {
|
||||
return { ok: true, json: async () => ({}) };
|
||||
}
|
||||
if (url.includes('/api/layouts/')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: {
|
||||
components: [{ type: 'basic', name: 'Div', props: {} }],
|
||||
...(layoutMeta ? { meta: layoutMeta } : {}),
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.resetInstance();
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = { t: (k: string) => k };
|
||||
(window as any).SirsoftBasic = {};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
(window as any).G7Core = originalG7Core;
|
||||
delete (window as any).SirsoftBasic;
|
||||
delete (window as any).__templateApp;
|
||||
ComponentRegistry.resetInstance();
|
||||
});
|
||||
|
||||
// 템플릿 sampleGlobal 소스 — 런타임에서 Chrome 이 loadEditorSpecBundle 결과로 주입하는
|
||||
// sirsoft-basic editor-spec.json.sampleGlobal 과 동형. 코어 시드 폐기 후
|
||||
// currentUser/settings 는 본 템플릿 소스가 제공한다.
|
||||
const templateSampleGlobalSources = [
|
||||
{
|
||||
id: 'sirsoft-basic',
|
||||
kind: 'template' as const,
|
||||
sampleGlobal: {
|
||||
currentUser: { uuid: 'sample-uuid-current-user', name: '샘플 사용자', is_admin: false },
|
||||
settings: { general: { site_name: '샘플 사이트' }, site_name: '샘플 사이트' },
|
||||
site: { name: '샘플 사이트' },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function renderCanvas(path: string, layoutName: string) {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: engine,
|
||||
translationContext: { templateId: 'sirsoft-admin_basic', locale: 'ko' },
|
||||
},
|
||||
React.createElement(
|
||||
LayoutEditorProvider,
|
||||
{ templateIdentifier: 'sirsoft-basic', initialLocale: 'ko' },
|
||||
React.createElement(
|
||||
EditorModalProvider,
|
||||
null,
|
||||
React.createElement(SelectRoute, { path, layoutName }),
|
||||
React.createElement(PreviewCanvas, { sampleGlobalSources: templateSampleGlobalSources }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it('guest_only 레이아웃 → 격리 store _global.currentUser 미시드 (비로그인 분기)', async () => {
|
||||
installFetchMock({ guest_only: true });
|
||||
renderCanvas('/forgot-password', 'auth/forgot_password');
|
||||
|
||||
// document 로드 후 guest_only 판정 → store 재설치로 currentUser 제거되어야 함
|
||||
await waitFor(
|
||||
() => {
|
||||
const app = (window as any).__templateApp;
|
||||
expect(app?.getGlobalState).toBeTypeOf('function');
|
||||
expect(app.getGlobalState().currentUser).toBeUndefined();
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
|
||||
// baseline settings 는 그대로 유지 (헤더/푸터 폴백 방지)
|
||||
const globalState = (window as any).__templateApp.getGlobalState();
|
||||
expect(globalState.settings?.general?.site_name).toBe('샘플 사이트');
|
||||
});
|
||||
|
||||
it('일반 레이아웃(guest_only 아님) → currentUser 정상 시드 (로그인 분기 보존)', async () => {
|
||||
installFetchMock(undefined);
|
||||
renderCanvas('/', 'home');
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
const app = (window as any).__templateApp;
|
||||
expect(app?.getGlobalState).toBeTypeOf('function');
|
||||
expect((app.getGlobalState().currentUser as { uuid?: string } | undefined)?.uuid).toBe(
|
||||
'sample-uuid-current-user',
|
||||
);
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* PreviewCanvas → useSampleData spec 연결 회귀 테스트
|
||||
*
|
||||
* 회귀 원인: `PreviewCanvas` 가 `useSampleData({ editorSpec: undefined })` 로
|
||||
* 하드코딩되어, Phase 4 에서 도입한 번들 editor-spec 의
|
||||
* `sampleData.byDataSourceId`/`bySource` 가 캔버스 샘플 해소에 전혀 반영되지
|
||||
* 않았다(모든 data_source 가 generic 폴백 → 캔버스 공백). Chrome 이 이미 병합
|
||||
* 스펙을 `spec` prop 으로 주입하고 있었으므로 `editorSpec: spec ?? undefined` 로
|
||||
* 연결해 해소.
|
||||
*
|
||||
* 본 테스트는 두 계층을 가드한다:
|
||||
* (1) PreviewCanvas 소스가 `useSampleData` 에 `editorSpec={spec}` 를 전달한다
|
||||
* (정적 가드 — `editorSpec: undefined` 로 회귀하면 실패).
|
||||
* (2) useSampleData 가 그 spec 의 `bySource`/`byDataSourceId` 샘플을 실제로
|
||||
* 해소한다(동작 가드) — 캔버스가 받는 sampleProvider 가 올바른 값을 반환.
|
||||
*
|
||||
* (2) 는 jsdom 캔버스 풀 렌더에 의존하지 않는 결정적 단위 검증으로, 엔진 회귀
|
||||
* 검사 원칙(코드 경로 우선)에 맞춰 sampleProvider 계약을 직접 잠근다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
import { useSampleData } from '../../hooks/useSampleData';
|
||||
import type { EditorSpec } from '../../spec/specTypes';
|
||||
import type { DataSource } from '../../../DataSourceManager';
|
||||
|
||||
describe('PreviewCanvas → useSampleData spec 연결 (engine-v1.50.0)', () => {
|
||||
it('(1) PreviewCanvas 가 useSampleData 에 editorSpec={spec} 를 전달한다 (정적 가드)', () => {
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const src = readFileSync(path.resolve(here, '../../components/PreviewCanvas.tsx'), 'utf8');
|
||||
// editorSpec: undefined 로 회귀하면 실패. spec 을 editorSpec 으로 연결해야 한다.
|
||||
// (S6-3: useSampleData 가 sampleOverride 인자를 추가로 받으며 멀티라인 호출로 바뀜 —
|
||||
// 객체 리터럴 내부에 `editorSpec: spec ?? undefined` 토큰이 존재하는지만 검사한다.)
|
||||
expect(src).toMatch(/useSampleData\(\s*\{[\s\S]*?editorSpec:\s*spec\s*\?\?\s*undefined[\s\S]*?\}\s*\)/);
|
||||
expect(src).not.toMatch(/useSampleData\(\s*\{[\s\S]*?editorSpec:\s*undefined\s*[,}]/);
|
||||
});
|
||||
|
||||
it('(2) useSampleData 가 spec.bySource 샘플을 출처별로 해소한다 (동작 가드)', () => {
|
||||
const spec: EditorSpec = {
|
||||
version: '1.0.0',
|
||||
sampleData: {
|
||||
bySource: {
|
||||
template: { product: { data: { id: 1, name: '샘플 상품 이름', sales_status: 'on_sale' } } },
|
||||
},
|
||||
byDataSourceId: { product: { data: { id: 1, name: '샘플 상품 이름', sales_status: 'on_sale' } } },
|
||||
},
|
||||
} as unknown as EditorSpec;
|
||||
|
||||
const { result } = renderHook(() => useSampleData({ isEditMode: true, editorSpec: spec }));
|
||||
const provider = result.current;
|
||||
expect(provider).toBeDefined();
|
||||
|
||||
// route 출처(__source.kind=route) → bySource['template'] 로 해소.
|
||||
const source = {
|
||||
id: 'product',
|
||||
endpoint: '/api/modules/sirsoft-ecommerce/products/1',
|
||||
__source: { kind: 'route', identifier: null },
|
||||
} as unknown as DataSource;
|
||||
|
||||
const resolved = provider!.resolve(source) as { data?: { name?: string; sales_status?: string } };
|
||||
expect(resolved?.data?.name).toBe('샘플 상품 이름');
|
||||
expect(resolved?.data?.sales_status).toBe('on_sale');
|
||||
});
|
||||
|
||||
it('(3) editorSpec 미전달 시 spec 샘플 미해소 (회귀 대조)', () => {
|
||||
const { result } = renderHook(() => useSampleData({ isEditMode: true, editorSpec: undefined }));
|
||||
const provider = result.current;
|
||||
expect(provider).toBeDefined();
|
||||
const source = {
|
||||
id: 'product',
|
||||
endpoint: '/api/modules/sirsoft-ecommerce/products/1',
|
||||
__source: { kind: 'route', identifier: null },
|
||||
} as unknown as DataSource;
|
||||
const resolved = provider!.resolve(source) as { data?: { name?: string } };
|
||||
// generic/preset 폴백 → 우리가 정의한 샘플 상품 이름이 나오지 않아야 한다.
|
||||
expect(resolved?.data?.name).not.toBe('샘플 상품 이름');
|
||||
});
|
||||
});
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
// e2e:allow VH_EXPAND 펼침은 실제 레이아웃 측정(computed 100vh)+캔버스 재렌더 의존이고, 캔버스는 dnd-kit/iframe 으로 Playwright 자동화 부적합(specTypes.ts/DataBindingSection.tsx 와 동일 정책). 순수 함수 단위(idempotent 재적용) + Chrome MCP T1~T7 매트릭스(재렌더 후 frameH 2206 유지 라이브 실측)로 검증.
|
||||
/**
|
||||
* PreviewCanvas.vhExpand.test.ts — VH_EXPAND 풀스크린 펼침 + 재렌더 재적용 회귀
|
||||
*
|
||||
* 배경(근본 원인): admin 류 풀스크린 레이아웃의 루트(`h-screen overflow-hidden`, height=100vh)는
|
||||
* 편집기 캔버스에서 콘텐츠를 뷰포트 높이로 잘라 캔버스가 작아지고 잘린다. `expandVhLockedElements`
|
||||
* 가 그 요소의 height/overflow 를 무력화(height:auto, overflow:visible)해 콘텐츠가 흐르게 한다.
|
||||
*
|
||||
* 회귀(본 테스트가 잠그는 것): 테이블 추가 후 **인라인 편집 진입→이탈** 시 `bustTranslationCache`
|
||||
* 가 캔버스를 재렌더 → `h-screen overflow-hidden` 루트 요소가 재생성되며 VH_EXPAND 인라인 스타일이
|
||||
* 사라진다. 그런데 VH_EXPAND useEffect 의 dep(`components/scriptsReady/deviceWidth/dataContext`)는
|
||||
* 인라인 편집 이탈로 변하지 않아 재실행되지 않았고, 100vh 클립이 복귀해 캔버스가 수축/잘렸다.
|
||||
* 펼침 로직을 순수 함수로 추출해 (1) 펼침이 올바른지 (2) 재렌더(스타일 소실) 후 재호출하면 다시
|
||||
* 펼쳐지는지를 가드한다. (PreviewCanvas 는 이 함수를 rAF effect + frame MutationObserver 양쪽에서
|
||||
* 호출해 재렌더 시 자동 재적용한다.)
|
||||
*
|
||||
* jsdom 은 레이아웃을 계산하지 않으므로, computed height 를 모킹해 vh 고정 요소를 시뮬레이션한다.
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { expandVhLockedElements } from '../../components/PreviewCanvas';
|
||||
|
||||
const VIEWPORT_H = 900;
|
||||
|
||||
/** getComputedStyle 을 요소별 지정 스타일로 모킹 (jsdom 레이아웃 부재 보완) */
|
||||
function mockComputedStyle(styleMap: Map<Element, Partial<CSSStyleDeclaration>>): () => void {
|
||||
const orig = window.getComputedStyle;
|
||||
window.getComputedStyle = ((el: Element) => {
|
||||
const s = styleMap.get(el) ?? {};
|
||||
return {
|
||||
height: s.height ?? 'auto',
|
||||
minHeight: s.minHeight ?? 'auto',
|
||||
overflow: s.overflow ?? 'visible',
|
||||
overflowY: s.overflowY ?? 'visible',
|
||||
} as CSSStyleDeclaration;
|
||||
}) as typeof window.getComputedStyle;
|
||||
return () => { window.getComputedStyle = orig; };
|
||||
}
|
||||
|
||||
describe('expandVhLockedElements — 풀스크린 vh 펼침', () => {
|
||||
let frame: HTMLElement;
|
||||
let restore: (() => void) | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
frame = document.createElement('div');
|
||||
document.body.appendChild(frame);
|
||||
});
|
||||
afterEach(() => {
|
||||
frame.remove();
|
||||
if (restore) restore();
|
||||
restore = null;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('h-screen + overflow:hidden(콘텐츠 가둠) 루트를 height:auto/overflow:visible 로 무력화한다', () => {
|
||||
const root = document.createElement('div'); // h-screen overflow-hidden
|
||||
frame.appendChild(root);
|
||||
restore = mockComputedStyle(new Map([
|
||||
[root, { height: `${VIEWPORT_H}px`, overflowY: 'hidden' }],
|
||||
]));
|
||||
|
||||
expandVhLockedElements(frame, VIEWPORT_H);
|
||||
|
||||
expect(root.style.height).toBe('auto');
|
||||
expect(root.style.overflow).toBe('visible');
|
||||
expect(root.getAttribute('data-g7le-vh-expanded')).toBe('1');
|
||||
});
|
||||
|
||||
it('min-height:100vh 센터링 컨테이너(overflow:visible)는 건드리지 않는다 (위지윅↔유저 동일성 보존)', () => {
|
||||
const centered = document.createElement('div'); // min-h-screen flex items-center, overflow visible
|
||||
frame.appendChild(centered);
|
||||
restore = mockComputedStyle(new Map([
|
||||
[centered, { minHeight: `${VIEWPORT_H}px`, overflowY: 'visible' }],
|
||||
]));
|
||||
|
||||
expandVhLockedElements(frame, VIEWPORT_H);
|
||||
|
||||
expect(centered.style.height).toBe('');
|
||||
expect(centered.style.minHeight).toBe('');
|
||||
expect(centered.getAttribute('data-g7le-vh-expanded')).toBeNull();
|
||||
});
|
||||
|
||||
it('재렌더로 인라인 스타일이 소실된 뒤 재호출하면 다시 펼친다 (인라인 편집 이탈 수축 회귀 가드)', () => {
|
||||
const root = document.createElement('div');
|
||||
frame.appendChild(root);
|
||||
restore = mockComputedStyle(new Map([
|
||||
[root, { height: `${VIEWPORT_H}px`, overflowY: 'hidden' }],
|
||||
]));
|
||||
|
||||
// 1차 펼침
|
||||
expandVhLockedElements(frame, VIEWPORT_H);
|
||||
expect(root.getAttribute('data-g7le-vh-expanded')).toBe('1');
|
||||
|
||||
// 재렌더 시뮬레이션 — DynamicRenderer 가 요소를 재생성해 인라인 스타일/attr 소실.
|
||||
root.removeAttribute('data-g7le-vh-expanded');
|
||||
root.style.removeProperty('height');
|
||||
root.style.removeProperty('overflow');
|
||||
expect(root.getAttribute('data-g7le-vh-expanded')).toBeNull();
|
||||
|
||||
// 재호출(MutationObserver 트리거 모사) → 다시 펼쳐져야 한다.
|
||||
expandVhLockedElements(frame, VIEWPORT_H);
|
||||
expect(root.style.height).toBe('auto');
|
||||
expect(root.style.overflow).toBe('visible');
|
||||
expect(root.getAttribute('data-g7le-vh-expanded')).toBe('1');
|
||||
});
|
||||
|
||||
it('viewportHeight 0/누락 시 아무 것도 하지 않는다 (안전 가드)', () => {
|
||||
const root = document.createElement('div');
|
||||
frame.appendChild(root);
|
||||
restore = mockComputedStyle(new Map([[root, { height: `${VIEWPORT_H}px`, overflowY: 'hidden' }]]));
|
||||
expandVhLockedElements(frame, 0);
|
||||
expect(root.getAttribute('data-g7le-vh-expanded')).toBeNull();
|
||||
});
|
||||
});
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* PropertyEditorModal.propsTab.test.tsx — 속성 탭 + 노드 에디터 디스패치
|
||||
*
|
||||
* 검증 매트릭스:
|
||||
* - propControls 보유 → [속성] 탭 등장 + 탭 순서(설정→속성→스타일) + BASE_SCOPE 컨트롤 렌더
|
||||
* - propControls 만 보유 → no-editable 탈출(안내 없음) + 속성 탭 기본 활성
|
||||
* - capability.nodeEditor.kind 등록 핸들러 → [속성] 탭에 직접 렌더(kind-agnostic, 구조=CSS 아님)
|
||||
* - nodeEditor.kind 미등록 → 디그레이드(렌더 0, 회귀 0)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { PropertyEditorModal } from '../../components/PropertyEditorModal';
|
||||
import { registerCoreWidgets } from '../../spec/registerCoreWidgets';
|
||||
import {
|
||||
registerNodeEditor,
|
||||
clearNodeEditorRegistry,
|
||||
} from '../../spec/nodeEditorRegistry';
|
||||
import type { EditorSpec } from '../../spec/specTypes';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
|
||||
const t = (k: string, params?: Record<string, string | number>) =>
|
||||
params ? `${k}(${JSON.stringify(params)})` : k;
|
||||
|
||||
beforeAll(() => {
|
||||
registerCoreWidgets();
|
||||
});
|
||||
beforeEach(() => {
|
||||
clearNodeEditorRegistry();
|
||||
});
|
||||
|
||||
const spec: EditorSpec = {
|
||||
controls: {
|
||||
iconName: {
|
||||
widget: 'text',
|
||||
label: '$t:editor.control.icon_name',
|
||||
apply: { type: 'propValue', propKey: 'name' },
|
||||
},
|
||||
imgSrc: {
|
||||
widget: 'text',
|
||||
label: '$t:editor.control.img_src',
|
||||
apply: { type: 'propValue', propKey: 'src' },
|
||||
},
|
||||
textColor: {
|
||||
widget: 'color',
|
||||
group: 'text-color',
|
||||
apply: { type: 'styleProp', prop: 'color' },
|
||||
},
|
||||
},
|
||||
componentCapabilities: {
|
||||
// 속성 prop 만 보유 — 스타일/설정/동작/고급 없음. no-editable 탈출만 확인.
|
||||
Icon: { propControls: ['iconName'] },
|
||||
// 속성 + 스타일 둘 다 보유 — 탭 순서(속성→스타일) 확인.
|
||||
Img: { propControls: ['imgSrc'], styleControls: ['textColor'] },
|
||||
// 노드 에디터 슬롯 — children kind(단계 2 빌트인). 테스트에서 더미 등록.
|
||||
Ul: { nodeEditor: { kind: 'children', params: { childComponent: 'Li' } } },
|
||||
// 미등록 kind — 디그레이드 확인.
|
||||
Mystery: { nodeEditor: { kind: 'no-such-kind' } },
|
||||
},
|
||||
};
|
||||
|
||||
function renderModal(node: EditorNode) {
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={node}
|
||||
spec={spec}
|
||||
manifest={null}
|
||||
t={t}
|
||||
onPatchNode={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('PropertyEditorModal — 속성(props) 탭', () => {
|
||||
it('propControls 보유 → [속성] 탭 등장 + no-editable 탈출', () => {
|
||||
renderModal({ name: 'Icon' });
|
||||
expect(screen.getByTestId('g7le-property-tab-props')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-property-modal-no-editable')).toBeNull();
|
||||
});
|
||||
|
||||
it('propControls 만 보유 → 속성 탭 기본 활성 + propValue 컨트롤 렌더(BASE_SCOPE)', () => {
|
||||
renderModal({ name: 'Icon' });
|
||||
const tab = screen.getByTestId('g7le-property-tab-props');
|
||||
expect(tab.getAttribute('data-active')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-property-props-tab')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-control-iconName')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('탭 순서: 속성 탭이 스타일 탭보다 앞(설정→속성→스타일)', () => {
|
||||
renderModal({ name: 'Img' });
|
||||
const bar = screen.getByRole('tablist');
|
||||
const order = Array.from(bar.querySelectorAll('[role="tab"]')).map((b) =>
|
||||
b.getAttribute('data-testid'),
|
||||
);
|
||||
const propsIdx = order.indexOf('g7le-property-tab-props');
|
||||
const styleIdx = order.indexOf('g7le-property-tab-style');
|
||||
expect(propsIdx).toBeGreaterThanOrEqual(0);
|
||||
expect(styleIdx).toBeGreaterThan(propsIdx);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PropertyEditorModal — nodeEditor kind-agnostic 디스패치', () => {
|
||||
it('등록된 kind → [속성] 탭에 노드 에디터 직접 렌더(구조 편집=CSS 아님)', () => {
|
||||
const DummyChildren = (): React.ReactElement => (
|
||||
<div data-testid="dummy-children-editor" />
|
||||
);
|
||||
registerNodeEditor('children', DummyChildren);
|
||||
renderModal({ name: 'Ul' });
|
||||
// 구조 에디터(nodeEditor)는 [속성] 탭에 둔다(스타일 탭=CSS 전용). 구조 에디터 보유는
|
||||
// 속성 탭을 기본 활성으로 띄운다 → 진입 즉시 더미 에디터가 렌더된다.
|
||||
expect(screen.getByTestId('g7le-property-tab-props')).toBeTruthy();
|
||||
expect(screen.getByTestId('dummy-children-editor')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-property-modal-no-editable')).toBeNull();
|
||||
});
|
||||
|
||||
it('미등록 kind → 디그레이드(노드 에디터 렌더 0, 속성 탭은 코어 id 로 유지)', () => {
|
||||
renderModal({ name: 'Mystery' });
|
||||
// 등록 핸들러 없음 → hasNodeEditor=false → 노드 에디터 미렌더.
|
||||
expect(screen.queryByTestId('dummy-children-editor')).toBeNull();
|
||||
// 단, 코어 제공 속성(id)으로 속성 탭은 노출되어 no-editable 은 아니다.
|
||||
// 미등록 nodeEditor 의 디그레이드는 "그 에디터가 안 뜬다"는 의미이지, 컴포넌트 전체가
|
||||
// 편집 불가가 되는 것은 아니다(코어 id 는 항상 제공, coreProps:false 일 때만 차단).
|
||||
expect(screen.queryByTestId('g7le-property-modal-no-editable')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-property-tab-props')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PropertyEditorModal — 데이터 연결(dataProps) 영역', () => {
|
||||
const bindingSpec: EditorSpec = {
|
||||
controls: {
|
||||
// 구조/수치 prop — 정적 propControl(데이터 연결 비대상, 회귀 가드용).
|
||||
colCount: { widget: 'slider', apply: { type: 'propValue', propKey: 'columns' } },
|
||||
},
|
||||
componentCapabilities: {
|
||||
// 데이터형 prop(배열) 선언 → 데이터 연결 영역 노출.
|
||||
CardGrid: { dataProps: [{ propKey: 'data', shape: 'array', itemFields: ['name'] }] },
|
||||
// 구조/수치 prop 만(dataProps 없음) → 데이터 연결 영역 0(1차 결함 근절 회귀 가드).
|
||||
Spacer: { propControls: ['colCount'] },
|
||||
},
|
||||
};
|
||||
|
||||
function renderBinding(node: EditorNode) {
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={node}
|
||||
spec={bindingSpec}
|
||||
manifest={null}
|
||||
t={t}
|
||||
onPatchNode={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
bindingCandidates={[
|
||||
{
|
||||
expression: '{{products.data.data}}',
|
||||
source: 'data_source',
|
||||
sourceId: 'products',
|
||||
path: 'data.data',
|
||||
shape: 'array',
|
||||
preview: '[3]',
|
||||
itemFields: ['name'],
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
it('dataProps 선언 컴포넌트 → [속성] 탭에 데이터 연결 영역 노출 + 기본 활성', () => {
|
||||
renderBinding({ name: 'CardGrid', props: {} });
|
||||
expect(screen.getByTestId('g7le-property-tab-props').getAttribute('data-active')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-data-binding-section')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-binding-row-data')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('회귀 가드: 구조/수치 prop 만 보유(dataProps 없음) → 데이터 연결 영역 0', () => {
|
||||
renderBinding({ name: 'Spacer', props: {} });
|
||||
// propControls(구조/수치)는 속성 탭에 있으나 데이터 연결 섹션은 렌더되지 않는다.
|
||||
expect(screen.queryByTestId('g7le-data-binding-section')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-control-colCount')).toBeTruthy();
|
||||
});
|
||||
|
||||
// iteration(반복) 노드 공용 데이터 연결. node.iteration 은 구조 키라
|
||||
// capability 무관 — capability 에 dataProps/nodeEditor 가 없는 순수 Div 라도 iteration 이
|
||||
// 있으면 "반복 데이터 연결" 영역이 [속성] 탭에 떠야 한다.
|
||||
it('iteration 노드(capability dataProps 무관) → [속성] 탭에 반복 데이터 연결 영역 노출 + no-editable 탈출', () => {
|
||||
renderBinding({ name: 'Spacer', iteration: { source: '', item_var: 'item' } });
|
||||
expect(screen.getByTestId('g7le-property-tab-props').getAttribute('data-active')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-iteration-binding-section')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-property-modal-no-editable')).toBeNull();
|
||||
});
|
||||
|
||||
it('iteration 없는 노드 → 반복 데이터 연결 영역 0(노드 구조 기반 게이트)', () => {
|
||||
renderBinding({ name: 'CardGrid', props: {} });
|
||||
expect(screen.queryByTestId('g7le-iteration-binding-section')).toBeNull();
|
||||
});
|
||||
});
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
/**
|
||||
* PropertyEditorModal.test.tsx — 속성 편집 모달 렌더링
|
||||
*
|
||||
* 검증 매트릭스:
|
||||
* - 탭 가용성: 집합 컴포넌트(settings) → 설정 탭, styleControls → 스타일 탭, advanced → 고급 탭
|
||||
* - 편집 가능 속성 없음 → 안내
|
||||
* - 고급 값 존재 → 상단 배지
|
||||
* - 스타일 컨트롤 조작 → onPatchNode (applyRecipe 경유)
|
||||
* - 설정 폼 변경 → props 패치
|
||||
* - 고급 탭 permissions TagInput + 보존 목록
|
||||
*
|
||||
* widgetRegistry 가 등록돼 있어야 ControlRenderer 가 위젯을 디스패치하므로 beforeAll 에서 등록.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeAll } from 'vitest';
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react';
|
||||
import { PropertyEditorModal } from '../../components/PropertyEditorModal';
|
||||
import { registerCoreWidgets } from '../../spec/registerCoreWidgets';
|
||||
import type { EditorSpec } from '../../spec/specTypes';
|
||||
import type { EditorNode } from '../../utils/layoutTreeUtils';
|
||||
import type { ComponentManifest } from '../../components/ComponentPalette';
|
||||
|
||||
const t = (k: string, params?: Record<string, string | number>) =>
|
||||
params ? `${k}(${JSON.stringify(params)})` : k;
|
||||
|
||||
beforeAll(() => {
|
||||
registerCoreWidgets();
|
||||
});
|
||||
|
||||
const spec: EditorSpec = {
|
||||
controls: {
|
||||
textAlign: {
|
||||
widget: 'segmented',
|
||||
group: 'text-align',
|
||||
options: [
|
||||
{ value: 'left', apply: { type: 'classToken', tokens: ['text-left'] } },
|
||||
{ value: 'center', apply: { type: 'classToken', tokens: ['text-center'] } },
|
||||
],
|
||||
},
|
||||
textColor: { widget: 'color', group: 'text-color', apply: { type: 'styleProp', prop: 'color' } },
|
||||
},
|
||||
componentCapabilities: {
|
||||
H1: { styleControls: ['textAlign', 'textColor'] },
|
||||
Div: { styleControls: ['textColor'], advanced: ['permissions', 'comment'] },
|
||||
// 빈 capability 라도 코어 제공 속성(요소 id)으로 속성 탭이 노출된다.
|
||||
Plain: {},
|
||||
// 코어 속성까지 opt-out 한 컴포넌트만 no-editable (coreProps:false).
|
||||
PlainOptOut: { coreProps: false },
|
||||
},
|
||||
};
|
||||
|
||||
const manifest: ComponentManifest = {
|
||||
components: {
|
||||
composite: [
|
||||
{
|
||||
name: 'RecentPosts',
|
||||
type: 'composite',
|
||||
settings: {
|
||||
groups: [
|
||||
{
|
||||
label: '$t:editor.component.recent_posts',
|
||||
fields: [
|
||||
{ key: 'count', label: '표시 개수', type: 'number', default: 6, min: 1, max: 20 },
|
||||
{
|
||||
key: 'listType',
|
||||
label: '유형',
|
||||
type: 'select',
|
||||
default: 'recent',
|
||||
options: [
|
||||
{ value: 'recent', label: '최신글' },
|
||||
{ value: 'popular', label: '인기글' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
function renderModal(node: EditorNode, onPatchNode = vi.fn(), onDelete = vi.fn()) {
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={node}
|
||||
spec={spec}
|
||||
manifest={manifest}
|
||||
t={t}
|
||||
onPatchNode={onPatchNode}
|
||||
onClose={vi.fn()}
|
||||
onDelete={onDelete}
|
||||
permissionCandidates={[{ value: 'core.users.view', label: '회원 조회' }]}
|
||||
/>,
|
||||
);
|
||||
return { onPatchNode, onDelete };
|
||||
}
|
||||
|
||||
describe('PropertyEditorModal — 탭 가용성', () => {
|
||||
it('styleControls 보유 컴포넌트 → 스타일 탭 + 컨트롤 렌더', () => {
|
||||
renderModal({ name: 'H1' });
|
||||
expect(screen.getByTestId('g7le-property-tab-style')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-control-textAlign')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-control-textColor')).toBeTruthy();
|
||||
// advanced 미선언 → 고급 탭 없음
|
||||
expect(screen.queryByTestId('g7le-property-tab-advanced')).toBeNull();
|
||||
});
|
||||
|
||||
it('advanced 선언 컴포넌트 → 고급 탭 존재', () => {
|
||||
renderModal({ name: 'Div' });
|
||||
expect(screen.getByTestId('g7le-property-tab-advanced')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('집합 컴포넌트(settings) → 설정 탭 기본 활성', () => {
|
||||
renderModal({ name: 'RecentPosts' });
|
||||
const tab = screen.getByTestId('g7le-property-tab-settings');
|
||||
expect(tab.getAttribute('data-active')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-composite-settings')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('빈 capability 컴포넌트 → 코어 제공 속성(id)으로 속성 탭 노출 (no-editable 아님)', () => {
|
||||
renderModal({ name: 'Plain' });
|
||||
expect(screen.queryByTestId('g7le-property-modal-no-editable')).toBeNull();
|
||||
expect(screen.getByTestId('g7le-property-tab-props')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-control-core-id')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('coreProps:false 로 opt-out 한 컴포넌트만 no-editable 안내', () => {
|
||||
renderModal({ name: 'PlainOptOut' });
|
||||
expect(screen.getByTestId('g7le-property-modal-no-editable')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-property-tab-props')).toBeNull();
|
||||
});
|
||||
|
||||
it('initialTab="translation" → 진입 즉시 번역 탭 활성', () => {
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={{ name: 'H1', text: '$t:custom.home.1' }}
|
||||
spec={spec}
|
||||
manifest={manifest}
|
||||
t={t}
|
||||
onPatchNode={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
templateIdentifier="sirsoft-basic"
|
||||
initialTab="translation"
|
||||
/>,
|
||||
);
|
||||
const tab = screen.getByTestId('g7le-property-tab-translation');
|
||||
expect(tab.getAttribute('data-active')).toBe('true');
|
||||
// 스타일 탭이 있으면 비활성(initialTab 우선).
|
||||
const style = screen.queryByTestId('g7le-property-tab-style');
|
||||
if (style) expect(style.getAttribute('data-active')).toBe('false');
|
||||
});
|
||||
|
||||
it('initialTab 이 가용 목록에 없으면 무시 → 기본 규칙(설정/스타일) 적용', () => {
|
||||
// settings 보유 컴포넌트인데 initialTab="advanced"(미선언) → settings 가 활성.
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={{ name: 'RecentPosts' }}
|
||||
spec={spec}
|
||||
manifest={manifest}
|
||||
t={t}
|
||||
onPatchNode={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
initialTab="advanced"
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-property-tab-settings').getAttribute('data-active')).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PropertyEditorModal — 고급 값 배지 / 무손실 보존', () => {
|
||||
it('복잡 표현식/개발자 속성 보유 → 상단 배지', () => {
|
||||
renderModal({ name: 'Div', props: { data_binding: { source: 'x' } } });
|
||||
expect(screen.getByTestId('g7le-property-modal-advanced-badge')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('고급 값 없으면 배지 미표시', () => {
|
||||
renderModal({ name: 'H1', text: '제목', props: { className: 'text-xl' } });
|
||||
expect(screen.queryByTestId('g7le-property-modal-advanced-badge')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PropertyEditorModal — 컨트롤 조작 → 패치', () => {
|
||||
it('스타일 탭 segmented 클릭 → onPatchNode(applyRecipe 결과)', () => {
|
||||
const { onPatchNode } = renderModal({ name: 'H1' });
|
||||
fireEvent.click(screen.getByTestId('g7le-segment-center'));
|
||||
expect(onPatchNode).toHaveBeenCalled();
|
||||
const patched = onPatchNode.mock.calls.at(-1)![0] as EditorNode;
|
||||
expect(patched.props?.className).toBe('text-center');
|
||||
});
|
||||
|
||||
it('설정 탭 number 필드 변경 → props 패치', () => {
|
||||
const { onPatchNode } = renderModal({ name: 'RecentPosts' });
|
||||
const input = screen.getByTestId('g7le-setting-input-count');
|
||||
fireEvent.change(input, { target: { value: '10' } });
|
||||
expect(onPatchNode).toHaveBeenCalled();
|
||||
const patched = onPatchNode.mock.calls.at(-1)![0] as EditorNode;
|
||||
expect(patched.props?.count).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PropertyEditorModal — 고급 탭', () => {
|
||||
it('permissions TagInput + 보존 목록 렌더', () => {
|
||||
renderModal({ name: 'Div', props: { data_binding: { source: 'x' } } });
|
||||
fireEvent.click(screen.getByTestId('g7le-property-tab-advanced'));
|
||||
expect(screen.getByTestId('g7le-advanced-permissions')).toBeTruthy();
|
||||
// data_binding 은 보존 목록에 (props.data_binding 키)
|
||||
expect(screen.getByTestId('g7le-advanced-preserved')).toBeTruthy();
|
||||
expect(within(screen.getByTestId('g7le-advanced-preserved')).getByText(/data_binding/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('permissions 후보에서 칩 추가 → onPatchNode(permissions 배열)', () => {
|
||||
const { onPatchNode } = renderModal({ name: 'Div' });
|
||||
fireEvent.click(screen.getByTestId('g7le-property-tab-advanced'));
|
||||
fireEvent.click(screen.getByTestId('g7le-tag-add'));
|
||||
fireEvent.click(screen.getByTestId('g7le-tag-candidate-core.users.view'));
|
||||
expect(onPatchNode).toHaveBeenCalled();
|
||||
const patched = onPatchNode.mock.calls.at(-1)![0] as EditorNode;
|
||||
expect(patched.permissions).toEqual(['core.users.view']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PropertyEditorModal — 삭제 버튼', () => {
|
||||
it('삭제 클릭 → onDelete', () => {
|
||||
const { onDelete } = renderModal({ name: 'H1' });
|
||||
fireEvent.click(screen.getByTestId('g7le-property-modal-delete'));
|
||||
expect(onDelete).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// 스타일/표시조건 탭의 색 모드 × 디바이스 세부탭 + scope 스냅샷
|
||||
describe('PropertyEditorModal — scope 세부탭', () => {
|
||||
function renderWithScope(
|
||||
node: EditorNode,
|
||||
scope?: { colorScheme: 'base' | 'dark'; breakpoint: string },
|
||||
onScopeChange = vi.fn(),
|
||||
) {
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={node}
|
||||
spec={spec}
|
||||
manifest={manifest}
|
||||
t={t}
|
||||
onPatchNode={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
scope={scope}
|
||||
onScopeChange={onScopeChange}
|
||||
/>,
|
||||
);
|
||||
return { onScopeChange };
|
||||
}
|
||||
|
||||
it('스타일 탭 상단에 색 모드 + 디바이스 세부탭 렌더', () => {
|
||||
renderWithScope({ name: 'H1' });
|
||||
expect(screen.getByTestId('g7le-style-scope-tabs')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-style-scheme-base')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('g7le-style-bp-tablet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('표시조건 탭 세부탭은 디바이스만(색 모드 줄 숨김, D9)', () => {
|
||||
renderWithScope({ name: 'Div' }); // Div 는 styleControls + advanced → visibility 가용
|
||||
fireEvent.click(screen.getByTestId('g7le-property-tab-visibility'));
|
||||
expect(screen.getByTestId('g7le-style-scope-device')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('g7le-style-scope-scheme')).toBeNull();
|
||||
});
|
||||
|
||||
it('초기 scope prop = mobile 이면 모바일 세부탭 활성(스냅샷, D1/D2)', () => {
|
||||
renderWithScope({ name: 'H1' }, { colorScheme: 'base', breakpoint: 'mobile' });
|
||||
expect(screen.getByTestId('g7le-style-bp-mobile').getAttribute('data-active')).toBe('true');
|
||||
expect(screen.getByTestId('g7le-style-bp-base').getAttribute('data-active')).toBe('false');
|
||||
});
|
||||
|
||||
it('세부탭 클릭 → onScopeChange 콜백(상위 스냅샷 갱신)', () => {
|
||||
const { onScopeChange } = renderWithScope({ name: 'H1' });
|
||||
fireEvent.click(screen.getByTestId('g7le-style-bp-tablet'));
|
||||
expect(onScopeChange).toHaveBeenCalledWith({ colorScheme: 'base', breakpoint: 'tablet' });
|
||||
});
|
||||
|
||||
it('tablet override 노드 + tablet scope → "기본값으로 초기화" 클릭 시 onPatchNode(브랜치 제거)', () => {
|
||||
const onPatchNode = vi.fn();
|
||||
render(
|
||||
<PropertyEditorModal
|
||||
node={{
|
||||
name: 'H1',
|
||||
props: { className: 'text-left' },
|
||||
responsive: { tablet: { props: { className: 'text-left text-center' } } },
|
||||
}}
|
||||
spec={spec}
|
||||
manifest={manifest}
|
||||
t={t}
|
||||
onPatchNode={onPatchNode}
|
||||
onClose={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
scope={{ colorScheme: 'base', breakpoint: 'tablet' }}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-style-scope-reset'));
|
||||
const patched = onPatchNode.mock.calls.at(-1)![0] as EditorNode;
|
||||
expect(patched.responsive).toBeUndefined();
|
||||
expect(patched.props?.className).toBe('text-left'); // base 불변
|
||||
});
|
||||
});
|
||||
+844
@@ -0,0 +1,844 @@
|
||||
/**
|
||||
* RouteTreePanel 컴포넌트 테스트
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { RouteTreePanel } from '../../components/RouteTreePanel';
|
||||
import { LayoutEditorProvider, useLayoutEditor, type RouteTreeNode } from '../../LayoutEditorContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function makeRouteNode(path: string, label: string, kind: RouteTreeNode['kind'] = 'route'): RouteTreeNode {
|
||||
return {
|
||||
path,
|
||||
layoutName: kind === 'route' ? `${path}/layout` : null,
|
||||
label,
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind,
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupNode(groupKey: string, label: string, children: RouteTreeNode[]): RouteTreeNode {
|
||||
return {
|
||||
path: `__group__/${groupKey}`,
|
||||
layoutName: null,
|
||||
label,
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'route',
|
||||
children,
|
||||
};
|
||||
}
|
||||
|
||||
function TreeSeeder({ tree, children }: { tree: RouteTreeNode[]; children?: React.ReactNode }): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SET_ROUTE_TREE', tree });
|
||||
}, [tree, dispatch]);
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function renderTree(tree: RouteTreeNode[]): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<TreeSeeder tree={tree}>
|
||||
<RouteTreePanel />
|
||||
</TreeSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('RouteTreePanel — 렌더', () => {
|
||||
it('트리가 비어있으면 empty 메시지 표시', () => {
|
||||
renderTree([]);
|
||||
expect(screen.getByTestId('g7le-route-tree-empty')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('그룹 + 자식 라우트 렌더', () => {
|
||||
const tree = [
|
||||
makeGroupNode('template', '템플릿', [
|
||||
makeRouteNode('/', '홈'),
|
||||
makeRouteNode('/about', '소개'),
|
||||
]),
|
||||
];
|
||||
renderTree(tree);
|
||||
const groups = screen.getAllByTestId('g7le-route-tree-group');
|
||||
expect(groups).toHaveLength(1);
|
||||
const items = screen.getAllByTestId('g7le-route-tree-item');
|
||||
expect(items).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('hidden 라우트는 badge 표시', () => {
|
||||
const node = makeRouteNode('/secret', '비밀');
|
||||
node.isHidden = true;
|
||||
renderTree([makeGroupNode('template', '템플릿', [node])]);
|
||||
expect(screen.getByTestId('g7le-route-tree-badge-hidden')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('redirect 라우트는 badge 표시', () => {
|
||||
const node = makeRouteNode('/old', '구 페이지');
|
||||
node.isRedirect = true;
|
||||
renderTree([makeGroupNode('template', '템플릿', [node])]);
|
||||
expect(screen.getByTestId('g7le-route-tree-badge-redirect')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('라우트 항목 클릭 시 data-route-path attribute 보유', () => {
|
||||
const tree = [
|
||||
makeGroupNode('template', '템플릿', [makeRouteNode('/board', '게시판')]),
|
||||
];
|
||||
renderTree(tree);
|
||||
const item = screen.getByTestId('g7le-route-tree-item');
|
||||
expect(item.getAttribute('data-route-path')).toBe('/board');
|
||||
expect(item.getAttribute('data-route-kind')).toBe('route');
|
||||
|
||||
fireEvent.click(item);
|
||||
// selectedRoute 가 업데이트되었는지는 context state 검증 어렵지만,
|
||||
// 클릭 핸들러가 호출되어 에러 없이 동작했음을 확인 (회귀 가드).
|
||||
expect(item).toBeTruthy();
|
||||
});
|
||||
|
||||
it('그룹 노드는 클릭해도 SELECT_ROUTE 트리거 안 함 (data-testid=group)', () => {
|
||||
const tree = [makeGroupNode('template', '템플릿', [])];
|
||||
renderTree(tree);
|
||||
const group = screen.getByTestId('g7le-route-tree-group');
|
||||
fireEvent.click(group); // 에러 없이 통과
|
||||
expect(group).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 라벨 해석 (S3\'\' 결함 보강)', () => {
|
||||
function renderWithTargetLang(
|
||||
tree: RouteTreeNode[],
|
||||
targetId: string,
|
||||
targetDict: Record<string, any>
|
||||
): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
// 편집 대상 dictionary 사전 등록 — useEditorRoutes 가 비동기 적재하는 시나리오 대신
|
||||
// 단위 테스트에서는 직접 시드.
|
||||
(engine as any).translations.set(`${targetId}:ko`, targetDict);
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'sirsoft-admin_basic', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier={targetId} initialLocale="ko">
|
||||
<TreeSeeder tree={tree}>
|
||||
<RouteTreePanel />
|
||||
</TreeSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
it('$t: prefix 라벨 — 편집 대상 dictionary 우선 조회', () => {
|
||||
const node: RouteTreeNode = {
|
||||
path: '/board',
|
||||
layoutName: 'board/list',
|
||||
label: '$t:user.board.list_title',
|
||||
labelSource: 'title',
|
||||
source: { kind: 'template', identifier: null },
|
||||
kind: 'route',
|
||||
children: [],
|
||||
};
|
||||
const { container } = renderWithTargetLang(
|
||||
[makeGroupNode('template', '$t:layout_editor.chrome.route_tree.group.template', [node])],
|
||||
'sirsoft-basic',
|
||||
{ user: { board: { list_title: '게시판' } } }
|
||||
);
|
||||
expect(container.textContent).toContain('게시판');
|
||||
expect(container.textContent).not.toContain('user.board.list_title');
|
||||
});
|
||||
|
||||
it('$t: prefix 라벨 — 양쪽 dict 모두 미해석이면 path 마지막 세그먼트로 폴백', () => {
|
||||
const node: RouteTreeNode = {
|
||||
path: '/shop/cart',
|
||||
layoutName: 'shop/cart',
|
||||
label: '$t:user.shop.cart_title',
|
||||
labelSource: 'title',
|
||||
source: { kind: 'template', identifier: null },
|
||||
kind: 'route',
|
||||
children: [],
|
||||
};
|
||||
const { container } = renderWithTargetLang(
|
||||
[makeGroupNode('template', '$t:layout_editor.chrome.route_tree.group.template', [node])],
|
||||
'sirsoft-basic',
|
||||
{} // target dict 비어있음
|
||||
);
|
||||
expect(container.textContent).toContain('cart');
|
||||
expect(container.textContent).not.toContain('user.shop.cart_title');
|
||||
});
|
||||
|
||||
it('$t: prefix + 파이프 파라미터 — params 해석 (group.module|name=...)', () => {
|
||||
const node: RouteTreeNode = {
|
||||
path: '__group__/module:sirsoft-ecommerce',
|
||||
layoutName: null,
|
||||
label: '$t:layout_editor.chrome.route_tree.group.module|name=이커머스',
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'route',
|
||||
children: [],
|
||||
};
|
||||
const engine = new TranslationEngine();
|
||||
(engine as any).translations.set('sirsoft-admin_basic:ko', {
|
||||
layout_editor: { chrome: { route_tree: { group: { module: '모듈: {name}' } } } },
|
||||
});
|
||||
const { container } = render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'sirsoft-admin_basic', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
|
||||
<TreeSeeder tree={[node]}>
|
||||
<RouteTreePanel />
|
||||
</TreeSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
expect(container.textContent).toContain('모듈: 이커머스');
|
||||
});
|
||||
|
||||
it('평문(비-$t:) 라벨은 그대로 표시', () => {
|
||||
const node: RouteTreeNode = {
|
||||
path: '/foo',
|
||||
layoutName: 'foo',
|
||||
label: '평문 라벨',
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'template', identifier: null },
|
||||
kind: 'route',
|
||||
children: [],
|
||||
};
|
||||
renderTree([makeGroupNode('template', '템플릿', [node])]);
|
||||
expect(screen.getByText('평문 라벨')).toBeTruthy();
|
||||
});
|
||||
|
||||
// 모달 노드 라벨도 라우트와 동일하게 편집 대상 dictionary 우선 조회한다.
|
||||
// 회귀: 편집기 최초 렌더 시 코어 t() 의 편집대상 ja 번역이 아직 전역 컨텍스트에 반영되기 전이면
|
||||
// 모달만 `$t:` 키 raw 로 노출(접었다 펴면 정상)되던 결함. 모달도 translationEngine.translate(편집대상)
|
||||
// 경로를 타야 로드 타이밍과 무관하게 즉시 해석된다.
|
||||
it('$t: 모달 라벨 — 편집 대상 dictionary 우선 조회 (전역 컨텍스트 미적재 상태)', () => {
|
||||
const modal: RouteTreeNode = {
|
||||
path: '__modal__/_user_base/identity-challenge-modal',
|
||||
layoutName: '_user_base',
|
||||
label: '$t:user.modal_label.identity_challenge_modal',
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'modal',
|
||||
modalId: 'identity-challenge-modal',
|
||||
modalHostLayout: '_user_base',
|
||||
children: [],
|
||||
};
|
||||
const { container } = renderWithTargetLang(
|
||||
[makeGroupNode('modal', '$t:layout_editor.chrome.route_tree.group.modal', [modal])],
|
||||
'sirsoft-basic',
|
||||
{ user: { modal_label: { identity_challenge_modal: '本人認証' } } }
|
||||
);
|
||||
expect(container.textContent).toContain('本人認証');
|
||||
expect(container.textContent).not.toContain('user.modal_label.identity_challenge_modal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 레이아웃 경로/파일명 노출', () => {
|
||||
function routeNodeWithSource(
|
||||
path: string,
|
||||
layoutName: string,
|
||||
source: RouteTreeNode['source'],
|
||||
kind: RouteTreeNode['kind'] = 'route',
|
||||
): RouteTreeNode {
|
||||
return {
|
||||
path,
|
||||
layoutName,
|
||||
label: '평문 라벨',
|
||||
labelSource: 'editor_label',
|
||||
source,
|
||||
kind,
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
it('템플릿 라우트 — "{식별자} · layouts/{경로}.json"', () => {
|
||||
const node = routeNodeWithSource('/mypage/profile', 'mypage/profile', {
|
||||
kind: 'template',
|
||||
identifier: 'sirsoft-basic',
|
||||
});
|
||||
renderTree([makeGroupNode('template', '템플릿', [node])]);
|
||||
const pathEl = screen.getByTestId('g7le-route-tree-layout-path');
|
||||
expect(pathEl.textContent).toBe('sirsoft-basic · layouts/mypage/profile.json');
|
||||
});
|
||||
|
||||
it('모듈 라우트 — "{식별자} · resources/layouts/{경로}.json"', () => {
|
||||
const node = routeNodeWithSource('/board', 'admin/admin_board_index', {
|
||||
kind: 'module',
|
||||
identifier: 'sirsoft-board',
|
||||
});
|
||||
renderTree([makeGroupNode('module:sirsoft-board', '게시판', [node])]);
|
||||
const pathEl = screen.getByTestId('g7le-route-tree-layout-path');
|
||||
expect(pathEl.textContent).toBe('sirsoft-board · resources/layouts/admin/admin_board_index.json');
|
||||
});
|
||||
|
||||
it('플러그인 라우트 — resources/layouts prefix', () => {
|
||||
const node = routeNodeWithSource('/pay', 'user/checkout', {
|
||||
kind: 'plugin',
|
||||
identifier: 'sirsoft-pay_nicepayments',
|
||||
});
|
||||
renderTree([makeGroupNode('plugin:sirsoft-pay_nicepayments', '결제', [node])]);
|
||||
const pathEl = screen.getByTestId('g7le-route-tree-layout-path');
|
||||
expect(pathEl.textContent).toBe('sirsoft-pay_nicepayments · resources/layouts/user/checkout.json');
|
||||
});
|
||||
|
||||
it('공통 레이아웃(core/base) — 식별자 없이 "layouts/{경로}.json"', () => {
|
||||
const baseNode: RouteTreeNode = {
|
||||
path: '__base__/_user_base',
|
||||
layoutName: '_user_base',
|
||||
label: '공통 레이아웃',
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'base',
|
||||
children: [],
|
||||
};
|
||||
renderTree([makeGroupNode('base', '공통 레이아웃', [baseNode])]);
|
||||
const pathEl = screen.getByTestId('g7le-route-tree-layout-path');
|
||||
expect(pathEl.textContent).toBe('layouts/_user_base.json');
|
||||
});
|
||||
|
||||
it('그룹 헤더(layoutName 없음)에는 경로를 표시하지 않음', () => {
|
||||
const tree = [makeGroupNode('template', '템플릿', [])];
|
||||
renderTree(tree);
|
||||
expect(screen.queryByTestId('g7le-route-tree-layout-path')).toBeNull();
|
||||
});
|
||||
|
||||
it('전체 경로를 title 툴팁으로 제공 (말줄임 대비)', () => {
|
||||
const node = routeNodeWithSource('/x', 'deep/nested/path/component', {
|
||||
kind: 'template',
|
||||
identifier: 'sirsoft-basic',
|
||||
});
|
||||
renderTree([makeGroupNode('template', '템플릿', [node])]);
|
||||
const pathEl = screen.getByTestId('g7le-route-tree-layout-path');
|
||||
expect(pathEl.getAttribute('title')).toBe('sirsoft-basic · layouts/deep/nested/path/component.json');
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 접기/펼치기', () => {
|
||||
function ToggleSeeder(): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
return (
|
||||
<button data-testid="seeder-toggle" onClick={() => dispatch({ type: 'TOGGLE_ROUTE_TREE' })}>
|
||||
toggle
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
it('TOGGLE_ROUTE_TREE 디스패치 후 collapsed 상태 반영', () => {
|
||||
const engine = new TranslationEngine();
|
||||
render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<ToggleSeeder />
|
||||
<RouteTreePanel />
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
|
||||
const panel = screen.getByTestId('g7le-route-tree-panel');
|
||||
expect(panel.getAttribute('data-collapsed')).toBe('false');
|
||||
|
||||
fireEvent.click(screen.getByTestId('seeder-toggle'));
|
||||
|
||||
const collapsedPanel = screen.getByTestId('g7le-route-tree-panel');
|
||||
expect(collapsedPanel.getAttribute('data-collapsed')).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 라우트 검색 + 강조', () => {
|
||||
beforeEach(() => {
|
||||
try {
|
||||
window.localStorage.clear();
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
});
|
||||
|
||||
function buildTree(): RouteTreeNode[] {
|
||||
return [
|
||||
makeGroupNode('template', '템플릿', [
|
||||
makeRouteNode('/board', '게시판'),
|
||||
makeRouteNode('/shop/cart', '장바구니'),
|
||||
makeRouteNode('/mypage', '마이페이지'),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
it('검색 입력칸이 트리 존재 시 표시됨', () => {
|
||||
renderTree(buildTree());
|
||||
expect(screen.getByTestId('g7le-route-tree-search')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('명칭(라벨) 매칭 — "장바구니" 검색 시 해당 항목만 남음', () => {
|
||||
renderTree(buildTree());
|
||||
const input = screen.getByTestId('g7le-route-tree-search');
|
||||
fireEvent.change(input, { target: { value: '장바구니' } });
|
||||
const items = screen.getAllByTestId('g7le-route-tree-item');
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].getAttribute('data-route-path')).toBe('/shop/cart');
|
||||
});
|
||||
|
||||
it('라우트 path 매칭 — "/board" 검색 시 게시판 항목만 남음', () => {
|
||||
renderTree(buildTree());
|
||||
const input = screen.getByTestId('g7le-route-tree-search');
|
||||
fireEvent.change(input, { target: { value: 'board' } });
|
||||
const items = screen.getAllByTestId('g7le-route-tree-item');
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].getAttribute('data-route-path')).toBe('/board');
|
||||
});
|
||||
|
||||
it('대소문자 무시 매칭', () => {
|
||||
renderTree([makeGroupNode('template', '템플릿', [makeRouteNode('/Board', 'Board')])]);
|
||||
const input = screen.getByTestId('g7le-route-tree-search');
|
||||
fireEvent.change(input, { target: { value: 'BOARD' } });
|
||||
expect(screen.getAllByTestId('g7le-route-tree-item')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('매칭 없음 시 no-results 안내', () => {
|
||||
renderTree(buildTree());
|
||||
const input = screen.getByTestId('g7le-route-tree-search');
|
||||
fireEvent.change(input, { target: { value: 'zzzznope' } });
|
||||
expect(screen.getByTestId('g7le-route-tree-no-results')).toBeTruthy();
|
||||
expect(screen.queryAllByTestId('g7le-route-tree-item')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('매칭 부분을 <mark> 로 강조', () => {
|
||||
renderTree([makeGroupNode('template', '템플릿', [makeRouteNode('/board', '게시판')])]);
|
||||
const input = screen.getByTestId('g7le-route-tree-search');
|
||||
fireEvent.change(input, { target: { value: '게시' } });
|
||||
const marks = document.querySelectorAll('.g7le-route-tree__highlight');
|
||||
expect(marks.length).toBeGreaterThan(0);
|
||||
expect(marks[0].textContent).toBe('게시');
|
||||
});
|
||||
|
||||
it('clear 버튼 클릭 시 검색어 초기화 + 전체 복원', () => {
|
||||
renderTree(buildTree());
|
||||
const input = screen.getByTestId('g7le-route-tree-search') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '장바구니' } });
|
||||
expect(screen.getAllByTestId('g7le-route-tree-item')).toHaveLength(1);
|
||||
fireEvent.click(screen.getByTestId('g7le-route-tree-search-clear'));
|
||||
expect(input.value).toBe('');
|
||||
expect(screen.getAllByTestId('g7le-route-tree-item')).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 접힘 상태 localStorage 영속화', () => {
|
||||
beforeEach(() => {
|
||||
try {
|
||||
window.localStorage.clear();
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
});
|
||||
|
||||
it('TOGGLE 후 localStorage 에 "1" 기록', () => {
|
||||
const engine = new TranslationEngine();
|
||||
render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<ToggleSeederForPersist />
|
||||
<RouteTreePanel />
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
expect(window.localStorage.getItem('g7le.routeTree.collapsed')).toBe('0');
|
||||
fireEvent.click(screen.getByTestId('persist-toggle'));
|
||||
expect(window.localStorage.getItem('g7le.routeTree.collapsed')).toBe('1');
|
||||
});
|
||||
|
||||
it('localStorage 에 "1" 이면 초기 collapsed 상태로 마운트', () => {
|
||||
window.localStorage.setItem('g7le.routeTree.collapsed', '1');
|
||||
const engine = new TranslationEngine();
|
||||
render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<RouteTreePanel />
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
expect(screen.getByTestId('g7le-route-tree-panel').getAttribute('data-collapsed')).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
function ToggleSeederForPersist(): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
return (
|
||||
<button data-testid="persist-toggle" onClick={() => dispatch({ type: 'TOGGLE_ROUTE_TREE' })}>
|
||||
toggle
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 라우트↔모달/확장 연결 그룹 렌더 + 클릭 진입 ────────────────────
|
||||
|
||||
/** editMode 를 노출해 연결 자식 클릭 진입을 검증하는 프로브. */
|
||||
function EditModeProbe(): React.ReactElement {
|
||||
const { state } = useLayoutEditor();
|
||||
return <div data-testid="edit-mode-probe">{state.editMode}</div>;
|
||||
}
|
||||
|
||||
function renderTreeWithProbe(tree: RouteTreeNode[]): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<TreeSeeder tree={tree}>
|
||||
<RouteTreePanel />
|
||||
<EditModeProbe />
|
||||
</TreeSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function makeConnectedModalNode(modalId: string, hostLayout: string, label: string): RouteTreeNode {
|
||||
return {
|
||||
path: `__modal__/${hostLayout}/${modalId}`,
|
||||
layoutName: hostLayout,
|
||||
label,
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'modal',
|
||||
modalId,
|
||||
modalHostLayout: hostLayout,
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
function makeConnectedExtensionNode(id: string, label: string): RouteTreeNode {
|
||||
return {
|
||||
path: `__extension__/${id}`,
|
||||
layoutName: null,
|
||||
label,
|
||||
labelSource: 'path',
|
||||
source: { kind: 'module', identifier: 'sirsoft-board' },
|
||||
kind: 'extension',
|
||||
extensionId: id,
|
||||
extensionType: 'overlay',
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
describe('RouteTreePanel — 라우트↔모달/확장 연결 그룹', () => {
|
||||
beforeEach(() => {
|
||||
// 접힘 상태 영속화 테스트가 남긴 localStorage 누수로 collapsed 마운트되는 것 방지(격리).
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
window.localStorage.clear();
|
||||
}
|
||||
});
|
||||
|
||||
function makeRouteWithConnModal(hostPath: string): RouteTreeNode {
|
||||
const route = makeRouteNode(hostPath, '회원 목록');
|
||||
const modal = makeConnectedModalNode('delete_confirm', 'admin_user_list', '삭제 확인');
|
||||
modal.connectedHostRoutePath = hostPath;
|
||||
route.children = [
|
||||
{
|
||||
path: `__conngroup__/modals/${hostPath}`,
|
||||
layoutName: null,
|
||||
label: '$t:layout_editor.chrome.route_tree.connected.modals|count=1',
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'route',
|
||||
children: [modal],
|
||||
},
|
||||
];
|
||||
return route;
|
||||
}
|
||||
|
||||
it('연결 그룹(__conngroup__) 은 토글 가능한 헤더로 렌더 (기본 접힘 → 자식 미표시)', () => {
|
||||
const route = makeRouteWithConnModal('/admin/users');
|
||||
renderTree([makeGroupNode('template', '템플릿', [route])]);
|
||||
|
||||
const groups = screen.getAllByTestId('g7le-route-tree-group');
|
||||
const connGroup = groups.find(
|
||||
(g) => g.getAttribute('data-route-path') === '__conngroup__/modals//admin/users',
|
||||
);
|
||||
expect(connGroup).toBeTruthy();
|
||||
// 연결 그룹은 토글 버튼(role=button) + 기본 접힘(aria-expanded=false)
|
||||
expect(connGroup!.getAttribute('role')).toBe('button');
|
||||
expect(connGroup!.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(connGroup!.getAttribute('data-conn-collapsed')).toBe('true');
|
||||
// 기본 접힘이라 모달 자식이 트리에 렌더되지 않는다
|
||||
const modalItems = screen
|
||||
.queryAllByTestId('g7le-route-tree-item')
|
||||
.filter((el) => el.getAttribute('data-route-kind') === 'modal');
|
||||
expect(modalItems).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('연결 그룹 헤더 클릭 → 펼침 → 자식 표시, 재클릭 → 접힘', () => {
|
||||
const route = makeRouteWithConnModal('/admin/users');
|
||||
renderTree([makeGroupNode('template', '템플릿', [route])]);
|
||||
|
||||
const connGroup = screen
|
||||
.getAllByTestId('g7le-route-tree-group')
|
||||
.find((g) => g.getAttribute('data-route-path') === '__conngroup__/modals//admin/users')!;
|
||||
|
||||
// 펼침
|
||||
fireEvent.click(connGroup);
|
||||
expect(connGroup.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(
|
||||
screen.getAllByTestId('g7le-route-tree-item').filter((el) => el.getAttribute('data-route-kind') === 'modal'),
|
||||
).toHaveLength(1);
|
||||
|
||||
// 재클릭 → 접힘
|
||||
fireEvent.click(connGroup);
|
||||
expect(connGroup.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(
|
||||
screen.queryAllByTestId('g7le-route-tree-item').filter((el) => el.getAttribute('data-route-kind') === 'modal'),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('연결 모달 자식 클릭 → ENTER_MODAL_EDIT + 호스트 라우트 강조 유지', () => {
|
||||
const route = makeRouteWithConnModal('/admin/users');
|
||||
renderTreeWithProbe([makeGroupNode('template', '템플릿', [route])]);
|
||||
|
||||
expect(screen.getByTestId('edit-mode-probe').textContent).toBe('route');
|
||||
// 연결 그룹 펼치기
|
||||
const connGroup = screen
|
||||
.getAllByTestId('g7le-route-tree-group')
|
||||
.find((g) => g.getAttribute('data-route-path') === '__conngroup__/modals//admin/users')!;
|
||||
fireEvent.click(connGroup);
|
||||
|
||||
const modalItem = screen
|
||||
.getAllByTestId('g7le-route-tree-item')
|
||||
.find((el) => el.getAttribute('data-route-kind') === 'modal')!;
|
||||
fireEvent.click(modalItem);
|
||||
expect(screen.getByTestId('edit-mode-probe').textContent).toBe('modal');
|
||||
|
||||
// 호스트 라우트(/admin/users) 노드가 강조 유지 (selectedRoute 가 가상 path 여도)
|
||||
const hostRoute = screen
|
||||
.getAllByTestId('g7le-route-tree-item')
|
||||
.find((el) => el.getAttribute('data-route-path') === '/admin/users')!;
|
||||
// 강조 = 파란 배경(#eff6ff). style 속성으로 확인
|
||||
expect(hostRoute.getAttribute('style')).toContain('rgb(239, 246, 255)');
|
||||
|
||||
// 편집 중 모달 노드 자체도 강조되어야 한다. reducer 의 selectedRoute.path 는
|
||||
// `__modal__/{modalId}`(hostLayout 미포함)라 트리 모달 path(`__modal__/{host}/{modalId}`)와
|
||||
// 직접 비교가 어긋나 종전엔 강조가 누락됐다 → modalId 매칭으로 강조한다.
|
||||
const selectedModal = screen
|
||||
.getAllByTestId('g7le-route-tree-item')
|
||||
.find((el) => el.getAttribute('data-route-kind') === 'modal')!;
|
||||
expect(selectedModal.getAttribute('style')).toContain('rgb(239, 246, 255)');
|
||||
});
|
||||
|
||||
it('연결 확장 자식 클릭 → ENTER_EXTENSION_EDIT (editMode=extension)', () => {
|
||||
const route = makeRouteNode('/admin/users', '회원 목록');
|
||||
const ext = makeConnectedExtensionNode('2', '🧩 게시판 · admin_user_list');
|
||||
ext.connectedHostRoutePath = '/admin/users';
|
||||
route.children = [
|
||||
{
|
||||
path: '__conngroup__/extensions//admin/users',
|
||||
layoutName: null,
|
||||
label: '$t:layout_editor.chrome.route_tree.connected.extensions|count=1',
|
||||
labelSource: 'editor_label',
|
||||
source: { kind: 'core', identifier: null },
|
||||
kind: 'route',
|
||||
children: [ext],
|
||||
},
|
||||
];
|
||||
renderTreeWithProbe([makeGroupNode('템플릿', '템플릿', [route])]);
|
||||
|
||||
// 연결 그룹 펼치기 후 자식 클릭
|
||||
const connGroup = screen
|
||||
.getAllByTestId('g7le-route-tree-group')
|
||||
.find((g) => g.getAttribute('data-route-path') === '__conngroup__/extensions//admin/users')!;
|
||||
fireEvent.click(connGroup);
|
||||
|
||||
const extItem = screen
|
||||
.getAllByTestId('g7le-route-tree-item')
|
||||
.find((el) => el.getAttribute('data-route-kind') === 'extension')!;
|
||||
fireEvent.click(extItem);
|
||||
expect(screen.getByTestId('edit-mode-probe').textContent).toBe('extension');
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 레이아웃 버전 배지', () => {
|
||||
function VersionSeeder({
|
||||
tree,
|
||||
versions,
|
||||
children,
|
||||
}: {
|
||||
tree: RouteTreeNode[];
|
||||
versions: Record<string, number>;
|
||||
children?: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SET_ROUTE_TREE', tree });
|
||||
dispatch({ type: 'SET_LAYOUT_VERSIONS', versions });
|
||||
}, [tree, versions, dispatch]);
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function renderTreeWithVersions(
|
||||
tree: RouteTreeNode[],
|
||||
versions: Record<string, number>,
|
||||
): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<VersionSeeder tree={tree} versions={versions}>
|
||||
<RouteTreePanel />
|
||||
</VersionSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
it('버전 이력이 있는 레이아웃 노드에 v{N} 배지를 표시한다', () => {
|
||||
const home = makeRouteNode('/', '홈'); // layoutName = '//layout'
|
||||
const tree = [makeGroupNode('template', '템플릿', [home])];
|
||||
renderTreeWithVersions(tree, { [home.layoutName as string]: 7 });
|
||||
|
||||
const badge = screen.getByTestId('g7le-route-tree-version');
|
||||
expect(badge.textContent).toBe('v7');
|
||||
});
|
||||
|
||||
it('버전 이력이 없는(맵 미포함) 레이아웃에는 배지를 표시하지 않는다', () => {
|
||||
const home = makeRouteNode('/', '홈');
|
||||
const tree = [makeGroupNode('template', '템플릿', [home])];
|
||||
renderTreeWithVersions(tree, { 'other/layout': 3 });
|
||||
|
||||
expect(screen.queryByTestId('g7le-route-tree-version')).toBeNull();
|
||||
});
|
||||
|
||||
it('SET_LAYOUT_VERSION(저장/복원 동기화) 디스패치 시 배지 숫자가 즉시 갱신된다', () => {
|
||||
const home = makeRouteNode('/', '홈');
|
||||
const layoutName = home.layoutName as string;
|
||||
const tree = [makeGroupNode('template', '템플릿', [home])];
|
||||
|
||||
function Bumper(): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="bump-version"
|
||||
onClick={() => dispatch({ type: 'SET_LAYOUT_VERSION', layoutName, version: 8 })}
|
||||
>
|
||||
bump
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const engine = new TranslationEngine();
|
||||
render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<VersionSeeder tree={tree} versions={{ [layoutName]: 7 }}>
|
||||
<RouteTreePanel />
|
||||
<Bumper />
|
||||
</VersionSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('g7le-route-tree-version').textContent).toBe('v7');
|
||||
fireEvent.click(screen.getByTestId('bump-version'));
|
||||
expect(screen.getByTestId('g7le-route-tree-version').textContent).toBe('v8');
|
||||
});
|
||||
|
||||
it('그룹 헤더(layoutName 없음)에는 배지를 표시하지 않는다', () => {
|
||||
const tree = [makeGroupNode('template', '템플릿', [])];
|
||||
renderTreeWithVersions(tree, { whatever: 1 });
|
||||
expect(screen.queryByTestId('g7le-route-tree-version')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RouteTreePanel — 확장 노드 버전 배지', () => {
|
||||
function makeExtensionNode(id: string): RouteTreeNode {
|
||||
return {
|
||||
path: `__extension__/${id}`,
|
||||
layoutName: null,
|
||||
label: `🧩 게시판 · html_content`,
|
||||
labelSource: 'path',
|
||||
source: { kind: 'module', identifier: 'sirsoft-board' },
|
||||
kind: 'extension',
|
||||
extensionId: id,
|
||||
extensionType: 'extension_point',
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
function ExtensionVersionSeeder({
|
||||
tree,
|
||||
versions,
|
||||
children,
|
||||
}: {
|
||||
tree: RouteTreeNode[];
|
||||
versions: Record<string, number>;
|
||||
children?: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
const { dispatch } = useLayoutEditor();
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: 'SET_ROUTE_TREE', tree });
|
||||
dispatch({ type: 'SET_EXTENSION_VERSIONS', versions });
|
||||
}, [tree, versions, dispatch]);
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function renderExtensionTree(
|
||||
tree: RouteTreeNode[],
|
||||
versions: Record<string, number>,
|
||||
): ReturnType<typeof render> {
|
||||
const engine = new TranslationEngine();
|
||||
return render(
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
<LayoutEditorProvider templateIdentifier="test-tpl" initialLocale="ko">
|
||||
<ExtensionVersionSeeder tree={tree} versions={versions}>
|
||||
<RouteTreePanel />
|
||||
</ExtensionVersionSeeder>
|
||||
</LayoutEditorProvider>
|
||||
</TranslationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
it('버전 이력이 있는 확장 노드에 v{N} 배지를 표시한다 (extensionId 키 매칭)', () => {
|
||||
const tree = [makeGroupNode('extension', '확장 주입', [makeExtensionNode('7')])];
|
||||
renderExtensionTree(tree, { '7': 4 });
|
||||
|
||||
const badge = screen.getByTestId('g7le-route-tree-version');
|
||||
expect(badge.textContent).toBe('v4');
|
||||
});
|
||||
|
||||
it('이력이 없는(맵 미포함) 확장 노드에는 배지를 표시하지 않는다', () => {
|
||||
const tree = [makeGroupNode('extension', '확장 주입', [makeExtensionNode('7')])];
|
||||
renderExtensionTree(tree, { '99': 2 });
|
||||
|
||||
expect(screen.queryByTestId('g7le-route-tree-version')).toBeNull();
|
||||
});
|
||||
});
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* SaveFeedbackBanner 컴포넌트 테스트
|
||||
*
|
||||
* useLayoutDocument.save 가 반환하는 SaveResult 6종 kind 별로:
|
||||
* - DOM 마운트 여부 / data-testid 매칭 / 표시 메시지 / 액션 콜백 호출 / 자동 dismiss
|
||||
* - concurrent_modification 모달의 3개 버튼 분기 (load_latest / view_my_changes / cancel)
|
||||
* - validation_failed 의 errors 필드별 메시지 렌더
|
||||
* - blocked_inactive_extension 의 blockedPaths 목록 렌더
|
||||
* - network_error 의 message 렌더
|
||||
* - 자동 dismiss 타이머 (5초) 동작 — concurrent / validation 은 자동 dismiss 없음
|
||||
* - result=null 일 때 미렌더 (조기 반환)
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import { SaveFeedbackBanner } from '../../components/SaveFeedbackBanner';
|
||||
import type { SaveResult } from '../../hooks/useLayoutDocument';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
function withTranslation(node: React.ReactElement): React.ReactElement {
|
||||
const engine = new TranslationEngine();
|
||||
return (
|
||||
<TranslationProvider
|
||||
translationEngine={engine}
|
||||
translationContext={{ templateId: 'test', locale: 'ko' }}
|
||||
>
|
||||
{node}
|
||||
</TranslationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('SaveFeedbackBanner — result=null', () => {
|
||||
it('result 가 null 이면 아무것도 렌더하지 않는다 (조기 반환)', () => {
|
||||
const { container } = render(
|
||||
withTranslation(<SaveFeedbackBanner result={null} onDismiss={vi.fn()} />)
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — success', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('success kind → success banner 마운트 + 닫기 버튼 노출', () => {
|
||||
const result: SaveResult = { kind: 'success', newLockVersion: 5 };
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
expect(screen.getByTestId('g7le-save-banner-success')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-save-banner-success-close')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('success kind → 닫기 버튼 클릭 시 onDismiss 호출', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner result={{ kind: 'success', newLockVersion: 5 }} onDismiss={onDismiss} />
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-save-banner-success-close'));
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('success kind → 5초 후 자동 dismiss', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner result={{ kind: 'success', newLockVersion: 5 }} onDismiss={onDismiss} />
|
||||
)
|
||||
);
|
||||
expect(onDismiss).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — validation_failed', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('validation_failed kind → 에러 배너 마운트 + 각 필드 메시지 표시', () => {
|
||||
const result: SaveResult = {
|
||||
kind: 'validation_failed',
|
||||
status: 422,
|
||||
errors: {
|
||||
content: ['content 형식이 올바르지 않습니다'],
|
||||
'content.components.0.name': ['name 은 필수입니다'],
|
||||
},
|
||||
};
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
expect(screen.getByTestId('g7le-save-banner-validation')).toBeTruthy();
|
||||
const list = screen.getByTestId('g7le-save-banner-validation-errors');
|
||||
expect(list.textContent).toContain('content 형식이 올바르지 않습니다');
|
||||
expect(list.textContent).toContain('name 은 필수입니다');
|
||||
expect(list.textContent).toContain('content.components.0.name');
|
||||
});
|
||||
|
||||
it('validation_failed → errors=null 이어도 배너 마운트 (목록만 미표시)', () => {
|
||||
const result: SaveResult = {
|
||||
kind: 'validation_failed',
|
||||
status: 422,
|
||||
errors: null,
|
||||
};
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
expect(screen.getByTestId('g7le-save-banner-validation')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-save-banner-validation-errors')).toBeNull();
|
||||
});
|
||||
|
||||
it('validation_failed → 자동 dismiss 없음 (사용자 명시 닫기 필요)', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'validation_failed', status: 422, errors: {} }}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(30000);
|
||||
});
|
||||
expect(onDismiss).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — concurrent_modification', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('concurrent kind → 모달 마운트 + 3개 버튼 노출 + 버전 정보 키 사용', () => {
|
||||
const result: SaveResult = { kind: 'concurrent_modification', currentVersion: 7, yourVersion: 5 };
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
const modal = screen.getByTestId('g7le-save-banner-concurrent');
|
||||
expect(modal).toBeTruthy();
|
||||
expect(modal.getAttribute('role')).toBe('dialog');
|
||||
expect(screen.getByTestId('g7le-save-banner-concurrent-load-latest')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-save-banner-concurrent-keep-mine')).toBeTruthy();
|
||||
expect(screen.getByTestId('g7le-save-banner-concurrent-cancel')).toBeTruthy();
|
||||
// jsdom TranslationEngine 폴백은 키 자체를 반환하므로 보간 값(7/5) 대신
|
||||
// version_info 키 호출 자체를 검증 — 키가 텍스트에 노출되어 있다는 것은 t() 호출 경로가 정상이라는 신호.
|
||||
expect(modal.textContent).toContain('layout_editor.save.concurrent.version_info');
|
||||
});
|
||||
|
||||
it('concurrent → "최신 불러오기" 클릭 → onLoadLatest + onDismiss 호출', () => {
|
||||
const onLoadLatest = vi.fn();
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'concurrent_modification', currentVersion: 7, yourVersion: 5 }}
|
||||
onDismiss={onDismiss}
|
||||
onLoadLatest={onLoadLatest}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-save-banner-concurrent-load-latest'));
|
||||
expect(onLoadLatest).toHaveBeenCalledTimes(1);
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('concurrent → "내 변경 내용 보기" 클릭 → onKeepMyChanges + onDismiss 호출', () => {
|
||||
const onKeepMyChanges = vi.fn();
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'concurrent_modification', currentVersion: 7, yourVersion: 5 }}
|
||||
onDismiss={onDismiss}
|
||||
onKeepMyChanges={onKeepMyChanges}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-save-banner-concurrent-keep-mine'));
|
||||
expect(onKeepMyChanges).toHaveBeenCalledTimes(1);
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('concurrent → "취소" 클릭 → onDismiss 만 호출 (다른 콜백 미호출)', () => {
|
||||
const onLoadLatest = vi.fn();
|
||||
const onKeepMyChanges = vi.fn();
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'concurrent_modification', currentVersion: 7, yourVersion: 5 }}
|
||||
onDismiss={onDismiss}
|
||||
onLoadLatest={onLoadLatest}
|
||||
onKeepMyChanges={onKeepMyChanges}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-save-banner-concurrent-cancel'));
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
expect(onLoadLatest).not.toHaveBeenCalled();
|
||||
expect(onKeepMyChanges).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('concurrent → 자동 dismiss 없음 (사용자 명시 결정 필요)', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'concurrent_modification', currentVersion: 7, yourVersion: 5 }}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(30000);
|
||||
});
|
||||
expect(onDismiss).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('concurrent → onLoadLatest 콜백 미제공 시에도 "최신 불러오기" 가 오류 없이 동작 + onDismiss 호출', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'concurrent_modification', currentVersion: 7, yourVersion: 5 }}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
)
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('g7le-save-banner-concurrent-load-latest'));
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — blocked_inactive_extension', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('blocked kind → 경고 배너 + blockedPaths 목록 렌더', () => {
|
||||
const result: SaveResult = {
|
||||
kind: 'blocked_inactive_extension',
|
||||
blockedPaths: ['2.children.1', '4.children.0.children.2'],
|
||||
};
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
expect(screen.getByTestId('g7le-save-banner-blocked')).toBeTruthy();
|
||||
const list = screen.getByTestId('g7le-save-banner-blocked-paths');
|
||||
expect(list.textContent).toContain('2.children.1');
|
||||
expect(list.textContent).toContain('4.children.0.children.2');
|
||||
});
|
||||
|
||||
it('blocked → blockedPaths=[] 이면 배너만 표시 (목록 미표시)', () => {
|
||||
const result: SaveResult = { kind: 'blocked_inactive_extension', blockedPaths: [] };
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
expect(screen.getByTestId('g7le-save-banner-blocked')).toBeTruthy();
|
||||
expect(screen.queryByTestId('g7le-save-banner-blocked-paths')).toBeNull();
|
||||
});
|
||||
|
||||
it('blocked → 5초 후 자동 dismiss', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'blocked_inactive_extension', blockedPaths: ['a'] }}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — network_error', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('network_error kind → 에러 배너 + 메시지 표시', () => {
|
||||
const result: SaveResult = { kind: 'network_error', message: 'Failed to fetch' };
|
||||
render(withTranslation(<SaveFeedbackBanner result={result} onDismiss={vi.fn()} />));
|
||||
const banner = screen.getByTestId('g7le-save-banner-network');
|
||||
expect(banner).toBeTruthy();
|
||||
expect(banner.textContent).toContain('Failed to fetch');
|
||||
});
|
||||
|
||||
it('network_error → 5초 후 자동 dismiss', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner
|
||||
result={{ kind: 'network_error', message: 'timeout' }}
|
||||
onDismiss={onDismiss}
|
||||
/>
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — guard_no_document', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('guard_no_document kind → neutral 배너 마운트', () => {
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner result={{ kind: 'guard_no_document' }} onDismiss={vi.fn()} />
|
||||
)
|
||||
);
|
||||
expect(screen.getByTestId('g7le-save-banner-guard-no-document')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('guard_no_document → 5초 후 자동 dismiss', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner result={{ kind: 'guard_no_document' }} onDismiss={onDismiss} />
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaveFeedbackBanner — result 변경 시 dismiss 타이머 재설정', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('success → 4초 경과 후 새 success 도착 → 누적 9초 시점에도 첫 onDismiss 미호출 (타이머 재설정)', () => {
|
||||
const onDismiss = vi.fn();
|
||||
const { rerender } = render(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner result={{ kind: 'success', newLockVersion: 1 }} onDismiss={onDismiss} />
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(4000);
|
||||
});
|
||||
rerender(
|
||||
withTranslation(
|
||||
<SaveFeedbackBanner result={{ kind: 'success', newLockVersion: 2 }} onDismiss={onDismiss} />
|
||||
)
|
||||
);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(4000);
|
||||
});
|
||||
// 두 번째 success 의 5초 타이머가 아직 만료 안 됨
|
||||
expect(onDismiss).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1000);
|
||||
});
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 3582 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user