-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrapDiscord.js
1239 lines (1151 loc) · 41.4 KB
/
scrapDiscord.js
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
const fetch = require('node-fetch');
const fs = require('fs');
var categorys = ['collection', 'client', 'role', 'channel', 'message', 'guild', 'user', 'member', 'reaction'];
(async () => {
if (!fs.existsSync("./scratch-blocks-simple/blocks_vertical")) {
fs.mkdirSync("./scratch-blocks-simple/blocks_vertical", { recursive: true });
}
var responce = await fetch("https://raw.githubusercontent.com/discordjs/docs/main/discord.js/stable.json");
var json = await responce.json();
var toolbox = `'use strict';
goog.provide('Blockly.Blocks.defaultToolbox');
goog.require('Blockly.Blocks');
Blockly.Blocks.defaultToolbox = '<xml id="toolbox-categories" style="display: none">' +`;
var javascript = `var start = 'const fs = require("fs"), discord = require("discord.js");\\nconst bot = new discord.Client();\\n';
var end = "\\nbot.login(token);";
Blockly.JavaScript['discord_token'] = function(block) {
return ["const token = '" + block.getFieldValue('TEXT') + "';\\n", Blockly.JavaScript.ORDER_NONE];
};`;
for (const value of json.classes) {
// if (categorys.includes(value.name.toLocaleLowerCase())) {
toolbox += `
'<category name="${value.name}" id="${value.name.toLowerCase()}" colour="#4C97FF" secondaryColour="#3373CC">' +`;
var data = `'use strict';
goog.provide('Blockly.Blocks.${value.name.toLowerCase()}');
goog.require('Blockly.Blocks');
goog.require('Blockly.Colours');
goog.require('Blockly.constants');
goog.require('Blockly.ScratchBlocks.VerticalExtensions');`;
if (value.events) {
var dropdown = "";
var switchData = "";
var jsSwitchData = "";
for (const event of value.events) {
// [ 'name', 'description', 'params', 'meta', 'deprecated' ]
if (!event.deprecated) {
dropdown += `["${event.name}", "${event.name}"], `;
if (event.params) {
switchData += `
case "${event.name}":
this.addOutputs(${JSON.stringify(event.params.map((v) => v.name))});
break;`
jsSwitchData += `
case "${event.name}":
variables = "${event.params.map((v) => v.name).join(", ")}";
break;`
}
}
}
dropdown.slice(0, -2);
javascript += `
Blockly.JavaScript['${value.name.toLowerCase()}_on'] = function(block) {
var ${value.name.toLowerCase()} = Blockly.JavaScript.valueToCode(block, '${value.name.toUpperCase()}', Blockly.JavaScript.ORDER_NONE) || "null";
var action = block.getFieldValue('ACTION');
var d = Blockly.JavaScript.statementToCode(block, 'DO') || "";
var variables = "";
switch (action) {${jsSwitchData}
}
block.variables = variables;
return [${value.name.toLowerCase()} + ".on('" + action + "', (" + variables + ") => {\\n" + d + "});\\n", Blockly.JavaScript.ORDER_FUNCTION_CALL];
};`;
toolbox += `
'<block type="${value.name.toLowerCase()}_on" id="${value.name.toLowerCase()}_on"></block>' +`;
data += `
Blockly.Blocks['${value.name.toLowerCase()}_on'] = {
init: function() {
this.appendDummyInput()
.appendField('on');
this.appendValueInput("${value.name.toUpperCase()}")
.appendField(new Blockly.FieldDropdown([${dropdown}]), "ACTION");
this.appendStatementInput('DO');
this.setColour(Blockly.Colours.${value.name.toLowerCase()}.primary);
},
addOutputs: function(variables) {
for (var i = 0; i < variables.length; i++) {
var input = this.appendValueInput("VARIABLE" + (i + 1));
this.moveInputBefore("VARIABLE" + (i + 1), i === 0 ? "DO" : "VARIABLE" + i);
var block = new Blockly.BlockSvg(this.workspace, "event_variables");
block.initSvg();
block.render(true);
block.contextMenu = false;
block.setFieldValue(variables[i], "VARIABLE");
input.connection.connect(block.outputConnection);
}
},
onchange: function(e) {
if (e.blockId === this.id) {
var i = 1;
while (this.getInput('VARIABLE' + i)) {
if (this.getInputTargetBlock("VARIABLE" + i)) {
this.getInputTargetBlock("VARIABLE" + i).dispose();
}
this.removeInput('VARIABLE' + i);
i++;
}
var action = this.getFieldValue("ACTION");
switch (action) {${switchData}
}
this.render(true);
}
}
};
`;
}
if (value.props) {
for (const prop of value.props) {
// [ 'name', 'description', 'type', 'meta', 'access', 'readonly', 'nullable', 'abstract', 'see', 'deprecated', 'props', 'scope' ]
if (!prop.deprecated && !prop.access) {
data += `
Blockly.Blocks['${value.name.toLowerCase()}_${prop.name.toLowerCase()}'] = {
init: function() {
this.jsonInit({
"message0": "${prop.name.replace(/([A-Z])/, " $1").toLocaleLowerCase()} of %1",
"args0": [
{
"type": "input_value",
"name": "${value.name.toUpperCase()}"
}
],
"category": Blockly.Categories.${value.name.toLowerCase()},
"extensions": ["colours_${value.name.toLowerCase()}", "output_string"]
});
}
};
`;
toolbox += `
'<block type="${value.name.toLowerCase()}_${prop.name.toLowerCase()}" id="${value.name.toLowerCase()}_${prop.name}"></block>' +`;
javascript += `
Blockly.JavaScript['${value.name.toLowerCase()}_${prop.name.toLowerCase()}'] = function(block) {
var ${value.name.toLowerCase()} = Blockly.JavaScript.valueToCode(block, '${value.name.toUpperCase()}', Blockly.JavaScript.ORDER_NONE) || "null";
return [${value.name.toLowerCase()} + ".${prop.name}", Blockly.JavaScript.ORDER_NONE];
};`;
}
}
}
if (value.methods) {
for (const method of value.methods) {
// [ 'name', 'description', 'returns', 'meta', 'access', 'examples', 'params', 'async', 'inherits', 'inherited', 'implements', 'see', 'scope', 'emits', 'deprecated', 'abstract' ]
if (!method.deprecated && !method.access) {
var params = "";
var paramsIDs = "";
var paramsID = 2;
var jsParams = "";
var jsParamsIDs = [];
var options = [];
var toolboxParams = "";
if (method.params) {
for (const param of method.params) {
if (param.type[0][0][0] === 'function') {
console.log(value.name + ": " + method.name + " argument is a function");
}
params += `
{
"type": "input_value",
"name": "${param.name.replace("options.", "").toUpperCase()}"
},`;
switch (param.type[0][0][0]) {
case "string":
toolboxParams += `
'<value name="${param.name.replace("options.", "").toUpperCase()}">' +
'<shadow type="text">' +
'<field name="TEXT">text</field>' +
'</shadow>' +
'</value>' +`;
break;
case "number":
toolboxParams += `
'<value name="${param.name.replace("options.", "").toUpperCase()}">' +
'<shadow type="math_number">' +
'<field name="NUM">1</field>' +
'</shadow>' +
'</value>' +`;
break;
case "boolean":
// toolboxParams += `
// '<value name="${param.name.replace("options.", "").toUpperCase()}">' +
// '<shadow type="boolean">' +
// '<field name="BOOL">true</field>' +
// '</shadow>' +
// '</value>' +`;
break;
}
jsParams += `
var ${param.name.replace("options.", "")} = Blockly.JavaScript.valueToCode(block, '${param.name.replace("options.", "").toUpperCase()}', Blockly.JavaScript.ORDER_NONE) || "";`;
if (param.name.startsWith("options.")) {
options.push(`" + ${param.name.replace("options.", "")} + "`);
} else {
jsParamsIDs.push(`" + ${param.name} + "`);
}
paramsIDs += ` ${param.name.replace("options.", "")}: %${paramsID}`;
paramsID++;
}
}
toolbox += `
'<block type="${value.name.toLowerCase()}_${method.name}" id="${value.name.toLowerCase()}_${method.name}">' +${toolboxParams}
'</block>' +`;
data += `
Blockly.Blocks['${value.name.toLowerCase()}_${method.name}'] = {
init: function() {
this.jsonInit({
"message0": "${method.name.replace(/([A-Z])/, " $1").toLocaleLowerCase()} of %1${paramsIDs}",
"args0": [
{
"type": "input_value",
"name": "${value.name.toUpperCase()}"
},${params}
],
"category": Blockly.Categories.${value.name.toLowerCase()},
"extensions": ["colours_${value.name.toLowerCase()}", "shape_statement"]
});
}
};
`;
if (method.async) {
javascript += `
Blockly.JavaScript['${value.name.toLowerCase()}_${method.name}'] = function(block) {
var finalstring = ";\\n";
if (block.getNextBlock()) {
if (block.getNextBlock().type === "sensing_then") {
finalstring = "";
}
}
var ${value.name.toLowerCase()} = Blockly.JavaScript.valueToCode(block, '${value.name.toUpperCase()}', Blockly.JavaScript.ORDER_NONE) || "null";${jsParams}
return ${value.name.toLowerCase()} + ".${method.name}(${jsParamsIDs.join(", ")}${options.length > 0 ? ", { " + options.join(", ") + " }" : ""})" + finalstring;
};`;
} else {
javascript += `
Blockly.JavaScript['${value.name.toLowerCase()}_${method.name}'] = function(block) {
var ${value.name.toLowerCase()} = Blockly.JavaScript.valueToCode(block, '${value.name.toUpperCase()}', Blockly.JavaScript.ORDER_NONE) || "null";${jsParams}
return ${value.name.toLowerCase()} + ".${method.name}(${jsParamsIDs.join(", ")}${options.length > 0 ? ", { " + options.join(", ") + " }" : ""});\\n";
};`;
}
}
}
}
fs.writeFileSync("./scratch-blocks-simple/blocks_vertical/" + value.name.toLowerCase() + ".js", data);
toolbox += `
'</category>' +`;
// }
}
toolbox += `
'</xml>';`;
fs.writeFileSync("./scratch-blocks-simple/blocks_vertical/vertical_extensions.js", `/**
* @license
* Visual Blocks Editor
*
* Copyright 2017 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Extensions for vertical blocks in scratch-blocks.
* The following extensions can be used to describe a block in Scratch terms.
* For instance, a block in the operators colour scheme with a number output
* would have the "colours_operators" and "output_number" extensions.
* @author [email protected] (Rachel Fenichel)
*/
'use strict';
goog.provide('Blockly.ScratchBlocks.VerticalExtensions');
goog.require('Blockly.Colours');
goog.require('Blockly.constants');
/**
* Helper function that generates an extension based on a category name.
* The generated function will set primary, secondary, and tertiary colours
* based on the category name.
* @param {String} category The name of the category to set colours for.
* @return {function} An extension function that sets colours based on the given
* category.
*/
Blockly.ScratchBlocks.VerticalExtensions.colourHelper = function(category) {
var colours = Blockly.Colours[category];
if (!(colours && colours.primary && colours.secondary && colours.tertiary)) {
throw new Error('Could not find colours for category "' + category + '"');
}
/**
* Set the primary, secondary, and tertiary colours on this block for the
* given category.
* @this {Blockly.Block}
*/
return function() {
this.setColourFromRawValues_(colours.primary, colours.secondary,
colours.tertiary);
};
};
/**
* Extension to set the colours of a text field, which are all the same.
*/
Blockly.ScratchBlocks.VerticalExtensions.COLOUR_TEXTFIELD = function() {
this.setColourFromRawValues_(Blockly.Colours.textField,
Blockly.Colours.textField, Blockly.Colours.textField);
};
/**
* Extension to make a block fit into a stack of statements, regardless of its
* inputs. That means the block should have a previous connection and a next
* connection and have inline inputs.
* @this {Blockly.Block}
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.SHAPE_STATEMENT = function() {
this.setInputsInline(true);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
};
/**
* Extension to make a block be shaped as a hat block, regardless of its
* inputs. That means the block should have a next connection and have inline
* inputs, but have no previous connection.
* @this {Blockly.Block}
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.SHAPE_HAT = function() {
this.setInputsInline(true);
this.setNextStatement(true, null);
};
/**
* Extension to make a block be shaped as an end block, regardless of its
* inputs. That means the block should have a previous connection and have
* inline inputs, but have no next connection.
* @this {Blockly.Block}
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.SHAPE_END = function() {
this.setInputsInline(true);
this.setPreviousStatement(true, null);
};
/**
* Extension to make represent a number reporter in Scratch-Blocks.
* That means the block has inline inputs, a round output shape, and a 'Number'
* output type.
* @this {Blockly.Block}
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.OUTPUT_NUMBER = function() {
this.setInputsInline(true);
this.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND);
this.setOutput(true, 'Number');
};
/**
* Extension to make represent a string reporter in Scratch-Blocks.
* That means the block has inline inputs, a round output shape, and a 'String'
* output type.
* @this {Blockly.Block}
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.OUTPUT_STRING = function() {
this.setInputsInline(true);
this.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND);
this.setOutput(true, 'String');
};
/**
* Extension to make represent a boolean reporter in Scratch-Blocks.
* That means the block has inline inputs, a round output shape, and a 'Boolean'
* output type.
* @this {Blockly.Block}
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.OUTPUT_BOOLEAN = function() {
this.setInputsInline(true);
this.setOutputShape(Blockly.OUTPUT_SHAPE_HEXAGONAL);
this.setOutput(true, 'Boolean');
};
/**
* Mixin to add a context menu for a procedure definition block.
* It adds the "edit" option and removes the "duplicate" option.
* @mixin
* @augments Blockly.Block
* @package
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_DEF_CONTEXTMENU = {
/**
* Add the "edit" option and removes the "duplicate" option from the context
* menu.
* @param {!Array.<!Object>} menuOptions List of menu options to edit.
* @this Blockly.Block
*/
customContextMenu: function(menuOptions) {
// Add the edit option at the end.
menuOptions.push(Blockly.Procedures.makeEditOption(this));
// Find the delete option and update its callback to be specific to
// functions.
for (var i = 0, option; option = menuOptions[i]; i++) {
if (option.text == Blockly.Msg.DELETE_BLOCK) {
var input = this.getInput('custom_block');
// this is the root block, not the shadow block.
if (input && input.connection && input.connection.targetBlock()) {
var procCode = input.connection.targetBlock().getProcCode();
} else {
return;
}
var rootBlock = this;
option.callback = function() {
var didDelete = Blockly.Procedures.deleteProcedureDefCallback(
procCode, rootBlock);
if (!didDelete) {
alert(Blockly.Msg.PROCEDURE_USED);
}
};
}
}
// Find and remove the duplicate option
for (var i = 0, option; option = menuOptions[i]; i++) {
if (option.text == Blockly.Msg.DUPLICATE) {
menuOptions.splice(i, 1);
break;
}
}
}
};
/**
* Mixin to add a context menu for a procedure call block.
* It adds the "edit" option and the "define" option.
* @mixin
* @augments Blockly.Block
* @package
* @readonly
*/
Blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU = {
/**
* Add the "edit" option to the context menu.
* @todo Add "go to definition" option once implemented.
* @param {!Array.<!Object>} menuOptions List of menu options to edit.
* @this Blockly.Block
*/
customContextMenu: function(menuOptions) {
menuOptions.push(Blockly.Procedures.makeEditOption(this));
}
};
Blockly.ScratchBlocks.VerticalExtensions.SCRATCH_EXTENSION = function() {
this.isScratchExtension = true;
};
/**
* Register all extensions for scratch-blocks.
* @package
*/
Blockly.ScratchBlocks.VerticalExtensions.registerAll = function() {
var categoryNames = ${JSON.stringify(json.classes.map((v) => v.name.toLowerCase()))};
// Register functions for all category colours.
for (var i = 0; i < categoryNames.length; i++) {
var name = categoryNames[i];
Blockly.Extensions.register('colours_' + name,
Blockly.ScratchBlocks.VerticalExtensions.colourHelper(name));
}
// Text fields transcend categories.
Blockly.Extensions.register('colours_textfield',
Blockly.ScratchBlocks.VerticalExtensions.COLOUR_TEXTFIELD);
// Register extensions for common block shapes.
Blockly.Extensions.register('shape_statement',
Blockly.ScratchBlocks.VerticalExtensions.SHAPE_STATEMENT);
Blockly.Extensions.register('shape_hat',
Blockly.ScratchBlocks.VerticalExtensions.SHAPE_HAT);
Blockly.Extensions.register('shape_end',
Blockly.ScratchBlocks.VerticalExtensions.SHAPE_END);
// Output shapes and types are related.
Blockly.Extensions.register('output_number',
Blockly.ScratchBlocks.VerticalExtensions.OUTPUT_NUMBER);
Blockly.Extensions.register('output_string',
Blockly.ScratchBlocks.VerticalExtensions.OUTPUT_STRING);
Blockly.Extensions.register('output_boolean',
Blockly.ScratchBlocks.VerticalExtensions.OUTPUT_BOOLEAN);
// Custom procedures have interesting context menus.
Blockly.Extensions.registerMixin('procedure_def_contextmenu',
Blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_DEF_CONTEXTMENU);
Blockly.Extensions.registerMixin('procedure_call_contextmenu',
Blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU);
// Extension blocks have slightly different block rendering.
Blockly.Extensions.register('scratch_extension',
Blockly.ScratchBlocks.VerticalExtensions.SCRATCH_EXTENSION);
};
Blockly.ScratchBlocks.VerticalExtensions.registerAll();
`);
fs.writeFileSync("./scratch-blocks-simple/core/colours.js", `/**
* @license
* Visual Blocks Editor
*
* Copyright 2016 Massachusetts Institute of Technology
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
goog.provide('Blockly.Colours');
Blockly.Colours = {${json.classes.map((v) => `
${v.name.toLowerCase()}: {
"primary": "#4C97FF",
"secondary": "#4280D7",
"tertiary": "#3373CC"
},`).join("")}
"filesystem": {
"primary": "#9966FF",
"secondary": "#855CD6",
"tertiary": "#774DCB"
},
"control": {
"primary": "#FFAB19",
"secondary": "#EC9C13",
"tertiary": "#CF8B17"
},
"event": {
"primary": "#FFBF00",
"secondary": "#E6AC00",
"tertiary": "#CC9900"
},
"sensing": {
"primary": "#5CB1D6",
"secondary": "#47A8D1",
"tertiary": "#2E8EB8"
},
"operators": {
"primary": "#59C059",
"secondary": "#46B946",
"tertiary": "#389438"
},
"data": {
"primary": "#FF8C1A",
"secondary": "#FF8000",
"tertiary": "#DB6E00"
},
"data_lists": {
"primary": "#FF661A",
"secondary": "#FF5500",
"tertiary": "#E64D00"
},
"data_dictionary": {
"primary": "#ff3c1a",
"secondary": "#FF2b00",
"tertiary": "#E62A00"
},
"more": {
"primary": "#FF6680",
"secondary": "#FF4D6A",
"tertiary": "#FF3355"
},
"text": "#575E75",
"workspace": "#F9F9F9",
"toolboxHover": "#4C97FF",
"toolboxSelected": "#e9eef2",
"toolboxText": "#575E75",
"toolbox": "#FFFFFF",
"flyout": "#F9F9F9",
"scrollbar": "#CECDCE",
"scrollbarHover": '#CECDCE',
"textField": "#FFFFFF",
"insertionMarker": "#000000",
"insertionMarkerOpacity": 0.2,
"dragShadowOpacity": 0.3,
"stackGlow": "#FFF200",
"stackGlowSize": 4,
"stackGlowOpacity": 1,
"replacementGlow": "#FFFFFF",
"replacementGlowSize": 2,
"replacementGlowOpacity": 1,
"colourPickerStroke": "#FFFFFF",
// CSS colours: support RGBA
"fieldShadow": "rgba(0,0,0,0.1)",
"dropDownShadow": "rgba(0, 0, 0, .3)",
"numPadBackground": "#547AB2",
"numPadBorder": "#435F91",
"numPadActiveBackground": "#435F91",
"numPadText": "white", // Do not use hex here, it cannot be inlined with data-uri SVG
"valueReportBackground": "#FFFFFF",
"valueReportBorder": "#AAAAAA"
};
/**
* Override the colours in Blockly.Colours with new values basded on the
* given dictionary.
* @param {!Object} colours Dictionary of colour properties and new values.
* @package
*/
Blockly.Colours.overrideColours = function(colours) {
// Colour overrides provided by the injection
if (colours) {
for (var colourProperty in colours) {
if (colours.hasOwnProperty(colourProperty) &&
Blockly.Colours.hasOwnProperty(colourProperty)) {
// If a property is in both colours option and Blockly.Colours,
// set the Blockly.Colours value to the override.
// Override Blockly category color object properties with those
// provided.
var colourPropertyValue = colours[colourProperty];
if (goog.isObject(colourPropertyValue)) {
for (var colourSequence in colourPropertyValue) {
if (colourPropertyValue.hasOwnProperty(colourSequence) &&
Blockly.Colours[colourProperty].hasOwnProperty(colourSequence)) {
Blockly.Colours[colourProperty][colourSequence] =
colourPropertyValue[colourSequence];
}
}
} else {
Blockly.Colours[colourProperty] = colourPropertyValue;
}
}
}
}
};
`);
fs.writeFileSync("./scratch-blocks-simple/tests/vertical_playground.html", `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Vertical Playground</title>
<script src="../blockly_uncompressed_vertical.js"></script>
<script src="../msg/messages.js"></script>
<script src="../msg/scratch_msgs.js"></script>
<script src="../blocks_vertical/vertical_extensions.js"></script>
<script src="../blocks_common/math.js"></script>
<script src="../blocks_common/matrix.js"></script>
<script src="../blocks_common/note.js"></script>
<script src="../blocks_common/text.js"></script>
<script src="../blocks_common/colour.js"></script>${json.classes.map((v) => `
<script src="../blocks_vertical/${v.name.toLowerCase()}.js"></script>`).join("")}
<script src="../blocks_vertical/event.js"></script>
<script src="../blocks_vertical/default_toolbox.js"></script>
<script>
'use strict';
var workspace = null;
function start() {
var soundsEnabled = null;
if (sessionStorage) {
// Restore sounds state.
soundsEnabled = sessionStorage.getItem('soundsEnabled');
if (soundsEnabled === null) {
soundsEnabled = true;
} else {
soundsEnabled = (soundsEnabled === 'true');
}
} else {
soundsEnabled = true;
}
setSoundsEnabled(soundsEnabled);
// Setup blocks
// Parse the URL arguments.
var match = location.search.match(/dir=([^&]+)/);
var rtl = match && match[1] == 'rtl';
document.forms.options.elements.dir.selectedIndex = Number(rtl);
var toolbox = getToolboxElement();
document.forms.options.elements.toolbox.selectedIndex =
toolbox ? 1: 0;
match = location.search.match(/side=([^&]+)/);
var side = match ? match[1] : 'start';
document.forms.options.elements.side.value = side;
match = location.search.match(/locale=([^&]+)/);
var locale = match ? match[1] : 'en';
Blockly.ScratchMsgs.setLocale(locale);
document.forms.options.elements.locale.value = locale;
// Create main workspace.
workspace = Blockly.inject('blocklyDiv', {
comments: true,
disable: false,
collapse: false,
media: '../media/',
readOnly: false,
rtl: rtl,
scrollbars: true,
toolbox: toolbox,
toolboxPosition: side == 'top' || side == 'start' ? 'start' : 'end',
horizontalLayout: side == 'top' || side == 'bottom',
sounds: soundsEnabled,
zoom: {
controls: true,
wheel: true,
startScale: 0.675,
maxScale: 4,
minScale: 0.25,
scaleSpeed: 1.1
},
colours: {
fieldShadow: 'rgba(255, 255, 255, 0.3)',
dragShadowOpacity: 0.6
}
});
if (sessionStorage) {
// Restore previously displayed text.
var text = sessionStorage.getItem('textarea');
if (text) {
document.getElementById('importExport').value = text;
}
taChange();
}
if (sessionStorage) {
// Restore event logging state.
var state = sessionStorage.getItem('logEvents');
logEvents(Boolean(state));
// Restore flyout event logging state.
state = sessionStorage.getItem('logFlyoutEvents');
logFlyoutEvents(Boolean(state));
}
}
function getToolboxElement() {
var match = location.search.match(/toolbox=([^&]+)/);
return document.getElementById('toolbox-' + (match ? match[1] : 'categories'));
}
function toXml() {
var output = document.getElementById('importExport');
var xml = Blockly.Xml.workspaceToDom(workspace);
output.value = Blockly.Xml.domToPrettyText(xml);
output.focus();
output.select();
taChange();
}
function fromXml() {
var input = document.getElementById('importExport');
var xml = Blockly.Xml.textToDom(input.value);
Blockly.Xml.domToWorkspace(xml, workspace);
taChange();
}
// Disable the "Import from XML" button if the XML is invalid.
// Preserve text between page reloads.
function taChange() {
var textarea = document.getElementById('importExport');
if (sessionStorage) {
sessionStorage.setItem('textarea', textarea.value)
}
var valid = true;
try {
Blockly.Xml.textToDom(textarea.value);
} catch (e) {
valid = false;
}
document.getElementById('import').disabled = !valid;
}
function logEvents(state) {
var checkbox = document.getElementById('logCheck');
checkbox.checked = state;
if (sessionStorage) {
sessionStorage.setItem('logEvents', state ? 'checked' : '');
}
if (state) {
workspace.addChangeListener(logger);
} else {
workspace.removeChangeListener(logger);
}
}
function logFlyoutEvents(state) {
var checkbox = document.getElementById('logFlyoutCheck');
checkbox.checked = state;
var soundsEnabled = null;
if (sessionStorage) {
sessionStorage.setItem('logFlyoutEvents', state ? 'checked' : '');
}
var flyoutWorkspace = (workspace.flyout_) ? workspace.flyout_.workspace_ :
workspace.toolbox_.flyout_.workspace_;
if (state) {
flyoutWorkspace.addChangeListener(logger);
} else {
flyoutWorkspace.removeChangeListener(logger);
}
}
function logger(e) {
console.log(e);
}
function glowBlock() {
if (Blockly.selected) {
workspace.glowBlock(Blockly.selected.id, true);
}
}
function unglowBlock() {
if (Blockly.selected) {
workspace.glowBlock(Blockly.selected.id, false);
}
}
function glowStack() {
if (Blockly.selected) {
workspace.glowStack(Blockly.selected.id, true);
}
}
function unglowStack() {
if (Blockly.selected) {
workspace.glowStack(Blockly.selected.id, false);
}
}
function sprinkles(n) {
var prototypes = [];
var toolbox = workspace.options.languageTree;
if (!toolbox) {
console.error('Toolbox not found; add a toolbox element to the DOM.');
return;
}
var blocks = toolbox.getElementsByTagName('block');
for (var i = 0; i < n; i++) {
var blockXML = blocks[Math.floor(Math.random() * blocks.length)];
var block = Blockly.Xml.domToBlock(blockXML, workspace);
block.initSvg();
block.moveBy(
Math.round(Math.random() * 450 + 40),
Math.round(Math.random() * 600 + 40)
);
}
}
var equalsXml = [
' <shadow type="operator_equals">',
' <value name="OPERAND1">',
' <shadow type="text">',
' <field name="TEXT">foo</field>',
' </shadow>',
' </value>',
' <value name="OPERAND2">',
' <shadow type="operator_equals"></shadow>',
' </value>',
' </shadow>'
].join('\\n');
var spaghettiXml = [
' <block type="control_if_else">',
' <value name="CONDITION">',
' <shadow type="operator_equals"></shadow>',
' </value>',
' <statement name="SUBSTACK"></statement>',
' <statement name="SUBSTACK2"></statement>',
' <next></next>',
' </block>'
].join('\\n');
function spaghetti(n) {
console.log("Starting spaghetti. This may take some time...");
var xml = spaghettiXml;
// Nest if/else statements deeply.
for(var i = 0; i < 2 * n; i++) {
xml = xml.replace(/(<statement name="SUBSTACK2?"?>)<\\//g,
'$1' + spaghettiXml + '</');
}
// Stack a bit.
for(var i = 0; i < n; i++) {
xml = xml.replace(/(<next>)<\//g,
'$1' + spaghettiXml + '</');
}
// Nest boolean comparisons.
var equalsBlock = equalsXml;
for (var i = 0; i < n; i++) {
equalsBlock = equalsBlock.replace(
/(<shadow( type="operator_equals")?>)<\\/shadow>/g, equalsXml);
}
// Put the nested boolean comparisons into if/else statements.
xml = xml.replace(/(<shadow( type="operator_equals")?>)<\\/shadow>/g,
equalsBlock);
xml = '<xml xmlns="http://www.w3.org/1999/xhtml">' + xml + '</xml>';
var dom = Blockly.Xml.textToDom(xml);
console.time('Spaghetti domToWorkspace');
Blockly.Xml.domToWorkspace(dom, workspace);
console.timeEnd('Spaghetti domToWorkspace');
}
function setSoundsEnabled(state) {
var checkbox = document.getElementById('soundsEnabled');
checkbox.checked = (state) ? 'checked' : '';
if (sessionStorage) {
sessionStorage.setItem('soundsEnabled', state);
}
}
function reportDemo() {
if (Blockly.selected) {
workspace.reportValue(
Blockly.selected.id,
document.getElementById('reportValue').value
);
}
}
function setLocale(locale) {
workspace.getFlyout().setRecyclingEnabled(false);
var xml = Blockly.Xml.workspaceToDom(workspace);
Blockly.ScratchMsgs.setLocale(locale);
Blockly.Xml.clearWorkspaceAndLoadFromXml(xml, workspace);
workspace.getFlyout().setRecyclingEnabled(true);
}
// function codeUpdate(event) {
// if (connected) {
// var code = start + Blockly.JavaScript.workspaceToCode(workspace) + end;
// document.getElementById("javascript-viewer").innerHTML = code;
// }
// }
// workspace.addChangeListener(codeUpdate);
</script>
<style>
html, body {
height: 100%;
}
body {
background-color: #fff;
font-family: sans-serif;
overflow: hidden;
}
h1 {
font-weight: normal;
font-size: 140%;
}
#blocklyDiv {
float: right;
height: 95%;
width: 70%;
}
.blocklyToolboxDiv {
scrollbar-width: 0;
}
.blocklyToolboxDiv::-webkit-scrollbar {
display: none;
}
#collaborators {
float: right;
width: 30px;
margin-left: 10px;
}
#collaborators > img {
margin-right: 5px;
height: 30px;
padding-bottom: 5px;
width: 30px;
border-radius: 3px;