feat(converter): onEvent 脚本挂回改由 XML 事件绑定驱动,覆盖 NO_S3+按钮联动

WS-B Phase1-3:把老模板事件脚本按事件类型正确挂回 amis onEvent。

Phase1 解析:
- scriptKeyToSeq(Element):<scripts><script key> → key→1-based 文档序(对齐 rewriter 落盘 seq)。
- extractEventBindings(Element):递归收集 onselectedscript/onloadscript 属性 → List<EventBinding>(新增 public static EventBinding{eventType,scriptKey})。

Phase2 重写 attachScriptOnEvent(schema,templateId,List<EventBinding>,Map<key,seq>):
- onselectedscript → crud selectedChange,item=${event.data.selectedItems[0]}(行选中按钮联动)。
- onloadscript → inited,item=${&}(加载只读/显隐联动)。
- seq 由 keyToSeq 解析,引用不存在 key 则跳过(fail-closed);覆盖 NO_S3+FULL_AUTO,不再读 full_auto_index 决定挂哪段。
- scriptActionChain 重载支持自定义 item 表达式,原方法委托传 ${&}。
- 废弃旧「只挂 FULL_AUTO/每段同挂 inited+change」语义。

Phase3:buildToolbar 每按钮补 id=中文名(=label=enableButton 实参,三者同源),供 amis enabled/disabled 动作按 componentId 精准启停工具栏按钮。

BatchConvertCli:删 loadFullAutoIndex,改从每模板源 XML 解析 bindings+keyToSeq 调新 attach;rewriterDir 仍作 onEvent 总开关。

测试:platform-converter 85 绿(TemplateToAmisConverterTest 78,含新增 9 例:scriptKeyToSeq 文档序/extractEventBindings 收集/scriptActionChain 自定义 item/onselected→selectedChange+onload→inited/NO_S3 也挂/引用不存在 key 跳过/按钮含 id)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-14 14:58:27 +08:00
parent 3d483b1009
commit 79eb8e2087
3 changed files with 333 additions and 73 deletions

View File

@@ -18,6 +18,8 @@ import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
@@ -30,8 +32,11 @@ import com.fasterxml.jackson.databind.SerializationFeature;
* <p>流程:从客户库(PostgreSQL,只读)拉全部 view_template.xml → 逐个 {@link TemplateToAmisConverter}
* 转换 → 闸一 {@link SchemaGate} 官方 schema 校验 → 产物落盘 + 分级清单 CSV。
*
* <p>F1-4b 扩展:第 5 参数为改写产物根目录(含 full_auto_index.json),转换完成后自动调用
* {@link TemplateToAmisConverter#attachScriptOnEvent} 补挂 onEvent 脚本钩子。
* <p>WS-B:第 5 参数为改写产物根目录(rewriterDir),传入即启用 onEvent 挂回。挂回不再读
* full_auto_index.json,而是从每个模板源 XML 解析事件绑定(onselectedscript/onloadscript →
* scriptKey)+ {@code <scripts>} 文档序(key→seq),按事件类型调用
* {@link TemplateToAmisConverter#attachScriptOnEvent}(onselected→selectedChange / onload→inited),
* 覆盖 NO_S3+FULL_AUTO 两类脚本。
*
* <p>用法(本地 eip4dev):
* <pre>{@code
@@ -107,26 +112,31 @@ public final class BatchConvertCli {
}
/**
* 从 full_auto_index.json 加载 templateId → seqs 映射。
* 文件结构:[{"template_id":"...","seq":1,...}, ...]
* 从源模板 XML 解析事件绑定(onselectedscript/onloadscript → scriptKey)。
* 委托 {@link TemplateToAmisConverter#extractEventBindings};XML 不可解析则返回空列表(不挂 onEvent)。
*/
@SuppressWarnings("unchecked")
static Map<String, List<Integer>> loadFullAutoIndex(Path rewriterDir) throws IOException {
Path indexFile = rewriterDir.resolve("full_auto_index.json");
if (!Files.exists(indexFile)) {
static List<TemplateToAmisConverter.EventBinding> parseEventBindings(String xml) {
try {
Element root = DocumentHelper.parseText(xml).getRootElement();
TemplateToAmisConverter helper = new TemplateToAmisConverter(null);
return helper.extractEventBindings(root);
} catch (Exception e) {
return List.of();
}
}
/**
* 从源模板 XML 解析 scriptKey→seq({@code <scripts>} 1-based 文档序,与 rewriter 落盘 seq 对齐)。
* 委托 {@link TemplateToAmisConverter#scriptKeyToSeq};XML 不可解析则返回空 map。
*/
static Map<String, Integer> parseKeyToSeq(String xml) {
try {
Element root = DocumentHelper.parseText(xml).getRootElement();
TemplateToAmisConverter helper = new TemplateToAmisConverter(null);
return helper.scriptKeyToSeq(root);
} catch (Exception e) {
return Map.of();
}
ObjectMapper om = new ObjectMapper();
List<Map<String, Object>> entries = om.readValue(indexFile.toFile(), List.class);
Map<String, List<Integer>> result = new LinkedHashMap<>();
for (Map<String, Object> entry : entries) {
String tid = (String) entry.get("template_id");
Object seqObj = entry.get("seq");
if (tid == null || seqObj == null) continue;
int seq = ((Number) seqObj).intValue();
result.computeIfAbsent(tid, k -> new ArrayList<>()).add(seq);
}
return result;
}
static BatchSummary run(Connection conn, Path outDir) throws IOException, SQLException {
@@ -142,10 +152,11 @@ public final class BatchConvertCli {
SchemaGate gate = new SchemaGate();
Function<String, String> pageResolver = pageId -> loadPageXml(conn, pageId);
// F1-4b:加载 full_auto_index.json(rewriterDir 为空则不挂 onEvent)
Map<String, List<Integer>> fullAutoIndex = (rewriterDir != null)
? loadFullAutoIndex(rewriterDir) : Map.of();
System.out.println("[F1-4b] full_auto_index 已加载:" + fullAutoIndex.size() + " 个模板有 FULL_AUTO 脚本");
// WS-B:onEvent 挂回改由 XML 事件绑定驱动(onselectedscript/onloadscript → 脚本 key → <scripts> 文档序 seq),
// 覆盖 NO_S3+FULL_AUTO 两类脚本,不再依赖 full_auto_index.json 决定挂哪段。rewriterDir 仍作为「是否挂 onEvent」总开关。
boolean attachOnEvent = rewriterDir != null;
System.out.println("[WS-B] onEvent 挂回:" + (attachOnEvent
? "启用(按 XML onselected/onload 事件绑定驱动,覆盖 NO_S3+FULL_AUTO)" : "关闭(未传 rewriterDir)"));
ObjectMapper json = new ObjectMapper();
json.enable(SerializationFeature.INDENT_OUTPUT);
@@ -180,12 +191,20 @@ public final class BatchConvertCli {
boolean gate1 = false;
boolean onEventAttached = false;
if (result.getSchema() != null) {
// F1-4b:闸一通过前先挂 onEvent(挂后再校验,确保含 onEvent 的 schema 也能过闸)
List<Integer> seqs = fullAutoIndex.get(id);
if (seqs != null && !seqs.isEmpty()) {
converter.attachScriptOnEvent(result.getSchema(), id, seqs);
onEventAttached = true;
summary.onEventCount++;
// WS-B:闸一通过前先挂 onEvent(挂后再校验,确保含 onEvent 的 schema 也能过闸)。
// 从源 XML 解析事件绑定(onselected/onload→scriptKey) + scripts 文档序(key→seq),
// 按事件类型挂到正确 amis 事件(onselected→selectedChange / onload→inited),覆盖 NO_S3+FULL_AUTO。
if (attachOnEvent) {
List<TemplateToAmisConverter.EventBinding> bindings = parseEventBindings(xml);
if (!bindings.isEmpty()) {
Map<String, Integer> keyToSeq = parseKeyToSeq(xml);
converter.attachScriptOnEvent(result.getSchema(), id, bindings, keyToSeq);
Object body = result.getSchema().get("body");
if (body instanceof Map && ((Map<?, ?>) body).containsKey("onEvent")) {
onEventAttached = true;
summary.onEventCount++;
}
}
}
List<String> errors = gate.validate(result.getSchema());

View File

@@ -464,6 +464,9 @@ public class TemplateToAmisConverter {
String btnName = UiTypeMapper.firstNonBlank(b.attributeValue("name"), b.attributeValue("id"), btnType);
Map<String, Object> btn = new LinkedHashMap<>();
btn.put("type", "button");
// WS-B:按钮 id = 中文名(= label = ScriptFacade.enableButton 实参,三者同源、零规范化),
// 供 onselectedscript 脚本经 amis 内置 enabled/disabled 动作按 componentId 精准启停工具栏按钮。
btn.put("id", btnName);
btn.put("label", btnName);
switch (btnType) {
case "insert" -> {
@@ -1678,29 +1681,119 @@ public class TemplateToAmisConverter {
/** 前端 AmisRenderer 注册的自定义重放动作名(拿到指令数组逐条 doAction)。 */
static final String REPLAY_ACTION = "replayScriptCommands";
/** crud 行选中事件名(Phase 0 spike 已用真实 amis 6.13+SDK 源码验证)。 */
static final String EVENT_SELECTED_CHANGE = "selectedChange";
/** 页面/表单初次渲染事件名。 */
static final String EVENT_INITED = "inited";
/** 老模板事件绑定属性:行选中(按钮联动) / 加载(字段只读·显隐联动)。 */
static final String ATTR_ON_SELECTED = "onselectedscript";
static final String ATTR_ON_LOAD = "onloadscript";
private static final List<String> EVENT_ATTRS = List.of(ATTR_ON_SELECTED, ATTR_ON_LOAD);
/**
* 把模板的 FULL_AUTO 改写脚本挂回 amis 页面 schema 的 {@code onEvent}(P4-5 事件生成段)。
* 一条事件绑定:原始事件属性名({@code onselectedscript}/{@code onloadscript})+ 引用的脚本 key。
*
* <p>每段脚本生成两类联动触发:
* <p>scriptKey 对到模板 {@code <scripts><script key=..>} 的同 key 节点,后续经
* {@link #scriptKeyToSeq(Element)} 解析为 1-based 文档序 seq(与 rewriter 落盘 seq 对齐)。
*/
public static final class EventBinding {
public final String eventType; // onselectedscript | onloadscript
public final String scriptKey;
public EventBinding(String eventType, String scriptKey) {
this.eventType = eventType;
this.scriptKey = scriptKey;
}
@Override
public String toString() {
return eventType + ":" + scriptKey;
}
}
/**
* 解析 {@code <scripts><script key=...>} 的 key→seq(1-based 文档序,与 rewriter 落盘 seq 对齐)。
*
* <p>rewriter 落盘路径为 {@code rewritten/<templateId>/<seq>.<LABEL>.groovy},seq 即
* view_template.xml {@code <scripts>} 内 {@code <script>} 的 1-based 文档序;本方法重建该映射,
* 供事件绑定 {@code onselectedscript="<scriptKey>"} 反查 seq。
*/
Map<String, Integer> scriptKeyToSeq(Element root) {
Map<String, Integer> map = new LinkedHashMap<>();
if (root == null) {
return map;
}
Element scripts = root.element("scripts");
if (scripts == null) {
return map;
}
int seq = 0;
for (Element s : scripts.elements("script")) {
seq++;
String key = s.attributeValue("key");
if (key != null && !key.isBlank()) {
map.put(key, seq);
}
}
return map;
}
/**
* 递归扫描根元素树,收集所有带 {@code onselectedscript}/{@code onloadscript} 属性的元素,
* 产出事件绑定列表(全库 onselected 930 / onload 422 模板;onclick/onchange 为 0,只处理两类)。
*/
List<EventBinding> extractEventBindings(Element root) {
List<EventBinding> out = new ArrayList<>();
if (root != null) {
collectBindings(root, out);
}
return out;
}
private void collectBindings(Element el, List<EventBinding> out) {
for (String attr : EVENT_ATTRS) {
String v = el.attributeValue(attr);
if (v != null && !v.isBlank()) {
out.add(new EventBinding(attr, v));
}
}
for (Element c : el.elements()) {
collectBindings(c, out);
}
}
/**
* 把老模板的事件脚本按事件类型挂回 amis 页面 schema 的 {@code onEvent}(P4-5 事件生成段,WS-B 修复)。
*
* <p>映射规则(事件名已用真实 amis 6.13 验证):
* <ul>
* <li>{@code inited}:页面/表单初次渲染时跑一遍(脚本里初始化字段显隐/选项/只读等);</li>
* <li>{@code change}:字段值变更时重跑(脚本据当前数据域 item 做联动)。</li>
* <li>{@code onselectedscript} → crud {@code selectedChange}(行选中),item 取选中行
* {@code ${event.data.selectedItems[0]}}:脚本据选中行 STATUS 等 {@code enableButton} 点亮/置灰
* 工具栏按钮(空选 selectedItems:[] 时脚本走 else 自然置灰全部);</li>
* <li>{@code onloadscript} → {@code inited}(初次渲染),item 取全量数据域 {@code ${&}}:
* 表单加载时按数据做字段只读/显隐联动。</li>
* </ul>
* 触发动作链:先 {@code ajax} 调 {@link #SCRIPT_EXECUTE_API}(传 {@code templateId/seq} +
* {@code item:${&}} 全量表单数据),把返回的 {@code commands} 数组交给前端自定义动作
* {@link #REPLAY_ACTION} 逐条重放(show/hidden/setValue/setOptions/toast 等 → amis doAction)。
* componentId 用改写器输出的大写列名,与 amis 字段 name 同源,天然对齐(报告 §5.4)。
* 触发动作链:先 {@code ajax} 调 {@link #SCRIPT_EXECUTE_API}(传 {@code templateId/seq/item}),
* 把返回的 {@code commands} 数组交给前端自定义动作 {@link #REPLAY_ACTION} 逐条重放
* (enabled/disabled/show/hidden/setValue 等 → amis 内置动作,componentId=按钮 id / 字段 name)。
*
* @param pageSchema 已转换的页面 schema(顶层 type=page)
* @param templateId 模板 ID(改写产物落盘目录名)
* @param fullAutoSeqs 该模板 FULL_AUTO 改写脚本的序号列表(取自 full_auto_index.json)
* <p>覆盖 NO_S3 + FULL_AUTO 两类脚本:seq 由 {@code keyToSeq}({@link #scriptKeyToSeq})从
* {@code <scripts>} 文档序解析得到,runtime {@code RewrittenScriptStore.load(templateId,seq)} 可加载
* 任意 seq(含 NO_S3),故不再依赖 full_auto_index.json 决定挂哪段。
*
* @param pageSchema 已转换的页面 schema(顶层 type=page,body 为 crud/form/tabs...)
* @param templateId 模板 ID(改写产物落盘目录名)
* @param bindings 从源 XML 提取的事件绑定列表({@link #extractEventBindings})
* @param keyToSeq scriptKey→1-based 文档序({@link #scriptKeyToSeq})
* @return 同一 pageSchema 引用(已就地挂上 onEvent),便于链式使用
*/
@SuppressWarnings("unchecked")
public Map<String, Object> attachScriptOnEvent(Map<String, Object> pageSchema, String templateId,
List<Integer> fullAutoSeqs) {
List<EventBinding> bindings, Map<String, Integer> keyToSeq) {
if (pageSchema == null || templateId == null || templateId.isBlank()
|| fullAutoSeqs == null || fullAutoSeqs.isEmpty()) {
|| bindings == null || bindings.isEmpty() || keyToSeq == null) {
return pageSchema;
}
Object bodyObj = pageSchema.get("body");
@@ -1709,25 +1802,45 @@ public class TemplateToAmisConverter {
}
Map<String, Object> body = (Map<String, Object>) bodyObj;
List<Object> selectedActions = new ArrayList<>();
List<Object> initedActions = new ArrayList<>();
List<Object> changeActions = new ArrayList<>();
for (Integer seq : fullAutoSeqs) {
for (EventBinding b : bindings) {
Integer seq = keyToSeq.get(b.scriptKey);
if (seq == null) {
continue;
continue; // 绑定引用了不存在的 scriptKey → 跳过(fail-closed,不挂错脚本)
}
if (ATTR_ON_SELECTED.equals(b.eventType)) {
selectedActions.addAll(scriptActionChain(templateId, seq, "${event.data.selectedItems[0]}"));
} else if (ATTR_ON_LOAD.equals(b.eventType)) {
initedActions.addAll(scriptActionChain(templateId, seq, "${&}"));
}
initedActions.addAll(scriptActionChain(templateId, seq));
changeActions.addAll(scriptActionChain(templateId, seq));
}
Map<String, Object> onEvent = new LinkedHashMap<>();
onEvent.put("inited", Map.of("actions", initedActions));
onEvent.put("change", Map.of("actions", changeActions));
body.put("onEvent", onEvent);
if (!selectedActions.isEmpty()) {
onEvent.put(EVENT_SELECTED_CHANGE, Map.of("actions", selectedActions));
}
if (!initedActions.isEmpty()) {
onEvent.put(EVENT_INITED, Map.of("actions", initedActions));
}
if (!onEvent.isEmpty()) {
body.put("onEvent", onEvent);
}
return pageSchema;
}
/** 单段脚本的动作链:ajax 调执行端点 → 自定义动作重放返回的指令数组。 */
/** 单段脚本的动作链:ajax 调执行端点 → 自定义动作重放返回的指令数组(item 默认全量数据域 {@code ${&}})。 */
private List<Object> scriptActionChain(String templateId, int seq) {
return scriptActionChain(templateId, seq, "${&}");
}
/**
* 单段脚本的动作链(可指定 item 表达式):ajax 调执行端点 → 自定义动作重放返回的指令数组。
*
* @param itemExpr 作为脚本 item 上下文的 amis 表达式(如 {@code ${&}} 全量数据域、
* {@code ${event.data.selectedItems[0]}} 选中行)
*/
private List<Object> scriptActionChain(String templateId, int seq, String itemExpr) {
Map<String, Object> ajax = new LinkedHashMap<>();
ajax.put("actionType", "ajax");
Map<String, Object> api = new LinkedHashMap<>();
@@ -1736,7 +1849,7 @@ public class TemplateToAmisConverter {
api.put("data", new LinkedHashMap<>(Map.of(
"templateId", templateId,
"seq", seq,
"item", "${&}"))); // ${&} = amis 当前全量数据域,作为脚本 item 上下文
"item", itemExpr))); // 脚本 item 上下文表达式(${&} 全量域 / ${event.data.selectedItems[0]} 选中行)
ajax.put("api", api);
ajax.put("outputVar", "scriptResult" + seq);