This repository has been archived by the owner on Mar 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
inject3.js
2338 lines (1976 loc) · 84.3 KB
/
inject3.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
console.log('Griffpatch Scratch Developer Tools Extension Handler');
function initGUI() {
const helpHTML = `
<div id="s3devHelpPop">
<div>
<h1><strong>Scratch 3 Developer Tools</strong></h1>
<p>Version 0.2.4 - Released 4 July 2020 – by <a target="_blank" href="https://www.youtube.com/user/griffpatch">Griffpatch</a></p>
<hr />
<h2><strong>Changes in 0.2.3 - 0.2.4</strong></h2>
<p><strong>Ctrl + Space or Middle Click</strong> – Experimental Feature - This pops up a floating input box where you can type the name of a block (or parts of it) and drag the block into the code to make use of it right there.</p>
<p><strong>Fixes</strong> – Fix for input box not appearing on project load. Fix for pressing Ctrl+Left or Right while trying to enter text.</p>
<hr />
<h2><strong>Code Tab Features</strong></h2>
<p><strong>Interactive Find Bar (Ctrl + F)</strong> - Quickly find and jump to any Custom Block, Variable, Event, or Hat block defined in a sprite by clicking on the new find bar located to the right of the Code, Costumes and Sound tabs. Begin typing to filter down the list. Use the up and down arrow keys to switch between the possible entries, and the left and right arrows to cycle between al found instances of that block.</p>
<p><strong>Improved Code Tidy Up</strong> – Right click on the scripts window to pop up the menu and the clean up blocks option will have been replaced by a Clean Up Blocks (+) option. Se this to tidy your scripts and it will preserve your scripts columns as well as attempt to align the comments and remove all those orphaned variables, etc. You'll like this a lot I guarantee!</p>
<p><strong>Copy to Clipboard</strong> – Right click a block and 3 new options are available to Copy All, Copy Block, and Cut Block. The Copy All will copy to the clipboard everything including and below the block you clicked on. Copy block will only copy the current block and its contents, but nothing below. And cut block will copy it and remove it from the workspace.</p>
<p><strong>Paste from Clipboard</strong> – Pastes from the clipboard, but importantly pastes it where your mouse cursor is so you can then place it (rather than placing it where you copied it from like the current scratch implementation).</p>
<p><strong>Swap Variable in Sprite</strong> – Right click a variable in your scripts for this new option. It allows you to switch all references to this variable in the current sprite all in one go to another variable. This is great for when you made a mistake and want to switch from one variable to another or need to change from a 'for all sprites' to a 'for this sprite only'. This option will not remove the old variable and will not affect any other sprites variables.</p>
<p><strong>Middle Click</strong> – Using the middle mouse button on a variable or custom block allows you to jump to its definition or open it in the interactive find bar.</p>
<p><strong>Ctrl + Left, Ctrl + Right</strong> – Navigate to previous / next visited position in the script window (after using the navigate to block or find bar). This allows you to middle click a custom block to go to its definition, then press ctrl + Left to go back to where you were before.</p>
<p><strong>Ctrl + Space, Middle Click</strong> – Experimental Feature - This pops up a floating input box where you can type the name of a block (or parts of it) and drag the block into the code to make use of it right there.</p>
<hr />
<h2><strong>Costumes Tab Features</strong></h2>
<p><strong>Find Bar</strong> – Click to list all costumes by name, and type to locate one. Use the arrow keys or mouse to click a name to just straight to that costume.</p>
<p><strong>Ctrl + Left, Ctrl + Right</strong> – These keys navigate you to the previous / next costume in the sprite.</p>
<p><strong>Send to Top, Send to Bottom</strong> – Right click a costume and 2 new menu items are present. These can be used to send the clicked sprite to the top or bottom of the list of costumes for fast re-ordering.</p>
<hr />
<h2><strong>Other Features</strong></h2>
<p><strong>Share</strong> – I have added an 'are you sure?' check to the sharing of projects - Yep I've done that a number of times by mistake - lol</p>
<hr />
<p>Youtube tutorials - <a target="_blank" href="https://www.youtube.com/user/griffpatch">https://www.youtube.com/user/griffpatch</a></p>
</div>
</div>
`
const NavHist = function() {
this.views = [];
this.forward = [];
function distance(pos, next) {
return Math.sqrt(Math.pow(pos.left - next.left, 2) + Math.pow( pos.top - next.top, 2));
}
/**
* Keep a record of the scroll and zoom position
*/
this.storeView = function(next, dist) {
this.forward = [];
let wksp = getWorkspace(),
s = wksp.getMetrics();
let pos = {left:s.viewLeft, top:s.viewTop};
if (!next || distance(pos, next) > dist) {
this.views.push(pos);
}
}
this.peek = function() {
return this.views.length > 0 ? this.views[this.views.length - 1] : null;
}
this.goBack = function() {
let wksp = getWorkspace(),
s = wksp.getMetrics();
let pos = {left:s.viewLeft, top:s.viewTop};
let view = this.peek();
if (!view) {
return;
}
if (distance(pos, view) < 64) { // Go back to current if we are already far away from it
if (this.views.length > 1) {
this.views.pop();
this.forward.push(view);
}
}
view = this.peek();
if (!view) {
return;
}
let sx = view.left - s.contentLeft,
sy = view.top - s.contentTop;
// transform.setTranslate(-600,0);
wksp.scrollbar.set(sx, sy);
/*
let blocklySvg = document.getElementsByClassName('blocklySvg')[0];
let blocklyBlockCanvas = blocklySvg.getElementsByClassName('blocklyBlockCanvas')[0];
let transform = blocklyBlockCanvas.transform.baseVal.getItem(0);
let scale = blocklyBlockCanvas.transform.baseVal.getItem(1);
let transformMatrix = transform.matrix;
let scaleMatrix = scale.matrix;
console.log('Transform - getMetrics', s);
console.log('sx, sy: ', sx, sy);
console.log('left, top: ', view.left, view.top);
console.log('contentLeft, right:', s.contentLeft, s.contentTop);
console.log('transform, scale matrix: ', transformMatrix, scaleMatrix);
*/
}
this.goForward = function() {
let view = this.forward.pop();
if (!view) {
return;
}
this.views.push(view);
let wksp = getWorkspace(),
s = wksp.getMetrics();
let sx = view.left - s.contentLeft,
sy = view.top - s.contentTop;
wksp.scrollbar.set(sx, sy);
}
}
let find, findInp, ddOut, dd, wksp, offsetX = 32, offsetY = 32,
codeTab, costTab, costTabBody, selVarID,
floatInp, blockCursor,
navHist = new NavHist(),
canShare = false,
events = [];
let mouseXY = {x:0, y:0};
function bindOnce(dom, event, func, capture) {
capture = !!capture;
dom.removeEventListener(event, func, capture);
dom.addEventListener(event, func, capture);
events.push({dom:dom, event:event, func:func, capture:capture});
}
function unbindAllEvents() {
console.log('Unbinding Events - gui has become dirty');
for (const event of events) {
event.dom.removeEventListener(event.event, event.func, event.capture);
}
events = [];
}
function isScriptEditor() {
return codeTab.className.indexOf("gui_is-selected") >= 0;
}
function isCostumeEditor() {
return costTab.className.indexOf("gui_is-selected") >= 0;
}
function eventClickHelp(e) {
if (!document.getElementById('s3devHelpPop')) {
document.body.insertAdjacentHTML('beforeend', helpHTML);
document.getElementById('s3devHelpPop').addEventListener('mousedown', function(e) {
if (e.target.id === 's3devHelpPop') {
e.target.remove();
}
});
}
e.preventDefault();
}
/**
*
* @returns Blockly.Workspace
*/
function getWorkspace() {
let wksp2 = Blockly.getMainWorkspace();
if (wksp2.getToolbox()) {
// Sadly get get workspace does not always return the 'real' workspace... Not sure how to get that at the moment,
// but we can work out whether it's the right one by whether it hsa a toolbox.
wksp = wksp2;
}
return wksp;
}
function getScratchCostumes() {
let costumes = costTabBody.querySelectorAll("div[class^='sprite-selector-item_sprite-name']");
// costTab[0].click();
let myBlocks = [];
let myBlocksByProcCode = {};
/**
* @param cls
* @param txt
* @param root
* @returns {{clones: null, procCode: *, labelID: *, lower: *, y: number, cls: *}|*}
*/
function addBlock(cls, txt, root) {
let id = root.className;
let items = {cls: cls, procCode: txt, labelID: id, y: 0, lower: txt.toLowerCase(), clones:null};
// items.y = root.getRelativeToSurfaceXY ? root.getRelativeToSurfaceXY().y : null;
myBlocks.push(items);
myBlocksByProcCode[txt] = items;
return items;
}
let i = 0;
for (const costume of costumes) {
addBlock('costume', costume.innerText, costume).y = i;
i++;
}
return {procs:myBlocks};
}
/**
* Fetch the scratch 3 block list
* @returns jsonFetch object
*/
function getScratchBlocks() {
// Access Blockly!
let myBlocks = [];
let myBlocksByProcCode = {};
// todo - get blockyly from an svg???
let wksp = getWorkspace();
let topBlocks = wksp.getTopBlocks();
// console.log(topBlocks);
/**
* @param cls
* @param txt
* @param root
* @returns {{clones: null, procCode: *, labelID: *, lower: *, y: number, cls: *}|*}
*/
function addBlock(cls, txt, root) {
let id = root.id ? root.id : root.getId ? root.getId() : null;
let clone = myBlocksByProcCode[txt];
if (clone) {
if (!clone.clones) {
clone.clones = [];
}
clone.clones.push(id);
return clone;
}
let items = {cls: cls, procCode: txt, labelID: id, y: 0, lower: txt.toLowerCase(), clones:null};
items.y = root.getRelativeToSurfaceXY ? root.getRelativeToSurfaceXY().y : null;
myBlocks.push(items);
myBlocksByProcCode[txt] = items;
return items;
}
function getDescFromField(root) {
let fields = root.inputList[0];
let desc;
for (const fieldRow of fields.fieldRow) {
desc = (desc ? desc + ' ' : '') + fieldRow.getText();
}
return desc;
}
for (const root of topBlocks) {
if (root.type === "procedures_definition") {
let fields = root.inputList[0];
let typeDesc = fields.fieldRow[0].getText();
let label = root.getChildren()[0];
let procCode = label.getProcCode();
if (!procCode) {
continue;
}
addBlock('define', typeDesc + ' ' + procCode, root);
continue;
}
if (root.type === "event_whenflagclicked") {
addBlock('flag', getDescFromField(root), root); // "When Flag Clicked"
continue;
}
if (root.type === "event_whenbroadcastreceived") {
try { // let wksp2 = Blockly.getMainWorkspace().getTopBlocks()[2].inputList[0].fieldRow[1];
let fields = root.inputList[0];
let typeDesc = fields.fieldRow[0].getText();
let eventName = fields.fieldRow[1].getText();
addBlock('receive', typeDesc + ' ' + eventName, root).eventName = eventName;
} catch (e) {
// eat
}
continue;
}
if (root.type.substr(0, 10) === 'event_when') {
addBlock('event', getDescFromField(root), root); // "When Flag Clicked"
continue;
}
if (root.type === 'control_start_as_clone') {
addBlock('event', getDescFromField(root), root); // "when I start as a clone"
continue;
}
}
let map = wksp.getVariableMap();
let vars = map.getVariablesOfType('');
for (const row of vars) {
addBlock((row.isLocal ? "var" : "VAR"), (row.isLocal ? "var " : "VAR ") + row.name, row);
}
let lists = map.getVariablesOfType('list');
for (const row of lists) {
addBlock((row.isLocal ? "list" : "LIST"), (row.isLocal ? "list " : "LIST ") + row.name, row);
}
const clsOrder = {flag:0, receive:1, event:2, define:3, var:4, VAR:5, list:6, LIST:7};
myBlocks.sort(function (a, b) {
let t = clsOrder[a.cls] - clsOrder[b.cls];
if (t !== 0) {
return t;
}
if (a.lower < b.lower) {
return -1;
}
if (a.lower > b.lower) {
return 1;
}
return a.y - b.y;
});
return {procs:myBlocks};
}
let rhdd = 0;
let rhdd2 = 0;
function showDropDown(e, focusID, instanceBlock) {
clearTimeout(rhdd);
rhdd = 0;
if (!focusID && ddOut.classList.contains('vis')) {
return;
}
// special '' vs null... - null forces a reevaluation
prevVal = focusID ? '' : null; // Clear the previous value of the input search
ddOut.classList.add('vis');
let scratchBlocks;
if (isCostumeEditor()) {
scratchBlocks = getScratchCostumes();
} else {
scratchBlocks = getScratchBlocks();
}
dom_removeChildren(dd);
let foundLi = null;
let procs = scratchBlocks.procs;
for (const proc of procs) {
let li = document.createElement("li");
li.innerText = proc.procCode;
li.data = proc;
li.className = proc.cls;
if (focusID) {
if (proc.labelID === focusID) {
foundLi = li;
li.classList.add("sel");
} else {
li.style.display = 'none';
}
}
dd.appendChild(li);
}
let label = document.getElementById('s3devFindLabel');
offsetX = ddOut.getBoundingClientRect().right - label.getBoundingClientRect().left + 26;
offsetY = 32;
if (foundLi) {
clickDropDownRow(foundLi, wksp, instanceBlock);
}
}
function hideDropDown() {
clearTimeout(rhdd);
rhdd = setTimeout(reallyHideDropDown, 250);
}
function reallyHideDropDown() {
// Check focus of find box
if (findInp === document.activeElement) {
hideDropDown();
return;
}
// document.getElementById('s3devReplace').classList.add('s3devHide');
ddOut.classList.remove('vis');
rhdd = 0;
}
function hideFloatDropDown() {
clearTimeout(rhdd2);
rhdd2 = setTimeout(reallyHideFloatDropDown, 50);
}
function reallyHideFloatDropDown(force) {
// Check focus of find box
if (!force && floatInp === document.activeElement) {
hideFloatDropDown();
return;
}
let float = document.getElementById('s3devFloatingBar');
if (float) {
float.remove();
}
floatInp = null;
rhdd2 = 0;
}
function dom_removeChildren(myNode) {
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
/**
* A nicely ordered version of the top blocks
* @returns {[]}
*/
function getTopBlocks() {
let result = getOrderedTopBlockColumns();
let columns = result.cols;
let topBlocks = [];
for (const col of columns) {
topBlocks = topBlocks.concat(col.blocks);
}
return topBlocks;
}
/**
* A much nicer way of laying out the blocks into columns
*/
function doCleanUp(e) {
if (e) {
e.cancelBubble = true;
e.preventDefault();
let wksp = getWorkspace();
wksp.setVisible(false);
wksp.setVisible(true);
setTimeout(doCleanUp, 0);
return;
}
let result = getOrderedTopBlockColumns(true);
let columns = result.cols;
let orphanCount = result.orphans.blocks.length;
if (orphanCount > 0) {
let message = 'Griffpatch: I found ' + orphanCount;
message += orphanCount === 1 ? ' orphaned reporter block. Shall I delete it for you?' :
' orphaned reporter blocks. Shall I delete it for you?';
if (confirm(message)) {
for (const block of result.orphans.blocks) {
block.dispose();
}
} else {
columns.unshift(result.orphans);
}
}
let cursorX = 48;
let maxWidths = result.maxWidths;
for (const column of columns) {
let cursorY = 64;
let maxWidth = 0;
for (const block of column.blocks) {
let xy = block.getRelativeToSurfaceXY();
if (cursorX - xy.x !== 0 || cursorY - xy.y !== 0) {
block.moveBy(cursorX - xy.x, cursorY - xy.y);
}
let heightWidth = block.getHeightWidth();
cursorY += heightWidth.height + 72;
let maxWidthWithComments = maxWidths[block.id] || 0;
maxWidth = Math.max(maxWidth, Math.max(heightWidth.width, maxWidthWithComments));
}
cursorX += maxWidth + 96;
}
let topComments = wksp.getTopComments();
for (const comment of topComments) {
if (comment.setVisible) {
comment.setVisible(false);
comment.needsAutoPositioning_ = true;
comment.setVisible(true);
}
}
setTimeout(function () {
// Locate unused local variables...
let workspace = getWorkspace();
let map = workspace.getVariableMap();
let vars = map.getVariablesOfType('');
let unusedLocals = [];
for (const row of vars) {
if (row.isLocal) {
let usages = map.getVariableUsesById(row.getId());
if (!usages || usages.length === 0) {
unusedLocals.push(row);
}
}
}
if (unusedLocals.length > 0) {
let message = 'Griffpatch: I found ' + unusedLocals.length;
message += unusedLocals.length === 1 ? ' unused local variable. Shall I delete it for you?\nHere it is: ' : ' unused local variables. Shall I delete them for you?\nHere they are: ';
for (let i=0; i<unusedLocals.length; i++) {
let orphan = unusedLocals[i];
if (i > 0) {
message += ', ';
}
message += orphan.name;
}
if (confirm(message)) {
for (const orphan of unusedLocals) {
workspace.deleteVariableById(orphan.getId());
}
}
}
}, 100);
}
/**
* Badly Ophaned - might want to delete these!
* @param topBlock
* @returns {boolean}
*/
function isBlockAnOrphan(topBlock) {
if (topBlock.getOutputShape() && !topBlock.getSurroundParent()) {
return true;
}
return false;
}
/**
* Split the top blocks into ordered columns
* @param separateOrphans true to keep all orphans separate
* @returns {{orphans: {blocks: [], x: number, count: number}, cols: []}}
*/
function getOrderedTopBlockColumns(separateOrphans) {
let w = getWorkspace();
let topBlocks = w.getTopBlocks();
let maxWidths = {};
if (separateOrphans) {
let topComments = w.getTopComments();
// todo: tie comments to blocks... find widths and width of block stack row...
for (const comment of topComments) {
// coment.autoPosition_();
// Hiding and showing repositions the comment right next to it's block - nice!
if (comment.setVisible) {
comment.setVisible(false);
comment.needsAutoPositioning_ = true;
comment.setVisible(true);
// let bb = comment.block_.svgPath_.getBBox();
let right = comment.getBoundingRectangle().bottomRight.x;
// Get top block for stack...
let root = comment.block_.getRootBlock();
let left = root.getBoundingRectangle().topLeft.x;
maxWidths[root.id] = Math.max(right - left, maxWidths[root.id] || 0);
}
}
}
// Default scratch ordering is horrid... Lets try something more clever.
let cols = [];
const TOLERANCE = 256;
let orphans = {x:-999999, count:0, blocks:[]};
for (const topBlock of topBlocks) {
// let r = b.getBoundingRectangle();
let position = topBlock.getRelativeToSurfaceXY();
let bestCol = null;
let bestError = TOLERANCE;
if (separateOrphans && isBlockAnOrphan(topBlock)) {
orphans.blocks.push(topBlock);
continue;
}
// Find best columns
for (const col of cols) {
let err = Math.abs(position.x - col.x);
if (err < bestError) {
bestError = err;
bestCol = col;
}
}
if (bestCol) {
// We found a column that we fitted into
bestCol.x = (bestCol.x * bestCol.count + position.x) / ++bestCol.count; // re-average the columns as more items get added...
bestCol.blocks.push(topBlock);
} else {
// Create a new column
cols.push({x:position.x,count:1,blocks:[topBlock]});
}
}
// if (orphans.blocks.length > 0) {
// cols.push(orphans);
// }
// Sort columns, then blocks inside the columns
cols.sort(function (a, b) {return a.x - b.x;});
for (const col of cols) {
col.blocks.sort(function (a, b) {return a.getRelativeToSurfaceXY().y - b.getRelativeToSurfaceXY().y;});
}
return {cols:cols, orphans:orphans, maxWidths:maxWidths};
}
/**
* Find all the uses of a named variable.
* @param {string} id ID of the variable to find.
* @return {!Array.<!Blockly.Block>} Array of block usages.
*/
function getVariableUsesById(id) {
let uses = [];
let topBlocks = getTopBlocks(true);
for (const topBlock of topBlocks) {
let kids = topBlock.getDescendants();
for (const block of kids) {
let blockVariables = block.getVarModels();
if (blockVariables) {
for (const blockVar of blockVariables) {
if (blockVar.getId() === id) {
uses.push(block);
}
}
}
}
}
return uses;
}
/**
* Find all the uses of a named procedure.
* @param {string} id ID of the variable to find.
* @return {!Array.<!Blockly.Block>} Array of block usages.
*/
function getCallsToProcedureById(id) {
let w = getWorkspace();
let procBlock = w.getBlockById(id);
let label = procBlock.getChildren()[0];
let procCode = label.getProcCode();
let uses = [procBlock]; // Definition First, then calls to it
let topBlocks = getTopBlocks(true);
for (const topBlock of topBlocks) {
let kids = topBlock.getDescendants();
for (const block of kids) {
if (block.type === "procedures_call") {
if (block.getProcCode() === procCode) {
uses.push(block);
}
}
}
}
return uses;
}
/**
* Find all the uses of a named procedure.
* @param {string} id ID of the variable to find.
* @return {!Array.<!Blockly.Block>} Array of block usages.
*/
function getCallsToEventsByName(name) {
let uses = []; // Definition First, then calls to it
let topBlocks = getTopBlocks(true);
for (const topBlock of topBlocks) {
let kids = topBlock.getDescendants();
for (const block of kids) {
if (block.type === "event_broadcast" || block.type === "event_broadcastandwait") {
if (name === block.getChildren()[0].inputList[0].fieldRow[0].getText()) {
uses.push(block);
}
}
}
}
return uses;
}
function buildNavigationCarousel(nav, li, blocks, instanceBlock) {
if (nav && nav.parentNode === li) {
// Same control... click again to go to next
multi.navRight();
} else {
if (nav) {
nav.remove();
}
li.insertAdjacentHTML('beforeend', `
<span id="s3devMulti" class="s3devMulti">
<span id="s3devMultiLeft" class="s3devNav">◀</span><span id="s3devMultiCount"></span><span id="s3devMultiRight" class="s3devNav">▶</span>
</span>
`);
document.getElementById('s3devMultiLeft').addEventListener("mousedown", multi.navLeft);
document.getElementById('s3devMultiRight').addEventListener("mousedown", multi.navRight);
multi.idx = 0;
if (instanceBlock) {
multi.idx = blocks.indexOf(instanceBlock);
}
multi.blocks = blocks;
multi.update();
if (multi.idx < blocks.length) {
centerTop(blocks[multi.idx]);
}
}
}
function triggerDragAndDrop(selectorDrag, selectorDrop, mouseXY) {
// function for triggering mouse events
let fireMouseEvent = function (type, elem, centerX, centerY) {
let evt = document.createEvent('MouseEvents');
evt.initMouseEvent(type, true, true, window, 1, 1, 1, centerX, centerY, false, false, false, false, 0, elem);
elem.dispatchEvent(evt);
};
// fetch target elements
let elemDrag = selectorDrag; // document.querySelector(selectorDrag);
let elemDrop = selectorDrop; // document.querySelector(selectorDrop);
if (!elemDrag/* || !elemDrop*/) return false;
// calculate positions
let pos = elemDrag.getBoundingClientRect();
let center1X = Math.floor((pos.left + pos.right) / 2);
let center1Y = Math.floor((pos.top + pos.bottom) / 2);
// mouse over dragged element and mousedown
fireMouseEvent('mouseover', elemDrag, center1X, center1Y);
fireMouseEvent('mousedown', elemDrag, center1X, center1Y);
// start dragging process over to drop target
fireMouseEvent('dragstart', elemDrag, center1X, center1Y);
fireMouseEvent('drag', elemDrag, center1X, center1Y);
fireMouseEvent('mousemove', elemDrag, center1X, center1Y);
if (!elemDrop) {
if (mouseXY) {
// console.log(mouseXY);
let center2X = mouseXY.x;
let center2Y = mouseXY.y;
fireMouseEvent('drag', elemDrag, center2X, center2Y);
fireMouseEvent('mousemove', elemDrag, center2X, center2Y);
}
return false;
}
pos = elemDrop.getBoundingClientRect();
let center2X = Math.floor((pos.left + pos.right) / 2);
let center2Y = Math.floor((pos.top + pos.bottom) / 2);
fireMouseEvent('drag', elemDrag, center2X, center2Y);
fireMouseEvent('mousemove', elemDrop, center2X, center2Y);
// trigger dragging process on top of drop target
fireMouseEvent('mouseenter', elemDrop, center2X, center2Y);
fireMouseEvent('dragenter', elemDrop, center2X, center2Y);
fireMouseEvent('mouseover', elemDrop, center2X, center2Y);
fireMouseEvent('dragover', elemDrop, center2X, center2Y);
// release dragged element on top of drop target
fireMouseEvent('drop', elemDrop, center2X, center2Y);
fireMouseEvent('dragend', elemDrag, center2X, center2Y);
fireMouseEvent('mouseup', elemDrag, center2X, center2Y);
return true;
}
/**
* Move a costume to the top or bottom of the list
* @param top true for the top, false for the bottom
* @param selected optional parameter to pass in the costume div to be moved
*/
function moveCostumeTo(top, selected) {
let isSelected = !selected || selected.className.indexOf("sprite-selector-item_is-selected") >= 0;
if (!selected) {
selected = costTabBody.querySelectorAll("div[class*='sprite-selector-item_is-selected']");
if (selected.length === 0) {
return;
}
selected = selected[0].querySelectorAll("div[class^='sprite-selector-item_sprite-name']")[0];
}
let costumes = costTabBody.querySelectorAll("div[class^='sprite-selector-item_sprite-name']");
// First scroll sprite view to reveal top or bottom otherwise this won't work.
let scroller = selected.closest("div[class*=selector_list-area]");
let lastScroll = scroller.scrollTop;
scroller.scrollTop = top ? 0 : scroller.scrollHeight;
triggerDragAndDrop(selected, costumes[top ? 0 : costumes.length - 1]);
if (!isSelected) {
// Restore Scroll position
scroller.scrollTop = lastScroll;
}
}
/**
*
* @param li
* @param workspace
* @param instanceBlock the instance to be highlighted (or null)
*/
function clickDropDownRow(li, workspace, instanceBlock) {
let nav = document.getElementById('s3devMulti');
let cls = li.data.cls;
if (cls === 'costume') {
// Viewing costumes - jump to selected costume
let costumes = costTabBody.querySelectorAll("div[class^='sprite-selector-item_sprite-name']");
let costume = costumes[li.data.y];
if (costume) {
costume.click();
setTimeout(function () {
let wrapper = costume.closest("div[class*=gui_flex-wrapper]");
costume.parentElement.parentElement.scrollIntoView({
behavior: "auto",
block: "center",
inline: "start"
});
wrapper.scrollTop = 0;
}, 10);
}
} else if (cls === 'var' || cls === 'VAR' || cls === 'list' || cls === 'LIST') {
// Search now for all instances
// let wksp = getWorkspace();
// let blocks = wksp.getVariableUsesById(li.data.labelID);
let blocks = getVariableUsesById(li.data.labelID);
buildNavigationCarousel(nav, li, blocks, instanceBlock);
} else if (cls === 'define') {
let blocks = getCallsToProcedureById(li.data.labelID);
buildNavigationCarousel(nav, li, blocks, instanceBlock);
} else if (cls === 'receive') {
let blocks = [workspace.getBlockById(li.data.labelID)];
if (li.data.clones) {
for (const cloneID of li.data.clones) {
blocks.push(workspace.getBlockById(cloneID))
}
}
blocks = blocks.concat(getCallsToEventsByName(li.data.eventName));
buildNavigationCarousel(nav, li, blocks, instanceBlock);
} else if (li.data.clones) {
let blocks = [workspace.getBlockById(li.data.labelID)];
for (const cloneID of li.data.clones) {
blocks.push(workspace.getBlockById(cloneID))
}
buildNavigationCarousel(nav, li, blocks, instanceBlock);
} else {
multi.blocks = null;
centerTop(li.data.labelID);
if (nav) {
nav.remove();
}
}
}
function dropDownClick(e) {
// console.log(e);
let workspace = getWorkspace();
if (prevVal === null) {
prevVal = findInp.value; // Hack to stop filter change if not entered data into edt box, but clicked on row
}
let li = e.target;
for (;;) {
if (!li || li === dd) {
return;
}
if (li.data) {
break;
}
li = li.parentNode;
}
// If this was a mouse click, unselect the keyboard selection
// e.navKey is set when this is called from the keyboard handler...
if (!e.navKey) {
let sel = dd.getElementsByClassName('sel');
sel = sel.length > 0 ? sel[0] : null;
if (sel && sel !== li) {
try {
sel.classList.remove('sel');
} catch (e) {
console.log(sel);
console.error(e);
}
}
if (li !== sel) {
li.classList.add('sel');
}
}
clickDropDownRow(li, workspace);
if (e) {
e.preventDefault();
e.cancelBubble = true;
}
return false;
}
let multi = {
idx: 0,
blocks: null,
update: function () {
let count = document.getElementById('s3devMultiCount');
count.innerText = multi.blocks && multi.blocks.length > 0 ? enc((multi.idx + 1) + " / " + multi.blocks.length) : "0"
},
navLeft: function(e) { return multi.navSideways(e, -1); },
navRight: function(e) { return multi.navSideways(e, 1); },
navSideways: function(e, dir) {
if (multi.blocks && multi.blocks.length > 0) {
multi.idx = (multi.idx + dir + multi.blocks.length) % multi.blocks.length; // + length to fix negative modulo js issue.
multi.update();
centerTop(multi.blocks[multi.idx]);
}
if (e) {
e.cancelBubble = true;
e.preventDefault();
}
return false;
}
};
let myFlash = {block:null, timerID:null, colour:null};
let myFlashTimer;
/**
* Based on wksp.centerOnBlock(li.data.labelID);
* @param e
* @param force if true, the view always moves, otherwise only move if the selected element is not entirely visible
*/
function centerTop(e, force) {
let wksp = getWorkspace();
if (e = (e && e.id ? e : wksp.getBlockById(e))) {
let root = e.getRootBlock();
let base = e;
while (base.getOutputShape() && base.getSurroundParent()) {
base = base.getSurroundParent();
}
let ePos = base.getRelativeToSurfaceXY(), // Align with the top of the block
rPos = root.getRelativeToSurfaceXY(), // Align with the left of the block 'stack'
eSiz = e.getHeightWidth(),
scale = wksp.scale,
// x = (ePos.x + (wksp.RTL ? -1 : 1) * eSiz.width / 2) * scale,
x = rPos.x * scale,
y = ePos.y * scale,
xx = e.width + x, // Turns out they have their x & y stored locally, and they are the actual size rather than scaled or including children...
yy = e.height + y,
// xx = eSiz.width * scale + x,
// yy = eSiz.height * scale + y,