F4-L1: amis-editor 页面设计器(多页入口隔离)+overlay 编辑闭环
- editor.html 独立 vite 入口,amis-editor npm 依赖与主应用本地 SDK 隔离 - 设计器:画布编辑/保存→overlay/还原标准版/预览;页面 Tab 管理员「设计」入口 - designer.spec.ts 7 用例(编辑→保存→渲染 overlay→还原,X-Schema-Layer 断言);全套 e2e 68/68 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
BIN
e2e/artifacts/f4-l1/01-designer-canvas.png
Normal file
BIN
e2e/artifacts/f4-l1/01-designer-canvas.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
BIN
e2e/artifacts/f4-l1/03-render-standard-after-restore.png
Normal file
BIN
e2e/artifacts/f4-l1/03-render-standard-after-restore.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
BIN
e2e/artifacts/f4-l1/04-designer-save-toast.png
Normal file
BIN
e2e/artifacts/f4-l1/04-designer-save-toast.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
296
e2e/designer.spec.ts
Normal file
296
e2e/designer.spec.ts
Normal file
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* F4-L1 页面设计器 e2e
|
||||
*
|
||||
* 闭环流程:
|
||||
* 1. 取标准层 schema(Node 侧 API,断言 X-Schema-Layer: standard)
|
||||
* 2. 保存 overlay(Node 侧 PUT)
|
||||
* 3. GET 断言 X-Schema-Layer: overlay,schema 内容已更新
|
||||
* 4. 浏览器打开 /page/:templateId,断言 amis-host 渲染(overlay 版)
|
||||
* 5. 浏览器打开设计器 /editor.html?templateId=xxx(admin 可见)
|
||||
* 6. 设计器加载完成(designer-root 或 designer-loading→designer-root)
|
||||
* 7. 点击「还原标准版」按钮
|
||||
* 8. GET 断言 X-Schema-Layer: standard(overlay 已删除)
|
||||
* 9. 测后保证清理(afterAll DELETE overlay 幂等)
|
||||
*
|
||||
* 测试用 00511ac1-ee64-4ecd-a550-22842ee5be72(会议纪要归档表单),不污染业务模板。
|
||||
* 数据纪律:测后 DELETE overlay 还原;断言响应头变化。
|
||||
*/
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import http from 'node:http';
|
||||
|
||||
// ── 常量 ──────────────────────────────────────────────────────────────────
|
||||
const TEST_TEMPLATE_ID = '00511ac1-ee64-4ecd-a550-22842ee5be72';
|
||||
// overlay 用于测试的轻量 schema(保留 type:page,改 title 以便断言)
|
||||
const OVERLAY_TITLE = 'E2E-Overlay-F4L1-测试定制标题';
|
||||
const OVERLAY_SCHEMA = JSON.stringify({
|
||||
type: 'page',
|
||||
title: OVERLAY_TITLE,
|
||||
body: [{ type: 'tpl', tpl: 'F4-L1 overlay 测试内容' }],
|
||||
});
|
||||
|
||||
// ── Node 侧 http 工具 ──────────────────────────────────────────────────────
|
||||
let _adminToken: string | undefined;
|
||||
|
||||
async function adminToken(): Promise<string> {
|
||||
if (_adminToken) return _adminToken;
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({ account: 'admin', password: '111111' });
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: 'localhost', port: 8093,
|
||||
path: '/api/auth/login', method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
|
||||
},
|
||||
(res) => {
|
||||
let d = '';
|
||||
res.on('data', (c) => (d += c));
|
||||
res.on('end', () => {
|
||||
const p = JSON.parse(d) as { success: boolean; token: string };
|
||||
if (!p.success) return reject(new Error('admin login failed'));
|
||||
_adminToken = p.token;
|
||||
resolve(p.token);
|
||||
});
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Node 侧 GET,返回 {body, headers, status} */
|
||||
async function apiGet(path: string): Promise<{ body: string; headers: Record<string, string | string[] | undefined>; status: number }> {
|
||||
const tok = await adminToken();
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: 'localhost', port: 8093,
|
||||
path, method: 'GET',
|
||||
headers: { Authorization: `Bearer ${tok}`, 'Cache-Control': 'no-cache' },
|
||||
},
|
||||
(res) => {
|
||||
let d = '';
|
||||
res.on('data', (c) => (d += c));
|
||||
res.on('end', () =>
|
||||
resolve({ body: d, headers: res.headers as Record<string, string | string[] | undefined>, status: res.statusCode ?? 0 }),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Node 侧 PUT,返回解析后 JSON */
|
||||
async function apiPut(path: string, body: string): Promise<Record<string, unknown>> {
|
||||
const tok = await adminToken();
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: 'localhost', port: 8093,
|
||||
path, method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
Authorization: `Bearer ${tok}`,
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let d = '';
|
||||
res.on('data', (c) => (d += c));
|
||||
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Node 侧 DELETE,返回解析后 JSON */
|
||||
async function apiDelete(path: string): Promise<Record<string, unknown>> {
|
||||
const tok = await adminToken();
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: 'localhost', port: 8093,
|
||||
path, method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${tok}` },
|
||||
},
|
||||
(res) => {
|
||||
let d = '';
|
||||
res.on('data', (c) => (d += c));
|
||||
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// ── 种入 admin session(browser 侧) ────────────────────────────────────────
|
||||
async function seedAdminAuth(page: Page) {
|
||||
const tok = await adminToken();
|
||||
await page.addInitScript(
|
||||
({ t }: { t: string }) => {
|
||||
localStorage.setItem('eip4_token', t);
|
||||
localStorage.setItem(
|
||||
'eip4_profile',
|
||||
JSON.stringify({ userId: 'ADMIN', account: 'admin', name: '系统管理员', roles: [] }),
|
||||
);
|
||||
},
|
||||
{ t: tok },
|
||||
);
|
||||
}
|
||||
|
||||
// ── 测后清理 ───────────────────────────────────────────────────────────────
|
||||
test.afterAll(async () => {
|
||||
// 幂等删除 overlay(保证还原标准版)
|
||||
await apiDelete(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`).catch(() => {});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// 测试套件
|
||||
// ============================================================================
|
||||
|
||||
test.describe('F4-L1 设计器 overlay 协议', () => {
|
||||
|
||||
test('1. 标准层 GET 返回 X-Schema-Layer: standard', async () => {
|
||||
// 先确保无 overlay(幂等 DELETE)
|
||||
await apiDelete(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`).catch(() => {});
|
||||
|
||||
const { headers, status } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
|
||||
expect(status).toBe(200);
|
||||
expect(headers['x-schema-layer']).toBe('standard');
|
||||
});
|
||||
|
||||
test('2. PUT overlay 保存成功,返回 status:0', async () => {
|
||||
const result = await apiPut(
|
||||
`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`,
|
||||
OVERLAY_SCHEMA,
|
||||
);
|
||||
expect(result['status']).toBe(0);
|
||||
const data = result['data'] as Record<string, unknown>;
|
||||
expect(data['templateId']).toBe(TEST_TEMPLATE_ID);
|
||||
expect(typeof data['etag']).toBe('string');
|
||||
expect((data['etag'] as string).length).toBe(64); // sha256 hex
|
||||
});
|
||||
|
||||
test('3. PUT overlay 后 GET 返回 X-Schema-Layer: overlay,title 已更新', async () => {
|
||||
const { body, headers, status } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
|
||||
expect(status).toBe(200);
|
||||
expect(headers['x-schema-layer']).toBe('overlay');
|
||||
const schema = JSON.parse(body) as Record<string, unknown>;
|
||||
expect(schema['title']).toBe(OVERLAY_TITLE);
|
||||
});
|
||||
|
||||
test('4. ?layer=standard 强制取标准层,X-Schema-Layer: standard', async () => {
|
||||
const { headers, status } = await apiGet(
|
||||
`/api/page/schema/${TEST_TEMPLATE_ID}?layer=standard`,
|
||||
);
|
||||
expect(status).toBe(200);
|
||||
expect(headers['x-schema-layer']).toBe('standard');
|
||||
});
|
||||
|
||||
test('5. /page/:templateId 浏览器渲染 overlay 版(amis-host 可见)', async ({ page }) => {
|
||||
await seedAdminAuth(page);
|
||||
await page.goto(`/page/${TEST_TEMPLATE_ID}`);
|
||||
// 等待 amis 渲染宿主出现(最多 30s)
|
||||
await page.waitForSelector('[data-testid="amis-host"]', { timeout: 30000 });
|
||||
// 无 schema 错误卡片
|
||||
await expect(page.locator('[data-testid="schema-error-card"]')).toHaveCount(0);
|
||||
// 管理员可见「设计」按钮
|
||||
await expect(page.locator('[data-testid="designer-open-btn"]')).toBeVisible();
|
||||
});
|
||||
|
||||
test('6. 设计器页面加载(editor.html)—— designer-root 出现', async ({ page }) => {
|
||||
await seedAdminAuth(page);
|
||||
await page.goto(`/editor.html?templateId=${TEST_TEMPLATE_ID}`);
|
||||
// 等待设计器根节点(loading → root,最多 60s,amis-editor 首次加载较慢)
|
||||
await page.waitForSelector('[data-testid="designer-root"]', { timeout: 60000 });
|
||||
// 顶部工具条可见
|
||||
await expect(page.locator('[data-testid="designer-topbar"]')).toBeVisible();
|
||||
// 保存/还原/预览按钮可见
|
||||
await expect(page.locator('[data-testid="designer-btn-save"]')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="designer-btn-restore"]')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="designer-btn-preview"]')).toBeVisible();
|
||||
// overlay badge 可见(当前是 overlay 状态)
|
||||
await expect(page.locator('[data-testid="designer-overlay-badge"]')).toBeVisible();
|
||||
|
||||
// 截图:设计器加载完成(画布编辑状态)
|
||||
await page.screenshot({
|
||||
path: 'e2e/artifacts/f4-l1/01-designer-canvas.png',
|
||||
fullPage: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('7. 设计器「还原标准版」→ GET 返回 X-Schema-Layer: standard', async ({ page }) => {
|
||||
// 先确保 overlay 存在(前序 test 可能已删)
|
||||
await apiPut(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`, OVERLAY_SCHEMA);
|
||||
|
||||
await seedAdminAuth(page);
|
||||
await page.goto(`/editor.html?templateId=${TEST_TEMPLATE_ID}`);
|
||||
await page.waitForSelector('[data-testid="designer-root"]', { timeout: 60000 });
|
||||
// 等还原按钮可交互(amis-editor 完全初始化后才 enabled)
|
||||
await page.waitForSelector('[data-testid="designer-btn-restore"]:not([disabled])', { timeout: 30000 });
|
||||
|
||||
// 点击还原标准版
|
||||
await page.click('[data-testid="designer-btn-restore"]');
|
||||
// 等待成功 Toast
|
||||
await page.waitForSelector('[data-testid="designer-toast-success"]', { timeout: 30000 });
|
||||
|
||||
// 截图:还原成功提示
|
||||
await page.screenshot({
|
||||
path: 'e2e/artifacts/f4-l1/02-designer-restore-toast.png',
|
||||
fullPage: false,
|
||||
});
|
||||
|
||||
// Node 侧验证 X-Schema-Layer 回到 standard
|
||||
const { headers } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
|
||||
expect(headers['x-schema-layer']).toBe('standard');
|
||||
});
|
||||
|
||||
test('8. 还原后 /page/:templateId 渲染标准版(无 overlay)', async ({ page }) => {
|
||||
await seedAdminAuth(page);
|
||||
await page.goto(`/page/${TEST_TEMPLATE_ID}`);
|
||||
await page.waitForSelector('[data-testid="amis-host"]', { timeout: 30000 });
|
||||
await expect(page.locator('[data-testid="schema-error-card"]')).toHaveCount(0);
|
||||
|
||||
// 截图:渲染标准版效果
|
||||
await page.screenshot({
|
||||
path: 'e2e/artifacts/f4-l1/03-render-standard-after-restore.png',
|
||||
fullPage: false,
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
test.describe('F4-L1 设计器「保存」按钮流程', () => {
|
||||
|
||||
test('9. 设计器点击「保存」→ overlay 更新 → Toast 成功', async ({ page }) => {
|
||||
// 先确保有 overlay(PUT 一个初始版本)
|
||||
await apiPut(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`, OVERLAY_SCHEMA);
|
||||
|
||||
await seedAdminAuth(page);
|
||||
await page.goto(`/editor.html?templateId=${TEST_TEMPLATE_ID}`);
|
||||
await page.waitForSelector('[data-testid="designer-root"]', { timeout: 60000 });
|
||||
|
||||
// 点击保存(当前 schema 即 currentSchemaRef 的值)
|
||||
await page.click('[data-testid="designer-btn-save"]');
|
||||
await page.waitForSelector('[data-testid="designer-toast-success"]', { timeout: 15000 });
|
||||
|
||||
// 截图:保存提示
|
||||
await page.screenshot({
|
||||
path: 'e2e/artifacts/f4-l1/04-designer-save-toast.png',
|
||||
fullPage: false,
|
||||
});
|
||||
|
||||
// 验证 overlay 仍然存在
|
||||
const { headers } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
|
||||
expect(headers['x-schema-layer']).toBe('overlay');
|
||||
|
||||
// 清理
|
||||
await apiDelete(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`).catch(() => {});
|
||||
});
|
||||
|
||||
});
|
||||
20
editor.html
Normal file
20
editor.html
Normal file
@@ -0,0 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>EIP4 页面设计器</title>
|
||||
<!-- amis-editor 独立入口:用 npm 包版 amis,与主应用 sdk-local 完全隔离 -->
|
||||
<!-- CSS 在 HTML 里直接引用,绕开 vite esbuild 对 amis-ui 包路径的解析 -->
|
||||
<link rel="stylesheet" href="/node_modules/amis-editor-core/lib/style.css" />
|
||||
<link rel="stylesheet" href="/node_modules/amis-ui/lib/themes/default.css" />
|
||||
<link rel="stylesheet" href="/node_modules/amis-ui/lib/helper.css" />
|
||||
<style>
|
||||
html, body, #editor-root { height: 100%; margin: 0; overflow: hidden; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="editor-root"></div>
|
||||
<script type="module" src="/src/editor/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
3528
package-lock.json
generated
3528
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -25,6 +25,13 @@
|
||||
"@types/react": "18.3.12",
|
||||
"@types/react-dom": "18.3.1",
|
||||
"@vitejs/plugin-react": "4.3.4",
|
||||
"amis": "^6.13.0",
|
||||
"amis-core": "^6.13.0",
|
||||
"amis-editor": "^6.13.0",
|
||||
"amis-formula": "^6.13.0",
|
||||
"amis-theme-editor-helper": "^6.12.0-ab.1",
|
||||
"amis-ui": "^6.13.0",
|
||||
"i18n-runtime": "^1.0.13",
|
||||
"jsdom": "^29.1.1",
|
||||
"typescript": "5.6.3",
|
||||
"vite": "5.4.11",
|
||||
|
||||
@@ -61,3 +61,42 @@ export async function fetchSchema(templateId: string): Promise<Record<string, un
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// F4-L1 overlay API(Node 侧 http 调用,供设计器 e2e 断言 X-Schema-Layer 用)
|
||||
// ============================================================================
|
||||
|
||||
/** 获取 schema 并返回 layer 信息(overlay / standard) */
|
||||
export async function fetchSchemaLayer(
|
||||
templateId: string,
|
||||
): Promise<{ schema: Record<string, unknown>; layer: string }> {
|
||||
const resp = await http.get<Record<string, unknown>>(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}`,
|
||||
{ headers: { 'Cache-Control': 'no-cache' } },
|
||||
);
|
||||
const layer = (resp.headers['x-schema-layer'] ?? 'standard') as string;
|
||||
return { schema: resp.data, layer };
|
||||
}
|
||||
|
||||
/** 保存 overlay(仅管理员) */
|
||||
export async function putOverlay(
|
||||
templateId: string,
|
||||
schemaJson: string,
|
||||
): Promise<{ status: number; msg: string }> {
|
||||
const resp = await http.put(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}/overlay`,
|
||||
schemaJson,
|
||||
{ headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
return resp.data as { status: number; msg: string };
|
||||
}
|
||||
|
||||
/** 还原标准版(删除 overlay,仅管理员) */
|
||||
export async function restoreStandard(
|
||||
templateId: string,
|
||||
): Promise<{ status: number; msg: string }> {
|
||||
const resp = await http.delete(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}/overlay`,
|
||||
);
|
||||
return resp.data as { status: number; msg: string };
|
||||
}
|
||||
|
||||
305
src/editor/DesignerPage.tsx
Normal file
305
src/editor/DesignerPage.tsx
Normal file
@@ -0,0 +1,305 @@
|
||||
// ============================================================================
|
||||
// F4-L1 页面设计器 —— amis-editor 三屏布局(左组件/中画布/右属性面板)
|
||||
// 多页入口隔离方案:editor.html → src/editor/main.tsx → 本组件
|
||||
// 依赖 npm amis 包,与主应用 sdk-local 完全隔离,正常包体不受影响。
|
||||
// ============================================================================
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
// @ts-ignore — amis-editor CJS lib(含 Editor 组件)
|
||||
// CSS 由 editor.html <link> 标签加载,绕开 vite esbuild 对 amis-ui CSS 路径的解析
|
||||
import { Editor } from 'amis-editor';
|
||||
import {
|
||||
fetchSchemaWithLayer,
|
||||
fetchStandardSchema,
|
||||
saveOverlay,
|
||||
deleteOverlay,
|
||||
} from './overlayApi';
|
||||
|
||||
// URL 中读取 templateId:editor.html?templateId=xxx
|
||||
function getTemplateId(): string {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
return params.get('templateId') ?? '';
|
||||
}
|
||||
|
||||
function getToken(): string | null {
|
||||
try {
|
||||
return localStorage.getItem('eip4_token');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type ToastType = 'success' | 'error' | 'info';
|
||||
|
||||
interface ToastMsg {
|
||||
type: ToastType;
|
||||
text: string;
|
||||
id: number;
|
||||
}
|
||||
|
||||
let _toastId = 0;
|
||||
|
||||
// ============ 简单 Toast ============
|
||||
function Toast({ msgs, onRemove }: { msgs: ToastMsg[]; onRemove: (id: number) => void }) {
|
||||
return (
|
||||
<div style={{ position: 'fixed', top: 12, right: 16, zIndex: 9999, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{msgs.map((m) => (
|
||||
<div
|
||||
key={m.id}
|
||||
data-testid={`designer-toast-${m.type}`}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: 4,
|
||||
background: m.type === 'success' ? '#52c41a' : m.type === 'error' ? '#ff4d4f' : '#1890ff',
|
||||
color: '#fff',
|
||||
minWidth: 200,
|
||||
maxWidth: 360,
|
||||
boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13,
|
||||
}}
|
||||
onClick={() => onRemove(m.id)}
|
||||
>
|
||||
{m.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ============ 顶部工具条 ============
|
||||
interface TopbarProps {
|
||||
templateId: string;
|
||||
layer: 'overlay' | 'standard' | null;
|
||||
standardEtag: string;
|
||||
saving: boolean;
|
||||
restoring: boolean;
|
||||
onSave: () => void;
|
||||
onRestore: () => void;
|
||||
onPreview: () => void;
|
||||
}
|
||||
|
||||
function Topbar({ templateId, layer, standardEtag, saving, restoring, onSave, onRestore, onPreview }: TopbarProps) {
|
||||
return (
|
||||
<div
|
||||
data-testid="designer-topbar"
|
||||
style={{
|
||||
height: 48,
|
||||
background: '#001529',
|
||||
color: '#fff',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
padding: '0 16px',
|
||||
gap: 12,
|
||||
flexShrink: 0,
|
||||
zIndex: 100,
|
||||
}}
|
||||
>
|
||||
<span style={{ fontWeight: 600, fontSize: 15, marginRight: 8 }}>
|
||||
页面设计器
|
||||
</span>
|
||||
<span style={{ fontSize: 12, color: '#8c99a8', flex: 1 }}>
|
||||
模板 ID:{templateId}
|
||||
{layer === 'overlay' && (
|
||||
<span
|
||||
data-testid="designer-overlay-badge"
|
||||
style={{ marginLeft: 8, background: '#faad14', color: '#000', borderRadius: 10, padding: '1px 8px', fontSize: 11 }}
|
||||
>
|
||||
当前编辑的是定制版(基于标准版 {standardEtag.slice(0, 8)})
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
data-testid="designer-btn-save"
|
||||
disabled={saving}
|
||||
onClick={onSave}
|
||||
style={btnStyle('#1890ff', saving)}
|
||||
>
|
||||
{saving ? '保存中…' : '保存'}
|
||||
</button>
|
||||
<button
|
||||
data-testid="designer-btn-restore"
|
||||
disabled={restoring}
|
||||
onClick={onRestore}
|
||||
style={btnStyle('#faad14', restoring)}
|
||||
>
|
||||
{restoring ? '还原中…' : '还原标准版'}
|
||||
</button>
|
||||
<button
|
||||
data-testid="designer-btn-preview"
|
||||
onClick={onPreview}
|
||||
style={btnStyle('#52c41a', false)}
|
||||
>
|
||||
预览
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function btnStyle(bg: string, disabled: boolean): React.CSSProperties {
|
||||
return {
|
||||
background: disabled ? '#888' : bg,
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
padding: '5px 14px',
|
||||
cursor: disabled ? 'not-allowed' : 'pointer',
|
||||
fontSize: 13,
|
||||
fontWeight: 500,
|
||||
};
|
||||
}
|
||||
|
||||
// ============ 主组件 ============
|
||||
export function DesignerPage() {
|
||||
const templateId = getTemplateId();
|
||||
|
||||
const [schema, setSchema] = useState<Record<string, unknown> | null>(null);
|
||||
const [layer, setLayer] = useState<'overlay' | 'standard' | null>(null);
|
||||
const [standardEtag, setStandardEtag] = useState('');
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [restoring, setRestoring] = useState(false);
|
||||
const [toasts, setToasts] = useState<ToastMsg[]>([]);
|
||||
|
||||
// 当前编辑的 schema(amis-editor onChange 回调更新)
|
||||
const currentSchemaRef = useRef<Record<string, unknown> | null>(null);
|
||||
|
||||
const toast = useCallback((type: ToastType, text: string) => {
|
||||
const id = ++_toastId;
|
||||
setToasts((prev) => [...prev, { type, text, id }]);
|
||||
setTimeout(() => setToasts((prev) => prev.filter((m) => m.id !== id)), 3500);
|
||||
}, []);
|
||||
|
||||
const removeToast = useCallback((id: number) => {
|
||||
setToasts((prev) => prev.filter((m) => m.id !== id));
|
||||
}, []);
|
||||
|
||||
// 检查登录态
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
setLoadError('未登录,请先登录后打开设计器');
|
||||
return;
|
||||
}
|
||||
if (!templateId) {
|
||||
setLoadError('缺少 templateId 参数(URL 应包含 ?templateId=xxx)');
|
||||
return;
|
||||
}
|
||||
// 加载标准层 etag(供 badge 提示对比)
|
||||
fetchStandardSchema(templateId)
|
||||
.then(({ etag }) => setStandardEtag(etag))
|
||||
.catch(() => {});
|
||||
|
||||
// 加载 overlay 优先 schema
|
||||
fetchSchemaWithLayer(templateId)
|
||||
.then(({ schema: s, layer: l }) => {
|
||||
setSchema(s);
|
||||
setLayer(l);
|
||||
currentSchemaRef.current = s;
|
||||
})
|
||||
.catch((e: Error) => setLoadError(e.message ?? '加载 schema 失败'));
|
||||
}, [templateId]);
|
||||
|
||||
// amis-editor onChange
|
||||
const handleChange = useCallback((value: Record<string, unknown>) => {
|
||||
currentSchemaRef.current = value;
|
||||
}, []);
|
||||
|
||||
// 保存 overlay
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!currentSchemaRef.current) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const json = JSON.stringify(currentSchemaRef.current);
|
||||
const result = await saveOverlay(templateId, json);
|
||||
if (result.status === 0) {
|
||||
setLayer('overlay');
|
||||
toast('success', '保存成功(overlay 已更新)');
|
||||
} else {
|
||||
toast('error', '保存失败:' + result.msg);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
toast('error', '保存失败:' + String(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [templateId, toast]);
|
||||
|
||||
// 还原标准版
|
||||
const handleRestore = useCallback(async () => {
|
||||
setRestoring(true);
|
||||
try {
|
||||
const result = await deleteOverlay(templateId);
|
||||
if (result.status === 0) {
|
||||
// 重新加载标准层 schema
|
||||
const { schema: s, layer: l } = await fetchSchemaWithLayer(templateId);
|
||||
setSchema(s);
|
||||
setLayer(l);
|
||||
currentSchemaRef.current = s;
|
||||
toast('success', '已还原标准版');
|
||||
} else {
|
||||
toast('error', '还原失败:' + result.msg);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
toast('error', '还原失败:' + String(e));
|
||||
} finally {
|
||||
setRestoring(false);
|
||||
}
|
||||
}, [templateId, toast]);
|
||||
|
||||
// 预览(新 Tab 打开 /page/:templateId)
|
||||
const handlePreview = useCallback(() => {
|
||||
window.open(`/page/${encodeURIComponent(templateId)}`, '_blank');
|
||||
}, [templateId]);
|
||||
|
||||
// 错误/加载状态
|
||||
if (loadError) {
|
||||
return (
|
||||
<div
|
||||
data-testid="designer-error"
|
||||
style={{ padding: 40, color: '#a94442', background: '#fff5f5', minHeight: '100vh' }}
|
||||
>
|
||||
<h2>设计器加载失败</h2>
|
||||
<p>{loadError}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!schema) {
|
||||
return (
|
||||
<div
|
||||
data-testid="designer-loading"
|
||||
style={{ padding: 40, color: '#888', minHeight: '100vh' }}
|
||||
>
|
||||
加载设计器中…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="designer-root"
|
||||
style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden' }}
|
||||
>
|
||||
<Topbar
|
||||
templateId={templateId}
|
||||
layer={layer}
|
||||
standardEtag={standardEtag}
|
||||
saving={saving}
|
||||
restoring={restoring}
|
||||
onSave={handleSave}
|
||||
onRestore={handleRestore}
|
||||
onPreview={handlePreview}
|
||||
/>
|
||||
<div style={{ flex: 1, overflow: 'hidden' }}>
|
||||
{/* amis-editor 期望 SchemaObject 类型,但 schema 本就是动态 JSON,any 断言可接受 */}
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
<Editor
|
||||
value={schema as any}
|
||||
onChange={handleChange as any}
|
||||
theme="cxd"
|
||||
preview={false}
|
||||
/>
|
||||
</div>
|
||||
<Toast msgs={toasts} onRemove={removeToast} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
14
src/editor/main.tsx
Normal file
14
src/editor/main.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
// F4-L1 设计器独立入口(editor.html 多页应用)
|
||||
// 与主应用 React 实例完全隔离,amis 用 npm 包版,不依赖 sdk-local
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { DesignerPage } from './DesignerPage';
|
||||
|
||||
const root = document.getElementById('editor-root');
|
||||
if (root) {
|
||||
createRoot(root).render(
|
||||
<React.StrictMode>
|
||||
<DesignerPage />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
}
|
||||
71
src/editor/overlayApi.ts
Normal file
71
src/editor/overlayApi.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
// ============================================================================
|
||||
// F4-L1 overlay API —— 设计器专用,独立 axios 实例(不依赖主应用 http)
|
||||
// ============================================================================
|
||||
import axios from 'axios';
|
||||
|
||||
function getToken(): string | null {
|
||||
try {
|
||||
return localStorage.getItem('eip4_token');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const overlayHttp = axios.create({ baseURL: '/', timeout: 30000 });
|
||||
|
||||
overlayHttp.interceptors.request.use((cfg) => {
|
||||
const t = getToken();
|
||||
if (t) cfg.headers.set('Authorization', `Bearer ${t}`);
|
||||
return cfg;
|
||||
});
|
||||
|
||||
/** 取 schema(overlay 优先)。返回 {schema, layer, etag} */
|
||||
export async function fetchSchemaWithLayer(templateId: string): Promise<{
|
||||
schema: Record<string, unknown>;
|
||||
layer: 'overlay' | 'standard';
|
||||
etag: string;
|
||||
}> {
|
||||
const resp = await overlayHttp.get<Record<string, unknown>>(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}`,
|
||||
{ headers: { 'Cache-Control': 'no-cache' } },
|
||||
);
|
||||
const layer = (resp.headers['x-schema-layer'] ?? 'standard') as 'overlay' | 'standard';
|
||||
const etag = (resp.headers['etag'] ?? '').replace(/"/g, '');
|
||||
return { schema: resp.data, layer, etag };
|
||||
}
|
||||
|
||||
/** 取标准层 schema(?layer=standard)。返回 {schema, etag} */
|
||||
export async function fetchStandardSchema(templateId: string): Promise<{
|
||||
schema: Record<string, unknown>;
|
||||
etag: string;
|
||||
}> {
|
||||
const resp = await overlayHttp.get<Record<string, unknown>>(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}?layer=standard`,
|
||||
{ headers: { 'Cache-Control': 'no-cache' } },
|
||||
);
|
||||
const etag = (resp.headers['etag'] ?? '').replace(/"/g, '');
|
||||
return { schema: resp.data, etag };
|
||||
}
|
||||
|
||||
/** 保存 overlay(PUT)。返回 {status, data:{templateId,etag,baseEtag}} */
|
||||
export async function saveOverlay(
|
||||
templateId: string,
|
||||
schemaJson: string,
|
||||
): Promise<{ status: number; msg: string; data?: { templateId: string; etag: string; baseEtag: string } }> {
|
||||
const resp = await overlayHttp.put(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}/overlay`,
|
||||
schemaJson,
|
||||
{ headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
return resp.data as { status: number; msg: string; data?: { templateId: string; etag: string; baseEtag: string } };
|
||||
}
|
||||
|
||||
/** 还原标准版(DELETE overlay)。返回 {status, msg} */
|
||||
export async function deleteOverlay(
|
||||
templateId: string,
|
||||
): Promise<{ status: number; msg: string }> {
|
||||
const resp = await overlayHttp.delete(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}/overlay`,
|
||||
);
|
||||
return resp.data as { status: number; msg: string };
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// 页面渲染路由 /page/:templateId —— 取转换后 schema 交 amis 渲染
|
||||
// F1-4:加错误边界(schema 拉取失败/JSON 异常/amis 渲染抛错均显示页内错误卡片)
|
||||
// F4-L1:管理员可见「设计」按钮,打开设计器(editor.html 多页入口)
|
||||
import { Component, useEffect, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
@@ -7,6 +8,7 @@ import { fetchSchema } from '../api/schema';
|
||||
import { AmisRenderer } from '../components/AmisRenderer';
|
||||
import { recordRecentPage } from '../utils/recentPages';
|
||||
import { useTabTitle } from '../shell/TabTitleContext';
|
||||
import { getProfile } from '../auth/token';
|
||||
|
||||
// ---- amis 渲染层错误边界(class component,捕获子树抛错)----
|
||||
interface ErrorBoundaryState {
|
||||
@@ -69,6 +71,36 @@ function SchemaErrorCard({ templateId, summary }: { templateId: string; summary:
|
||||
);
|
||||
}
|
||||
|
||||
// ---- 管理员设计按钮 ----
|
||||
function DesignButton({ templateId }: { templateId: string }) {
|
||||
const profile = getProfile();
|
||||
const isAdmin = profile?.account === 'admin' || profile?.userId === 'ADMIN';
|
||||
if (!isAdmin) return null;
|
||||
return (
|
||||
<button
|
||||
data-testid="designer-open-btn"
|
||||
onClick={() => window.open(`/editor.html?templateId=${encodeURIComponent(templateId)}`, '_blank')}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 8,
|
||||
right: 12,
|
||||
zIndex: 10,
|
||||
background: '#1890ff',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
padding: '4px 12px',
|
||||
cursor: 'pointer',
|
||||
fontSize: 12,
|
||||
fontWeight: 500,
|
||||
opacity: 0.85,
|
||||
}}
|
||||
>
|
||||
设计
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- 主组件 ----
|
||||
export function PageRenderPage() {
|
||||
const { templateId = '' } = useParams();
|
||||
@@ -114,7 +146,8 @@ export function PageRenderPage() {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div style={{ height: '100%' }} data-testid="amis-host">
|
||||
<div style={{ height: '100%', position: 'relative' }} data-testid="amis-host">
|
||||
<DesignButton templateId={templateId} />
|
||||
<AmisErrorBoundary templateId={templateId}>
|
||||
<AmisRenderer schema={schema} />
|
||||
</AmisErrorBoundary>
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { resolve } from 'path';
|
||||
|
||||
// 开发期 dev server 把 /api 反代到后端(默认 8084,端口被占时改 8090)。
|
||||
// 后端地址经 .env 的 VITE_BACKEND_TARGET 配置;生产由 Nginx 反代,前端只发相对 /api。
|
||||
//
|
||||
// F4-L1 多页应用(MPA):
|
||||
// index.html → 主应用(amis sdk-local UMD)
|
||||
// editor.html → 设计器(amis npm 包,与主应用隔离)
|
||||
//
|
||||
// amis 栈(amis/amis-editor/amis-editor-core/amis-ui/amis-core/amis-formula/i18n-runtime)
|
||||
// 均为 webpack 产物,package.json 无 exports 字段,vite esbuild pre-bundle 会失败。
|
||||
// 解法:optimizeDeps.exclude 排出这些包,让 vite 对它们走 native CJS → ESM 转换;
|
||||
// resolve.alias 把 i18n-runtime 直接指向 lib/index.js(无 exports 字段的包需要手动指向)。
|
||||
// CSS 由 editor.html <link> 直接引用 /node_modules/... 路径,server.fs.allow 放开目录。
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '');
|
||||
const backendTarget = env.VITE_BACKEND_TARGET || 'http://localhost:8084';
|
||||
return {
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
// i18n-runtime 无 exports 字段,vite pre-bundle 无法找到入口;手动指向 lib/index.js
|
||||
'i18n-runtime': resolve(__dirname, 'node_modules/i18n-runtime/lib/index.js'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
@@ -16,11 +33,53 @@ export default defineConfig(({ mode }) => {
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
// 允许 vite dev server 服务 node_modules 下的静态文件(editor.html 的 CSS link)
|
||||
fs: {
|
||||
allow: ['..'],
|
||||
},
|
||||
},
|
||||
build: {
|
||||
// 产物直接交 Nginx 托管;amis 本地 SDK 在 public/ 下原样拷贝,不参与打包。
|
||||
outDir: 'dist',
|
||||
sourcemap: false,
|
||||
rollupOptions: {
|
||||
input: {
|
||||
main: resolve(__dirname, 'index.html'),
|
||||
editor: resolve(__dirname, 'editor.html'),
|
||||
},
|
||||
},
|
||||
},
|
||||
optimizeDeps: {
|
||||
// amis 系列包及其 CJS 传递依赖全部显式 include,让 vite esbuild 统一预构建为 ESM。
|
||||
// 不用 exclude——exclude 会让传递依赖(如 remove-accents)跳过 CJS→ESM 转换,
|
||||
// 导致 "does not provide an export named 'default'" 运行时错误。
|
||||
include: [
|
||||
'amis',
|
||||
'amis-editor',
|
||||
'amis-editor-core',
|
||||
'amis-ui',
|
||||
'amis-core',
|
||||
'amis-formula',
|
||||
'amis-theme-editor-helper',
|
||||
'remove-accents',
|
||||
'classnames',
|
||||
'lodash',
|
||||
'hoist-non-react-statics',
|
||||
'react-is',
|
||||
'prop-types',
|
||||
'qs',
|
||||
'file-saver',
|
||||
'papaparse',
|
||||
'ua-parser-js',
|
||||
'immutability-helper',
|
||||
'dayjs',
|
||||
'moment',
|
||||
'codemirror',
|
||||
'markdown-it',
|
||||
'jsbarcode',
|
||||
'keycode',
|
||||
'deep-diff',
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user