-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
2192 lines (1849 loc) · 61.1 KB
/
main.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
// Flock - Creative coding in 3D
// Dr Tracy Gardner - https://github.com/tracygardner
// Flip Computing Limited - flipcomputing.com
import * as Blockly from "blockly";
import { javascriptGenerator } from "blockly/javascript";
//import { registerFieldColour } from "@blockly/field-colour";
import { FieldGridDropdown } from "@blockly/field-grid-dropdown";
import { WorkspaceSearch } from "@blockly/plugin-workspace-search";
import { NavigationController } from "@blockly/keyboard-navigation";
import * as BlockDynamicConnection from "@blockly/block-dynamic-connection";
//import {CrossTabCopyPaste} from '@blockly/plugin-cross-tab-copy-paste';
import "@babylonjs/core/Debug/debugLayer";
import "@babylonjs/inspector";
import { flock, initializeFlock } from "./flock.js";
import {
options,
defineBlocks,
initializeVariableIndexes,
handleBlockSelect,
handleBlockDelete,
CustomZelosRenderer,
} from "./blocks";
import { defineBaseBlocks } from "./blocks/base";
import { defineShapeBlocks } from "./blocks/shapes";
import { defineGenerators } from "./generators";
import {
enableGizmos,
setGizmoManager,
disposeGizmoManager,
} from "./ui/designview";
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/flock/sw.js")
.then((registration) => {
console.log("Service Worker registered:", registration);
// Check for updates to the Service Worker
registration.onupdatefound = () => {
const newWorker = registration.installing;
if (newWorker) {
newWorker.onstatechange = () => {
if (newWorker.state === "installed") {
// If the old Service Worker is controlling the page
if (navigator.serviceWorker.controller) {
// Notify the user about the update
console.log("New update available");
showUpdateNotification();
}
}
};
}
};
})
.catch((error) => {
console.error("Service Worker registration failed:", error);
});
}
function showUpdateNotification() {
const notification = document.createElement("div");
notification.innerHTML = `
<div style="position: fixed; bottom: 0; left: 0; width: 100%; background: #511D91; color: white; text-align: center; padding: 10px; z-index: 1000;">
A new version of Flock is available. <button id="reload-btn" style="background: white; color: #511D91; padding: 5px 10px; border: none; cursor: pointer;">Reload</button>
</div>
`;
document.body.appendChild(notification);
document.getElementById("reload-btn").addEventListener("click", () => {
// Reload the page to activate the new service worker
window.location.reload();
});
}
let workspace = null;
Blockly.utils.colour.setHsvSaturation(0.3); // 0 (inclusive) to 1 (exclusive), defaulting to 0.45
Blockly.utils.colour.setHsvValue(0.85); // 0 (inclusive) to 1 (exclusive), defaulting to 0.65
/*
function Mesh(id = "UNDEFINED") {
this.id = id;
}
flock.Mesh = Mesh;
Mesh.prototype.toString = function MeshToString() {
console.log("Mesh.toString", `${this.id}`);
return `${this.id}`;
};
*/
// Function to save the current workspace state
function saveWorkspace() {
const state = Blockly.serialization.workspaces.save(workspace);
const key = "flock_autosave.json";
// Save today's workspace state
localStorage.setItem(key, JSON.stringify(state));
}
function loadWorkspaceAndExecute(json, workspace, executeCallback) {
try {
// Ensure that the workspace and json are valid before attempting to load
if (!workspace || !json) {
throw new Error("Invalid workspace or json data.");
}
Blockly.serialization.workspaces.load(json, workspace);
executeCallback(); // Runs only if loading succeeds
} catch (error) {
console.error("Failed to load workspace:", error);
// Additional handling for corrupt local storage or recovery
if (error.message.includes("isDeadOrDying")) {
// Try to reset workspace or handle specific cleanup for the isDeadOrDying error
console.warn("Workspace might be corrupted, attempting reset.");
workspace.clear(); // Clear the workspace if needed
localStorage.removeItem("flock_autosave.json")
}
}
}
function loadWorkspace() {
const urlParams = new URLSearchParams(window.location.search);
const projectUrl = urlParams.get("project"); // Check for project URL parameter
const reset = urlParams.get("reset"); // Check for reset URL parameter
const savedState = localStorage.getItem("flock_autosave.json");
const starter = "examples/starter.json"; // Starter JSON fallback
// Helper function to load starter project
function loadStarter() {
fetch(starter)
.then((response) => response.json())
.then((json) => {
loadWorkspaceAndExecute(json, workspace, executeCode);
})
.catch((error) => {
console.error("Error loading starter example:", error);
});
}
// Reset logic if 'reset' URL parameter is present
if (reset) {
console.warn("Resetting workspace and clearing local storage.");
workspace.clear(); // Clear the workspace
localStorage.removeItem("flock_autosave.json"); // Clear the saved state in localStorage
// Optionally reload the starter project after reset
loadStarter();
return; // Exit the function after reset
}
if (projectUrl) {
if (projectUrl === "starter") {
// Explicit request for the starter project
loadStarter();
} else {
// Load from project URL parameter
fetch(projectUrl)
.then((response) => {
if (!response.ok) throw new Error("Invalid response");
return response.json();
})
.then((json) => {
loadWorkspaceAndExecute(json, workspace, executeCode);
})
.catch((error) => {
console.error("Error loading project from URL:", error);
// Fallback to starter project
loadStarter();
});
}
} else if (savedState) {
// Load from local storage if available
loadWorkspaceAndExecute(JSON.parse(savedState), workspace, executeCode);
} else {
// Load starter project if no other options
loadStarter();
}
}
function stripFilename(inputString) {
const removeEnd = inputString.replace(/\(\d+\)/g, "");
// Find the last occurrence of '/' or '\'
let lastIndex = Math.max(
removeEnd.lastIndexOf("/"),
removeEnd.lastIndexOf("\\"),
);
if (lastIndex === -1) {
return removeEnd.trim();
}
return removeEnd.substring(lastIndex + 1).trim();
}
async function exportCode() {
try {
const projectName =
document.getElementById("projectName").value || "default_project";
let ws = Blockly.getMainWorkspace();
let usedModels = Blockly.Variables.allUsedVarModels(ws);
let allModels = ws.getAllVariables();
for (const model of allModels) {
if (
!usedModels.find((element) => element.getId() === model.getId())
) {
ws.deleteVariableById(model.getId());
}
}
const json = Blockly.serialization.workspaces.save(workspace);
const jsonString = JSON.stringify(json, null, 2); // Pretty-print the JSON
// Use File System Access API if available
if ("showSaveFilePicker" in window) {
const options = {
suggestedName: `${projectName}.json`,
types: [
{
description: "JSON Files",
accept: { "application/json": [".json"] },
},
],
};
const fileHandle = await window.showSaveFilePicker(options);
const writable = await fileHandle.createWritable();
await writable.write(jsonString);
await writable.close();
} else {
// Fallback for older browsers
const blob = new Blob([jsonString], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${projectName}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
} catch (e) {
console.error("Error exporting project:", e);
}
}
let toolboxVisible = false;
let isExecuting = false;
async function executeCode() {
// Check if the function is already running
if (isExecuting) {
console.log("Function already running, skipping execution.");
return; // Exit if already running
}
// Set the flag to indicate the function is running
isExecuting = true;
// Utility function for delay
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Wait until the engine is ready using a loop with an async delay
while (!flock.engineReady) {
await delay(100);
}
console.log("Engine ready");
// Cache DOM elements
const container = document.getElementById("maincontent");
const switchViewsBtn = document.getElementById("switchViews");
const renderCanvas = document.getElementById("renderCanvas");
// Switch to code view if currently in canvas view
if (currentView === "canvas") {
currentView = "code";
container.style.transform = `translateX(0px)`; // Move to Code view
switchViewsBtn.textContent = "Canvas >>"; // Update button text
}
disposeGizmoManager();
let showDebug = flock.scene?.debugLayer?.isVisible();
if (showDebug) {
flock.scene.debugLayer.hide();
}
// Generate the code from the workspace
const code = javascriptGenerator.workspaceToCode(workspace);
try {
console.log(code);
await flock.runCode(code);
renderCanvas?.focus(); // Focus the render canvas safely if it exists
} catch (error) {
console.error("Error executing Blockly code:", error);
isExecuting = false; // Reset the flag if there's an error
// Load the starter project if execution fails
const starter = "examples/starter.json";
fetch(starter)
.then((response) => response.json())
.then((json) => {
loadWorkspaceAndExecute(json, workspace, executeCode);
})
.catch((loadError) => {
console.error(
"Error loading starter project after execution failure:",
loadError,
);
});
return; // Exit after handling the error
}
// Check if the debug layer is visible and show it if necessary
if (showDebug) {
try {
await flock.scene.debugLayer.show({
embedMode: true,
enableClose: false,
enablePopup: false,
});
} catch (error) {
console.error("Error showing debug layer:", error);
}
}
setGizmoManager(new flock.BABYLON.GizmoManager(flock.scene, 8));
await delay(1000);
// Reset the flag to allow future executions
isExecuting = false;
}
function stopCode() {
// Stop all playing sounds
if (flock.scene && flock.scene.mainSoundTrack) {
flock.scene.mainSoundTrack.soundCollection.forEach((sound) => {
if (sound.isPlaying) {
sound.stop();
console.log(`Stopped sound: ${sound.name}`);
}
});
}
// Close the audio context
if (flock.audioContext) {
flock.audioContext
.close()
.then(() => {
console.log("Audio context closed.");
})
.catch((error) => {
console.error("Error closing audio context:", error);
});
}
// Stop rendering
flock.engine.stopRenderLoop();
console.log("Render loop stopped.");
// Remove event listeners
flock.removeEventListeners();
// Switch to code view
switchView(codeMode);
}
window.stopCode = stopCode;
function onResize() {
Blockly.svgResize(workspace);
//document.body.style.zoom = "reset";
resizeCanvas();
if (flock.engine) flock.engine.resize();
}
window.onresize = onResize;
async function exportBlockSnippet(block) {
try {
// Save the block and its children to a JSON object
const blockJson = Blockly.serialization.blocks.save(block);
// Convert the JSON object to a pretty-printed JSON string
const jsonString = JSON.stringify(blockJson, null, 2);
// Check if the File System Access API is available
if ("showSaveFilePicker" in window) {
// Define the options for the file picker
const options = {
suggestedName: "blockly_snippet.json",
types: [
{
description: "JSON Files",
accept: {
"application/json": [".json"],
},
},
],
};
// Show the save file picker
const fileHandle = await window.showSaveFilePicker(options);
// Create a writable stream
const writable = await fileHandle.createWritable();
// Write the JSON string to the file
await writable.write(jsonString);
// Close the writable stream
await writable.close();
} else {
// Fallback for browsers that don't support the File System Access API
const filename =
prompt(
"Enter a filename for the snippet:",
"blockly_snippet",
) || "blockly_snippet";
const blob = new Blob([jsonString], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${filename}.json`;
link.click();
}
} catch (e) {
console.error("Error exporting block:", e);
}
}
import { getMetadata } from "meta-png";
function importSnippet() {
const fileInput = document.getElementById("importFile");
fileInput.click();
fileInput.onchange = (event) => {
const file = event.target.files[0];
if (file) {
const fileType = file.type;
const reader = new FileReader();
reader.onload = () => {
const content = reader.result;
if (fileType === "image/svg+xml") {
// Handle SVG
try {
const parser = new DOMParser();
const svgDoc = parser.parseFromString(
content,
"image/svg+xml",
);
// Extract metadata
const metadataElement =
svgDoc.querySelector("metadata");
if (!metadataElement) {
console.error(
"No <metadata> tag found in the SVG file.",
);
return;
}
// Extract and parse JSON from metadata
const metadataContent =
metadataElement.textContent.trim();
let blockJson;
try {
const parsedData = JSON.parse(metadataContent);
// Ensure the key containing JSON exists
if (!parsedData.blockJson) {
console.error(
"Metadata JSON does not contain 'blockJson'.",
);
return;
}
// Parse the block JSON if needed
blockJson = JSON.parse(parsedData.blockJson);
} catch (parseError) {
console.error(
"Error parsing metadata JSON:",
parseError,
);
return;
}
// Load blocks into Blockly workspace without clearing
try {
const workspace = Blockly.getMainWorkspace(); // Ensure correct reference
Blockly.serialization.blocks.append(
blockJson,
workspace,
);
} catch (workspaceError) {
console.error(
"Error loading blocks into workspace:",
workspaceError,
);
}
} catch (error) {
console.error(
"An error occurred while processing the SVG file:",
error,
);
}
} else if (fileType === "image/png") {
// Handle PNG metadata
try {
const arrayBuffer = new Uint8Array(content);
const encodedMetadata = getMetadata(
arrayBuffer,
"blockJson",
);
if (!encodedMetadata) {
console.error("No metadata found in the PNG file.");
return;
}
// Decode the URL-encoded metadata and parse it as JSON
const decodedMetadata = JSON.parse(
decodeURIComponent(encodedMetadata),
);
// Load blocks into Blockly workspace without clearing
const workspace = Blockly.getMainWorkspace();
Blockly.serialization.blocks.append(
decodedMetadata,
workspace,
);
} catch (error) {
console.error("Error processing PNG metadata:", error);
}
} else if (fileType === "application/json") {
// Handle JSON
try {
const blockJson = JSON.parse(content);
// Load blocks into Blockly workspace without clearing
const workspace = Blockly.getMainWorkspace();
Blockly.serialization.blocks.append(
blockJson,
workspace,
);
} catch (error) {
console.error("Error processing JSON file:", error);
}
} else {
console.error("Unsupported file type:", fileType);
}
};
if (fileType === "image/png") {
reader.readAsArrayBuffer(file); // PNG files need ArrayBuffer for metadata
} else {
reader.readAsText(file); // Other files use text
}
}
};
}
function addExportContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "exportBlock",
weight: 200,
displayText: function () {
return "Export block as JSON snippet";
},
preconditionFn: function (scope) {
return scope.block ? "enabled" : "hidden";
},
callback: function (scope) {
exportBlockSnippet(scope.block);
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK,
checkbox: false,
});
}
// Extend Blockly with custom context menu for importing snippets in the workspace
function addImportContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "importSnippet",
weight: 100,
displayText: function () {
return "Import snippet";
},
preconditionFn: function (scope) {
return "enabled";
},
callback: function (scope) {
importSnippet();
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE,
checkbox: false,
});
}
function addExportPNGContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "exportPNG",
weight: 100,
displayText: function () {
return "Export as PNG";
},
preconditionFn: function (scope) {
return "enabled";
},
callback: function (scope) {
if (scope.block) {
exportBlockAsPNG(scope.block);
} else if (scope.workspace) {
//exportWorkspaceAsPNG(scope.workspace);
}
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK,
checkbox: false,
});
}
// Extend Blockly with custom context menu for exporting SVG of the workspace
function addExportSVGContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "exportSVG",
weight: 101,
displayText: function () {
return "Export as SVG";
},
preconditionFn: function (scope) {
return "enabled";
},
callback: function (scope) {
if (scope.block) {
// Export selected block or stack as SVG
exportBlockAsSVG(scope.block);
} else if (scope.workspace) {
// Export the entire workspace as SVG
exportWorkspaceAsSVG(scope.workspace);
}
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK,
checkbox: false,
});
}
/*
function toggleToolbox() {
const toolboxControl = document.getElementById("toolboxControl");
if (!workspace) return;
if (toolboxVisible) {
toolboxVisible = false;
workspace.getToolbox().setVisible(false);
//onResize();
} else {
toolboxVisible = true;
workspace.getToolbox().setVisible(true);
// Delay binding the click event listener
setTimeout(() => {
document.addEventListener("click", handleClickOutside);
}, 100); // Small delay to ensure the menu is shown before adding the listener
}
function handleClickOutside(event) {
if (!toolboxControl.contains(event.target)) {
workspace.getToolbox().setVisible(false);
document.removeEventListener("click", handleClickOutside);
}
}
}
window.toggleToolbox = toggleToolbox;
*/
async function loadExample() {
window.loadingCode = true;
const exampleSelect = document.getElementById("exampleSelect");
const exampleFile = exampleSelect.value;
const projectNameElement = document.getElementById("projectName");
if (exampleFile) {
// Set the project name based on the selected option's text
const selectedOption =
exampleSelect.options[exampleSelect.selectedIndex].text;
projectNameElement.value = selectedOption;
fetch(exampleFile)
.then((response) => response.json())
.then((json) => {
console.error("Loading:", selectedOption);
loadWorkspaceAndExecute(json, workspace, executeCode);
})
.catch((error) => {
console.error("Error loading example:", error);
});
}
exampleSelect.value = "";
}
window.executeCode = executeCode;
window.exportCode = exportCode;
window.loadExample = loadExample;
// Function to maintain a 16:9 aspect ratio for the canvas
function resizeCanvas() {
const canvasArea = document.getElementById("rightArea");
const canvas = document.getElementById("renderCanvas");
const areaWidth = canvasArea.clientWidth;
let areaHeight = canvasArea.clientHeight;
const gizmoButtons = document.getElementById("gizmoButtons");
if (gizmoButtons.style.display != "none") {
areaHeight -= 60; //Gizmos visible
}
const aspectRatio = 16 / 9;
let newWidth, newHeight;
if (areaWidth / areaHeight > aspectRatio) {
newHeight = areaHeight;
newWidth = newHeight * aspectRatio;
} else {
newWidth = areaWidth;
newHeight = newWidth / aspectRatio;
}
canvas.style.width = `${newWidth}px`;
canvas.style.height = `${newHeight}px`;
}
let viewMode = "both";
let codeMode = "both";
window.viewMode = viewMode;
window.codeMode = codeMode;
function switchView(view) {
if (flock.scene) flock.scene.debugLayer.hide();
const blocklyArea = document.getElementById("codePanel");
const canvasArea = document.getElementById("rightArea");
if (view === "both") {
viewMode = "both";
codeMode = "both";
blocklyArea.style.display = "block";
canvasArea.style.display = "block";
blocklyArea.style.width = "0";
canvasArea.style.width = "0";
blocklyArea.style.flex = "2 1 0"; // 2/3 of the space
canvasArea.style.flex = "1 1 0"; // 1/3 of the space gizmoButtons.style.display = "flex";
} else if (view === "canvas") {
console.log("canvas");
viewMode = "canvas";
blocklyArea.style.display = "none";
canvasArea.style.display = "block";
}
onResize(); // Ensure both Blockly and Babylon.js canvas resize correctly
}
window.switchView = switchView;
function toggleMenu() {
const menu = document.getElementById("menu");
const currentDisplay = window.getComputedStyle(menu).display;
if (currentDisplay != "none") {
menu.style.display = "none";
document.removeEventListener("click", handleClickOutside);
} else {
menu.style.display = "flex";
// Delay binding the click event listener
setTimeout(() => {
document.addEventListener("click", handleClickOutside);
}, 100); // Small delay to ensure the menu is shown before adding the listener
}
function handleClickOutside(event) {
if (!menu.contains(event.target)) {
menu.style.display = "none";
document.removeEventListener("click", handleClickOutside);
}
}
}
window.toggleMenu = toggleMenu;
document.addEventListener("DOMContentLoaded", () => {
const requestFullscreen = () => {
const elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
// For Firefox
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
// For Chrome, Safari, and Opera
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (elem.msRequestFullscreen) {
// For IE/Edge
elem.msRequestFullscreen();
}
};
const isMobile = () => {
return /Mobi|Android/i.test(navigator.userAgent);
};
const isFullscreen = window.matchMedia(
"(display-mode: fullscreen)",
).matches;
// Request fullscreen on mobile only when running as a PWA
if (isMobile() && isFullscreen) {
requestFullscreen();
document.getElementById("fullscreenToggle").style.display = "none";
}
if (window.matchMedia("(display-mode: fullscreen)").matches) {
// Adjust layout for fullscreen mode
adjustViewport();
}
window
.matchMedia("(display-mode: fullscreen)")
.addEventListener("change", (e) => {
if (e.matches) {
// The app has entered fullscreen mode
adjustViewport();
}
});
if (isMobile()) {
adjustViewport();
//const dpr = window.devicePixelRatio || 1;
// document.body.style.zoom = dpr; // This adjusts the zoom based on DPR
}
// Additional adjustments for mobile UI in fullscreen mode
const examples = document.getElementById("exampleSelect");
if (examples) {
examples.style.width = "70px";
}
const projectName = document.getElementById("projectName");
if (projectName) {
//projectName.style.minWidth = "5px";
//projectName.style.maxWidth = "80px";
}
});
let currentView = "start"; // Start with the code view
// Function to be called once the app has fully loaded
const container = document.getElementById("maincontent");
const bottomBar = document.getElementById("bottomBar");
const switchViewsBtn = document.getElementById("switchViews");
let startX = 0;
let currentTranslate = 0;
let previousTranslate = 0;
let isDragging = false;
const swipeThreshold = 50; // Minimum swipe distance
function showCanvasView() {
const gizmoButtons = document.getElementById("gizmoButtons");
gizmoButtons.style.display = "block";
currentView = "canvas";
container.style.transform = `translateX(0px)`; // Move to Code view
switchViewsBtn.textContent = "Code >>"; // Update button text
onResize();
}
function showCodeView() {
const blocklyArea = document.getElementById("codePanel");
blocklyArea.style.display = "block";
const panelWidth = window.innerWidth;
currentView = "code";
container.style.transform = `translateX(-${panelWidth}px)`; // Move to Canvas view
switchViewsBtn.textContent = "<< Canvas"; // Update button text
}
function togglePanels() {
if (switchViewsBtn.textContent === "Code >>") {
showCodeView();
} else {
showCanvasView();
}
}
function setTranslateX(value) {
container.style.transform = `translateX(${value}px)`;
}
// Function to add the swipe event listeners
function addSwipeListeners() {
// Handle touch start (drag begins)
bottomBar.addEventListener("touchstart", (e) => {
startX = e.touches[0].clientX;
isDragging = true;
});
// Handle touch move (drag in progress)
bottomBar.addEventListener("touchmove", (e) => {
if (!isDragging) return;
const currentX = e.touches[0].clientX;
const deltaX = currentX - startX;
currentTranslate = previousTranslate + deltaX;
// Ensure the container doesn't drag too far
if (currentTranslate > 0) currentTranslate = 0;
if (currentTranslate < -window.innerWidth)
currentTranslate = -window.innerWidth;
setTranslateX(currentTranslate);
});
// Handle touch end (drag ends, snap to nearest panel)
bottomBar.addEventListener("touchend", () => {
isDragging = false;
// Calculate the total distance swiped
const deltaX = currentTranslate - previousTranslate;
// Snap to the next or previous panel based on swipe distance and direction
if (deltaX < -swipeThreshold) {
showCodeView(); // Swipe left to switch to the Canvas view
} else if (deltaX > swipeThreshold) {
showCanvasView(); // Swipe right to switch to the Code view
}
previousTranslate = currentTranslate; // Update the last translate value
});
}
let savedView = "canvas";
function togglePlayMode() {
if (!flock.scene) return;
const blocklyArea = document.getElementById("codePanel");
const canvasArea = document.getElementById("rightArea");
const gizmoButtons = document.getElementById("gizmoButtons");
const bottomBar = document.getElementById("bottomBar");
const gizmosVisible =
gizmoButtons &&
getComputedStyle(gizmoButtons).display !== "none" &&
getComputedStyle(gizmoButtons).visibility !== "hidden";
if (gizmosVisible) {
savedView = currentView;
showCanvasView();
flock.scene.debugLayer.hide();
blocklyArea.style.display = "none";
gizmoButtons.style.display = "none";
bottomBar.style.display = "none";
document.documentElement.style.setProperty("--dynamic-offset", "40px");
} else {
flock.scene.debugLayer.hide();
blocklyArea.style.display = "block";
canvasArea.style.display = "block";
gizmoButtons.style.display = "block";
bottomBar.style.display = "block";
switchView("both");
document.documentElement.style.setProperty("--dynamic-offset", "65px");
if (savedView === "code") showCodeView();
else showCanvasView();
}
onResize();
}
// Function to add the button event listener
function addButtonListener() {
switchViewsBtn.addEventListener("click", togglePanels);
}
function toggleDesignMode() {
if (!flock.scene) return;
const blocklyArea = document.getElementById("codePanel");
const canvasArea = document.getElementById("rightArea");
const gizmoButtons = document.getElementById("gizmoButtons");
if (flock.scene.debugLayer.isVisible()) {
switchView("both");
flock.scene.debugLayer.hide();