-
Notifications
You must be signed in to change notification settings - Fork 2
/
editor.js
2204 lines (1827 loc) · 81.1 KB
/
editor.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
/*
* Copyright (c) 2019 Parallax Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the “Software”), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** GLOBAL VARIABLES **/
/**
*
* @type {*|jQuery}
*/
var baseUrl = $('meta[name=base]').attr("content");
/*
* TODO: This is used in the blocklypropclient.js file, but that file is loaded
* first, so when JS is condensed, make sure this global is decalred at the top
* of the file
*/
/**
*
* @type {*|jQuery}
*/
var cdnUrl = $('meta[name=cdn]').attr("content");
/**
*
* @type {boolean}
*/
var user_authenticated = ($("meta[name=user-auth]").attr("content") === 'true') ? true : false;
/**
*
* @type {boolean}
*/
var isOffline = ($("meta[name=isOffline]").attr("content") === 'true') ? true : false;
/**
* Constant string that represents the base, empty project header
*
* @type {string}
*
* @description Converting the string to a constant because it is referenced
* in a number of places. The string is sufficiently complex that it could
* be misspelled without detection.
*/
const EmptyProjectCodeHeader = '<xml xmlns="http://www.w3.org/1999/xhtml">';
/**
* Force the saveCheck() function to exit immediately with a false result
*
* TODO: This flag is used in exactly one place. Why do we need it?
*
* @type {boolean}
*/
var ignoreSaveCheck = false;
/**
*
* @type {number}
*/
var last_saved_timestamp = 0;
/**
* Timestamp to record when the current project was last saved to
* storage
*
* @type {number}
*/
var last_saved_time = 0;
/**
* The primary key for the project (online version)
*
* @type {number}
*/
var idProject = 0;
/**
* Uploaded project XML code
*
* @type {string}
*/
var uploadedXML = '';
/** WIP/TODO: generate svg icons and inject them. This keeps the HTML simple and clean.
*
* @type {object}
*/
bpIcons = {
warningCircle: '<svg width="15" height="15"><path d="M7,8 L8,8 8,11 8,11 7,11 Z" style="stroke-width:1px;stroke:#8a6d3b;fill:none;"/><circle cx="7.5" cy="7.5" r="6" style="stroke-width:1.3px;stroke:#8a6d3b;fill:none;"/><circle cx="7.5" cy="5" r="1.25" style="stroke-width:0;fill:#8a6d3b;"/></svg>',
dangerTriangleBlack: '<svg width="15" height="15"><path d="M1,12 L2,13 13,13 14,12 8,2 7,2 1,12 Z M7.25,6 L7.75,6 7.5,9 Z" style="stroke-width:1.5px;stroke:#000;fill:none;"/><circle cx="7.5" cy="10.75" r="1" style="stroke-width:0;fill:#000;"/><circle cx="7.5" cy="5.5" r="1" style="stroke-width:0;fill:#000;"/></svg>',
dangerTriangle: '<svg width="15" height="15"><path d="M1,12 L2,13 13,13 14,12 8,2 7,2 1,12 Z M7.25,6 L7.75,6 7.5,9 Z" style="stroke-width:1.5px;stroke:#a94442;fill:none;"/><circle cx="7.5" cy="10.75" r="1" style="stroke-width:0;fill:#a94442;"/><circle cx="7.5" cy="5.5" r="1" style="stroke-width:0;fill:#a94442;"/></svg>',
checkMarkWhite: '<svg width="14" height="15"><path d="M2.25,6 L5.5,9.25 12,2.5 13.5,4 5.5,12 1,7.5 Z" style="stroke:#fff;stroke-width:1;fill:#fff;"/></svg>',
checkMarkGreen: '<svg width="14" height="15"><path d="M2.25,6 L5.5,9.25 12,2.5 13.5,4 5.5,12 1,7.5 Z" style="stroke:#3c763d;stroke-width:1;fill:#3c763d;"/></svg>',
downArrowWhite: '<svg width="14" height="15"><path d="M5.5,0 L8.5,0 8.5,9 12.5,9 7,14.5 1.5,9 5.5,9 Z" style="stroke:#fff;stroke-width:1;fill:#fff;"/></svg>',
downArrowBoxWhite: '<svg width="14" height="15"><path d="M5.5,0 L8.5,0 8.5,6 12.5,6 7,11.5 1.5,6 5.5,6 Z M0.5,12 L13.5,12 13.5,14.5 0.5,14.5 Z" style="stroke:#fff;stroke-width:1;fill:#fff;"/></svg>',
terminalWhite: '<svg width="14" height="15"><path d="M3,4.5 L10,4.5 M3,6.5 L6,6.5 M3,8.5 L8,8.5 M1,1 L13,1 13,14 1,14 1,1 M2,0 L12,0 M14,2 L14,13 M12,15 L2,15 M0,2 L0,13" style="stroke:#fff;stroke-width:1;fill:none;"/></svg>',
graphWhite: '<svg width="13" height="14"><path d="M.5,0 L.5,13.5 L12.5,13.5 M3.5,0 L3.5,13.5 M6.5,0 L6.5,13.5 M9.5,0 L9.5,13.5 M12.5,0 L12.5,13.5 M.5,3.5 L12.5,3.5 M.5,7 L12.5,7 M.5,10.5 L12.5,10.5 M.5,.5 L12.5,.5" style="stroke:rgba(255,255,255,.6);stroke-width:1;fill:none;"/><path d="M0,13 L6,5 L9,8 L14,2" style="stroke:#fff;stroke-width:2;fill:none;"/></svg>',
searchWhite: '<svg width="14" height="15"><path d="M1.5,13.25 L4.5,8.75" style="stroke:#fff;stroke-width:2px;fill:none;"/><circle cx="7" cy="5" r="3.5" style="stroke:#fff;stroke-width:1.5px;fill:none;"></circle></svg>',
magicWandWhite: '<svg width="14" height="15"><path d="M1,10 L5,10 5,11 1,11 Z M2,12 L6,12 6,13 2,13 Z M1,14 5,14 5,15 1,15 Z M0.5,2.75 L2.5,0.6 5.5,3.5 3.5,5.5 Z M5,7 L7,4.75 14,12 12,14 Z M0,7 Q1.5,6.5 2,5 Q2.5,6.5 4,7 Q2.5,7.5 2,9 Q1.5,7.5 0,7 Z M7,3 Q9.5,2.5 10,0 Q10.5,2.5 13,3 Q10.5,3.5 10,6 Q9.5,3.5 7,3 Z" style="stroke-width:0;fill:#fff;"/></svg>',
undoWhite: '<svg width="15" height="15"><path d="M3.5,6.5 L2.25,4.5 0.75,10.25 6,10.5 5,8.5 Q8.5,5.5 12,7 Q8,3.5 3.5,6.5 Z M11,11 L14.5,11 Q12.5,6 7,8.25 Q11,8 11,11 Z" style="stroke-width:0;fill:#fff;"/></svg>',
redoWhite: '<svg width="15" height="15"><path d="M11.5,6.5 L12.75,4.5 14.25,10.25 9,10.5 10,8.5 Q6.5,5.5 3,7 Q7,3.5 11.5,6.5 Z M4,11 L0.5,11 Q2.5,6 8,8.25 Q4,8 4,11 Z" style="stroke-width:0;fill:#fff;"/></svg>',
eyeBlack: '<svg width="14" height="15" style="vertical-align: middle;"><path d="M0.5,7 C4,1.5 10,1.5 13.5,7 C10,12.5 4,12.5 0.5,7 M0.5,7 C4,3.5 10,3.5 13.5,7" style="stroke:#000;stroke-width:1.5;fill:none;"/><circle cx="7" cy="6.5" r="2.75" style="stroke:#000;stroke-width:1.5;fill:none;"></circle><circle cx="7" cy="6.5" r=".5" style="stroke:#000;stroke-width:1.5;fill:#000;"></circle></svg>',
eyeWhite: '<svg width="14" height="15" style="vertical-align: middle;"><path d="M0.5,7 C4,1.5 10,1.5 13.5,7 C10,12.5 4,12.5 0.5,7 M0.5,7 C4,3.5 10,3.5 13.5,7" style="stroke:#fff;stroke-width:1.5;fill:none;"/><circle cx="7" cy="6.5" r="2.75" style="stroke:#fff;stroke-width:1.5;fill:none;"></circle><circle cx="7" cy="6.5" r=".5" style="stroke:#fff;stroke-width:1.5;fill:#fff;"></circle></svg>',
playWhite: '<svg width="14" height="15"><path d="M4,3 L4,11 10,7 Z" style="stroke:#fff;stroke-width:1;fill:#fff;"/></svg>',
pauseWhite: '<svg width="14" height="15"><path d="M5.5,2 L4,2 4,11 5.5,11 Z M8.5,2 L10,2 10,11 8.5,11 Z" style="stroke:#fff;stroke-width:1;fill:#fff;"/></svg>',
fileWhite: '<svg width="14" height="15"><path d="M2,.5 L2,13.5 12,13.5 12,7.5 5.5,7.5 5.5,.5 Z M 8,1.5 L8,5 11,5 Z" style="stroke:#fff;stroke-width:1;fill:#fff;" fill-rule="evenodd"/></svg>',
eraserWhite: '<svg width="15" height="15"><path d="M2,12 A1.5,1.5 0 0 1 2,10 L10,2 14.5,6.5 7,14 M10,11 L5.5,6.5 M15,14 L4,14 2,12 M15,13.2 5,13.2" style="stroke:#fff;stroke-width:1;fill:none;"/><path d="M2,12 A1.5,1.5 0 0 1 2,10 L5.5,6.5 10,11 7,14 4,14 Z" style="stroke-width:0;fill:#fff;"/></svg>',
cameraWhite: '<svg width="14" height="15"><path d="M1.5,13.5 L.5,12.5 .5,5.5 1.5,4.5 2.5,4.5 4,3 7,3 8.5,4.5 12.5,4.5 13.5,5.5 13.5,12.5 12.5,13.5 Z M 2,9 A 4,4,0,0,0,10,9 A 4,4,0,0,0,2,9 Z M 4.5,9 A 1.5,1.5,0,0,0,7.5,9 A 1.5,1.5,0,0,0,4.5,9 Z M 10.5,6.5 A 1,1,0,0,0,13.5,6.5 A 1,1,0,0,0,10.5,6.5 Z" style="stroke:#fff;stroke-width:1;fill:#fff;" fill-rule="evenodd"/></svg>',
}
/**
* The name used to store a project that is being loaded from
* offline storage.
*
* temp... is used to persist the imported SVG file. This file is a
* candidate until the user selects the 'Open' button to confirm that
* this file is the one to be loaded into the app.
*
* local... is used as the project that will either replace the
* current project or be appended to the current project.
*
* @type {string}
*/
const tempProjectStoreName = "tempProject";
const localProjectStoreName = 'localProject';
/**
* This is the object returned from the call to Blockly.inject()
*/
var blocklyWorkSpace;
/**
* Project class implementation
class Project {
id = 0;
user = '';
name = '';
yours = true;
description = '';
htmlDescription = '';
boardType = '';
code = '';
private = true;
shared = false;
createDate = null;
lastUpdated = null;
constructor() {
}
getCreated() {
return this.createDate;
}
setCreated(value) {
this.createDate = value;
}
getTimestamp() {
return this.lastUpdated;
}
setTimestamp(value) {
this.lastUpdated = value;
}
}
*/
// TODO: set up a markdown editor (removed because it doesn't work in a Bootstrap modal...)
/**
* Ping the Rest API every 60 seconds
*
* @type {number}
*/
const pingInterval = setInterval(() => {
$.get(baseUrl + 'ping');
},
60000
);
/**
*
* @param delayMinutes
* @param resetTimer
*/
const timestampSaveTime = (delayMinutes, resetTimer) => {
const timeNow = getTimestamp();
// If the proposed delay is less than the delay that's already in
// process, don't update the delay to a new shorter time.
if (timeNow + (delayMinutes * 60000) > last_saved_timestamp) {
last_saved_timestamp = timeNow + (delayMinutes * 60000);
if (resetTimer) {
last_saved_time = timeNow;
}
}
};
// TODO: We have to have a better way to manage the timer than using
// an HTML tag.
/**
* Checks a time value embedded within a <span> element to determine
* if it is time to prompt the user to save their project code.
*
* The <span> tag is introduced as part of a message, located in the
* _messages.js file, page_text_label['editor_save-check_warning'].
*/
const checkLastSavedTime = function () {
const t_now = getTimestamp();
const s_save = Math.round((t_now - last_saved_time) / 60000);
// Write the timestamp to the DOM
// $('#save-check-warning-time').html(s_save.toString(10));
//if (s_save > 58) {
// TODO: It's been to long - autosave, then close/set URL back to login page.
//}
if (t_now > last_saved_timestamp && checkLeave() && user_authenticated) {
// It's time to pop up a modal to remind the user to save.
ShowProjectTimerModalDialog();
}
};
/**
* Execute this code as soon as the DOM becomes ready.
*/
$(document).ready( () => {
/* -- Set up amy event handlers once the DOM is ready -- */
// Update the blockly workspace to ensure that it takes
// the remainder of the window. This is an async call.
$(window).on('resize', function () {
resetToolBoxSizing()
});
// Event handler for the OnBeforeUnload event
// --------------------------------------------------------------
// This event fires just before the document begins to unload.
// The unload can be stopped by returning a string message. The
// browser will then open a modal dialog the presents the
// message and options for Cancel and Leave. If the Cancel option
// is selected the unload event is cancelled and page processing
// continues.
// --------------------------------------------------------------
window.addEventListener('beforeunload', function (e) {
if (isOffline) {
// Call checkLeave only if we are NOT loading a new project
if (getURLParameter('openFile') === "true") {
return;
}
// ------------------------------------------------------
// This code attempts to save the current workspace into
// the localStorage.
// ------------------------------------------------------
// Store the current project into the localStore so that
// if the page is being refreshed, it will automatically
// be reloaded
// ------------------------------------------------------
if (projectData) {
if (projectData['name'] !== "undefined") {
let tempProject = {};
Object.assign(tempProject, projectData);
tempProject.code = getXml();
tempProject.timestamp = getTimestamp();
window.localStorage.setItem(localProjectStoreName, JSON.stringify(tempProject));
}
}
}
if (checkLeave()) {
e.preventDefault(); // Cancel the event
e.returnValue = Blockly.Msg.DIALOG_CHANGED_SINCE;
return Blockly.Msg.DIALOG_CHANGED_SINCE;
}
});
initInternationalText();
initEditorIcons();
initEventHandlers();
initUploadModalLabels();
disableUploadDialogButtons();
// Reset the upload/import modal to its default state when closed
$('#upload-dialog').on('hidden.bs.modal', resetUploadImportModalDialog());
// Set up login/guest user UI elements
initLoginUiElement();
$('.url-prefix').attr('href', function (idx, cur) {
return baseUrl + cur;
});
initCdnImageUrls();
initClientDownloadLinks();
idProject = getURLParameter('project');
//Decode and parse project data coming from a sharelink
if (window.location.href.indexOf('projectlink') > -1) {
// Decode the base-64 encoded project link
let projectRaw = atob($("meta[name=projectlink]").attr("content"));
if (projectRaw.length > 0) {
setupWorkspace(JSON.parse(projectRaw));
}
} else if (!idProject && !isOffline) {
// redirect to the home page if the project id was not specified
// and the code is running in the online mode
window.location = baseUrl;
} else if (isOffline) {
// TODO: Use the ping endpoint to verify that we are offline.
// Stop pinging the Rest API
clearInterval(pingInterval);
// hide save interaction elements
$('.online-only').addClass('hidden');
$('.offline-only').removeClass('hidden');
// SetupSaveAsModalDialog();
// populate the board type drop down list
// TODO: Make this a function
// see PopulateProjectBoardTypesUIElement()
// Load a project file from local storage
if (getURLParameter('openFile') === "true") {
console.log("Calling OpenProjectFileDialog() from document.ready()");
OpenProjectFileDialog();
}
else if (getURLParameter('newProject') === "true") {
NewProjectModal();
}
// Load a project from localStorage if available
else if (window.localStorage.getItem(localProjectStoreName)) {
try {
// Get a copy of the last know state of the current project
let localProject = JSON.parse(window.localStorage.getItem(localProjectStoreName));
// **************************************************
// This should clear out the existing blockly project
// and reset Blockly core for a new project. That
// not appear to be happening.
// **************************************************
setupWorkspace( localProject,
function () {
console.log('Removing the localProject from browser localStorage');
window.localStorage.removeItem(localProjectStoreName);
});
}
catch (objError) {
if (objError instanceof SyntaxError) {
console.error(objError.name);
alert(objError.message);
} else {
console.error(objError.message);
}
// No viable project available, so redirect to index page.
window.location.href = (isOffline) ? 'index.html' : baseUrl;
}
}
else {
// No viable project available, so redirect to index page.
window.location.href = (isOffline) ? 'index.html' : baseUrl;
}
} // End of offline mode
else {
// We need to test for the case where we are creating a new local project
// and the project detail are being passed in the Request body
// TODO: Create a new project from details passed in from the new-project page
// ----------------------------------------------------------------------------
$.get(baseUrl + 'rest/shared/project/editor/' + idProject,
function(data) {
setupWorkspace(data)
})
.fail(function () {
// Failed to load project - this probably means that it belongs to another user and is not shared.
utils.showMessage('Unable to Access Project', 'The BlocklyProp Editor was unable to access the project you requested. If you are sure the project exists, you may need to contact the project\'s owner and ask them to share their project before you will be able to view it.', function () {
window.location = baseUrl;
});
});
}
// Make sure the toolbox appears correctly, just for good measure.
resetToolBoxSizing(250);
});
/**
* Get the current time stamp
*
* @returns {number} Number of seconds since 1/1/1970
*/
function getTimestamp() {
const date = new Date();
return date.getTime();
}
/**
*
*/
function initUploadModalLabels() {
// set the upload modal's title to "import" if offline
if (isOffline) {
$('#upload-dialog-title').html(page_text_label['editor_import']);
$('#upload-project span').html(page_text_label['editor_import']);
// Hide the save-as button.
$('#save-project-as, save-as-btn').addClass('hidden');
}
}
/**
* Check project state to see if it has changed before leaving the page
*
* @returns {boolean}
* Return true if the project has been changed but has not been
* persisted to storage.
*
* @description
* The function assumes that the projectData global variable holds
* the original copy of the project, prior to any user modification.
* The code then compares the code in the Blockly core against the
* original version of the project to determine if any changes have
* occurred.
*
* This only examines the project data. This code should also check
* the project name and descriptions for changes.
*/
function checkLeave () {
// Return if there is no project data
if (! projectData || projectData.length === 0) {
return false;
}
let currentXml = getXml();
let savedXml = projectData['code'];
return ! (savedXml === currentXml);
};
/**
* Verify that the project name and board type form fields have data
*
* @returns {boolean} True if form contains valid data, otherwise false
*/
function validateNewProjectForm() {
// This function should only be used in offline mode
if (!isOffline) {
return true;
}
// Select the 'proj' class
let project = $(".proj");
// Validate the jQuery object based on these rules. Supply helpful
// error messages to use when a rule is violated
project.validate({
rules: {
'new-project-name': "required",
'new-project-board-type': "required"
},
messages: {
'new-project-name': "Please enter a project name",
'new-project-board-type': "Please select a board type"
}
});
return !!project.valid();
}
/**
* Insert the text strings (internationalization) for all of the UI
* elements on the editor page once the page has been loaded.
*/
function initInternationalText() {
// Locate each HTML element of class 'keyed-lang-string'
$(".keyed-lang-string").each(function () {
// Set a reference to the current selected element
let span_tag = $(this);
// Get the associated key value that will be used to locate
// the text string in the page_text_label array. This array
// is declared in _messages.js
let pageLabel = span_tag.attr('data-key');
// If there is a key value
if (pageLabel) {
if (span_tag.is('a')) {
// if the html element is an anchor, add a link
span_tag.attr('href', page_text_label[pageLabel]);
} else if (span_tag.is('input')) {
// if the html element is a form input, set the
// default value for the element
span_tag.attr('value', page_text_label[pageLabel]);
} else {
// otherwise, assume that we're inserting html
span_tag.html(page_text_label[pageLabel]);
}
}
});
// insert text strings (internationalization) into button/link tooltips
for (let i = 0; i < tooltip_text.length; i++) {
if (tooltip_text[i] && document.getElementById(tooltip_text[i][0])) {
$('#' + tooltip_text[i][0]).attr('title', tooltip_text[i][1]);
}
}
}
/**
* Initialize the tool bar icons
*/
function initEditorIcons() {
// Locate each element that has a class 'bpIcon' assigned and
// contains a 'data-icon' attribute. Itereate through each
// match and draw the custom icons into the specified element
// --------------------------------------------------------------
// TODO: not sure why, but the ES6 shorthand function notation
// breaks this...
// ... because the arrow function does not set the 'this'
// value whereas an anonymous function does.
// --------------------------------------------------------------
$('.bpIcon[data-icon]').each(function () {
$(this).html(bpIcons[$(this).attr('data-icon')]);
});
}
/**
* Configure all of the event handlers
*/
function initEventHandlers() {
/*
* TODO: Move javascript that is inline in the HTML files to included scripts.
* This keeps the HTML simple and clean.
*
* This is a WIP.
*/
// Set up event handlers - Attach events to nav/action menus/buttons
$('#prop-btn-comp').on('click', function () { compile(); });
$('#prop-btn-ram').on('click', function () { loadInto('Load into RAM', 'bin', 'CODE', 'RAM'); });
$('#prop-btn-eeprom').on('click', function () { loadInto('Load into EEPROM', 'eeprom', 'CODE', 'EEPROM'); });
$('#prop-btn-term').on('click', function () { serial_console(); });
$('#prop-btn-graph').on('click', function () { graphing_console(); });
$('#prop-btn-find-replace').on('click', function () { findReplaceCode(); });
$('#prop-btn-pretty').on('click', function () { formatWizard(); });
$('#prop-btn-undo').on('click', function () { codePropC.undo(); });
$('#prop-btn-redo').on('click', function () { codePropC.redo(); });
$('#btn-view-propc').on('click', function () { renderContent('tab_propc'); });
$('#btn-view-blocks').on('click', function () { renderContent('tab_blocks'); });
$('#btn-view-xml').on('click', function () { renderContent('tab_xml'); });
$('#download-side').on('click', function () { downloadPropC(); });
$('#term-graph-setup').on('click', function () { configure_term_graph(); });
$('#client-setup').on('click', function () { configure_client(); });
$('#propc-find-btn').on('click', function () {
codePropC.find(document.getElementById('propc-find').value, {}, true);
});
$('#propc-replace-btn').on('click', function () {
codePropC.replace(document.getElementById(
'propc-replace').value,
{needle: document.getElementById('propc-find').value},
true);
});
$('#find-replace-close').on('click', function () { findReplaceCode(); });
$('#upload-close').on('click', function () { clearUploadInfo(false); });
// Hamburger menu items
// $('#selectfile-replace').on('click', function () { uploadMergeCode(false); });
// $('#selectfile-append').on('click', function () { uploadMergeCode(true); });
$('#edit-project-details').on('click', function () { editProjectDetails(); });
$('#selectfile-clear').on('click', function () { clearUploadInfo(true); });
$('#save-as-btn').on('click', function () { saveAsDialog(); });
// Save Project modal 'Save' button click handler
$('#save-btn, #save-project').on('click', function () {
if (isOffline) {
downloadCode();
} else {
saveProject();
}
});
// Load a new project menu click handler
// window.location = 'blocklyc.html?newProject=true' });
$('#new-project-menu-item').on('click', () => { NewProjectModal(); });
$('#btn-graph-play').on('click', function () { graph_play(); });
$('#btn-graph-snapshot').on('click', function () { downloadGraph(); });
$('#btn-graph-csv').on('click', function () { downloadCSV(); });
$('#btn-graph-clear').on('click', function () { graphStartStop('clear'); });
$('#save-as-board-type').on('change', function () {
checkBoardType( $('#saveAsDialogSender').html());
});
$('#save-as-board-btn').on('click', function () { saveProjectAs(); });
$('#win1-btn').on('click', function () { showStep('win', 1, 3); });
$('#win2-btn').on('click', function () { showStep('win', 2, 3); });
$('#win3-btn').on('click', function () { showStep('win', 3, 3); });
$('#chr1-btn').on('click', function () { showStep('chr', 1, 3); });
$('#chr2-btn').on('click', function () { showStep('chr', 2, 3); });
$('#chr3-btn').on('click', function () { showStep('chr', 3, 3); });
$('#mac1-btn').on('click', function () { showStep('mac', 1, 4); });
$('#mac2-btn').on('click', function () { showStep('mac', 2, 4); });
$('#mac3-btn').on('click', function () { showStep('mac', 3, 4); });
$('#mac4-btn').on('click', function () { showStep('mac', 4, 4); });
$('.show-os-win').on('click', function () { showOS('Windows'); });
$('.show-os-mac').on('click', function () { showOS('MacOS'); });
$('.show-os-chr').on('click', function () { showOS('ChromeOS'); });
$('.show-os-lnx').on('click', function () { showOS('Linux'); });
// Save-As Project
$('#save-project-as').on('click', function () { saveAsDialog(); });
// download to disk
$('#download-project').on('click', function () { downloadCode(); });
// upload from disk
$('#upload-project').on('click', function () { uploadCode(); });
// --------------------------------------------------------------
// Bootstrap modal event handler for the Save Project Timer
// dialog. The hidden.bs.model event occurs when the modal is
// fully hidden (after CSS transitions have completed)
// --------------------------------------------------------------
$('#save-check-dialog').on('hidden.bs.modal',
function () {
timestampSaveTime(5, false);
});
// Hide these elements of the Open Project File modal when it
// receives focus
$("#selectfile").focus(function () {
$('#selectfile-verify-notvalid').css('display', 'none');
$('#selectfile-verify-valid').css('display', 'none');
$('#selectfile-verify-boardtype').css('display', 'none');
});
}
/**
* disable to upload dialog buttons until a valid file is uploaded
*/
function disableUploadDialogButtons() {
document.getElementById("selectfile-replace").disabled = true;
document.getElementById("selectfile-append").disabled = true;
}
/**
* Reset the upload/import modal window to defaults after use
*/
function resetUploadImportModalDialog() {
// reset the title of the modal
if (isOffline) {
$('upload-dialog-title').html(page_text_label['editor_import']);
} else {
$('upload-dialog-title').html(page_text_label['editor_upload']);
}
// hide "append" button
$('#selectfile-append').removeClass('hidden');
// change color of the "replace" button to blue and change text to "Open"
$('#selectfile-replace').removeClass('btn-primary').addClass('btn-danger').html(page_text_label['editor_button_replace']);
// reset the blockly toolbox sizing to ensure it renders correctly:
resetToolBoxSizing(100);
}
/**
* Set the BlocklyProp Client download links
*
* Set the href for each of the client links to point to the correct files
* available on the downloads.parallax.com S3 site. The URL is stored in a
* HTML meta tag.
*/
function initClientDownloadLinks() {
// Windows 32-bit
$('.client-win32-link').attr('href', $("meta[name=win32client]").attr("content"));
$('.client-win32zip-link').attr('href', $("meta[name=win32zipclient]").attr("content"));
// Windows 64-bit
$('.client-win64-link').attr('href', $("meta[name=win64client]").attr("content"));
$('.client-win64zip-link').attr('href', $("meta[name=win64zipclient]").attr("content"));
// MacOS
$('.client-mac-link').attr('href', $("meta[name=macOSclient]").attr("content"));
}
/**
* Set the URLs for all of the CDN-sourced images
*/
function initCdnImageUrls() {
$("img").each(function () {
let img_tag = $(this);
// Set the source of the image
let img_source = img_tag.attr('data-src');
if (img_source) {
img_tag.attr('src', cdnUrl + img_source);
}
});
}
/**
* Initialize the UI elements that display the users logged-in state
* in the production BlocklyProp system. These elements do not exist
* in the BlocklyProp Solo or BlocklyProp Local systems.
*/
function initLoginUiElement() {
// Offline has no concept of authentication
if (! isOffline) {
if (user_authenticated) {
$('.auth-true').css('display', $(this).attr('data-displayas'));
$('.auth-false').css('display', 'none');
} else {
$('.auth-false').css('display', $(this).attr('data-displayas'));
$('.auth-true').css('display', 'none');
}
}
}
/**
* Display the Timed Save Project modal dialog
*
*/
function ShowProjectTimerModalDialog() {
$('#save-check-dialog').modal({keyboard: false, backdrop: 'static'});
}
/**
* Reset the sizing of blockly's toolbox and canvas.
*
* NOTE: This is a workaround to ensure that it renders correctly
* TODO: Find a permanent replacement for this workaround.
*
* @param resizeDelay milliseconds to delay the resizing, especially
* if used after a change in the window's location or a during page
* reload.
*/
function resetToolBoxSizing(resizeDelay) {
// Vanilla Javascript is used here for speed - jQuery
// could probably be used, but this is faster. Force
// the toolbox to render correctly
setTimeout(() => {
// find the height of just the blockly workspace by
// subtracting the height of the navigation bar
let navTop = document.getElementById('editor').offsetHeight;
let navHeight = window.innerHeight - navTop;
let navWidth = window.innerWidth;
// Build an array of UI divs that display content
let blocklyDiv = [
document.getElementById('content_blocks'),
document.getElementById('content_propc'),
document.getElementById('content_xml')
];
// Set the size of the divs
for (let i = 0; i < 3; i++) {
blocklyDiv[i].style.left = '0px';
blocklyDiv[i].style.top = navTop + 'px';
blocklyDiv[i].style.width = navWidth + 'px';
blocklyDiv[i].style.height = navHeight + 'px';
}
// Update the Blockly editor canvas to use the new space
if (Blockly.mainWorkspace && blocklyDiv[0].style.display !== 'none') {
Blockly.svgResize(Blockly.mainWorkspace);
}
}, resizeDelay || 10); // 10 millisecond delay
}
/**
* Populate the projectData global
*
* @param data, callback
*
*/
function setupWorkspace(data, callback) {
ClearBlocklyWorkspace();
projectData = data;
// Update the UI with project related details
showInfo(data);
// Set the global project ID. in the offline mode, the project
// id is set to 0 when the project is loaded from local storage.
// --------------------------------------------------------------
if (!idProject) {
idProject = projectData['id'];
}
// Set various project settings based on the project board type
// NOTE: This function is in propc.js
setProfile(projectData['board']);
// Determine if this is a pure C project
if (projectData['board'] !== 'propcfile') {
initToolbox(projectData['board'], []);
// Reinstate key bindings from block workspace if this is not a code-only project.
if (Blockly.codeOnlyKeybind === true) {
Blockly.bindEvent_(document, 'keydown', null, Blockly.onKeyDown_);
Blockly.codeOnlyKeybind = false;
}
// Create UI block content from project details
renderContent('blocks');
// Set the help link to the ab-blocks or s3 reference
// TODO: modify blocklyc.html/jsp and use an id or class selector
if (projectData.board === 's3') {
$('#online-help').attr('href', 'https://learn.parallax.com/s3-blocks');
} else {
$('#online-help').attr('href', 'https://learn.parallax.com/ab-blocks');
}
} else {
// No, init the blockly interface
init(Blockly);
// Remove keybindings from block workspace if this is a code-only project.
Blockly.unbindEvent_(document, 'keydown', null, Blockly.onKeyDown_);
Blockly.codeOnlyKeybind = true;
// Show PropC editing UI elements
$('.propc-only').removeClass('hidden');
// Create UI block content from project details
renderContent('propc');
// Set the help link to the prop-c reference
// TODO: modify blocklyc.html/jsp and use an id or class selector
$('#online-help').attr('href', 'https://learn.parallax.com/support/C/propeller-c-reference');
}
// View or edit project details menu item
if (projectData && projectData['yours'] === false) {
$('#edit-project-details').html(page_text_label['editor_view-details'])
} else {
$('#edit-project-details').html(page_text_label['editor_edit-details']);
}
resetToolBoxSizing();
timestampSaveTime(20, true);
// Save project reminder timer. Check every 60 seconds
setInterval(checkLastSavedTime, 60000);
// Execute the callback function if one was provided
if (callback) {
callback();
}
}
/**
* Set the UI fields for the project name, project owner and project type icon
*
* @param data is the project data structure
*/
function showInfo(data) {
if (getURLParameter('debug')) {
console.log(data);
}
// Display the project name
$(".project-name").text(data['name']);
// Does the current user own the project?
if (!data['yours']) {
// If not, display owner username
$(".project-owner").text("(" + data['user'] + ")");
}
// Create an array of board type icons
let projectBoardIcon = {
"activity-board": "images/board-icons/IconActivityBoard.png",
"s3": "images/board-icons/IconS3.png",
"heb": "images/board-icons/IconBadge.png",
"heb-wx": "images/board-icons/IconBadgeWX.png",
"flip": "images/board-icons/IconFlip.png",
"other": "images/board-icons/IconOtherBoards.png",
"propcfile": "images/board-icons/IconC.png"
};
// Set the prject icon to the correct board type
$("#project-icon").html('<img src="' + cdnUrl + projectBoardIcon[ data['board'] ] + '"/>');
};
/**
*
*/
function saveProject() {
if (projectData['yours']) {
var code = getXml();
projectData['code'] = code;
$.post(baseUrl + 'rest/project/code', projectData, function (data) {
var previousOwner = projectData['yours'];
projectData = data;
projectData['code'] = code; // Save code in projectdata to be able to verify if code has changed upon leave
// If the current user doesn't own this project, a new one is created and the page is redirected to the new project.
if (!previousOwner) {
window.location.href = baseUrl + 'projecteditor?id=' + data['id'];
}
}).done(function () {
// Save was successful, show green with checkmark
var elem = document.getElementById('save-project');
elem.style.paddingLeft = '10px';