XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEServerManager

【Java】我的世界XFE服务器管理器

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEServerManager

支持 V2 触发器递归命令参数树及前后端校验

为 TriggerProgramV2.EventBinding 增加 arguments 字段,支持递归 Brigadier 命令参数树,完善类型校验,仅 player.command_trigger 事件允许参数树。同步更新编译、校验、事件转换逻辑,接口定义及类型前后端对齐。前端事件编辑器与 CommandTriggerFields 支持参数树可视化编辑和校验,兼容旧版配置。补充相关单元测试,优化 UI 布局,确保参数树表达能力和一致性。

0382ce5
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

14 个文件 +248 -47
Modified common/core/src/main/java/com/xfestudio/xfeservermanager/core/trigger/TriggerLegacyV2Compiler.java +2 -1
@@ -50,7 +50,8 @@ public final class TriggerLegacyV2Compiler {
50 50 return new TriggerProgramV2(
51 51 TriggerProgramV2.SCHEMA_VERSION,
52 52 List.of(new TriggerProgramV2.EventBinding(
53 id(definition.id(), "event/0"), legacy.event().type(), legacy.event().configuration())),
53 id(definition.id(), "event/0"), legacy.event().type(),
54 legacy.event().configuration(), legacy.event().arguments())),
54 55 declarations, List.of(), body);
55 56 }
56 57
Modified common/core/src/main/java/com/xfestudio/xfeservermanager/core/trigger/TriggerProgramV2.java +19 -1
@@ -28,11 +28,29 @@ public record TriggerProgramV2(
28 28 TriggerProgramValidator.validate(events, declarations, functions, statements);
29 29 }
30 30
31 public record EventBinding(UUID nodeId, String type, Map<String, String> configuration) {
31 public record EventBinding(
32 UUID nodeId,
33 String type,
34 Map<String, String> configuration,
35 List<TriggerDefinition.CommandArgument> arguments) {
36 /** Source and persisted-document compatibility for V2 events created before typed commands. */
37 public EventBinding(UUID nodeId, String type, Map<String, String> configuration) {
38 this(nodeId, type, configuration, List.of());
39 }
40
32 41 public EventBinding {
33 42 nodeId = stable(nodeId);
34 43 type = id(type, "event type");
35 44 configuration = Map.copyOf(configuration == null ? Map.of() : configuration);
45 arguments = immutable(arguments, "command argument");
46 if (!arguments.isEmpty() && !TriggerCommandConfiguration.EVENT_TYPE.equals(type)) {
47 throw new IllegalArgumentException(
48 "typed command arguments require event " + TriggerCommandConfiguration.EVENT_TYPE);
49 }
50 if (TriggerCommandConfiguration.EVENT_TYPE.equals(type)) {
51 TriggerCommandConfiguration.parse(new TriggerDefinition.TriggerEvent(
52 type, configuration, arguments, List.of()));
53 }
36 54 }
37 55 }
38 56
Modified common/testkit/src/test/java/com/xfestudio/xfeservermanager/core/trigger/TriggerProgramV2Test.java +30 -0
@@ -86,6 +86,36 @@ class TriggerProgramV2Test {
86 86 assertThrows(IllegalArgumentException.class, () -> TriggerActionTree.validate(List.of(tooDeep)));
87 87 }
88 88
89 @Test
90 void typedCommandArgumentTreesRoundTripThroughV2AndLegacyCompilation() {
91 TriggerDefinition.CommandArgument message = new TriggerDefinition.CommandArgument(
92 "message", "greedy_string", "", true, "message is invalid",
93 "", "", List.of("hello", "help"), List.of());
94 TriggerDefinition.CommandArgument target = new TriggerDefinition.CommandArgument(
95 "target", "player", "", false, "player is invalid",
96 "", "", List.of("@s", "@a"), List.of(message));
97 List<TriggerDefinition.CommandArgument> arguments = List.of(target);
98 TriggerProgramV2.EventBinding binding = new TriggerProgramV2.EventBinding(
99 UUID.randomUUID(), TriggerCommandConfiguration.EVENT_TYPE,
100 Map.of("command", "notice"), arguments);
101
102 assertEquals(arguments, binding.arguments());
103 assertThrows(IllegalArgumentException.class, () -> new TriggerProgramV2.EventBinding(
104 UUID.randomUUID(), "player.join", Map.of(), arguments));
105
106 Instant now = Instant.EPOCH;
107 TriggerDefinition legacy = new TriggerDefinition(
108 UUID.randomUUID(), UUID.randomUUID(), "Typed command", "", true,
109 TriggerDefinition.Mode.VISUAL,
110 new TriggerDefinition.TriggerEvent(TriggerCommandConfiguration.EVENT_TYPE,
111 Map.of("command", "notice"), arguments, List.of()),
112 TriggerDefinition.MatchMode.ALL, List.of(),
113 List.of(new TriggerDefinition.Action("log", Map.of("message", "{args.message}"))),
114 "", 0, "owner", now, now, false);
115
116 assertEquals(arguments, TriggerLegacyV2Compiler.compile(legacy).events().get(0).arguments());
117 }
118
89 119 @Test
90 120 void functionArgumentsUseCallerSnapshotAndOutParametersWriteBack() {
91 121 TriggerProgramV2.Statement assignOutput = new TriggerProgramV2.Statement(UUID.randomUUID(),
Modified docs/openapi.yaml +4 -0
@@ -3518,6 +3518,10 @@ components:
3518 3518 nodeId: {type: string, format: uuid}
3519 3519 type: {type: string, minLength: 1, maxLength: 128}
3520 3520 configuration: {type: object, additionalProperties: {type: string}}
3521 arguments:
3522 type: array
3523 description: Recursive Brigadier alternatives for player.command_trigger. Omitted by early V2 documents and migrated from configuration.arguments when edited.
3524 items: {$ref: "#/components/schemas/TriggerCommandArgument"}
3521 3525 TriggerVariableDeclarationV2:
3522 3526 type: object
3523 3527 required: [nodeId, name, valueType, visibility, storage, lifetime]
Modified platform/shared/src/forge-common/java/com/xfestudio/xfeservermanager/platform/forge/ForgeManagementGateway.java +19 -5
@@ -2365,7 +2365,7 @@ final class ForgeManagementGateway implements ManagementGateway {
2365 2365 ForgeTriggerService.validateEventActions(trigger.executableProgram()));
2366 2366 requireTriggerGroupActionCapability(principal, groupTriggers);
2367 2367 }
2368 validateTriggerSet(current, id, enabled, null);
2368 validateTriggerSet(current, id, enabled, null, null);
2369 2369 }
2370 2370 requirePolicyAudit(principal, "trigger.group.save.admission",
2371 2371 id == null ? "new-trigger-group" : id.toString(), "trigger group saved", requestId, Map.of());
@@ -2425,7 +2425,7 @@ final class ForgeManagementGateway implements ManagementGateway {
2425 2425 !body.containsKey("enabled") || booleanValue(body.get("enabled"), "enabled"),
2426 2426 mode, event, conditionMode, conditions, actions,
2427 2427 script, 0, principal.username(), now, now, false);
2428 validateTriggerSet(current, null, false, draft);
2428 validateTriggerSet(current, null, false, draft, v2Program);
2429 2429 requirePolicyAudit(principal, "trigger.save.admission", id.toString(),
2430 2430 "trigger saved", requestId, Map.of("mode", mode.name(), "event", draft.executableProgram().event().type()));
2431 2431 TriggerDefinition saved = v2Program == null
@@ -2475,7 +2475,8 @@ final class ForgeManagementGateway implements ManagementGateway {
2475 2475 Map<String, String> configuration = binding.type().startsWith("region.")
2476 2476 ? Map.of("regionId", Objects.toString(binding.configuration().get("regionId"), ""))
2477 2477 : binding.configuration();
2478 return new TriggerDefinition.TriggerEvent(binding.type(), configuration, List.of(), variables);
2478 return new TriggerDefinition.TriggerEvent(
2479 binding.type(), configuration, binding.arguments(), variables);
2479 2480 }
2480 2481
2481 2482 private static String legacyInitialValue(TriggerProgramV2.VariableDeclaration declaration) {
@@ -2510,7 +2511,8 @@ final class ForgeManagementGateway implements ManagementGateway {
2510 2511
2511 2512 private void validateTriggerSet(ServerManagerRuntime runtime, UUID overriddenGroupId,
2512 2513 boolean overriddenGroupEnabled,
2513 TriggerDefinition replacement) {
2514 TriggerDefinition replacement,
2515 TriggerProgramV2 replacementProgram) {
2514 2516 Map<UUID, Boolean> groupEnabled = runtime.triggers().groups().stream().collect(
2515 2517 java.util.stream.Collectors.toMap(
2516 2518 com.xfestudio.xfeservermanager.core.trigger.TriggerGroup::id,
@@ -2529,7 +2531,19 @@ final class ForgeManagementGateway implements ManagementGateway {
2529 2531 .filter(trigger -> groupEnabled.getOrDefault(trigger.groupId(), false))
2530 2532 .toList();
2531 2533 ForgeTriggerService.validateFanOut(enabled);
2532 List<ForgeTriggerService.CommandBinding> bindings = ForgeTriggerService.commandBindings(enabled);
2534 Map<UUID, TriggerProgramV2> programs = new LinkedHashMap<>();
2535 for (TriggerDefinition trigger : enabled) {
2536 TriggerProgramV2 program;
2537 if (replacement != null && trigger.id().equals(replacement.id())) {
2538 program = replacementProgram != null
2539 ? replacementProgram : TriggerLegacyV2Compiler.compile(trigger);
2540 } else {
2541 program = runtime.triggers().triggerProgram(trigger);
2542 }
2543 programs.put(trigger.id(), program);
2544 }
2545 List<ForgeTriggerService.CommandBinding> bindings =
2546 ForgeTriggerService.commandBindings(enabled, programs);
2533 2547 try {
2534 2548 onServerThread(() -> {
2535 2549 triggerCommandRegistry.validateAvailable(server.getCommands().getDispatcher(), bindings);
Modified platform/shared/src/forge-common/java/com/xfestudio/xfeservermanager/platform/forge/ForgeTriggerService.java +49 -15
@@ -10,6 +10,7 @@ import com.xfestudio.xfeservermanager.core.trigger.TriggerDefinition;
10 10 import com.xfestudio.xfeservermanager.core.trigger.TriggerDescriptorCatalog;
11 11 import com.xfestudio.xfeservermanager.core.trigger.TriggerEvaluator;
12 12 import com.xfestudio.xfeservermanager.core.trigger.TriggerIntervalSchedule;
13 import com.xfestudio.xfeservermanager.core.trigger.TriggerLegacyV2Compiler;
13 14 import com.xfestudio.xfeservermanager.core.trigger.TriggerTimeContext;
14 15 import com.xfestudio.xfeservermanager.core.trigger.TriggerValueTypes;
15 16 import com.xfestudio.xfeservermanager.core.trigger.TriggerStateRevisionConflictException;
@@ -129,7 +130,6 @@ final class ForgeTriggerService {
129 130 validateVariableDeclarations(allDefinitions);
130 131 List<TriggerDefinition> enabled = runtime.triggers().enabledTriggers();
131 132 validateFanOut(enabled);
132 TriggerCommandConfiguration.validateUniqueEnabledCommands(enabled);
133 133 Map<UUID, TriggerProgramV2> programs = new LinkedHashMap<>();
134 134 Map<String, List<TriggerDefinition>> mutableByEvent = new LinkedHashMap<>();
135 135 for (TriggerDefinition trigger : enabled) {
@@ -152,7 +152,8 @@ final class ForgeTriggerService {
152 152 Map<String, List<TriggerDefinition>> enabledByEvent = Map.copyOf(immutableByEvent);
153 153 Map<UUID, TriggerDefinition> enabledById = enabled.stream().collect(Collectors.toUnmodifiableMap(
154 154 TriggerDefinition::id, trigger -> trigger));
155 index = new TriggerIndex(enabledByEvent, enabledById, commandBindings(enabled), Map.copyOf(programs));
155 index = new TriggerIndex(enabledByEvent, enabledById,
156 commandBindings(enabled, programs), Map.copyOf(programs));
156 157 protectionCooldowns.keySet().removeIf(key -> enabledById.keySet().stream()
157 158 .noneMatch(id -> key.startsWith(id.toString() + '|')));
158 159 reconcileVariables(allDefinitions);
@@ -313,18 +314,48 @@ final class ForgeTriggerService {
313 314 }
314 315
315 316 static List<CommandBinding> commandBindings(List<TriggerDefinition> definitions) {
317 Map<UUID, TriggerProgramV2> programs = definitions.stream().collect(Collectors.toMap(
318 TriggerDefinition::id, TriggerLegacyV2Compiler::compile));
319 return commandBindings(definitions, programs);
320 }
321
322 static List<CommandBinding> commandBindings(
323 List<TriggerDefinition> definitions, Map<UUID, TriggerProgramV2> programs) {
316 324 List<CommandBinding> result = new ArrayList<>();
325 Set<String> commandRoots = new java.util.LinkedHashSet<>();
317 326 for (TriggerDefinition trigger : definitions) {
318 327 if (!trigger.enabled()) continue;
319 TriggerDefinition.TriggerEvent event = trigger.executableProgram().event();
320 if (!TriggerCommandConfiguration.EVENT_TYPE.equals(event.type())) continue;
321 TriggerCommandConfiguration.CommandSpec specification = TriggerCommandConfiguration.parse(event);
322 result.add(new CommandBinding(trigger.id(), trigger.revision(),
323 specification.command(), specification.argumentTree(), trigger.name()));
328 TriggerProgramV2 program = programs.get(trigger.id());
329 if (program == null) program = TriggerLegacyV2Compiler.compile(trigger);
330 for (TriggerProgramV2.EventBinding binding : program.events()) {
331 if (!TriggerCommandConfiguration.EVENT_TYPE.equals(binding.type())) continue;
332 TriggerCommandConfiguration.CommandSpec specification = commandSpecification(binding);
333 if (!commandRoots.add(specification.command())) {
334 throw new IllegalArgumentException(
335 "duplicate enabled trigger command: " + specification.command());
336 }
337 result.add(new CommandBinding(trigger.id(), trigger.revision(),
338 specification.command(), specification.argumentTree(), trigger.name()));
339 }
324 340 }
325 341 return List.copyOf(result);
326 342 }
327 343
344 private static TriggerCommandConfiguration.CommandSpec commandSpecification(
345 TriggerProgramV2.EventBinding binding) {
346 return TriggerCommandConfiguration.parse(new TriggerDefinition.TriggerEvent(
347 binding.type(), binding.configuration(), binding.arguments(), List.of()));
348 }
349
350 private static boolean containsCommandBinding(
351 TriggerProgramV2 program, CommandBinding expected) {
352 return program.events().stream()
353 .filter(binding -> TriggerCommandConfiguration.EVENT_TYPE.equals(binding.type()))
354 .map(ForgeTriggerService::commandSpecification)
355 .anyMatch(current -> current.command().equals(expected.command())
356 && current.argumentTree().equals(expected.argumentTree()));
357 }
358
328 359 static void validateEventActions(TriggerDefinition.Program program) {
329 360 for (TriggerDefinition.Action action : TriggerActionTree.leafActions(program.actions())) {
330 361 if (Set.of("send_player", "broadcast", "actionbar", "kick").contains(action.type())) {
@@ -358,10 +389,9 @@ final class ForgeTriggerService {
358 389 suppliedContext, Instant.now(), ZoneId.systemDefault());
359 390 TriggerDefinition target = index.enabledById().get(binding.triggerId());
360 391 if (target == null || !target.enabled()) return List.of();
361 TriggerCommandConfiguration.CommandSpec current = TriggerCommandConfiguration.parse(
362 target.executableProgram().event());
363 if (target.revision() != binding.revision() || !current.command().equals(binding.command())
364 || !current.argumentTree().equals(binding.argumentTree())) return List.of();
392 TriggerProgramV2 program = index.programsById().get(target.id());
393 if (target.revision() != binding.revision()
394 || program == null || !containsCommandBinding(program, binding)) return List.of();
365 395 return prepareMatchingRuntime(TriggerCommandConfiguration.EVENT_TYPE, List.of(target), context);
366 396 }
367 397
@@ -428,15 +458,15 @@ final class ForgeTriggerService {
428 458 TriggerProgramV2 v2 = index.programsById().get(trigger.id());
429 459 if (v2 == null) v2 = runtime.triggers().triggerProgram(trigger);
430 460 TriggerProgramV2.EventBinding binding = v2.events().stream()
431 .filter(value -> value.type().equals(eventType)).findFirst().orElse(null);
461 .filter(value -> value.type().equals(eventType))
462 .filter(value -> eventBindingMatches(value, baseContext)).findFirst().orElse(null);
432 463 if (binding == null) continue;
433 464 List<String> unsupported = unsupportedOnlineActions(program);
434 465 if (eventType.equals("player.leave") && !unsupported.isEmpty()) continue;
435 466 Map<String, Object> context = contextWithVariables(trigger, baseContext);
436 467 TriggerDefinition.TriggerEvent matchingEvent = new TriggerDefinition.TriggerEvent(
437 binding.type(), binding.configuration());
438 if (!eventBindingMatches(binding, context)
439 || !protectionEventMatches(matchingEvent, context)
468 binding.type(), binding.configuration(), binding.arguments(), List.of());
469 if (!protectionEventMatches(matchingEvent, context)
440 470 || !TriggerEvaluator.matches(program, context)
441 471 || !admitProtectionCooldown(trigger, matchingEvent, context)) continue;
442 472 Map<String, Object> vmVariables = v2Variables(v2, context);
@@ -452,6 +482,10 @@ final class ForgeTriggerService {
452 482
453 483 private static boolean eventBindingMatches(
454 484 TriggerProgramV2.EventBinding binding, Map<String, Object> context) {
485 if (TriggerCommandConfiguration.EVENT_TYPE.equals(binding.type())) {
486 return binding.configuration().getOrDefault("command", "")
487 .equals(Objects.toString(context.get("command.name"), ""));
488 }
455 489 if (binding.type().startsWith("region.")) {
456 490 return binding.configuration().getOrDefault("regionId", "")
457 491 .equals(Objects.toString(context.get("region.id"), ""));
Modified platform/shared/src/test/java/com/xfestudio/xfeservermanager/platform/forge/ForgeTriggerServiceTest.java +27 -0
@@ -406,6 +406,33 @@ class ForgeTriggerServiceTest {
406 406 }
407 407 }
408 408
409 @Test
410 void discoversTypedCommandBindingsFromEveryV2Event() {
411 TriggerDefinition definition = definition("log", Map.of("message", "command"));
412 TriggerDefinition.CommandArgument target = new TriggerDefinition.CommandArgument(
413 "target", "player", "", false, "", "", "", List.of("@s"), List.of());
414 TriggerProgramV2.EventBinding command = new TriggerProgramV2.EventBinding(
415 UUID.randomUUID(), "player.command_trigger", Map.of("command", "inspect"),
416 List.of(target));
417 TriggerProgramV2 program = new TriggerProgramV2(2, List.of(
418 new TriggerProgramV2.EventBinding(UUID.randomUUID(), "player.join", Map.of()), command),
419 List.of(), List.of(), List.of());
420
421 List<ForgeTriggerService.CommandBinding> bindings = ForgeTriggerService.commandBindings(
422 List.of(definition), Map.of(definition.id(), program));
423
424 assertEquals(1, bindings.size());
425 assertEquals("inspect", bindings.get(0).command());
426 assertEquals(List.of(target), bindings.get(0).argumentTree());
427
428 TriggerProgramV2 duplicate = new TriggerProgramV2(2,
429 List.of(command, new TriggerProgramV2.EventBinding(UUID.randomUUID(),
430 "player.command_trigger", Map.of("command", "inspect"), List.of())),
431 List.of(), List.of(), List.of());
432 assertThrows(IllegalArgumentException.class, () -> ForgeTriggerService.commandBindings(
433 List.of(definition), Map.of(definition.id(), duplicate)));
434 }
435
409 436 @Test
410 437 void v2AuthorLiteralsKeepFormattingAndInterpolateOnlyTheirBody() {
411 438 String literal = ForgeRichTextMessage.PREFIX + "{\"version\":1,\"segments\":[{\"text\":\"Hello {player.name}\"}]}";
Modified web-ui/src/generated/openapi.ts +2 -0
@@ -2520,6 +2520,8 @@ export interface components {
2520 2520 configuration: {
2521 2521 [key: string]: string;
2522 2522 };
2523 /** @description Recursive Brigadier alternatives for player.command_trigger. Omitted by early V2 documents and migrated from configuration.arguments when edited. */
2524 arguments?: components["schemas"]["TriggerCommandArgument"][];
2523 2525 };
2524 2526 TriggerVariableDeclarationV2: {
2525 2527 /** Format: uuid */
Modified web-ui/src/lib/trigger-program-clipboard.test.ts +9 -1
@@ -102,9 +102,17 @@ describe('V2 program node clipboard', () => {
102 102
103 103 it('preserves event configuration verbatim and enforces resulting event/node/depth limits', () => {
104 104 const value = program([statement()]);
105 value.events[0] = { nodeId: 'event', type: 'player.command_trigger', configuration: { command: 'tools' },
106 arguments: [{ name: 'target', type: 'player', literal: '', optional: false, errorMessage: '', minimum: '',
107 maximum: '', suggestions: ['@s', '@a'], children: [{ name: 'message', type: 'message', literal: '',
108 optional: true, errorMessage: '', minimum: '', maximum: '', suggestions: [], children: [] }] }] };
105 109 const result = insertTriggerNode(value, { category: 'event', value: value.events[0] }, 'event');
106 expect(result.program.events[1].configuration.nodeId).toBe('configuration-data');
110 expect(result.program.events[1].configuration.command).toBe('tools');
111 expect(result.program.events[1].arguments).toEqual(value.events[0].arguments);
107 112 expect(result.program.events[1].nodeId).not.toBe('event');
113 const malformed = { ...value.events[0], arguments: [{ ...value.events[0].arguments![0], suggestions: '@s' }] };
114 expect(parseTriggerNode(serializeTriggerNode({ category: 'event',
115 value: malformed as unknown as TriggerProgramV2['events'][number] }))).toBeUndefined();
108 116 expect(triggerProgramFitsLimits(result.program)).toBe(true);
109 117 expect(triggerProgramFitsLimits(result.program, 1)).toBe(false);
110 118 expect(triggerProgramFitsLimits({ ...value, events: Array.from({ length: 33 }, () => value.events[0]) })).toBe(false);
Modified web-ui/src/lib/trigger-program-clipboard.ts +7 -1
@@ -32,8 +32,14 @@ function checker(maxNodes = 4096, maxDepth = 32) {
32 32 && array(value.elseStatements, (entry) => statement(entry, depth + 1))
33 33 && array(value.cases, (entry) => node(entry) && expression(entry.match)
34 34 && array(entry.statements, (child) => statement(child, depth + 1)));
35 const commandArgument = (value: unknown, depth = 0): boolean => object(value) && depth <= maxDepth
36 && text(value.name) && text(value.type) && text(value.literal) && typeof value.optional === 'boolean'
37 && text(value.errorMessage) && text(value.minimum) && text(value.maximum)
38 && array(value.suggestions, text)
39 && array(value.children, (entry) => commandArgument(entry, depth + 1));
35 40 const event = (value: unknown): boolean => node(value) && text(value.type) && object(value.configuration)
36 && Object.values(value.configuration).every(text);
41 && Object.values(value.configuration).every(text)
42 && (value.arguments == null || array(value.arguments, (entry) => commandArgument(entry)));
37 43 const fn = (value: unknown): boolean => node(value) && text(value.name) && text(value.returnType)
38 44 && array(value.parameters, (entry) => object(entry) && text(entry.name) && text(entry.valueType)
39 45 && ['IN', 'OUT', 'INOUT'].includes(String(entry.mode)))
Modified web-ui/src/pages/triggers.test.tsx +42 -0
@@ -282,6 +282,48 @@ describe('trigger editor state and permissions', () => {
282 282 expect(screen.getByText('高级事件配置 JSON')).toBeInTheDocument();
283 283 });
284 284
285 it('edits detailed custom-command parameters in V2 and migrates compatibility names on save', async () => {
286 const command = trigger({
287 schemaVersion: 2,
288 event: { type: 'player.command_trigger', configuration: { command: 'tools', arguments: 'target message' } },
289 events: [{ nodeId: '10000000-0000-0000-0000-000000000001', type: 'player.command_trigger',
290 configuration: { command: 'tools', arguments: 'target message' } }],
291 declarations: [], functions: [], statements: [],
292 });
293 const api = client({ data: workspace([command]) });
294 const update = vi.spyOn(api, 'updateTrigger').mockImplementation(async (value) => ({
295 trigger: value, workspace: workspace([value]),
296 }));
297 const user = userEvent.setup();
298 renderTriggers(api);
299
300 await user.click(await screen.findByRole('button', { name: /Alpha trigger/ }));
301 expect(screen.getByRole('article', { name: '参数 1' })).toBeInTheDocument();
302 expect(screen.getByRole('article', { name: '参数 1.1' })).toBeInTheDocument();
303 expect(screen.getByText('/tools <target> <message>')).toBeInTheDocument();
304
305 const firstArgument = screen.getByRole('article', { name: '参数 1' });
306 await user.selectOptions(within(firstArgument).getByLabelText('参数 1 类型'), 'player');
307 await user.type(within(firstArgument).getByPlaceholderText('在线玩家会由游戏自动补全'), '@s, @a');
308 await user.click(screen.getByRole('button', { name: '保存' }));
309
310 const expectedArguments = [{
311 name: 'target', type: 'player', literal: '', optional: false,
312 errorMessage: '', minimum: '', maximum: '', suggestions: ['@s', '@a'],
313 children: [{
314 name: 'message', type: 'word', literal: '', optional: false,
315 errorMessage: '', minimum: '', maximum: '', suggestions: [], children: [],
316 }],
317 }];
318 await waitFor(() => expect(api.validateTriggerV2).toHaveBeenCalledWith(expect.objectContaining({
319 events: [expect.objectContaining({ configuration: { command: 'tools' }, arguments: expectedArguments })],
320 })));
321 expect(update).toHaveBeenCalledWith(expect.objectContaining({
322 event: expect.objectContaining({ configuration: { command: 'tools' }, arguments: expectedArguments }),
323 events: [expect.objectContaining({ configuration: { command: 'tools' }, arguments: expectedArguments })],
324 }));
325 });
326
285 327 it('previews actual legacy and typed conditions, rich messages, and live parameter edits in the tree', async () => {
286 328 const legacy = v2Expression({ kind: 'FUNCTION', name: 'legacy_condition', valueType: 'bool', arguments: [
287 329 v2Expression({ valueType: 'record', literal: { field: 'player.firstJoin', operator: 'eq', value: 'true' } }),
Modified web-ui/src/pages/triggers.tsx +33 -23
@@ -1208,7 +1208,9 @@ function TriggerEditor({ value, catalog, writable, canExecuteCommands, commandLo
1208 1208 const eventTypes = catalog.events.includes('custom') ? catalog.events : [...catalog.events, 'custom'];
1209 1209 const selectableEvents = !customEvent && !eventTypes.includes(value.event.type)
1210 1210 ? [value.event.type, ...eventTypes] : eventTypes;
1211 const commandArguments = [...new Set(commandArgumentNames(value.event)
1211 const v2Program = triggerV2Program(value);
1212 const commandArguments = [...new Set((v2Program?.events ?? [value.event])
1213 .flatMap(commandArgumentNames)
1212 1214 .filter((argument) => commandPartPattern.test(argument)))];
1213 1215 const stateVariables = (value.event.variables ?? []).filter((variable) => triggerVariableNameIsValid(variable.name));
1214 1216 const localVariables = stateVariables.filter((variable) => (variable.visibility ?? 'trigger') === 'trigger');
@@ -1237,7 +1239,6 @@ function TriggerEditor({ value, catalog, writable, canExecuteCommands, commandLo
1237 1239 const suggestedFields = [...new Set([...eventFieldSuggestions(value.event, catalog),
1238 1240 ...availableGlobals.map((variable) => `global.${variable.name}`)])];
1239 1241 const actionNodeCount = countActionNodes(value.actions);
1240 const v2Program = triggerV2Program(value);
1241 1242 const simulate = async () => {
1242 1243 if (!value.id || simulating) return;
1243 1244 setSimulating(true);
@@ -1451,7 +1452,7 @@ function TriggerProgramWorkspace({ value, program, catalog, writable, owner, zh,
1451 1452 const first = next.events[0];
1452 1453 onChange({ ...value, schemaVersion: 2, events: next.events, declarations: next.declarations,
1453 1454 functions: next.functions, statements: next.statements,
1454 event: { type: first.type, configuration: first.configuration,
1455 event: { type: first.type, configuration: first.configuration, arguments: first.arguments,
1455 1456 variables: next.declarations.map(v2VariableProjection) } });
1456 1457 };
1457 1458 const undo = () => {
@@ -1865,8 +1866,11 @@ function EventBindingInspector({ value, catalog, zh, onChange }: { value: Trigge
1865 1866 const l = (chinese: string, english: string) => zh ? chinese : english;
1866 1867 const custom = value.type === 'custom' || value.type.startsWith('custom.');
1867 1868 return <div className="galaxy-inspector__fields"><Field label={l('事件类型', 'Event type')}>
1868 <Select value={custom ? 'custom' : value.type} onChange={(event) => onChange({ ...value,
1869 type: event.target.value, configuration: defaultV2EventConfiguration(event.target.value) })}>
1869 <Select value={custom ? 'custom' : value.type} onChange={(event) => {
1870 const type = event.target.value;
1871 onChange({ ...value, type, configuration: defaultV2EventConfiguration(type),
1872 arguments: type === 'player.command_trigger' ? [] : undefined });
1873 }}>
1870 1874 {catalog.events.map((entry) => <option key={entry} value={entry}>{eventLabel(entry, zh)}</option>)}</Select></Field>
1871 1875 {custom && <Field label={l('自定义事件 ID', 'Custom event ID')}
1872 1876 hint={l('填写发布模组的命名空间与事件名,例如 custom.mymod.quest_completed。',
@@ -1875,14 +1879,14 @@ function EventBindingInspector({ value, catalog, zh, onChange }: { value: Trigge
1875 1879 onChange={(event) => onChange({ ...value, type: event.target.value.trim().toLowerCase() || 'custom' })} /></Field>}
1876 1880 <p className="galaxy-context-help"><strong>{eventLabel(value.type, zh)}</strong>
1877 1881 <span>{eventDescription(value.type, zh)}</span><code>{value.type}</code></p>
1878 <V2EventConfigurationFields value={value} zh={zh} onChange={onChange} />
1882 <V2EventConfigurationFields value={value} catalog={catalog} zh={zh} onChange={onChange} />
1879 1883 <details className="galaxy-json"><summary>{l('高级事件配置 JSON', 'Advanced event configuration JSON')}</summary>
1880 1884 <JsonValueEditor label={l('事件配置', 'Event configuration')} value={value.configuration}
1881 1885 onCommit={(configuration) => onChange({ ...value, configuration: configuration as Record<string, string> })} /></details></div>;
1882 1886 }
1883 1887
1884 function V2EventConfigurationFields({ value, zh, onChange }: { value: TriggerEventBindingLike;
1885 zh: boolean; onChange: (value: TriggerEventBindingLike) => void }) {
1888 function V2EventConfigurationFields({ value, catalog, zh, onChange }: { value: TriggerEventBindingLike;
1889 catalog: TriggerCatalog; zh: boolean; onChange: (value: TriggerEventBindingLike) => void }) {
1886 1890 const l = (chinese: string, english: string) => zh ? chinese : english;
1887 1891 const update = (name: string, next: string) => onChange({ ...value,
1888 1892 configuration: { ...value.configuration, [name]: next } });
@@ -1897,16 +1901,8 @@ function V2EventConfigurationFields({ value, zh, onChange }: { value: TriggerEve
1897 1901 if (value.type.startsWith('protection.')) return <ProtectionEventFields
1898 1902 event={{ type: value.type, configuration: value.configuration }} zh={zh}
1899 1903 onChange={(event) => onChange({ ...value, configuration: event.configuration })} />;
1900 if (value.type === 'player.command_trigger') return <div className="galaxy-event-fields">
1901 <Field label={l('自定义命令', 'Custom command')}
1902 hint={l('不含 /,只能使用小写字母、数字、下划线和连字符。', 'Omit /; use lowercase letters, numbers, underscores, and hyphens.')}>
1903 <Input value={value.configuration.command ?? ''} placeholder="rules" pattern="[a-z][a-z0-9_-]{0,31}"
1904 onChange={(event) => update('command', event.target.value.trim().toLowerCase())} /></Field>
1905 <Field label={l('参数名称(兼容模式)', 'Argument names (compatibility mode)')}
1906 hint={l('用空格分隔,将生成 args.<名称> 事件响应;复杂类型参数请继续使用旧版参数树。',
1907 'Separate names with spaces to expose args.<name>; keep using the legacy argument tree for complex typed arguments.')}>
1908 <Input value={value.configuration.arguments ?? ''} placeholder="target amount"
1909 onChange={(event) => update('arguments', event.target.value.toLowerCase())} /></Field></div>;
1904 if (value.type === 'player.command_trigger') return <CommandTriggerFields
1905 event={value} catalog={catalog} zh={zh} onChange={onChange} />;
1910 1906 if (value.type.startsWith('region.')) return <div className="galaxy-event-fields">
1911 1907 <Field label={l('区域 ID', 'Region ID')} hint={l('同一个 ID 的几何定义必须完全一致。', 'Geometry must be identical for every binding with the same ID.')}>
1912 1908 <Input value={value.configuration.regionId ?? ''} placeholder="spawn.safe_zone" pattern="[a-z][a-z0-9_.-]{1,63}"
@@ -2208,8 +2204,12 @@ function ProtectionEventFields({ event, zh, onChange }: {
2208 2204 </div>;
2209 2205 }
2210 2206
2211 function CommandTriggerFields({ event, catalog, zh, onChange }: {
2212 event: TriggerEventSpec; catalog: TriggerCatalog; zh: boolean; onChange: (event: TriggerEventSpec) => void;
2207 type CommandArgumentEventLike = {
2208 type: string; configuration: Record<string, string>; arguments?: TriggerCommandArgument[];
2209 };
2210
2211 function CommandTriggerFields<T extends CommandArgumentEventLike>({ event, catalog, zh, onChange }: {
2212 event: T; catalog: TriggerCatalog; zh: boolean; onChange: (event: T) => void;
2213 2213 }) {
2214 2214 const l = (chinese: string, english: string) => zh ? chinese : english;
2215 2215 const command = event.configuration.command ?? '';
@@ -2905,14 +2905,14 @@ function mapActionTree(actions: TriggerAction[], transform: (action: TriggerActi
2905 2905 });
2906 2906 }
2907 2907
2908 function commandArgumentNames(event: TriggerEventSpec): string[] {
2908 function commandArgumentNames(event: CommandArgumentEventLike): string[] {
2909 2909 if (event.type.trim().toLowerCase() !== 'player.command_trigger') return [];
2910 2910 if ((event.arguments?.length ?? 0) > 0) return flattenCommandArguments(event.arguments ?? []).map((item) => item.name);
2911 2911 const raw = event.configuration.arguments ?? '';
2912 2912 return raw.trim() ? raw.trim().split(/\s+/) : [];
2913 2913 }
2914 2914
2915 function commandArgumentTree(event: TriggerEventSpec): TriggerCommandArgument[] {
2915 function commandArgumentTree(event: CommandArgumentEventLike): TriggerCommandArgument[] {
2916 2916 if ((event.arguments?.length ?? 0) > 0) return event.arguments ?? [];
2917 2917 const legacy = (event.configuration.arguments ?? '').trim();
2918 2918 if (!legacy) return [];
@@ -3283,7 +3283,7 @@ function triggerIsSavable(value: TriggerDefinition, canExecuteCommands: boolean,
3283 3283 if (!canExecuteCommands && triggerUsesCommandAction(value)) return false;
3284 3284 const v2 = triggerV2Program(value);
3285 3285 if (v2) return v2.events.length > 0 && v2.events.length <= 32
3286 && v2.events.every((event) => Boolean(event.nodeId && event.type.trim()))
3286 && v2.events.every(v2EventBindingIsValid)
3287 3287 && uniqueNodeIds(v2).size === countV2Nodes(v2);
3288 3288 if (value.mode === 'code') return Boolean(value.script.trim()) && value.script.length <= 65_536;
3289 3289 const eventType = value.event.type.trim().toLowerCase();
@@ -3296,6 +3296,16 @@ function triggerIsSavable(value: TriggerDefinition, canExecuteCommands: boolean,
3296 3296 && actionTreeIsValid(value.actions, value.event.type, catalog);
3297 3297 }
3298 3298
3299 function v2EventBindingIsValid(event: TriggerEventBindingLike): boolean {
3300 if (!event.nodeId || !event.type.trim() || event.type.length > 128) return false;
3301 const entries = Object.entries(event.configuration);
3302 if (entries.length > 16 || entries.some(([key, value]) => !key.trim() || key.length > 80
3303 || typeof value !== 'string' || value.length > 4_096)) return false;
3304 if (event.type !== 'player.command_trigger') return (event.arguments?.length ?? 0) === 0;
3305 return eventConfigurationIsValid({ type: event.type, configuration: event.configuration,
3306 arguments: event.arguments });
3307 }
3308
3299 3309 function eventConfigurationIsValid(event: TriggerEventSpec): boolean {
3300 3310 const variables = event.variables ?? [];
3301 3311 if (variables.some((variable, index) => !triggerVariableNameIsValid(variable.name)
Modified web-ui/src/styles.css +3 -0
Modified web-ui/src/types.ts +2 -0