feat: P4-3 eip4-web 前端渲染宿主脚手架(amis 6.13.0 本地化/登录JWT/待办/双闸渲染闸)
- 脚手架:React 18 + Vite 5 + TS;amis 6.13.0 本地 SDK(public/sdk-local,不依赖 CDN,
照 PoC amis-local.html 范式 amisRequire('amis/embed'))
- 登录页:POST /api/auth/login + JWT 存储(内存+localStorage 折中,XSS 权衡见 README/token.ts)
- 页面渲染 /page/:templateId:取转换后 schema 渲染;开发期静态 mock(public/schemas/ 放
角色维护/通知管理归档/用户组管理 3 个真实转换产物,均过官方 schema.json 校验闸);
生产期 schema 接口契约已设计(VITE_SCHEMA_SOURCE 切换)
- 待办页 /todo:GET /api/todo + 503 熔断降级展示
- amis fetcher 适配:复用宿主 axios 注入 Bearer,对接 /api/entity amis CRUD 格式
- axios 拦截器:Bearer 注入 + 401 清会话跳登录
- 联调验证(playwright 无头):登录跳转→渲染用户组(本地库 3 行)→角色维护(真实产物)→
待办 503 降级→401 跳登录(prod 严格链 8090),5 张截图留 docs/
- 工程化:npm run build → dist/(应用 208KB/gzip 71KB + 本地 SDK 61MB,Nginx 可托管);
README/报告/gitignore
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
50
src/App.tsx
Normal file
50
src/App.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { useEffect } from 'react';
|
||||
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from 'react-router-dom';
|
||||
import { setUnauthorizedHandler } from './api/http';
|
||||
import { AppLayout } from './components/AppLayout';
|
||||
import { RequireAuth } from './components/RequireAuth';
|
||||
import { LoginPage } from './pages/LoginPage';
|
||||
import { PageRenderPage } from './pages/PageRenderPage';
|
||||
import { TodoPage } from './pages/TodoPage';
|
||||
|
||||
// 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate)
|
||||
function UnauthorizedBridge() {
|
||||
const navigate = useNavigate();
|
||||
useEffect(() => {
|
||||
setUnauthorizedHandler(() => navigate('/login', { replace: true }));
|
||||
}, [navigate]);
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<UnauthorizedBridge />
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="/page/:templateId"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<AppLayout>
|
||||
<PageRenderPage />
|
||||
</AppLayout>
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/todo"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<AppLayout>
|
||||
<TodoPage />
|
||||
</AppLayout>
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
<Route path="/" element={<Navigate to="/page/usergroup-manage" replace />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
28
src/api/auth.ts
Normal file
28
src/api/auth.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
// 登录 API —— POST /api/auth/login(契约见 P2 认证实测报告)
|
||||
import { http } from './http';
|
||||
import type { UserProfile } from '../auth/token';
|
||||
|
||||
export interface LoginResponse {
|
||||
success: boolean;
|
||||
msg?: string;
|
||||
token: string;
|
||||
expireSeconds: number;
|
||||
userId: string;
|
||||
account: string;
|
||||
name: string;
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
export async function login(account: string, password: string): Promise<LoginResponse> {
|
||||
const { data } = await http.post<LoginResponse>('/api/auth/login', { account, password });
|
||||
return data;
|
||||
}
|
||||
|
||||
export function toProfile(resp: LoginResponse): UserProfile {
|
||||
return {
|
||||
userId: resp.userId,
|
||||
account: resp.account,
|
||||
name: resp.name,
|
||||
roles: resp.roles ?? [],
|
||||
};
|
||||
}
|
||||
42
src/api/http.ts
Normal file
42
src/api/http.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
// ============================================================================
|
||||
// axios 实例 —— 请求注入 Bearer + 响应 401 统一跳登录
|
||||
// 后端契约(P2 认证实测报告):Authorization: Bearer <jwt>;未认证/伪造/过期 → 401。
|
||||
// 生产由 Nginx 反代 /api 到后端;开发期由 vite proxy 反代(见 vite.config.ts)。
|
||||
// ============================================================================
|
||||
import axios, { AxiosError, type InternalAxiosRequestConfig } from 'axios';
|
||||
import { clearSession, getToken } from '../auth/token';
|
||||
|
||||
// 401 处理回调由应用层(路由)注入,避免 http 层硬依赖 react-router。
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
export function setUnauthorizedHandler(handler: () => void): void {
|
||||
onUnauthorized = handler;
|
||||
}
|
||||
|
||||
export const http = axios.create({
|
||||
baseURL: '/',
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// 请求拦截:带令牌时注入 Bearer 头
|
||||
http.interceptors.request.use((config: InternalAxiosRequestConfig) => {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
config.headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// 响应拦截:401 → 清会话 + 跳登录(登录端点自身的 401 不触发跳转,由调用方处理错误文案)
|
||||
http.interceptors.response.use(
|
||||
(resp) => resp,
|
||||
(error: AxiosError) => {
|
||||
const status = error.response?.status;
|
||||
const url = error.config?.url ?? '';
|
||||
const isLoginCall = url.includes('/api/auth/login');
|
||||
if (status === 401 && !isLoginCall) {
|
||||
clearSession();
|
||||
if (onUnauthorized) onUnauthorized();
|
||||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
56
src/api/schema.ts
Normal file
56
src/api/schema.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
// ============================================================================
|
||||
// 页面 schema 获取 —— 双源(开发期静态 mock / 生产期后端接口)
|
||||
// ----------------------------------------------------------------------------
|
||||
// templateId → schema 映射:
|
||||
// - 开发期(VITE_SCHEMA_SOURCE 缺省或 'mock'):读 public/schemas/<id>.json
|
||||
// (内容是 eip4-poc 转换器对客户库真实模板的转换产物,已过官方 schema.json 校验闸)。
|
||||
// - 生产期(VITE_SCHEMA_SOURCE='backend'):读后端 schema 接口(契约见下)。
|
||||
//
|
||||
// 生产期后端 schema 接口契约(本期为设计,后端 P5 落地):
|
||||
// GET /api/page/schema/{templateId}
|
||||
// 响应:200 直接返回 amis 页面 schema(JSON,顶层 type:'page'),
|
||||
// 由后端在「校验闸」通过后下发(官方 schema.json 校验,见迁移手册 §8 双闸)。
|
||||
// 404:模板不存在;503:转换器不可用。
|
||||
// 鉴权:带 Bearer(由 http 拦截器注入)。
|
||||
// ============================================================================
|
||||
import { http } from './http';
|
||||
|
||||
const SOURCE = (import.meta.env.VITE_SCHEMA_SOURCE as string) || 'mock';
|
||||
|
||||
// 开发期 mock:templateId → public/schemas 文件名
|
||||
const MOCK_MAP: Record<string, string> = {
|
||||
'role-maintain': '/schemas/role-maintain.json',
|
||||
'notice-archive': '/schemas/notice-archive.json',
|
||||
'usergroup-manage': '/schemas/usergroup-manage.json',
|
||||
};
|
||||
|
||||
export interface PageMeta {
|
||||
id: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
// 开发期可选页面清单(供页面入口展示导航)
|
||||
export const MOCK_PAGES: PageMeta[] = [
|
||||
{ id: 'usergroup-manage', title: '用户组管理(本地实体联调)' },
|
||||
{ id: 'role-maintain', title: '角色维护(真实转换产物)' },
|
||||
{ id: 'notice-archive', title: '通知管理归档(真实转换产物)' },
|
||||
];
|
||||
|
||||
export async function fetchSchema(templateId: string): Promise<Record<string, unknown>> {
|
||||
if (SOURCE === 'backend') {
|
||||
const { data } = await http.get<Record<string, unknown>>(
|
||||
`/api/page/schema/${encodeURIComponent(templateId)}`,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
// 开发期静态 mock
|
||||
const path = MOCK_MAP[templateId];
|
||||
if (!path) {
|
||||
throw new Error(`未知模板:${templateId}(开发期 mock 未配置)`);
|
||||
}
|
||||
const resp = await fetch(path);
|
||||
if (!resp.ok) {
|
||||
throw new Error(`加载 schema 失败:${resp.status}`);
|
||||
}
|
||||
return (await resp.json()) as Record<string, unknown>;
|
||||
}
|
||||
44
src/api/todo.ts
Normal file
44
src/api/todo.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// 待办聚合 API —— GET /api/todo(契约见 P3 网关实测报告)
|
||||
// 引擎(flowable-service)不可达时网关返回 503 FLOW_SERVICE_UNAVAILABLE;前端据此降级展示。
|
||||
import { http } from './http';
|
||||
|
||||
export interface TodoItem {
|
||||
taskId?: string;
|
||||
taskName?: string;
|
||||
assignee?: string;
|
||||
businessKey?: string;
|
||||
businessTable?: string | null;
|
||||
businessSummary?: Record<string, unknown>;
|
||||
createTime?: string;
|
||||
processInstanceId?: string;
|
||||
// 兜底:后端字段命名可能小幅差异,保留透传
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface TodoResult {
|
||||
items: TodoItem[];
|
||||
/** 503 熔断降级标记:true 表示工作流引擎暂不可达 */
|
||||
unavailable: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export async function fetchTodo(firstResult = 0, maxResults = 20): Promise<TodoResult> {
|
||||
try {
|
||||
const { data } = await http.get<TodoItem[] | { items: TodoItem[] }>('/api/todo', {
|
||||
params: { firstResult, maxResults },
|
||||
});
|
||||
// 网关返回数组(P3 报告示例为列表);兼容 {items:[]} 包裹形态
|
||||
const items = Array.isArray(data) ? data : (data?.items ?? []);
|
||||
return { items, unavailable: false };
|
||||
} catch (err) {
|
||||
const e = err as { response?: { status?: number; data?: { message?: string; error?: string } } };
|
||||
if (e.response?.status === 503) {
|
||||
return {
|
||||
items: [],
|
||||
unavailable: true,
|
||||
message: e.response.data?.message || '工作流引擎服务暂不可达,请稍后重试',
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
74
src/auth/token.ts
Normal file
74
src/auth/token.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
// ============================================================================
|
||||
// JWT 令牌存储 —— 内存 + localStorage 折中方案
|
||||
// ----------------------------------------------------------------------------
|
||||
// 权衡(XSS vs 刷新留存):
|
||||
// - 纯内存:最抗 XSS(脚本注入也读不到跨标签持久令牌),但刷新即丢失,体验差。
|
||||
// - 纯 localStorage:刷新留存,但任意 XSS 脚本可读取令牌 → 失窃风险高。
|
||||
// - httpOnly Cookie:最抗 XSS(JS 读不到),但需后端配合 Set-Cookie + CSRF 防护,
|
||||
// 当前后端契约是「Authorization: Bearer」头(P2 报告),不下发 Cookie,故本期不用。
|
||||
// 本期折中:运行内存为权威副本(请求注入用内存),localStorage 仅作刷新后的恢复源。
|
||||
// - 收益:刷新不掉登录态。
|
||||
// - 残留风险:XSS 仍可读 localStorage —— 缓解项见 README「安全权衡」:
|
||||
// 生产建议短有效期 + 后端轮转 + CSP 限制脚本来源;长期演进到 httpOnly Cookie + 刷新令牌。
|
||||
// ============================================================================
|
||||
|
||||
const STORAGE_KEY = 'eip4_token';
|
||||
const PROFILE_KEY = 'eip4_profile';
|
||||
|
||||
export interface UserProfile {
|
||||
userId: string;
|
||||
account: string;
|
||||
name: string;
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
// 内存权威副本(请求注入读这里,避免每次同步访问 localStorage)
|
||||
let memoryToken: string | null = null;
|
||||
let memoryProfile: UserProfile | null = null;
|
||||
|
||||
export function setSession(token: string, profile: UserProfile): void {
|
||||
memoryToken = token;
|
||||
memoryProfile = profile;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, token);
|
||||
localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
|
||||
} catch {
|
||||
// localStorage 不可用(隐私模式等)时退化为纯内存,登录态随刷新丢失,不阻断功能。
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
if (memoryToken) return memoryToken;
|
||||
try {
|
||||
memoryToken = localStorage.getItem(STORAGE_KEY);
|
||||
} catch {
|
||||
memoryToken = null;
|
||||
}
|
||||
return memoryToken;
|
||||
}
|
||||
|
||||
export function getProfile(): UserProfile | null {
|
||||
if (memoryProfile) return memoryProfile;
|
||||
try {
|
||||
const raw = localStorage.getItem(PROFILE_KEY);
|
||||
memoryProfile = raw ? (JSON.parse(raw) as UserProfile) : null;
|
||||
} catch {
|
||||
memoryProfile = null;
|
||||
}
|
||||
return memoryProfile;
|
||||
}
|
||||
|
||||
export function clearSession(): void {
|
||||
memoryToken = null;
|
||||
memoryProfile = null;
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
localStorage.removeItem(PROFILE_KEY);
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return !!getToken();
|
||||
}
|
||||
67
src/components/AmisRenderer.tsx
Normal file
67
src/components/AmisRenderer.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
// ============================================================================
|
||||
// AmisRenderer —— 本地 SDK(amisRequire('amis/embed'))渲染宿主
|
||||
// ----------------------------------------------------------------------------
|
||||
// 双闸「渲染闸」前端承接点:
|
||||
// schema 进入前已过「校验闸」(官方 schema.json,后端/转换器侧);
|
||||
// 本组件用 amis 真实 SDK 渲染 = 运行时渲染冒烟,渲染异常即闸失败。
|
||||
// fetcher 适配:
|
||||
// amis 内置 fetcher 直接发 schema 里的 api(如 /api/entity/SYS_USERGROUP/list)。
|
||||
// 此处替换为自定义 fetcher,统一注入 Bearer(由 http 拦截器完成)并复用宿主 axios,
|
||||
// 后端 /api/entity 已是 amis CRUD 格式 {status,msg,data:{items,total}},无需再适配响应。
|
||||
// ============================================================================
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { http } from '../api/http';
|
||||
|
||||
interface AmisRendererProps {
|
||||
schema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// amis fetcher 入参(简化,贴 amis SDK 的 fetcherConfig 形态)
|
||||
interface AmisFetcherOptions {
|
||||
url: string;
|
||||
method?: string;
|
||||
data?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
responseType?: string;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function AmisRenderer({ schema }: AmisRendererProps) {
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const instanceRef = useRef<{ unmount?: () => void } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!rootRef.current || typeof amisRequire !== 'function') return;
|
||||
|
||||
const amis = amisRequire('amis/embed');
|
||||
|
||||
// 自定义 fetcher:复用宿主 axios(已带 Bearer 注入 + 401 跳登录拦截)
|
||||
const fetcher = (options: AmisFetcherOptions) => {
|
||||
const { url, method = 'get', data, responseType } = options;
|
||||
const m = method.toLowerCase();
|
||||
if (m === 'get') {
|
||||
return http.get(url, { responseType: responseType as never });
|
||||
}
|
||||
return http.request({ url, method: m as never, data, responseType: responseType as never });
|
||||
};
|
||||
|
||||
const instance = amis.embed(
|
||||
rootRef.current,
|
||||
schema,
|
||||
{},
|
||||
{
|
||||
fetcher,
|
||||
// 与后端 amis CRUD 约定对齐:status===0 为成功
|
||||
isCancel: (e: unknown) => (http as unknown as { isCancel?: (x: unknown) => boolean }).isCancel?.(e) ?? false,
|
||||
},
|
||||
);
|
||||
instanceRef.current = instance;
|
||||
|
||||
return () => {
|
||||
instanceRef.current?.unmount?.();
|
||||
instanceRef.current = null;
|
||||
};
|
||||
}, [schema]);
|
||||
|
||||
return <div ref={rootRef} style={{ height: '100%' }} />;
|
||||
}
|
||||
61
src/components/AppLayout.tsx
Normal file
61
src/components/AppLayout.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
// 登录后的应用外壳:顶栏(品牌 + 导航 + 当前用户 + 登出)+ 内容区
|
||||
import { type ReactNode } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { clearSession, getProfile } from '../auth/token';
|
||||
import { MOCK_PAGES } from '../api/schema';
|
||||
|
||||
export function AppLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const profile = getProfile();
|
||||
|
||||
const logout = () => {
|
||||
clearSession();
|
||||
navigate('/login', { replace: true });
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<header
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 16,
|
||||
padding: '0 20px',
|
||||
height: 52,
|
||||
background: '#1f2d3d',
|
||||
color: '#fff',
|
||||
flex: '0 0 auto',
|
||||
}}
|
||||
>
|
||||
<strong style={{ fontSize: 16 }}>EIP4 渲染宿主</strong>
|
||||
<nav style={{ display: 'flex', gap: 12, fontSize: 14 }}>
|
||||
<Link to="/todo" style={{ color: '#cfe3ff' }}>
|
||||
待办
|
||||
</Link>
|
||||
{MOCK_PAGES.map((p) => (
|
||||
<Link key={p.id} to={`/page/${p.id}`} style={{ color: '#cfe3ff' }}>
|
||||
{p.title.split('(')[0]}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<span style={{ marginLeft: 'auto', fontSize: 13, opacity: 0.85 }}>
|
||||
{profile ? `${profile.name}(${profile.account})` : '未登录'}
|
||||
</span>
|
||||
<button
|
||||
onClick={logout}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: '1px solid #6c7a89',
|
||||
color: '#fff',
|
||||
borderRadius: 4,
|
||||
padding: '4px 10px',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
登出
|
||||
</button>
|
||||
</header>
|
||||
<main style={{ flex: '1 1 auto', overflow: 'auto', background: '#f5f6f7' }}>{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
12
src/components/RequireAuth.tsx
Normal file
12
src/components/RequireAuth.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
// 路由守卫:未登录跳 /login,回跳记录来源路径
|
||||
import { type ReactNode } from 'react';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { isAuthenticated } from '../auth/token';
|
||||
|
||||
export function RequireAuth({ children }: { children: ReactNode }) {
|
||||
const location = useLocation();
|
||||
if (!isAuthenticated()) {
|
||||
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
9
src/main.tsx
Normal file
9
src/main.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './App';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
112
src/pages/LoginPage.tsx
Normal file
112
src/pages/LoginPage.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
// 登录页:POST /api/auth/login → 存 JWT → 跳转
|
||||
import { type FormEvent, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { login, toProfile } from '../api/auth';
|
||||
import { setSession } from '../auth/token';
|
||||
|
||||
export function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const from = (location.state as { from?: string })?.from || '/page/usergroup-manage';
|
||||
|
||||
const [account, setAccount] = useState('alice');
|
||||
const [password, setPassword] = useState('123456');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const onSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const resp = await login(account.trim(), password);
|
||||
if (!resp.success || !resp.token) {
|
||||
setError(resp.msg || '登录失败');
|
||||
return;
|
||||
}
|
||||
setSession(resp.token, toProfile(resp));
|
||||
navigate(from, { replace: true });
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status;
|
||||
setError(status === 401 ? '账号或密码错误' : '登录请求失败,请检查后端服务');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: '#eef1f4',
|
||||
}}
|
||||
>
|
||||
<form
|
||||
onSubmit={onSubmit}
|
||||
style={{
|
||||
width: 340,
|
||||
padding: 32,
|
||||
background: '#fff',
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: '0 0 8px', color: '#1f2d3d' }}>EIP4 登录</h2>
|
||||
<p style={{ margin: '0 0 24px', color: '#888', fontSize: 13 }}>渲染宿主 · amis 6.13.0 本地化</p>
|
||||
|
||||
<label style={{ display: 'block', fontSize: 13, color: '#555', marginBottom: 6 }}>账号</label>
|
||||
<input
|
||||
value={account}
|
||||
onChange={(e) => setAccount(e.target.value)}
|
||||
autoComplete="username"
|
||||
style={inputStyle}
|
||||
/>
|
||||
|
||||
<label style={{ display: 'block', fontSize: 13, color: '#555', margin: '16px 0 6px' }}>密码</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
style={inputStyle}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div style={{ color: '#d9534f', fontSize: 13, marginTop: 12 }} role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button type="submit" disabled={loading} style={buttonStyle(loading)}>
|
||||
{loading ? '登录中…' : '登录'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
padding: '9px 12px',
|
||||
border: '1px solid #d4d7dc',
|
||||
borderRadius: 4,
|
||||
fontSize: 14,
|
||||
};
|
||||
|
||||
function buttonStyle(loading: boolean): React.CSSProperties {
|
||||
return {
|
||||
width: '100%',
|
||||
marginTop: 24,
|
||||
padding: '10px 0',
|
||||
background: loading ? '#7aa7e0' : '#2468f2',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
fontSize: 15,
|
||||
cursor: loading ? 'not-allowed' : 'pointer',
|
||||
};
|
||||
}
|
||||
39
src/pages/PageRenderPage.tsx
Normal file
39
src/pages/PageRenderPage.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
// 页面渲染路由 /page/:templateId —— 取转换后 schema 交 amis 渲染
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { fetchSchema } from '../api/schema';
|
||||
import { AmisRenderer } from '../components/AmisRenderer';
|
||||
|
||||
export function PageRenderPage() {
|
||||
const { templateId = '' } = useParams();
|
||||
const [schema, setSchema] = useState<Record<string, unknown> | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setSchema(null);
|
||||
setError('');
|
||||
fetchSchema(templateId)
|
||||
.then((s) => {
|
||||
if (alive) setSchema(s);
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (alive) setError(e.message);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [templateId]);
|
||||
|
||||
if (error) {
|
||||
return <div style={{ padding: 24, color: '#d9534f' }}>加载页面失败:{error}</div>;
|
||||
}
|
||||
if (!schema) {
|
||||
return <div style={{ padding: 24, color: '#888' }}>加载中…</div>;
|
||||
}
|
||||
return (
|
||||
<div style={{ height: '100%' }} data-testid="amis-host">
|
||||
<AmisRenderer schema={schema} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
114
src/pages/TodoPage.tsx
Normal file
114
src/pages/TodoPage.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
// 待办列表页 /todo —— 调 /api/todo,列表 + 点击进对应业务页占位
|
||||
// flowable-service 不起时网关 503,本页降级展示提示(不崩)。
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { fetchTodo, type TodoItem } from '../api/todo';
|
||||
|
||||
export function TodoPage() {
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<TodoItem[]>([]);
|
||||
const [unavailable, setUnavailable] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
fetchTodo()
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
setItems(r.items);
|
||||
setUnavailable(r.unavailable);
|
||||
setMessage(r.message || '');
|
||||
})
|
||||
.catch((e: Error) => alive && setError(e.message))
|
||||
.finally(() => alive && setLoading(false));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const openBusiness = (item: TodoItem) => {
|
||||
// 占位:按业务表跳对应业务页(本期无 表→templateId 映射表,跳通用占位并带参)
|
||||
const tpl = item.businessTable ? String(item.businessTable).toLowerCase() : 'usergroup-manage';
|
||||
navigate(`/page/${tpl}`, { state: { businessKey: item.businessKey } });
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2 style={{ marginTop: 0, color: '#1f2d3d' }}>我的待办</h2>
|
||||
|
||||
{loading && <div style={{ color: '#888' }}>加载中…</div>}
|
||||
|
||||
{!loading && unavailable && (
|
||||
<div
|
||||
data-testid="todo-degraded"
|
||||
style={{
|
||||
padding: 16,
|
||||
background: '#fff7e6',
|
||||
border: '1px solid #ffd591',
|
||||
borderRadius: 6,
|
||||
color: '#ad6800',
|
||||
}}
|
||||
>
|
||||
⚠ 工作流引擎暂不可达(网关 503 熔断降级):{message || '请稍后重试'}
|
||||
<div style={{ fontSize: 12, marginTop: 6, color: '#b08600' }}>
|
||||
单体侧待办聚合依赖 flowable-service;引擎宕机时本页降级,不影响其他页面。
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && <div style={{ color: '#d9534f' }}>请求失败:{error}</div>}
|
||||
|
||||
{!loading && !unavailable && !error && items.length === 0 && (
|
||||
<div style={{ color: '#888' }}>暂无待办。</div>
|
||||
)}
|
||||
|
||||
{!loading && items.length > 0 && (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', background: '#fff' }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#fafafa', textAlign: 'left' }}>
|
||||
<th style={thStyle}>任务名</th>
|
||||
<th style={thStyle}>业务摘要</th>
|
||||
<th style={thStyle}>业务表</th>
|
||||
<th style={thStyle}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((it, idx) => (
|
||||
<tr key={it.taskId || idx} style={{ borderTop: '1px solid #f0f0f0' }}>
|
||||
<td style={tdStyle}>{it.taskName || '-'}</td>
|
||||
<td style={tdStyle}>{summarize(it)}</td>
|
||||
<td style={tdStyle}>{it.businessTable || <span style={{ color: '#bbb' }}>(无映射)</span>}</td>
|
||||
<td style={tdStyle}>
|
||||
<button onClick={() => openBusiness(it)} style={linkBtnStyle}>
|
||||
打开
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function summarize(it: TodoItem): string {
|
||||
const s = it.businessSummary;
|
||||
if (s && typeof s === 'object') {
|
||||
const vals = Object.values(s).filter((v) => v != null && v !== '');
|
||||
if (vals.length) return vals.slice(0, 2).map(String).join(' / ');
|
||||
}
|
||||
return it.businessKey ? `businessKey:${it.businessKey}` : '-';
|
||||
}
|
||||
|
||||
const thStyle: React.CSSProperties = { padding: '10px 12px', fontSize: 13, color: '#555' };
|
||||
const tdStyle: React.CSSProperties = { padding: '10px 12px', fontSize: 13, color: '#333' };
|
||||
const linkBtnStyle: React.CSSProperties = {
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
color: '#2468f2',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13,
|
||||
};
|
||||
12
src/vite-env.d.ts
vendored
Normal file
12
src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
// amis 本地 SDK 经 index.html 的 <script> 注入全局 amisRequire(AMD 风格 require)。
|
||||
// 它不是 npm 模块,故在此声明全局,供 AmisRenderer 调用 amisRequire('amis/embed')。
|
||||
declare global {
|
||||
interface Window {
|
||||
amisRequire: (path: string) => any;
|
||||
}
|
||||
const amisRequire: (path: string) => any;
|
||||
}
|
||||
|
||||
export {};
|
||||
Reference in New Issue
Block a user