-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
8035 lines (6926 loc) · 331 KB
/
script.js
File metadata and controls
8035 lines (6926 loc) · 331 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
/**
* HTML Code Previewer
*
* Main application object containing all functionality for the HTML/CSS/JS previewer.
*
* STRUCTURE:
* - state: Application state (editors, files, mode, panel/order state)
* - dom: Cached DOM elements
* - constants: Configuration constants (IDs, file types, MIME types)
* - fileTypeUtils: File type detection and handling utilities
* - fileSystemUtils: Virtual file system runtime operations (path resolution, file lookup, data URLs)
* - previewScriptGenerator: Code-generation utilities — produces JS strings injected into the preview iframe
* - init(): Application initialization
* - Editor Management: initEditors(), createEditorForTextarea(), etc.
* - File Management: addNewFile(), importFile(), exportFile(), etc.
* - Preview Management: renderPreview(), toggleModal(), etc.
* - UI Management: eventManager.bindAll(), switchMode(), etc.
* - htmlGenerators: HTML generation utilities
* - notificationSystem: Toast notifications
* - assetReplacers: Asset path replacement for multi-file projects
* - consoleBridge: Console capture and logging
*
*/
const SVG_ICONS = {
// UI Action Icons
settings: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="4" x2="14" y2="4"/><line x1="2" y1="8" x2="14" y2="8"/><line x1="2" y1="12" x2="14" y2="12"/><circle cx="5" cy="4" r="1.5" fill="currentColor"/><circle cx="10" cy="8" r="1.5" fill="currentColor"/><circle cx="7" cy="12" r="1.5" fill="currentColor"/></svg>',
trash: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h10l-1 10H4L3 4z"/><path d="M1 4h14"/><path d="M6 4V2.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 .5.5V4"/><line x1="6.5" y1="7" x2="6.5" y2="11"/><line x1="9.5" y1="7" x2="9.5" y2="11"/></svg>',
package: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 1L14 4v8l-6 3L2 12V4l6-3z"/><path d="M8 8v7"/><path d="M2 4l6 4 6-4"/></svg>',
folder: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1.5 3.5h4l2 2h7v8h-13v-10z"/></svg>',
folderOpen: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1.5 3.5h4l2 2h7v2"/><path d="M1.5 13.5l2-6h12l-2 6h-12z"/></svg>',
folderTabs: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1.5 3.5h4l2 2h7v8h-13v-10z"/><path d="M5 3.5V1.5h4v2"/></svg>',
clipboard: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="2.5" width="10" height="12" rx="1"/><path d="M5.5 2.5V2a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 .5.5v.5"/><line x1="5.5" y1="7" x2="10.5" y2="7"/><line x1="5.5" y1="9.5" x2="10.5" y2="9.5"/><line x1="5.5" y1="12" x2="8.5" y2="12"/></svg>',
document: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h5.5L13 5v9.5H4V1.5z"/><path d="M9 1.5v4h4"/></svg>',
search: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6.5" cy="6.5" r="4.5"/><line x1="10" y1="10" x2="14.5" y2="14.5"/></svg>',
format: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="13" x2="10" y2="2"/><path d="M10 2l1.5 3"/><path d="M1 6l2-2 2 2"/><circle cx="12.5" cy="3.5" r="0.75" fill="currentColor" stroke="none"/></svg>',
expand: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="10,2 14,2 14,6"/><polyline points="6,14 2,14 2,10"/><line x1="14" y1="2" x2="9.5" y2="6.5"/><line x1="2" y1="14" x2="6.5" y2="9.5"/></svg>',
save: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 1.5h9.5L14 4v10.5H2V1.5z"/><rect x="4.5" y="1.5" width="5" height="4"/><rect x="4.5" y="9.5" width="7" height="5"/></svg>',
close: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="3" x2="13" y2="13"/><line x1="13" y1="3" x2="3" y2="13"/></svg>',
dock: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="1.5" y="2" width="13" height="12" rx="1"/><line x1="10" y1="2" x2="10" y2="14"/></svg>',
refresh: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 3v4H9"/><path d="M3 13v-4h4"/><path d="M4.1 6.1A5 5 0 0 1 13 7"/><path d="M11.9 9.9A5 5 0 0 1 3 9"/></svg>',
eye: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z"/><circle cx="8" cy="8" r="2"/></svg>',
pencil: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M11.5 1.5l3 3-9 9H2.5v-3l9-9z"/></svg>',
move: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="8" x2="14" y2="8"/><polyline points="10,4 14,8 10,12"/></svg>',
check: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3,8.5 6.5,12 13,4"/></svg>',
checkCircle: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6.5"/><polyline points="5,8.5 7,10.5 11,5.5"/></svg>',
xCircle: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6.5"/><line x1="5.5" y1="5.5" x2="10.5" y2="10.5"/><line x1="10.5" y1="5.5" x2="5.5" y2="10.5"/></svg>',
info: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="7.5" x2="8" y2="11.5"/><circle cx="8" cy="5" r="0.75" fill="currentColor" stroke="none"/></svg>',
warning: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 1.5L1 14h14L8 1.5z"/><line x1="8" y1="6" x2="8" y2="10"/><circle cx="8" cy="12" r="0.75" fill="currentColor" stroke="none"/></svg>',
folderPlus: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1.5 3.5h4l2 2h7v8h-13v-10z"/><line x1="8" y1="7.5" x2="8" y2="11.5"/><line x1="6" y1="9.5" x2="10" y2="9.5"/></svg>',
folderMinus: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1.5 3.5h4l2 2h7v8h-13v-10z"/><line x1="6" y1="9.5" x2="10" y2="9.5"/></svg>',
// File Type Icons
fileHtml: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6.5"/><ellipse cx="8" cy="8" rx="3" ry="6.5"/><path d="M1.5 8h13"/></svg>',
fileCss: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 14l-1-4 3-2-3-2 1-4"/><circle cx="12" cy="4" r="2"/><line x1="12" y1="6" x2="12" y2="12"/><path d="M10 12a2 2 0 1 0 4 0"/></svg>',
fileJs: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="4,4 1.5,8 4,12"/><polyline points="12,4 14.5,8 12,12"/></svg>',
fileJson: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 2c-2 0-2 2-2 3v1.5c0 1-1 1.5-1.5 1.5 .5 0 1.5.5 1.5 1.5V11c0 1 0 3 2 3"/><path d="M11 2c2 0 2 2 2 3v1.5c0 1 1 1.5 1.5 1.5-.5 0-1.5.5-1.5 1.5V11c0 1 0 3-2 3"/></svg>',
fileXml: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h5.5L13 5v9.5H4V1.5z"/><path d="M9 1.5v4h4"/><polyline points="6,9 5,11 6,13"/><polyline points="10,9 11,11 10,13"/></svg>',
fileMarkdown: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h5.5L13 5v9.5H4V1.5z"/><path d="M9 1.5v4h4"/><path d="M6.5 9v4h1v-2.5L9 12l1.5-1.5V13h1V9"/></svg>',
fileText: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h5.5L13 5v9.5H4V1.5z"/><path d="M9 1.5v4h4"/><line x1="6" y1="8" x2="11" y2="8"/><line x1="6" y1="10.5" x2="11" y2="10.5"/><line x1="6" y1="13" x2="9" y2="13"/></svg>',
fileImage: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="1.5" y="2" width="13" height="12" rx="1"/><circle cx="5" cy="5.5" r="1.5"/><path d="M1.5 12l4-4 3 3 2-2 4 4"/></svg>',
fileAudio: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 6v4h3l4 3V3L5 6H2z"/><path d="M11 5.5a3.5 3.5 0 0 1 0 5"/><path d="M12.5 3.5a6 6 0 0 1 0 9"/></svg>',
fileVideo: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="1.5" y="3" width="13" height="10" rx="1"/><path d="M6 6.5v3l3-1.5-3-1.5z"/></svg>',
fileFont: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14l4-12 4 12"/><line x1="5.5" y1="10" x2="10.5" y2="10"/><line x1="3" y1="14" x2="5" y2="14"/><line x1="11" y1="14" x2="13" y2="14"/></svg>',
filePdf: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h5.5L13 5v9.5H4V1.5z"/><path d="M9 1.5v4h4"/><path d="M6 9h1.5a1.25 1.25 0 0 0 0-2.5H6v6"/></svg>',
fileBinary: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 1L14 4v8l-6 3L2 12V4l6-3z"/><path d="M8 8v7"/><path d="M2 4l6 4 6-4"/></svg>',
};
// ============================================================================
// STANDALONE UTILITY FUNCTIONS
// Pure functions with no dependency on CodePreviewer instance.
// ============================================================================
const escapeHtml = (str) => {
if (str === null || str === undefined) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
const base64ToUint8Array = (base64) => {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
};
const formatFileSize = (bytes) => {
const normalized = Number.isFinite(bytes) && bytes >= 0 ? bytes : 0;
if (normalized < 1024) return `${normalized} B`;
const units = ['KB', 'MB', 'GB'];
let size = normalized;
let unitIndex = -1;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex += 1;
}
const roundedSize = size >= 10 ? Math.round(size) : Math.round(size * 10) / 10;
return `${roundedSize} ${units[unitIndex]}`;
};
const getLineCount = (content) => {
return content.length === 0 ? 1 : content.split(/\r\n|\r|\n/).length;
};
function createMockEditor(textarea, fontSize) {
if (!textarea) return null;
Object.assign(textarea.style, {
fontFamily: 'monospace', fontSize: `${fontSize}px`, lineHeight: '1.5',
resize: 'none', border: 'none', outline: 'none',
background: '#282a36', color: '#f8f8f2', padding: '1rem',
width: '100%', height: '400px'
});
return {
setValue: (value) => { textarea.value = value; },
getValue: () => textarea.value,
refresh: () => {},
setOption: () => {},
on: (eventName, handler) => {
if (eventName !== 'change' || !handler) return;
if (textarea.__changeListener) {
textarea.removeEventListener('input', textarea.__changeListener);
}
textarea.__changeListener = () => handler(null, { origin: '+input' });
textarea.addEventListener('input', textarea.__changeListener);
},
};
}
function findNextMatch(content, query, startIndex) {
if (!content || !query) return -1;
const lowerContent = content.toLowerCase();
const lowerQuery = query.toLowerCase();
let matchIndex = lowerContent.indexOf(lowerQuery, startIndex);
if (matchIndex === -1 && startIndex > 0) {
matchIndex = lowerContent.indexOf(lowerQuery);
}
return matchIndex;
}
/**
* Recursively freezes an object and all its nested objects.
* @param {Object} obj - The object to deep-freeze
* @returns {Object} The frozen object
*/
const deepFreeze = (obj) => {
Object.freeze(obj);
Object.values(obj).forEach(val => {
if (val && typeof val === 'object' && !Object.isFrozen(val)) {
deepFreeze(val);
}
});
return obj;
};
/**
* Handles preview rendering concerns such as debouncing and runtime fallback UI.
*/
class PreviewRenderer {
/**
* @param {typeof CodePreviewer} app
*/
constructor(app) {
this.app = app;
}
/**
* Debounce preview refresh requests to reduce expensive iframe updates while typing.
*/
scheduleRefresh() {
const { state } = this.app;
clearTimeout(state.previewRefreshTimer);
state.previewRefreshTimer = setTimeout(() => {
state.previewRefreshTimer = null;
this.safeRefreshOpenPreviews();
}, state.previewRefreshDelay);
}
/**
* Triggers a preview render to the requested target.
* Validates HTML availability before proceeding.
* @param {'modal'|'tab'} target - Where to display the preview
*/
render(target) {
const availability = this.app.getPreviewAvailability();
if (!availability.allowed) {
this.app.showNotification('No HTML file found. Import or create an HTML file to preview.', 'warn');
this.app.updatePreviewActionButtons();
return;
}
// Always revoke previous asset URLs before generating new ones to avoid leaks.
this.app.revokeTrackedObjectUrls(this.app.state.previewAssetUrls);
this.app.state.previewBlobUrlCache.clear();
const content = this.app.generatePreviewContent();
if (target === 'modal') {
this.app.consoleBridge.clear();
this.safeWritePreviewFrame(content);
this.app.toggleModal(true);
return;
}
if (target === 'tab') {
try {
this.app.updatePreviewTab(content, true);
this.app.showNotification('Preview opened in a new tab.', 'success');
} catch (error) {
console.error('Failed to create or open new tab:', error);
this.app.showNotification('Unable to open preview tab. Check popup settings and try again.', 'error');
}
}
}
/**
* Safely refresh already-open preview targets (modal and/or tab).
* On failure, writes an error document to the iframe instead of silently breaking.
*/
safeRefreshOpenPreviews() {
try {
this.app.refreshOpenPreviews();
} catch (error) {
console.error('Preview refresh failed:', error);
this.app.showNotification('Preview refresh failed. The editor content is unchanged.', 'error');
this.safeWritePreviewFrame(this.buildPreviewErrorDocument(error));
}
}
/**
* Writes an HTML string to the preview iframe's srcdoc.
* On failure, replaces the content with a formatted error document.
* @param {string} content - Complete HTML document string
*/
safeWritePreviewFrame(content) {
if (!this.app.dom.previewFrame) return;
try {
this.app.dom.previewFrame.srcdoc = content;
} catch (error) {
console.error('Unable to render preview iframe:', error);
this.app.dom.previewFrame.srcdoc = this.buildPreviewErrorDocument(error);
this.app.showNotification('Unable to render preview content. See details in preview pane.', 'error');
}
}
/**
* Builds a self-contained HTML error document for display inside the preview iframe.
* @param {unknown} error - The caught error value
* @returns {string} A minimal HTML document string
*/
buildPreviewErrorDocument(error) {
const errorText = escapeHtml(error instanceof Error ? error.message : String(error));
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Preview Error</title></head><body style="font-family:Arial,sans-serif;background:#121219;color:#f8f8ff;padding:16px;"><h2 style="margin-top:0;">Preview rendering error</h2><p>The preview could not be generated safely.</p><pre style="white-space:pre-wrap;background:#1d1f2e;padding:12px;border-radius:8px;border:1px solid #34364d;">${errorText}</pre></body></html>`;
}
}
/**
* Persists and restores user preferences via localStorage.
* All I/O is wrapped in try/catch so a corrupt or missing entry never
* prevents the application from starting.
*/
class StorageHandler {
/**
* @param {typeof CodePreviewer} app
*/
constructor(app) {
this.app = app;
}
/**
* Reads settings from localStorage and merges them into the current state.
* Silently ignores missing, malformed, or unreadable data.
* @returns {void}
*/
loadSettings() {
try {
const raw = localStorage.getItem(this.app.constants.SETTINGS_STORAGE_KEY);
if (!raw) return;
const parsed = JSON.parse(raw);
this.app.state.settings = this.app.normalizeSettings({
...this.app.state.settings,
...parsed,
});
} catch (error) {
console.warn('Unable to load settings:', error);
}
}
/**
* Serializes the current settings object to localStorage.
* Silently ignores QuotaExceededError and other write failures.
* @returns {void}
*/
saveSettings() {
try {
localStorage.setItem(
this.app.constants.SETTINGS_STORAGE_KEY,
JSON.stringify(this.app.state.settings)
);
} catch (error) {
console.warn('Unable to save settings:', error);
}
}
}
class EventManager {
/**
* @param {typeof CodePreviewer} app
*/
constructor(app) {
this.app = app;
}
/**
* Entry point — wires every category of events.
* Called once during init().
*/
bindAll() {
this.bindPrimaryActions();
this.bindConsoleActions();
this.bindPreviewDock();
this.bindModalOverlay();
this.bindKeyboard();
this.bindCodeModal();
this.bindMediaModal();
this.bindFileActions();
this.bindSettingsModal();
this.bindViewportResize();
}
// ─── Preview ──────────────────────────────────────────────────────────────
/**
* Binds the primary preview action buttons (modal / tab).
*/
bindPrimaryActions() {
this.app.dom.modalBtn.addEventListener('click', () => this.app.renderPreview('modal'));
this.app.dom.tabBtn.addEventListener('click', () => this.app.renderPreview('tab'));
this.app.dom.closeModalBtn.addEventListener('click', () => this.app.toggleModal(false));
this.app.dom.refreshPreviewBtn?.addEventListener('click', () => this.app.refreshModalPreview());
}
// ─── Console ──────────────────────────────────────────────────────────────
/**
* Binds console toggle button and console resize divider.
*/
bindConsoleActions() {
this.app.dom.toggleConsoleBtn.addEventListener('click', () => this.app.toggleConsole());
this.app.dom.consoleResizeDivider?.addEventListener(
'pointerdown',
(e) => this.app.startConsoleResize(e)
);
}
// ─── Preview Dock ─────────────────────────────────────────────────────────
/**
* Binds dock toggle and resize-divider drag events.
*/
bindPreviewDock() {
this.app.dom.dockPreviewBtn?.addEventListener('click', () => this.app.togglePreviewDock());
this.app.dom.previewDockDivider?.addEventListener(
'pointerdown',
(e) => this.app.startPreviewDockResize(e)
);
}
// ─── Modal Overlay ────────────────────────────────────────────────────────
/**
* Closes the preview modal when the backdrop is clicked (undocked mode only).
*/
bindModalOverlay() {
this.app.dom.modalOverlay.addEventListener('click', (e) => {
if (this.app.state.isPreviewDocked) return;
if (e.target === this.app.dom.modalOverlay) this.app.toggleModal(false);
});
}
// ─── Global Keyboard ──────────────────────────────────────────────────────
/**
* Binds application-wide keyboard shortcuts.
*/
bindKeyboard() {
document.addEventListener('keydown', (e) => {
const { app } = this;
const activePanel = app.getActiveEditorPanel();
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
app.renderPreview('modal');
return;
}
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === 'k') {
e.preventDefault();
app.focusSidebarSearch();
return;
}
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === 'f') {
const codeModal = app.dom.codeModal;
const isCodeModalOpen = codeModal?.getAttribute('aria-hidden') === 'false';
if (isCodeModalOpen) {
e.preventDefault();
app.openCodeModalSearch();
} else if (activePanel) {
e.preventDefault();
app.openPanelSearch(activePanel);
}
return;
}
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'e' && activePanel) {
e.preventDefault();
app.expandCode(activePanel);
return;
}
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'f' && activePanel) {
e.preventDefault();
app.formatPanelCode(activePanel, false);
return;
}
if (e.key === 'Escape') {
if (app.dom.modalOverlay.getAttribute('aria-hidden') === 'false') {
app.toggleModal(false);
}
app.toggleSettingsModal(false);
if (app.dom.codeModal?.getAttribute('aria-hidden') === 'false') {
app.closeCodeModal();
}
if (app.dom.mediaModal?.getAttribute('aria-hidden') === 'false') {
app.closeMediaModal();
}
}
});
}
// ─── Code Modal ───────────────────────────────────────────────────────────
/**
* Binds code-view modal close and search actions.
*/
bindCodeModal() {
const { app } = this;
const codeModalCloseBtn = app.dom.codeModal?.querySelector('.close-btn');
if (codeModalCloseBtn) {
codeModalCloseBtn.addEventListener('click', () => app.closeCodeModal());
}
if (app.dom.codeModal) {
app.dom.codeModal.addEventListener('click', (e) => {
if (e.target === app.dom.codeModal) app.closeCodeModal();
});
}
if (app.dom.codeModalDockBtn) {
app.dom.codeModalDockBtn.addEventListener('click', () => app.toggleCodeModalDockLeft());
}
if (app.dom.codeModalSearchBtn) {
app.dom.codeModalSearchBtn.addEventListener('click', () => app.toggleCodeModalSearch());
}
if (app.dom.codeModalSearchInput) {
app.dom.codeModalSearchInput.addEventListener('input', () => app.searchInCodeModal(false));
app.dom.codeModalSearchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
app.searchInCodeModal(true);
}
});
}
if (app.dom.codeModalSearchNextBtn) {
app.dom.codeModalSearchNextBtn.addEventListener('click', () => app.searchInCodeModal(true));
}
if (app.dom.codeModalSearchCloseBtn) {
app.dom.codeModalSearchCloseBtn.addEventListener('click', () => app.closeCodeModalSearch());
}
}
// ─── Media Modal ──────────────────────────────────────────────────────────
/**
* Binds media preview modal close action.
*/
bindMediaModal() {
const { app } = this;
const mediaModalCloseBtn = app.dom.mediaModal?.querySelector('.close-btn');
if (mediaModalCloseBtn) {
mediaModalCloseBtn.addEventListener('click', () => app.closeMediaModal());
}
if (app.dom.mediaModal) {
app.dom.mediaModal.addEventListener('click', (e) => {
if (e.target === app.dom.mediaModal) app.closeMediaModal();
});
}
}
// ─── File Actions ─────────────────────────────────────────────────────────
/**
* Binds file management toolbar buttons (add, import, export, clear).
*/
bindFileActions() {
const { app } = this;
app.dom.addFileBtn.addEventListener('click', () => app.addNewFile());
app.dom.addFolderBtn?.addEventListener('click', () => app.addNewFolder());
app.dom.clearAllFilesBtn?.addEventListener('click', () => app.clearAllFiles());
app.dom.importFileBtn.addEventListener('click', () => app.importFile());
app.dom.importFolderBtn?.addEventListener('click', () => app.importFolder());
app.dom.importZipBtn.addEventListener('click', () => app.importArchive());
app.dom.exportZipBtn.addEventListener('click', () => app.exportZip());
app.setupMainHtmlDropdownEvents();
// Close custom dropdowns when clicking outside their boundaries
document.addEventListener('click', (e) => {
if (!e.target.closest('.file-type-dropdown')) app.closeAllFileTypeDropdowns();
if (!e.target.closest('.settings-select-dropdown')) app.closeAllSettingsSelectDropdowns();
});
}
// ─── Settings Modal ───────────────────────────────────────────────────────
/**
* Binds settings button, settings modal close/backdrop, and all setting controls.
* Uses a declarative binding table to eliminate repetitive handler blocks.
*/
bindSettingsModal() {
const { app } = this;
app.dom.settingsBtn?.addEventListener('click', () => app.toggleSettingsModal(true));
if (!app.dom.settingsModal) return;
// Close on backdrop click
app.dom.settingsModal.addEventListener('click', (e) => {
if (e.target === app.dom.settingsModal) app.toggleSettingsModal(false);
});
// Custom dropdown: open/select
app.dom.settingsModal.addEventListener('click', (e) => {
const trigger = e.target.closest('.settings-select-dropdown-trigger');
if (trigger) {
app.toggleSettingsSelectDropdown(trigger.closest('.settings-select-dropdown'));
return;
}
const option = e.target.closest('.settings-select-dropdown-option');
if (option) {
app.selectSettingsDropdownOption(option.closest('.settings-select-dropdown'), option);
}
});
// Custom dropdown: keyboard navigation
app.dom.settingsModal.addEventListener('keydown', (e) => {
const dropdown = e.target.closest('.settings-select-dropdown');
if (!dropdown) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
app.toggleSettingsSelectDropdown(dropdown, true);
app.moveSettingsDropdownFocus(dropdown, 1);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
app.toggleSettingsSelectDropdown(dropdown, true);
app.moveSettingsDropdownFocus(dropdown, -1);
} else if (e.key === 'Enter' || e.key === ' ') {
const option = e.target.closest('.settings-select-dropdown-option');
if (option) {
e.preventDefault();
app.selectSettingsDropdownOption(dropdown, option);
} else if (e.target.closest('.settings-select-dropdown-trigger')) {
e.preventDefault();
app.toggleSettingsSelectDropdown(dropdown);
}
}
});
// Close button
const settingsCloseBtn = app.dom.settingsModal.querySelector('.close-btn');
if (settingsCloseBtn) {
settingsCloseBtn.addEventListener('click', () => app.toggleSettingsModal(false));
}
// ESC to close (registered once on document to avoid duplicates)
if (!app.state.settingsEscHandler) {
app.state.settingsEscHandler = (e) => {
if (e.key === 'Escape' && app.isSettingsModalOpen()) {
const hasOpenDropdown = !!app.dom.settingsModal?.querySelector(
'.settings-select-dropdown-trigger[aria-expanded="true"]'
);
if (hasOpenDropdown) {
app.closeAllSettingsSelectDropdowns();
return;
}
app.toggleSettingsModal(false);
}
};
document.addEventListener('keydown', app.state.settingsEscHandler);
}
this._bindSettingControls();
}
/**
* Declarative table-driven binding for individual setting controls.
* Each entry maps a DOM element to a state property and a value reader.
* This replaces nine near-identical if-block handlers.
* @private
*/
_bindSettingControls() {
const { app } = this;
/** @type {Array<{domKey: string, stateKey: string, readValue: function, refreshEditors?: boolean}>} */
const SETTING_BINDINGS = [
{ domKey: 'settingLineNumbers', stateKey: 'lineNumbers', readValue: (el) => el.checked, refreshEditors: true },
{ domKey: 'settingLineWrap', stateKey: 'lineWrapping', readValue: (el) => el.checked, refreshEditors: true },
{ domKey: 'settingAutoFormat', stateKey: 'autoFormatOnType', readValue: (el) => el.checked, refreshEditors: false },
{ domKey: 'settingFontSize', stateKey: 'fontSize', readValue: (el) => Number(el.value) || 14, refreshEditors: true },
{ domKey: 'settingEditorTheme', stateKey: 'theme', readValue: (el) => el.value || 'dracula', refreshEditors: true },
{ domKey: 'settingTabSize', stateKey: 'tabSize', readValue: (el) => Number(el.value) || 4, refreshEditors: true },
{ domKey: 'settingIndentWithTabs', stateKey: 'indentWithTabs', readValue: (el) => el.checked, refreshEditors: true },
{ domKey: 'settingAutoCloseBrackets', stateKey: 'autoCloseBrackets', readValue: (el) => el.checked, refreshEditors: true },
{ domKey: 'settingMatchBrackets', stateKey: 'matchBrackets', readValue: (el) => el.checked, refreshEditors: true },
];
const applySetting = (updateFn, { refreshEditors = false } = {}) => {
updateFn();
app.state.settings = app.normalizeSettings(app.state.settings);
app.syncSettingsUI();
if (refreshEditors) app.applyEditorSettingsToAllEditors();
app.saveSettings();
};
SETTING_BINDINGS.forEach(({ domKey, stateKey, readValue, refreshEditors }) => {
const el = app.dom[domKey];
if (!el) return;
el.addEventListener('change', () => {
applySetting(() => { app.state.settings[stateKey] = readValue(el); }, { refreshEditors });
});
});
}
// ─── Viewport Resize ──────────────────────────────────────────────────────
/**
* Registers debounced window-resize and visualViewport-resize handlers.
* Guards against duplicate registration.
*/
bindViewportResize() {
const { app } = this;
if (!app.state.viewportResizeHandler) {
app.state.viewportResizeHandler = () => {
clearTimeout(app.state.viewportResizeTimer);
app.state.viewportResizeTimer = setTimeout(() => {
app.updatePanelMoveButtonDirections();
app.updateCodeModalHeaderAndButtons();
app.updateAdaptiveLayoutMode();
app.updateDockedModalCompactModes();
}, 80);
};
// A single named handler avoids creating a second anonymous wrapper for dock resize.
const onWindowResize = () => {
app.state.viewportResizeHandler();
app.handleDockViewportResize();
};
window.addEventListener('resize', onWindowResize);
}
if (!app.state.visualViewportResizeHandler && window.visualViewport) {
app.state.visualViewportResizeHandler = () => {
app.updatePreviewViewportHeight();
app.handleDockViewportResize();
};
window.visualViewport.addEventListener('resize', app.state.visualViewportResizeHandler);
window.visualViewport.addEventListener('scroll', app.state.visualViewportResizeHandler);
}
}
}
class FileTypeUtils {
constructor(constants) {
this.constants = constants;
this.BINARY_MIME_PREFIXES = ['image/', 'audio/', 'video/', 'application/', 'font/'];
this.JS_MIME_TYPES = new Set(['text/javascript', 'application/javascript', 'application/x-javascript', 'text/ecmascript', 'application/ecmascript']);
this.MODULE_FILENAME_SUFFIXES = ['.mjs', '.esm.js', '.module.js'];
}
getBaseName(filename) {
if (typeof filename !== 'string') return '';
const normalizedPath = filename.trim().replace(/\\/g, '/');
if (!normalizedPath) return '';
const pathSegments = normalizedPath.split('/');
return (pathSegments.pop() || '').toLowerCase();
}
getExtension(filename) {
const baseName = this.getBaseName(filename);
if (!baseName || baseName === '.' || baseName === '..') return '';
const lastDotIndex = baseName.lastIndexOf('.');
if (lastDotIndex === -1) return '';
if (lastDotIndex === 0) return baseName.slice(1).toLowerCase();
return baseName.slice(lastDotIndex + 1).toLowerCase();
}
normalizeMimeType(mimeType) {
if (!mimeType || typeof mimeType !== 'string') return '';
return mimeType.toLowerCase().split(';')[0].trim();
}
getTypeFromExtension(filename) {
const extension = this.getExtension(filename);
return this.constants.EXTENSIONS[extension] || 'binary';
}
getMimeTypeFromExtension(extension) {
const normalizedExtension = extension?.toLowerCase();
return this.constants.EXTENSION_MIME_MAP[normalizedExtension] || 'application/octet-stream';
}
getMimeTypeFromFileType(fileType) {
return this.constants.MIME_TYPES[fileType] || 'text/plain';
}
getTypeFromMimeType(mimeType) {
const normalizedMimeType = this.normalizeMimeType(mimeType);
if (!normalizedMimeType) return null;
if (this.JS_MIME_TYPES.has(normalizedMimeType)) return 'javascript';
if (normalizedMimeType === 'text/html') return 'html';
if (normalizedMimeType === 'text/css') return 'css';
if (normalizedMimeType === 'application/json' || normalizedMimeType.endsWith('+json')) return 'json';
if (normalizedMimeType === 'application/xml' || normalizedMimeType === 'text/xml') return 'xml';
if (normalizedMimeType === 'text/markdown') return 'markdown';
if (normalizedMimeType === 'image/svg+xml') return 'svg';
if (normalizedMimeType.startsWith('image/')) return 'image';
if (normalizedMimeType.startsWith('audio/')) return 'audio';
if (normalizedMimeType.startsWith('video/')) return 'video';
if (normalizedMimeType.startsWith('font/')) return 'font';
if (normalizedMimeType === 'application/pdf') return 'pdf';
if (normalizedMimeType.startsWith('text/')) return 'text';
return null;
}
hasBinaryMimePrefix(mimeType) {
return this.BINARY_MIME_PREFIXES.some(prefix => mimeType.startsWith(prefix));
}
isBinaryExtension(extension) {
return this.constants.BINARY_EXTENSIONS.has(extension?.toLowerCase());
}
isJavaScriptMimeType(mimeType) {
return this.JS_MIME_TYPES.has(this.normalizeMimeType(mimeType));
}
hasModuleFilenameHint(filename) {
if (!filename || typeof filename !== 'string') return false;
const lowerName = filename.toLowerCase();
return this.MODULE_FILENAME_SUFFIXES.some(suffix => lowerName.endsWith(suffix));
}
hasModuleMimeHint(mimeType) {
return typeof mimeType === 'string' && /(?:^|;)\s*module(?:\s*=\s*(?:1|true))?\s*(?:;|$)/i.test(mimeType);
}
isJavaScriptModule(content, filename, mimeType) {
if (this.hasModuleFilenameHint(filename) || this.hasModuleMimeHint(mimeType)) {
return true;
}
if (!content || typeof content !== 'string') {
return false;
}
const modulePatterns = [
/^\s*import\s+/m,
/^\s*export\s+/m,
/import\s*\(/,
/export\s*\{/,
/export\s+default\s+/,
/export\s+\*/
];
return modulePatterns.some(pattern => pattern.test(content));
}
detectJavaScriptType(content, filename, mimeType) {
return this.isJavaScriptModule(content, filename, mimeType) ? 'javascript-module' : 'javascript';
}
isBinaryFile(filename, mimeType) {
if (!filename) return false;
const extension = this.getExtension(filename);
if (this.isBinaryExtension(extension)) {
return true;
}
const normalizedMimeType = this.normalizeMimeType(mimeType);
if (!normalizedMimeType) return false;
if (normalizedMimeType === 'image/svg+xml' || normalizedMimeType === 'application/json' || normalizedMimeType.endsWith('+json')) {
return false;
}
return this.hasBinaryMimePrefix(normalizedMimeType);
}
isEditableType(fileType) {
return this.constants.EDITABLE_TYPES.includes(fileType);
}
isPreviewableType(fileType) {
return this.constants.PREVIEWABLE_TYPES.includes(fileType);
}
getCodeMirrorMode(fileType) {
return this.constants.CODEMIRROR_MODES[fileType] || 'text';
}
detectTypeFromContent(content, filename, mimeType = '') {
const extensionType = this.getTypeFromExtension(filename);
if (!content) {
if (extensionType === 'javascript' || extensionType === 'javascript-module') {
return this.detectJavaScriptType(content, filename, mimeType);
}
return extensionType;
}
if (/<\s*html/i.test(content)) return 'html';
if (this.isJavaScriptModule(content, filename, mimeType)) return 'javascript-module';
if (/^\s*[\.\#\@]|\s*\w+\s*\{/m.test(content)) return 'css';
if (extensionType === 'javascript' || extensionType === 'javascript-module') {
return this.detectJavaScriptType(content, filename, mimeType);
}
return extensionType;
}
detectFileType(filename, content, mimeType) {
if (!filename) return 'text';
const extensionType = this.getTypeFromExtension(filename);
const mimeTypeType = this.getTypeFromMimeType(mimeType);
if (this.isBinaryExtension(this.getExtension(filename))) {
return extensionType === 'binary' && mimeTypeType ? mimeTypeType : extensionType;
}
if (mimeTypeType && mimeTypeType !== 'javascript') {
return mimeTypeType;
}
if (mimeTypeType === 'javascript') {
return this.detectJavaScriptType(content, filename, mimeType);
}
return this.detectTypeFromContent(content, filename, mimeType);
}
}
class FileSystemUtils {
constructor(fileTypeUtils) {
this.fileTypeUtils = fileTypeUtils;
}
/**
* Resolves a relative path against a base path
* @param {string} basePath - The base file path
* @param {string} relativePath - The relative path to resolve
* @returns {string} The resolved absolute path
*/
resolvePath(basePath, relativePath) {
// Absolute paths start fresh
if (relativePath.startsWith('/')) {
return relativePath.substring(1);
}
// Get directory portion of base path
const baseDir = basePath.includes('/')
? basePath.substring(0, basePath.lastIndexOf('/'))
: '';
const baseParts = baseDir ? baseDir.split('/') : [];
const relativeParts = relativePath.split('/');
const resultParts = [...baseParts];
for (const part of relativeParts) {
if (part === '..') {
if (resultParts.length > 0) {
resultParts.pop();
}
} else if (part !== '.' && part !== '') {
resultParts.push(part);
}
}
return resultParts.join('/');
}
/**
* Finds a file in the virtual file system
* @param {Map} fileSystem - The virtual file system map
* @param {string} targetFilename - The filename to find
* @param {string} currentFilePath - The current file context for relative paths
* @returns {Object|null} The file data or null if not found
*/
findFile(fileSystem, targetFilename, currentFilePath = '') {
if (typeof targetFilename !== 'string' || !targetFilename) {
return null;
}
// Resolve relative path if we have context
if (currentFilePath) {
targetFilename = this.resolvePath(currentFilePath, targetFilename);
} else if (targetFilename.startsWith('/')) {
// Strip leading slash for root-relative paths even without context
targetFilename = targetFilename.substring(1);
}
// Try exact match first
const exactMatch = fileSystem.get(targetFilename);
if (exactMatch) {
return exactMatch;
}
// Try case-insensitive match
const targetLower = targetFilename.toLowerCase();
for (const [filename, file] of fileSystem) {
if (filename.toLowerCase() === targetLower) {
return file;
}
}
// Try matching by filename only (without directory path)
const targetBasename = targetFilename.includes('/')
? targetFilename.substring(targetFilename.lastIndexOf('/') + 1)
: targetFilename;
if (targetBasename) {
const targetBasenameLower = targetBasename.toLowerCase();
for (const [filename, file] of fileSystem) {
const fileBasename = filename.includes('/')
? filename.substring(filename.lastIndexOf('/') + 1)
: filename;
if (fileBasename.toLowerCase() === targetBasenameLower) {
return file;
}
}
}
return null;
}
/**
* Gets a data URL for a file (handles both binary and text files)
* @param {Object} fileData - The file data object
* @param {string} defaultMimeType - Default MIME type for non-binary files
* @returns {string} The data URL or content
*/
getFileDataUrl(fileData, defaultMimeType = 'text/plain') {
if (fileData.isBinary) {
return fileData.content;
}
// Handle SVG specially
if (fileData.type === 'svg') {
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(fileData.content)}`;
}
// For other text files, create a proper data URL
const mimeType = this.fileTypeUtils.getMimeTypeFromFileType(fileData.type) || defaultMimeType;
return `data:${mimeType};charset=utf-8,${encodeURIComponent(fileData.content)}`;
}
}
class PreviewScriptGenerator {
/**