Files
eip4-web/src/components/AmisRenderer.tsx

116 lines
4.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ============================================================================
// 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, useState } from 'react';
import { http } from '../api/http';
import { APPROVAL_COMPLETED_EVENT } from '../amis/approvalActionEvents';
import { registerApprovalAction } from '../amis/registerApprovalAction';
import { registerReplayAction } from '../amis/registerReplayAction';
import { registerUserTransferPicker } from '../amis/registerUserTransferPicker';
import { getProfile } from '../auth/token';
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);
const [reloadSeq, setReloadSeq] = useState(0);
useEffect(() => {
const reload = () => setReloadSeq((n) => n + 1);
window.addEventListener(APPROVAL_COMPLETED_EVENT, reload);
return () => window.removeEventListener(APPROVAL_COMPLETED_EVENT, reload);
}, []);
useEffect(() => {
if (!rootRef.current || typeof amisRequire !== 'function') return;
const amis = amisRequire('amis/embed');
// P4-5:注册改写后脚本指令重放的自定义动作 replayScriptCommands。
// amis-core(含 registerAction/runActions)经 amisRequire('amis') 取得;注册幂等。
try {
registerReplayAction(amisRequire('amis'));
} catch {
// amis-core 未暴露 registerAction 时静默降级(onEvent 重放不可用,不阻断渲染)
}
try {
registerApprovalAction(amisRequire('amis'));
} catch {
// amis-core 未暴露 registerAction 时静默降级(审批抽屉入口不可用,不阻断渲染)
}
try {
registerUserTransferPicker(amisRequire('amis-core')) || registerUserTransferPicker(amisRequire('amis'));
} catch {
// amis-core 未暴露 registerRenderer 时静默降级,schema 会显示未知控件,测试会覆盖该问题。
}
// 自定义 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 });
};
// F2-9:注入当前用户 org 到 amis 数据域,供 select-tree source 中 ${orgId} 使用。
// §7-3:再注入 currentUser/currentProject/now,供转换器迁移的 initvalue 动态 token
// ({CURRENTUSER}/{CURRENTORG}/{CURRENTTIME}/{CURRENTPROJECT} → ${currentUser} 等)在表单初始化求值。
const profile = getProfile();
const pad = (n: number) => String(n).padStart(2, '0');
const d = new Date();
const now = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} `
+ `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const amisProps: Record<string, unknown> = { now };
if (profile?.org) {
amisProps.orgId = profile.org;
}
if (profile?.userId) {
amisProps.currentUser = profile.userId;
}
// currentProject 当前 profile 无此字段(会话级概念),注入空串使 ${currentProject} 求值为空而非裸 token
amisProps.currentProject = '';
const instance = amis.embed(
rootRef.current,
schema,
amisProps,
{
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, reloadSeq]);
return <div ref={rootRef} style={{ height: '100%' }} />;
}