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:
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user