P4-5: 前端改写后脚本指令 onEvent 重放胶水

AmisRenderer embed 前注册自定义 amis 动作 replayScriptCommands:
scriptCommands.translateCommands 把后端 facade 返回的 29 UI 动词指令
翻译成 amis 动作(show/hidden/static/setValue/setOptions/addOption/
toast/reload/...),逐条经 amis-core runActions 重放;带 componentId
者走组件级路由,componentId=大写列名与字段 name 天然对齐。

e2e(playwright,后端 8086 + dev):2 真实 FULL_AUTO facade-only 模板
- 福利保险结算单 inited → setFieldVisible 隐藏 BEGINDATE(截图留档)
- 办公用品领用申请 change → bindField(getFieldValue) 回填 OLD_STORE_ID
  (服务端 getFieldValue 从 item 求值闭环,截图留档),2 passed。

测试:vitest scriptCommands 12 + registerReplayAction 4;tsc+build 全绿。
工具链:devDeps 加 vitest/jsdom/testing-library/playwright + test script。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 16:56:04 +08:00
parent b3486c093e
commit 82e01f893a
17 changed files with 1788 additions and 4 deletions

View File

@@ -0,0 +1,65 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { registerReplayAction, __resetReplayActionForTest } from './registerReplayAction';
import type { ScriptCommand } from './scriptCommands';
// 自定义动作 run 的最小入参形态
interface RunCtx {
run: (action: { args?: { commands?: ScriptCommand[] } }, renderer: unknown, event: unknown) => Promise<void>;
}
describe('registerReplayAction', () => {
beforeEach(() => {
__resetReplayActionForTest();
});
it('amis-core 缺 registerAction 时返回 false(静默降级)', () => {
expect(registerReplayAction(null)).toBe(false);
expect(registerReplayAction({})).toBe(false);
});
it('注册 replayScriptCommands 动作(幂等)', () => {
const registerAction = vi.fn();
const core = { registerAction, runActions: vi.fn() };
expect(registerReplayAction(core)).toBe(true);
expect(registerAction).toHaveBeenCalledTimes(1);
expect(registerAction.mock.calls[0][0]).toBe('replayScriptCommands');
// 幂等:第二次不重复注册
expect(registerReplayAction(core)).toBe(true);
expect(registerAction).toHaveBeenCalledTimes(1);
});
it('run 把 commands 翻译后逐条经 runActions 重放', async () => {
let captured: RunCtx | null = null;
const runActions = vi.fn().mockResolvedValue(undefined);
const registerAction = vi.fn((_type: string, action: RunCtx) => {
captured = action;
});
registerReplayAction({ registerAction, runActions });
expect(captured).not.toBeNull();
const commands: ScriptCommand[] = [
{ actionType: 'hidden', componentId: 'BEGINDATE' },
{ actionType: 'toast', args: { msg: 'ok' } },
{ actionType: 'unknownVerb' }, // 翻译为 null,被过滤
];
await captured!.run({ args: { commands } }, { r: 1 }, { e: 1 });
// 2 条有效指令 → runActions 调 2 次,componentId/actionType 对齐
expect(runActions).toHaveBeenCalledTimes(2);
expect(runActions.mock.calls[0][0]).toEqual({ actionType: 'hidden', componentId: 'BEGINDATE' });
expect(runActions.mock.calls[1][0].actionType).toBe('toast');
});
it('run 在无指令时不调 runActions', async () => {
let captured: RunCtx | null = null;
const runActions = vi.fn();
registerReplayAction({
registerAction: (_t: string, a: RunCtx) => {
captured = a;
},
runActions,
});
await captured!.run({ args: { commands: [] } }, {}, {});
expect(runActions).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,64 @@
// ============================================================================
// 自定义 amis 动作 replayScriptCommands 注册(P4-5 onEvent 重放胶水)
// ----------------------------------------------------------------------------
// 转换器在页面 onEvent 里编排「ajax 调 /api/script/execute-template → replayScriptCommands」。
// 本模块向 amis 注册 replayScriptCommands:拿到执行端点返回的 commands 数组,翻译成 amis
// 标准动作(scriptCommands.translateCommands),逐条经 amis 动作执行器 runActions 重放——
// 实现 show/hidden/setValue/setOptions/toast 等 29 个 UI 动词 → amis doAction。
//
// amis 自定义动作契约:registerAction(type, { run(action, renderer, event) })。
// run 内用 amis-core 的 runActions 把翻译后的动作逐条派发(componentId 定位目标组件)。
// ============================================================================
import { translateCommands, type ScriptCommand, type AmisAction } from './scriptCommands';
// amis 自定义动作里能拿到的最小入参形态(贴 amis ListenerAction / RendererEvent)。
interface AmisActionArg {
args?: { commands?: ScriptCommand[] };
[key: string]: unknown;
}
interface AmisRenderer {
[key: string]: unknown;
}
interface AmisEvent {
[key: string]: unknown;
}
// amis-core 暴露的 API 子集(经 amisRequire('amis') 取得)。
interface AmisCore {
registerAction?: (type: string, action: unknown) => void;
runActions?: (actions: AmisAction | AmisAction[], renderer: AmisRenderer, event: AmisEvent) => Promise<unknown>;
}
let registered = false;
/**
* 向 amis 注册 replayScriptCommands 自定义动作(幂等,重复调用只注册一次)。
*
* @param amisCore amisRequire('amis') 取得的 amis-core 模块(含 registerAction/runActions)
* @returns 是否完成注册(amis-core 缺 registerAction 时返回 false)
*/
export function registerReplayAction(amisCore: AmisCore | undefined | null): boolean {
if (registered) return true;
if (!amisCore || typeof amisCore.registerAction !== 'function') return false;
amisCore.registerAction('replayScriptCommands', {
async run(action: AmisActionArg, renderer: AmisRenderer, event: AmisEvent) {
const commands = action?.args?.commands;
const amisActions = translateCommands(commands);
if (amisActions.length === 0) return;
if (typeof amisCore.runActions === 'function') {
for (const a of amisActions) {
// 逐条派发,componentId 已对齐 amis 字段 name(大写列名)
await amisCore.runActions(a, renderer, event);
}
}
},
});
registered = true;
return true;
}
// 测试可见:重置注册标志(避免跨用例污染)。
export function __resetReplayActionForTest(): void {
registered = false;
}

View File

@@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest';
import { translateCommand, translateCommands, type ScriptCommand } from './scriptCommands';
// P4-5:脚本指令 → amis 动作翻译(29 UI 动词覆盖核心分支)。
describe('translateCommand', () => {
it('显隐 show/hidden 透传 componentId', () => {
expect(translateCommand({ actionType: 'hidden', componentId: 'BEGINDATE' })).toEqual({
actionType: 'hidden',
componentId: 'BEGINDATE',
});
expect(translateCommand({ actionType: 'show', componentId: 'X' })).toEqual({
actionType: 'show',
componentId: 'X',
});
});
it('只读 static/nonstatic 透传 componentId', () => {
expect(translateCommand({ actionType: 'static', componentId: 'PM_PROJECTID' })?.actionType).toBe('static');
expect(translateCommand({ actionType: 'nonstatic', componentId: 'A' })?.actionType).toBe('nonstatic');
});
it('setValue 取 args.value(bindField/setConvertedValue 归并)', () => {
const a = translateCommand({ actionType: 'setValue', componentId: 'OLD_STORE_ID', args: { value: 'S-99', bind: true } });
expect(a).toEqual({ actionType: 'setValue', componentId: 'OLD_STORE_ID', args: { value: 'S-99' } });
});
it('清空选项 setOptions → setValue options 置空', () => {
const a = translateCommand({ actionType: 'setOptions', componentId: 'ELIGIBILITY', args: { options: [] } });
expect(a?.actionType).toBe('setValue');
expect((a?.args as Record<string, unknown>).options).toEqual([]);
});
it('追加选项 addOption 透传 value/label', () => {
const a = translateCommand({ actionType: 'addOption', componentId: 'ELIGIBILITY', args: { value: 4, label: '合格' } });
expect(a).toEqual({ actionType: 'addOption', componentId: 'ELIGIBILITY', args: { value: 4, label: '合格' } });
});
it('数据过滤 setFilter 透传 filter map', () => {
const a = translateCommand({ actionType: 'setFilter', componentId: 'BUILDCOMPANY', args: { filter: { UNITTYPE: 7 } } });
expect((a?.args as Record<string, unknown>).filter).toEqual({ UNITTYPE: 7 });
});
it('子表按钮 addSubTableButton 透传 args', () => {
const a = translateCommand({ actionType: 'addSubTableButton', componentId: 'GOODSDETAIL', args: { target: 'SELECT', index: 0 } });
expect(a?.actionType).toBe('addSubTableButton');
expect((a?.args as Record<string, unknown>).target).toBe('SELECT');
});
it('提示 toast → msg 透传', () => {
const a = translateCommand({ actionType: 'toast', args: { msg: '已保存' } });
expect(a?.actionType).toBe('toast');
expect((a?.args as Record<string, unknown>).msg).toBe('已保存');
});
it('reload/focus 透传 componentId', () => {
expect(translateCommand({ actionType: 'reload', componentId: 'G' })?.actionType).toBe('reload');
expect(translateCommand({ actionType: 'focus', componentId: 'F' })?.actionType).toBe('focus');
});
it('未知 actionType 返回 null(跳过不报错)', () => {
expect(translateCommand({ actionType: 'unknownVerb' })).toBeNull();
expect(translateCommand({} as ScriptCommand)).toBeNull();
});
});
describe('translateCommands', () => {
it('数组翻译并过滤无法翻译项', () => {
const cmds: ScriptCommand[] = [
{ actionType: 'hidden', componentId: 'A' },
{ actionType: 'unknownVerb' },
{ actionType: 'toast', args: { msg: 'x' } },
];
const out = translateCommands(cmds);
expect(out).toHaveLength(2);
expect(out[0].actionType).toBe('hidden');
expect(out[1].actionType).toBe('toast');
});
it('非数组入参返回空数组', () => {
expect(translateCommands(undefined)).toEqual([]);
expect(translateCommands(null)).toEqual([]);
});
});

120
src/amis/scriptCommands.ts Normal file
View File

@@ -0,0 +1,120 @@
// ============================================================================
// 改写后脚本指令 → amis 动作翻译(P4-5 onEvent 重放胶水)
// ----------------------------------------------------------------------------
// 后端 /api/script/execute-template 返回的指令数组形态(facade 动词产出):
// { actionType, componentId?, args? }
// actionType ∈ {show,hidden,enabled,disabled,static,nonstatic,setValue,setLabel,
// setRequired,setFilter,setOptions,addOption,setNullSelection,removeOption,
// addButton,addSubTableButton,setSubTableButtonVisible,focus,setStyle,reload,
// toast,setConvertedValue(归并 setValue)} —— 共 29 个 UI 语义动词。
// componentId = 改写器输出的大写列名,与转换后 amis 字段 name 同源(天然对齐)。
//
// 本模块把每条指令翻译成 amis 标准动作对象(amis ActionSchema 口径),交 amis 的
// 动作执行器逐条 doAction。translateCommand 与平台 facade 动词表一一对应(报告 §2.2)。
// ============================================================================
export interface ScriptCommand {
actionType: string;
componentId?: string;
args?: Record<string, unknown>;
}
// 翻译后的 amis 动作(amis ActionSchema 子集)。componentId 指向目标组件。
export interface AmisAction {
actionType: string;
componentId?: string;
args?: Record<string, unknown>;
// 部分动作走顶层属性(amis 约定),如 toast 的 msg
[key: string]: unknown;
}
/**
* 单条脚本指令 → amis 动作对象。
* 返回 null 表示该指令无对应 amis 动作(跳过,不报错)。
*/
export function translateCommand(cmd: ScriptCommand): AmisAction | null {
if (!cmd || !cmd.actionType) return null;
const { actionType, componentId, args = {} } = cmd;
switch (actionType) {
// 显隐 —— amis 内置 show/hidden 动作(componentId 定位组件)
case 'show':
case 'hidden':
return { actionType, componentId };
// 启停 —— amis 内置 enabled/disabled
case 'enabled':
case 'disabled':
return { actionType, componentId };
// 只读/可编辑 —— amis 内置 static/nonstatic
case 'static':
case 'nonstatic':
return { actionType, componentId };
// 赋值(含 setConvertedValue / bindField 归并)—— amis setValue
case 'setValue':
return { actionType: 'setValue', componentId, args: { value: args.value } };
// 标题 —— 走 setValue 到组件 label(amis 无独立 setLabel,用组件 schema 更新)
case 'setLabel':
return { actionType: 'setValue', componentId, args: { label: args.label } };
// 必填 —— amis 表单项 required(用 setValue 更新组件 required 态)
case 'setRequired':
return { actionType: 'setValue', componentId, args: { required: args.required, errorMessage: args.errorMessage } };
// 数据过滤 —— 透传 filter(联动数据源;componentId 为目标选择组件)
case 'setFilter':
return { actionType: 'setValue', componentId, args: { filter: args.filter } };
// 清空选项 —— amis setOptions 置空
case 'setOptions':
return { actionType: 'setValue', componentId, args: { options: args.options ?? [] } };
// 追加选项 —— 透传 addOption(前端合并进组件 options)
case 'addOption':
return { actionType: 'addOption', componentId, args: { value: args.value, label: args.label } };
case 'setNullSelection':
return { actionType: 'setValue', componentId, args: { nullSelection: args.value } };
case 'removeOption':
return { actionType: 'removeOption', componentId, args: { value: args.value } };
// 子表按钮(增删改查/自定义)—— 透传给子表组件
case 'addSubTableButton':
return { actionType: 'addSubTableButton', componentId, args };
case 'setSubTableButtonVisible':
return { actionType: 'setSubTableButtonVisible', componentId, args };
case 'addButton':
return { actionType: 'addButton', componentId, args };
// 聚焦 —— amis focus
case 'focus':
return { actionType: 'focus', componentId };
// 样式 —— 透传 width/height
case 'setStyle':
return { actionType: 'setValue', componentId, args: { style: args } };
// 重载数据源 —— amis reload
case 'reload':
return { actionType: 'reload', componentId };
// 提示 —— amis toast(msg 走顶层 args.msg)
case 'toast':
return { actionType: 'toast', args: { msgType: 'info', msg: args.msg } };
default:
return null;
}
}
/** 指令数组 → amis 动作数组(跳过无法翻译的)。 */
export function translateCommands(commands: ScriptCommand[] | undefined | null): AmisAction[] {
if (!Array.isArray(commands)) return [];
return commands
.map(translateCommand)
.filter((a): a is AmisAction => a !== null);
}

View File

@@ -22,6 +22,9 @@ const MOCK_MAP: Record<string, string> = {
'role-maintain': '/schemas/role-maintain.json',
'notice-archive': '/schemas/notice-archive.json',
'usergroup-manage': '/schemas/usergroup-manage.json',
// P4-5 改写后脚本挂回 onEvent 重放 e2e(真实 FULL_AUTO facade-only 脚本)
'welfare-settlement': '/schemas/welfare-settlement.json',
'office-collar': '/schemas/office-collar.json',
};
export interface PageMeta {

View File

@@ -11,6 +11,7 @@
// ============================================================================
import { useEffect, useRef } from 'react';
import { http } from '../api/http';
import { registerReplayAction } from '../amis/registerReplayAction';
interface AmisRendererProps {
schema: Record<string, unknown>;
@@ -35,6 +36,14 @@ export function AmisRenderer({ schema }: AmisRendererProps) {
const amis = amisRequire('amis/embed');
// P4-5:注册改写后脚本指令重放的自定义动作 replayScriptCommands。
// amis-core(含 registerAction/runActions)经 amisRequire('amis') 取得;注册幂等。
try {
registerReplayAction(amisRequire('amis'));
} catch {
// amis-core 未暴露 registerAction 时静默降级(onEvent 重放不可用,不阻断渲染)
}
// 自定义 fetcher:复用宿主 axios(已带 Bearer 注入 + 401 跳登录拦截)
const fetcher = (options: AmisFetcherOptions) => {
const { url, method = 'get', data, responseType } = options;