fix(core,extensions): 창 크기 변경 후 저장 시 편집기 본문이 사라지던 문제
저장소 B(_global._local)를 동기화하는 두 지점이 저장소 A 계열 스냅샷을 그대로
넘겨 왔다. setGlobalState 는 _local 을 얕게 병합하므로 그 쓰기는 patch 가 아니라
통째 교체이며, A 가 아직 받지 못한 값 — CKEditor 가 setLocal({render:false,
selfManaged:true}) 로 B 에만 쓴 본문 — 이 예외도 로그도 없이 사라진다.
handleSetState COMPONENT 분기의 B 쓰기와 sequence 반환값을 함께 live B 기반으로
바꾼다. 요청 body 는 B 가 아니라 그 반환값에서 오므로, B 쓰기만 고치면 저장은
여전히 422 가 난다. 같은 형태의 setParentLocal 도 함께 정정했다.
트리거는 브레이크포인트 교차가 아니라 19px 폭 변경이다 — 모바일 URL바 숨김·
가상키보드·화면 회전이 모두 해당한다. 작성 화면은 422 로, 수정 화면은 성공
토스트와 함께 조용한 데이터 손실로 나타났다.
함께 담은 것:
- ckeditor5: 미리보기 입력이 설정으로 저장되던 문제, 본문만 고치면 저장 버튼이
비활성으로 남던 문제
- board: 일괄 적용 확인 창의 항목 목록이 통째로 렌더되지 않던 문제(표현식
평가기가 콜백 안 멤버 대입을 거부), 「금지어」 라벨 누락
- 확장 문서의 Playwright 명령이 코어 config 를 잡아 "No tests found" 로 조용히
0건이 지나가던 문제
This commit is contained in:
1 parent
da5f76a9d8
commit
cd189190c2
41 files changed
+1899
-117
No files matched your search
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* G7CoreGlobals.selfManagedPromotion.test.ts
|
||||
*
|
||||
* 사례 40(engine-v1.63.3) L5 — 사례 32 의 자동 승격/`selfManaged` opt-out 을 **실물로** 검증한다.
|
||||
*
|
||||
* 왜 별도 파일인가:
|
||||
* 기존 사례 32 회귀 테스트(`troubleshooting-state-setstate.test.ts`)는 판정 함수
|
||||
* `shouldPromoteRender`/`flattenLeafPaths` 를 테스트 파일 안에 **재구현**해 검증한다.
|
||||
* 그래서 엔진의 판정 블록(G7CoreGlobals.ts:1834~1843)을 통째로 지워도 그 테스트는 초록이다.
|
||||
* 이 파일은 `initializeG7CoreGlobals()` 로 실제 `G7Core.state.setLocal` 을 세워
|
||||
* **엔진이 실제로 승격하는지**를 `setGlobalState` 의 `render` 인자로 관측한다.
|
||||
*
|
||||
* 그리고 troubleshooting 파일과 공존할 수 없다 — 그 파일은 실물 `ActionDispatcher` 를 쓰는데
|
||||
* 여기서는 `vi.mock('../template-engine/ActionDispatcher')` 가 필요하다.
|
||||
*
|
||||
* 사례 40 과의 관계:
|
||||
* `selfManaged: true` 는 **의도된 opt-out** 이다(37,000+ 바인딩 재평가 회피).
|
||||
* 그 opt-out 이 안전한 전제는 "저장소 B 를 통째로 교체하는 경로가 없을 것" 이며,
|
||||
* 그 전제는 사례 40 의 `handleSetState` COMPONENT path 수정이 잠근다.
|
||||
* 따라서 이 파일은 opt-out 이 **살아 있음**을 단언한다 — 없애는 것이 사례 40 의 수정 방향이 아니다.
|
||||
*
|
||||
* @see 트러블슈팅 사례 32(자동 승격 도입) · 사례 40(저장소 B 통째 교체)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { initializeG7CoreGlobals, G7CoreDependencies } from '../template-engine/G7CoreGlobals';
|
||||
|
||||
vi.mock('../template-engine/ComponentRegistry', () => ({
|
||||
ComponentRegistry: {
|
||||
getInstance: vi.fn(() => ({ getComponentMap: vi.fn(() => ({})) })),
|
||||
},
|
||||
}));
|
||||
vi.mock('../template-engine/TranslationEngine', () => ({
|
||||
TranslationEngine: vi.fn(),
|
||||
TranslationContext: {},
|
||||
}));
|
||||
vi.mock('../template-engine/ActionDispatcher', () => ({ ActionDispatcher: vi.fn() }));
|
||||
vi.mock('../template-engine/DataBindingEngine', () => ({
|
||||
DataBindingEngine: vi.fn(),
|
||||
dataBindingEngine: {},
|
||||
}));
|
||||
vi.mock('../template-engine/DataSourceManager', () => ({
|
||||
DataSourceManager: vi.fn(),
|
||||
dataSourceManager: {},
|
||||
}));
|
||||
vi.mock('../template-engine/DynamicRenderer', () => ({ default: () => null }));
|
||||
vi.mock('../template-engine/ResponsiveManager', () => ({
|
||||
responsiveManager: {},
|
||||
BREAKPOINT_PRESETS: {},
|
||||
}));
|
||||
vi.mock('../template-engine/TransitionContext', () => ({
|
||||
useTransitionState: vi.fn(() => ({ isPending: false })),
|
||||
}));
|
||||
vi.mock('../template-engine/TranslationContext', () => ({
|
||||
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
|
||||
TranslationProvider: () => null,
|
||||
TranslationReactContext: {},
|
||||
}));
|
||||
vi.mock('../template-engine/ResponsiveContext', () => ({
|
||||
useResponsive: vi.fn(() => ({ width: 1024, isMobile: false })),
|
||||
ResponsiveProvider: () => null,
|
||||
ResponsiveContext: {},
|
||||
}));
|
||||
vi.mock('../auth/AuthManager', () => ({ AuthManager: { getInstance: vi.fn() } }));
|
||||
vi.mock('../api/ApiClient', () => ({ getApiClient: vi.fn(() => ({ get: vi.fn(), post: vi.fn() })) }));
|
||||
vi.mock('../websocket/WebSocketManager', () => ({ WebSocketManager: vi.fn() }));
|
||||
vi.mock('../template-engine/helpers', () => ({
|
||||
renderItemChildren: vi.fn(() => []),
|
||||
createChangeEvent: vi.fn(),
|
||||
createClickEvent: vi.fn(),
|
||||
createSubmitEvent: vi.fn(),
|
||||
createKeyboardEvent: vi.fn(),
|
||||
mergeClasses: vi.fn((...args: string[]) => args.join(' ')),
|
||||
conditionalClass: vi.fn(() => ''),
|
||||
joinClasses: vi.fn((...args: (string | false | undefined)[]) => args.filter(Boolean).join(' ')),
|
||||
}));
|
||||
|
||||
function createMockDependencies(): G7CoreDependencies {
|
||||
return {
|
||||
getState: vi.fn(() => ({
|
||||
translationEngine: { translate: vi.fn((k: string) => k) } as any,
|
||||
translationContext: { templateId: 'test', locale: 'ko' },
|
||||
bindingEngine: {} as any,
|
||||
actionDispatcher: {} as any,
|
||||
templateMetadata: { locales: ['ko'] },
|
||||
})),
|
||||
transitionManager: { getIsPending: vi.fn(() => false), subscribe: vi.fn(() => () => {}) },
|
||||
responsiveManager: {},
|
||||
webSocketManager: {
|
||||
subscribe: vi.fn(() => 'sub'),
|
||||
unsubscribe: vi.fn(),
|
||||
leaveChannel: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
isInitialized: vi.fn(() => true),
|
||||
getSubscriptionCount: vi.fn(() => 0),
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
describe('[사례 32 실물화] setLocal 자동 승격과 selfManaged opt-out (사례 40 L5)', () => {
|
||||
let globalState: Record<string, any>;
|
||||
let setGlobalState: ReturnType<typeof vi.fn>;
|
||||
let originalG7Core: any;
|
||||
|
||||
/** 마지막 setGlobalState 호출의 render 옵션 (undefined = 미지정 = 기본 true) */
|
||||
const lastRenderOption = () => {
|
||||
const calls = setGlobalState.mock.calls;
|
||||
return calls.length ? calls[calls.length - 1][1]?.render : 'NOT_CALLED';
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalG7Core = (window as any).G7Core;
|
||||
delete (window as any).G7Core;
|
||||
|
||||
globalState = { _local: {} };
|
||||
setGlobalState = vi.fn((updates: any) => {
|
||||
globalState = { ...globalState, ...updates };
|
||||
});
|
||||
|
||||
(window as any).__templateApp = {
|
||||
getGlobalState: () => globalState,
|
||||
setGlobalState,
|
||||
// debounce 경로로 새지 않도록 ActionDispatcher 를 노출하지 않는다
|
||||
getActionDispatcher: undefined,
|
||||
};
|
||||
(window as any).__g7AutoBindingPaths = new Map<string, number>();
|
||||
(window as any).__g7PendingLocalState = undefined;
|
||||
(window as any).__g7ForcedLocalFields = undefined;
|
||||
(window as any).__g7SetLocalOverrideKeys = undefined;
|
||||
(window as any).__g7ActionContext = undefined;
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
|
||||
initializeG7CoreGlobals(createMockDependencies());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete (window as any).__templateApp;
|
||||
delete (window as any).__g7AutoBindingPaths;
|
||||
(window as any).__g7PendingLocalState = undefined;
|
||||
(window as any).__g7ForcedLocalFields = undefined;
|
||||
(window as any).__g7SetLocalOverrideKeys = undefined;
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
if (originalG7Core === undefined) delete (window as any).G7Core;
|
||||
else (window as any).G7Core = originalG7Core;
|
||||
});
|
||||
|
||||
const setLocal = (updates: any, options?: any) =>
|
||||
(window as any).G7Core.state.setLocal(updates, options);
|
||||
|
||||
it('레지스트리에 겹치는 경로를 render:false 로 쓰면 엔진이 render:true 로 승격한다', () => {
|
||||
(window as any).__g7AutoBindingPaths.set('form.title', 1);
|
||||
|
||||
setLocal({ 'form.title': 'X' }, { render: false });
|
||||
|
||||
expect(lastRenderOption()).toBe(true);
|
||||
});
|
||||
|
||||
it('selfManaged:true 는 겹쳐도 승격하지 않는다 (CKEditor 성능 opt-out 보존)', () => {
|
||||
// @scenario save_flow=edit, resize_kind=none
|
||||
// @effects selfmanaged_setlocal_writes_canonical_without_render
|
||||
(window as any).__g7AutoBindingPaths.set('form.content', 1);
|
||||
|
||||
setLocal({ 'form.content': '<p>내용</p>' }, { render: false, selfManaged: true });
|
||||
|
||||
expect(lastRenderOption()).toBe(false);
|
||||
});
|
||||
|
||||
it('레지스트리가 비면 승격하지 않는다 (SPA 네비게이션 직후)', () => {
|
||||
setLocal({ 'form.title': 'X' }, { render: false });
|
||||
|
||||
expect(lastRenderOption()).toBe(false);
|
||||
});
|
||||
|
||||
it('겹치지 않는 경로는 승격하지 않는다', () => {
|
||||
(window as any).__g7AutoBindingPaths.set('form.title', 1);
|
||||
|
||||
setLocal({ 'form.content': 'Y' }, { render: false });
|
||||
|
||||
expect(lastRenderOption()).toBe(false);
|
||||
});
|
||||
|
||||
it('render 옵션을 생략하면 판정 분기에 들어가지 않는다 (기본 render:true)', () => {
|
||||
(window as any).__g7AutoBindingPaths.set('form.title', 1);
|
||||
|
||||
setLocal({ 'form.title': 'X' });
|
||||
|
||||
expect(lastRenderOption()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('selfManaged 경로도 저장소 B 에는 값을 남긴다 (사례 40 의 재현 전제)', () => {
|
||||
// @scenario save_flow=create, resize_kind=none
|
||||
// @effects selfmanaged_setlocal_writes_canonical_without_render
|
||||
(window as any).__g7AutoBindingPaths.set('form.content', 1);
|
||||
|
||||
setLocal({ 'form.content': '<p>본문</p>' }, { render: false, selfManaged: true });
|
||||
|
||||
expect(globalState._local.form.content).toBe('<p>본문</p>');
|
||||
// 오버레이/pending 도 함께 세워진다 — 리사이즈가 pending 만 지우는 것이 결함의 절반이다
|
||||
expect((window as any).__g7PendingLocalState.form.content).toBe('<p>본문</p>');
|
||||
expect((window as any).__g7ForcedLocalFields.form.content).toBe('<p>본문</p>');
|
||||
expect((window as any).__g7SetLocalOverrideKeys.form.content).toBe('<p>본문</p>');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* 회귀: `setParentLocal` 의 저장소 B 쓰기가 live B 를 base 로 한다 (engine-v1.63.3 / 공개 이슈 #130 계열)
|
||||
*
|
||||
* 결함: `setParentLocal` 은 부모 컨텍스트의 **저장소 A**(`parentEntry.state._local`)를 base 로
|
||||
* `merged` 를 만든 뒤 그것을 그대로 `setGlobalState({ _local: merged })` 로 보냈다.
|
||||
* `setGlobalState` 는 `_local` 을 얕게 병합하므로 이 쓰기는 patch 가 아니라 **통째 교체**이며,
|
||||
* A 가 아직 받지 못한 값(예: `selfManaged` 플러그인이 B 에만 쓴 편집기 본문)이 조용히 사라진다.
|
||||
* 부모가 페이지 루트일 때 그 A 스냅샷은 B 보다 뒤처져 있을 수 있다(사례 21).
|
||||
*
|
||||
* 계약:
|
||||
* 1. B 쓰기는 live B + 변경 키 (A 에만 있던 키는 `addMissingLeafKeys` 로 보충)
|
||||
* 2. 저장소 A 경로(`parentEntry.setState`)와 `__g7PendingLocalState` 는 종전 그대로 —
|
||||
* 그쪽 base 를 바꾸면 React 전용 배열이 B 초기값으로 덮이는 사례 22 위험이 생긴다
|
||||
* 3. `merge: 'replace'` 는 의도적 리셋이므로 live B 를 base 로 쓰지 않는다 (사례 17)
|
||||
*
|
||||
* 이 파일은 **실물 엔진**을 세운다 — `template-engine/__tests__/G7CoreGlobals.test.ts` 의
|
||||
* `setParentLocal` 테스트는 G7Core 를 테스트 파일 안에 재구현해 검증하므로 엔진을 지워도 초록이다.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { initializeG7CoreGlobals, G7CoreDependencies } from '../template-engine/G7CoreGlobals';
|
||||
|
||||
vi.mock('../template-engine/ComponentRegistry', () => ({
|
||||
ComponentRegistry: { getInstance: vi.fn(() => ({ getComponentMap: vi.fn(() => ({})) })) },
|
||||
}));
|
||||
vi.mock('../template-engine/TranslationEngine', () => ({ TranslationEngine: vi.fn(), TranslationContext: {} }));
|
||||
vi.mock('../template-engine/ActionDispatcher', () => ({ ActionDispatcher: vi.fn() }));
|
||||
vi.mock('../template-engine/DataBindingEngine', () => ({ DataBindingEngine: vi.fn(), dataBindingEngine: {} }));
|
||||
vi.mock('../template-engine/DataSourceManager', () => ({ DataSourceManager: vi.fn(), dataSourceManager: {} }));
|
||||
vi.mock('../template-engine/DynamicRenderer', () => ({ default: () => null }));
|
||||
vi.mock('../template-engine/ResponsiveManager', () => ({ responsiveManager: {}, BREAKPOINT_PRESETS: {} }));
|
||||
vi.mock('../template-engine/TransitionContext', () => ({ useTransitionState: vi.fn(() => ({ isPending: false })) }));
|
||||
vi.mock('../template-engine/TranslationContext', () => ({
|
||||
useTranslation: vi.fn(() => ({ t: (k: string) => k })),
|
||||
TranslationProvider: () => null,
|
||||
TranslationReactContext: {},
|
||||
}));
|
||||
vi.mock('../template-engine/ResponsiveContext', () => ({
|
||||
useResponsive: vi.fn(() => ({ width: 1024, isMobile: false })),
|
||||
ResponsiveProvider: () => null,
|
||||
ResponsiveContext: {},
|
||||
}));
|
||||
vi.mock('../auth/AuthManager', () => ({ AuthManager: { getInstance: vi.fn() } }));
|
||||
vi.mock('../api/ApiClient', () => ({ getApiClient: vi.fn(() => ({ get: vi.fn(), post: vi.fn() })) }));
|
||||
vi.mock('../websocket/WebSocketManager', () => ({ WebSocketManager: vi.fn() }));
|
||||
vi.mock('../template-engine/helpers', () => ({
|
||||
renderItemChildren: vi.fn(() => []),
|
||||
createChangeEvent: vi.fn(),
|
||||
createClickEvent: vi.fn(),
|
||||
createSubmitEvent: vi.fn(),
|
||||
createKeyboardEvent: vi.fn(),
|
||||
mergeClasses: vi.fn((...a: string[]) => a.join(' ')),
|
||||
conditionalClass: vi.fn(() => ''),
|
||||
joinClasses: vi.fn((...a: (string | false | undefined)[]) => a.filter(Boolean).join(' ')),
|
||||
}));
|
||||
|
||||
function createMockDependencies(): G7CoreDependencies {
|
||||
return {
|
||||
getState: vi.fn(() => ({
|
||||
translationEngine: { translate: vi.fn((k: string) => k) } as any,
|
||||
translationContext: { templateId: 'test', locale: 'ko' },
|
||||
bindingEngine: {} as any,
|
||||
actionDispatcher: {} as any,
|
||||
templateMetadata: { locales: ['ko'] },
|
||||
})),
|
||||
transitionManager: { getIsPending: vi.fn(() => false), subscribe: vi.fn(() => () => {}) },
|
||||
responsiveManager: {},
|
||||
webSocketManager: {
|
||||
subscribe: vi.fn(() => 'sub'),
|
||||
unsubscribe: vi.fn(),
|
||||
leaveChannel: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
isInitialized: vi.fn(() => true),
|
||||
getSubscriptionCount: vi.fn(() => 0),
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
describe('setParentLocal — 저장소 B 쓰기는 live B 를 base 로 한다', () => {
|
||||
let globalState: Record<string, any>;
|
||||
let setGlobalState: ReturnType<typeof vi.fn>;
|
||||
let parentSetState: ReturnType<typeof vi.fn>;
|
||||
let originalG7Core: any;
|
||||
|
||||
/** setGlobalState 로 B 에 실제로 쓰인 _local */
|
||||
const writtenLocal = () => {
|
||||
const calls = setGlobalState.mock.calls;
|
||||
return calls.length ? calls[calls.length - 1][0]._local : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* 부모 컨텍스트를 스택에 세웁니다.
|
||||
*
|
||||
* @param parentLocalA 부모 컨텍스트의 저장소 A 스냅샷
|
||||
*/
|
||||
const pushParent = (parentLocalA: Record<string, any>): void => {
|
||||
(window as any).__g7LayoutContextStack = [{ state: { _local: parentLocalA }, setState: parentSetState }];
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalG7Core = (window as any).G7Core;
|
||||
delete (window as any).G7Core;
|
||||
|
||||
globalState = { _local: {} };
|
||||
setGlobalState = vi.fn((updates: any) => {
|
||||
globalState = { ...globalState, ...updates };
|
||||
});
|
||||
parentSetState = vi.fn();
|
||||
|
||||
(window as any).__templateApp = { getGlobalState: () => globalState, setGlobalState };
|
||||
(window as any).__g7PendingLocalState = undefined;
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
|
||||
initializeG7CoreGlobals(createMockDependencies());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete (window as any).__templateApp;
|
||||
(window as any).__g7PendingLocalState = undefined;
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
if (originalG7Core === undefined) delete (window as any).G7Core;
|
||||
else (window as any).G7Core = originalG7Core;
|
||||
});
|
||||
|
||||
it('결함 재현 핀: B 에만 있던 편집기 본문이 stale 부모 A 스냅샷으로 덮이지 않는다', () => {
|
||||
// CKEditor 가 setLocal({render:false, selfManaged:true}) 로 B 에만 기록한 본문
|
||||
globalState._local = { form: { title: '제목', content: '<p>본문</p>' } };
|
||||
// 부모 컨텍스트의 저장소 A 는 그 본문을 아직 못 받았다
|
||||
pushParent({ form: { title: '제목', content: '' } });
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ 'form.title': '새 제목' });
|
||||
|
||||
expect(writtenLocal().form.content, 'B 의 본문이 살아 있어야 한다').toBe('<p>본문</p>');
|
||||
expect(writtenLocal().form.title).toBe('새 제목');
|
||||
});
|
||||
|
||||
it('B 에만 있던 최상위 키도 잃지 않는다', () => {
|
||||
globalState._local = { couponId: 7, orderer: { name: '관리자' } };
|
||||
pushParent({ selectedItems: [1, 2] });
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ memo: 'x' });
|
||||
|
||||
expect(writtenLocal().couponId).toBe(7);
|
||||
expect(writtenLocal().orderer).toEqual({ name: '관리자' });
|
||||
expect(writtenLocal().memo).toBe('x');
|
||||
});
|
||||
|
||||
it('부모 A 에만 있던 키는 addMissingLeafKeys 로 보충된다', () => {
|
||||
globalState._local = { form: { content: '<p>본문</p>' } };
|
||||
pushParent({ form: { content: '' }, loadingActions: { save: true } });
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ memo: 'y' });
|
||||
|
||||
expect(writtenLocal().loadingActions, 'A 전용 키가 B 에 보충되어야 한다').toEqual({ save: true });
|
||||
expect(writtenLocal().form.content).toBe('<p>본문</p>');
|
||||
});
|
||||
|
||||
it('사례 22 핀: 저장소 A 경로는 종전대로 부모 A 기반이다', () => {
|
||||
globalState._local = { expandedRows: [] };
|
||||
pushParent({ expandedRows: [301] });
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ memo: 'z' });
|
||||
|
||||
// parentEntry.setState 는 부모 A 기반 merged 를 받아야 한다 (B 기반으로 바꾸면 배열이 초기값으로 덮인다)
|
||||
expect(parentSetState).toHaveBeenCalledTimes(1);
|
||||
expect(parentSetState.mock.calls[0][0].expandedRows).toEqual([301]);
|
||||
});
|
||||
|
||||
it('사례 17 핀: merge replace 는 live B 를 base 로 쓰지 않는다', () => {
|
||||
globalState._local = { form: { content: '<p>본문</p>' }, keep: 1 };
|
||||
pushParent({ form: { content: '' } });
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ only: 'this' }, { merge: 'replace' });
|
||||
|
||||
expect(writtenLocal().keep, 'replace 는 의도적 리셋이다').toBeUndefined();
|
||||
expect(writtenLocal().only).toBe('this');
|
||||
});
|
||||
|
||||
it('merge shallow 도 live B 를 base 로 한다', () => {
|
||||
globalState._local = { a: 1, b: 2, form: { content: '<p>본문</p>' } };
|
||||
pushParent({ a: 1 });
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ b: 99 }, { merge: 'shallow' });
|
||||
|
||||
expect(writtenLocal().b).toBe(99);
|
||||
expect(writtenLocal().a).toBe(1);
|
||||
expect(writtenLocal().form.content).toBe('<p>본문</p>');
|
||||
});
|
||||
|
||||
it('컨텍스트 스택이 비면 아무것도 쓰지 않는다', () => {
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
|
||||
(window as any).G7Core.state.setParentLocal({ x: 1 });
|
||||
|
||||
expect(setGlobalState).not.toHaveBeenCalled();
|
||||
expect(parentSetState).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,7 @@ import type { ErrorHandlerConfig, ErrorContext } from '../types/ErrorHandling';
|
||||
import { createLogger } from '../utils/Logger';
|
||||
import type { G7DevToolsInterface } from './G7CoreGlobals';
|
||||
import { evaluateConditionBranches } from './helpers/ConditionEvaluator';
|
||||
import { addMissingLeafKeys } from './helpers/StateMerge';
|
||||
import { triggerModalParentUpdate } from './ParentContextProvider';
|
||||
import type { GlobalHeaderRule } from './LayoutLoader';
|
||||
import { IdentityGuardInterceptor } from '../identity/IdentityGuardInterceptor';
|
||||
@@ -4141,9 +4142,69 @@ export class ActionDispatcher {
|
||||
// (_localInit 미반영 시점)에 __g7PendingLocalState 를 fresh B baseline 으로 미리 채워두므로,
|
||||
// currentState 가 pending(정상)을 우선 사용하여 stale context.state 를 건너뛴다.
|
||||
// 그 사전설정 경로를 변경/제거하면 사례 13/22(stale 배열의 globalLocal 통째 교체 오염) 재발 가능성을 함께 점검해야 한다.
|
||||
// engine-v1.63.3 (공개 이슈 #130): B 동기화의 base 를 A 계열 전체 스냅샷에서
|
||||
// live B(_global._local) + 변경 키로 바꾼다.
|
||||
//
|
||||
// 위 [안전성 의존 관계] 주석이 전제한 "currentState 가 정합한 _local 전체" 는 성립하지
|
||||
// 않는 구간이 있다. CKEditor 등 selfManaged 플러그인이 setLocal({render:false}) 로
|
||||
// B 에만 본문을 쓰면 React 렌더가 일어나지 않아 extendedDataContext useMemo 가
|
||||
// 재계산되지 않고(deps 에 __g7ForcedLocalFields 가 없다 — window 전역이라 deps 가 될 수 없다),
|
||||
// context.state 는 본문 타이핑 이전 스냅샷으로 고정된다. 그 상태에서 폭 변경 리렌더가
|
||||
// __g7PendingLocalState 를 null 로 지우면(DynamicRenderer.tsx:1110) currentState 가
|
||||
// stale A 로 떨어지고, 그것을 B 에 통째로 덮어써 본문이 사라진다.
|
||||
//
|
||||
// 정답 선례는 같은 파일의 dot-notation path(engine-v1.58.2, :4235~)다. 그것이 이미
|
||||
// "live B base + 변경 키" 로 같은 문제를 풀었고 주석에서 이 COMPONENT path 를 위험으로
|
||||
// 지목했다. 이번 수정은 그 정책을 이 경로에 맞춘다.
|
||||
//
|
||||
// 제외 조건:
|
||||
// - merge:"replace" — 의도적 리셋이므로 live B 를 base 로 삼지 않는다 (사례 17)
|
||||
// - 모달 컨텍스트 스택이 있음 — 모달의 setState 가 페이지 _local 을 흡수하는 것을 막는다
|
||||
// (사례 29, setLocal v1.24.7 가드와 동형)
|
||||
// 한계: 스택은 openModal/closeModal 핸들러에서만 push/pop 되므로(:4836·:4911)
|
||||
// setState 플래그로 여는 모달과 G7Core.modal.open() 은 depth 0 으로 보인다. 이는
|
||||
// v1.24.7 가드가 이미 가진 사각과 동일하며, 그 경우에도 새 동작은 "B 통째 교체" 가
|
||||
// 아니라 "B 에 병합" 이라 사례 29 대비 악화되지 않는다.
|
||||
// - __templateApp 부재 — 종전 전체 스냅샷 폴백 (v1.50.4 호환)
|
||||
//
|
||||
// merge:"shallow" 는 제외하지 않는다. 현행 shallow 는 pending 을 무시하고 context.state
|
||||
// 만 base 로 쓰므로(:4110) 리프 컴포넌트의 부분 상태가 base 가 되어 오히려 이 결함에
|
||||
// 더 노출돼 있다.
|
||||
const modalDepth = ((window as any).__g7LayoutContextStack || []).length;
|
||||
let canonicalMerged: Record<string, any> | undefined;
|
||||
|
||||
if (this.globalStateUpdater) {
|
||||
this.globalStateUpdater({ _local: pendingExpected }, { render: false });
|
||||
logger.log('[handleSetState] _global._local synced (render:false):', pendingExpected);
|
||||
const canonicalLocal = modalDepth === 0
|
||||
? (window as any).__templateApp?.getGlobalState?.()?._local
|
||||
: undefined;
|
||||
const canUseCanonical = mergeMode !== 'replace'
|
||||
&& !!canonicalLocal && typeof canonicalLocal === 'object' && !Array.isArray(canonicalLocal);
|
||||
|
||||
if (canUseCanonical) {
|
||||
// convertedPayload 를 쓰면 안 된다 — 그것은 빈 base 위의 변환이라
|
||||
// {"form.title":"X"} → {form:{title:"X"}} 가 되고, 얕게 얹으면 B.form 이 통째
|
||||
// 교체되어 고치려던 결함을 재생산한다. deepMergeWithState 는 createNestedUpdate 로
|
||||
// 형제 키를 유지한 채 leaf 만 바꾼다. result={...currentState}(:4521) 로 시작하고
|
||||
// deepMergeInto 가 참조 동일성 가드(:4608)로 매 레벨 방어 복사하므로 live B 를
|
||||
// 변이하지 않는다.
|
||||
const merged = mergeMode === 'deep'
|
||||
? this.deepMergeWithState(resolvedPayload, canonicalLocal as Record<string, any>)
|
||||
: { ...(canonicalLocal as Record<string, any>), ...resolvedPayload };
|
||||
const { __mergeMode: _cmm, __setStateId: _cssid, ...rest } = merged as any;
|
||||
canonicalMerged = rest;
|
||||
} else if (mergeMode !== 'replace') {
|
||||
logger.log('[handleSetState] canonical _local 미사용 → 전체 스냅샷 폴백',
|
||||
{ modalDepth, hasTemplateApp: !!(window as any).__templateApp });
|
||||
}
|
||||
|
||||
// B 쓰기에도 A 전용 키를 보충한다 — setLocal 선례(G7CoreGlobals 의
|
||||
// addMissingLeafKeys(globalLocal, dynamicLocal))와 대칭.
|
||||
// addMissingLeafKeys 는 base 에 이미 있는 값을 절대 덮지 않으므로 사례 13/22 위험이 없다.
|
||||
const syncedLocal = canonicalMerged
|
||||
? addMissingLeafKeys(canonicalMerged, pendingExpected)
|
||||
: pendingExpected;
|
||||
this.globalStateUpdater({ _local: syncedLocal }, { render: false });
|
||||
logger.log('[handleSetState] _global._local synced (render:false):', syncedLocal);
|
||||
}
|
||||
|
||||
// engine-v1.17.5: dataKey 자동 바인딩이 있는 컴포넌트에서 setState 핸들러 호출 시
|
||||
@@ -4170,7 +4231,24 @@ export class ActionDispatcher {
|
||||
// DevTools: 렌더링 완료 후 상태 변경 완료 (DynamicRenderer에서 처리되지만 fallback으로 setTimeout 사용)
|
||||
if (setStateId && devTools) setTimeout(() => devTools.completeStateChange(setStateId), 0);
|
||||
// sequence에서 _local 동기화에 사용하기 위해 __target 마커 추가
|
||||
return { __target: 'local', ...fullMergedState };
|
||||
//
|
||||
// engine-v1.63.3 (공개 이슈 #130): 반환값도 live B 기반으로 신선화한다.
|
||||
// 요청 body 는 저장소 B 를 읽지 않는다 — handleApiCall 의 getLocal() 은
|
||||
// getMatchingGlobalHeaders 전용이고, body 는 sequence 의 currentState(= 이 반환값)에서
|
||||
// 온다(handleSequence:5342·5379·5428, 트러블슈팅 사례 15 계약). 따라서 B 쓰기만 고치면
|
||||
// B 는 지켜지지만 422 는 그대로 난다.
|
||||
//
|
||||
// base 는 live B(충돌 leaf 는 B 승), extra 는 A 기반 스냅샷에서 B 에 없는 키만 보충
|
||||
// — 사례 13(engine-v1.41.0) 정책 재사용. React 전용 키(loadingActions, DataGrid 선택 등)를
|
||||
// 잃지 않는다. __mergeMode 재부착은 handleSequence:5431~5438 계약 보존용.
|
||||
const returnedState = canonicalMerged
|
||||
? addMissingLeafKeys(canonicalMerged, pendingExpected)
|
||||
: fullMergedState;
|
||||
return {
|
||||
__target: 'local',
|
||||
...returnedState,
|
||||
...(mergeMode !== 'deep' ? { __mergeMode: mergeMode } : {}),
|
||||
};
|
||||
} else if (this.globalStateUpdater) {
|
||||
// init_actions 등에서 componentContext가 없는 경우 globalStateUpdater를 통해 _local 업데이트
|
||||
logger.log('[handleSetState] Using GLOBAL STATE UPDATER path for _local');
|
||||
|
||||
@@ -5,6 +5,28 @@
|
||||
>
|
||||
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
|
||||
|
||||
## [engine-v1.63.3] - 2026-09-01
|
||||
|
||||
### Fixed
|
||||
|
||||
#### 리사이즈 후 저장 시 편집기 본문이 저장소 B 와 sequence 반환값에서 함께 사라지던 문제 (#130)
|
||||
|
||||
- `handleSetState` 의 COMPONENT 분기가 `_global._local`(저장소 B)을 동기화할 때, base 를 저장소 A 계열 전체 스냅샷 대신 **live B + 변경 키**로 삼는다. `setGlobalState` 는 `_local` 을 얕게 병합하므로 이 동기화는 patch 가 아니라 **통째 교체**였고, A 가 아직 받지 못한 값이 조용히 사라졌다. 정답 선례는 같은 파일의 dot-notation 경로(engine-v1.58.2)이며 그 주석이 이 경로를 위험으로 지목하고 있었다.
|
||||
- **같은 분기의 반환값도 live B 기반으로 신선화한다.** 요청 body 는 저장소 B 를 읽지 않는다 — sequence 의 `currentState`(= 이 반환값)에서 온다. B 쓰기만 고치면 B 는 지켜지지만 저장은 여전히 422 가 났다.
|
||||
- A 가 값을 못 받는 대표 경로는 `setLocal({ render:false, selfManaged:true })`(CKEditor5 등 자체 DOM 관리 플러그인)다. 이 호출은 React 렌더를 한 번도 일으키지 않아, `extendedDataContext` useMemo 가 재계산되지 않고 `context.state` 가 입력 이전 스냅샷으로 고정된다. 여기에 **브레이크포인트를 넘지 않는 폭 변경**(19px 로 재현)이 겹쳐 `__g7PendingLocalState` 가 null 이 되면 base 가 stale A 로 떨어졌다.
|
||||
- 예외도 콘솔 에러도 남지 않는 결함이었다 — 작성 화면은 422, **수정 화면은 성공 토스트와 함께 직전 본문이 저장되어 편집분이 사라졌다.**
|
||||
- 제외 조건은 종전 동작을 유지한다: `merge:"replace"`(의도적 리셋 · 사례 17), 모달 컨텍스트 스택이 있는 경우(사례 29), `__templateApp` 부재(v1.50.4 호환 폴백). `merge:"shallow"` 는 제외하지 않는다 — 현행 shallow 는 리프 컴포넌트의 부분 상태를 base 로 써서 오히려 이 결함에 더 노출돼 있었다.
|
||||
- 두 쓰기 경로(B 쓰기 · 반환값)가 같은 규칙으로 저장소 A 전용 키(`loadingActions` 등)를 보충한다. 규칙이 갈리면 나중에 소비자가 생길 때 어느 경로를 탔느냐로 결과가 달라진다.
|
||||
|
||||
#### `setParentLocal` 이 모달에서 부모로 값을 올릴 때 저장소 B 를 통째 교체하던 문제
|
||||
|
||||
- `setParentLocal` 은 부모 컨텍스트의 **저장소 A**(`parentEntry.state._local`)를 base 로 만든 값을 그대로 `setGlobalState({ _local: ... })` 에 넘겼다. 위와 같은 얕은 병합 특성 때문에 이 쓰기도 patch 가 아니라 통째 교체였고, 부모가 페이지 루트일 때 그 A 스냅샷은 B 보다 뒤처져 있을 수 있다(사례 21). 이제 B 에는 live B + 변경 키만 얹고 A 전용 키는 보충한다.
|
||||
- 저장소 A 경로(`parentEntry.setState`)와 `__g7PendingLocalState` 는 종전 그대로다 — 그쪽 base 까지 B 기반으로 바꾸면 React 전용 배열이 B 초기값으로 덮이는 사례 22 위험이 생긴다. `merge:"replace"` 는 여기서도 제외한다(사례 17).
|
||||
|
||||
### Changed
|
||||
|
||||
- `addMissingLeafKeys` 를 `helpers/StateMerge.ts` 로 옮겨 `G7CoreGlobals` 와 `ActionDispatcher` 가 공유한다. `G7CoreGlobals` 가 이미 `ActionDispatcher` 를 import 하고 있어 역방향 값 import 가 런타임 순환이 되기 때문이며, 동작은 원문 그대로다.
|
||||
|
||||
## [engine-v1.63.2] - 2026-08-27
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -22,6 +22,7 @@ import { DataBindingEngine, dataBindingEngine } from './DataBindingEngine';
|
||||
import { hasPipes } from './PipeRegistry';
|
||||
import { extractSingleBinding } from './BindingShape';
|
||||
import { evaluateStringCondition } from './helpers/ConditionEvaluator';
|
||||
import { addMissingLeafKeys } from './helpers/StateMerge';
|
||||
import { DataSourceManager, dataSourceManager } from './DataSourceManager';
|
||||
import DynamicRenderer from './DynamicRenderer';
|
||||
import { useTransitionState } from './TransitionContext';
|
||||
@@ -1627,48 +1628,10 @@ function hasOnlyNumericKeys(obj: Record<string, any>): boolean {
|
||||
* @param source 병합할 소스 객체
|
||||
* @returns 병합된 결과 객체
|
||||
*/
|
||||
/**
|
||||
* base 객체에 없는 leaf 키만 extra에서 추가합니다.
|
||||
*
|
||||
* deepMerge와 달리 base에 이미 존재하는 값(배열 포함)은 절대 덮어쓰지 않습니다.
|
||||
* extra에만 존재하는 키는 재귀적으로 추가됩니다.
|
||||
*
|
||||
* 용도: setLocal에서 dynamicLocal(actionContext.state)의 setState 전용 키를 globalLocal에
|
||||
* 안전하게 추가할 때 사용. dynamicLocal의 stale 배열(init_actions 기본값)이 globalLocal의
|
||||
* 정상 API 데이터를 덮어쓰는 것을 방지합니다.
|
||||
*
|
||||
* @since engine-v1.41.0
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const base = { form: { category_ids: [381, 384], name: 'A' } };
|
||||
* const extra = { form: { category_ids: [], options: [] }, selectedProducts: [1] };
|
||||
* addMissingLeafKeys(base, extra);
|
||||
* // → { form: { category_ids: [381, 384], name: 'A', options: [] }, selectedProducts: [1] }
|
||||
* // base의 category_ids는 보존, extra의 selectedProducts와 options는 추가
|
||||
* ```
|
||||
*/
|
||||
function addMissingLeafKeys(base: Record<string, any>, extra: Record<string, any>): Record<string, any> {
|
||||
const result = { ...base };
|
||||
for (const key of Object.keys(extra)) {
|
||||
if (!(key in result)) {
|
||||
// base에 없는 키: extra 값 그대로 추가
|
||||
result[key] = extra[key];
|
||||
} else if (
|
||||
result[key] !== null &&
|
||||
typeof result[key] === 'object' &&
|
||||
!Array.isArray(result[key]) &&
|
||||
extra[key] !== null &&
|
||||
typeof extra[key] === 'object' &&
|
||||
!Array.isArray(extra[key])
|
||||
) {
|
||||
// 양쪽 모두 plain object: 재귀적으로 처리
|
||||
result[key] = addMissingLeafKeys(result[key], extra[key]);
|
||||
}
|
||||
// base에 이미 존재하는 leaf 값(배열, 문자열, 숫자 등): 건너뜀 (base 값 보존)
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// addMissingLeafKeys 는 engine-v1.63.3 에서 helpers/StateMerge 로 이동했다.
|
||||
// ActionDispatcher 의 handleSetState COMPONENT path 가 같은 보충 규칙을 써야 하는데
|
||||
// G7CoreGlobals → ActionDispatcher import 가 이미 있어 역방향 값 import 가 순환이 되기 때문이다.
|
||||
// 동작은 원문 그대로다 (사례 13 회귀 테스트가 잠금 역할).
|
||||
|
||||
function deepMerge(target: Record<string, any>, source: Record<string, any>): Record<string, any> {
|
||||
// 특수 케이스: target이 배열이고 source가 숫자 키만 가진 객체인 경우
|
||||
@@ -2363,7 +2326,31 @@ function initStateAPI(G7Core: any): void {
|
||||
// globalState._local도 함께 업데이트해야 후속 getLocal() 호출이 최신 값을 반환함.
|
||||
const templateApp = (window as any).__templateApp;
|
||||
if (templateApp?.setGlobalState) {
|
||||
templateApp.setGlobalState({ _local: merged });
|
||||
// 저장소 B 쓰기의 base 는 live B 다 (engine-v1.63.3 / 공개 이슈 #130 과 같은 정책).
|
||||
//
|
||||
// `merged` 는 부모 컨텍스트의 **저장소 A**(`parentEntry.state._local`)를 base 로 만든 값이다.
|
||||
// `setGlobalState` 는 `_local` 을 얕게 병합하므로 그것을 그대로 쓰면 B 가 통째 교체되고,
|
||||
// A 가 아직 받지 못한 값(예: selfManaged 플러그인이 B 에만 쓴 편집기 본문)이 사라진다.
|
||||
// 부모 컨텍스트가 페이지 루트일 때 그 A 스냅샷은 B 보다 뒤처져 있을 수 있다(사례 21).
|
||||
//
|
||||
// 그래서 B 에는 live B + 변경 키만 얹고, A 전용 키는 `addMissingLeafKeys` 로 보충한다.
|
||||
// 저장소 A 경로(`parentEntry.setState`)와 pending 은 종전 그대로 둔다 — 그쪽 base 를
|
||||
// 바꾸면 React 전용 배열이 B 초기값으로 덮이는 사례 22 위험이 생긴다.
|
||||
//
|
||||
// `merge: 'replace'` 는 의도적 리셋이므로 제외한다(사례 17).
|
||||
const canonicalLocal = templateApp.getGlobalState?.()?._local;
|
||||
const canUseCanonical = mergeMode !== 'replace'
|
||||
&& !!canonicalLocal && typeof canonicalLocal === 'object' && !Array.isArray(canonicalLocal);
|
||||
|
||||
const canonicalMerged = canUseCanonical
|
||||
? (mergeMode === 'shallow'
|
||||
? { ...(canonicalLocal as Record<string, any>), ...converted }
|
||||
: deepMerge(canonicalLocal as Record<string, any>, converted))
|
||||
: undefined;
|
||||
|
||||
templateApp.setGlobalState({
|
||||
_local: canonicalMerged ? addMissingLeafKeys(canonicalMerged, merged) : merged,
|
||||
});
|
||||
}
|
||||
|
||||
parentEntry.setState(merged);
|
||||
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* DynamicRenderer.resizePendingClear.test.tsx
|
||||
*
|
||||
* 사례 40(engine-v1.63.3) 위험 핀 — 트리거의 절반을 실물 렌더로 잠근다.
|
||||
*
|
||||
* 공개 이슈 #130 의 재현 조건은 두 조각으로 이루어진다:
|
||||
* ① CKEditor 가 `setLocal({ render:false, selfManaged:true })` 로 저장소 B 에만 본문을 기록
|
||||
* ② **브레이크포인트를 넘지 않는 폭 변경만으로도** 루트 렌더러가 리렌더되어
|
||||
* `__g7PendingLocalState` 가 null 이 된다
|
||||
*
|
||||
* 이 파일은 ②만 잠근다. `useLayoutEffect` 에 의존성 배열이 없어(DynamicRenderer.tsx:1082~1116)
|
||||
* ResponsiveContext 의 width 값이 바뀌어 리렌더가 일어나기만 하면 클리어가 실행된다는 사실이
|
||||
* 코드 주석이 아니라 실물 렌더로 고정된다. 이 줄에 의존성 배열이 붙거나 조건이 생기면
|
||||
* 여기서 red 가 된다.
|
||||
*
|
||||
* 소실 자체(저장소 B 통째 교체)는 이 계층에서 재현할 수 없다 — TemplateApp 재구현이 필요하다.
|
||||
* 그 축은 troubleshooting-state-setstate.test.ts 의 `[사례 40]` 이 담당한다.
|
||||
* 따라서 이 파일은 fail-first 가 아니다.
|
||||
*
|
||||
* @see 트러블슈팅 사례 40 (저장소 B 통째 교체 + stale 반환값)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { render, cleanup } 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';
|
||||
import * as ResponsiveContextModule from '../ResponsiveContext';
|
||||
|
||||
vi.mock('../ResponsiveManager', () => ({
|
||||
responsiveManager: {
|
||||
getWidth: vi.fn(() => 1440),
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
getMatchingKey: vi.fn(() => null),
|
||||
parseRange: vi.fn(() => null),
|
||||
},
|
||||
}));
|
||||
|
||||
const TestDiv: React.FC<{ className?: string; children?: React.ReactNode }> = ({
|
||||
className,
|
||||
children,
|
||||
}) => (
|
||||
<div data-testid="test-div" className={className}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
describe('DynamicRenderer — 폭 변경만으로 __g7PendingLocalState 가 클리어된다 (사례 40 위험 핀)', () => {
|
||||
let registry: ComponentRegistry;
|
||||
let bindingEngine: DataBindingEngine;
|
||||
let translationEngine: TranslationEngine;
|
||||
let actionDispatcher: ActionDispatcher;
|
||||
let translationContext: TranslationContext;
|
||||
|
||||
const setWidth = (width: number) => {
|
||||
vi.spyOn(ResponsiveContextModule, 'useResponsive').mockReturnValue({
|
||||
width,
|
||||
isMobile: width < 768,
|
||||
isTablet: width >= 768 && width < 1024,
|
||||
isDesktop: width >= 1024,
|
||||
matchedPreset: width < 768 ? 'mobile' : width < 1024 ? 'tablet' : 'desktop',
|
||||
} as any);
|
||||
};
|
||||
|
||||
const componentDef: ComponentDefinition = {
|
||||
id: 'resize-pending-root',
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { className: 'root' },
|
||||
};
|
||||
|
||||
const renderTree = () => (
|
||||
<DynamicRenderer
|
||||
componentDef={componentDef}
|
||||
dataContext={{ _local: { form: { title: '제목' } } }}
|
||||
translationContext={translationContext}
|
||||
registry={registry}
|
||||
bindingEngine={bindingEngine}
|
||||
translationEngine={translationEngine}
|
||||
actionDispatcher={actionDispatcher}
|
||||
/>
|
||||
);
|
||||
|
||||
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' };
|
||||
|
||||
setWidth(1440);
|
||||
delete (window as any).__g7PendingLocalState;
|
||||
delete (window as any).__g7SetLocalOverrideKeys;
|
||||
delete (window as any).__g7ForcedLocalFields;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
delete (window as any).__g7PendingLocalState;
|
||||
delete (window as any).__g7SetLocalOverrideKeys;
|
||||
delete (window as any).__g7ForcedLocalFields;
|
||||
});
|
||||
|
||||
it('브레이크포인트를 넘지 않는 19px 변경만으로 pending 이 null 이 된다', () => {
|
||||
// @scenario save_flow=create, resize_kind=same_breakpoint
|
||||
// @effects resize_clears_pending_local_state
|
||||
const { rerender } = render(renderTree());
|
||||
|
||||
// CKEditor 의 setLocal(render:false) 이 남긴 상태를 모사한다
|
||||
(window as any).__g7PendingLocalState = { form: { content: '<p>본문</p>' } };
|
||||
(window as any).__g7SetLocalOverrideKeys = { form: { content: '<p>본문</p>' } };
|
||||
(window as any).__g7ForcedLocalFields = { form: { content: '<p>본문</p>' } };
|
||||
|
||||
// 1440 → 1421: desktop 프리셋 안에서만 움직인다 (브레이크포인트 미교차)
|
||||
setWidth(1421);
|
||||
rerender(renderTree());
|
||||
|
||||
expect((window as any).__g7PendingLocalState).toBeNull();
|
||||
});
|
||||
|
||||
it('같은 렌더에서 __g7ForcedLocalFields 는 살아남는다 (__g7SetLocalOverrideKeys 가 있으므로)', () => {
|
||||
// @scenario save_flow=create, resize_kind=crossed_breakpoint
|
||||
// @effects resize_clears_pending_local_state
|
||||
const { rerender } = render(renderTree());
|
||||
|
||||
(window as any).__g7PendingLocalState = { form: { content: '<p>본문</p>' } };
|
||||
(window as any).__g7SetLocalOverrideKeys = { form: { content: '<p>본문</p>' } };
|
||||
(window as any).__g7ForcedLocalFields = { form: { content: '<p>본문</p>' } };
|
||||
|
||||
setWidth(1421);
|
||||
rerender(renderTree());
|
||||
|
||||
// 오버레이는 조건부 클리어라 남는다 — 그럼에도 결함이 나는 이유는
|
||||
// extendedDataContext useMemo 의 deps 가 이 전역을 포함하지 않아
|
||||
// 리사이즈 렌더에서 오버레이가 context.state 로 합성되지 않기 때문이다.
|
||||
expect((window as any).__g7ForcedLocalFields).toEqual({ form: { content: '<p>본문</p>' } });
|
||||
});
|
||||
|
||||
it('__g7SetLocalOverrideKeys 가 없으면 오버레이도 함께 클리어된다 (조건부 클리어 계약)', () => {
|
||||
const { rerender } = render(renderTree());
|
||||
|
||||
(window as any).__g7PendingLocalState = { form: { content: '<p>본문</p>' } };
|
||||
(window as any).__g7ForcedLocalFields = { form: { content: '<p>본문</p>' } };
|
||||
delete (window as any).__g7SetLocalOverrideKeys;
|
||||
|
||||
setWidth(1421);
|
||||
rerender(renderTree());
|
||||
|
||||
expect((window as any).__g7PendingLocalState).toBeNull();
|
||||
expect((window as any).__g7ForcedLocalFields).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -5269,3 +5269,221 @@ describe('[사례 39] dot notation setState 의 canonical source 동기화 (engi
|
||||
expect(globalState._local.form).toEqual({ title: '변경', body: '유지' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('[사례 40] 리사이즈 후 저장 시 편집기 본문이 저장소 B 와 반환값에서 함께 사라짐 (engine-v1.63.3)', () => {
|
||||
let dispatcher: ActionDispatcher;
|
||||
let globalState: Record<string, any>;
|
||||
let componentState: Record<string, any>;
|
||||
let setStateCalls: any[];
|
||||
|
||||
/** TemplateApp.setGlobalState 와 동일한 계약: 최상위 키 얕은 병합 + 동기 대입 */
|
||||
const globalStateUpdater = vi.fn((updates: any) => {
|
||||
globalState = { ...globalState, ...updates };
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
setStateCalls = [];
|
||||
componentState = {};
|
||||
globalState = { _local: {} };
|
||||
|
||||
dispatcher = new ActionDispatcher({ navigate: vi.fn() });
|
||||
dispatcher.setGlobalStateUpdater(globalStateUpdater);
|
||||
Logger.getInstance().setDebug(false);
|
||||
|
||||
(window as any).__templateApp = { getGlobalState: () => globalState };
|
||||
// 리사이즈 렌더가 이미 pending 을 비운 상태를 결정화한다
|
||||
// (관측 가능한 결과가 이 값 하나뿐이므로 타이밍 모사가 불필요)
|
||||
(window as any).__g7PendingLocalState = null;
|
||||
(window as any).__g7ForcedLocalFields = undefined;
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete (window as any).__templateApp;
|
||||
(window as any).__g7PendingLocalState = undefined;
|
||||
(window as any).__g7ForcedLocalFields = undefined;
|
||||
(window as any).__g7LayoutContextStack = [];
|
||||
});
|
||||
|
||||
const context = () => ({
|
||||
state: componentState,
|
||||
setState: vi.fn((updates: any) => {
|
||||
setStateCalls.push(updates);
|
||||
componentState = { ...componentState, ...updates };
|
||||
}),
|
||||
actionId: 'case-40',
|
||||
});
|
||||
|
||||
it('1. 결함 재현 핀: B 의 편집기 본문이 stale A 스냅샷으로 덮이지 않는다', async () => {
|
||||
// @scenario save_flow=create, resize_kind=same_breakpoint
|
||||
// @effects canonical_local_keeps_editor_content_after_resize, setstate_local_preserves_canonical_keys_when_pending_is_null
|
||||
// CKEditor 가 setLocal({ render:false, selfManaged:true }) 로 B 에만 기록한 본문
|
||||
globalState._local = { form: { title: '제목', content: '<p>본문</p>' }, isSaving: false };
|
||||
// 리사이즈 렌더로 memo 가 재계산되지 않아 context.state 는 본문 타이핑 이전 스냅샷
|
||||
componentState = { form: { title: '제목', content: '' }, isSaving: false };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { isSaving: true, errors: null } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local.form.content).toBe('<p>본문</p>');
|
||||
expect(globalState._local.isSaving).toBe(true);
|
||||
});
|
||||
|
||||
it('2. body 회귀 핀: 반환값에도 원문 본문이 실린다 (없으면 422 가 남는다)', async () => {
|
||||
// @scenario save_flow=edit, resize_kind=crossed_breakpoint
|
||||
// @effects request_body_content_matches_editor_getdata, edit_save_persists_typed_addition
|
||||
globalState._local = { form: { title: '제목', content: '<p>본문</p>' } };
|
||||
componentState = { form: { title: '제목', content: '' } };
|
||||
|
||||
const result = await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { isSaving: true } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(result.data.form.content).toBe('<p>본문</p>');
|
||||
expect(result.data.isSaving).toBe(true);
|
||||
expect(result.data.__target).toBe('local');
|
||||
});
|
||||
|
||||
it('3. 사례 22 핀: __g7PendingLocalState 는 A 계열 기반으로 유지된다', async () => {
|
||||
globalState._local = { form: { content: '<p>본문</p>' }, expandedRows: [] };
|
||||
componentState = { form: { content: '' }, expandedRows: [301] };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { isSaving: true } },
|
||||
context()
|
||||
);
|
||||
|
||||
// pending 은 A(context.state) 기반이어야 한다 — B 기반으로 바꾸면 사례 22 재발
|
||||
expect((window as any).__g7PendingLocalState.expandedRows).toEqual([301]);
|
||||
});
|
||||
|
||||
it('4. 중첩 경로 핀: 다국어 form.{name}.{locale} 에서 형제 로케일/필드가 보존된다', async () => {
|
||||
globalState._local = { form: { content: { ko: '<p>본문</p>', en: '<p>body</p>' }, title: { ko: '제목' } } };
|
||||
componentState = { form: { content: { ko: '', en: '' }, title: { ko: '제목' } } };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { 'form.title.ko': '새 제목' } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local.form.content).toEqual({ ko: '<p>본문</p>', en: '<p>body</p>' });
|
||||
expect(globalState._local.form.title.ko).toBe('새 제목');
|
||||
});
|
||||
|
||||
it('5. 사례 17 핀: merge replace 는 live B 를 base 로 쓰지 않는다', async () => {
|
||||
globalState._local = { form: { content: '<p>본문</p>' }, keep: 1 };
|
||||
componentState = { form: { content: '' } };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { merge: 'replace', only: 'this' } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local.keep).toBeUndefined();
|
||||
expect(globalState._local.only).toBe('this');
|
||||
});
|
||||
|
||||
it('6. 사례 29 핀: 모달 컨텍스트 스택이 있으면 종전 동작(전체 스냅샷)을 유지한다', async () => {
|
||||
(window as any).__g7LayoutContextStack = [{ state: {}, setState: vi.fn() }];
|
||||
globalState._local = { form: { content: '<p>페이지 본문</p>' } };
|
||||
componentState = { modalField: 'x' };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { modalField: 'y' } },
|
||||
context()
|
||||
);
|
||||
|
||||
// 모달 안에서는 live B 를 base 로 삼지 않는다 (페이지 _local 흡수 방지)
|
||||
expect(globalState._local.modalField).toBe('y');
|
||||
expect(globalState._local.form).toBeUndefined();
|
||||
});
|
||||
|
||||
it('7. 폴백 핀: __templateApp 이 없으면 종전 전체 스냅샷 경로를 탄다', async () => {
|
||||
delete (window as any).__templateApp;
|
||||
componentState = { form: { content: '' }, a: 1 };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { b: 2 } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local).toEqual({ form: { content: '' }, a: 1, b: 2 });
|
||||
});
|
||||
|
||||
it('8. A 전용 키 핀: loadingActions 가 반환값에 남는다', async () => {
|
||||
globalState._local = { form: { content: '<p>본문</p>' } };
|
||||
componentState = { form: { content: '' }, loadingActions: { save: true } };
|
||||
|
||||
const result = await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { isSaving: true } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(result.data.loadingActions).toEqual({ save: true });
|
||||
expect(result.data.form.content).toBe('<p>본문</p>');
|
||||
});
|
||||
|
||||
it('9. B 의 중첩 객체가 in-place 변이되지 않는다', async () => {
|
||||
const liveForm = { title: '제목', content: '<p>본문</p>' };
|
||||
globalState._local = { form: liveForm };
|
||||
componentState = { form: { title: '제목', content: '' } };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { 'form.title': '변경' } },
|
||||
context()
|
||||
);
|
||||
|
||||
// 원본 참조는 변이되지 않아야 한다
|
||||
expect(liveForm.title).toBe('제목');
|
||||
expect(globalState._local.form.title).toBe('변경');
|
||||
});
|
||||
|
||||
it('10. merge shallow 핀(F3): payload 밖 키를 live B 값으로 보존한다', async () => {
|
||||
// 모집단: admin_ecommerce_{order,product}_list 필터 (#421 회귀 핀 대상)
|
||||
globalState._local = { filters: { status: 'paid' }, search: '주문번호', page: 3 };
|
||||
componentState = { filters: { status: 'paid' } };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { merge: 'shallow', page: 1 } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local.page).toBe(1);
|
||||
expect(globalState._local.search).toBe('주문번호');
|
||||
expect(globalState._local.filters).toEqual({ status: 'paid' });
|
||||
});
|
||||
|
||||
it('11. A 전용 키 핀(F2): loadingActions 가 B 에도 보충된다 (setLocal 선례와 대칭)', async () => {
|
||||
globalState._local = { form: { content: '<p>본문</p>' } };
|
||||
componentState = { form: { content: '' }, loadingActions: { save: true }, apiError: null };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { isSaving: true } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local.loadingActions).toEqual({ save: true });
|
||||
expect(globalState._local.form.content).toBe('<p>본문</p>');
|
||||
});
|
||||
|
||||
it('12. 편집기 프리뷰 핀(F5): 격리 façade 에서도 canonical 경로를 타고 폴백이 발생하지 않는다', async () => {
|
||||
// PreviewCanvas 는 _local 을 항상 객체로 보장하므로 폴백이 발생하지 않는다
|
||||
const isolatedStore: Record<string, any> = { _local: { previewOnly: true } };
|
||||
(window as any).__templateApp = { getGlobalState: () => isolatedStore };
|
||||
componentState = { form: { content: '' } };
|
||||
|
||||
await dispatcher.executeAction(
|
||||
{ handler: 'setState' as const, params: { isSaving: true } },
|
||||
context()
|
||||
);
|
||||
|
||||
expect(globalState._local.previewOnly).toBe(true);
|
||||
expect(globalState._local.isSaving).toBe(true);
|
||||
// 격리 store 자체는 globalStateUpdater 를 통하지 않으므로 그대로다
|
||||
expect(isolatedStore._local).toEqual({ previewOnly: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* 상태 병합 헬퍼
|
||||
*
|
||||
* 이중 저장소(React `localDynamicState` = 저장소 A, `globalState._local` = 저장소 B)를
|
||||
* 동기화하는 두 쓰기 경로가 공유하는 병합 프리미티브를 담는다.
|
||||
*
|
||||
* 왜 `helpers/` 인가:
|
||||
* `addMissingLeafKeys` 는 `G7CoreGlobals.ts` 의 모듈 프라이빗 함수였다. 그런데
|
||||
* `G7CoreGlobals.ts` 가 `ActionDispatcher` 를 import 하므로 `ActionDispatcher` 에서
|
||||
* 역방향 값 import 를 하면 런타임 순환이 된다. `helpers/` 는 엔진 모듈을 import 하지
|
||||
* 않으므로 양쪽이 안전하게 공유할 수 있다.
|
||||
*
|
||||
* @since engine-v1.63.3
|
||||
* @packageDocumentation
|
||||
*/
|
||||
|
||||
/**
|
||||
* base 객체에 없는 leaf 키만 extra에서 추가합니다.
|
||||
*
|
||||
* deepMerge와 달리 base에 이미 존재하는 값(배열 포함)은 절대 덮어쓰지 않습니다.
|
||||
* extra에만 존재하는 키는 재귀적으로 추가됩니다.
|
||||
*
|
||||
* 용도:
|
||||
* - `setLocal`(G7CoreGlobals)에서 dynamicLocal(actionContext.state)의 setState 전용 키를
|
||||
* globalLocal에 안전하게 추가할 때. dynamicLocal의 stale 배열(init_actions 기본값)이
|
||||
* globalLocal의 정상 API 데이터를 덮어쓰는 것을 방지합니다.
|
||||
* - `handleSetState`(ActionDispatcher) COMPONENT path 에서 저장소 B 를 base 로 삼을 때
|
||||
* 저장소 A 전용 키(`loadingActions`, `apiError`, `*_result` 등)를 보충할 때.
|
||||
*
|
||||
* @param base 우선하는 기준 객체 (충돌 시 이 값이 이긴다)
|
||||
* @param extra base 에 없는 키만 가져올 보충 객체
|
||||
* @return base 를 얕게 복사한 뒤 누락 키를 채운 새 객체 (base/extra 모두 변이하지 않음)
|
||||
*
|
||||
* @since engine-v1.41.0 (G7CoreGlobals 내부 함수로 최초 도입)
|
||||
* @since engine-v1.63.3 helpers/StateMerge 로 이동해 ActionDispatcher 와 공유
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const base = { form: { category_ids: [381, 384], name: 'A' } };
|
||||
* const extra = { form: { category_ids: [], options: [] }, selectedProducts: [1] };
|
||||
* addMissingLeafKeys(base, extra);
|
||||
* // → { form: { category_ids: [381, 384], name: 'A', options: [] }, selectedProducts: [1] }
|
||||
* // base의 category_ids는 보존, extra의 selectedProducts와 options는 추가
|
||||
* ```
|
||||
*/
|
||||
export function addMissingLeafKeys(
|
||||
base: Record<string, any>,
|
||||
extra: Record<string, any>
|
||||
): Record<string, any> {
|
||||
const result = { ...base };
|
||||
for (const key of Object.keys(extra)) {
|
||||
if (!(key in result)) {
|
||||
// base에 없는 키: extra 값 그대로 추가
|
||||
result[key] = extra[key];
|
||||
} else if (
|
||||
result[key] !== null &&
|
||||
typeof result[key] === 'object' &&
|
||||
!Array.isArray(result[key]) &&
|
||||
extra[key] !== null &&
|
||||
typeof extra[key] === 'object' &&
|
||||
!Array.isArray(extra[key])
|
||||
) {
|
||||
// 양쪽 모두 plain object: 재귀적으로 처리
|
||||
result[key] = addMissingLeafKeys(result[key], extra[key]);
|
||||
}
|
||||
// base에 이미 존재하는 leaf 값(배열, 문자열, 숫자 등): 건너뜀 (base 값 보존)
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -90,6 +90,14 @@ export {
|
||||
type ActionDefinition,
|
||||
} from './ConditionEvaluator';
|
||||
|
||||
// ============================================
|
||||
// 상태 병합 헬퍼
|
||||
// ============================================
|
||||
|
||||
export {
|
||||
addMissingLeafKeys,
|
||||
} from './StateMerge';
|
||||
|
||||
// ============================================
|
||||
// 향후 추가 예정 헬퍼 모듈 예시
|
||||
// ============================================
|
||||
|
||||
Reference in new issue
Block a user