-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathutils.js
More file actions
1792 lines (1587 loc) · 53 KB
/
utils.js
File metadata and controls
1792 lines (1587 loc) · 53 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
// Copyright (c) 2014-21 Walter Bender
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
/*
globals
jQuery, PALETTEICONS, PALETTEFILLCOLORS, PALETTESTROKECOLORS,
PALETTEHIGHLIGHTCOLORS, HIGHLIGHTSTROKECOLORS, MULTIPALETTES,
platformColor
*/
/*
Global locations
- js/artwork.js
PALETTEICONS, PALETTEFILLCOLORS, PALETTESTROKECOLORS, PALETTEHIGHLIGHTCOLORS,
HIGHLIGHTSTROKECOLORS
- js/turtledefs.js
MULTIPALETTES
- js/utils/platformstyle.js
platformColor
*/
/* exported
canvasPixelRatio, changeImage, closeBlkWidgets, closeWidgets,
delayExecution, displayMsg, doBrowserCheck, docByClass, docByName,
docBySelector, docByTagName, doPublish, doStopVideoCam, doSVG,
doUseCamera, fileBasename, fileExt, format, getTextWidth, hex2rgb,
hexToRGB, hideDOMLabel, httpGet, httpPost, HttpRequest,
importMembers, isSVGEmpty, last, mixedNumber, nearestBeat,
oneHundredToFraction, prepareMacroExports, preparePluginExports,
processMacroData, processRawPluginData, rationalSum, rgbToHex,
safeSVG, toFixed2, toTitleCase, windowHeight, windowWidth,
fnBrowserDetect, waitForReadiness
*/
/**
* Changes the source of an image element from one SVG data URI to another.
* @function
* @param {HTMLImageElement} imgElement - The image element to update.
* @param {string} from - The base64-encoded SVG data URI to replace.
* @param {string} to - The new base64-encoded SVG data URI.
*/
const changeImage = (imgElement, from, to) => {
const oldSrc = "data:image/svg+xml;base64," + window.btoa(base64Encode(from));
const newSrc = "data:image/svg+xml;base64," + window.btoa(base64Encode(to));
if (imgElement.src === oldSrc) {
imgElement.src = newSrc;
}
};
/**
* Enhanced _() method to handle case variations for translations
* prioritize exact matches and preserve the case of the input text.
* @function
* @param {string} text - The input text to be translated.
* @returns {string} The translated text.
*/
function _(text, options = {}) {
if (!text) return "";
try {
const removeChars = [
",",
"(",
")",
"?",
"¿",
"<",
">",
".",
"\n",
'"',
":",
"%s",
"%d",
"/",
"'",
";",
"×",
"!",
"¡"
];
let cleanedText = text;
for (let char of removeChars) cleanedText = cleanedText.split(char).join("");
let translated = "";
const lang = i18next.language;
if (lang.startsWith("ja")) {
const kanaPref = localStorage.getItem("kanaPreference") || "kanji";
const script = kanaPref === "kana" ? "kana" : "kanji";
const resolveObj = key => {
let obj = i18next.t(key, { ...options, ns: undefined, returnObjects: true });
if (obj && typeof obj === "object") {
return obj[script] || key;
}
if (typeof obj === "string") {
return obj;
}
return key;
};
translated = resolveObj(text);
} else {
translated = i18next.t(text, options);
}
return translated || text;
} catch (e) {
return text;
}
}
/**
* A string formatting function using placeholder substitution.
* @function
* @param {string} str - The template string with placeholders.
* @param {Object} data - The data object containing values for substitution.
* @returns {string} The formatted string.
*/
let format = (str, data) => {
str = str.replace(/{([a-zA-Z0-9.]*)}/g, (match, name) => {
let x = data;
name.split(".").forEach(v => {
if (x === undefined) {
// eslint-disable-next-line no-console
console.debug("Undefined value in template string", str, name, x, v);
}
x = x[v];
});
return x === undefined ? "" : x;
});
return str.replace(/{_([a-zA-Z0-9]+)}/g, (match, item) => {
return _(item);
});
};
/**
* Detects the current browser name.
* @function
* @returns {string} The name of the detected browser.
*/
function fnBrowserDetect() {
const userAgent = navigator.userAgent;
let browserName;
if (userAgent.match(/chrome|chromium|crios/i)) {
browserName = "chrome";
} else if (userAgent.match(/firefox|fxios/i)) {
browserName = "firefox";
} else if (userAgent.match(/safari/i)) {
browserName = "safari";
} else if (userAgent.match(/opr\//i)) {
browserName = "opera";
} else if (userAgent.match(/edg/i)) {
browserName = "edge";
} else {
browserName = "No browser detection";
}
return browserName;
}
/**
* Returns the pixel ratio of the canvas for high-resolution displays.
* @function
* @returns {number} The canvas pixel ratio.
*/
function canvasPixelRatio() {
const devicePixelRatio = window.devicePixelRatio || 1;
const context = document.querySelector("#myCanvas").getContext("2d");
const backingStoreRatio =
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio ||
1;
return devicePixelRatio / backingStoreRatio;
}
/**
* Returns the height of the window, accounting for Android-specific behavior.
* @function
* @returns {number} The window height.
*/
function windowHeight() {
const onAndroid = /Android/i.test(navigator.userAgent);
if (onAndroid) {
return window.outerHeight;
} else {
return window.innerHeight;
}
}
/**
* Returns the width of the window, accounting for Android-specific behavior.
* @function
* @returns {number} The window width.
*/
function windowWidth() {
const onAndroid = /Android/i.test(navigator.userAgent);
if (onAndroid) {
return window.outerWidth;
} else {
return window.innerWidth;
}
}
/**
* Performs an HTTP GET request to retrieve data from the server.
* Uses async fetch to avoid blocking the UI during network requests.
* @param {string|null} projectName - The name of the project (or null for the base URL).
* @throws {Error} Throws an error if the HTTP status code is greater than 299.
* @returns {Promise<string>} A promise that resolves to the response text from the server.
*/
let httpGet = async projectName => {
const url = projectName === null ? window.server : window.server + projectName;
const response = await fetch(url, {
method: "GET",
headers: {
"x-api-key": "3tgTzMXbbw6xEKX7"
}
});
if (!response.ok) {
throw new Error("Error from server");
}
return response.text();
};
/**
* Performs an HTTP POST request to send data to the server.
* Uses async fetch to avoid blocking the UI during network requests.
* @param {string} projectName - The name of the project.
* @param {string} data - The data to be sent in the POST request.
* @returns {Promise<string>} A promise that resolves to the response text from the server.
*/
let httpPost = async (projectName, data) => {
const response = await fetch(window.server + projectName, {
method: "POST",
headers: {
"x-api-key": "3tgTzMXbbw6xEKX7"
},
body: data
});
if (!response.ok) {
throw new Error("Error from server");
}
return response.text();
};
/**
* Constructor function for making an HTTP request.
* @constructor
* @param {string} url - The URL to make the HTTP request to.
* @param {function} loadCallback - The callback function to handle the loaded response.
* @param {function} [userCallback] - An optional user-defined callback function.
*/
function HttpRequest(url, loadCallback, userCallback) {
// userCallback is an optional callback-handler.
const req = (this.request = new XMLHttpRequest());
this.handler = loadCallback;
this.url = url;
this.localmode = Boolean(self.location.href.search(/^file:/i) === 0);
this.userCallback = userCallback;
const objref = this;
try {
req.open("GET", url);
req.onreadystatechange = () => {
objref.handler();
};
req.send("");
} catch (e) {
if (self.console) {
// eslint-disable-next-line no-console
console.debug("Failed to load resource from " + url + ": Network error.");
// eslint-disable-next-line no-console
console.debug(e);
}
if (typeof userCallback === "function") {
userCallback(false, "network error");
}
this.request = this.handler = this.userCallback = null;
}
}
/**
* Checks the browser type and version.
* Sets properties in the jQuery.browser object based on the user agent.
* @function
*/
function doBrowserCheck() {
jQuery.uaMatch = ua => {
ua = ua.toLowerCase();
const match =
/(chrome)[ /]([\w.]+)/.exec(ua) ||
/(webkit)[ /]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ /]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
(ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua)) ||
[];
return {
browser: match[1] || "",
version: match[2] || "0"
};
};
const matched = jQuery.uaMatch(navigator.userAgent);
const browser = {};
if (matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
}
if (browser.chrome) {
browser.webkit = true;
} else if (browser.webkit) {
browser.safari = true;
}
jQuery.browser = browser;
}
/**
* Wait for critical dependencies to be ready before calling callback.
* Uses polling with exponential backoff and maximum timeout.
* This replaces the arbitrary 5-second delay for Firefox with actual readiness checks.
*
* @param {Function} callback - The function to call when ready
* @param {Object} options - Configuration options
* @param {number} options.maxWait - Maximum wait time in ms (default: 10000)
* @param {number} options.minWait - Minimum wait time in ms (default: 500)
* @param {number} options.checkInterval - Initial check interval in ms (default: 100)
*/
function waitForReadiness(callback, options = {}) {
const { maxWait = 10000, minWait = 500, checkInterval = 100 } = options;
const startTime = Date.now();
/**
* Check if critical dependencies and DOM elements are ready
* @returns {boolean} True if all critical dependencies are loaded
*/
const isReady = () => {
// Check if critical JavaScript libraries are loaded
const createjsLoaded = typeof createjs !== "undefined" && createjs.Stage;
const howlerLoaded = typeof Howler !== "undefined";
const jqueryLoaded = typeof jQuery !== "undefined";
// Check if critical DOM elements exist
const canvas = document.getElementById("myCanvas");
const loader = document.getElementById("loader");
const toolbars = document.getElementById("toolbars");
const domReady = canvas && loader && toolbars;
return createjsLoaded && howlerLoaded && jqueryLoaded && domReady;
};
/**
* Polling function that checks readiness and calls callback when ready
*/
const check = () => {
const elapsed = Date.now() - startTime;
if (elapsed >= minWait && isReady()) {
// Ready! Initialize the app
// eslint-disable-next-line no-console
console.log(`[Firefox] Initialized in ${elapsed}ms (readiness-based)`);
callback();
} else if (elapsed >= maxWait) {
// Timeout - initialize anyway as fallback
// eslint-disable-next-line no-console
console.warn(
`[Firefox] Initialization timed out after ${maxWait}ms, proceeding anyway`
);
callback();
} else {
// Not ready yet, check again on next animation frame
requestAnimationFrame(check);
}
};
// Start the readiness check loop
requestAnimationFrame(check);
}
// Check for Internet Explorer
window.onload = () => {
const userAgent = window.navigator.userAgent;
// For IE 10 or older
const MSIE = userAgent.indexOf("MSIE ");
let DetectVersionOfIE;
if (MSIE > 0) {
DetectVersionOfIE = parseInt(
userAgent.substring(MSIE + 5, userAgent.indexOf(".", MSIE)),
10
);
}
// For IE 11
const IETrident = userAgent.indexOf("Trident/");
if (IETrident > 0) {
const IERv = userAgent.indexOf("rv:");
DetectVersionOfIE = parseInt(
userAgent.substring(IERv + 3, userAgent.indexOf(".", IERv)),
10
);
}
// For IE 12
const IEEDGE = userAgent.indexOf("Edge/");
if (IEEDGE > 0) {
DetectVersionOfIE = parseInt(
userAgent.substring(IEEDGE + 5, userAgent.indexOf(".", IEEDGE)),
10
);
}
if (typeof DetectVersionOfIE != "undefined") {
document.body.innerHTML = "<div style='margin: 200px;'>";
document.body.innerHTML +=
"<h1 style='font-size: 100px; font-family: Arial; text-align: center; color: #F00;'>Music Blocks</h1>";
document.body.innerHTML +=
"<h3 style='font-size: 40px; font-family: Arial; text-align: center;'>Music Blocks will not work in Internet Explorer, you can use:</h3>";
document.body.innerHTML +=
"<div style='width: 550px; margin: 0 auto;'><a href='https://www.chromium.org/getting-involved/download-chromium' style='float: left; display: inherit; font-family: Arial; font-size: 30px; color: #0327F1; text-decoration: none;'>Chromium</a>";
document.body.innerHTML +=
"<a href='https://www.google.com/chrome/' style='float: left; margin-left: 40px;display: inherit; font-family: Arial; font-size: 30px; color: #0327F1; text-decoration: none;'>Chrome</a>";
document.body.innerHTML +=
"<a href='https://support.apple.com/downloads/safari' style='float: left; margin-left: 40px;display: inherit; font-family: Arial; font-size: 30px; color: #0327F1; text-decoration: none;'>Safari</a>";
document.body.innerHTML +=
"<a href='https://www.mozilla.org/en-US/firefox/new/' style='float: left; margin-left: 40px;display: inherit; font-family: Arial; font-size: 30px; color: #0327F1; text-decoration: none;'>Firefox</a>";
document.body.innerHTML += "</div></div>";
}
};
/**
* Retrieves a collection of elements by class name.
* @param {string} classname - The class name to search for.
* @returns {HTMLCollectionOf<Element>} A collection of elements with the specified class name.
*/
function docByClass(classname) {
return document.getElementsByClassName(classname);
}
/**
* Retrieves a collection of elements by tag name.
* @param {string} tag - The tag name to search for.
* @returns {NodeList} A collection of elements with the specified tag name.
*/
function docByTagName(tag) {
return document.getElementsByTagName(tag);
}
/**
* Retrieves an element by its ID.
* @param {string} id - The ID of the element to retrieve.
* @returns {HTMLElement|null} The element with the specified ID, or null if not found.
*/
function docById(id) {
return document.getElementById(id);
}
/**
* Retrieves a collection of elements by name.
* @param {string} name - The name attribute value to search for.
* @returns {NodeListOf<Element>} A collection of elements with the specified name attribute.
*/
function docByName(name) {
return document.getElementsByName(name);
}
/**
* Retrieves the first element that matches a specified CSS selector.
* @param {string} selector - A CSS selector string.
* @returns {Element|null} The first element that matches the selector, or null if not found.
*/
function docBySelector(selector) {
return document.querySelector(selector);
}
/**
* Returns the last element of an array.
* @param {Array} myList - The array from which to get the last element.
* @returns {*} The last element of the array, or null if the array is empty.
*/
let last = myList => {
const i = myList.length;
if (i === 0) {
return null;
} else {
return myList[i - 1];
}
};
/**
* Gets the width of a text string given a specific font.
* @param {string} text - The text string.
* @param {string} font - The font style and size.
* @returns {number} The width of the text in pixels.
*/
let getTextWidth = (text, font) => {
// re-use canvas object for better performance
const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
};
/**
* Generates an SVG string representing the canvas, logo, and turtles.
* @param {object} canvas - The canvas object.
* @param {object} logo - The logo object.
* @param {object} turtles - The turtles object.
* @param {number} width - The width of the SVG.
* @param {number} height - The height of the SVG.
* @param {number} scale - The scaling factor.
* @returns {string} The SVG string.
*/
function doSVG(canvas, logo, turtles, width, height, scale) {
// Aggregate SVG output from each turtle. If there is none, return an empty string.
let turtleSVG = "";
for (const turtle in turtles.turtleList) {
turtles.getTurtle(turtle).painter.closeSVG();
turtleSVG += turtles.getTurtle(turtle).painter.svgOutput;
}
let svg =
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="' +
width +
'" height="' +
height +
'">\n';
svg += '<g transform="scale(' + scale + "," + scale + ')">\n';
svg += logo.svgOutput;
if (turtleSVG === "") {
return "";
} else {
svg += turtleSVG;
}
svg += "</g>";
svg += "</svg>";
return svg;
}
/**
* Checks if the SVG output from turtles is empty.
* @param {object} turtles - The turtles object.
* @returns {boolean} True if all turtle SVG outputs are empty, false otherwise.
*/
let isSVGEmpty = turtles => {
for (const turtle in turtles.turtleList) {
turtles.getTurtle(turtle).painter.closeSVG();
if (turtles.getTurtle(turtle).painter.svgOutput !== "") {
return false;
}
}
return true;
};
/**
* Gets the file extension from a file path.
* @param {string} file - The file path or name.
* @returns {string} The file extension.
*/
let fileExt = file => {
if (file === null) {
return "";
}
const parts = file.split(".");
if (parts.length === 1 || (parts[0] === "" && parts.length === 2)) {
return "";
}
return parts.pop();
};
/**
* Gets the basename of a file path (excluding the extension).
* @param {string} file - The file path or name.
* @returns {string} The basename.
*/
let fileBasename = file => {
const parts = file.split(".");
if (parts.length === 1) {
return parts[0];
} else if (parts[0] === "" && parts.length === 2) {
return file;
} else {
parts.pop(); // throw away suffix
return parts.join(".");
}
};
/**
* Converts the first character of a string to uppercase.
* @param {string} str - The input string.
* @returns {string} The string with the first character in uppercase.
*/
function toTitleCase(str) {
if (typeof str !== "string") return;
if (str.length === 0) return "";
return str.charAt(0).toUpperCase() + str.slice(1);
}
if (typeof module !== "undefined" && module.exports) {
module.exports.toTitleCase = toTitleCase;
}
if (typeof window !== "undefined") {
window.toTitleCase = toTitleCase;
}
/**
* Processes plugin data and updates the activity based on the provided JSON-encoded dictionary.
* @param {object} activity - The activity object to update.
* @param {string} pluginData - The JSON-encoded plugin data.
* @returns {object|null} The processed plugin data object or null if parsing fails.
*/
const processPluginData = (activity, pluginData, pluginSource) => {
// Plugins are JSON-encoded dictionaries.
if (pluginData === undefined) {
return null;
}
const isTrustedPluginSource = src => {
if (!src) return false;
// allow only local paths
return (
src.startsWith("./") ||
src.startsWith("../") ||
src.startsWith("/") ||
(!src.includes("http://") && !src.includes("https://"))
);
};
const safeEval = (code, label = "plugin") => {
if (typeof code !== "string") return;
// basic sanity limit (prevents huge payloads)
if (code.length > 500000) {
// eslint-disable-next-line no-console
console.warn("Plugin code too large:", label);
return;
}
// NOTE: This eval is required for the Plugin system to load dynamic block definitions.
// The content comes from plugin JSON files which satisfy the isTrustedPluginSource check.
try {
// eslint-disable-next-line no-eval
eval(code);
} catch (e) {
// eslint-disable-next-line no-console
console.error("Plugin execution failed:", label, e);
}
};
if (!isTrustedPluginSource(pluginSource)) {
// eslint-disable-next-line no-console
console.warn("Blocked untrusted plugin source:", pluginSource);
return null;
}
let obj;
try {
obj = JSON.parse(pluginData);
} catch (error) {
console.error(`PluginProcessor: Failed to parse plugin data from source "${pluginSource}":`, error);
console.debug("Malformed plugin data:", pluginData);
return null;
}
// Create a palette entry.
let newPalette = false,
paletteName = null;
if ("PALETTEPLUGINS" in obj) {
for (const name in obj["PALETTEPLUGINS"]) {
paletteName = name;
PALETTEICONS[name] = obj["PALETTEPLUGINS"][name];
let fillColor = "#ff0066";
if ("PALETTEFILLCOLORS" in obj) {
if (name in obj["PALETTEFILLCOLORS"]) {
fillColor = obj["PALETTEFILLCOLORS"][name];
}
}
PALETTEFILLCOLORS[name] = fillColor;
let strokeColor = "#ef003e";
if ("PALETTESTROKECOLORS" in obj) {
if (name in obj["PALETTESTROKECOLORS"]) {
strokeColor = obj["PALETTESTROKECOLORS"][name];
}
}
PALETTESTROKECOLORS[name] = strokeColor;
let highlightColor = "#ffb1b3";
if ("PALETTEHIGHLIGHTCOLORS" in obj) {
if (name in obj["PALETTEHIGHLIGHTCOLORS"]) {
highlightColor = obj["PALETTEHIGHLIGHTCOLORS"][name];
}
}
PALETTEHIGHLIGHTCOLORS[name] = highlightColor;
let strokeHighlightColor = "#404040";
if ("HIGHLIGHTSTROKECOLORS" in obj) {
if (name in obj["HIGHLIGHTSTROKECOLORS"]) {
strokeHighlightColor = obj["HIGHLIGHTSTROKECOLORS"][name];
}
}
HIGHLIGHTSTROKECOLORS[name] = strokeHighlightColor;
platformColor.paletteColors[name] = [
fillColor,
strokeColor,
highlightColor,
strokeHighlightColor
];
if (name in activity.palettes.buttons) {
// eslint-disable-next-line no-console
console.debug("palette " + name + " already exists");
} else {
// eslint-disable-next-line no-console
console.debug("adding palette " + name);
activity.palettes.add(name);
if (!MULTIPALETTES[2].includes(name)) MULTIPALETTES[2].push(name);
newPalette = true;
}
}
}
if (newPalette) {
try {
// console.debug("Calling makePalettes");
activity.palettes.makePalettes(1);
} catch (e) {
// eslint-disable-next-line no-console
console.debug("makePalettes: " + e);
}
}
// Define the image blocks
if ("IMAGES" in obj) {
for (const blkName in obj["IMAGES"]) {
activity.pluginsImages[blkName] = obj["IMAGES"][blkName];
}
}
// Populate the flow-block dictionary, i.e., the code that is
// eval'd by this block.
if ("FLOWPLUGINS" in obj) {
for (const flow in obj["FLOWPLUGINS"]) {
activity.logo.evalFlowDict[flow] = obj["FLOWPLUGINS"][flow];
}
}
// Populate the arg-block dictionary, i.e., the code that is
// eval'd by this block.
if ("ARGPLUGINS" in obj) {
for (const arg in obj["ARGPLUGINS"]) {
activity.logo.evalArgDict[arg] = obj["ARGPLUGINS"][arg];
}
}
// Populate the macro dictionary, i.e., the code that is
// eval'd by this block.
if ("MACROPLUGINS" in obj) {
for (const macro in obj["MACROPLUGINS"]) {
try {
activity.palettes.pluginMacros[macro] = JSON.parse(obj["MACROPLUGINS"][macro]);
} catch (e) {
// eslint-disable-next-line no-console
console.debug("could not parse macro " + macro);
// eslint-disable-next-line no-console
console.debug(e);
}
}
}
// Populate the setter dictionary, i.e., the code that is
// used to set a value block.
if ("SETTERPLUGINS" in obj) {
for (const setter in obj["SETTERPLUGINS"]) {
activity.logo.evalSetterDict[setter] = obj["SETTERPLUGINS"][setter];
}
}
// Create the plugin protoblocks.
// FIXME: On Chrome, plugins are broken (They still work on Firefox):
// EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:".
// Maybe:
// let g = (function() { return this ? this : typeof self !== 'undefined' ? self : undefined})() || Function("return this")();
if ("BLOCKPLUGINS" in obj) {
for (const block in obj["BLOCKPLUGINS"]) {
// eslint-disable-next-line no-console
console.debug("adding plugin block " + block);
safeEval(obj["BLOCKPLUGINS"][block], "BLOCKPLUGINS:" + block);
}
}
// Create the globals.
if ("GLOBALS" in obj) {
safeEval(obj["GLOBALS"], "GLOBALS");
}
if ("PARAMETERPLUGINS" in obj) {
for (const parameter in obj["PARAMETERPLUGINS"]) {
activity.logo.evalParameterDict[parameter] = obj["PARAMETERPLUGINS"][parameter];
}
}
// Code to execute when plugin is loaded
if ("ONLOAD" in obj) {
for (const arg in obj["ONLOAD"]) {
safeEval(obj["ONLOAD"][arg], "ONLOAD:" + arg);
}
}
// Code to execute when turtle code is started
if ("ONSTART" in obj) {
for (const arg in obj["ONSTART"]) {
activity.logo.evalOnStartList[arg] = obj["ONSTART"][arg];
}
}
// Code to execute when turtle code is stopped
if ("ONSTOP" in obj) {
for (const arg in obj["ONSTOP"]) {
activity.logo.evalOnStopList[arg] = obj["ONSTOP"][arg];
}
}
for (const protoblock in activity.blocks.protoBlockDict) {
try {
// Push the protoblocks onto their palettes.
if (activity.blocks.protoBlockDict[protoblock].palette === undefined) {
// eslint-disable-next-line no-console
console.debug("Cannot find palette for protoblock " + protoblock);
} else if (activity.blocks.protoBlockDict[protoblock].palette === null) {
// eslint-disable-next-line no-console
console.debug("Cannot find palette for protoblock " + protoblock);
} else {
activity.blocks.protoBlockDict[protoblock].palette.add(
activity.blocks.protoBlockDict[protoblock]
);
}
} catch (e) {
// eslint-disable-next-line no-console
console.debug(e);
}
}
if (paletteName !== null) {
// console.debug("updating palette " + paletteName);
activity.palettes.updatePalettes(paletteName);
}
setTimeout(() => {
activity.palettes.show();
}, 2000);
// Return the object in case we need to save it to local storage.
return obj;
};
/**
* Processes raw plugin data, removes blank lines and comments, and then calls `processPluginData` to update the activity.
* @param {object} activity - The activity object to update.
* @param {string} rawData - Raw plugin data to process.
* @returns {object|null} The processed plugin data object or null if parsing fails.
*/
const processRawPluginData = (activity, rawData, pluginSource) => {
const lineData = rawData.split("\n");
let cleanData = "";
// We need to remove blank lines and comments and then
// join the data back together for processing as JSON.
for (let i = 0; i < lineData.length; i++) {
if (lineData[i].length === 0) {
continue;
}
if (lineData[i][0] === "/") {
continue;
}
cleanData += lineData[i];
}
// Note to plugin developers: You may want to comment out this
// try/catch while debugging your plugin.
let obj;
try {
obj = processPluginData(activity, cleanData.replace(/\n/g, ""), pluginSource);
} catch (e) {
obj = null;
// eslint-disable-next-line no-console
console.log(rawData);
// eslint-disable-next-line no-console
console.log(cleanData);
activity.errorMsg("Error loading plugin: " + e);
}
return obj;
};
/**
* Updates the plugin objects with data from the processed plugin data object.
* @param {object} activity - The activity object to update.
* @param {object} obj - The processed plugin data object.
*/
const updatePluginObj = (activity, obj) => {
if (obj === null) {
return;
}
for (const name in obj["PALETTEPLUGINS"]) {
activity.pluginObjs["PALETTEPLUGINS"][name] = obj["PALETTEPLUGINS"][name];
}
for (const name in obj["PALETTEFILLCOLORS"]) {
activity.pluginObjs["PALETTEFILLCOLORS"][name] = obj["PALETTEFILLCOLORS"][name];
}
for (const name in obj["PALETTESTROKECOLORS"]) {
activity.pluginObjs["PALETTESTROKECOLORS"][name] = obj["PALETTESTROKECOLORS"][name];
}
for (const name in obj["PALETTEHIGHLIGHTCOLORS"]) {
activity.pluginObjs["PALETTEHIGHLIGHTCOLORS"][name] = obj["PALETTEHIGHLIGHTCOLORS"][name];
}
for (const flow in obj["FLOWPLUGINS"]) {
activity.pluginObjs["FLOWPLUGINS"][flow] = obj["FLOWPLUGINS"][flow];
}
for (const arg in obj["ARGPLUGINS"]) {
activity.pluginObjs["ARGPLUGINS"][arg] = obj["ARGPLUGINS"][arg];
}
for (const block in obj["BLOCKPLUGINS"]) {
activity.pluginObjs["BLOCKPLUGINS"][block] = obj["BLOCKPLUGINS"][block];
}
if ("MACROPLUGINS" in obj) {
for (const macro in obj["MACROPLUGINS"]) {
activity.pluginObjs["MACROPLUGINS"][macro] = obj["MACROPLUGINS"][macro];
}
}
if ("GLOBALS" in obj) {
if (!("GLOBALS" in activity.pluginObjs)) {
activity.pluginObjs["GLOBALS"] = "";
}
activity.pluginObjs["GLOBALS"] += obj["GLOBALS"];
}
if ("IMAGES" in obj) {
activity.pluginObjs["IMAGES"] = obj["IMAGES"];
}
for (const name in obj["ONLOAD"]) {
activity.pluginObjs["ONLOAD"][name] = obj["ONLOAD"][name];
}