feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)
공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다. 브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도 남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데 자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기 하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발 대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다. 런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다. 자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그 실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML 에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다. 편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다. 두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의 custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에 의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다. 확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을 고치면 그 변경을 감지해 재게시까지 예약된다. FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접 넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로 나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린 스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과 분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠 화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를 함께 뒀다. 동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에 써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
1 parent
72f2e94c1a
commit
3945b6f1b3
1042 files changed
+107435
-947
No files matched your search
@@ -5,6 +5,55 @@
|
||||
>
|
||||
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
|
||||
|
||||
## [engine-v1.63.1] - 2026-08-27
|
||||
|
||||
### Fixed
|
||||
|
||||
#### 정적 게시 미스에서 운영자 추가 자산이 복구되지 않던 문제 (#123)
|
||||
|
||||
- `staticToLegacy()` 가 세 확장 타입을 모두 역변환한다 — 종전에는 `templates/{id}/assets/**` 만 처리했다. 모듈·플러그인의 `custom/**` 도 같은 형태(`{type}/{id}/assets/**`)로 게시되는데 그 규칙이 없어, 게시본이 GC(현재+직전 1개 보존)로 사라지면 되돌릴 주소를 만들지 못했다. blade 인라인 복구기(`partials/asset-url-recovery.blade.php`)도 동형으로 갱신했다 — 두 구현이 갈리면 코어 번들 로드 전 경로만 조용히 다르게 동작한다.
|
||||
- `ModuleAssetLoader.loadCustomAssets()` 가 정적 → 종전 API 폴백 계층을 갖는다. 형제 경로(`loadBundleCss`)는 이미 갖고 있었고 이 경로만 비어 있었다: 정적 URL 이 404 가 확정된 뒤에도 같은 URL 을 3회 재시도할 뿐이라 복구가 원리상 불가능했고, 화면은 정상 렌더되면서 운영자가 덧붙인 스타일만 조용히 빠졌다.
|
||||
- 자산 실패 배너의 [다시 시도]가 **복구 가능한 주소**를 다시 부른다. 종전에는 정적 미스로 실패한 경우에도 원본 정적 URL 을 넘겨, 버튼은 있는데 눌러도 구조적으로 항상 실패했다.
|
||||
|
||||
## [engine-v1.63.0] - 2026-08-26
|
||||
|
||||
### Added
|
||||
|
||||
#### 서버가 심은 템플릿 externals 의 로드 실패 표면화 (#123)
|
||||
|
||||
- `drainExternalAssetFailures()` 신설 — 템플릿 `externals`(아이콘 폰트 CSS·웹폰트·부팅 스크립트)는 서버가 HTML 에 직접 심으므로 엔진 번들보다 먼저 평가된다. 실패해도 자바스크립트에는 아무 신호가 오지 않아, engine-v1.62.0 이 세운 실패 표면화 계층이 **이 경로만 통째로 비어 있었다**: 아이콘 58개가 0×0 으로 사라진 화면이 배너도 로그도 없이 남았고(아이콘만으로 조작하는 버튼이 있는 화면에서는 곧 조작 불능), 자체 서버 로그에도 흔적이 없어 운영자가 원인을 특정할 수 없었다. 이제 각 태그의 `onerror` 가 부트스트랩 대기열에 쌓이고, 엔진이 뜨면 그 대기열을 배너로 흘려보낸 뒤 이후 실패용 sink 를 건다. 배너의 [다시 시도]는 해당 태그를 캐시 무효화 쿼리와 함께 다시 심어 복구되면 배너를 해제한다.
|
||||
- 힌트(`preload`/`preconnect`/`dns-prefetch`)는 대상에서 제외한다 — 실패해도 화면 기능이 사라지지 않으므로, 여기까지 알리면 안내가 잡음이 되어 정작 조작 불능을 만드는 실패가 묻힌다.
|
||||
|
||||
#### 커스텀 자산 관리가 모듈·플러그인까지 확장 (#123)
|
||||
|
||||
- 편집기 [커스텀 자산] 모달이 **대상 선택기**를 갖는다 — 편집 중인 템플릿과 활성 모듈·플러그인을 오간다. 같은 기능이 확장 타입에 따라 화면에서 되고 안 되면 운영자는 그 이유를 알 수 없고, 모듈·플러그인 `custom/` 은 그동안 FTP 말고 경로가 없었다.
|
||||
- 관리 API 가 확장 공통 엔드포인트(`/api/admin/extensions/{type}/{id}/custom-assets`)로 재편됐다. 타입별로 나누면 같은 검증·문서·테스트가 세 벌로 갈리고, 그중 하나만 약해지면 그 경로가 조용한 우회로가 된다.
|
||||
- 대상을 바꾸면 이전 확장의 선택·초안을 버린다. 남겨 두면 A 확장에서 열어 둔 본문을 B 확장에 저장하게 되고, 경로가 유효하면 서버는 정상 200 으로 받아들인다.
|
||||
|
||||
### Changed
|
||||
|
||||
#### 레이아웃 편집기 번들 로드의 재시도 계층 + 실패 문구 정리 (#123)
|
||||
|
||||
- `loadLayoutEditorBundle()` 이 `loadScriptWithRetry` 를 쓴다 — 이 경로만 재시도 계층이 없어(원시 `<script>` + `onerror` 1회), 일시적 네트워크 유실 한 번에 편집기가 통째로 열리지 않았다. 다른 모든 자산 경로(레이아웃 스크립트·확장 병합 번들·CSS)가 이미 이 로더를 쓰고 있었다.
|
||||
- 실패 화면 문구에서 번들 경로를 걷어냈다. 종전에는 `편집기 번들 로드 실패: /build/core/layout-editor.min.js` 처럼 내부 배치 구조가 그대로 노출됐는데, 사용자가 고칠 수 있는 정보가 아니다. 경로는 콘솔 로그로만 남기고, 화면에는 다음 행동(네트워크 확인 · 새로고침)을 안내한다.
|
||||
|
||||
## [engine-v1.62.0] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
#### 구동 자산 자체 제공 seam + 로드 실패 표면화 (#123)
|
||||
|
||||
- `networkResilience.loadStylesheetWithRetry()` 신설 — `loadScriptWithRetry` 와 동형(3시도·지수 백오프·재시도 전 element 제거·**최종 실패 시 reject**). CSS 경로만 이 계층이 없어 실패가 통째로 무음이었다: `onerror` 를 아예 걸지 않거나 `resolve()` 로 삼켜, 스타일이 붙지 않은 화면(아이콘 소실·본문 서식 붕괴)이 오류 없이 남았다.
|
||||
- `G7Core.asset.{template,templateDir,module,plugin,convertToCurrentMode,loadScript,loadStylesheet}` 신설 — 확장 IIFE 번들은 코어의 `assetUrl.ts` 를 import 할 수 없어 URL 을 문자열로 조립하는 수밖에 없었고, 그 조립은 자산 URL 이중 모드(확장자를 정적 location 이 가로채는 서버)에서 그 자산만 404 로 만든다.
|
||||
- `templateAssetDir()` — AMD 로더·워커처럼 **디렉토리 접두에 파일명을 이어 붙이는** 소비자용. 정적 게시본이 있으면 그 실경로를 우선하고(모드와 무관하게 하위 파일이 해석된다), 없으면 확장자 형태 API 경로를 돌려준다. 확장자를 가로채는 서버에서는 후자가 404 이므로 소비자가 폴백을 갖춰야 한다.
|
||||
- `G7Core.assets.{notifyFailure,clearFailure,clearAll,getFailures,retryAll}` + `assets/AssetFailureNotice.ts` — 자산 로드 실패를 사용자에게 알리고 재시도를 제공한다. **호스트 컴포넌트에 의존하지 않고 DOM 에 직접 주입**한다: Toast·Modal 은 베이스 레이아웃이 마운트한 호스트가 있어야 뜨는데, 독립 레이아웃(`extends` 없음 — 예: `admin_login.json`)에는 그 호스트가 없고 자산 실패는 바로 그런 화면에서도 알려야 한다. 테마 색은 일괄 문자열(cssText)이 아니라 개별 프로퍼티로도 못 박는다 — 파서가 모르는 선언 하나로 전체가 버려지는 환경에서 배너가 배경 없이 뜨면 안내로서 기능하지 못한다.
|
||||
- `ModuleAssetLoader.loadCustomAssets()` + `parseCustomAssetsFromConfig()` — 운영자가 확장 `custom/` 에 덧붙인 자산을 확장 병합 번들 **뒤**에 로드한다. CSS 는 나중에 온 규칙이 이기므로 앞에 붙이면 운영자의 재정의가 확장 스타일에 밀린다.
|
||||
|
||||
### Changed
|
||||
|
||||
- `TemplateApp.loadLayoutScripts` — ① same-origin 경로에 `convertToCurrentMode` 적용(종전 미적용: 확장자를 가로채는 서버에서 자체 제공 자산이 404) ② `loadScriptWithRetry` 로 교체 ③ 최종 실패를 `failedLayoutScripts` 에 기록하고 안내 배너로 표면화. "한 스크립트의 실패가 나머지 로드를 막지 않는다" 는 기존 계약은 유지한다.
|
||||
- `ModuleAssetLoader` 의 `loadCSS`/`loadBundleCss` 가 재시도 계층을 갖는다. 최종 실패는 `failedCssAssets` 와 안내 배너에 남기되 **throw 하지 않는다** — 스타일이 없어도 화면은 동작하므로 한 확장의 CSS 실패로 나머지 확장 로드를 중단시키지 않는다. 병합 CSS 의 정적 게시 미스 폴백은 종전 "같은 `<link>` 의 href 1회 교체"(재시도 예산 없음)에서 레거시 URL 에 대한 정규 재시도로 바뀌었다.
|
||||
|
||||
## [engine-v1.61.0] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
@@ -55,6 +55,22 @@ import {
|
||||
} from '../hooks/useControllableState';
|
||||
import { triggerModalParentUpdate } from './ParentContextProvider';
|
||||
import { IdentityGuardInterceptor, IDENTITY_REDIRECT_STASH_KEY } from '../identity/IdentityGuardInterceptor';
|
||||
import { loadScriptWithRetry, loadStylesheetWithRetry } from './networkResilience';
|
||||
import {
|
||||
templateAsset,
|
||||
templateAssetDir,
|
||||
moduleAsset,
|
||||
pluginAsset,
|
||||
convertToCurrentMode,
|
||||
} from '../support/assetUrl';
|
||||
import {
|
||||
notifyAssetFailure,
|
||||
drainExternalAssetFailures,
|
||||
clearAssetFailure,
|
||||
clearAllAssetFailures,
|
||||
getAssetFailures,
|
||||
retryAssetFailures,
|
||||
} from '../assets/AssetFailureNotice';
|
||||
|
||||
const logger = createLogger('G7CoreGlobals');
|
||||
|
||||
@@ -857,6 +873,86 @@ function initLayoutEditorStub(G7Core: any): void {
|
||||
logger.log('전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* 자산 URL·자산 실패 안내 API 초기화
|
||||
*
|
||||
* 확장(모듈·플러그인·템플릿)의 IIFE 번들은 코어의 `assetUrl.ts` 를 import 할 수 없다
|
||||
* — 별도 번들이라 모듈 그래프가 이어지지 않는다. 그래서 확장이 자기 동봉 자산의 URL 을
|
||||
* 만들려면 `/api/plugins/assets/...` 를 **문자열로 조립**하는 수밖에 없었는데, 그러면
|
||||
* 자산 URL 이중 모드(확장자 없는 서버)에서 그 자산만 404 가 된다.
|
||||
*
|
||||
* `G7Core.asset.*` 이 그 seam 이다 — 서버측 `AssetUrl` 과 같은 규약으로 URL 을 만든다.
|
||||
* `G7Core.assets.*` 는 그 자산을 끝내 못 불러왔을 때의 안내·재시도 표면이다.
|
||||
*
|
||||
* @param G7Core 전역 객체
|
||||
* @return void
|
||||
* @since engine-v1.62.0
|
||||
*/
|
||||
function initAssetUrlAPI(G7Core: any): void {
|
||||
/**
|
||||
* 확장 자산 URL 생성기.
|
||||
*
|
||||
* 템플릿은 서버가 `dist/` 를 자동 부가하므로 `path` 에 `dist/` 를 포함하지 않는다
|
||||
* (모듈·플러그인은 확장 루트 기준이라 `dist/` 를 직접 포함 — 서버측과 동일한 비대칭).
|
||||
*/
|
||||
G7Core.asset = {
|
||||
/** 템플릿 자산 URL (`dist/` 이하 경로) */
|
||||
template: (identifier: string, path: string, version?: number | string | null): string =>
|
||||
templateAsset(identifier, path, version),
|
||||
/**
|
||||
* 템플릿 자산 **디렉토리** URL — AMD 로더·워커처럼 디렉토리 접두에 파일명을
|
||||
* 이어 붙이는 소비자용. 확장자 없는 모드에서 404 일 수 있으므로 폴백이 필요하다.
|
||||
*/
|
||||
templateDir: (identifier: string, path: string): string => templateAssetDir(identifier, path),
|
||||
/** 모듈 자산 URL (모듈 루트 기준 경로) */
|
||||
module: (identifier: string, path: string, version?: number | string | null): string =>
|
||||
moduleAsset(identifier, path, version),
|
||||
/** 플러그인 자산 URL (플러그인 루트 기준 경로) */
|
||||
plugin: (identifier: string, path: string, version?: number | string | null): string =>
|
||||
pluginAsset(identifier, path, version),
|
||||
/** 서버가 확장자 형태로 굳혀 내려준 URL 을 현재 모드로 보정 */
|
||||
convertToCurrentMode: (url: string): string => convertToCurrentMode(url),
|
||||
/**
|
||||
* 재시도 계층을 갖춘 스크립트 로더.
|
||||
*
|
||||
* 확장이 자기 자산을 런타임에 직접 로드할 때 쓴다. 확장 번들이 코어 모듈을
|
||||
* import 할 수 없어 각자 `document.createElement('script')` 를 쓰면, 코어가
|
||||
* 갖춘 재시도·실패 표면화 계층이 그 경로에만 없게 된다.
|
||||
*/
|
||||
loadScript: (
|
||||
url: string,
|
||||
attrs?: Record<string, string>,
|
||||
options?: Record<string, unknown>
|
||||
): Promise<void> => loadScriptWithRetry(url, attrs, options as any),
|
||||
/** 재시도 계층을 갖춘 스타일시트 로더 */
|
||||
loadStylesheet: (
|
||||
url: string,
|
||||
attrs?: Record<string, string>,
|
||||
options?: Record<string, unknown>
|
||||
): Promise<void> => loadStylesheetWithRetry(url, attrs, options as any),
|
||||
};
|
||||
|
||||
/**
|
||||
* 자산 로드 실패 안내.
|
||||
*
|
||||
* 실패를 화면에 표면화하지 않으면 사용자에게는 "빈 자리" 로만 나타나고, 자체 서버
|
||||
* 로그에도 흔적이 남지 않아 운영자가 원인을 특정할 수 없다.
|
||||
*/
|
||||
G7Core.assets = {
|
||||
notifyFailure: notifyAssetFailure,
|
||||
clearFailure: clearAssetFailure,
|
||||
clearAll: clearAllAssetFailures,
|
||||
getFailures: getAssetFailures,
|
||||
retryAll: retryAssetFailures,
|
||||
};
|
||||
|
||||
// 서버가 심은 템플릿 externals 는 엔진보다 먼저 평가되므로 실패가 대기열에 쌓여 있다.
|
||||
// 여기서 비우지 않으면 아이콘 폰트·글꼴 실패가 화면에 영영 드러나지 않는다.
|
||||
drainExternalAssetFailures();
|
||||
|
||||
logger.log('전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* 번역 관련 API 초기화
|
||||
*/
|
||||
@@ -3148,6 +3244,7 @@ export function initializeG7CoreGlobals(deps: G7CoreDependencies): void {
|
||||
// 레이아웃 편집기 확장점 예약 접수함(편집기 lazy 로드 전 템플릿 등록을 큐에 보존)
|
||||
initLayoutEditorStub(G7Core);
|
||||
initCoreAPIs(G7Core, deps);
|
||||
initAssetUrlAPI(G7Core);
|
||||
initTranslationAPI(G7Core, deps);
|
||||
initHelperAPIs(G7Core, deps);
|
||||
initDispatchAPI(G7Core);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* loadStylesheetWithRetry — CSS 로드의 재시도 계층
|
||||
*
|
||||
* CSS 경로만 이 계층이 없어 실패가 통째로 무음이었다. 아이콘만으로 조작하는 버튼이
|
||||
* 있는 화면에서는 스타일 소실이 곧 조작 불능이다.
|
||||
*
|
||||
* @scenario asset_class=vendored, outcome=failed
|
||||
* @scenario asset_class=translation, outcome=failed
|
||||
* @effects stylesheet_failure_retries_then_surfaces
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { loadStylesheetWithRetry } from '../networkResilience';
|
||||
|
||||
describe('loadStylesheetWithRetry', () => {
|
||||
let appendSpy: ReturnType<typeof vi.spyOn>;
|
||||
let created: HTMLLinkElement[];
|
||||
|
||||
/**
|
||||
* head.appendChild 를 가로채 시도별 결과를 발화시킵니다.
|
||||
*
|
||||
* @param outcomes 시도 순서대로의 결과
|
||||
* @return void
|
||||
*/
|
||||
function stub(outcomes: Array<'load' | 'error'>): void {
|
||||
appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName !== 'LINK') {
|
||||
return node;
|
||||
}
|
||||
|
||||
created.push(node);
|
||||
const outcome = outcomes[created.length - 1] ?? 'load';
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (outcome === 'error') {
|
||||
node.onerror?.(new Event('error'));
|
||||
} else {
|
||||
node.onload?.(new Event('load'));
|
||||
}
|
||||
});
|
||||
|
||||
return node;
|
||||
}) as any);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
created = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
document.querySelectorAll('link[id^="test-css"]').forEach(el => el.remove());
|
||||
});
|
||||
|
||||
it('첫 시도에 성공하면 재시도하지 않는다', async () => {
|
||||
stub(['load']);
|
||||
|
||||
await expect(loadStylesheetWithRetry('/a.css')).resolves.toBeUndefined();
|
||||
expect(created).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('rel 과 href 를 설정하고 전달한 속성을 붙인다', async () => {
|
||||
stub(['load']);
|
||||
|
||||
await loadStylesheetWithRetry('/a.css', { id: 'test-css-1', media: 'screen' });
|
||||
|
||||
expect(created[0].rel).toBe('stylesheet');
|
||||
expect(created[0].getAttribute('href')).toBe('/a.css');
|
||||
expect(created[0].id).toBe('test-css-1');
|
||||
expect(created[0].getAttribute('media')).toBe('screen');
|
||||
});
|
||||
|
||||
it('일시 실패 후 성공하면 최종 resolve 한다', async () => {
|
||||
stub(['error', 'load']);
|
||||
|
||||
await expect(
|
||||
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1, maxDelayMs: 2 })
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(created).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('모든 시도가 실패하면 reject 한다 (실패를 resolve 로 은폐하지 않는다)', async () => {
|
||||
stub(['error', 'error', 'error']);
|
||||
|
||||
await expect(
|
||||
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1, maxDelayMs: 2 })
|
||||
).rejects.toThrow(/Failed to load stylesheet/);
|
||||
|
||||
expect(created).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('retries 옵션으로 시도 횟수를 조정할 수 있다', async () => {
|
||||
stub(['error']);
|
||||
|
||||
await expect(
|
||||
loadStylesheetWithRetry('/a.css', {}, { retries: 0 })
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(created).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('재시도 전 실패한 element 를 문서에서 제거한다 (누적 방지)', async () => {
|
||||
// 실제 DOM 에 붙여 제거 여부를 관측한다
|
||||
appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName !== 'LINK') return node;
|
||||
|
||||
created.push(node);
|
||||
document.body.appendChild(node);
|
||||
const isFirst = created.length === 1;
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (isFirst) {
|
||||
node.onerror?.(new Event('error'));
|
||||
} else {
|
||||
node.onload?.(new Event('load'));
|
||||
}
|
||||
});
|
||||
|
||||
return node;
|
||||
}) as any);
|
||||
|
||||
await loadStylesheetWithRetry('/a.css', { id: 'test-css-2' }, { baseDelayMs: 1 });
|
||||
|
||||
// 실패분은 제거되고 성공분만 남는다
|
||||
expect(document.querySelectorAll('#test-css-2')).toHaveLength(1);
|
||||
expect(created[0].isConnected).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -385,3 +385,67 @@ describe('[사례 3] 확장 부재 시 5초 백지 + 내부 식별자 raw 노출
|
||||
expect(normalError.unknownHandler).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 사례 4: CSS 로더에 `onerror` 가 없으면 스타일 소실이 완전히 무음이다
|
||||
*
|
||||
* `<script>` 경로에는 재시도·실패 표면화 계층이 이미 있었는데 CSS 경로만 그 계층이
|
||||
* 없었다. 같은 저장소 안에서 형제 경로의 계층이 어긋나 있으면, 그 차이는 사고가 나기
|
||||
* 전까지 드러나지 않는다.
|
||||
*/
|
||||
describe('[사례 4] CSS 로드 실패의 무음 처리', () => {
|
||||
/**
|
||||
* head.appendChild 를 가로채 시도별 결과를 발화시킵니다.
|
||||
*
|
||||
* @param decide 시도 회차를 받아 결과를 돌려주는 판정 함수
|
||||
* @return 생성된 link element 목록
|
||||
*/
|
||||
function stubStylesheet(decide: (attempt: number) => 'load' | 'error'): HTMLLinkElement[] {
|
||||
const created: HTMLLinkElement[] = [];
|
||||
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName !== 'LINK') return node;
|
||||
|
||||
created.push(node);
|
||||
const outcome = decide(created.length);
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (outcome === 'error') {
|
||||
node.onerror?.(new Event('error'));
|
||||
} else {
|
||||
node.onload?.(new Event('load'));
|
||||
}
|
||||
});
|
||||
|
||||
return node;
|
||||
}) as any);
|
||||
|
||||
return created;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('CSS 실패는 재시도된다 (일시 실패가 스타일 소실로 굳지 않는다)', async () => {
|
||||
const { loadStylesheetWithRetry } = await import('../networkResilience');
|
||||
const created = stubStylesheet(attempt => (attempt === 1 ? 'error' : 'load'));
|
||||
|
||||
await expect(
|
||||
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1 })
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(created).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('CSS 최종 실패는 reject 된다 (resolve 로 위장하지 않는다)', async () => {
|
||||
const { loadStylesheetWithRetry } = await import('../networkResilience');
|
||||
stubStylesheet(() => 'error');
|
||||
|
||||
// 성공으로 위장하면 호출부의 try/catch 가 무력화되고, 스타일이 없다는 사실이
|
||||
// 어디에도 남지 않는다 — 사례 2 와 동형의 결함이다.
|
||||
await expect(
|
||||
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1 })
|
||||
).rejects.toThrow(/Failed to load stylesheet/);
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,7 @@ import { LayoutAttachmentManager } from './components/property-controls/LayoutAt
|
||||
import { CustomTranslationManager } from './components/property-controls/CustomTranslationManager';
|
||||
import { PageSettingsModal } from './components/page-settings/PageSettingsModal';
|
||||
import { VersionHistoryModal } from './components/VersionHistoryModal';
|
||||
import { CustomAssetsModal } from './components/CustomAssetsModal';
|
||||
import type { VersionTarget } from './hooks/useLayoutVersions';
|
||||
import { ShortcutHelpModal } from './components/ShortcutHelpModal';
|
||||
import { collectReferencedCustomKeys } from './utils/customTranslations';
|
||||
@@ -521,6 +522,69 @@ function LayoutEditorChromeBody({
|
||||
[templateIdentifier, activeDocument.isDirty, t],
|
||||
);
|
||||
|
||||
// 커스텀 자산 관리 모달 — 운영자 CSS·JS·폰트·이미지를 화면에서 직접 넣고 고친다.
|
||||
// 권한은 서버가 판정하므로 여기서 버튼을 감추지 않는다(모달이 403 을 안내로 바꾼다).
|
||||
const handleManageCustomAssets = useCallback(() => {
|
||||
const id = modal.open({
|
||||
ariaLabel: t('layout_editor.custom_assets.title'),
|
||||
width: 860,
|
||||
maxHeightRatio: 0.86,
|
||||
content: React.createElement(CustomAssetsModal, {
|
||||
templateIdentifier,
|
||||
t,
|
||||
onClose: () => modal.close(id),
|
||||
}),
|
||||
});
|
||||
}, [modal, templateIdentifier, t]);
|
||||
|
||||
// 사용자 추가 에셋(`custom/`) 적용 토글 — 탈출구(D33).
|
||||
//
|
||||
// 운영자가 넣은 CSS 한 줄이 화면을 조작 불능으로 만들면, 그것을 고칠 편집기에도
|
||||
// 그 CSS 가 실려 있어 스스로 갇힌다. `?custom=off` 로 다시 열면 서버가 목록을
|
||||
// 비워 자산이 페이지에 **도달하지 않는다** — 이미 깨진 화면에서 자바스크립트가
|
||||
// 돌기를 기대하지 않아도 된다.
|
||||
//
|
||||
// DOM 에서 `<link>` 를 떼는 방식을 쓰지 않는 이유: 이미 실행된 custom JS 는 되돌릴
|
||||
// 수 없어 절반만 꺼진다. 나가기·템플릿 전환과 같은 dirty 가드를 태운다.
|
||||
//
|
||||
// 현재 상태는 **서버가 실제로 한 일**(`G7Config.customAssetsDisabled`)로 판정한다.
|
||||
// URL 로 판정하면 안 된다 — SPA 부팅이 주소를 다시 쓰면서 `?custom=off` 를 지우므로,
|
||||
// 자산은 꺼졌는데 버튼은 "켜져 있음" 으로 표시되고 되돌릴 방법이 화면에서 사라진다.
|
||||
// URL 검사는 서버가 그 값을 심지 않는 구형 렌더용 폴백으로만 남긴다.
|
||||
const customAssetsDisabled =
|
||||
typeof window !== 'undefined' &&
|
||||
(!!(window as any).G7Config?.customAssetsDisabled ||
|
||||
new URLSearchParams(window.location.search).get('custom') === 'off');
|
||||
|
||||
const handleToggleCustomAssets = useCallback(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (activeDocument.isDirty) {
|
||||
const proceed = window.confirm(t('layout_editor.chrome.dirty_guard.message'));
|
||||
if (!proceed) return;
|
||||
}
|
||||
|
||||
const url = new URL(window.location.href);
|
||||
|
||||
if (customAssetsDisabled) {
|
||||
url.searchParams.delete('custom');
|
||||
|
||||
// 주소가 이미 파라미터를 잃은 상태라면 같은 주소로의 이동은 아무 일도 하지 않는다.
|
||||
// 그 경우 다시 요청하는 것 자체가 되돌리는 동작이다.
|
||||
if (url.toString() === window.location.href) {
|
||||
window.location.reload();
|
||||
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
url.searchParams.set('custom', 'off');
|
||||
}
|
||||
|
||||
(window as any).G7Core?.dispatch?.({
|
||||
handler: 'openWindow',
|
||||
params: { path: `${url.pathname}${url.search}${url.hash}`, target: '_self' },
|
||||
});
|
||||
}, [activeDocument.isDirty, customAssetsDisabled, t]);
|
||||
|
||||
// 코드편집 — 기존 텍스트 레이아웃 편집기 화면을 새 창으로 연다(위지윅 편집은
|
||||
// 유지한 채 코드 편집을 별도 창에서). 본체는 별도 라우트로 이미 존재
|
||||
// (admin_template_layout_edit). 위지윅에서 선택 중이던 라우트 path 를 `?route=` 쿼리로
|
||||
@@ -890,6 +954,9 @@ function LayoutEditorChromeBody({
|
||||
templateVersion={templateVersion}
|
||||
templateList={templateList}
|
||||
onSwitchTemplate={handleSwitchTemplate}
|
||||
onToggleCustomAssets={handleToggleCustomAssets}
|
||||
customAssetsDisabled={customAssetsDisabled}
|
||||
onManageCustomAssets={handleManageCustomAssets}
|
||||
/>
|
||||
<SaveFeedbackBanner
|
||||
result={saveResult}
|
||||
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* CustomAssetsModal + 툴바 커스텀 자산 버튼 테스트 (#123, D32·D33)
|
||||
*
|
||||
* 잠그는 계약:
|
||||
* - 목록 403 은 오류 문구가 아니라 **안내**로 바뀐다 (권한이 부족하다는 사실과 무엇을
|
||||
* 요청해야 하는지가 화면에 나와야 한다 — "HTTP 403" 은 그 둘 다 말해 주지 않는다)
|
||||
* - 저장은 PUT `custom-assets/content` 로 나가고 성공 후 목록을 다시 읽는다
|
||||
* - 편집 불가(바이너리) 파일은 본문 편집기를 열지 않고 교체 안내를 보여 준다
|
||||
* - 툴바 토글은 `?custom=off` 상태를 문구·`aria-pressed` 로 드러낸다
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { CustomAssetsModal } from '../../components/CustomAssetsModal';
|
||||
import { EditorToolbar } from '../../components/EditorToolbar';
|
||||
import { LayoutEditorProvider } from '../../LayoutEditorContext';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
|
||||
/** 키를 그대로 돌려주는 t — 문구가 아니라 어떤 키가 쓰였는지를 단언한다 */
|
||||
const t = (key: string): string => key;
|
||||
|
||||
function wrapToolbar(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>
|
||||
);
|
||||
}
|
||||
|
||||
function jsonResponse(status: number, body: unknown): Response {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
const listBody = {
|
||||
data: {
|
||||
files: [
|
||||
{
|
||||
path: '10-overrides.css',
|
||||
name: '10-overrides.css',
|
||||
extension: 'css',
|
||||
size: 42,
|
||||
modified_at: '2026-08-26T00:00:00+00:00',
|
||||
editable: true,
|
||||
loaded: true,
|
||||
},
|
||||
{
|
||||
path: 'fonts/brand.woff2',
|
||||
name: 'brand.woff2',
|
||||
extension: 'woff2',
|
||||
size: 1024,
|
||||
modified_at: '2026-08-26T00:00:00+00:00',
|
||||
editable: false,
|
||||
loaded: false,
|
||||
},
|
||||
],
|
||||
editable_extensions: ['css', 'js', 'mjs', 'json'],
|
||||
uploadable_extensions: ['css', 'js', 'png', 'woff2'],
|
||||
max_text_bytes: 524288,
|
||||
max_upload_bytes: 5242880,
|
||||
},
|
||||
};
|
||||
|
||||
describe('CustomAssetsModal', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
// 대상 목록은 서버가 심은 활성 확장 메타에서 만들어진다.
|
||||
(window as any).G7Config = {
|
||||
activeModules: [{ identifier: 'sirsoft-page', display_name: { ko: '페이지' } }],
|
||||
activePlugins: [{ identifier: 'sirsoft-gdpr', display_name: 'GDPR' }],
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).G7Config;
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** @effects custom_asset_manager_surfaces_permission_denial_as_guidance */
|
||||
it('403 은 오류 문구가 아니라 안내로 바뀐다', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(403, { message: 'This action is unauthorized.' }));
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-custom-assets-forbidden')).toBeTruthy();
|
||||
});
|
||||
|
||||
// 원시 상태 코드가 아니라 안내 키가 화면에 있어야 한다
|
||||
expect(screen.getByTestId('g7le-custom-assets-forbidden').textContent).toBe(
|
||||
'layout_editor.custom_assets.forbidden',
|
||||
);
|
||||
expect(screen.queryByTestId('g7le-custom-assets-error')).toBeNull();
|
||||
});
|
||||
|
||||
it('목록을 읽어 파일 행을 그린다', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-custom-asset-row-10-overrides.css')).toBeTruthy();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('g7le-custom-asset-row-fonts/brand.woff2')).toBeTruthy();
|
||||
expect(
|
||||
screen.getByTestId('g7le-custom-asset-row-10-overrides.css').getAttribute('data-loaded'),
|
||||
).toBe('true');
|
||||
});
|
||||
|
||||
/** @effects custom_asset_binary_file_offers_replace_not_text_edit */
|
||||
it('편집 불가 파일은 본문 편집기를 열지 않고 교체를 안내한다', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-custom-asset-row-fonts/brand.woff2')).toBeTruthy();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-custom-asset-row-fonts/brand.woff2'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('g7le-custom-assets-content')).toBeNull();
|
||||
});
|
||||
|
||||
// 본문을 읽으러 가지 않는다 — 바이너리를 텍스트로 열면 저장 시 손상된다
|
||||
const readCalls = fetchMock.mock.calls.filter(([url]) => String(url).includes('/content'));
|
||||
expect(readCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
/** @effects custom_asset_editor_save_invalidates_published_copy */
|
||||
it('저장은 PUT content 로 나가고 성공 후 목록을 다시 읽는다', async () => {
|
||||
fetchMock.mockImplementation((url: string, init?: RequestInit) => {
|
||||
if (init?.method === 'PUT') {
|
||||
return Promise.resolve(jsonResponse(200, { data: { path: 'new.css', size: 5 } }));
|
||||
}
|
||||
|
||||
return Promise.resolve(jsonResponse(200, listBody));
|
||||
});
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-custom-assets-path')).toBeTruthy();
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByTestId('g7le-custom-assets-path'), {
|
||||
target: { value: 'new.css' },
|
||||
});
|
||||
fireEvent.change(screen.getByTestId('g7le-custom-assets-content'), {
|
||||
target: { value: 'body{}' },
|
||||
});
|
||||
fireEvent.click(screen.getByTestId('g7le-custom-assets-save'));
|
||||
|
||||
await waitFor(() => {
|
||||
const put = fetchMock.mock.calls.find(([, init]) => (init as RequestInit)?.method === 'PUT');
|
||||
expect(put).toBeTruthy();
|
||||
expect(String(put?.[0])).toContain('/api/admin/extensions/template/sirsoft-basic/custom-assets/content');
|
||||
expect(JSON.parse(String((put?.[1] as RequestInit).body))).toEqual({
|
||||
path: 'new.css',
|
||||
content: 'body{}',
|
||||
});
|
||||
});
|
||||
|
||||
// 저장 후 목록 재조회 — 새 파일이 목록에 나타나야 한다
|
||||
await waitFor(() => {
|
||||
const listCalls = fetchMock.mock.calls.filter(
|
||||
([url, init]) => !(init as RequestInit)?.method && String(url).endsWith('/custom-assets'),
|
||||
);
|
||||
expect(listCalls.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 대상은 템플릿뿐 아니라 활성 모듈·플러그인도 고를 수 있어야 한다.
|
||||
*
|
||||
* 같은 기능이 확장 타입에 따라 화면에서 되고 안 되면 운영자는 그 이유를 알 수 없다.
|
||||
*
|
||||
* @effects custom_asset_manage_all_extension_types_parity
|
||||
*/
|
||||
it('대상 선택기에 활성 모듈·플러그인이 함께 오른다', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
const select = (await screen.findByTestId('g7le-custom-assets-target')) as HTMLSelectElement;
|
||||
const values = Array.from(select.options).map((o) => o.value);
|
||||
|
||||
expect(values).toEqual([
|
||||
'template:sirsoft-basic',
|
||||
'module:sirsoft-page',
|
||||
'plugin:sirsoft-gdpr',
|
||||
]);
|
||||
});
|
||||
|
||||
/** @effects custom_asset_manage_all_extension_types_parity */
|
||||
it('대상을 바꾸면 그 확장의 경로로 다시 읽는다', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
const select = (await screen.findByTestId('g7le-custom-assets-target')) as HTMLSelectElement;
|
||||
fireEvent.change(select, { target: { value: 'module:sirsoft-page' } });
|
||||
|
||||
await waitFor(() => {
|
||||
const called = fetchMock.mock.calls.map(([url]) => String(url));
|
||||
expect(
|
||||
called.some((u) => u.includes('/api/admin/extensions/module/sirsoft-page/custom-assets')),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 대상 전환은 이전 확장의 선택·초안을 버려야 한다.
|
||||
*
|
||||
* 남겨 두면 A 확장에서 열어 둔 본문을 B 확장에 저장하게 되고, 경로가 유효하면 서버는
|
||||
* 정상 200 으로 받아들인다 — 오류가 남지 않는 종류의 사고다.
|
||||
*
|
||||
* @effects custom_asset_manage_all_extension_types_parity
|
||||
*/
|
||||
it('대상을 바꾸면 선택과 초안을 버린다', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
|
||||
|
||||
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('g7le-custom-asset-row-10-overrides.css')).toBeTruthy();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-custom-asset-row-10-overrides.css'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect((screen.getByTestId('g7le-custom-assets-path') as HTMLInputElement).readOnly).toBe(true);
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByTestId('g7le-custom-assets-target'), {
|
||||
target: { value: 'plugin:sirsoft-gdpr' },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const path = screen.getByTestId('g7le-custom-assets-path') as HTMLInputElement;
|
||||
expect(path.readOnly).toBe(false);
|
||||
expect(path.value).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditorToolbar — 커스텀 자산 (D32·D33)', () => {
|
||||
it('관리 버튼은 핸들러 미제공 시 disabled', () => {
|
||||
render(wrapToolbar(<EditorToolbar />));
|
||||
|
||||
expect((screen.getByTestId('g7le-toolbar-custom-assets') as HTMLButtonElement).disabled).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('관리 버튼 클릭이 핸들러를 호출한다', () => {
|
||||
const onManage = vi.fn();
|
||||
render(wrapToolbar(<EditorToolbar onManageCustomAssets={onManage} />));
|
||||
|
||||
fireEvent.click(screen.getByTestId('g7le-toolbar-custom-assets'));
|
||||
|
||||
expect(onManage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
/**
|
||||
* 상태 판정의 출처는 서버다.
|
||||
*
|
||||
* SPA 부팅이 주소를 다시 쓰면서 `?custom=off` 를 지우므로, URL 로 판정하면 자산은
|
||||
* 꺼졌는데 버튼은 "켜져 있음" 으로 표시되고 되돌릴 방법이 화면에서 사라진다.
|
||||
*
|
||||
* @effects custom_assets_disabled_by_request_parameter
|
||||
*/
|
||||
it('주소에 파라미터가 없어도 서버가 껐다고 하면 꺼짐으로 표시한다', () => {
|
||||
render(
|
||||
wrapToolbar(<EditorToolbar onToggleCustomAssets={() => {}} customAssetsDisabled={true} />),
|
||||
);
|
||||
|
||||
const button = screen.getByTestId('g7le-toolbar-toggle-custom-assets');
|
||||
|
||||
expect(window.location.search).not.toContain('custom=off');
|
||||
expect(button.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(button.textContent).toContain('custom_assets_on');
|
||||
});
|
||||
|
||||
/** @effects custom_assets_disabled_by_request_parameter */
|
||||
it('토글이 현재 끔 상태를 문구와 aria-pressed 로 드러낸다', () => {
|
||||
const onToggle = vi.fn();
|
||||
const { rerender } = render(
|
||||
wrapToolbar(<EditorToolbar onToggleCustomAssets={onToggle} customAssetsDisabled={false} />),
|
||||
);
|
||||
|
||||
const button = () => screen.getByTestId('g7le-toolbar-toggle-custom-assets');
|
||||
|
||||
expect(button().getAttribute('aria-pressed')).toBe('false');
|
||||
expect(button().getAttribute('data-custom-disabled')).toBe('false');
|
||||
|
||||
rerender(
|
||||
wrapToolbar(<EditorToolbar onToggleCustomAssets={onToggle} customAssetsDisabled={true} />),
|
||||
);
|
||||
|
||||
// 지금 화면이 평소와 다른 상태임이 보이지 않으면, 운영자가 "내 CSS 가 사라졌다" 를
|
||||
// 새 결함으로 오인한다
|
||||
expect(button().getAttribute('aria-pressed')).toBe('true');
|
||||
expect(button().getAttribute('data-custom-disabled')).toBe('true');
|
||||
|
||||
fireEvent.click(button());
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,533 @@
|
||||
/**
|
||||
* CustomAssetsModal.tsx — 사용자 추가 에셋(`custom/`) 관리 모달
|
||||
*
|
||||
* 운영자가 확장의 `custom/` 디렉토리에 자기 CSS·JS 를 넣고 고치고, 그 CSS 가 참조할
|
||||
* 폰트·이미지를 올린다. 종전에는 FTP 나 서버 셸이 유일한 경로였다 — 그 접근이 없는
|
||||
* 운영자에게는 기능 자체가 없는 것과 같았다.
|
||||
*
|
||||
* 권한(`core.extensions.custom_assets.manage`)은 서버가 판정한다. 403 은 오류 문구가
|
||||
* 아니라 **안내**로 바꿔 보여 준다 — "HTTP 403" 만 띄우면 운영자는 무엇이 부족한지
|
||||
* 알 수 없다.
|
||||
*
|
||||
* 대상은 편집 중인 템플릿뿐 아니라 **활성 모듈·플러그인**도 고를 수 있다. 같은 기능이
|
||||
* 확장 타입에 따라 화면에서 되고 안 되면 운영자는 그 이유를 알 수 없고, 모듈·플러그인
|
||||
* `custom/` 은 그동안 FTP 말고 경로가 없었다.
|
||||
*
|
||||
* 편집기 코어 위젯이므로 `g7le-*` + 인라인 스타일만 쓴다(CSS 라이브러리 비종속).
|
||||
* 자산이 깨진 상황에서도 이 화면만은 떠야 하기 때문이다.
|
||||
*
|
||||
* @since engine-v1.63.0
|
||||
*/
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
useCustomAssets,
|
||||
type CustomAssetFile,
|
||||
type CustomAssetTarget,
|
||||
} from '../hooks/useCustomAssets';
|
||||
|
||||
export interface CustomAssetsModalProps {
|
||||
/** 편집 대상 템플릿 식별자 — 대상 목록의 기본 선택 */
|
||||
templateIdentifier: string;
|
||||
/** 다국어 해석 함수 */
|
||||
t: (key: string, params?: Record<string, string | number>) => string;
|
||||
/** 모달 닫기 */
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const wrap: React.CSSProperties = {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%',
|
||||
minHeight: 0,
|
||||
};
|
||||
|
||||
const header: React.CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
padding: '12px 16px',
|
||||
borderBottom: '1px solid #e2e8f0',
|
||||
background: '#f8fafc',
|
||||
fontWeight: 600,
|
||||
color: '#0f172a',
|
||||
};
|
||||
|
||||
const closeBtn: React.CSSProperties = {
|
||||
marginLeft: 'auto',
|
||||
border: 'none',
|
||||
background: 'transparent',
|
||||
fontSize: 16,
|
||||
color: '#64748b',
|
||||
cursor: 'pointer',
|
||||
outline: 'none',
|
||||
};
|
||||
|
||||
const body: React.CSSProperties = {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
display: 'flex',
|
||||
};
|
||||
|
||||
const listPane: React.CSSProperties = {
|
||||
width: 260,
|
||||
flexShrink: 0,
|
||||
borderRight: '1px solid #e2e8f0',
|
||||
overflowY: 'auto',
|
||||
padding: 8,
|
||||
};
|
||||
|
||||
const editPane: React.CSSProperties = {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
padding: 12,
|
||||
gap: 8,
|
||||
};
|
||||
|
||||
const rowBase: React.CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
width: '100%',
|
||||
padding: '6px 8px',
|
||||
borderRadius: 6,
|
||||
borderWidth: 1,
|
||||
borderStyle: 'solid',
|
||||
borderColor: 'transparent',
|
||||
backgroundColor: 'transparent',
|
||||
fontSize: 12,
|
||||
color: '#334155',
|
||||
cursor: 'pointer',
|
||||
textAlign: 'left',
|
||||
};
|
||||
|
||||
const rowSelected: React.CSSProperties = {
|
||||
...rowBase,
|
||||
backgroundColor: '#eff6ff',
|
||||
borderColor: '#bfdbfe',
|
||||
color: '#1d4ed8',
|
||||
fontWeight: 600,
|
||||
};
|
||||
|
||||
const noticeBox: React.CSSProperties = {
|
||||
margin: 16,
|
||||
padding: 16,
|
||||
borderRadius: 8,
|
||||
border: '1px solid #fcd34d',
|
||||
background: '#fffbeb',
|
||||
color: '#92400e',
|
||||
fontSize: 13,
|
||||
lineHeight: 1.7,
|
||||
};
|
||||
|
||||
const errorBar: React.CSSProperties = {
|
||||
padding: '8px 12px',
|
||||
borderRadius: 6,
|
||||
border: '1px solid #fecaca',
|
||||
background: '#fef2f2',
|
||||
color: '#b91c1c',
|
||||
fontSize: 12,
|
||||
};
|
||||
|
||||
const textarea: React.CSSProperties = {
|
||||
flex: 1,
|
||||
minHeight: 220,
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
padding: 10,
|
||||
borderRadius: 6,
|
||||
borderWidth: 1,
|
||||
borderStyle: 'solid',
|
||||
borderColor: '#cbd5e1',
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
|
||||
fontSize: 12,
|
||||
lineHeight: 1.6,
|
||||
resize: 'vertical',
|
||||
};
|
||||
|
||||
const actionRow: React.CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
flexWrap: 'wrap',
|
||||
};
|
||||
|
||||
const button: React.CSSProperties = {
|
||||
padding: '6px 12px',
|
||||
borderRadius: 6,
|
||||
borderWidth: 1,
|
||||
borderStyle: 'solid',
|
||||
borderColor: '#cbd5e1',
|
||||
backgroundColor: '#ffffff',
|
||||
color: '#334155',
|
||||
fontSize: 12,
|
||||
cursor: 'pointer',
|
||||
};
|
||||
|
||||
const primary: React.CSSProperties = {
|
||||
...button,
|
||||
backgroundColor: '#2563eb',
|
||||
borderColor: '#2563eb',
|
||||
color: '#ffffff',
|
||||
fontWeight: 600,
|
||||
};
|
||||
|
||||
const danger: React.CSSProperties = {
|
||||
...button,
|
||||
borderColor: '#fca5a5',
|
||||
color: '#b91c1c',
|
||||
};
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
...button,
|
||||
cursor: 'text',
|
||||
minWidth: 200,
|
||||
};
|
||||
|
||||
const selectStyle: React.CSSProperties = {
|
||||
...button,
|
||||
cursor: 'pointer',
|
||||
minWidth: 220,
|
||||
};
|
||||
|
||||
/**
|
||||
* 확장 표시 이름을 뽑습니다 (다국어 객체 또는 문자열).
|
||||
*
|
||||
* @param value display_name 값
|
||||
* @param fallback 이름이 없을 때 쓸 식별자
|
||||
* @returns 표시 이름
|
||||
*/
|
||||
function displayNameOf(value: unknown, fallback: string): string {
|
||||
if (typeof value === 'string' && value !== '') return value;
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
const map = value as Record<string, unknown>;
|
||||
const locale = (window as any)?.G7Config?.locale ?? 'ko';
|
||||
const picked = map[locale] ?? map.ko ?? map.en ?? Object.values(map)[0];
|
||||
|
||||
if (typeof picked === 'string' && picked !== '') return picked;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리 가능한 대상 목록을 만듭니다 — 편집 중인 템플릿 + 활성 모듈·플러그인.
|
||||
*
|
||||
* **활성** 확장만 싣는다. 자산 서빙이 활성 확장에만 응답하므로, 비활성 확장의 파일을
|
||||
* 넣어 봐야 저장은 되는데 화면에는 영영 나타나지 않는다.
|
||||
*
|
||||
* @param templateIdentifier 편집 중인 템플릿 식별자
|
||||
* @returns 대상 목록 (템플릿 → 모듈 → 플러그인)
|
||||
*/
|
||||
function buildTargets(
|
||||
templateIdentifier: string,
|
||||
): Array<CustomAssetTarget & { label: string }> {
|
||||
const config = (typeof window !== 'undefined' ? (window as any).G7Config : null) ?? {};
|
||||
const list: Array<CustomAssetTarget & { label: string }> = [
|
||||
{ type: 'template', identifier: templateIdentifier, label: templateIdentifier },
|
||||
];
|
||||
|
||||
for (const [type, rows] of [
|
||||
['module', config.activeModules],
|
||||
['plugin', config.activePlugins],
|
||||
] as const) {
|
||||
if (!Array.isArray(rows)) continue;
|
||||
|
||||
for (const row of rows) {
|
||||
const identifier = typeof row?.identifier === 'string' ? row.identifier : '';
|
||||
|
||||
if (!identifier) continue;
|
||||
|
||||
list.push({
|
||||
type,
|
||||
identifier,
|
||||
label: displayNameOf(row?.display_name, identifier),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 바이트를 읽기 쉬운 크기로 바꿉니다.
|
||||
*
|
||||
* @param bytes 바이트
|
||||
* @returns 표시 문자열
|
||||
*/
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function CustomAssetsModal(props: CustomAssetsModalProps): React.ReactElement {
|
||||
const { templateIdentifier, t, onClose } = props;
|
||||
|
||||
const targets = useMemo(() => buildTargets(templateIdentifier), [templateIdentifier]);
|
||||
const [targetKey, setTargetKey] = useState(`template:${templateIdentifier}`);
|
||||
const target = useMemo(
|
||||
() => targets.find((x) => `${x.type}:${x.identifier}` === targetKey) ?? targets[0],
|
||||
[targets, targetKey],
|
||||
);
|
||||
|
||||
const assets = useCustomAssets({ type: target.type, identifier: target.identifier });
|
||||
const { reload } = assets;
|
||||
|
||||
const [selected, setSelected] = useState<CustomAssetFile | null>(null);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [newPath, setNewPath] = useState('');
|
||||
const [isBusy, setIsBusy] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void reload();
|
||||
}, [reload]);
|
||||
|
||||
// 대상이 바뀌면 이전 확장의 선택·초안을 버린다. 남겨 두면 A 확장에서 열어 둔 본문을
|
||||
// B 확장에 저장하게 되고, 경로가 유효하면 서버는 정상 200 으로 받아들인다.
|
||||
useEffect(() => {
|
||||
setSelected(null);
|
||||
setDraft('');
|
||||
setNewPath('');
|
||||
}, [targetKey]);
|
||||
|
||||
const openFile = useCallback(
|
||||
async (file: CustomAssetFile) => {
|
||||
setSelected(file);
|
||||
|
||||
if (!file.editable) {
|
||||
setDraft('');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
setIsBusy(true);
|
||||
const content = await assets.read(file.path);
|
||||
setIsBusy(false);
|
||||
setDraft(content ?? '');
|
||||
},
|
||||
[assets],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
const path = selected?.path ?? newPath.trim();
|
||||
|
||||
if (!path) return;
|
||||
|
||||
setIsBusy(true);
|
||||
const ok = await assets.save(path, draft);
|
||||
setIsBusy(false);
|
||||
|
||||
if (ok && !selected) {
|
||||
setNewPath('');
|
||||
setSelected({
|
||||
path,
|
||||
name: path.split('/').pop() ?? path,
|
||||
extension: (path.split('.').pop() ?? '').toLowerCase(),
|
||||
size: draft.length,
|
||||
modified_at: new Date().toISOString(),
|
||||
editable: true,
|
||||
loaded: true,
|
||||
});
|
||||
}
|
||||
}, [assets, selected, newPath, draft]);
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!selected) return;
|
||||
|
||||
// 되돌릴 수 없는 조작이라 확인을 받는다. 편집기 코어 위젯이므로 모달 스택을
|
||||
// 더 쌓지 않고 브라우저 확인을 쓴다(나가기·템플릿 전환과 같은 방식).
|
||||
if (typeof window !== 'undefined' && !window.confirm(t('layout_editor.custom_assets.delete_confirm'))) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsBusy(true);
|
||||
const ok = await assets.remove(selected.path);
|
||||
setIsBusy(false);
|
||||
|
||||
if (ok) {
|
||||
setSelected(null);
|
||||
setDraft('');
|
||||
}
|
||||
}, [assets, selected, t]);
|
||||
|
||||
const handleUpload = useCallback(
|
||||
async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
|
||||
if (!file) return;
|
||||
|
||||
setIsBusy(true);
|
||||
await assets.upload(file);
|
||||
setIsBusy(false);
|
||||
|
||||
// 같은 파일을 다시 고를 수 있도록 입력을 비운다 (change 이벤트가 재발화되지 않는다)
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
},
|
||||
[assets],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="g7le-custom-assets" style={wrap} data-testid="g7le-custom-assets-modal">
|
||||
<div style={header}>
|
||||
<span>🎨 {t('layout_editor.custom_assets.title')}</span>
|
||||
<select
|
||||
value={targetKey}
|
||||
onChange={(event) => setTargetKey(event.target.value)}
|
||||
style={selectStyle}
|
||||
aria-label={t('layout_editor.custom_assets.target_label')}
|
||||
data-testid="g7le-custom-assets-target"
|
||||
>
|
||||
{targets.map((option) => (
|
||||
<option key={`${option.type}:${option.identifier}`} value={`${option.type}:${option.identifier}`}>
|
||||
{t(`layout_editor.custom_assets.type_${option.type}`)} · {option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
style={closeBtn}
|
||||
onClick={onClose}
|
||||
aria-label={t('layout_editor.custom_assets.close')}
|
||||
data-testid="g7le-custom-assets-close"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{assets.forbidden ? (
|
||||
<div style={noticeBox} data-testid="g7le-custom-assets-forbidden">
|
||||
{t('layout_editor.custom_assets.forbidden')}
|
||||
</div>
|
||||
) : (
|
||||
<div style={body}>
|
||||
<div style={listPane} data-testid="g7le-custom-assets-list">
|
||||
{assets.isLoading && assets.files.length === 0 ? (
|
||||
<div style={{ padding: 12, color: '#94a3b8', fontSize: 12 }}>
|
||||
{t('layout_editor.custom_assets.loading')}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!assets.isLoading && assets.files.length === 0 ? (
|
||||
<div style={{ padding: 12, color: '#94a3b8', fontSize: 12 }}>
|
||||
{t('layout_editor.custom_assets.empty')}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{assets.files.map((file) => (
|
||||
<button
|
||||
key={file.path}
|
||||
type="button"
|
||||
style={selected?.path === file.path ? rowSelected : rowBase}
|
||||
onClick={() => void openFile(file)}
|
||||
data-testid={`g7le-custom-asset-row-${file.path}`}
|
||||
data-loaded={file.loaded ? 'true' : 'false'}
|
||||
>
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{file.path}
|
||||
</span>
|
||||
<span style={{ color: '#94a3b8', fontSize: 11 }}>{formatSize(file.size)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div style={editPane}>
|
||||
{assets.error ? (
|
||||
<div style={errorBar} data-testid="g7le-custom-assets-error">
|
||||
{assets.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div style={actionRow}>
|
||||
<input
|
||||
type="text"
|
||||
value={selected ? selected.path : newPath}
|
||||
readOnly={!!selected}
|
||||
onChange={(event) => setNewPath(event.target.value)}
|
||||
placeholder={t('layout_editor.custom_assets.new_path_placeholder')}
|
||||
style={inputStyle}
|
||||
aria-label={t('layout_editor.custom_assets.path_label')}
|
||||
data-testid="g7le-custom-assets-path"
|
||||
/>
|
||||
{selected ? (
|
||||
<button
|
||||
type="button"
|
||||
style={button}
|
||||
onClick={() => {
|
||||
setSelected(null);
|
||||
setDraft('');
|
||||
}}
|
||||
data-testid="g7le-custom-assets-new"
|
||||
>
|
||||
{t('layout_editor.custom_assets.new_file')}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{selected && !selected.editable ? (
|
||||
<div style={{ color: '#64748b', fontSize: 12, lineHeight: 1.7 }}>
|
||||
{t('layout_editor.custom_assets.binary_hint', { extension: selected.extension })}
|
||||
</div>
|
||||
) : (
|
||||
<textarea
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
style={textarea}
|
||||
spellCheck={false}
|
||||
aria-label={t('layout_editor.custom_assets.content_label')}
|
||||
data-testid="g7le-custom-assets-content"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div style={actionRow}>
|
||||
<button
|
||||
type="button"
|
||||
style={primary}
|
||||
disabled={isBusy || (selected ? !selected.editable : newPath.trim() === '')}
|
||||
onClick={() => void handleSave()}
|
||||
data-testid="g7le-custom-assets-save"
|
||||
>
|
||||
{t('layout_editor.custom_assets.save')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
style={button}
|
||||
disabled={isBusy}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
data-testid="g7le-custom-assets-upload"
|
||||
>
|
||||
{t('layout_editor.custom_assets.upload')}
|
||||
</button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
style={{ display: 'none' }}
|
||||
onChange={(event) => void handleUpload(event)}
|
||||
data-testid="g7le-custom-assets-file-input"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
style={danger}
|
||||
disabled={isBusy || !selected}
|
||||
onClick={() => void handleDelete()}
|
||||
data-testid="g7le-custom-assets-delete"
|
||||
>
|
||||
{t('layout_editor.custom_assets.delete')}
|
||||
</button>
|
||||
<span style={{ color: '#94a3b8', fontSize: 11 }}>
|
||||
{t('layout_editor.custom_assets.apply_hint')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -360,6 +360,23 @@ export interface EditorToolbarProps {
|
||||
onPreview?: () => void | Promise<void>;
|
||||
/** 버전 히스토리 클릭 — 현재 레이아웃 저장 버전 목록·복원 모달 */
|
||||
onShowVersions?: () => void;
|
||||
/**
|
||||
* 사용자 추가 에셋(`custom/`) 적용 토글 — 탈출구(D33).
|
||||
*
|
||||
* 끄기는 `?custom=off` 를 붙여 페이지를 **다시 여는** 방식이다. DOM 에서 `<link>` 를
|
||||
* 떼는 방식이 아닌 이유: 이미 실행된 custom JS 는 되돌릴 수 없어 절반만 꺼진다.
|
||||
* 서버가 목록을 비우면 CSS·JS 가 애초에 페이지에 도달하지 않는다.
|
||||
*/
|
||||
onToggleCustomAssets?: () => void;
|
||||
/** 현재 요청이 `?custom=off` 상태인지 (버튼 문구·상태 표시) */
|
||||
customAssetsDisabled?: boolean;
|
||||
/**
|
||||
* 커스텀 자산 관리 모달 열기.
|
||||
*
|
||||
* 버튼을 권한으로 감추지 않는다 — 서버가 403 을 돌려주면 모달이 "무엇이 부족한지"를
|
||||
* 문장으로 알린다. 보이지 않는 버튼은 권한이 없다는 사실조차 알려 주지 못한다.
|
||||
*/
|
||||
onManageCustomAssets?: () => void;
|
||||
}
|
||||
|
||||
export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElement {
|
||||
@@ -379,6 +396,9 @@ export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElemen
|
||||
templateVersion,
|
||||
templateList,
|
||||
onSwitchTemplate,
|
||||
onToggleCustomAssets,
|
||||
customAssetsDisabled = false,
|
||||
onManageCustomAssets,
|
||||
} = props;
|
||||
|
||||
// 저장 진행 상태 — onSave 가 Promise 면 완료까지 스피너 + disabled.
|
||||
@@ -467,6 +487,15 @@ export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElemen
|
||||
fontWeight: 600,
|
||||
};
|
||||
|
||||
// custom 자산이 꺼진 동안의 토글 강조 — 지금 화면이 평소와 다른 상태임을 알린다.
|
||||
// 이 사실이 안 보이면 운영자가 "내 CSS 가 사라졌다" 를 새 결함으로 오인한다.
|
||||
const activeToggleStyle: React.CSSProperties = {
|
||||
backgroundColor: '#fef3c7',
|
||||
borderColor: '#f59e0b',
|
||||
color: '#92400e',
|
||||
fontWeight: 600,
|
||||
};
|
||||
|
||||
const ghostButton: React.CSSProperties = {
|
||||
...buttonBase,
|
||||
borderColor: '#e2e8f0',
|
||||
@@ -694,6 +723,38 @@ export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElemen
|
||||
>
|
||||
🌐 {t('layout_editor.chrome.toolbar.translations')}
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
data-testid="g7le-toolbar-custom-assets"
|
||||
disabled={!onManageCustomAssets}
|
||||
onClick={() => onManageCustomAssets?.()}
|
||||
title={t('layout_editor.chrome.toolbar.custom_assets_hint')}
|
||||
baseStyle={buttonBase}
|
||||
hoverStyle={buttonHover}
|
||||
>
|
||||
🎨 {t('layout_editor.chrome.toolbar.custom_assets')}
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
data-testid="g7le-toolbar-toggle-custom-assets"
|
||||
data-custom-disabled={customAssetsDisabled ? 'true' : 'false'}
|
||||
disabled={!onToggleCustomAssets}
|
||||
onClick={() => onToggleCustomAssets?.()}
|
||||
aria-pressed={customAssetsDisabled}
|
||||
title={t(
|
||||
customAssetsDisabled
|
||||
? 'layout_editor.chrome.toolbar.custom_assets_on_hint'
|
||||
: 'layout_editor.chrome.toolbar.custom_assets_off_hint'
|
||||
)}
|
||||
baseStyle={buttonBase}
|
||||
hoverStyle={buttonHover}
|
||||
style={customAssetsDisabled ? { ...buttonBase, ...activeToggleStyle } : undefined}
|
||||
>
|
||||
{customAssetsDisabled ? '👁' : '🚫'}{' '}
|
||||
{t(
|
||||
customAssetsDisabled
|
||||
? 'layout_editor.chrome.toolbar.custom_assets_on'
|
||||
: 'layout_editor.chrome.toolbar.custom_assets_off'
|
||||
)}
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
data-testid="g7le-toolbar-page-settings"
|
||||
disabled={
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* useCustomAssets.ts — 사용자 추가 에셋(`custom/`) 조회·편집 hook
|
||||
*
|
||||
* 운영자가 자기 CSS·JS·폰트·이미지를 화면에서 직접 넣고 고칠 수 있게 하는 관리 API 를
|
||||
* 감싼다. 종전에는 FTP 나 서버 셸이 유일한 경로였고, 그 접근이 없는 운영자에게는 기능
|
||||
* 자체가 없는 것과 같았다.
|
||||
*
|
||||
* - GET /api/admin/extensions/{type}/{id}/custom-assets (목록 + 편집기 메타)
|
||||
* - GET /api/admin/extensions/{type}/{id}/custom-assets/content (본문)
|
||||
* - PUT /api/admin/extensions/{type}/{id}/custom-assets/content (본문 저장·생성)
|
||||
* - POST /api/admin/extensions/{type}/{id}/custom-assets/upload (바이너리 업로드)
|
||||
* - DELETE /api/admin/extensions/{type}/{id}/custom-assets (삭제)
|
||||
*
|
||||
* `{type}` 은 `module` | `plugin` | `template`. 세 타입이 한 엔드포인트를 공유하므로
|
||||
* 이 훅도 타입을 인자로 받는다 — 타입별 훅을 세 벌 두면 그중 하나만 고쳐 놓는 상태가 된다.
|
||||
*
|
||||
* 권한(`core.extensions.custom_assets.manage`)은 서버가 판정한다. 403 은 오류가 아니라
|
||||
* **상태**로 취급해 호출자가 안내 문구로 바꿀 수 있게 별도 플래그(`forbidden`)로 알린다 —
|
||||
* "HTTP 403" 을 그대로 띄우면 운영자는 무엇이 부족한지 알 수 없다.
|
||||
*
|
||||
* @since engine-v1.63.0
|
||||
*/
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { buildAuthHeaders } from '../utils/authToken';
|
||||
|
||||
/** 목록 항목 1건 */
|
||||
export interface CustomAssetFile {
|
||||
/** `custom/` 기준 상대 경로 */
|
||||
path: string;
|
||||
/** 파일명 */
|
||||
name: string;
|
||||
/** 소문자 확장자 */
|
||||
extension: string;
|
||||
/** 바이트 크기 */
|
||||
size: number;
|
||||
/** 최종 수정 시각 (ISO 8601) */
|
||||
modified_at: string;
|
||||
/** 편집기에서 본문을 열 수 있는지 */
|
||||
editable: boolean;
|
||||
/** 실제로 페이지에 실리는지 (규약 스캔·선언 파일 결과) */
|
||||
loaded: boolean;
|
||||
}
|
||||
|
||||
/** 목록 응답의 편집기 메타 */
|
||||
export interface CustomAssetMeta {
|
||||
editable_extensions: string[];
|
||||
uploadable_extensions: string[];
|
||||
max_text_bytes: number;
|
||||
max_upload_bytes: number;
|
||||
}
|
||||
|
||||
/** 훅 반환 */
|
||||
export interface UseCustomAssetsResult {
|
||||
files: CustomAssetFile[];
|
||||
meta: CustomAssetMeta | null;
|
||||
isLoading: boolean;
|
||||
/** 권한 부족 — 오류 문구가 아니라 안내로 바꿔야 하는 상태 */
|
||||
forbidden: boolean;
|
||||
error: string | null;
|
||||
reload: () => Promise<void>;
|
||||
read: (path: string) => Promise<string | null>;
|
||||
save: (path: string, content: string) => Promise<boolean>;
|
||||
upload: (file: File, directory?: string) => Promise<boolean>;
|
||||
remove: (path: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
/** 관리 대상 확장 — 타입 + 식별자. */
|
||||
export interface CustomAssetTarget {
|
||||
type: 'module' | 'plugin' | 'template';
|
||||
identifier: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리 API base URL 을 만듭니다.
|
||||
*
|
||||
* @param target 관리 대상 확장
|
||||
* @returns base URL
|
||||
*/
|
||||
function baseUrl(target: CustomAssetTarget): string {
|
||||
return `/api/admin/extensions/${encodeURIComponent(target.type)}/${encodeURIComponent(target.identifier)}/custom-assets`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답 본문에서 사용자에게 보일 메시지를 뽑습니다.
|
||||
*
|
||||
* 서버가 다국어 키를 해석해 문장으로 내려주므로 그것을 그대로 쓴다. 없을 때만
|
||||
* 상태 코드로 폴백한다 — 그 경우에도 "HTTP 500" 이 안내로서 최소한의 단서는 된다.
|
||||
*
|
||||
* @param body 파싱된 응답 본문
|
||||
* @param status HTTP 상태 코드
|
||||
* @returns 메시지
|
||||
*/
|
||||
function messageOf(body: unknown, status: number): string {
|
||||
const message = (body as { message?: unknown })?.message;
|
||||
|
||||
return typeof message === 'string' && message !== '' ? message : `HTTP ${status}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋 관리 hook.
|
||||
*
|
||||
* @param target 관리 대상 확장 (타입 + 식별자)
|
||||
* @returns 목록 상태 + 조작 함수
|
||||
*/
|
||||
export function useCustomAssets(target: CustomAssetTarget): UseCustomAssetsResult {
|
||||
const [files, setFiles] = useState<CustomAssetFile[]>([]);
|
||||
const [meta, setMeta] = useState<CustomAssetMeta | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [forbidden, setForbidden] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const reload = useCallback(async (): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(baseUrl(target), {
|
||||
credentials: 'same-origin',
|
||||
headers: buildAuthHeaders(),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
setForbidden(true);
|
||||
setFiles([]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
setForbidden(false);
|
||||
|
||||
if (!response.ok) {
|
||||
setError(messageOf(body, response.status));
|
||||
setFiles([]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const data = (body as { data?: Record<string, unknown> })?.data ?? {};
|
||||
const list = data.files;
|
||||
|
||||
setFiles(Array.isArray(list) ? (list as CustomAssetFile[]) : []);
|
||||
setMeta({
|
||||
editable_extensions: (data.editable_extensions as string[]) ?? [],
|
||||
uploadable_extensions: (data.uploadable_extensions as string[]) ?? [],
|
||||
max_text_bytes: (data.max_text_bytes as number) ?? 0,
|
||||
max_upload_bytes: (data.max_upload_bytes as number) ?? 0,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'network error');
|
||||
setFiles([]);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [target.type, target.identifier]);
|
||||
|
||||
const read = useCallback(
|
||||
async (path: string): Promise<string | null> => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const url = `${baseUrl(target)}/content?path=${encodeURIComponent(path)}`;
|
||||
const response = await fetch(url, {
|
||||
credentials: 'same-origin',
|
||||
headers: buildAuthHeaders(),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
|
||||
if (!response.ok) {
|
||||
setError(messageOf(body, response.status));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = (body as { data?: { content?: unknown } })?.data?.content;
|
||||
|
||||
return typeof content === 'string' ? content : '';
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'network error');
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[target.type, target.identifier],
|
||||
);
|
||||
|
||||
const save = useCallback(
|
||||
async (path: string, content: string): Promise<boolean> => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${baseUrl(target)}/content`, {
|
||||
method: 'PUT',
|
||||
credentials: 'same-origin',
|
||||
headers: buildAuthHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ path, content }),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
|
||||
if (!response.ok) {
|
||||
setError(messageOf(body, response.status));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
await reload();
|
||||
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'network error');
|
||||
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[target.type, target.identifier, reload],
|
||||
);
|
||||
|
||||
const upload = useCallback(
|
||||
async (file: File, directory?: string): Promise<boolean> => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
|
||||
if (directory) {
|
||||
form.append('directory', directory);
|
||||
}
|
||||
|
||||
// multipart 는 boundary 를 브라우저가 붙이므로 Content-Type 을 명시하지 않는다.
|
||||
const response = await fetch(`${baseUrl(target)}/upload`, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: buildAuthHeaders(),
|
||||
body: form,
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
|
||||
if (!response.ok) {
|
||||
setError(messageOf(body, response.status));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
await reload();
|
||||
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'network error');
|
||||
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[target.type, target.identifier, reload],
|
||||
);
|
||||
|
||||
const remove = useCallback(
|
||||
async (path: string): Promise<boolean> => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const url = `${baseUrl(target)}?path=${encodeURIComponent(path)}`;
|
||||
const response = await fetch(url, {
|
||||
method: 'DELETE',
|
||||
credentials: 'same-origin',
|
||||
headers: buildAuthHeaders(),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
|
||||
if (!response.ok) {
|
||||
setError(messageOf(body, response.status));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
await reload();
|
||||
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'network error');
|
||||
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[target.type, target.identifier, reload],
|
||||
);
|
||||
|
||||
return { files, meta, isLoading, forbidden, error, reload, read, save, upload, remove };
|
||||
}
|
||||
@@ -357,3 +357,110 @@ function loadScriptOnce(url: string, attrs: Record<string, string>): Promise<voi
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `<link rel="stylesheet">` 로드를 재시도하는 로더입니다.
|
||||
*
|
||||
* `loadScriptWithRetry` 와 동형이다 — 3시도(기본) · 지수 백오프 · **최종 실패 시 reject**.
|
||||
* CSS 경로만 이 계층이 없어 실패가 통째로 무음이었다: `onerror` 를 아예 걸지 않거나
|
||||
* `resolve()` 로 삼켜, 스타일이 붙지 않은 화면(아이콘 소실·본문 서식 붕괴)이 오류 없이
|
||||
* 남았다. 아이콘만으로 조작하는 버튼이 있는 화면에서는 그것이 곧 조작 불능이다.
|
||||
*
|
||||
* `<link>` 의 `onerror` 도 사유를 주지 않으므로 모든 실패를 재시도 대상으로 본다.
|
||||
* 재시도 전 기존 element 를 제거한다 — 남겨두면 실패한 `<link>` 가 누적되고, id 를
|
||||
* 지정한 경우 다음 시도와 충돌한다.
|
||||
*
|
||||
* @param url 스타일시트 URL
|
||||
* @param attrs link element 에 부여할 속성 (id, media, crossorigin 등)
|
||||
* @param options 재시도 옵션
|
||||
* @return Promise<void> 로드 성공 시 resolve
|
||||
* @throws Error 모든 시도가 실패한 경우
|
||||
* @since engine-v1.62.0
|
||||
*/
|
||||
export async function loadStylesheetWithRetry(
|
||||
url: string,
|
||||
attrs: Record<string, string> = {},
|
||||
options: RetryOptions = {}
|
||||
): Promise<void> {
|
||||
const {
|
||||
retries = DEFAULT_RETRIES,
|
||||
baseDelayMs = DEFAULT_BASE_DELAY_MS,
|
||||
maxDelayMs = DEFAULT_MAX_DELAY_MS,
|
||||
label = url,
|
||||
} = options;
|
||||
|
||||
const maxAttempts = retries + 1;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
let link: HTMLLinkElement | null = null;
|
||||
|
||||
try {
|
||||
link = createStylesheetElement(url, attrs);
|
||||
await loadStylesheetOnce(link);
|
||||
return;
|
||||
} catch (error) {
|
||||
// 실패한 element 를 제거한다 (누적 방지 + 다음 시도의 id 충돌 방지)
|
||||
link?.remove();
|
||||
if (attrs.id) {
|
||||
document.getElementById(attrs.id)?.remove();
|
||||
}
|
||||
|
||||
if (isDocumentUnloading()) {
|
||||
logger.warn(`Document unloading, aborting stylesheet retries: ${label}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const isLastAttempt = attempt === maxAttempts - 1;
|
||||
if (isLastAttempt) {
|
||||
logger.warn(`All ${maxAttempts} stylesheet attempts failed: ${label}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const waitMs = computeBackoffDelay(attempt, baseDelayMs, maxDelayMs);
|
||||
logger.warn(
|
||||
`Stylesheet load failed (attempt ${attempt + 1}/${maxAttempts}), retrying in ${waitMs}ms: ${label}`
|
||||
);
|
||||
await delay(waitMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `<link rel="stylesheet">` element 를 생성해 head 에 추가합니다.
|
||||
*
|
||||
* @param url 스타일시트 URL
|
||||
* @param attrs link element 속성
|
||||
* @return HTMLLinkElement 생성된 element
|
||||
* @since engine-v1.62.0
|
||||
*/
|
||||
function createStylesheetElement(url: string, attrs: Record<string, string>): HTMLLinkElement {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = url;
|
||||
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
if (key === 'id') {
|
||||
link.id = value;
|
||||
} else {
|
||||
link.setAttribute(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
document.head.appendChild(link);
|
||||
|
||||
return link;
|
||||
}
|
||||
|
||||
/**
|
||||
* `<link>` 1회 로드를 시도합니다 (재시도 없음).
|
||||
*
|
||||
* @param link head 에 이미 추가된 link element
|
||||
* @return Promise<void> 로드 성공 시 resolve, 실패 시 reject
|
||||
* @since engine-v1.62.0
|
||||
*/
|
||||
function loadStylesheetOnce(link: HTMLLinkElement): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
link.onload = () => resolve();
|
||||
link.onerror = () => reject(new Error(`Failed to load stylesheet: ${link.href}`));
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user