Repository navigation
Expand file tree
/
Copy pathkether-editor.js
More file actions
4354 lines (4139 loc) · 179 KB
/
Copy pathkether-editor.js
File metadata and controls
4354 lines (4139 loc) · 179 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================
// Kether 可视化编辑器 (Scratch 风格积木块)
// ============================================
(function () {
'use strict';
// ============================================
// 常量定义
// ============================================
const DEFAULT_PROVIDERS = ['Kether', 'TabooLib', 'Chemdah', 'Adyeshach', '内置'];
const CAT_COLORS = {
'实体操作': '#c06262', '数据与变量': '#5edf85', '文本与运算': '#437a32',
'游戏机制': '#1566d1', '系统管理': '#ee4d4d', '逻辑判断': '#55939e',
'世界与坐标': '#8ad195', '物品管理': '#ad9a69', '脚本控制': '#d115a8',
'界面与显示': '#3e5255', '时间与日期': '#1a182c', '基本': '#6b7475'
};
const DEFAULT_CAT_COLOR = '#7f8c8d';
var SLOT_HELP = '点击或者拖拽到此处以添加动作<br>CTRL+点击 快速添加文本<br>SHIFT+点击 快速添加动作组<br>CTRL+SHIFT+点击 快速添加列表';
// 原始分类 → 合并后的大类
const CAT_GROUP = {
实体控制: '实体操作', 数据处理: '数据与变量', 变量操作: '数据与变量',
文本处理: '文本与运算', 数学运算: '文本与运算', 正则表达式: '文本与运算',
游戏系统: '游戏机制', 经济: '游戏机制', 游戏机制: '游戏机制',
药水效果: '游戏机制', 网络信息: '游戏机制',
系统配置: '系统管理', 服务器管理: '系统管理',
逻辑与数学: '逻辑判断',
世界与坐标: '世界与坐标', 物品管理: '物品管理',
脚本控制: '脚本控制', 脚本操作: '脚本控制', 命令执行: '脚本控制',
权限操作: '脚本控制', 事件处理: '脚本控制', 函数操作: '脚本控制',
界面交互: '界面与显示', 消息显示: '界面与显示', 视觉特效: '界面与显示',
模型处理: '界面与显示', 音效操作: '界面与显示',
时间与日期: '时间与日期',
};
// 模块颜色增强(部分模块颜色过暗/过淡)
const COLOR_ENHANCE = {
Invero: '#1a8a8a', Zaphkiel: '#a0a0a0',
};
// 动作名称中文化
const NAME_CN = {
check: '检查', tell: '发送消息', print: '输出', give: '给予', take: '取出',
set: '设置', delete: '删除', remove: '移除', create: '创建', spawn: '生成',
kill: '杀死', damage: '伤害', heal: '治疗', teleport: '传送', play: '播放',
stop: '停止', wait: '等待', loop: '循环', break: '中断', return: '返回',
random: '随机数', math: '数学计算', format: '格式化', eval: '表达式计算',
papi: '变量解析', placeholderapi: '变量解析', command: '执行命令', permission: '权限检测',
hasPermission: '权限判断', has: '拥有判断', item: '物品操作', inventory: '背包操作',
open: '打开', close: '关闭', click: '点击事件', sound: '音效',
particle: '粒子效果', title: '标题显示', actionbar: '操作栏', bossbar: 'Boss血条',
json: 'JSON操作', yaml: 'YAML操作', http: '网络请求',
if_else: '如果/判断', all: '全部条件', any: '任一条件',
while: '循环执行', repeat: '重复执行', foreach: '遍历循环', for: '遍历循环',
__true__: '真', __false__: '假',
};
// 参数标签中文化
const PARAM_LABEL_CN = {
symbol: '符号', action: '动作', int: '整数', double: '小数',
number: '数字', string: '文本', token: '参数', player: '玩家',
item: '物品', location: '坐标', world: '世界', time: '时间',
message: '消息', permission: '权限', list: '列表',
};
function blockLabelHtml(block, semanticOverride) {
const cn = semanticOverride || NAME_CN[block.actionId];
const nameMode = (_state && _state.settings) ? _state.settings.nameMode : 'cn-en';
if (nameMode === 'cn') {
return '<span class="ke-b-label">' + esc(cn || block.name) + '</span>';
}
if (nameMode === 'en') {
return '<span class="ke-b-label">' + esc(block.name) + '</span>';
}
// 'cn-en' (default)
if (cn) {
return '<span class="ke-b-label">' + esc(cn) + '</span><span class="ke-b-label-sub">' + esc(block.name) + '</span>';
}
return '<span class="ke-b-label">' + esc(block.name) + '</span>';
}
// 显式定义控制流语句的参数结构
const CONTROL_PARAMS = {
if_else: [
{ type: 'action', label: '条件', key: 'condition' },
{ type: 'body-then', label: '执行', key: 'thenBody' },
{ type: 'body-else', label: '否则', key: 'elseBody', optional: true },
],
all: [
{ type: 'action-list', label: '条件列表', key: 'conditions' },
],
any: [
{ type: 'action-list', label: '条件列表', key: 'conditions' },
],
while: [
{ type: 'action', label: '条件', key: 'condition' },
{ type: 'body', label: '执行', key: 'body' },
],
repeat: [
{ type: 'text', label: '次数', key: 'count' },
{ type: 'body', label: '执行', key: 'body' },
],
foreach: [
{ type: 'text', label: '变量', key: 'varName' },
{ type: 'action', label: '列表', key: 'list' },
{ type: 'body', label: '执行', key: 'body' },
],
'case & when': [
{ type: 'action', label: '条件', key: 'condition' },
],
};
// 数据
let _actions = [];
let _modules = [];
let _categorizedActions = {};
let _categoryList = [];
let _state = null;
let _clipboard = null;
let _keMouseX = 0, _keMouseY = 0;
let _savedBlocks = []; // { name, code }
let _stashBlocks = [];
let _commonBlocks = []; // 常用积木(来自文件 + 用户自定义)
let _userCommonBlocks = []; // 用户自定义常用积木(localStorage)
let _COMMON_CAT = '⭐ 常用';
let _undoStack = [];
let _redoStack = [];
let _undoDuringRedo = false;
const _MAX_UNDO = 50;
function _pushUndo(state) {
if (_undoDuringRedo) return;
_undoStack.push(JSON.parse(JSON.stringify(state.blocks)));
if (_undoStack.length > _MAX_UNDO) _undoStack.shift();
_redoStack = [];
_updateUndoButtons();
}
function _undo(state, overlay) {
if (_undoStack.length === 0) return;
_redoStack.push(JSON.parse(JSON.stringify(state.blocks)));
state.blocks = JSON.parse(JSON.stringify(_undoStack.pop()));
state.mode = 'visual';
_undoDuringRedo = true;
switchMode(overlay, state);
updatePreview(overlay, state);
_undoDuringRedo = false;
_updateUndoButtons();
}
function _redo(state, overlay) {
if (_redoStack.length === 0) return;
_undoStack.push(JSON.parse(JSON.stringify(state.blocks)));
state.blocks = JSON.parse(JSON.stringify(_redoStack.pop()));
state.mode = 'visual';
_undoDuringRedo = true;
switchMode(overlay, state);
updatePreview(overlay, state);
_undoDuringRedo = false;
_updateUndoButtons();
}
function _updateUndoButtons() {
const ub = document.getElementById('ke-undo');
const rb = document.getElementById('ke-redo');
if (ub) ub.disabled = _undoStack.length === 0;
if (rb) rb.disabled = _redoStack.length === 0;
}
// ============================================
// localStorage 持久化
// ============================================
function loadPersistentData() {
try {
const s = localStorage.getItem('kether_editor_settings');
if (s) _savedSettings = JSON.parse(s);
// 加载编辑器主配置(分类颜色、字体等)
const cfg = localStorage.getItem('editorConfig');
if (cfg) {
const config = JSON.parse(cfg);
if (config.categoryColors) {
Object.assign(CAT_COLORS, config.categoryColors);
}
_savedSettings._editorConfig = config;
}
const b = localStorage.getItem('kether_saved_blocks');
if (b) _savedBlocks = JSON.parse(b);
const st = localStorage.getItem('kether_stash_blocks');
if (st) _stashBlocks = JSON.parse(st);
const uc = localStorage.getItem('kether_user_common');
if (uc) _userCommonBlocks = JSON.parse(uc);
} catch (e) { /* ignore */ }
}
let _savedSettings = {};
function saveSettings(settings) {
_savedSettings = settings;
try { localStorage.setItem('kether_editor_settings', JSON.stringify(settings)); } catch (e) {}
}
function saveSavedBlocks() {
try { localStorage.setItem('kether_saved_blocks', JSON.stringify(_savedBlocks)); } catch (e) {}
}
function saveStashBlocks() {
try { localStorage.setItem('kether_stash_blocks', JSON.stringify(_stashBlocks)); } catch (e) {}
}
function saveUserCommonBlocks() {
try { localStorage.setItem('kether_user_common', JSON.stringify(_userCommonBlocks)); } catch (e) {}
}
// ============================================
// 工具
// ============================================
function esc(s) {
if (typeof s !== 'string') return '';
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function catColor(cat) {
if (CAT_COLORS[cat]) return CAT_COLORS[cat];
for (const [k, v] of Object.entries(CAT_COLORS)) {
if (cat.includes(k)) return v;
}
return DEFAULT_CAT_COLOR;
}
function modColor(provider) {
const mod = _modules.find(m => m.name === provider);
return mod ? mod.color : '#7f8c8d';
}
function isDefaultProvider(provider) {
return DEFAULT_PROVIDERS.includes(provider);
}
function textColorForBg(hexColor) {
const c = hexColor.replace('#', '');
if (c.length < 6) return '#fff';
const r = parseInt(c.slice(0, 2), 16);
const g = parseInt(c.slice(2, 4), 16);
const b = parseInt(c.slice(4, 6), 16);
// 相对亮度公式 (ITU-R BT.709)
const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return lum > 140 ? '#000' : '#fff';
}
function getBlockColor(block) {
if (_state && _state.settings && _state.settings.colorMode === 'category') {
let cat;
if (block._preferredCat) {
cat = block._preferredCat;
} else {
const cats = block.categories;
if (cats && cats.length > 0) {
cat = CAT_GROUP[cats[0]] || cats[0];
}
}
if (cat) return catColor(cat);
}
return block.color;
}
function actionColor(act, preferredCat) {
if (_state && _state.settings && _state.settings.colorMode === 'category') {
let cat;
if (preferredCat) {
cat = preferredCat;
} else {
const cats = act.categories;
if (cats && cats.length > 0) {
cat = CAT_GROUP[cats[0]] || cats[0];
}
}
if (cat) return catColor(cat);
}
return act._providerColor;
}
function resetBlockIds(b) {
b.id = uid();
(b.thenBlocks || []).forEach(resetBlockIds);
(b.elseBlocks || []).forEach(resetBlockIds);
(b.condBlocks || []).forEach(resetBlockIds);
if (b._actSlots) {
for (const k of Object.keys(b._actSlots)) {
b._actSlots[k].forEach(resetBlockIds);
}
}
}
function cloneBlock(block) {
return JSON.parse(JSON.stringify(block));
}
// ============================================
// 加载动作定义
// ============================================
async function loadActions() {
if (_actions.length > 0) return;
try {
const resp = await fetch('desc/kether-actions.json');
_modules = await resp.json();
const all = [];
const catMap = {};
for (const mod of _modules) {
mod.color = COLOR_ENHANCE[mod.name] || mod.color;
for (const act of mod.actions) {
// Expand syntaxs into individual action entries
if (act.syntaxs) {
for (const [key, variant] of Object.entries(act.syntaxs)) {
const entry = Object.assign({}, act);
entry.id = act.id + '_' + key;
entry.name = act.name + ' (' + key + ')';
entry.syntax = variant.syntax;
entry.example = variant.example || act.example;
entry.semantic = variant.semantic || act.semantic;
entry.syntaxs = undefined;
entry._providerColor = mod.color;
entry._module = mod.name;
entry._variantOf = act.id;
all.push(entry);
const seen = new Set();
for (const cat of entry.categories) {
const group = CAT_GROUP[cat] || cat;
if (seen.has(group)) continue;
seen.add(group);
if (!catMap[group]) catMap[group] = [];
catMap[group].push(entry);
}
}
} else {
act._providerColor = mod.color;
act._module = mod.name;
all.push(act);
const seen = new Set();
for (const cat of act.categories) {
const group = CAT_GROUP[cat] || cat;
if (seen.has(group)) continue;
seen.add(group);
if (!catMap[group]) catMap[group] = [];
catMap[group].push(act);
}
}
}
}
_actions = all;
// 注入内置积木块
for (const def of _BUILTIN_DEFS) {
def._module = '内置';
_actions.push(def);
for (const cat of def.categories) {
if (!catMap[cat]) catMap[cat] = [];
catMap[cat].push(def);
}
}
const order = Object.keys(CAT_COLORS);
_categoryList = Object.keys(catMap).sort((a, b) => {
const ia = order.indexOf(a);
const ib = order.indexOf(b);
if (ia >= 0 && ib >= 0) return ia - ib;
if (ia >= 0) return -1;
if (ib >= 0) return 1;
return a.localeCompare(b);
});
_categorizedActions = catMap;
} catch (e) {
console.error('[KE] Failed to load actions:', e);
}
}
async function loadCommonBlocks() {
try {
const resp = await fetch('desc/common-kether.json');
const data = await resp.json();
_commonBlocks = [];
for (const [id, entry] of Object.entries(data)) {
_commonBlocks.push({ id: id, isUser: false, ...entry });
}
} catch (e) { console.warn('[KE] 无法加载常用积木文件:', e); }
// 合并用户自定义
for (const ub of _userCommonBlocks) {
if (!_commonBlocks.find(function(b) { return b.id === ub.id; })) {
_commonBlocks.push(ub);
}
}
}
function resolveCommonSyntax(syntax, params, values) {
var result = syntax;
for (var key in params) {
var val = values[key];
if (val != null) {
result = result.split('%' + key + '%').join(val);
}
}
return result;
}
function addUserCommonBlock(name, syntax) {
var id = 'user_' + Date.now().toString(36);
_userCommonBlocks.push({ id: id, name: name, isUser: true, desc: '', syntax: syntax, params: {} });
saveUserCommonBlocks();
// 合并到 _commonBlocks
if (!_commonBlocks.find(function(b) { return b.id === id; })) {
_commonBlocks.push(_userCommonBlocks[_userCommonBlocks.length - 1]);
}
}
function removeUserCommonBlock(id) {
_userCommonBlocks = _userCommonBlocks.filter(function(b) { return b.id !== id; });
_commonBlocks = _commonBlocks.filter(function(b) { return b.id !== id; });
saveUserCommonBlocks();
}
// ============================================
// 块数据模型
// ============================================
function uid() {
var _keUidCounter = window._keUidCounter || 0;
_keUidCounter++;
window._keUidCounter = _keUidCounter;
return Date.now().toString(36) + '_' + (_keUidCounter).toString(36) + '_' + Math.random().toString(36).slice(2, 6);
}
function createBlock(action) {
const b = {
id: uid(),
actionId: action.id,
name: action.name,
provider: action.provider,
module: action._module,
color: action._providerColor || modColor(action.provider),
categories: action.categories,
isControl: !!CONTROL_PARAMS[action.id],
params: [],
values: {},
children: [],
thenBlocks: [],
elseBlocks: [],
condBlocks: [], // for all/any
customCode: null,
_actionLiterals: {},
_actSlots: {},
_actionQuoted: {},
};
// 使用显式控制流参数或从语法解析
if (CONTROL_PARAMS[action.id]) {
b.params = CONTROL_PARAMS[action.id];
} else {
b.params = parseSyntax(action.syntax);
}
// case & when 初始化 when 分支
if (action.id === 'case & when') {
b._whenBranches = [
{ id: uid(), condition: '', condBlocks: [], blocks: [] },
];
}
// 初始化值
for (const p of b.params) {
if (p.type === 'action' || p.type === 'body' || p.type === 'body-then' || p.type === 'body-else' || p.type === 'action-list') continue;
b.values[p.key || p.label] = '';
}
return b;
}
function createCustomBlock(code) {
return {
id: uid(),
actionId: '__custom__',
name: '自定义',
provider: '', module: '', color: '#ffd600',
categories: [], params: [], values: { code: code || '' },
isControl: false,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {},
customCode: code || '',
};
}
// ============================================
// 值积木块(文本、无引号、列表)
// ============================================
function createTextBlock(value) {
return {
id: uid(),
actionId: '__text__',
name: '文本值',
provider: '内置', module: '', color: '#bdbdbd',
categories: ['_值'], params: [], values: { text: value || '' },
isControl: false, isValueBlock: true,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {}, _quoted: true,
};
}
function createUnquotedBlock(value) {
return {
id: uid(),
actionId: '__unquoted__',
name: '无引号值',
provider: '内置', module: '', color: '#bdbdbd',
categories: ['_值'], params: [], values: { text: value || '' },
isControl: false, isValueBlock: true,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {},
};
}
function createListBlock() {
return {
id: uid(),
actionId: '__list__',
name: '列表',
provider: '内置', module: '', color: '#888888',
categories: ['基本'], params: [], values: { separator: ' ' },
isControl: false, isValueBlock: true,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {},
};
}
function createBraceBlock() {
return {
id: uid(),
actionId: '__brace__',
name: '动作组',
provider: '内置', module: '', color: '#555555',
categories: ['基本'], params: [], values: {},
isControl: false,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {},
};
}
function createTrueBlock() {
return {
id: uid(),
actionId: '__true__',
name: 'true',
provider: '内置', module: '', color: '#6b7475',
categories: ['基本'], params: [], values: {},
isControl: false, isValueBlock: true,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {},
};
}
function createFalseBlock() {
return {
id: uid(),
actionId: '__false__',
name: 'false',
provider: '内置', module: '', color: '#6b7475',
categories: ['基本'], params: [], values: {},
isControl: false, isValueBlock: true,
children: [], thenBlocks: [], elseBlocks: [], condBlocks: [],
_actSlots: {}, _actionQuoted: {},
};
}
// 内置积木块定义(文本值、数值、列表、动作组)
const _BUILTIN_DEFS = [
{ id: '__text__', name: '文本值', syntax: '"text"', provider: '内置', _providerColor: '#bdbdbd', color: '#bdbdbd', categories: ['基本'] },
{ id: '__true__', name: 'true', syntax: 'true', provider: '内置', _providerColor: '#6b7475', color: '#6b7475', categories: ['基本'] },
{ id: '__false__', name: 'false', syntax: 'false', provider: '内置', _providerColor: '#6b7475', color: '#6b7475', categories: ['基本'] },
{ id: '__list__', name: '列表', syntax: '[items]', provider: '内置', _providerColor: '#888888', color: '#888888', categories: ['基本'] },
{ id: '__brace__', name: '动作组', syntax: '{actions}', provider: '内置', _providerColor: '#555555', color: '#555555', categories: ['基本'] },
];
function createEntryBlock(type, name) {
return {
id: uid(),
actionId: '__entry__',
isEntry: true,
entryType: type || 'normal',
defName: name || 'main',
thenBlocks: [],
elseBlocks: [],
condBlocks: [],
_actSlots: {},
};
}
function expandName(name) {
// "color[ed]" → ["color", "colored"]
const m = name.match(/^(\w+)\[(\w+)\]$/);
if (m) return [m[1], m[1] + m[2]];
return [name];
}
/** Expand syntax first token to possible names: (javascript|js|$) → ["javascript","js","$"] */
function expandSyntaxFirst(syntax) {
if (!syntax) return [];
const raw = syntax.trim().split(/\s+/)[0];
if (!raw) return [];
const altMatch = raw.match(/^\((.+)\)$/);
if (altMatch) return altMatch[1].split('|').map(s => s.trim().toLowerCase());
return expandName(raw.toLowerCase());
}
// 分割语法中的 | 替代项,仅在括号外分割
function splitSyntaxFirst(syntax) {
if (!syntax) return '';
let depth = 0;
for (let i = 0; i < syntax.length; i++) {
const ch = syntax[i];
if (ch === '(') depth++;
else if (ch === ')') depth--;
else if ((ch === '|' || ch === '\n' || ch === '\r') && depth === 0) {
return syntax.substring(0, i).trim();
}
}
return syntax.trim();
}
// ============================================
// 语法解析(通用动作参数)
// ============================================
function parseSyntax(syntax) {
if (!syntax) return [];
const first = splitSyntaxFirst(syntax);
const rawTokens = first.split(/\s+/);
// 去除动作名中的 [别名] 后缀:color[ed] → color, hour[s] → hour
if (rawTokens[0]) rawTokens[0] = rawTokens[0].replace(/\[\w+\]$/, '');
// 合并被空格拆分的花括号参数:{action list} → {action list}
// 仅合并纯 {word ... word} 形式,排除 ( ) 后缀干扰
const mergedTokens = [];
for (let ri = 0; ri < rawTokens.length; ri++) {
const t = rawTokens[ri];
const next = rawTokens[ri + 1];
if (t.startsWith('{') && !t.endsWith('}') && !t.includes(')') && next && next.endsWith('}') && !next.startsWith('{') && !next.includes(')')) {
mergedTokens.push(t + ' ' + next);
ri++;
} else {
mergedTokens.push(t);
}
}
// 去除可选组标记 [ ],保留内部内容
const tokens = [];
for (const t of mergedTokens) {
let s = t;
if (s.startsWith('[')) s = s.slice(1);
else if (s.startsWith('\\[')) s = s.slice(2);
if (s.endsWith(']')) s = s.slice(0, -1);
else if (s.endsWith('\\]')) s = s.slice(0, -2);
if (s) tokens.push(s);
}
const params = [];
for (let i = 1; i < tokens.length; i++) {
const t = tokens[i];
if (t.startsWith('(') && t.endsWith(')')) {
params.push({ type: 'select', label: '', key: i.toString(), options: t.slice(1, -1).split('|').map(s => s.trim()) });
} else if (t === '{action}') {
params.push({ type: 'action', label: '', key: 'action' + i });
} else if (t === '{action' || t.startsWith('{action')) {
const rest = t.slice(8, -1);
params.push({ type: 'action', label: rest || '', key: 'action' + i });
} else if (t === '{aciton}') {
// 兼容 typo:{aciton} → 视为 {action}
params.push({ type: 'action', label: '', key: 'action' + i });
} else if (t === '{aciton' || t.startsWith('{aciton')) {
const rest = t.slice(8, -1);
params.push({ type: 'action', label: rest || '', key: 'action' + i });
} else if (t.startsWith('<') && t.endsWith('>')) {
// 兼容 Invero 的 <param> 语法
const inner = t.slice(1, -1);
params.push({ type: 'text', label: inner, key: 'param' + i });
} else if (t.startsWith('{') && t.endsWith('}')) {
const inner = t.slice(1, -1);
if (inner === 'int' || inner === 'double' || inner === 'number') {
params.push({ type: 'text', label: inner, key: 'param' + i });
} else if (inner === 'token' || inner === 'string') {
params.push({ type: 'text', label: inner, key: 'param' + i });
} else if (inner.includes('list')) {
params.push({ type: 'text', label: inner, key: 'list' + i });
} else {
params.push({ type: 'text', label: inner, key: 'param' + i });
}
} else if (t.startsWith('{') && !t.endsWith('}')) {
// {token}) 之类的拆分 token,剥离后缀非字母字符
var clean = t.slice(1);
while (clean.length > 0 && !/[\w一-鿿]/.test(clean[clean.length - 1])) {
clean = clean.slice(0, -1);
}
params.push({ type: 'text', label: clean || t.slice(1), key: 'param' + i });
} else if (t.startsWith('(') && !t.endsWith(')') && t.length > 1) {
// 处理以 ( 开头的混合 token,如 (to、(by、(percent|bar
// 提取内部内容创建 select 或 keyword
const inner = t.slice(1);
if (inner.includes('|')) {
params.push({ type: 'select', label: '', key: i.toString(), options: inner.split('|').map(s => s.trim()) });
} else {
params.push({ type: 'keyword', label: inner, key: inner, value: inner });
}
} else if ((t.endsWith(')') || t.endsWith('}>')) && t.length > 1 && (t.startsWith('<') || t.startsWith('{'))) {
// 处理以 ) 或 }> 结尾的混合 token,如 <slot)>、{token})
// 剥离后缀字符
var clean = t;
while (clean.length > 1 && (clean.endsWith(')') || clean.endsWith('>') || clean.endsWith('}'))) {
clean = clean.slice(0, -1);
}
if (clean.startsWith('<') && clean.endsWith('>')) {
params.push({ type: 'text', label: clean.slice(1, -1), key: 'param' + i });
} else if (clean.startsWith('{') && clean.endsWith('}')) {
params.push({ type: 'text', label: clean.slice(1, -1), key: 'param' + i });
} else if (clean.startsWith('<')) {
params.push({ type: 'text', label: clean.slice(1), key: 'param' + i });
} else if (clean.startsWith('{')) {
params.push({ type: 'text', label: clean.slice(1), key: 'param' + i });
} else {
params.push({ type: 'keyword', label: t, key: t, value: clean });
}
} else if (t.startsWith('&') && t.length > 1) {
// Aiyatsbus ¶m → 视为可编辑文本
params.push({ type: 'text', label: t, key: 'param' + i });
} else {
// keyword (e.g., "to", "as", "in", "then", "else")
params.push({ type: 'keyword', label: t, key: t, value: t });
}
}
if (params.length === 0 && tokens.length === 1 && tokens[0].startsWith('&') && tokens[0].length > 1) {
// &{token} only: first token is both action name and param
params.push({ type: 'text', label: 'token', key: 'param1' });
}
return params;
}
// ============================================
// 代码生成
// ============================================
function generateCode(blocks) {
return blocks.map(b => blockToCode(b, '')).filter(l => l.trim()).join('\n');
}
function blockToCode(block, indent) {
if (block.actionId === '__entry__') {
if (block.entryType === 'definition') {
const body = block.thenBlocks.map(b => blockToCode(b, indent + ' ')).join('\n');
return indent + 'def ' + (block.defName || 'main') + ' = {\n' + body + '\n' + indent + '}';
}
// normal entry: just output children
return block.thenBlocks.map(b => blockToCode(b, indent)).join('\n');
}
if (block.actionId === '__custom__') return indent + (block.values.code || block.customCode || '');
if (block.actionId === '__text__') {
const v = block.values.text || '';
const quoted = block._quoted !== false;
return indent + (quoted ? '"' + v + '"' : v);
}
if (block.actionId === '__true__') return indent + 'true';
if (block.actionId === '__false__') return indent + 'false';
if (block.actionId === '__unquoted__') return indent + (block.values.text || '');
if (block.actionId === '__list__') {
const items = block.thenBlocks || [];
if (items.length === 0) return indent + '[ ]';
const parts = items.map(b => blockToCode(b, '').trim());
return indent + '[ ' + parts.join(' ') + ' ]';
}
if (block.actionId === '__brace__') {
const items = block.thenBlocks || [];
if (items.length === 0) return indent + '{ }';
const parts = items.map(b => blockToCode(b, '').trim());
if (parts.length === 1) return indent + '{ ' + parts[0] + ' }';
return indent + '{\n' + parts.map(l => indent + ' ' + l).join('\n') + '\n' + indent + '}';
}
const aid = block.actionId;
if (aid === 'if_else') return genIfElse(block, indent);
if (aid === 'all' || aid === 'any') return genAllAny(block, indent);
if (aid === 'while') return genWhile(block, indent);
if (aid === 'repeat') return genRepeat(block, indent);
if (aid === 'foreach' || aid === 'for') return genForEach(block, indent);
if (aid === 'case & when') return genCaseWhen(block, indent);
// 通用动作
const action = _actions.find(a => a.id === aid);
const syn = action ? splitSyntaxFirst(action.syntax) : aid;
const synTokens = syn.split(/\s+/);
let actionName = synTokens[0];
// 处理 (javascript|js|$) 替代语法 → javascript
const altMatch = actionName && actionName.match(/^\((.+)\)$/);
if (altMatch) actionName = altMatch[1].split('|')[0].trim();
// 去除动作名中的 [别名] 后缀:color[ed] → color
actionName = actionName.replace(/\[\w+\]$/, '');
const args = [];
// &{token} 直接输出 &+值
if (synTokens.length === 1 && synTokens[0].startsWith('&')) {
const tp = block.params.find(pp => pp.type === 'text');
const rawVal = block.values[tp ? (tp.key || tp.label) : 'param1'] || '';
return indent + '&' + (rawVal.includes(' ') ? '"' + rawVal + '"' : rawVal);
}
if (CONTROL_PARAMS[aid]) {
// 如果有控制参数定义但没被上面的特殊处理覆盖
for (const p of block.params) {
if (p.type === 'keyword') args.push(p.value);
else if (p.type === 'select') args.push(block.values[p.key || p.label] || '');
else if (p.type === 'text') {
const val = block.values[p.key || p.label] || '';
if (val) args.push(val.includes(' ') ? '"' + val + '"' : val);
} else if (p.type === 'action') {
if (block.thenBlocks.length > 0) {
args.push('{');
args.push(block.thenBlocks.map(b => blockToCode(b, '')).join(' '));
args.push('}');
}
}
}
} else {
// 从语法推导
for (let pi = 0; pi < block.params.length; pi++) {
const p = block.params[pi];
if (p.type === 'keyword') {
// 跳过后接空可选 select 的关键字(如 [as xxx])
const nextP = block.params[pi + 1];
if (nextP && nextP.type === 'select' && !block.values[nextP.key || nextP.label]) continue;
// 跳过后接空动作的关键字(如 [default {action}])
if (nextP && nextP.type === 'action') {
const k = nextP.key || nextP.label;
const isEmpty = !(block._actionLiterals && block._actionLiterals[k]) &&
!(block._actSlots && block._actSlots[k] && block._actSlots[k].length);
if (isEmpty) continue;
}
args.push(p.value); continue;
}
if (p.type === 'select') {
const val = block.values[p.key || p.label] || '';
if (val) args.push(val);
continue;
}
if (p.type === 'action') {
const key = p.key || p.label;
let code;
// 文字模式
if (block._actionLiterals && block._actionLiterals[key] !== undefined && block._actionLiterals[key] !== '') {
code = block._actionLiterals[key];
} else {
// 积木模式——从专用动作槽读取
let children;
if (block._actSlots && block._actSlots[key]) children = block._actSlots[key];
else children = block.thenBlocks || [];
if (children.length > 0) {
code = children.map(b => blockToCode(b, '')).join(' ');
}
}
if (code !== undefined && code !== '') {
const quoted = block._actionQuoted && block._actionQuoted[key] === true;
if (quoted && code.length >= 2 && code[0] === '"' && code[code.length - 1] === '"') {
args.push('"' + code.slice(1, -1) + '"');
} else {
args.push(quoted ? '"' + code + '"' : code);
}
}
continue;
}
const val = block.values[p.key || p.label] || '';
if (val) args.push(val.includes(' ') ? '"' + val + '"' : val);
}
}
const line = [actionName, ...args].join(' ');
return indent + line;
}
function genIfElse(block, indent) {
const lines = [indent + 'if'];
// 条件
const condBlocks = block.thenBlocks; // NOTE: first block goes to thenBlocks as "condition"
const thenBlocks = block.elseBlocks; // NOTE: this is a mapping trick
// Actually, let's restructure: condition is in thenBlocks[0] if it's sub-blocks,
// or in values as expression text.
// Better: for if/else, use children[0] for condition, children[1] for then, children[2] for else
// Let me redo this cleanly:
// - block.condBlocks -> condition sub-blocks
// - block.thenBlocks -> then body
// - block.elseBlocks -> else body
const condTxt = block._actionLiterals && block._actionLiterals['condition'] !== undefined
? block._actionLiterals['condition']
: block.condBlocks.map(b => blockToCode(b, '')).join(' ');
if (condTxt) {
if (condTxt.includes(' ')) lines.push('{ ' + condTxt + ' }');
else lines.push(condTxt);
}
const thenTxt = block.thenBlocks.map(b => blockToCode(b, '')).join('\n');
const elseTxt = block.elseBlocks.map(b => blockToCode(b, '')).join('\n');
if (thenTxt) {
if (block.thenBlocks.length === 1 && !block.thenBlocks[0].isControl) {
lines.push('then ' + blockToCode(block.thenBlocks[0], ''));
} else {
lines.push('then {\n' + thenTxt.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + '}');
}
}
if (elseTxt) {
if (block.elseBlocks.length === 1 && !block.elseBlocks[0].isControl) {
lines.push('else ' + blockToCode(block.elseBlocks[0], ''));
} else {
lines.push('else {\n' + elseTxt.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + '}');
}
}
return lines.join(' ');
}
function genAllAny(block, indent) {
const actionName = block.actionId; // "all" or "any"
const conds = block.condBlocks;
if (conds.length === 0) return indent + actionName + ' [ ]';
// 每个条件用 {} 包裹(防止 UNIT 返回值破坏判断)
const items = conds.map(b => {
const code = blockToCode(b, '').trim();
// 如果包含空格或含可能返回 UNIT 的动作,用 {} 包裹
if (code.includes(' ') || b.isControl) {
return '{ ' + code + ' }';
}
return code;
});
return indent + actionName + ' [ ' + items.join(' ') + ' ]';
}
function genWhile(block, indent) {
// block.condBlocks[0] = condition
const condTxt = block._actionLiterals && block._actionLiterals['condition'] !== undefined
? block._actionLiterals['condition']
: (block.condBlocks.length > 0 ? blockToCode(block.condBlocks[0], '').trim() : '');
const body = block.thenBlocks;
const bodyTxt = body.map(b => blockToCode(b, '')).join('\n');
let line = indent + 'while';
if (condTxt) line += ' ' + (condTxt.includes(' ') ? '{ ' + condTxt + ' }' : condTxt);
if (body.length === 1 && !body[0].isControl) {
line += ' then ' + blockToCode(body[0], '');
} else if (bodyTxt) {
line += ' then {\n' + bodyTxt.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + '}';
}
return line;
}
function genRepeat(block, indent) {
const count = block.values.count || '1';
const body = block.thenBlocks;
const bodyTxt = body.map(b => blockToCode(b, '')).join('\n');
let line = indent + 'repeat ' + count;
if (body.length === 1 && !body[0].isControl) {
line += ' ' + blockToCode(body[0], '');
} else if (bodyTxt) {
line += ' {\n' + bodyTxt.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + '}';
}
return line;
}
function genForEach(block, indent) {
const varName = block.values.varName || 'i';
const list = block._actionLiterals && block._actionLiterals['list'] !== undefined
? block._actionLiterals['list']
: (block.condBlocks.length > 0 ? blockToCode(block.condBlocks[0], '').trim() : '');
const body = block.thenBlocks;
const bodyTxt = body.map(b => blockToCode(b, '')).join('\n');
let line = indent + 'for ' + varName + ' in';
if (list) line += ' ' + (list.includes(' ') ? '{ ' + list + ' }' : list);
if (body.length === 1 && !body[0].isControl) {
line += ' then ' + blockToCode(body[0], '');
} else if (bodyTxt) {
line += ' then {\n' + bodyTxt.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + '}';
}
return line;
}
function genCaseWhen(block, indent) {
// 条件
const condTxt = block._actionLiterals && block._actionLiterals['condition'] !== undefined
? block._actionLiterals['condition']
: block.condBlocks.map(b => blockToCode(b, '')).join(' ');
const branches = block._whenBranches || [];
const elseBlocks = block.elseBlocks || [];
let line = indent + 'case';
if (condTxt) line += ' ' + (condTxt.includes(' ') ? '{ ' + condTxt + ' }' : condTxt);
line += ' [';
// when 分支
for (const br of branches) {
const cond = (br.condBlocks && br.condBlocks.length > 0)
? br.condBlocks.map(b => blockToCode(b, '')).join(' ')
: (br.condition || '');
const body = br.blocks.map(b => blockToCode(b, '')).join('\n');
if (!cond && !body) continue;
const bodyWrapped = body.includes('\n')
? '{\n' + body.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + ' }'
: body || '""';
line += '\n' + indent + ' when ' + cond + ' -> ' + bodyWrapped;
}
// else 分支
if (elseBlocks.length > 0) {
const elseTxt = elseBlocks.map(b => blockToCode(b, '')).join('\n');
const elseWrapped = elseTxt.includes('\n')
? '{\n' + elseTxt.split('\n').map(l => indent + ' ' + l).join('\n') + '\n' + indent + ' }'
: elseTxt;
line += '\n' + indent + ' else ' + elseWrapped;