-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathBoardFrame.js
More file actions
1269 lines (1188 loc) · 49.8 KB
/
BoardFrame.js
File metadata and controls
1269 lines (1188 loc) · 49.8 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
/*
* Project Name : Visual Python
* Description : GUI-based Python code generator
* File Name : BoardFrame.js
* Author : Black Logic
* Note : Render and load board frame
* License : GNU GPLv3 with Visual Python special exception
* Date : 2021. 09. 13
* Change Date :
*/
//============================================================================
// [CLASS] BoardFrame
//============================================================================
define([
__VP_TEXT_LOADER__('../../html/boardFrame.html'), // INTEGRATION: unified version of text loader
__VP_CSS_LOADER__('../../css/boardFrame'), // INTEGRATION: unified version of css loader
'../com/com_Config',
'../com/com_Const',
'../com/com_String',
'../com/com_util',
'../com/com_interface',
'../com/component/Component',
'../com/component/FileNavigation',
'./Block',
'./BlockMenu',
'./CodeView'
], function(boardFrameHtml, boardFrameCss, com_Config, com_Const, com_String, com_util, com_interface,
Component, FileNavigation, Block, BlockMenu, CodeView) {
'use strict';
//========================================================================
// Define Variable
//========================================================================
const BLOCK_PADDING = 20;
/**
* BoardFrame
*/
class BoardFrame extends Component{
//========================================================================
// Constructor
//========================================================================
constructor($target, state, prop) {
super($target, state, prop);
/*
* state.vp_note_display
* state.vp_note_width
* prop.parent: MainFrame
*/
}
//========================================================================
// Internal call function
//========================================================================
_init() {
// selected block
this.selectedBlock = null;
this._blockList = {
'default': {
title: '',
blockList: []
}
}
// state
this.state = {
vp_note_display: true,
viewDepthNumber: false,
indentCount: 4,
...this.state
};
// temporary state
this.tmpState = {
boardTitle: 'Untitled',
boardPath: null,
copy: {
start: 0,
end: 0
}
}
this.headBlocks = ['lgCtrl_if', 'lgCtrl_for', 'lgCtrl_try'];
this.subBlocks = ['lgCtrl_elif', 'lgCtrl_else', 'lgCtrl_except', 'lgCtrl_finally'];
}
get blockList() {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
if (sessionId in this._blockList) {
return this._blockList[sessionId].blockList;
}
return [];
}
set blockList(val) {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
if (sessionId in this._blockList) {
this._blockList[sessionId].blockList = val;
} else {
this._blockList[sessionId] = {
title: '',
blockList: val
}
}
return true;
}
addToBlockList(newVal, position=-1) {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
} else {
// No Session
sessionId = null;
}
}
if (sessionId == null) {
// No session
return false;
} else {
if (sessionId in this._blockList) {
if (position >= 0) {
this._blockList[sessionId].blockList.splice(position, 0, newVal);
} else {
this._blockList[sessionId].blockList.push(newVal);
}
} else {
this._blockList[sessionId] = {
title: '',
blockList: [ newVal ]
};
}
}
return true;
}
removeFromBlockList(removeVal) {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
if (sessionId in this._blockList) {
this._blockList[sessionId].blockList.splice(
this._blockList[sessionId].blockList.indexOf(removeVal), 1
);
} else {
return false;
}
return true;
}
getTitle() {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
if (sessionId in this._blockList) {
return this._blockList[sessionId].title;
} else {
return '';
}
}
setTitle(newTitle) {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
if (sessionId in this._blockList) {
this._blockList[sessionId].title = newTitle;
} else {
this._blockList[sessionId] = {
title: newTitle,
blockList: [ ]
};
}
}
_bindEvent() {
let that = this;
// board menu toggle button
$(this.wrapSelector('.vp-board-header-button')).on('click', function(evt) {
$(that.wrapSelector('.vp-board-header-button-inner')).toggle();
evt.stopPropagation();
});
// board menu button click
$(this.wrapSelector('.vp-board-header-button-inner ul li')).on('click', function() {
let menu = $(this).data('menu');
switch (menu) {
case 'new':
that.createNewNoteWithChecking();
break;
case 'open':
that.openNote();
break;
case 'save':
that.saveNote();
break;
case 'save-as':
that.saveAsNote();
break;
case 'run-all':
that.runAll();
break;
case 'code-view':
that.viewCode();
break;
case 'code-export':
that.exportCode();
break;
case 'clear':
that.clearBoardWithChecking();
break;
}
});
// footer +code, +text button
$('.vp-board-footer-buttons button').on('click', function() {
let menu = $(this).data('menu');
if (menu === 'code') {
// code
$('#vp_wrapper').trigger({
type: 'create_option_page',
blockType: 'block',
menuId: 'lgExe_code',
menuState: {}
});
} else if (menu === 'text') {
// text
$('#vp_wrapper').trigger({
type: 'create_option_page',
blockType: 'block',
menuId: 'apps_markdown',
menuState: {}
});
}
});
// change of boardTitle
$(this.wrapSelector('#vp_boardTitle')).on('change', function() {
let fileName = $(this).val();
that.setTitle(fileName); // LAB: session note title
that.tmpState.boardTitle = fileName;
that.tmpState.boardPath = null;
});
// click board - blur block
$(this.wrapSelector()).on('click', function() {
that.blurAllblock();
});
}
_bindSortable() {
let that = this;
let parent = this.prop.parent;
let position = -1;
let targetBlock = null;
let targetId = '';
let groupedBlocks = null;
let parentBlock = null;
let depth = 0;
let revert = false;
$('.vp-board-body').sortable({
items: '> .vp-block',
axis: 'y',
scroll: true,
revert: false,
cursor: 'move',
handle: '.vp-block-header',
helper: function(evt, currentItem) {
let header = currentItem.data('name');
let tag = new com_String();
tag.appendLine('<div class="vp-sortable-helper" style="z-index: 199;">');
tag.appendFormatLine('<div>{0}</div>', header);
tag.appendLine('</div>');
return tag.toString();
},
placeholder: {
element: function(currentItem) {
let block = currentItem.data('block');
let color = currentItem.data('color');
targetId = currentItem.data('menu');
if (block) {
let tag = new com_String();
tag.appendFormatLine('<div class="vp-block vp-block-group vp-sortable-placeholder {0}" style="z-index: 199;">', block.getColorLabel());
tag.appendFormatLine('<div class="vp-block-header">{0}</div>', block.name);
tag.appendLine('</div>');
return tag.toString();
} else {
let header = currentItem.find('.vp-block-header').text();
let tag = new com_String();
tag.appendFormatLine('<div class="vp-block vp-block-group vp-sortable-placeholder {0}" style="z-index: 199;">', color);
tag.appendFormatLine('<div class="vp-block-header">{0}</div>', header);
tag.appendLine('</div>');
return tag.toString();
}
},
update: function(container, p) {
// container: container
// p: placeholder object
return;
}
},
start: function(evt, ui) {
position = ui.item.index();
targetBlock = that.blockList[position];
if (targetBlock) {
if (targetBlock.isSubBlock) {
revert = true;
return;
}
// hide grouped item
groupedBlocks = targetBlock.getGroupedBlocks();
groupedBlocks.forEach(block => {
block.hide();
});
} else {
// hide original item
ui.item.hide();
}
},
sort: function(evt, ui) {
let tmpPos = ui.placeholder.index();
let currCursorX = evt.clientX;
let currCursorY = evt.clientY;
if (position < tmpPos && groupedBlocks) {
tmpPos += (1 - groupedBlocks.length);
}
// sorting is not allowed for sub blocks (elif, else, except, finally)
if (revert) {
ui.placeholder.removeClass('vp-block-group');
ui.placeholder.insertAfter($('.vp-block:not(.vp-draggable-helper):not(.vp-sortable-placeholder):nth('+(position - 1)+')'));
return;
}
let befBlockTag = $('.vp-block:not(.vp-draggable-helper):not(.vp-sortable-placeholder):nth('+(tmpPos - 1)+')');
if (befBlockTag && befBlockTag.length > 0) {
let befBlock = befBlockTag.data('block');
let befGroupBlock = befBlock.getGroupBlock();
let rect = befBlockTag[0].getBoundingClientRect();
let befStart = rect.y;
let befRange = rect.y + rect.height;
let befGroupRange = befRange + (rect.height/2);
let befDepth = befBlock.getChildDepth();
let isMarkdown = false; // if befBlock or thisBlock is markdown
// check if thisBlock is markdown block or befBlock is markdown block
if (targetId == 'apps_markdown' || (befBlock && befBlock.id == 'apps_markdown')) {
isMarkdown = true;
}
if (isMarkdown) {
let befGroupedBlocks = befGroupBlock.getGroupedBlocks();
let befGroupLastBlock = befGroupedBlocks[befGroupedBlocks.length - 1]; // last block of previous group
if (!befBlock.equals(befGroupLastBlock)) {
ui.placeholder.insertAfter(befGroupLastBlock.getTag());
return;
}
}
if (!isMarkdown) {
if (befBlock.isSubBlock || (befStart < currCursorY && currCursorY < befRange)) {
// sort as child of befBlock (except Markdown)
// - if befBlock is subBlock, no group block is allowed
parentBlock = befBlock;
depth = befDepth;
ui.placeholder.removeClass('vp-block-group');
ui.placeholder.css({ 'padding-left': depth*BLOCK_PADDING + 'px'});
return;
}
if (befRange <= currCursorY && currCursorY < befGroupRange) {
// sort as child of befGroupBlock (except Markdown)
parentBlock = befGroupBlock;
depth = befGroupBlock.getChildDepth();
ui.placeholder.removeClass('vp-block-group');
ui.placeholder.css({ 'padding-left': depth*BLOCK_PADDING + 'px'});
return;
}
}
// sort after befBlock
parentBlock = null;
if (!ui.placeholder.hasClass('vp-block-group')) {
ui.placeholder.addClass('vp-block-group');
}
ui.placeholder.css({ 'padding-left': 0});
depth = 0;
}
},
stop: function(evt, ui) {
var spos = position;
var epos = ui.item.index();
if (revert) {
revert = false;
return;
}
if (spos < epos && groupedBlocks) {
epos += (1 - groupedBlocks.length);
}
if (epos > -1) {
// move list element
if (parentBlock) {
that.moveBlock(spos, epos, parentBlock);
} else {
that.moveBlock(spos, epos);
}
}
if (targetBlock && groupedBlocks) {
// show grouped block
groupedBlocks.forEach(block => {
block.show();
});
} else {
// show original item
ui.item.show();
}
}
}).disableSelection();
}
//========================================================================
// External call function
//========================================================================
/**
* Make template
*/
template() {
return boardFrameHtml.replaceAll('${vp_base}', com_Const.BASE_PATH);
}
/**
* Render and load on parentDom, bind events
*/
render() {
super.render();
// display note
if (!this.state.vp_note_display) {
this.hide();
}
// set width using metadata
$(this.wrapSelector()).width(this.state.vp_note_width);
// render taskBar
this.renderBlockList([]);
this._bindSortable();
this.blockMenu = new BlockMenu(this);
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let that = this;
vpLab.shell._currentChanged.connect(function(sender, value) {
// if lab tab changed, reset title and reload board
that.reloadBlockList();
});
}
}
/**
* Render block list
*/
renderBlockList(blockPopupList) {
let that = this;
let parent = this.prop.parent;
$('.vp-board-body').html('');
blockPopupList && blockPopupList.forEach(task => {
let block = new Block(this, { task: task });
// LAB: add session queue to blockList
// that.blockList.push(block);
that.addToBlockList(block);
});
}
/**
* Reload block list on the board
*/
reloadBlockList() {
let num = 1;
// reset boardframe title
$(this.wrapSelector('#vp_boardTitle')).val(this.getTitle());
// init boardframe body
$(this.wrapSelector('.vp-board-body')).html('');
// render block list
this.blockList.forEach(block => {
// if it's already rendered and block
if (block && block instanceof Block) {
if (block.isGroup) {
block.setNumber(num++);
}
block.render();
}
})
this.renderInfo();
}
renderInfo() {
let num = 1;
$('.vp-block.vp-block-group').each(function(i, block) {
let numInfo = $(block).find('.vp-block-num-info');
$(numInfo).html(num++);
});
}
show() {
// show note area
$(this.wrapSelector()).show();
$('#vp_toggleBoard').removeClass('vp-hide');
$('#vp_toggleBoard').attr('title', 'Hide VP Note');
// set width
let boardWidth = com_Config.BOARD_MIN_WIDTH;
$(this.wrapSelector()).width(boardWidth);
// save as metadata
vpConfig.setMetadata({ vp_note_display: true, vp_note_width: boardWidth });
}
hide() {
// hide note area
$(this.wrapSelector()).hide();
if (!$('#vp_toggleBoard').hasClass('vp-hide')) {
$('#vp_toggleBoard').addClass('vp-hide');
}
$('#vp_toggleBoard').attr('title', 'Show VP Note');
// set width
let boardWidth = 0;
$(this.wrapSelector()).width(boardWidth);
// save as metadata
vpConfig.setMetadata({ vp_note_display: false, vp_note_width: boardWidth });
}
showLoadingBar() {
$(this.wrapSelector('#vp_boardLoading')).show();
}
hideLoadingBar() {
$(this.wrapSelector('#vp_boardLoading')).hide();
}
//========================================================================
// Note control
//========================================================================
/**
* Check if note has changes to save
*/
checkNote() {
if (this.blockList.length > 0) {
return true;
}
return false;
}
createNewNoteWithChecking() {
// alert before closing
let that = this;
if (this.checkNote()) {
// render update modal
com_util.renderModal({
title: 'Unsaved changes',
message: 'Do you want to save?',
buttons: ['Cancel', 'No', 'Save'],
defaultButtonIdx: 0,
buttonClass: ['cancel', '', 'activated'],
finish: function(clickedBtnIdx) {
switch (clickedBtnIdx) {
case 0:
// cancel - do nothing
return;
case 1:
// don't save
that.createNewNote();
break;
case 2:
// save
that.saveAsNote(function() {
that.createNewNote();
});
break;
}
}
});
return;
}
this.createNewNote();
}
createNewNote() {
// clear board before create new note
this.clearBoard();
let defaultTitle = 'Untitled';
// set title to Untitled
this.tmpState.boardTitle = defaultTitle;
// set path to empty
this.tmpState.boardPath = null;
// set title
$(this.wrapSelector('#vp_boardTitle')).val(defaultTitle);
this.setTitle(defaultTitle); // LAB: session note title
}
openNote() {
// TODO: check save as
let that = this;
// open file navigation
let fileNavi = new FileNavigation({
type: 'open',
extensions: ['vp'],
finish: function(filesPath, status, error) {
// clear board before open note
that.clearBoard();
let vpFilePath = filesPath[0].path;
let vpFileName = filesPath[0].file;
// read file
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
// LAB: read file using python open
vpKernel.readFile(vpFilePath).then(function(resultObj) {
try {
var jsonList = JSON.parse(resultObj.result);
// load blocks
that.jsonToBlock(jsonList);
var indexVp = vpFileName.indexOf('.vp');
var saveFileName = vpFileName.slice(0,indexVp);
// show title of board and path
$('#vp_boardTitle').val(saveFileName);
that.setTitle(saveFileName); // LAB: session note title
that.tmpState.boardTitle = saveFileName;
that.tmpState.boardPath = vpFilePath;
com_util.renderSuccessMessage('Successfully opened file. (' + vpFileName + ')');
} catch (ex) {
com_util.renderAlertModal('Not applicable file contents with vp format! (JSON)');
}
}).catch(function(err) {
vpLog.display(VP_LOG_TYPE.ERROR, err);
})
} else {
fetch(vpFilePath).then(function(file) {
if (file.status != 200) {
com_util.renderAlertModal('The file format is not valid. (file: '+file+')');
return;
}
file.text().then(function(data) {
// var parsedData = decodeURIComponent(data);
try {
var jsonList = JSON.parse(data);
// load blocks
that.jsonToBlock(jsonList);
var indexVp = vpFileName.indexOf('.vp');
var saveFileName = vpFileName.slice(0,indexVp);
// show title of board and path
$('#vp_boardTitle').val(saveFileName);
that.setTitle(saveFileName); // LAB: session note title
that.tmpState.boardTitle = saveFileName;
that.tmpState.boardPath = vpFilePath;
com_util.renderSuccessMessage('Successfully opened file. (' + vpFileName + ')');
} catch (ex) {
com_util.renderAlertModal('Not applicable file contents with vp format! (JSON)');
}
});
}).catch(function(err) {
vpLog.display(VP_LOG_TYPE.ERROR, err);
});
}
}
});
fileNavi.open();
}
saveNote() {
let { boardPath, boardTitle } = this.tmpState;
// if path exists, save note
if (boardPath && boardPath != '') {
// save vp file
let idx = boardTitle.lastIndexOf('.vp');
if (idx < 0) {
boardTitle += '.vp';
}
let saveData = this.blockToJson(this.blockList);
let saveDataStr = JSON.stringify(saveData);
vpKernel.saveFile(boardTitle, boardPath, saveDataStr);
return;
}
this.saveAsNote();
}
saveAsNote(callback) {
let that = this;
// save file navigation
let fileNavi = new FileNavigation({
type: 'save',
fileName: this.tmpState.boardTitle,
extensions: ['vp'],
finish: function(filesPath, status, error) {
let boardTitle = filesPath[0].file;
let boardPath = filesPath[0].path;
// save vp file
let saveData = that.blockToJson(that.blockList);
let saveDataStr = JSON.stringify(saveData);
vpKernel.saveFile(boardTitle, boardPath, saveDataStr);
// save it in tmpState
// detach extension
let idx = boardTitle.lastIndexOf('.vp');
boardTitle = boardTitle.substring(0, idx);
that.tmpState.boardTitle = boardTitle;
that.tmpState.boardPath = boardPath;
$('#vp_boardTitle').val(boardTitle);
that.setTitle(boardTitle); // LAB: session note title
if (callback != undefined && typeof callback === 'function') {
callback();
}
}
});
fileNavi.open();
}
runBlock(block, execute=true, addcell=true) {
if (block.id == 'apps_markdown') {
// if markdown, run single
return block.popup.run(execute, addcell);
}
let rootBlockDepth = block.depth;
let groupedBlocks = block.getGroupedBlocks();
let code = new com_String();
let indentCount = this.state.indentCount;
groupedBlocks.forEach((groupBlock, idx) => {
let prevNewLine = idx > 0?'\n':'';
let indent = ' '.repeat((groupBlock.depth - rootBlockDepth) * indentCount);
let thisBlockCode = groupBlock.popup.generateCode();
if (Array.isArray(thisBlockCode)) {
for (let i = 0; i < thisBlockCode.length; i++) {
thisBlockCode[i] = thisBlockCode[i].replaceAll('\n', '\n' + indent);
}
if (addcell) {
// insert single cell using prev code
com_interface.insertCell('code', code.toString(), execute, block.sigText);
code = new com_String();
// insert cells using this block code list
com_interface.insertCells('code', thisBlockCode, execute, block.sigText);
}
} else {
// set indent to every line of thisblockcode
thisBlockCode = thisBlockCode.replaceAll('\n', '\n' + indent);
code.appendFormat('{0}{1}{2}', prevNewLine, indent, thisBlockCode);
}
});
if (addcell) {
com_interface.insertCell('code', code.toString(), execute, block.sigText);
}
return code.toString();
}
runAll() {
let that = this;
this.blockList.forEach(block => {
if (block.isGroup) {
that.runBlock(block);
}
})
}
getOverallCode() {
let overallCode = new com_String();
let that = this;
this.blockList.forEach((block) => {
if (block.isGroup) {
if (overallCode.toString() != '') {
overallCode.appendLine();
overallCode.appendLine();
}
let groupCode = that.runBlock(block, false, false);
if (block.id == 'apps_markdown') {
// if markdown, add #
groupCode = '#' + groupCode.replaceAll('\n', '\n# ');
}
overallCode.appendFormatLine('# Visual Python: {0} > {1}', block.name, block.name,
block.id == 'apps_markdown'? ' - Markdown':'');
overallCode.append(groupCode);
}
});
return overallCode.toString();
}
viewCode() {
let overallCode = this.getOverallCode();
let codeview = new CodeView({
codeview: overallCode,
config: {
id: 'boardCodeview',
name: 'Overall Codeview',
path: ''
}
});
codeview.open();
}
exportCode() {
let that = this;
// save .py file
let fileNavi = new FileNavigation({
type: 'save',
fileName: this.tmpState.boardTitle,
extensions: ['py'],
finish: function(filesPath, status, error) {
let fileName = filesPath[0].file;
let filePath = filesPath[0].path;
// save py file
let overallCode = that.getOverallCode();
vpKernel.saveFile(fileName, filePath, overallCode);
}
});
fileNavi.open();
}
/**
* Deprecated on v2.0.2.
*/
// viewDepthInfo() {
// this.state.viewDepthNumber = !this.state.viewDepthNumber;
// if (this.state.viewDepthNumber) {
// $(this.wrapSelector('.vp-board-header-button-inner li[data-menu="view-depth"]')).text('Hide Depth Number');
// } else {
// $(this.wrapSelector('.vp-board-header-button-inner li[data-menu="view-depth"]')).text('View Depth Number');
// }
// // reloadBlockList
// this.reloadBlockList();
// }
clearBoardWithChecking() {
// alert before closing
let that = this;
if (this.checkNote()) {
// render update modal
com_util.renderModal({
title: 'Unsaved changes',
message: 'Do you want to save?',
buttons: ['Cancel', "No", 'Save'],
defaultButtonIdx: 0,
buttonClass: ['cancel', '', 'activated'],
finish: function(clickedBtnIdx) {
switch (clickedBtnIdx) {
case 0:
// cancel - do nothing
return;
case 1:
// don't save
that.clearBoard();
break;
case 2:
// save
that.saveAsNote(function() {
that.clearBoard();
});
break;
}
}
});
return;
}
this.clearBoard();
}
clearBoard() {
// clear board
this.blockList.forEach(block => {
block.popup.remove();
})
this.blockList = [];
// render block list
this.reloadBlockList();
}
/**
* Deprecated on v2.0.2.
*/
// closeBoard() {
// this.createNewNote();
// }
//========================================================================
// Block control
//========================================================================
createBlock(component, state) {
let createdBlock = new Block(this, state);
component.setTaskItem(createdBlock);
return createdBlock;
}
addBlock(option, position=-1, blockState={}) {
let block = new Block(this, { task: option, ...blockState });
option.setTaskItem(block);
if (position < 0) {
// add to the end
// this.blockList.push(block);
this.addToBlockList(block);
position = this.blockList.length;
} else {
// add to specific position
// this.blockList.splice(position, 0, block);
this.addToBlockList(block, position);
}
return block;
}
removeBlock(blockToRemove) {
let that = this;
// if sub block, change group block's state
let groupBlock = blockToRemove.getGroupBlock();
if (blockToRemove.id === 'lgCtrl_else') {
groupBlock.state.elseFlag = false;
}
if (blockToRemove.id === 'lgCtrl_finally') {
groupBlock.state.finallyFlag = false;
}
// remove grouped blocks (under this depth)
let groupedBlocks = blockToRemove.getGroupedBlocks();
groupedBlocks.forEach(block => {
// remove block
if (blockToRemove.isGroup || blockToRemove.equals(block) || block.depth > blockToRemove.depth) {
// const blockIdx = that.blockList.indexOf(block);
block.popup.remove();
// that.blockList.splice(blockIdx, 1);
that.removeFromBlockList(block);
}
});
// render block list
this.reloadBlockList();
}
/**
* Change position of task in blockPopupList
* @param {int} startIdx
* @param {int} endIdx
*/
moveBlock(startIdx, endIdx, parentBlock=null) {
let sessionId = 'default';
// LAB: get session id
if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
if (!(sessionId in this._blockList)) {
this._blockList[sessionId] = {
title: '',
blockList: []
}
}
}
}
var blockList = this._blockList[sessionId].blockList;
if (blockList) {
var movingBlock = blockList[startIdx];
if (movingBlock) {
let groupBlocks = this.getGroupedBlocks(movingBlock);
this._blockList[sessionId].blockList.splice(startIdx, groupBlocks.length);
this._blockList[sessionId].blockList.splice(endIdx, 0, ...groupBlocks);
// move tag
if (parentBlock != null) {
// set this movingBlock as child of parentBlock
movingBlock.setChildBlock(parentBlock.getChildDepth());
} else {
// set group block
movingBlock.setGroupBlock();