aboutsummaryrefslogtreecommitdiff
path: root/modules/ext/filemgr.js
blob: acbb963e291449184d09c6a80f51ac6bf02a436c (plain)
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
class FileManagerModule {
    constructor() {
        this.commands = {};
        this.commandsMeta = {
            'files': { argType: 'file' }, 'preview': { argType: 'file' },
        };
        this.terminal = null;
        this.currentPath = [];
        this._overlay = null;
        this._selectedFile = null;
        this._multiSelect = new Set();  // v4.5.78: multi-select for batch ops
        this._clipboard = { mode: null, paths: [] };  // 'copy' or 'cut'
        this._searchFilter = '';
        this._rawMode = false;
        this._inlineHtml = false;
    }

    requirements() {
        return { met: true, missing: [] };
    }

    getHelpInfo() {
        return {
            'files': 'files — Open the file manager overlay with VFS directory listing, preview, encrypt, zip',
            'preview': 'preview <path> — Preview a specific file',
        };
    }

    registerCommands() {
        this.commands['files'] = () => this._openOverlay();
        this.commands['preview'] = (args) => this._previewCommand(args);
    }

    _previewCommand(args) {
        if (!args[0]) return this.terminal.print('Usage: preview <path>', 'warning');
        const path = args.join(' ');
        this._openOverlay();
        this._navigateToPathFromParts(path);
        const content = this.terminal.fs.readFile(path);
        if (content === null || content === false) {
            this._renderPreviewError('File not found: ' + path);
            return;
        }
        this._selectedFile = path;
        this._renderPreview(path, content);
        this._highlightSelected();
    }

    _navigateToPathFromParts(path) {
        const parts = path.split('/').filter(p => p);
        if (parts.length <= 1) {
            this.currentPath = [];
            return;
        }
        this.currentPath = parts.slice(0, -1);
    }

    _detectType(filePath) {
        const ext = filePath.split('.').pop().toLowerCase();
        if (!ext || ext === filePath) return 'other';
        const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'ico'];
        const videoExts = ['mp4', 'webm', 'avi', 'mov', 'mkv'];
        const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'];
        const codeExts = ['js', 'py', 'css', 'yaml', 'yml', 'toml'];
        if (ext === 'md') return 'md';
        if (imageExts.includes(ext)) return 'image';
        if (videoExts.includes(ext)) return 'video';
        if (audioExts.includes(ext)) return 'audio';
        if (codeExts.includes(ext)) return 'code';
        if (ext === 'html') return 'html';
        if (ext === 'json') return 'json';
        if (ext === 'csv') return 'csv';
        if (ext === 'pdf') return 'pdf';
        if (ext === 'svg') return 'svg';
        if (ext === 'txt') return 'text';
        return 'other';
    }

    _renderMarkdown(text) {
        if (!text) return '';
        try {
            let html = text
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
            // code blocks first
            html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
            // inline code
            html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
            // headers
            html = html.replace(/^### (.+)$/gm, '<h3 style="color:var(--accent-color);margin:8px 0 4px">$1</h3>');
            html = html.replace(/^## (.+)$/gm, '<h2 style="color:var(--accent-color);margin:10px 0 4px">$1</h2>');
            html = html.replace(/^# (.+)$/gm, '<h1 style="color:var(--accent-color);margin:12px 0 6px">$1</h1>');
            // bold
            html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
            // italic
            html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
            // links — v4.5.67: sanitize URL to prevent javascript: scheme injection
            html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
                const safeUrl = /^(https?:\/\/|mailto:|\/|#)/.test(url) ? url : '#';
                return `<a href="${safeUrl}" target="_blank" style="color:var(--info-color)">${text}</a>`;
            });
            // horizontal rules
            html = html.replace(/^---$/gm, '<hr style="border-color:var(--border-color);margin:8px 0">');
            // unordered lists
            html = html.replace(/^[\s]*[-*]\s+(.+)$/gm, '<li style="margin-left:16px;list-style:disc">$1</li>');
            // paragraphs - double newlines
            html = html.replace(/\n\n/g, '</p><p style="margin:6px 0">');
            html = '<p style="margin:6px 0">' + html + '</p>';
            return html;
        } catch (e) {
            return '<pre style="white-space:pre-wrap">' + text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</pre>';
        }
    }

    _getPreviewHtml(path, content) {
        if (content === null || content === false) {
            return '<div style="color:var(--error-color);padding:20px">File not found: ' + this._escapeHtml(path) + '</div>';
        }

        const type = this._detectType(path);
        const ext = path.split('.').pop().toLowerCase();
        const fileName = path.split('/').pop() || path;

        // Handle binary detection for media types
        if (typeof content !== 'string') {
            return '<div style="padding:20px;text-align:center;color:var(--text-muted)">Cannot preview: non-string content</div>';
        }
        const isLikelyBinary = content.length > 0 && !content.startsWith('\n') && !content.startsWith('\r') && !content.startsWith(' ') && !content.startsWith('<') && !content.startsWith('{') && !content.startsWith('[') && content.charCodeAt(0) < 32 && content.charCodeAt(0) !== 9 && content.charCodeAt(0) !== 10 && content.charCodeAt(0) !== 13;

        const isTextContent = typeof content === 'string' && (content.startsWith('{') || content.startsWith('[') || content.startsWith('<') || content.startsWith('#') || /^[\w\s\n\r\t.,;:!?()\-=+*@#$%^&"'\/\\|`~]/.test(content.substring(0, 100)));

        if (type === 'md' && isTextContent) {
            return '<div class="markdown-preview" style="padding:12px;font-family:var(--font-primary);line-height:1.5">' + this._renderMarkdown(content) + '</div>';
        }

        if (type === 'html') {
            // Render HTML in an inline sandbox frame
            const safeHtml = content
                .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
                .replace(/on\w+\s*=\s*"[^"]*"/gi, '')
                .replace(/on\w+\s*=\s*'[^']*'/gi, '');
            return '<div style="padding:0;width:100%;height:60vh;border:none;overflow:hidden">' +
                '<iframe srcdoc="' + this._escapeHtml(safeHtml.replace(/"/g, '&quot;').replace(/'/g, '&#39;')) + '" ' +
                'style="width:100%;height:100%;border:none;background:#fff" sandbox="allow-same-origin"></iframe></div>';
        }

        if (type === 'text') {
            const truncated = content.substring(0, 2000);
            const extra = content.length > 2000 ? '<div style="color:var(--text-muted);margin-top:8px">(truncated to 2000 chars)</div>' : '';
            return '<pre style="white-space:pre-wrap;padding:12px;font-family:var(--font-primary);font-size:0.9em;margin:0;overflow-x:auto">' + this._escapeHtml(truncated) + extra + '</pre>';
        }

        if (type === 'json') {
            try {
                const parsed = JSON.parse(content);
                const formatted = JSON.stringify(parsed, null, 2);
                const html = this._syntaxHighlightJson(formatted);
                return '<pre style="padding:12px;font-family:var(--font-primary);font-size:0.9em;margin:0;overflow-x:auto;line-height:1.4">' + html + '</pre>';
            } catch (e) {
                return '<pre style="padding:12px;font-family:var(--font-primary);font-size:0.9em;margin:0;overflow-x:auto">' + this._escapeHtml(content.substring(0, 5000)) + '</pre>';
            }
        }

        if (type === 'code') {
            const lines = content.split('\n');
            const totalLines = lines.length;
            const maxLines = 150;
            const displayLines = lines.slice(0, maxLines);
            let html = '<table style="border-collapse:collapse;width:100%;font-family:var(--font-primary);font-size:0.85em;margin:0"><tbody>';
            displayLines.forEach((line, i) => {
                const lineNum = i + 1;
                const escaped = this._escapeHtml(line);
                html += '<tr><td style="color:var(--text-muted);padding:0 8px 0 4px;text-align:right;user-select:none;border-right:1px solid var(--border-color);vertical-align:top;width:40px">' + lineNum + '</td>';
                html += '<td style="padding:0 8px;white-space:pre;width:100%">' + (escaped || '&nbsp;') + '</td></tr>';
            });
            html += '</tbody></table>';
            if (totalLines > maxLines) {
                html += '<div style="color:var(--text-muted);padding:8px;border-top:1px solid var(--border-color)">(showing ' + maxLines + ' of ' + totalLines + ' lines)</div>';
            }
            return html;
        }

        if (type === 'image') {
            // VFS stores images as base64 strings — detect and render inline
            const isBase64 = /^[A-Za-z0-9+/=]+$/.test(content.substring(0, 100));
            if (isBase64) {
                const mimeTypes = {jpg:'image/jpeg',jpeg:'image/jpeg',png:'image/png',gif:'image/gif',webp:'image/webp',bmp:'image/bmp',ico:'image/x-icon'};
                const mime = mimeTypes[ext] || 'image/png';
                return '<div style="padding:12px;text-align:center;max-width:100%"><img src="data:' + mime + ';base64,' + content + '" style="max-width:100%;max-height:70vh;border-radius:4px;border:1px solid var(--border-color)" alt="' + this._escapeHtml(fileName) + '"></div>';
            }
            return '<div style="padding:20px;text-align:center;color:var(--text-muted)">📷 Image — cannot render, file may be stored as binary</div>';
        }

        if (type === 'svg') {
            try {
                const parser = new DOMParser();
                const doc = parser.parseFromString(content, 'text/html');
                const scripts = doc.querySelectorAll('script');
                scripts.forEach(s => s.remove());
                // Remove event handlers from svg elements
                const allEls = doc.querySelectorAll('*');
                allEls.forEach(el => {
                    for (let i = el.attributes.length - 1; i >= 0; i--) {
                        const attr = el.attributes[i].name;
                        if (attr.startsWith('on')) el.removeAttribute(attr);
                    }
                });
                const cleanSvg = doc.body.innerHTML;
                return '<div style="padding:12px;text-align:center;max-width:100%;overflow:auto">' + cleanSvg + '</div>';
            } catch (e) {
                return '<pre style="padding:12px;font-family:var(--font-primary);font-size:0.9em;overflow-x:auto">' + this._escapeHtml(content.substring(0, 5000)) + '</pre>';
            }
        }

        if (type === 'video') {
            const isBase64 = /^[A-Za-z0-9+/=]+$/.test(content.substring(0, 100));
            if (isBase64) {
                const mimeTypes = {mp4:'video/mp4',webm:'video/webm',avi:'video/x-msvideo',mov:'video/quicktime',mkv:'video/x-matroska'};
                const mime = mimeTypes[ext] || 'video/mp4';
                return '<div style="padding:12px;text-align:center"><video controls style="max-width:90%;max-height:65vh;border-radius:4px"><source src="data:' + mime + ';base64,' + content + '" type="' + mime + '"></video></div>';
            }
            return '<div style="padding:20px;text-align:center;color:var(--text-muted)">🎬 Video — cannot render</div>';
        }

        if (type === 'audio') {
            const isBase64 = /^[A-Za-z0-9+/=]+$/.test(content.substring(0, 100));
            if (isBase64) {
                const mimeTypes = {mp3:'audio/mpeg',wav:'audio/wav',ogg:'audio/ogg',flac:'audio/flac',aac:'audio/aac',m4a:'audio/mp4'};
                const mime = mimeTypes[ext] || 'audio/mpeg';
                return '<div style="padding:12px;text-align:center"><audio controls style="max-width:90%"><source src="data:' + mime + ';base64,' + content + '" type="' + mime + '"></audio></div>';
            }
            return '<div style="padding:20px;text-align:center;color:var(--text-muted)">🎵 Audio — cannot render</div>';
        }

        if (type === 'pdf') {
            const isBase64 = /^[A-Za-z0-9+/=]+$/.test(content.substring(0, 100));
            if (isBase64) {
                return '<div style="padding:12px;text-align:center;height:70vh"><embed src="data:application/pdf;base64,' + content + '" type="application/pdf" style="width:100%;height:100%;border:1px solid var(--border-color);border-radius:4px"></div>';
            }
            return '<div style="padding:20px;text-align:center;color:var(--text-muted)">📄 PDF — cannot render</div>';
        }

        if (type === 'csv') {
            try {
                const lines = content.split('\n').filter(l => l.trim());
                const maxRows = 50;
                const rows = lines.slice(0, maxRows).map(l => l.split(',').map(c => c.trim().replace(/^"|"$/g, '')));
                let html = '<table class="csv-table" style="border-collapse:collapse;width:100%;font-family:var(--font-primary);font-size:0.85em;margin:0;background:var(--bg-secondary)">';
                if (rows.length > 0) {
                    html += '<thead><tr>';
                    rows[0].forEach(cell => {
                        html += '<th style="border:1px solid var(--border-color);padding:6px 8px;text-align:left;background:var(--bg-tertiary);color:var(--accent-color);font-weight:bold">' + this._escapeHtml(cell) + '</th>';
                    });
                    html += '</tr></thead><tbody>';
                    rows.slice(1).forEach(row => {
                        html += '<tr>';
                        row.forEach(cell => {
                            html += '<td style="border:1px solid var(--border-color);padding:4px 8px">' + this._escapeHtml(cell) + '</td>';
                        });
                        html += '</tr>';
                    });
                    html += '</tbody></table>';
                    if (lines.length > maxRows) {
                        html += '<div style="color:var(--text-muted);padding:8px">(showing ' + maxRows + ' of ' + lines.length + ' rows)</div>';
                    }
                }
                return html;
            } catch (e) {
                return '<pre style="padding:12px;font-family:var(--font-primary);font-size:0.9em;overflow-x:auto">' + this._escapeHtml(content.substring(0, 5000)) + '</pre>';
            }
        }

        // 'other' — raw text fallback
        if (typeof content === 'string' && isTextContent) {
            const lines = content.split('\n');
            const maxLines = 80;
            const displayLines = lines.slice(0, maxLines);
            const truncated = lines.length > maxLines;
            let html = '<pre style="white-space:pre-wrap;padding:12px;font-family:var(--font-primary);font-size:0.9em;margin:0;overflow-x:auto">';
            displayLines.forEach((line, i) => {
                html += this._escapeHtml(line) + '\n';
            });
            html += '</pre>';
            if (truncated) {
                html += '<div style="color:var(--text-muted);padding:8px;border-top:1px solid var(--border-color)">(showing ' + maxLines + ' of ' + lines.length + ' lines)</div>';
            }
            return html;
        }

        return '<div style="padding:20px;text-align:center;color:var(--text-muted)">📁 Preview not available for this file type</div>';
    }

    _syntaxHighlightJson(jsonStr) {
        return jsonStr.replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span style="color:var(--info-color)">$1</span>:')
            .replace(/:\s*("(?:\\.|[^"\\])*")/g, ': <span style="color:var(--success-color)">$1</span>')
            .replace(/:\s*(\d+\.?\d*)/g, ': <span style="color:var(--warning-color)">$1</span>')
            .replace(/:\s*(true|false|null)/g, ': <span style="color:var(--error-color)">$1</span>');
    }

    _escapeHtml(str) {
        if (typeof str !== 'string') return '';
        return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
    }

    _formatSize(size) {
        if (!size && size !== 0) return '';
        if (size < 1024) return size + ' B';
        if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB';
        return (size / (1024 * 1024)).toFixed(1) + ' MB';
    }

    _createOverlay() {
        if (this._overlay) return;

        const overlay = document.createElement('div');
        overlay.id = 'filemgr-overlay';
        overlay.style.cssText = 'position:fixed;inset:0;z-index:1800;display:flex;flex-direction:column;background:var(--bg-color);color:var(--text-color);font-family:var(--font-primary);font-size:14px;height:100vh;';

        // Inject responsive styles for the overlay
        const styleId = 'filemgr-styles';
        if (!document.getElementById(styleId)) {
            const style = document.createElement('style');
            style.id = styleId;
            style.textContent = `
                #filemgr-overlay.responsive .filemgr-main {
                    flex-direction: column !important;
                }
                #filemgr-overlay.responsive #filemgr-sidebar {
                    width: 100% !important;
                    max-height: 40vh;
                }
                #filemgr-overlay.responsive #filemgr-preview {
                    width: 100% !important;
                }
                #filemgr-overlay .filemgr-main {
                    display: flex;
                    flex: 1;
                    min-height: 0;
                }
                @media (max-width: 600px) {
                    #filemgr-overlay .filemgr-main {
                        flex-direction: column !important;
                    }
                    #filemgr-overlay #filemgr-sidebar {
                        width: 100% !important;
                        max-height: 40vh;
                        border-right: none !important;
                        border-bottom: 1px solid var(--border-color);
                    }
                #filemgr-overlay #filemgr-preview {
                    width: 100% !important;
                    flex: 1 !important;
                    min-height: 0;
                }
                    #filemgr-action-bar {
                        flex-wrap: wrap;
                        gap: 6px;
                    }
                    #filemgr-action-bar button {
                        min-width: 44px;
                        min-height: 44px;
                        font-size: 0.9em;
                    }
                }
            `;
            document.head.appendChild(style);
        }

        // Toolbar
        const toolbar = document.createElement('div');
        toolbar.style.cssText = 'display:flex;align-items:center;padding:8px 12px;border-bottom:1px solid var(--border-color);background:var(--bg-secondary);flex-shrink:0;gap:8px;flex-wrap:wrap;';

        const closeBtn = document.createElement('button');
        closeBtn.textContent = '✕';
        closeBtn.style.cssText = 'background:none;border:1px solid var(--border-color);color:var(--text-color);cursor:pointer;padding:4px 10px;border-radius:4px;font-family:inherit;font-size:1em;min-height:44px;touch-action:manipulation;';
        closeBtn.onclick = () => this._closeOverlay();
        toolbar.appendChild(closeBtn);

        const titleSpan = document.createElement('span');
        titleSpan.textContent = '📁 File Manager';
        titleSpan.style.cssText = 'font-weight:bold;margin-right:8px;';
        toolbar.appendChild(titleSpan);

        // Breadcrumbs
        const breadcrumbs = document.createElement('div');
        breadcrumbs.style.cssText = 'display:flex;align-items:center;gap:4px;flex-wrap:wrap;font-size:0.9em;';
        breadcrumbs.id = 'filemgr-breadcrumbs';

        // Root breadcrumb
        const rootSeg = document.createElement('span');
        rootSeg.textContent = '/';
        rootSeg.style.cssText = 'color:var(--accent-color);cursor:pointer;padding:2px 4px;border-radius:3px;';
        rootSeg.onmouseenter = () => { rootSeg.style.background = 'var(--bg-tertiary)'; };
        rootSeg.onmouseleave = () => { rootSeg.style.background = 'transparent'; };
        rootSeg.onclick = () => this._navigateTo([]);
        breadcrumbs.appendChild(rootSeg);

        toolbar.appendChild(breadcrumbs);

        // Search input
        const searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.placeholder = '🔍 Filter files...';
        searchInput.style.cssText = 'flex:1;min-width:120px;max-width:300px;padding:6px 10px;background:var(--bg-tertiary);border:1px solid var(--border-color);border-radius:4px;color:var(--text-color);font-family:var(--font-primary);font-size:0.9em;outline:none;';
        searchInput.oninput = (e) => {
            this._searchFilter = e.target.value.toLowerCase();
            this._refreshFileList();
        };
        toolbar.appendChild(searchInput);

        // v4.5.78: Batch operation buttons
        const batchBar = document.createElement('div');
        batchBar.style.cssText = 'display:flex;align-items:center;gap:4px;flex-wrap:wrap;';
        const mkBtn = (label, title, action) => {
            const b = document.createElement('button');
            b.textContent = label;
            b.title = title;
            b.style.cssText = 'background:none;border:1px solid var(--border-color);color:var(--text-color);cursor:pointer;padding:4px 8px;border-radius:4px;font-family:inherit;font-size:0.85em;min-height:32px;touch-action:manipulation;';
            b.onclick = () => action();
            return b;
        };
        batchBar.appendChild(mkBtn('📋 Copy', 'Copy selected files', () => this._batchCopy()));
        batchBar.appendChild(mkBtn('✂️ Cut', 'Cut selected files', () => this._batchCut()));
        batchBar.appendChild(mkBtn('📥 Paste', 'Paste from clipboard', () => this._batchPaste()));
        batchBar.appendChild(mkBtn('🗑️ Del', 'Delete selected files', () => this._batchDelete()));
        batchBar.appendChild(mkBtn('📝 Rename', 'Rename selected file', () => this._batchRename()));
        batchBar.appendChild(mkBtn('☐ All', 'Toggle select all', () => this._toggleSelectAll()));
        toolbar.appendChild(batchBar);

        overlay.appendChild(toolbar);

        // Main area — wraps sidebar + preview in a responsive flex container
        const mainArea = document.createElement('div');
        mainArea.id = 'filemgr-main-container';
        mainArea.className = 'filemgr-main';
        mainArea.style.cssText = 'flex:1;overflow:hidden;display:flex;min-height:0;';

        // Sidebar
        const sidebar = document.createElement('div');
        sidebar.id = 'filemgr-sidebar';
        sidebar.style.cssText = 'width:25%;min-width:150px;overflow-y:auto;background:var(--bg-secondary);border-right:1px solid var(--border-color);';

        mainArea.appendChild(sidebar);

        // Preview pane
        const preview = document.createElement('div');
        preview.id = 'filemgr-preview';
        preview.style.cssText = 'flex:1;overflow-y:auto;padding:0;';

        mainArea.appendChild(preview);

        overlay.appendChild(mainArea);

        // Action bar
        const actionBar = document.createElement('div');
        actionBar.id = 'filemgr-action-bar';
        actionBar.style.cssText = 'display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border-color);background:var(--bg-secondary);flex-shrink:0;gap:8px;flex-wrap:wrap;';

        const statusSpan = document.createElement('span');
        statusSpan.id = 'filemgr-status';
        statusSpan.style.cssText = 'flex:1;color:var(--text-muted);font-size:0.85em;';
        statusSpan.textContent = 'No file selected';
        actionBar.appendChild(statusSpan);

        const encryptBtn = document.createElement('button');
        encryptBtn.textContent = '🔐 Encrypt';
        encryptBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--warning-color);color:var(--warning-color);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        encryptBtn.onclick = () => this._actionEncrypt();
        actionBar.appendChild(encryptBtn);

        const compressBtn = document.createElement('button');
        compressBtn.textContent = '📦 Zip';
        compressBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--info-color);color:var(--info-color);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        compressBtn.onclick = () => this._actionCompress();
        actionBar.appendChild(compressBtn);

        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '🗑 Delete';
        deleteBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--error-color);color:var(--error-color);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        deleteBtn.onclick = () => this._actionDelete();
        actionBar.appendChild(deleteBtn);

        const downloadBtn = document.createElement('button');
        downloadBtn.textContent = '⬇ Download';
        downloadBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--border-color);color:var(--text-color);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        downloadBtn.onclick = () => this._actionDownload();
        actionBar.appendChild(downloadBtn);

        const editBtn = document.createElement('button');
        editBtn.textContent = '✏ Edit';
        editBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--accent-color);color:var(--accent-color);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        editBtn.onclick = () => this._actionEdit();
        actionBar.appendChild(editBtn);

        const newFileBtn = document.createElement('button');
        newFileBtn.textContent = '📄 New';
        newFileBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--success-color);color:var(--success-color);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        newFileBtn.onclick = () => this._actionNewFile();
        actionBar.appendChild(newFileBtn);

        const previewToggleBtn = document.createElement('button');
        previewToggleBtn.id = 'filemgr-toggle-raw';
        previewToggleBtn.textContent = '📄 Raw';
        previewToggleBtn.style.cssText = 'padding:6px 14px;background:var(--bg-tertiary);border:1px solid var(--border-color);color:var(--text-muted);border-radius:4px;cursor:pointer;font-family:inherit;font-size:0.9em;min-height:44px;touch-action:manipulation;';
        previewToggleBtn.onclick = () => this._togglePreviewMode();
        actionBar.appendChild(previewToggleBtn);

        overlay.appendChild(actionBar);

        this._overlay = overlay;
        return overlay;
    }

    _openOverlay() {
        if (this._overlay) {
            this._overlay.style.display = 'flex';
            this._refreshFileList();
            return;
        }
        const overlay = this._createOverlay();
        document.body.appendChild(overlay);
        this._navigateTo(this.currentPath);
    }

    _closeOverlay() {
        if (this._overlay) {
            this._overlay.style.display = 'none';
        }
    }

    _clearOverlay() {
        if (this._overlay && this._overlay.parentNode) {
            this._overlay.parentNode.removeChild(this._overlay);
        }
        this._overlay = null;
        this._selectedFile = null;
        this._searchFilter = '';
        this._rawMode = false;
    }

    _navigateTo(pathParts) {
        this.currentPath = pathParts || [];
        this._selectedFile = null;
        this._searchFilter = '';
        const searchInput = this._overlay?.querySelector('input[type="text"]');
        if (searchInput) searchInput.value = '';
        this._updateBreadcrumbs();
        this._refreshFileList();
        this._clearPreview();
        this._updateStatus('No file selected');
    }

    _updateBreadcrumbs() {
        const breadcrumbs = document.getElementById('filemgr-breadcrumbs');
        if (!breadcrumbs) return;

        // Keep root segment, remove rest
        while (breadcrumbs.children.length > 1) {
            breadcrumbs.removeChild(breadcrumbs.lastChild);
        }

        let accumulated = '';
        this.currentPath.forEach((part, i) => {
            const sep = document.createElement('span');
            sep.textContent = ' › ';
            sep.style.cssText = 'color:var(--text-muted);margin:0 2px;';
            breadcrumbs.appendChild(sep);

            const seg = document.createElement('span');
            seg.textContent = part;
            seg.style.cssText = 'cursor:pointer;padding:2px 4px;border-radius:3px;color:var(--text-color);';
            if (i === this.currentPath.length - 1) {
                seg.style.color = 'var(--accent-color)';
                seg.style.fontWeight = 'bold';
            }
            seg.onmouseenter = () => { seg.style.background = 'var(--bg-tertiary)'; };
            seg.onmouseleave = () => { seg.style.background = 'transparent'; };
            const pathUpTo = this.currentPath.slice(0, i + 1);
            seg.onclick = () => this._navigateTo(pathUpTo);
            breadcrumbs.appendChild(seg);
        });
    }

    _refreshFileList() {
        const sidebar = document.getElementById('filemgr-sidebar');
        if (!sidebar) return;

        // Read directory
        const pathStr = '/' + this.currentPath.join('/');
        const entries = this.terminal.fs.ls(pathStr) || [];

        // Separate dirs and files
        const dirs = entries.filter(e => e.type === 'dir');
        const files = entries.filter(e => e.type !== 'dir');

        // Sort alphabetically
        dirs.sort((a, b) => a.name.localeCompare(b.name));
        files.sort((a, b) => a.name.localeCompare(b.name));

        // Apply search filter
        let filteredDirs = dirs;
        let filteredFiles = files;
        if (this._searchFilter) {
            const q = this._searchFilter;
            filteredDirs = dirs.filter(e => e.name.toLowerCase().includes(q));
            filteredFiles = files.filter(e => e.name.toLowerCase().includes(q));
        }

        sidebar.innerHTML = '';

        if (filteredDirs.length === 0 && filteredFiles.length === 0) {
            const emptyMsg = document.createElement('div');
            emptyMsg.style.cssText = 'padding:20px;text-align:center;color:var(--text-muted);';
            emptyMsg.textContent = this._searchFilter ? 'No matching files' : '(empty)';
            sidebar.appendChild(emptyMsg);
            this._updateStatus('0 files');
            return;
        }

        // Add directory items
        filteredDirs.forEach(entry => {
            const item = document.createElement('div');
            const fullPath = pathStr === '/' ? '/' + entry.name : pathStr + '/' + entry.name;
            item.dataset.path = fullPath;
            item.dataset.type = 'dir';
            item.style.cssText = 'display:flex;align-items:center;padding:6px 10px;cursor:pointer;border-bottom:1px solid var(--border-color);gap:6px;';
            item.onmouseenter = () => { if (!item.dataset.selected) item.style.background = 'var(--bg-tertiary)'; };
            item.onmouseleave = () => { if (!item.dataset.selected) item.style.background = 'transparent'; };
            item.onclick = () => {
                const newPath = [...this.currentPath, entry.name];
                this._navigateTo(newPath);
            };

            const icon = document.createElement('span');
            icon.textContent = '📁';
            item.appendChild(icon);

            const nameSpan = document.createElement('span');
            nameSpan.textContent = entry.name + '/';
            nameSpan.style.cssText = 'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
            item.appendChild(nameSpan);

            sidebar.appendChild(item);
        });

        // Add file items
        filteredFiles.forEach(entry => {
            const item = document.createElement('div');
            const fullPath = pathStr === '/' ? '/' + entry.name : pathStr + '/' + entry.name;
            const isSelected = this._selectedFile === fullPath;
            const isMulti = this._multiSelect.has(fullPath);
            item.dataset.path = fullPath;
            item.dataset.type = 'file';
            item.dataset.selected = (isSelected || isMulti) ? 'true' : 'false';
            const bgColor = (isSelected || isMulti) ? 'var(--bg-tertiary)' : 'transparent';
            item.style.cssText = 'display:flex;align-items:center;padding:6px 10px;cursor:pointer;border-bottom:1px solid var(--border-color);gap:6px;background:' + bgColor + ';';
            if (isSelected || isMulti) {
                item.style.borderLeft = '3px solid var(--accent-color)';
            }
            item.onmouseenter = () => { if (!item.dataset.selected) item.style.background = 'var(--bg-tertiary)'; };
            item.onmouseleave = () => { if (!item.dataset.selected) item.style.background = 'transparent'; };
            item.onclick = (e) => {
                // v4.5.78: Ctrl+click or checkbox for multi-select
                if (e.ctrlKey || e.metaKey) {
                    if (this._multiSelect.has(fullPath)) this._multiSelect.delete(fullPath);
                    else this._multiSelect.add(fullPath);
                    this._refreshFileList();
                    return;
                }
                this._selectedFile = fullPath;
                this._highlightSelected();
                const content = this.terminal.fs.readFile(fullPath);
                this._renderPreview(fullPath, content);
            };

            const icon = document.createElement('span');
            icon.textContent = '📄';
            item.appendChild(icon);

            const nameSpan = document.createElement('span');
            nameSpan.textContent = entry.name;
            nameSpan.style.cssText = 'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
            item.appendChild(nameSpan);

            const sizeSpan = document.createElement('span');
            sizeSpan.textContent = this._formatSize(entry.size);
            sizeSpan.style.cssText = 'color:var(--text-muted);font-size:0.8em;white-space:nowrap;margin-left:4px;';
            item.appendChild(sizeSpan);

            sidebar.appendChild(item);
        });

        const totalCount = entries.length;
        this._updateStatus(totalCount + ' item' + (totalCount !== 1 ? 's' : ''));
    }

    _highlightSelected() {
        const sidebar = document.getElementById('filemgr-sidebar');
        if (!sidebar) return;
        const items = sidebar.querySelectorAll('[data-type="file"]');
        items.forEach(item => {
            const selected = item.dataset.path === this._selectedFile || this._multiSelect.has(item.dataset.path);
            item.dataset.selected = selected ? 'true' : 'false';
            item.style.background = selected ? 'var(--bg-tertiary)' : 'transparent';
            item.style.borderLeft = selected ? '3px solid var(--accent-color)' : '3px solid transparent';
        });
    }

    // v4.5.78: Batch operations
    _getSelectedPaths() {
        const paths = [...this._multiSelect];
        if (this._selectedFile && !paths.includes(this._selectedFile)) paths.push(this._selectedFile);
        return paths;
    }

    _batchCopy() {
        const paths = this._getSelectedPaths();
        if (!paths.length) { this._updateStatus('No files selected'); return; }
        this._clipboard = { mode: 'copy', paths: [...paths] };
        this._multiSelect.clear();
        this._updateStatus('📋 Copied ' + paths.length + ' item(s)');
    }

    _batchCut() {
        const paths = this._getSelectedPaths();
        if (!paths.length) { this._updateStatus('No files selected'); return; }
        this._clipboard = { mode: 'cut', paths: [...paths] };
        this._multiSelect.clear();
        this._updateStatus('✂️ Cut ' + paths.length + ' item(s)');
    }

    _batchPaste() {
        if (!this._clipboard.paths.length) { this._updateStatus('Clipboard empty'); return; }
        const dest = '/' + this.currentPath.join('/');
        let count = 0;
        this._clipboard.paths.forEach(src => {
            const name = src.split('/').pop();
            const destPath = dest === '/' ? '/' + name : dest + '/' + name;
            try {
                if (this._clipboard.mode === 'copy') {
                    const content = this.terminal.fs.readFile(src);
                    if (content !== null) { this.terminal.fs.writeFile(destPath, content); count++; }
                } else if (this._clipboard.mode === 'cut') {
                    const content = this.terminal.fs.readFile(src);
                    if (content !== null) {
                        this.terminal.fs.writeFile(destPath, content);
                        this.terminal.fs.deleteFile(src);
                        count++;
                    }
                }
            } catch (e) { /* skip errors */ }
        });
        if (this._clipboard.mode === 'cut') this._clipboard = { mode: null, paths: [] };
        this._multiSelect.clear();
        this._refreshFileList();
        this._updateStatus('📥 Pasted ' + count + ' item(s)');
    }

    _batchDelete() {
        const paths = this._getSelectedPaths();
        if (!paths.length) { this._updateStatus('No files selected'); return; }
        if (!confirm('Delete ' + paths.length + ' file(s)?')) return;
        let count = 0;
        paths.forEach(p => {
            try { this.terminal.fs.deleteFile(p); count++; } catch (e) { /* skip */ }
        });
        this._multiSelect.clear();
        this._selectedFile = null;
        this._refreshFileList();
        this._updateStatus('🗑️ Deleted ' + count + ' file(s)');
    }

    _batchRename() {
        const path = this._selectedFile || (this._multiSelect.size === 1 ? [...this._multiSelect][0] : null);
        if (!path) { this._updateStatus('Select one file to rename'); return; }
        const oldName = path.split('/').pop();
        const newName = prompt('Rename to:', oldName);
        if (!newName || newName === oldName) return;
        const dir = path.substring(0, path.lastIndexOf('/')) || '/';
        const newPath = dir === '/' ? '/' + newName : dir + '/' + newName;
        try {
            const content = this.terminal.fs.readFile(path);
            if (content === null) { this._updateStatus('Cannot read file'); return; }
            this.terminal.fs.writeFile(newPath, content);
            this.terminal.fs.deleteFile(path);
            this._selectedFile = newPath;
            this._multiSelect.clear();
            this._refreshFileList();
            this._updateStatus('📝 Renamed to ' + newName);
        } catch (e) { this._updateStatus('Rename failed: ' + e.message); }
    }

    _toggleSelectAll() {
        const sidebar = document.getElementById('filemgr-sidebar');
        if (!sidebar) return;
        const fileItems = sidebar.querySelectorAll('[data-type="file"]');
        if (this._multiSelect.size >= fileItems.length) {
            this._multiSelect.clear();
        } else {
            fileItems.forEach(item => this._multiSelect.add(item.dataset.path));
        }
        this._refreshFileList();
        this._updateStatus(this._multiSelect.size + ' selected');
    }

    _renderPreview(path, content) {
        const preview = document.getElementById('filemgr-preview');
        if (!preview) return;

        // Re-read content on each preview call
        if (content === undefined) {
            content = this.terminal.fs.readFile(path);
        }

        // For raw mode, show raw text regardless of type
        if (this._rawMode && typeof content === 'string') {
            preview.innerHTML = '<div style="padding:12px"><div style="color:var(--text-muted);font-size:0.85em;margin-bottom:8px">RAW: ' + this._escapeHtml(path) + '</div><pre style="white-space:pre-wrap;font-family:var(--font-primary);font-size:0.9em;margin:0;overflow-x:auto">' + this._escapeHtml(content.substring(0, 10000)) + '</pre></div>';
            this._updateStatus('Preview: ' + path);
            return;
        }

        // Check file size for text files
        const type = this._detectType(path);
        const textTypes = ['md', 'text', 'json', 'code', 'csv', 'other'];
        if (textTypes.includes(type) && typeof content === 'string' && content.length > 51200) {
            content = content.substring(0, 51200);
            preview.innerHTML = this._getPreviewHtml(path, content);
            const truncatedMsg = document.createElement('div');
            truncatedMsg.style.cssText = 'color:var(--warning-color);padding:8px 12px;border-top:1px solid var(--border-color);font-size:0.85em;';
            truncatedMsg.textContent = '(truncated — file exceeds 50KB)';
            preview.appendChild(truncatedMsg);
            this._updateStatus('Preview: ' + path);
            return;
        }

        preview.innerHTML = this._getPreviewHtml(path, content);
        this._updateStatus('Preview: ' + path);
    }

    _renderPreviewError(msg) {
        const preview = document.getElementById('filemgr-preview');
        if (!preview) return;
        preview.innerHTML = '<div style="color:var(--error-color);padding:20px;font-size:1em">' + this._escapeHtml(msg) + '</div>';
        this._updateStatus('Error');
    }

    _clearPreview() {
        const preview = document.getElementById('filemgr-preview');
        if (preview) preview.innerHTML = '';
    }

    _updateStatus(msg) {
        const status = document.getElementById('filemgr-status');
        if (status) status.textContent = msg;
    }

    _actionDelete() {
        if (!this._selectedFile) {
            this._updateStatus('No file selected to delete');
            return;
        }
        if (!confirm('Delete ' + this._selectedFile + '?')) return;
        const ok = this.terminal.fs.deleteFile(this._selectedFile);
        if (ok) {
            this._selectedFile = null;
            this._refreshFileList();
            this._clearPreview();
            this._updateStatus('✅ Deleted');
        } else {
            this._updateStatus('❌ Failed to delete');
        }
    }

    _actionDownload() {
        if (!this._selectedFile) {
            this._updateStatus('No file selected to download');
            return;
        }
        const content = this.terminal.fs.readFile(this._selectedFile);
        if (content === null || content === false) {
            this._updateStatus('❌ File not found');
            return;
        }
        const fileName = this._selectedFile.split('/').pop() || 'file';
        const blob = new Blob([content], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        this._updateStatus('⬇ Downloaded: ' + fileName);
    }

    _actionEdit() {
        if (!this._selectedFile) {
            this._updateStatus('No file selected to edit');
            return;
        }
        const path = this._selectedFile;
        // Close file manager first so code editor modal (z-index:1000) is visible above
        this._closeOverlay();
        if (typeof webx11 !== 'undefined' && webx11 && webx11.dispatchCommand) {
            setTimeout(() => {
                webx11.dispatchCommand('edit', [path]);
            }, 100);
            this._updateStatus('✏ Opened in editor: ' + path);
        } else {
            this._updateStatus('❌ Editor not available');
        }
    }

    _togglePreviewMode() {
        this._rawMode = !this._rawMode;
        const btn = document.getElementById('filemgr-toggle-raw');
        if (btn) {
            btn.textContent = this._rawMode ? '📄 Rendered' : '📄 Raw';
            btn.style.borderColor = this._rawMode ? 'var(--accent-color)' : 'var(--border-color)';
            btn.style.color = this._rawMode ? 'var(--accent-color)' : 'var(--text-muted)';
        }
        if (this._selectedFile) {
            const content = this.terminal.fs.readFile(this._selectedFile);
            this._renderPreview(this._selectedFile, content);
        }
    }

    _actionEncrypt() {
        if (!this._selectedFile) {
            this._updateStatus('No file selected');
            return;
        }
        if (this._selectedFile.endsWith('.enc')) {
            this._updateStatus('⚠ Already encrypted (.enc)');
            return;
        }
        const passphrase = prompt('Enter passphrase for AES-256-GCM encryption:');
        if (!passphrase || passphrase.length < 4) {
            this._updateStatus('❌ Passphrase too short (min 4 chars)');
            return;
        }
        // Delegate to cryptogzip module's encrypt command
        if (typeof webx11 !== 'undefined' && webx11.executeCommand) {
            webx11.executeCommand('encrypt ' + this._selectedFile + ' ' + passphrase);
            this._updateStatus('🔐 Encrypted: ' + this._selectedFile + '.enc');
            this._refreshFileList();
        }
    }

    _actionCompress() {
        if (!this._selectedFile) {
            this._updateStatus('No file selected');
            return;
        }
        if (this._selectedFile.endsWith('.gz')) {
            this._updateStatus('⚠ Already compressed (.gz)');
            return;
        }
        if (typeof webx11 !== 'undefined' && webx11.executeCommand) {
            webx11.executeCommand('gzip ' + this._selectedFile);
            this._updateStatus('📦 Compressed: ' + this._selectedFile + '.gz');
            this._refreshFileList();
        }
    }

    _actionNewFile() {
        const name = prompt('New file name (e.g. myfile.txt):');
        if (!name) return;
        const pathStr = '/' + this.currentPath.join('/');
        const cleanPath = pathStr === '/' ? '/' + name : pathStr + '/' + name;
        const content = prompt('Enter file content (optional):') || '';
        const ok = this.terminal.fs.writeFile(cleanPath, content);
        if (ok) {
            this._updateStatus('✅ Created: ' + cleanPath + ' (' + content.length + ' chars)');
            this._refreshFileList();
        } else {
            this._updateStatus('❌ Failed to create file');
        }
    }
}

if (typeof window.webx11 !== 'undefined' && window.webx11) {
    webx11.moduleManager.registerModule(new FileManagerModule(), 'https://webx11.duckdns.org/spaces/newos4/modules/ext/filemgr.js');
}