-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
325 lines (297 loc) · 13.4 KB
/
plugin.js
File metadata and controls
325 lines (297 loc) · 13.4 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
class Plugin {
constructor(workspace) {
this.workspace = workspace;
this.blockIds = [
"bc_slash_command",
"bc_str_arg",
"bc_int_arg",
"bc_bool_arg",
"bc_member_arg",
"bc_channel_arg",
"bc_vchannel_arg",
"bc_choice_arg",
"bc_choice_item",
"bc_get_arg",
"bc_get_choice_val",
];
this.toolboxCategoryId = "bettercommand_category";
this.insertedCategory = null;
this.toolboxRetryTimer = null;
}
async onload() {
this._registerBlocks();
this._registerGenerators();
this._mountToolbox();
}
async onunload() {
for (const id of this.blockIds) {
delete Blockly.Blocks[id];
delete Blockly.Python.forBlock[id];
}
this._unmountToolbox();
if (this.toolboxRetryTimer) {
clearTimeout(this.toolboxRetryTimer);
this.toolboxRetryTimer = null;
}
}
// -------------------------------------------------------
// ブロック定義
// -------------------------------------------------------
_registerBlocks() {
// ⚡ スラッシュコマンド定義(トップレベル・引数付き)
Blockly.Blocks["bc_slash_command"] = {
init() {
this.appendDummyInput()
.appendField("スラッシュコマンド /")
.appendField(new Blockly.FieldTextInput("hello"), "NAME")
.appendField("説明")
.appendField(new Blockly.FieldTextInput("コマンドの説明"), "DESC");
this.appendStatementInput("ARGS").appendField("引数(任意)");
this.appendStatementInput("BODY").appendField("実行する処理");
this.setColour(240);
this.setTooltip("引数・説明・Choice 対応のスラッシュコマンドを定義します。");
}
};
// ─── 共通引数ブロックファクトリー ───
const _makeArgBlock = (label, colour) => ({
init() {
this.appendDummyInput()
.appendField(label)
.appendField("名:")
.appendField(new Blockly.FieldTextInput("arg"), "ARG_NAME")
.appendField("説明:")
.appendField(new Blockly.FieldTextInput(""), "ARG_DESC")
.appendField("必須:")
.appendField(new Blockly.FieldCheckbox("TRUE"), "REQUIRED");
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(colour);
this.setTooltip(`${label} 引数をコマンドに追加します。`);
}
});
Blockly.Blocks["bc_str_arg"] = _makeArgBlock("文字列引数", 120);
Blockly.Blocks["bc_int_arg"] = _makeArgBlock("整数引数", 120);
Blockly.Blocks["bc_bool_arg"] = _makeArgBlock("真偽値引数", 120);
Blockly.Blocks["bc_member_arg"] = _makeArgBlock("メンバー引数", 120);
Blockly.Blocks["bc_channel_arg"] = _makeArgBlock("テキストch引数", 120);
Blockly.Blocks["bc_vchannel_arg"] = _makeArgBlock("VCチャンネル引数", 120);
// 🔽 選択肢(Choice)引数
Blockly.Blocks["bc_choice_arg"] = {
init() {
this.appendDummyInput()
.appendField("選択肢引数")
.appendField("名:")
.appendField(new Blockly.FieldTextInput("choice"), "ARG_NAME")
.appendField("説明:")
.appendField(new Blockly.FieldTextInput(""), "ARG_DESC")
.appendField("型:")
.appendField(new Blockly.FieldDropdown([
["文字列(str)", "str"],
["整数(int)", "int"],
]), "CHOICE_TYPE")
.appendField("必須:")
.appendField(new Blockly.FieldCheckbox("TRUE"), "REQUIRED");
this.appendStatementInput("CHOICES").appendField("選択肢 ↓");
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(270);
this.setTooltip("ドロップダウン選択肢付き引数を追加します。下に bc_choice_item を並べてください。");
}
};
// ・ 選択肢アイテム
Blockly.Blocks["bc_choice_item"] = {
init() {
this.appendDummyInput()
.appendField("・ 表示名:")
.appendField(new Blockly.FieldTextInput("選択肢A"), "LABEL")
.appendField("値:")
.appendField(new Blockly.FieldTextInput("value_a"), "VALUE");
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(270);
this.setTooltip("選択肢の一項目です。");
}
};
// 引数の値を取得(str / int / bool / member / channel)
Blockly.Blocks["bc_get_arg"] = {
init() {
this.appendDummyInput()
.appendField("引数")
.appendField(new Blockly.FieldTextInput("arg"), "ARG_NAME")
.appendField("の値");
this.setOutput(true, null);
this.setColour(120);
this.setTooltip("str / int / bool / member / channel 引数の値を返します。");
}
};
// 選択肢引数の値を取得(.value が必要)
Blockly.Blocks["bc_get_choice_val"] = {
init() {
this.appendDummyInput()
.appendField("選択肢引数")
.appendField(new Blockly.FieldTextInput("choice"), "ARG_NAME")
.appendField("の値");
this.setOutput(true, null);
this.setColour(270);
this.setTooltip("選択肢引数の値 (.value) を返します。");
}
};
}
// -------------------------------------------------------
// Python ジェネレーター
// -------------------------------------------------------
_registerGenerators() {
// ⚡ bc_slash_command ── 引数チェーンを読んでデコレーター・関数を組み立てる
Blockly.Python.forBlock["bc_slash_command"] = function (block) {
const name = block.getFieldValue("NAME").toLowerCase().replace(/\s+/g, "_");
const desc = block.getFieldValue("DESC") || `${name} command`;
const params = []; // 関数シグネチャ (interaction は別途先頭に追加)
const describes = []; // @app_commands.describe(...)
const choiceDecorators = []; // @app_commands.choices(...)
// ARGS ステートメント入力のブロックチェーンを読む
let argB = block.getInputTargetBlock("ARGS");
while (argB) {
const argName = argB.getFieldValue("ARG_NAME") || "arg";
const argDesc = argB.getFieldValue("ARG_DESC") || argName;
const required = (argB.getFieldValue("REQUIRED") ?? "TRUE") === "TRUE";
const sfx = required ? "" : " = None";
describes.push(`${argName}="${argDesc}"`);
switch (argB.type) {
case "bc_str_arg":
params.push(`${argName}: str${sfx}`);
break;
case "bc_int_arg":
params.push(`${argName}: int${sfx}`);
break;
case "bc_bool_arg":
params.push(`${argName}: bool${sfx}`);
break;
case "bc_member_arg":
params.push(`${argName}: discord.Member${sfx}`);
break;
case "bc_channel_arg":
params.push(`${argName}: discord.TextChannel${sfx}`);
break;
case "bc_vchannel_arg":
params.push(`${argName}: discord.VoiceChannel${sfx}`);
break;
case "bc_choice_arg": {
const ctype = argB.getFieldValue("CHOICE_TYPE") || "str";
const items = [];
let itemB = argB.getInputTargetBlock("CHOICES");
while (itemB) {
const label = itemB.getFieldValue("LABEL") || "選択肢";
const val = itemB.getFieldValue("VALUE") || "value";
const quoted = ctype === "int" ? val : `"${val}"`;
items.push(`app_commands.Choice(name="${label}", value=${quoted})`);
itemB = itemB.getNextBlock();
}
if (items.length > 0) {
choiceDecorators.push(
`@app_commands.choices(${argName}=[${items.join(", ")}])`
);
}
params.push(`${argName}: app_commands.Choice[${ctype}]${sfx}`);
break;
}
}
argB = argB.getNextBlock();
}
// 関数本体
const body = Blockly.Python.statementToCode(block, "BODY") || " pass\n";
// コード生成
let code = `@bot.tree.command(name="${name}", description="${desc}")\n`;
if (describes.length > 0) {
code += `@app_commands.describe(${describes.join(", ")})\n`;
}
for (const deco of choiceDecorators) {
code += deco + "\n";
}
const sigParams = ["interaction: discord.Interaction", ...params].join(", ");
code += `async def ${name}_cmd(${sigParams}):\n`;
code += ` ctx = interaction\n`;
code += ` user = interaction.user\n`;
code += body;
return code;
};
// 引数ブロックは親が直接読むため Python コードを返さない
const _noop = () => "";
for (const id of [
"bc_str_arg", "bc_int_arg", "bc_bool_arg",
"bc_member_arg", "bc_channel_arg", "bc_vchannel_arg",
"bc_choice_arg", "bc_choice_item",
]) {
Blockly.Python.forBlock[id] = _noop;
}
// 引数の値を取得
Blockly.Python.forBlock["bc_get_arg"] = function (block) {
const n = block.getFieldValue("ARG_NAME") || "arg";
return [n, Blockly.Python.ORDER_ATOMIC];
};
// 選択肢引数の値を取得
Blockly.Python.forBlock["bc_get_choice_val"] = function (block) {
const n = block.getFieldValue("ARG_NAME") || "choice";
return [`${n}.value`, Blockly.Python.ORDER_MEMBER];
};
}
// -------------------------------------------------------
// ツールボックス
// -------------------------------------------------------
_getToolboxTree() {
const el = document.getElementById("toolbox");
if (el) return el;
return this.workspace?.options?.languageTree ?? null;
}
_scheduleRetry() {
if (this.toolboxRetryTimer) return;
this.toolboxRetryTimer = setTimeout(() => {
this.toolboxRetryTimer = null;
this._mountToolbox();
}, 500);
}
_mountToolbox() {
const tree = this._getToolboxTree();
if (!tree) { this._scheduleRetry(); return; }
if (tree.querySelector?.(`#${this.toolboxCategoryId}`)) return;
const xml = new DOMParser().parseFromString(
`<xml>
<category id="${this.toolboxCategoryId}" name="Better Command" colour="#7c3aed">
<label text="── コマンド定義 ──"></label>
<block type="bc_slash_command"></block>
<sep></sep>
<label text="── 引数の種類 ──"></label>
<block type="bc_str_arg"></block>
<block type="bc_int_arg"></block>
<block type="bc_bool_arg"></block>
<block type="bc_member_arg"></block>
<block type="bc_channel_arg"></block>
<block type="bc_vchannel_arg"></block>
<sep></sep>
<label text="── 選択肢(Choice) ──"></label>
<block type="bc_choice_arg"></block>
<block type="bc_choice_item"></block>
<sep></sep>
<label text="── 引数の値を取得 ──"></label>
<block type="bc_get_arg"></block>
<block type="bc_get_choice_val"></block>
</category>
</xml>`,
"text/xml"
);
const cat = xml.documentElement.firstElementChild;
if (!cat) return;
tree.appendChild(cat);
this.insertedCategory = cat;
this.workspace?.updateToolbox?.(tree);
}
_unmountToolbox() {
const tree = this._getToolboxTree();
if (!tree) return;
const cat = this.insertedCategory
|| tree.querySelector?.(`#${this.toolboxCategoryId}`);
if (!cat) return;
cat.remove();
this.insertedCategory = null;
this.workspace?.updateToolbox?.(tree);
}
}