-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathfiles.js
More file actions
1093 lines (956 loc) · 32 KB
/
files.js
File metadata and controls
1093 lines (956 loc) · 32 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
import * as Blockly from "blockly";
import { workspace } from "./blocklyinit.js";
import { translate } from "./translation.js";
import { getMetadata } from "meta-png";
import { AUTOSAVE_KEY } from "../config.js";
function collectWorkspaceSnapshot(ws) {
if (!ws) {
return {
blockIds: new Set(),
variableIds: new Set(),
blockCount: 0,
variableCount: 0,
};
}
const blocks = ws.getAllBlocks?.(false) || [];
const variables = ws.getVariableMap?.().getAllVariables?.() || [];
return {
blockIds: new Set(blocks.map((b) => b.id).filter(Boolean)),
variableIds: new Set(variables.map((v) => v.getId?.()).filter(Boolean)),
blockCount: blocks.length,
variableCount: variables.length,
};
}
function collectIncomingSnapshot(json) {
const blockIds = new Set();
const variableIds = new Set();
const walkBlock = (block) => {
if (!block || typeof block !== "object") return;
if (block.id) blockIds.add(block.id);
if (block.inputs && typeof block.inputs === "object") {
Object.values(block.inputs).forEach((input) => {
walkBlock(input?.block);
walkBlock(input?.shadow);
});
}
if (block.next?.block) walkBlock(block.next.block);
};
(json?.blocks?.blocks || []).forEach(walkBlock);
(json?.variables || []).forEach((v) => {
if (v?.id) variableIds.add(v.id);
});
return {
blockIds,
variableIds,
blockCount: blockIds.size,
variableCount: variableIds.size,
};
}
function intersectSets(a, b) {
const result = [];
a.forEach((value) => {
if (b.has(value)) result.push(value);
});
return result;
}
// Function to save the current workspace state
export function saveWorkspace(workspace) {
if (workspace && workspace.getAllBlocks) {
const usedModels = Blockly.Variables.allUsedVarModels(workspace);
const allModels = workspace.getVariableMap().getAllVariables();
for (const model of allModels) {
if (!usedModels.find((element) => element.getId() === model.getId())) {
workspace.deleteVariableById(model.getId());
}
}
}
const state = Blockly.serialization.workspaces.save(workspace);
const key = AUTOSAVE_KEY;
localStorage.setItem(key, JSON.stringify(state));
}
function validateBlocklyJson(json) {
// 1. Parse JSON safely
let data;
try {
data = typeof json === "string" ? JSON.parse(json) : json;
} catch {
throw new Error("Invalid JSON format");
}
// 2. Check for dangerous properties that could execute code
const dangerousKeys = [
"__proto__",
"constructor",
"prototype",
"eval",
"Function",
"setTimeout",
"setInterval",
"innerHTML",
"outerHTML",
"onclick",
"onerror",
"onload",
];
function checkForDangerousContent(obj, path = "") {
if (obj === null || obj === undefined) return;
// Check primitive values for suspicious patterns
if (typeof obj === "string") {
// Skip validation for block IDs - they can contain random characters
if (path.endsWith(".id") || path.endsWith(".ID_VAR.id")) {
return;
}
// Allow newlines in specific safe contexts:
// - extraState (for Blockly mutation XML)
// - comment text (for block comments and workspace comments)
const allowNewlines =
path.includes("extraState") ||
path.includes("icons.comment") ||
path.includes("workspaceComments");
// Block newlines everywhere else as they could be code
if (/[\r\n]/.test(obj) && !allowNewlines) {
throw new Error(
`Newline characters not allowed at ${path}: potential code injection`,
);
}
// Normalize string by removing/reducing whitespace for pattern matching
const normalized = obj.replace(/\s+/g, " ").trim();
// Look for script tags, event handlers, or javascript: protocol
const suspiciousPatterns = [
/<\s*script/i,
/javascript\s*:/i,
/on\w+\s*=/i, // Event handlers like onclick=
/\beval\s*\(/i,
/\bFunction\s*\(/i,
/\bnew\s+Function/i,
/\bimport\s*\(/i, // Dynamic imports
/\bimport\s+.*from/i,
/\brequire\s*\(/i,
/\bexec\s*\(/i,
/\bspawn\s*\(/i,
/\bsetTimeout\s*\(/i,
/\bsetInterval\s*\(/i,
/\bsetImmediate\s*\(/i,
/\bexecScript/i,
/\bexpression\s*\(/i, // IE expression()
/vbscript:/i,
/data:text\/html/i,
/<\s*iframe/i,
/<\s*object/i,
/<\s*embed/i,
/\.innerHTML\s*=/i,
/\.outerHTML\s*=/i,
/\bdocument\s*\.\s*write/i,
/\bwindow\s*\.\s*location/i,
];
if (suspiciousPatterns.some((pattern) => pattern.test(normalized))) {
throw new Error(
`Suspicious content found at ${path}: potential code injection. Content: "${obj.substring(0, 50)}${obj.length > 50 ? "..." : ""}"`,
);
}
// Check for suspicious character sequences that might indicate obfuscation
const obfuscationPatterns = [
/\\x[0-9a-f]{2}/i, // Hex escape sequences
/\\u[0-9a-f]{4}/i, // Unicode escape sequences
/&#x?[0-9a-f]+;/i, // HTML entities
/%[0-9a-f]{2}/i, // URL encoded characters
];
// Flag any obfuscation pattern - legitimate Blockly field values should not
// contain escape sequences, HTML entities, or URL-encoded characters.
const suspiciousCount = obfuscationPatterns.filter((pattern) =>
pattern.test(obj),
).length;
if (suspiciousCount >= 1) {
throw new Error(`Potential obfuscation detected at ${path}`);
}
}
if (typeof obj === "object") {
// Check for dangerous keys
for (const key of Object.keys(obj)) {
if (dangerousKeys.includes(key)) {
throw new Error(`Dangerous property found: ${key} at ${path}`);
}
checkForDangerousContent(obj[key], path ? `${path}.${key}` : key);
}
}
}
function upgradeAnimationInputs(block) {
if (!block || typeof block !== "object") return;
const legacyAnimationName = block.fields?.ANIMATION_NAME;
const hasNewAnimationInput = block.inputs?.ANIMATION_NAME;
if (
legacyAnimationName &&
!hasNewAnimationInput &&
(block.type === "play_animation" || block.type === "switch_animation")
) {
block.inputs = block.inputs || {};
block.inputs.ANIMATION_NAME = {
shadow: {
type: "animation_name",
fields: { ANIMATION_NAME: legacyAnimationName },
},
};
delete block.fields.ANIMATION_NAME;
if (block.fields && Object.keys(block.fields).length === 0) {
delete block.fields;
}
}
if (block.inputs) {
Object.values(block.inputs).forEach((input) => {
upgradeAnimationInputs(input?.block);
upgradeAnimationInputs(input?.shadow);
});
}
upgradeAnimationInputs(block.next?.block);
}
// 3. Validate it's actually a Blockly workspace structure
function validateBlocklyStructure(data) {
// Empty workspace is valid
if (Object.keys(data).length === 0) {
return;
}
// Blockly workspace JSON should have specific structure
// Check if data.blocks exists and is a non-null object (not an array)
if (
!data.blocks ||
typeof data.blocks !== "object" ||
Array.isArray(data.blocks)
) {
throw new Error(
"Invalid Blockly structure: missing or invalid blocks object",
);
}
// Whitelist allowed properties at root level
const allowedRootKeys = ["blocks", "variables", "workspaceComments"];
const rootKeys = Object.keys(data);
for (const key of rootKeys) {
if (!allowedRootKeys.includes(key)) {
console.warn(`Unexpected property in Blockly JSON: ${key}`);
}
}
// Whitelist allowed properties in blocks object
const allowedBlocksKeys = ["languageVersion", "blocks"];
if (data.blocks) {
for (const key of Object.keys(data.blocks)) {
if (!allowedBlocksKeys.includes(key)) {
console.warn(`Unexpected property in blocks object: ${key}`);
}
}
}
// Validate blocks array if present
if (data.blocks.blocks) {
if (!Array.isArray(data.blocks.blocks)) {
throw new Error(
"Invalid Blockly structure: blocks.blocks must be an array",
);
}
data.blocks.blocks.forEach((block, index) => {
validateBlock(block, `blocks.blocks[${index}]`);
});
}
// Validate variables if present
if (data.variables) {
if (!Array.isArray(data.variables)) {
throw new Error(
"Invalid Blockly structure: variables must be an array",
);
}
data.variables.forEach((variable, index) => {
if (!variable.name || !variable.id) {
throw new Error(
`Invalid variable at variables[${index}]: must have name and id`,
);
}
});
}
}
// 4. Validate individual block structure
function validateBlock(block, path) {
if (!block || typeof block !== "object") {
throw new Error(`Invalid block at ${path}`);
}
// Whitelist allowed block properties
const allowedBlockKeys = [
"type",
"id",
"x",
"y",
"collapsed",
"disabled",
"deletable",
"movable",
"editable",
"inline",
"data",
"extraState",
"icons",
"fields",
"inputs",
"next",
"shadow",
"disabledReasons",
];
for (const key of Object.keys(block)) {
if (!allowedBlockKeys.includes(key)) {
throw new Error(`Unexpected block property: ${key} at ${path}`);
}
}
// Validate field values
if (block.fields) {
Object.entries(block.fields).forEach(([fieldName, fieldValue]) => {
if (fieldValue && typeof fieldValue === "object") {
// Field values can be objects with 'id' property for variables
if (!fieldValue.id) {
checkForDangerousContent(fieldValue, `${path}.fields.${fieldName}`);
}
} else if (typeof fieldValue === "string") {
// Check string field values for dangerous content
checkForDangerousContent(fieldValue, `${path}.fields.${fieldName}`);
}
});
}
// Recursively validate nested blocks
if (block.inputs) {
Object.entries(block.inputs).forEach(([inputName, input]) => {
if (input.block) {
validateBlock(input.block, `${path}.inputs.${inputName}.block`);
}
if (input.shadow) {
validateBlock(input.shadow, `${path}.inputs.${inputName}.shadow`);
}
});
}
if (block.next?.block) {
validateBlock(block.next.block, `${path}.next.block`);
}
}
// Run all validations
checkForDangerousContent(data);
validateBlocklyStructure(data);
if (data?.blocks?.blocks) {
data.blocks.blocks.forEach((block) => upgradeAnimationInputs(block));
}
return data;
}
export function loadWorkspaceAndExecute(json, workspace, executeCallback) {
try {
if (!workspace || !json) {
throw new Error("Invalid workspace or json data.");
}
// Validate JSON before loading into workspace
const validatedJson = validateBlocklyJson(json);
console.log("[workspace-load:entry]", {
workspaceId: workspace?.id ?? null,
topLevelBlocksInJson: validatedJson?.blocks?.blocks?.length ?? 0,
variablesInJson: validatedJson?.variables?.length ?? 0,
});
const before = collectWorkspaceSnapshot(workspace);
const incoming = collectIncomingSnapshot(validatedJson);
const collidingBlockIds = intersectSets(before.blockIds, incoming.blockIds);
const collidingVariableIds = intersectSets(
before.variableIds,
incoming.variableIds,
);
console.log("[workspace-load:before]", {
existingBlocks: before.blockCount,
existingVariables: before.variableCount,
incomingBlocks: incoming.blockCount,
incomingVariables: incoming.variableCount,
});
console.log("[workspace-load:collisions]", {
blockIdCollisions: collidingBlockIds.length,
variableIdCollisions: collidingVariableIds.length,
sampleBlockIds: collidingBlockIds.slice(0, 10),
sampleVariableIds: collidingVariableIds.slice(0, 10),
});
// Load the validated JSON
Blockly.serialization.workspaces.load(validatedJson, workspace);
const after = collectWorkspaceSnapshot(workspace);
const missingIncomingBlockIds = [...incoming.blockIds].filter(
(id) => !after.blockIds.has(id),
);
const missingIncomingVariableIds = [...incoming.variableIds].filter(
(id) => !after.variableIds.has(id),
);
console.log("[workspace-load:after]", {
resultingBlocks: after.blockCount,
resultingVariables: after.variableCount,
missingIncomingBlockIds: missingIncomingBlockIds.length,
missingIncomingVariableIds: missingIncomingVariableIds.length,
sampleMissingBlockIds: missingIncomingBlockIds.slice(0, 10),
sampleMissingVariableIds: missingIncomingVariableIds.slice(0, 10),
});
workspace.scroll(0, 0);
executeCallback();
} catch (error) {
console.error("Failed to load workspace:", error);
// Handle validation errors
if (
error.message.includes("Suspicious content") ||
error.message.includes("Dangerous property") ||
error.message.includes("Invalid Blockly structure")
) {
console.error(
"Security validation failed - JSON may contain malicious content",
);
throw error; // Re-throw security errors - don't try to recover
}
// Handle corruption errors
if (error.message.includes("isDeadOrDying")) {
console.warn("Workspace might be corrupted, attempting reset.");
workspace.clear();
// Note: localStorage usage - be aware this won't work in Claude artifacts
if (typeof localStorage !== "undefined") {
localStorage.removeItem(AUTOSAVE_KEY);
}
}
}
}
function parseProjectJsonResponse(response) {
if (!response.ok) {
throw new Error(
`Failed to load project (${response.status} ${response.statusText})`,
);
}
const contentType = (
response.headers.get("content-type") || ""
).toLowerCase();
return response.text().then((projectText) => {
const trimmedProjectText = projectText.trim();
if (
contentType.includes("text/html") ||
trimmedProjectText.startsWith("<!doctype html") ||
trimmedProjectText.startsWith("<html")
) {
throw new Error(
`Expected JSON project data but received ${contentType || "text/html"}`,
);
}
try {
return JSON.parse(projectText);
} catch (error) {
throw new Error(
`Failed to parse project JSON from ${contentType || "unknown content type"}`,
{ cause: error },
);
}
});
}
export function fetchProjectJson(projectPath) {
return fetch(projectPath).then(parseProjectJsonResponse);
}
// Function to load workspace from various sources
export function loadWorkspace(workspace, executeCallback) {
const urlParams = new URLSearchParams(window.location.search);
const projectUrl = urlParams.get("project");
const reset = urlParams.get("reset");
const autoplay = urlParams.get("autoplay") !== "false";
const effectiveCallback = autoplay ? executeCallback : () => {};
const savedState = localStorage.getItem(AUTOSAVE_KEY);
const starter = "examples/starter.flock";
function loadStarter() {
fetchProjectJson(starter)
.then((json) => {
loadWorkspaceAndExecute(json, workspace, effectiveCallback);
})
.catch((error) => {
console.error("Error loading starter example:", error);
});
}
if (reset) {
console.warn("Resetting workspace and clearing local storage.");
workspace.clear();
localStorage.removeItem(AUTOSAVE_KEY);
loadStarter();
return;
}
if (projectUrl) {
if (projectUrl === "starter") {
loadStarter();
} else if (projectUrl === "new") {
fetchProjectJson("examples/new.flock")
.then((json) => {
loadWorkspaceAndExecute(json, workspace, effectiveCallback);
})
.catch((error) => {
console.error("Error loading new project:", error);
loadStarter();
});
} else {
let validatedUrl;
try {
validatedUrl = new URL(projectUrl, window.location.href);
if (!["http:", "https:"].includes(validatedUrl.protocol)) {
throw new Error("Project URL must use http or https protocol");
}
const path = validatedUrl.pathname.toLowerCase();
if (!path.endsWith(".json") && !path.endsWith(".flock")) {
throw new Error("Project URL must point to a .json or .flock file");
}
} catch (error) {
console.error("Invalid project URL:", error);
loadStarter();
return;
}
fetch(validatedUrl.href)
.then(parseProjectJsonResponse)
.then((json) => {
loadWorkspaceAndExecute(json, workspace, effectiveCallback);
})
.catch((error) => {
console.error("Error loading project from URL:", error);
loadStarter();
});
}
} else if (savedState) {
loadWorkspaceAndExecute(
JSON.parse(savedState),
workspace,
effectiveCallback,
);
} else {
loadStarter();
}
}
// Function to strip filename from path
export function stripFilename(inputString) {
const removeEnd = inputString.replace(/\(\d+\)/g, "");
let lastIndex = Math.max(
removeEnd.lastIndexOf("/"),
removeEnd.lastIndexOf("\\"),
);
if (lastIndex === -1) {
return removeEnd.trim();
}
return removeEnd.substring(lastIndex + 1).trim();
}
// Preserve user-facing imported filename characters (including spaces and
// punctuation) while still stripping potentially unsafe invisible chars.
function getSafeImportedFileBaseName(fileName) {
const rawName = String(fileName || "untitled");
const cleanedName = rawName
.replace(/\p{Cc}/gu, "")
.replace(/[\u200B-\u200F\u2060-\u206F\uFEFF]/g, "")
.replace(/[\u202A-\u202E\u2066-\u2069]/g, "");
const withoutExtension = cleanedName.replace(/\.(json|flock)$/i, "");
const baseName = stripFilename(withoutExtension).trim();
return baseName.substring(0, 50) || "untitled";
}
// Holds the FileSystemFileHandle from the last explicit save (File System Access API)
let currentFileHandle = null;
// Clears the stored file handle (call whenever a new project is loaded)
export function clearFileHandle() {
currentFileHandle = null;
}
// Function to export project code
export async function exportCode(workspace) {
try {
const projectName =
document.getElementById("projectName").value || "default_project";
// Ensure we have a valid workspace
const ws =
workspace && workspace.getAllBlocks
? workspace
: Blockly.getMainWorkspace();
if (!ws || !ws.getAllBlocks) {
throw new Error("No valid workspace found");
}
let usedModels = Blockly.Variables.allUsedVarModels(ws);
let allModels = ws.getVariableMap().getAllVariables();
for (const model of allModels) {
if (!usedModels.find((element) => element.getId() === model.getId())) {
ws.deleteVariableById(model.getId());
}
}
const json = Blockly.serialization.workspaces.save(ws);
const jsonString = JSON.stringify(json, null, 2);
// Custom MIME type for Flock project files
const FLOCK_MIME = "application/vnd.flock+json";
const FLOCK_EXT = ".flock";
if ("showSaveFilePicker" in window) {
const options = {
suggestedName: `${projectName}${FLOCK_EXT}`,
types: [
{
description: translate("project_file_description"),
accept: {
[FLOCK_MIME]: [FLOCK_EXT],
},
},
],
};
const fileHandle = await window.showSaveFilePicker(options);
const writable = await fileHandle.createWritable();
await writable.write(jsonString);
await writable.close();
currentFileHandle = fileHandle;
} else {
const blob = new Blob([jsonString], { type: FLOCK_MIME });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${projectName}${FLOCK_EXT}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
} catch (e) {
console.error("Error exporting project:", e);
}
}
// Autosave to the last explicitly-saved file handle (no picker shown)
export async function autoSaveToFile(workspace) {
if (!currentFileHandle) return;
try {
const ws =
workspace && workspace.getAllBlocks
? workspace
: Blockly.getMainWorkspace();
if (!ws || !ws.getAllBlocks) return;
const json = Blockly.serialization.workspaces.save(ws);
const jsonString = JSON.stringify(json, null, 2);
const writable = await currentFileHandle.createWritable();
await writable.write(jsonString);
await writable.close();
} catch (e) {
console.error("Error during file autosave:", e);
}
}
// Function to import snippet from file
export function importSnippet() {
const fileInput = document.getElementById("importFile");
fileInput.click();
fileInput.onchange = (event) => {
const file = event.target.files[0];
if (!file) return;
const maxSize = 5 * 1024 * 1024;
if (file.size > maxSize) {
console.error("Snippet file is too large:", file.size);
event.target.value = "";
return;
}
const fileType = file.type;
const fileName = file.name.toLowerCase();
// Custom MIME for Flock snippets (matches exportBlockSnippet)
const FLOCK_SNIP_MIME = "application/vnd.flock-snippet+json";
const reader = new FileReader();
reader.onload = () => {
const content = reader.result;
if (fileType === "image/png") {
handlePNGImport(content);
} else if (
fileType === "application/json" ||
fileType === FLOCK_SNIP_MIME ||
fileName.endsWith(".fsnip")
) {
// Treat .fsnip the same as JSON snippets
handleJSONImport(content);
} else {
console.error("Unsupported file type:", fileType || "(none)");
}
// Allow re-selecting the same file
event.target.value = "";
};
if (fileType === "image/png") {
reader.readAsArrayBuffer(file);
} else {
reader.readAsText(file);
}
};
}
// Handle PNG import
function handlePNGImport(content) {
try {
const arrayBuffer = new Uint8Array(content);
const encodedMetadata = getMetadata(arrayBuffer, "blockJson");
if (!encodedMetadata) {
console.error("No metadata found in the PNG file.");
return;
}
const decodedMetadata = JSON.parse(decodeURIComponent(encodedMetadata));
const validatedBlocks = validateSnippetBlocks(decodedMetadata);
const workspace = Blockly.getMainWorkspace();
appendSnippetBlocksAtViewport(workspace, validatedBlocks);
} catch (error) {
console.error("Error processing PNG metadata:", error);
}
}
// Handle JSON import
function handleJSONImport(content) {
try {
const blockJson = JSON.parse(content);
const validatedBlocks = validateSnippetBlocks(blockJson);
const workspace = Blockly.getMainWorkspace();
appendSnippetBlocksAtViewport(workspace, validatedBlocks);
} catch (error) {
console.error("Error processing JSON file:", error);
}
}
// Validate snippet content before appending to the workspace
function validateSnippetBlocks(snippetData) {
if (!snippetData) {
throw new Error("Snippet data is empty or undefined");
}
// Support both raw block JSON and wrapped workspace snippets
const blocks =
snippetData?.blocks?.blocks ??
(Array.isArray(snippetData) ? snippetData : [snippetData]);
const wrappedWorkspace = {
blocks: {
blocks,
},
};
const validated = validateBlocklyJson(wrappedWorkspace);
return validated.blocks.blocks;
}
function appendSnippetBlocksAtViewport(workspace, blocksJson) {
// Capture the set of existing top blocks so we can detect new ones.
const before = new Set(workspace.getTopBlocks(false).map((b) => b.id));
// Append
blocksJson.forEach((b) => Blockly.serialization.blocks.append(b, workspace));
// Collect the newly created top blocks
const created = workspace
.getTopBlocks(false)
.filter((b) => !before.has(b.id));
if (!created.length) return;
// Place them near the current viewport top-left, with a stagger.
const m = workspace.getMetrics();
const baseX = m.viewLeft + 40;
const baseY = m.viewTop + 40;
created.forEach((b, i) => {
// If the block had x/y, keep it. If not, move it.
// (Many snippets won't have x/y, so they'll move.)
b.moveBy(baseX + i * 40, baseY + i * 40);
});
}
// Private helper: process a project file (used by file input and drag-and-drop)
function processProjectFileDrop(file, workspace, executeCallback) {
console.log("[workspace-import:start]", {
fileName: file?.name ?? null,
fileSize: file?.size ?? null,
workspaceId: workspace?.id ?? null,
});
const maxSize = 5 * 1024 * 1024;
if (file.size > maxSize) {
alert(translate("file_too_large_alert"));
return;
}
const lowerName = file.name.toLowerCase();
if (!lowerName.endsWith(".json") && !lowerName.endsWith(".flock")) {
alert(translate("invalid_filetype_alert"));
return;
}
const reader = new FileReader();
reader.onload = function () {
window.loadingCode = true;
try {
const text = reader.result;
if (typeof text !== "string") {
throw new Error("File content is invalid (not a string)");
}
if (text.length > 4 * 1024 * 1024) {
throw new Error("File content is too large");
}
const json = JSON.parse(text);
if (
!json ||
typeof json !== "object" ||
!json.blocks ||
typeof json.blocks !== "object" ||
!json.blocks.blocks
) {
throw new Error("Invalid Blockly project file structure");
}
document.getElementById("projectName").value =
getSafeImportedFileBaseName(file.name);
clearFileHandle();
loadWorkspaceAndExecute(json, workspace, executeCallback);
} catch (e) {
console.error("Error loading Blockly project:", e);
alert(translate("invalid_project_alert"));
window.loadingCode = false;
}
};
reader.onerror = function () {
alert(translate("failed_to_read_file_alert"));
window.loadingCode = false;
};
reader.readAsText(file);
}
// Private helper: process a dropped snippet or PNG file
function processSnippetFileDrop(file) {
const reader = new FileReader();
reader.onload = () => {
const content = reader.result;
if (file.type === "image/png") {
handlePNGImport(content);
} else {
handleJSONImport(content);
}
};
if (file.type === "image/png") {
reader.readAsArrayBuffer(file);
} else {
reader.readAsText(file);
}
}
// Set up drag-and-drop for .flock, .json, .fsnip, and .png files
export function setupDragAndDrop(workspace, executeCallback) {
// Create the drop overlay
const overlay = document.createElement("div");
overlay.id = "drag-drop-overlay";
overlay.setAttribute("aria-hidden", "true");
overlay.textContent = translate("drag_drop_hint");
document.body.appendChild(overlay);
let dragCounter = 0;
let isDraggingFromPage = false;
document.addEventListener("dragstart", () => {
isDraggingFromPage = true;
});
document.addEventListener("dragend", () => {
isDraggingFromPage = false;
});
function isFileDrag(e) {
if (isDraggingFromPage) return false;
return (
e.dataTransfer?.types &&
Array.from(e.dataTransfer.types).includes("Files")
);
}
document.addEventListener("dragenter", (e) => {
if (!isFileDrag(e)) return;
e.preventDefault();
dragCounter++;
overlay.classList.add("visible");
});
document.addEventListener("dragover", (e) => {
if (!isFileDrag(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
});
document.addEventListener("dragleave", (e) => {
if (!isFileDrag(e)) return;
dragCounter = Math.max(0, dragCounter - 1);
if (dragCounter === 0) {
overlay.classList.remove("visible");
}
});
document.addEventListener("drop", (e) => {
dragCounter = 0;
overlay.classList.remove("visible");
const files = e.dataTransfer?.files;
if (!files || files.length === 0) return;
e.preventDefault();
e.stopPropagation();
const file = files[0];
const lowerName = file.name.toLowerCase();
if (lowerName.endsWith(".flock") || lowerName.endsWith(".json")) {
processProjectFileDrop(file, workspace, executeCallback);
} else if (lowerName.endsWith(".fsnip") || file.type === "image/png") {
processSnippetFileDrop(file);
} else {
alert(translate("drop_unsupported_file_alert"));
}
});
}
// Function to set up file input handler
export function setupFileInput(workspace, executeCallback) {
const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", function (event) {
const file = event.target.files[0];
if (!file) return;
const maxSize = 5 * 1024 * 1024;
if (file.size > maxSize) {
alert(translate("file_too_large_alert"));
event.target.value = ""; // Reset the input
return;
}
const lowerName = file.name.toLowerCase();
if (!lowerName.endsWith(".json") && !lowerName.endsWith(".flock")) {
alert(translate("invalid_filetype_alert"));
event.target.value = ""; // Reset the input
return;
}
const reader = new FileReader();
reader.onload = function () {
window.loadingCode = true;