-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathApp.tsx
More file actions
1994 lines (1794 loc) · 72.6 KB
/
Copy pathApp.tsx
File metadata and controls
1994 lines (1794 loc) · 72.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useEffect, useRef, useState, MouseEvent, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import type { Event } from '@tauri-apps/api/event';
import Sidebar from './components/Sidebar';
import MainPanel from './components/MainPanel';
import PathBar from './components/PathBar';
import StatusBar from './components/StatusBar';
import { useAppStore } from './store/useAppStore';
import { useToastStore } from './store/useToastStore';
import { useUndoStore } from './store/useUndoStore';
import { openFolderSizeWindow } from './store/useFolderSizeStore';
import { useDirectoryStream } from './hooks/useDirectoryStream';
import { message } from '@tauri-apps/plugin-dialog';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { platform } from '@tauri-apps/plugin-os';
import { getEffectiveExtension, isArchiveFile } from './utils/fileTypes';
import { dirname } from './utils/pathUtils';
import { applyAccentVariables, DEFAULT_ACCENT, normalizeHexColor } from '@/utils/accent';
import { getSuggestedZipName } from './utils/zipNaming';
import { revealInFileBrowser } from '@/utils/fileBrowser';
import Toast from './components/Toast';
import FilterInput from './components/FilterInput';
import { FULL_DISK_ACCESS_DISMISSED_KEY } from '@/utils/fullDiskAccessPrompt';
import {
PREFERENCES_UPDATED_EVENT,
SMB_CONNECT_SUCCESS_EVENT,
SFTP_CONNECT_SUCCESS_EVENT,
} from '@/utils/events';
import { usePrefersReducedMotion } from '@/hooks/usePrefersReducedMotion';
import { invalidateThumbnailsForPaths } from '@/hooks/useThumbnail';
import type {
DirectoryChangeEventPayload,
DirectoryListingResponse,
FileItem,
PersistedPreferences,
SmbConnectSuccessPayload,
SftpConnectSuccessPayload,
ViewPreferences,
} from './types';
// Error codes matching backend (src-tauri/src/commands.rs)
const ErrorCodes = {
ENOENT: 'ENOENT', // Path does not exist
ENOTDIR: 'ENOTDIR', // Path is not a directory
EPERM: 'EPERM', // Permission denied / Operation not permitted
} as const;
/** Parse error code from structured error message format "[CODE] message" */
function parseErrorCode(error: unknown): string | null {
const message = error instanceof Error ? error.message : String(error);
const match = message.match(/^\[([A-Z]+)\]/);
return match ? match[1] : null;
}
function hasUriScheme(path: string): boolean {
return /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(path);
}
const ACCENT_POLL_INTERVAL_MS = 5000;
// Grid zoom constants (for keyboard shortcuts - wheel handler moved to MainPanel)
import {
GRID_SIZE_MIN,
GRID_SIZE_MAX,
GRID_SIZE_DEFAULT,
GRID_SIZE_STEP,
} from '@/utils/gridConstants';
async function checkAndShowFullDiskAccessPrompt() {
if (platform() !== 'macos') return;
if (localStorage.getItem(FULL_DISK_ACCESS_DISMISSED_KEY) === 'true') return;
try {
const mod = await import('tauri-plugin-macos-permissions-api');
const hasAccess = await mod.checkFullDiskAccessPermission();
if (!hasAccess) {
await invoke('open_permissions_window');
}
} catch {
// Plugin not available or check failed; avoid blocking app start.
}
}
function App() {
// Use selectors to only subscribe to state App actually uses
// This prevents re-renders when unrelated state (like selectedFiles) changes
const currentPath = useAppStore((state) => state.currentPath);
const setCurrentPath = useAppStore((state) => state.setCurrentPath);
const navigateTo = useAppStore((state) => state.navigateTo);
const setLoading = useAppStore((state) => state.setLoading);
const setError = useAppStore((state) => state.setError);
const setFiles = useAppStore((state) => state.setFiles);
const loading = useAppStore((state) => state.loading);
const setHomeDir = useAppStore((state) => state.setHomeDir);
const toggleHiddenFiles = useAppStore((state) => state.toggleHiddenFiles);
const toggleFoldersFirst = useAppStore((state) => state.toggleFoldersFirst);
const directoryPreferences = useAppStore((state) => state.directoryPreferences);
const globalPreferences = useAppStore((state) => state.globalPreferences);
const loadPinnedDirectories = useAppStore((state) => state.loadPinnedDirectories);
// Animation preference hook (reactive to system changes)
const prefersReducedMotion = usePrefersReducedMotion();
// Set up directory streaming event listener
useDirectoryStream();
const initializedRef = useRef(false);
const [showLoadingOverlay, setShowLoadingOverlay] = useState(false);
const openPreferences = useCallback(() => {
invoke('open_preferences_window').catch((error) => {
console.warn('Failed to open preferences window:', error);
});
}, []);
const prefsLoadedRef = useRef(false);
const firstLoadRef = useRef(true);
const altTogglePendingRef = useRef(false);
const windowRef = useRef(getCurrentWindow());
const thumbnailPrewarmRequestedRef = useRef(false);
const currentAccentRef = useRef<string | null>(null);
const saveGlobalPrefsTimeoutRef = useRef<number | null>(null);
const currentDirectoryPreference = directoryPreferences[currentPath];
const pendingFileSelectionRef = useRef<string | null>(null);
// Apply smart default view and sort preferences based on folder name or contents
const applySmartViewDefaults = async (path: string, files?: FileItem[]) => {
try {
const { directoryPreferences, updateDirectoryPreferences } = useAppStore.getState();
const existing = directoryPreferences[path];
// If user already set any preferences, don't override them — but fill in missing defaults
if (existing && Object.keys(existing).length > 0) {
const sb = existing.sortBy;
const so = existing.sortOrder;
// Only fill in missing sortOrder if sortBy is set but sortOrder is not
if (sb && !so) {
const defaultOrder: ViewPreferences['sortOrder'] =
sb === 'size' || sb === 'modified' ? 'desc' : 'asc';
updateDirectoryPreferences(path, { sortOrder: defaultOrder });
try {
await invoke('set_dir_prefs', {
path,
prefs: JSON.stringify({ sortOrder: defaultOrder }),
});
} catch (error) {
console.warn('Failed to persist sort order default:', error);
}
}
return;
}
const normalized = path.replace(/\\/g, '/').replace(/\/+$/g, '') || '/';
const base = normalized.split('/').pop()?.toLowerCase() ?? '';
// Smart defaults based on folder name
const folderDefaults: Record<string, Partial<ViewPreferences>> = {
downloads: { sortBy: 'modified', sortOrder: 'desc' },
download: { sortBy: 'modified', sortOrder: 'desc' },
pictures: { viewMode: 'grid', sortBy: 'modified', sortOrder: 'desc' },
photos: { viewMode: 'grid', sortBy: 'modified', sortOrder: 'desc' },
screenshots: { viewMode: 'grid', sortBy: 'modified', sortOrder: 'desc' },
videos: { viewMode: 'grid', sortBy: 'modified', sortOrder: 'desc' },
movies: { viewMode: 'grid', sortBy: 'modified', sortOrder: 'desc' },
applications: { viewMode: 'grid', sortBy: 'name', sortOrder: 'asc' },
documents: { sortBy: 'modified', sortOrder: 'desc' },
desktop: { sortBy: 'modified', sortOrder: 'desc' },
};
const folderDefault = folderDefaults[base];
if (folderDefault) {
updateDirectoryPreferences(path, folderDefault);
try {
await invoke('set_dir_prefs', { path, prefs: JSON.stringify(folderDefault) });
} catch (error) {
console.warn('Failed to persist folder defaults:', error);
}
return;
}
if (!files || files.length === 0) {
return;
}
const mediaRelevantFiles = files.filter((file) => !file.is_directory);
if (mediaRelevantFiles.length === 0) {
return;
}
// Default to grid only when we can actually show thumbnails (locally generated, or remote-provided).
// This avoids switching to grid for file types we can't thumbnail yet (e.g., docx).
const thumbnailCapableExtensions = new Set([
// Images
'jpg',
'jpeg',
'png',
'gif',
'webp',
'svg',
'bmp',
'tiff',
'tif',
'tga',
'ico',
// Videos
'mp4',
'mkv',
'avi',
'mov',
'webm',
'flv',
'm4v',
// Documents / other with generated thumbnails
'pdf',
'ai',
'eps',
'psd',
'psb',
'stl',
]);
const hasGeneratedThumbnail = (file: FileItem) => {
if (file.thumbnail_url) return true;
const ext = getEffectiveExtension(file)?.toLowerCase();
return !!ext && thumbnailCapableExtensions.has(ext);
};
const thumbnailFiles = mediaRelevantFiles.filter(hasGeneratedThumbnail);
const mediaRatio = thumbnailFiles.length / mediaRelevantFiles.length;
// If at least half the files can show thumbnails, default to grid when there's no stored preference.
const mediaThreshold = 0.5;
if (mediaRatio >= mediaThreshold) {
const prefs: Partial<ViewPreferences> = {
viewMode: 'grid',
sortBy: 'modified',
sortOrder: 'desc',
};
updateDirectoryPreferences(path, prefs);
try {
await invoke('set_dir_prefs', { path, prefs: JSON.stringify(prefs) });
} catch (error) {
console.warn('Failed to persist media folder defaults:', error);
}
return;
}
const stlFiles = mediaRelevantFiles.filter((file) => file.extension?.toLowerCase() === 'stl');
if (stlFiles.length >= 2 && stlFiles.length / mediaRelevantFiles.length >= 0.6) {
const prefs: Partial<ViewPreferences> = { viewMode: 'grid' };
updateDirectoryPreferences(path, prefs);
try {
await invoke('set_dir_prefs', { path, prefs: JSON.stringify(prefs) });
} catch (error) {
console.warn('Failed to persist STL folder defaults:', error);
}
}
} catch (error) {
console.warn('Failed to apply smart view defaults:', error);
}
};
// Only show the blocking loading overlay during initial app load (not folder navigation)
// Folder navigation uses a subtle spinner in MainPanel instead
useEffect(() => {
let timer: number | undefined;
// Only show full-screen overlay before app is initialized
if (loading && !initializedRef.current) {
timer = window.setTimeout(() => setShowLoadingOverlay(true), 500);
} else {
setShowLoadingOverlay(false);
}
return () => {
if (timer) window.clearTimeout(timer);
};
}, [loading]);
// Remove global subscriptions that write the entire file to avoid clobbering across windows
// Use a dedicated window for Full Disk Access prompt (macOS only)
useEffect(() => {
void checkAndShowFullDiskAccessPrompt();
}, []);
// Handle SMB connect flow coming from the SMB connect window
useEffect(() => {
let unlisten: (() => void) | undefined;
(async () => {
try {
unlisten = await listen<SmbConnectSuccessPayload>(
SMB_CONNECT_SUCCESS_EVENT,
async (evt) => {
const payload = evt.payload;
if (!payload?.hostname) return;
const state = useAppStore.getState();
try {
await state.loadSmbServers();
} catch (error) {
console.warn('Failed to refresh SMB server list after connect:', error);
}
state.setPendingSmbCredentialRequest(null);
await state.navigateTo(payload.targetPath || `smb://${payload.hostname}/`);
}
);
} catch (error) {
console.warn('Failed to listen for SMB connect success:', error);
}
})();
return () => {
if (unlisten) {
unlisten();
}
};
}, []);
// Handle SFTP connect flow coming from the SFTP connect window
useEffect(() => {
let unlisten: (() => void) | undefined;
(async () => {
try {
unlisten = await listen<SftpConnectSuccessPayload>(
SFTP_CONNECT_SUCCESS_EVENT,
async (evt) => {
const payload = evt.payload;
if (!payload?.hostname) return;
const state = useAppStore.getState();
try {
await state.loadSftpServers();
} catch (error) {
console.warn('Failed to refresh SFTP server list after connect:', error);
}
state.setPendingSftpCredentialRequest(null);
const portSuffix = payload.port === 22 ? '' : `:${payload.port}`;
await state.navigateTo(
payload.targetPath || `sftp://${payload.username}@${payload.hostname}${portSuffix}/`
);
}
);
} catch (error) {
console.warn('Failed to listen for SFTP connect success:', error);
}
})();
return () => {
if (unlisten) {
unlisten();
}
};
}, []);
// Sync preferences updates coming from the Preferences window.
useEffect(() => {
let unlisten: (() => void) | undefined;
(async () => {
try {
unlisten = await listen<Partial<ViewPreferences>>(PREFERENCES_UPDATED_EVENT, (evt) => {
const payload = evt.payload;
if (payload && typeof payload === 'object') {
useAppStore.getState().updateGlobalPreferences(payload);
}
});
} catch (error) {
console.warn('Failed to listen for preferences updates:', error);
}
})();
return () => {
if (unlisten) {
unlisten();
}
};
}, []);
useEffect(() => {
// Initialize the app by getting the home directory
async function initializeApp() {
try {
setLoading(true);
setError(undefined);
if (!thumbnailPrewarmRequestedRef.current) {
thumbnailPrewarmRequestedRef.current = true;
const startedAt = performance.now();
invoke<boolean>('initialize_thumbnail_service')
.then((serviceReady) => {
if (!import.meta.env.DEV) {
return;
}
const elapsed = Math.round(performance.now() - startedAt);
if (serviceReady) {
console.info(`Thumbnail worker ready in ${elapsed}ms`);
} else {
console.warn(`Thumbnail worker prewarm failed after ${elapsed}ms`);
}
})
.catch((error) => {
if (import.meta.env.DEV) {
console.warn('Thumbnail worker prewarm error:', error);
}
});
}
// Load persisted preferences first
let lastDir: string | undefined;
try {
const raw = await invoke<string>('read_preferences');
if (raw) {
const parsed = JSON.parse(raw || '{}') as PersistedPreferences;
if (parsed.globalPreferences) {
useAppStore.getState().updateGlobalPreferences(parsed.globalPreferences);
}
if (parsed.directoryPreferences) {
Object.entries(parsed.directoryPreferences).forEach(([dirPath, prefs]) => {
useAppStore.getState().updateDirectoryPreferences(dirPath, prefs);
});
}
if (parsed.lastDir) {
lastDir = parsed.lastDir;
}
}
} catch (error) {
console.error('❌ Error loading preferences:', error);
}
// Mark preferences as loaded regardless of whether we found any
prefsLoadedRef.current = true;
const homeDir = await invoke<string>('get_home_directory');
setHomeDir(homeDir);
// Load pinned directories
await loadPinnedDirectories();
// Check if a path was provided via URL parameter (for new windows)
const urlParams = new URLSearchParams(window.location.search);
const initialPath = urlParams.get('path');
const startPath = initialPath ? decodeURIComponent(initialPath) : lastDir || homeDir;
// Now try to load the initial directory
let loadSuccess = false;
const tryLoadPath = async (path: string): Promise<boolean> => {
try {
setCurrentPath(path);
// Use non-streaming refresh for remote paths since streaming isn't supported there.
if (hasUriScheme(path)) {
await useAppStore.getState().refreshCurrentDirectory();
} else {
await useAppStore.getState().refreshCurrentDirectoryStreaming();
}
const refreshFailure = useAppStore.getState().error;
if (refreshFailure) {
throw new Error(refreshFailure);
}
const normalizedPath = useAppStore.getState().currentPath;
useAppStore.setState({
pathHistory: [normalizedPath],
historyIndex: 0,
});
return true;
} catch (err) {
console.error('Failed to load directory:', path, err);
return false;
}
};
// Try paths in order: startPath -> homeDir -> root
loadSuccess = await tryLoadPath(startPath);
if (!loadSuccess && startPath !== homeDir) {
loadSuccess = await tryLoadPath(homeDir);
}
if (!loadSuccess) {
loadSuccess = await tryLoadPath('/');
}
if (!loadSuccess) {
await message('Unable to access any directory. Please check filesystem permissions.', {
title: 'Fatal Error',
okLabel: 'OK',
kind: 'error',
});
}
// Mark initialization complete only if we successfully loaded something
if (loadSuccess) {
setError(undefined);
initializedRef.current = true;
firstLoadRef.current = false;
}
} catch (error) {
// Critical error (can't even get home directory)
console.error('Critical initialization error:', error);
await message('Failed to initialize application. Please restart.', {
title: 'Fatal Error',
okLabel: 'OK',
kind: 'error',
});
} finally {
setLoading(false);
}
}
initializeApp();
}, [
setCurrentPath,
navigateTo,
setLoading,
setError,
setFiles,
setHomeDir,
loadPinnedDirectories,
]);
// Listen for pinned directories changes from other windows
useEffect(() => {
let unlisten: (() => void) | undefined;
let isActive = true;
const setup = async () => {
const unlistenFn = await listen('pinned-directories:changed', () => {
// Reload pinned directories when another window adds/removes a pin
loadPinnedDirectories();
});
// If component unmounted before listen resolved, clean up immediately
if (!isActive) {
unlistenFn();
} else {
unlisten = unlistenFn;
}
};
setup();
return () => {
isActive = false;
unlisten?.();
};
}, [loadPinnedDirectories]);
// Apply accent color preference (system or custom) and keep it updated.
useEffect(() => {
let isActive = true;
let intervalId: number | undefined;
const normalizedCustom =
normalizeHexColor(globalPreferences.accentColorCustom) ?? DEFAULT_ACCENT;
const mode = globalPreferences.accentColorMode ?? 'system';
const applyIfChanged = (hexColor: string) => {
const normalized = normalizeHexColor(hexColor);
if (!normalized) return;
if (currentAccentRef.current === normalized) return;
currentAccentRef.current = normalized;
applyAccentVariables(normalized);
};
const updateFromSystem = async () => {
try {
const accent = await invoke<string>('get_system_accent_color');
if (!isActive) return;
const normalized = normalizeHexColor(accent) ?? DEFAULT_ACCENT;
applyIfChanged(normalized);
} catch (error) {
if (import.meta.env.DEV) {
console.warn('Could not get system accent color:', error);
}
applyIfChanged(DEFAULT_ACCENT);
}
};
if (mode === 'system') {
updateFromSystem();
intervalId = window.setInterval(updateFromSystem, ACCENT_POLL_INTERVAL_MS);
} else {
applyIfChanged(normalizedCustom);
}
return () => {
isActive = false;
if (intervalId) {
window.clearInterval(intervalId);
}
};
}, [globalPreferences.accentColorCustom, globalPreferences.accentColorMode]);
// Persist global preferences (debounced) to avoid clobbering on load.
useEffect(() => {
if (!prefsLoadedRef.current) return;
if (saveGlobalPrefsTimeoutRef.current) {
window.clearTimeout(saveGlobalPrefsTimeoutRef.current);
}
saveGlobalPrefsTimeoutRef.current = window.setTimeout(() => {
invoke('set_global_prefs', { prefs: JSON.stringify(globalPreferences) }).catch((error) => {
console.warn('Failed to persist global preferences:', error);
});
}, 250);
return () => {
if (saveGlobalPrefsTimeoutRef.current) {
window.clearTimeout(saveGlobalPrefsTimeoutRef.current);
}
};
}, [globalPreferences]);
// Persist lastDir on navigation
useEffect(() => {
if (!prefsLoadedRef.current) {
return;
}
const currentPath = useAppStore.getState().currentPath;
(async () => {
try {
await invoke('set_last_dir', { path: currentPath });
} catch (error) {
console.error('❌ Failed to save lastDir:', error);
}
})();
}, [currentPath]);
// Note: Menu checkbox sync is now handled directly in the centralized toggleHiddenFiles function
// Load directory preferences and files when currentPath changes
useEffect(() => {
// Skip if not initialized yet or if this is the first load (already handled in init)
if (!initializedRef.current || firstLoadRef.current) return;
async function loadDirectory() {
try {
setLoading(true);
setError(undefined);
// Load per-directory preferences first (so sort applies before rendering)
// Skip if preferences were recently updated to prevent race conditions
try {
const { lastPreferenceUpdate } = useAppStore.getState();
const timeSinceUpdate = Date.now() - lastPreferenceUpdate;
const shouldSkipLoad = timeSinceUpdate < 2000; // Skip if updated within 2 seconds
if (!shouldSkipLoad) {
const raw = await invoke<string>('get_dir_prefs', { path: currentPath });
if (raw) {
const parsed = JSON.parse(raw || '{}') as unknown;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
const prefs = parsed as Partial<ViewPreferences>;
useAppStore.getState().updateDirectoryPreferences(currentPath, prefs);
}
}
}
} catch (error) {
console.warn('Failed to load directory preferences:', error);
}
// Try to load the directory using streaming for better performance
// Note: Remote paths (gdrive://, smb://) don't support streaming, use non-streaming method
const isRemotePath = currentPath.includes('://');
if (isRemotePath) {
await useAppStore.getState().refreshCurrentDirectory();
// Apply smart view defaults after loading remote directory
const { files } = useAppStore.getState();
await applySmartViewDefaults(currentPath, files);
} else {
await useAppStore.getState().refreshCurrentDirectoryStreaming();
}
const refreshFailure = useAppStore.getState().error;
if (refreshFailure) {
throw new Error(refreshFailure);
}
setError(undefined); // Clear any previous errors on success
// Check if we have a pending file selection (from navigating to a file path)
// Note: With streaming, files may not be loaded yet, so we poll until found
if (pendingFileSelectionRef.current) {
const fileToSelect = pendingFileSelectionRef.current;
pendingFileSelectionRef.current = null;
// Poll for the file to appear as batches are loaded
const intervalId = setInterval(() => {
const { files, isStreamingComplete } = useAppStore.getState();
const file = files.find((f: FileItem) => f.name === fileToSelect);
if (file || isStreamingComplete) {
clearInterval(intervalId);
if (file) {
useAppStore.getState().setSelectedFiles([file.path]);
}
}
}, 100);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
const errorCode = parseErrorCode(error);
console.error('Failed to load directory:', currentPath, error);
// Handle file path: navigate to parent directory and select the file
if (errorCode === ErrorCodes.ENOTDIR) {
// Extract parent directory and filename
const normalized = currentPath.replace(/\\/g, '/').replace(/\/+$/g, '');
const lastSlash = normalized.lastIndexOf('/');
if (lastSlash >= 0) {
// Handle root directory case: /file.txt -> parent is "/"
const parentDir = lastSlash === 0 ? '/' : normalized.slice(0, lastSlash);
const fileName = normalized.slice(lastSlash + 1);
// Set pending file selection and navigate to parent
pendingFileSelectionRef.current = fileName;
navigateTo(parentDir);
return; // Exit early, don't show error dialog
}
}
// Show alert for all other directory access errors
const isPermissionError =
errorCode === ErrorCodes.EPERM || errorMessage.includes('Operation not permitted');
const hint = isPermissionError
? '\n\nAllow Marlin under System Settings → Privacy & Security → Files and Folders.'
: '';
// This was a failed navigation, not a render-state error.
setLoading(false);
setError(undefined);
// Show native alert dialog
await message(`Cannot access: ${currentPath}\n\n${errorMessage}${hint}`, {
title: 'Directory Error',
okLabel: 'OK',
kind: 'error',
});
// Navigate back to previous valid location
// Don't change files - keep showing the previous directory's content
const { goBack, pathHistory, historyIndex } = useAppStore.getState();
if (pathHistory.length > 1 && historyIndex > 0) {
// Go back in history (this will restore the previous path in the address bar)
goBack();
} else {
// If no history, replace the failed location with home so we don't leave a dead path around.
const { homeDir } = useAppStore.getState();
if (homeDir && currentPath !== homeDir) {
setCurrentPath(homeDir);
useAppStore.setState({
pathHistory: [useAppStore.getState().currentPath],
historyIndex: 0,
});
}
}
}
// Note: Don't set loading=false here - streaming handles loading state via appendStreamingBatch
}
loadDirectory();
}, [currentPath, navigateTo, setError, setLoading, setCurrentPath]);
// File system watcher for auto-reload
useEffect(() => {
if (!currentPath || loading) {
return;
}
let isActive = true;
let debounceTimer: number | undefined;
let cleanupFunction: (() => void) | undefined;
const handleDirectoryChanged = (event: Event<DirectoryChangeEventPayload>) => {
if (!isActive) return;
const payload = event.payload;
// Skip access-only changes (e.g., opening a file updates atime)
// Only refresh for actual content changes: create, delete, rename, write, modify
const changeType = (payload?.changeType || '').toLowerCase();
const isContentChange =
changeType === 'created' ||
changeType === 'removed' ||
changeType === 'modified' ||
changeType === 'renamed' ||
changeType === 'changed'; // Catch-all for other modification events
// Normalize paths for comparison (strip trailing slashes)
const normalizedPayloadPath = payload?.path?.replace(/\/+$/, '') || '';
const normalizedCurrentPath = currentPath.replace(/\/+$/, '');
if (payload && normalizedPayloadPath === normalizedCurrentPath && isContentChange) {
// Invalidate frontend thumbnail cache for modified/removed files
// (created files don't have cached thumbnails yet)
if (
(changeType === 'modified' || changeType === 'removed') &&
payload.affectedPaths &&
payload.affectedPaths.length > 0
) {
invalidateThumbnailsForPaths(payload.affectedPaths);
}
// Clear any existing debounce timer
if (debounceTimer) {
window.clearTimeout(debounceTimer);
}
// Debounce the refresh to avoid excessive reloads
debounceTimer = window.setTimeout(async () => {
if (!isActive || loading) {
return;
}
try {
const state = useAppStore.getState();
const { files: currentFiles, selectedFiles } = state;
const affectedFiles = payload.affectedFiles || [];
// For small changes, try to update locally without full refresh
if (affectedFiles.length > 0 && affectedFiles.length <= 10) {
// Build paths of affected files using a Set for O(1) lookups
const affectedPaths = new Set(
affectedFiles.map((name: string) =>
currentPath.endsWith('/') ? `${currentPath}${name}` : `${currentPath}/${name}`
)
);
// Check which affected files exist in our current list (potential removals)
const filesToRemove = currentFiles.filter((f) => affectedPaths.has(f.path));
// Verify they're actually gone by checking if they exist on disk
// We'll do this by checking if they're in the new file list after a quick refresh
const response = await invoke<{ entries: FileItem[] }>('read_directory', {
path: currentPath,
}).catch(() => null);
if (response) {
const newFilePaths = new Set(response.entries.map((f: FileItem) => f.path));
const confirmedRemovals = filesToRemove.filter((f) => !newFilePaths.has(f.path));
// O(N+M) lookup for new files instead of O(N*M)
const currentFilesByPath = new Map(currentFiles.map((cf) => [cf.path, cf]));
const newFiles = response.entries.filter(
(f: FileItem) => !currentFilesByPath.has(f.path)
);
// Find modified files - either:
// 1. Files in affectedPaths (we KNOW they changed from fs-watcher)
// 2. Files with different mtime/size (fallback detection)
const modifiedFiles = response.entries.filter((f: FileItem) => {
const existing = currentFilesByPath.get(f.path);
if (!existing) return false;
// If this file is in the affected list from fs-watcher, always consider it modified
// This handles cases where mtime precision might not detect the change
const isAffected = affectedPaths.has(f.path);
// Also detect changes via mtime/size comparison
const hasMetadataChange =
existing.modified !== f.modified || existing.size !== f.size;
return isAffected || hasMetadataChange;
});
// Handle removals with animation
if (confirmedRemovals.length > 0 && !prefersReducedMotion) {
const removedPaths = confirmedRemovals.map((f) => f.path);
state.markFilesExiting(removedPaths);
} else if (confirmedRemovals.length > 0) {
// Reduced motion: remove immediately using store action
const removedPathsSet = new Set(confirmedRemovals.map((r) => r.path));
state.removeFilesByPath(removedPathsSet);
}
// Handle modified files - update metadata so thumbnails refresh
if (modifiedFiles.length > 0) {
state.updateFiles(modifiedFiles);
}
// Handle new files - just add to list, components will handle entry animation
if (newFiles.length > 0) {
state.addFiles(newFiles);
}
// Update selection
if (selectedFiles.length > 0) {
const stillExist = selectedFiles.filter((path) => newFilePaths.has(path));
if (stillExist.length !== selectedFiles.length) {
state.setSelectedFiles(stillExist);
}
}
return; // Skip full refresh
}
}
// Fallback: full refresh for large changes or when quick check fails
await useAppStore.getState().refreshCurrentDirectoryStreaming();
} catch (error) {
console.warn('Auto-refresh failed:', error);
// Fallback to full refresh on error
void useAppStore.getState().refreshCurrentDirectoryStreaming();
}
}, 500); // 500ms debounce
}
};
const setupWatcher = async () => {
if (!isActive) return;
try {
// Start watching current directory
await invoke('start_watching_directory', { path: currentPath });
// Listen for directory change events
const unlisten = await listen('directory-changed', handleDirectoryChanged);
// Store cleanup function
cleanupFunction = () => {
unlisten();
invoke('stop_watching_directory', { path: currentPath }).catch(() => {
// Ignore errors during cleanup
});
};
} catch (error) {
console.warn('Failed to setup file watcher:', error);
}
};
setupWatcher();
return () => {
isActive = false;
if (debounceTimer) {
window.clearTimeout(debounceTimer);
}
if (cleanupFunction) {
cleanupFunction();
}
};
}, [currentPath, loading, prefersReducedMotion]);
// Persist only current directory prefs on change to avoid global clobbering
useEffect(() => {
if (!initializedRef.current) return;
const state = useAppStore.getState();
const prefs = state.directoryPreferences[state.currentPath];
if (!prefs) return;
(async () => {
try {
await invoke('set_dir_prefs', { path: state.currentPath, prefs: JSON.stringify(prefs) });
// Keep native context menu's sort state in sync
if (prefs.sortBy || prefs.sortOrder) {
const sortBy = prefs.sortBy ?? state.globalPreferences.sortBy;
const sortOrder = prefs.sortOrder ?? state.globalPreferences.sortOrder;
try {
await invoke('update_sort_menu_state', { sortBy, ascending: sortOrder === 'asc' });
} catch (error) {
console.warn('Failed to update sort menu state:', error);
}
}
} catch (error) {
console.warn('Failed to persist directory preferences:', error);
}
})();
}, [currentPath, currentDirectoryPreference]);
// View and sort controls via system menu or keyboard
useEffect(() => {
let disposed = false;
const unsubs: Array<() => void> = [];
// Tauri menu events (if provided by backend)
const register = async <Payload,>(
eventName: string,
handler: (evt?: Event<Payload>) => void | Promise<void>
) => {
try {
const unlisten = await listen<Payload>(eventName, async (evt) => {
await handler(evt);
});
if (disposed) {
unlisten();
} else {
unsubs.push(unlisten);
}
} catch (error) {
console.warn('Failed to register menu listener:', { eventName, error });
}
};
// Focused-only registration: only executes handler if this window has focus
// This prevents menu accelerators (Cmd+C/X/V etc) from firing in ALL windows
const registerFocused = async <Payload,>(
eventName: string,
handler: (evt?: Event<Payload>) => void | Promise<void>
) => {
await register<Payload>(eventName, async (evt) => {
if (!document.hasFocus()) return;