diff --git a/i18n/en.json b/i18n/en.json index 9f5f171..99cbc66 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -84,6 +84,28 @@ "The folder may contain files. Try another name or category.": "The folder may contain files. Try another name or category.", "Files from the selected folder will appear here.": "Files from the selected folder will appear here.", "Clear filters": "Clear filters", + "Preview layout": "Preview layout", + "List": "List", + "By folder": "By folder", + "Not selected": "Not selected", + "Destination folders": "Destination folders", + "Search the history": "Search the history", + "Where did a file go? Search by name": "Where did a file go? Search by name", + "No moved file has this name.": "No moved file has this name.", + "Files found in the history": "Files found in the history", + "Showing the 50 most recent matches. Type more of the name to narrow them.": "Showing the 50 most recent matches. Type more of the name to narrow them.", + "Never organize this file": "Never organize this file", + "Show in folder": "Show in folder", + "This file is no longer at the destination.": "This file is no longer at the destination.", + "View conflicts": "View conflicts", + "Open destination folder": "Open destination folder", + "This folder doesn't exist yet. It's created when files are organized.": "This folder doesn't exist yet. It's created when files are organized.", + "Could not open the folder.": "Could not open the folder.", + "Clear search": "Clear search", + "Sort files": "Sort files", + "Name (A–Z)": "Name (A–Z)", + "Newest first": "Newest first", + "Largest first": "Largest first", "Preview files scroll area": "Preview files scroll area", "Files scroll area": "Files scroll area", "Use the scroll keys to review the files and destinations.": "Use the scroll keys to review the files and destinations.", @@ -115,7 +137,6 @@ "operation loaded": "operation loaded", "operations loaded": "operations loaded", ", newest first": ", newest first", - "New operations — refresh the list": "New operations — refresh the list", "Recorded operations": "Recorded operations", "Operation": "Operation", "Preparing restore…": "Preparing restore…", @@ -546,5 +567,6 @@ "Checking for updates…": "Checking for updates…", "You have the latest version": "You have the latest version", "Couldn't check for updates": "Couldn't check for updates", - "Check your connection and try again.": "Check your connection and try again." + "Check your connection and try again.": "Check your connection and try again.", + "Settings sections": "Settings sections" } diff --git a/i18n/es.json b/i18n/es.json index 333bba5..48c2ce4 100644 --- a/i18n/es.json +++ b/i18n/es.json @@ -84,6 +84,28 @@ "The folder may contain files. Try another name or category.": "La carpeta puede contener archivos. Prueba con otro nombre o categoría.", "Files from the selected folder will appear here.": "Los archivos de la carpeta seleccionada aparecerán aquí.", "Clear filters": "Borrar filtros", + "Preview layout": "Formato de la vista previa", + "List": "Lista", + "By folder": "Por carpeta", + "Not selected": "No seleccionado", + "Destination folders": "Carpetas de destino", + "Search the history": "Buscar en el historial", + "Where did a file go? Search by name": "¿Adónde fue un archivo? Busca por nombre", + "No moved file has this name.": "Ningún archivo movido tiene este nombre.", + "Files found in the history": "Archivos encontrados en el historial", + "Showing the 50 most recent matches. Type more of the name to narrow them.": "Se muestran las 50 coincidencias más recientes. Escribe más del nombre para acotarlas.", + "Never organize this file": "No organizar nunca este archivo", + "Show in folder": "Mostrar en la carpeta", + "This file is no longer at the destination.": "Este archivo ya no está en el destino.", + "View conflicts": "Ver conflictos", + "Open destination folder": "Abrir carpeta de destino", + "This folder doesn't exist yet. It's created when files are organized.": "Esta carpeta aún no existe. Se crea cuando se organizan los archivos.", + "Could not open the folder.": "No se pudo abrir la carpeta.", + "Clear search": "Borrar búsqueda", + "Sort files": "Ordenar archivos", + "Name (A–Z)": "Nombre (A–Z)", + "Newest first": "Más recientes", + "Largest first": "Más grandes", "Preview files scroll area": "Área de desplazamiento de los archivos de la vista previa", "Files scroll area": "Área de desplazamiento de los archivos", "Use the scroll keys to review the files and destinations.": "Usa las teclas de desplazamiento para revisar los archivos y destinos.", @@ -115,7 +137,6 @@ "operation loaded": "operación cargada", "operations loaded": "operaciones cargadas", ", newest first": ", de la más reciente a la más antigua", - "New operations — refresh the list": "Nuevas operaciones — actualizar lista", "Recorded operations": "Operaciones registradas", "Operation": "Operación", "Preparing restore…": "Preparando restauración…", @@ -546,5 +567,6 @@ "Checking for updates…": "Buscando actualizaciones…", "You have the latest version": "Tienes la versión más reciente", "Couldn't check for updates": "No se pudieron buscar actualizaciones", - "Check your connection and try again.": "Revisa tu conexión e inténtalo de nuevo." + "Check your connection and try again.": "Revisa tu conexión e inténtalo de nuevo.", + "Settings sections": "Secciones de los ajustes" } diff --git a/i18n/fr.json b/i18n/fr.json index 8b6f23c..fc8f50f 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -84,6 +84,28 @@ "The folder may contain files. Try another name or category.": "Le dossier peut contenir des fichiers. Essayez un autre nom ou une autre catégorie.", "Files from the selected folder will appear here.": "Les fichiers du dossier sélectionné apparaîtront ici.", "Clear filters": "Effacer les filtres", + "Preview layout": "Présentation de l'aperçu", + "List": "Liste", + "By folder": "Par dossier", + "Not selected": "Non sélectionné", + "Destination folders": "Dossiers de destination", + "Search the history": "Rechercher dans l'historique", + "Where did a file go? Search by name": "Où est passé un fichier ? Cherchez par nom", + "No moved file has this name.": "Aucun fichier déplacé ne porte ce nom.", + "Files found in the history": "Fichiers trouvés dans l'historique", + "Showing the 50 most recent matches. Type more of the name to narrow them.": "Affichage des 50 résultats les plus récents. Tapez plus du nom pour les affiner.", + "Never organize this file": "Ne jamais organiser ce fichier", + "Show in folder": "Afficher dans le dossier", + "This file is no longer at the destination.": "Ce fichier n'est plus dans la destination.", + "View conflicts": "Voir les conflits", + "Open destination folder": "Ouvrir le dossier de destination", + "This folder doesn't exist yet. It's created when files are organized.": "Ce dossier n'existe pas encore. Il est créé quand les fichiers sont organisés.", + "Could not open the folder.": "Impossible d'ouvrir le dossier.", + "Clear search": "Effacer la recherche", + "Sort files": "Trier les fichiers", + "Name (A–Z)": "Nom (A–Z)", + "Newest first": "Plus récents", + "Largest first": "Plus volumineux", "Preview files scroll area": "Zone de défilement des fichiers de l'aperçu", "Files scroll area": "Zone de défilement des fichiers", "Use the scroll keys to review the files and destinations.": "Utilisez les touches de défilement pour vérifier les fichiers et destinations.", @@ -115,7 +137,6 @@ "operation loaded": "opération chargée", "operations loaded": "opérations chargées", ", newest first": ", de la plus récente à la plus ancienne", - "New operations — refresh the list": "Nouvelles opérations — actualiser la liste", "Recorded operations": "Opérations enregistrées", "Operation": "Opération", "Preparing restore…": "Préparation de la restauration…", @@ -546,5 +567,6 @@ "Checking for updates…": "Recherche de mises à jour…", "You have the latest version": "Vous avez la version la plus récente", "Couldn't check for updates": "Impossible de rechercher des mises à jour", - "Check your connection and try again.": "Vérifiez votre connexion et réessayez." + "Check your connection and try again.": "Vérifiez votre connexion et réessayez.", + "Settings sections": "Sections des paramètres" } diff --git a/i18n/it.json b/i18n/it.json index 2a61a33..69946eb 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -84,6 +84,28 @@ "The folder may contain files. Try another name or category.": "La cartella può contenere file. Prova un altro nome o un'altra categoria.", "Files from the selected folder will appear here.": "I file della cartella selezionata appariranno qui.", "Clear filters": "Cancella i filtri", + "Preview layout": "Formato dell'anteprima", + "List": "Elenco", + "By folder": "Per cartella", + "Not selected": "Non selezionato", + "Destination folders": "Cartelle di destinazione", + "Search the history": "Cerca nella cronologia", + "Where did a file go? Search by name": "Dove è finito un file? Cerca per nome", + "No moved file has this name.": "Nessun file spostato ha questo nome.", + "Files found in the history": "File trovati nella cronologia", + "Showing the 50 most recent matches. Type more of the name to narrow them.": "Sono mostrati i 50 risultati più recenti. Scrivi più del nome per restringerli.", + "Never organize this file": "Non organizzare mai questo file", + "Show in folder": "Mostra nella cartella", + "This file is no longer at the destination.": "Questo file non è più nella destinazione.", + "View conflicts": "Vedi i conflitti", + "Open destination folder": "Apri la cartella di destinazione", + "This folder doesn't exist yet. It's created when files are organized.": "Questa cartella non esiste ancora. Viene creata quando i file vengono organizzati.", + "Could not open the folder.": "Impossibile aprire la cartella.", + "Clear search": "Cancella ricerca", + "Sort files": "Ordina i file", + "Name (A–Z)": "Nome (A–Z)", + "Newest first": "Più recenti", + "Largest first": "Più grandi", "Preview files scroll area": "Area di scorrimento dei file dell'anteprima", "Files scroll area": "Area di scorrimento dei file", "Use the scroll keys to review the files and destinations.": "Usa i tasti di scorrimento per controllare file e destinazioni.", @@ -115,7 +137,6 @@ "operation loaded": "operazione caricata", "operations loaded": "operazioni caricate", ", newest first": ", dalla più recente alla meno recente", - "New operations — refresh the list": "Nuove operazioni — aggiorna l'elenco", "Recorded operations": "Operazioni registrate", "Operation": "Operazione", "Preparing restore…": "Preparazione del ripristino…", @@ -546,5 +567,6 @@ "Checking for updates…": "Ricerca aggiornamenti…", "You have the latest version": "Hai la versione più recente", "Couldn't check for updates": "Impossibile cercare aggiornamenti", - "Check your connection and try again.": "Controlla la connessione e riprova." + "Check your connection and try again.": "Controlla la connessione e riprova.", + "Settings sections": "Sezioni delle impostazioni" } diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json index cfca7cc..a368cf9 100644 --- a/i18n/pt-BR.json +++ b/i18n/pt-BR.json @@ -84,6 +84,28 @@ "The folder may contain files. Try another name or category.": "A pasta pode conter arquivos. Tente outro nome ou categoria.", "Files from the selected folder will appear here.": "Os arquivos da pasta selecionada aparecerão aqui.", "Clear filters": "Limpar filtros", + "Preview layout": "Formato da prévia", + "List": "Lista", + "By folder": "Por pasta", + "Not selected": "Não selecionado", + "Destination folders": "Pastas de destino", + "Search the history": "Buscar no histórico", + "Where did a file go? Search by name": "Para onde foi um arquivo? Busque pelo nome", + "No moved file has this name.": "Nenhum arquivo movido tem esse nome.", + "Files found in the history": "Arquivos encontrados no histórico", + "Showing the 50 most recent matches. Type more of the name to narrow them.": "Mostrando os 50 resultados mais recentes. Digite mais do nome para filtrar.", + "Never organize this file": "Nunca organizar este arquivo", + "Show in folder": "Mostrar na pasta", + "This file is no longer at the destination.": "Este arquivo não está mais no destino.", + "View conflicts": "Ver conflitos", + "Open destination folder": "Abrir pasta de destino", + "This folder doesn't exist yet. It's created when files are organized.": "Esta pasta ainda não existe. Ela é criada quando os arquivos são organizados.", + "Could not open the folder.": "Não foi possível abrir a pasta.", + "Clear search": "Limpar busca", + "Sort files": "Ordenar arquivos", + "Name (A–Z)": "Nome (A–Z)", + "Newest first": "Mais recentes", + "Largest first": "Maiores", "Preview files scroll area": "Área de rolagem dos arquivos da prévia", "Files scroll area": "Área de rolagem dos arquivos", "Use the scroll keys to review the files and destinations.": "Use as teclas de rolagem para conferir os arquivos e destinos.", @@ -115,7 +137,6 @@ "operation loaded": "operação carregada", "operations loaded": "operações carregadas", ", newest first": ", da mais recente para a mais antiga", - "New operations — refresh the list": "Novas operações — atualizar lista", "Recorded operations": "Operações registradas", "Operation": "Operação", "Preparing restore…": "Preparando restauração…", @@ -546,5 +567,6 @@ "Checking for updates…": "Verificando atualizações…", "You have the latest version": "Você está na versão mais recente", "Couldn't check for updates": "Não foi possível verificar atualizações", - "Check your connection and try again.": "Confira sua conexão e tente de novo." + "Check your connection and try again.": "Confira sua conexão e tente de novo.", + "Settings sections": "Seções das configurações" } diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 3430c6b..2149ab4 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -36,7 +36,7 @@ getrandom = "0.4" tauri-plugin-updater = "2" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_Foundation", "Wdk_Foundation", "Wdk_Storage_FileSystem", "Win32_Security", "Win32_System_IO", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_Globalization"] } +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_Foundation", "Wdk_Foundation", "Wdk_Storage_FileSystem", "Win32_Security", "Win32_System_IO", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell", "Win32_Globalization"] } [dev-dependencies] tempfile = "3" diff --git a/src-tauri/src/file_preview.rs b/src-tauri/src/file_preview.rs index 16d342d..f74f14b 100644 --- a/src-tauri/src/file_preview.rs +++ b/src-tauri/src/file_preview.rs @@ -79,6 +79,15 @@ pub(super) fn identity(file: &File) -> Result { )) } +/// A path without the \\?\ prefix, the form people and Explorer read. +pub(crate) fn plain_path(name: &str) -> String { + if let Some(tail) = name.strip_prefix(r"\\?\UNC\") { + format!(r"\\{tail}") + } else { + name.strip_prefix(r"\\?\").unwrap_or(name).to_owned() + } +} + fn verify_physical_path(file: &File, expected: &Path) -> Result<()> { use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW; @@ -95,15 +104,8 @@ fn verify_physical_path(file: &File, expected: &Path) -> Result<()> { return Err(t("Could not confirm the file's safe path.").into()); } let actual = String::from_utf16(&buffer[..length]).map_err(|_| changed())?; - let normalize = |name: &str| { - if let Some(tail) = name.strip_prefix(r"\\?\UNC\") { - format!(r"\\{tail}") - } else { - name.strip_prefix(r"\\?\").unwrap_or(name).to_owned() - } - }; // Compare the resolved handle, never canonicalize the requested path after opening. - if normalize(&actual) != normalize(expected.to_str().ok_or(changed())?) { + if plain_path(&actual) != plain_path(expected.to_str().ok_or(changed())?) { return Err(changed().into()); } Ok(()) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c099da8..e606a9b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -24,7 +24,7 @@ use std::{ sync::{Arc, Mutex, atomic::AtomicU64, mpsc}, time::Duration, }; -use store::{DestinationSummary, HistoryPage, Operation, OperationSummary, Store}; +use store::{DestinationSummary, FoundMovement, HistoryPage, Operation, OperationSummary, Store}; use tauri::{ AppHandle, Emitter, Manager, menu::{Menu, MenuItem}, @@ -131,6 +131,10 @@ fn sync_tray_status(app: &AppHandle, runtime: &Runtime) { // The window already shows this feedback while it has focus. fn notify(app: &AppHandle, runtime: &Runtime, title: &str, body: &str) { + notify_with_id(app, runtime, 0, title, body); +} + +fn notify_with_id(app: &AppHandle, runtime: &Runtime, id: i32, title: &str, body: &str) { use tauri_plugin_notification::NotificationExt; let enabled = runtime.store.preferences().is_ok_and(|p| p.notifications); let focused = app @@ -138,7 +142,13 @@ fn notify(app: &AppHandle, runtime: &Runtime, title: &str, body: &str) { .is_some_and(|window| window.is_focused().unwrap_or(false)); if enabled && !focused { // On Windows the plugin sends it in the background and never reports a failure. - let _ = app.notification().builder().title(title).body(body).show(); + let _ = app + .notification() + .builder() + .id(id) + .title(title) + .body(body) + .show(); } } @@ -162,7 +172,30 @@ fn notify_organized(app: &AppHandle, runtime: &Runtime) { && let Some(summary) = page.operations.first() { let title = t("Automatic organization"); - notify(app, runtime, title, &organized_message(summary)); + notify_with_id( + app, + runtime, + ORGANIZED_NOTIFICATION, + title, + &organized_message(summary), + ); + } +} + +/// The id of the "files organized" notification, so a click on it can open the history. +const ORGANIZED_NOTIFICATION: i32 = 1; + +// Windows reports a click only while the toast is on screen, not from the Action Center. +fn open_from_notification(app: &AppHandle, performed: &tauri_plugin_notification::ActionPerformed) { + if performed.action_id() != "tap" { + return; + } + show_main_window(app); + if performed + .notification() + .is_some_and(|notification| notification.id() == ORGANIZED_NOTIFICATION) + { + let _ = app.emit("open-history", ()); } } @@ -653,6 +686,18 @@ async fn history_page(app: AppHandle, before: Option) -> Result Result> { + blocking(move || { + let state = app.state::(); + lock(&state)?.store.search_movements(&query, SEARCH_LIMIT) + }) + .await +} + #[tauri::command] async fn operation_summary(app: AppHandle, operation_id: i64) -> Result { blocking(move || { @@ -799,6 +844,86 @@ async fn install_update(app: AppHandle) -> Result<()> { blocking(move || install_pending_update(&app)).await } +/// Opens the saved source or destination folder in File Explorer. Takes no path from the page. +#[tauri::command] +async fn open_folder(app: AppHandle, which: String) -> Result<()> { + blocking(move || { + let prefs = lock(&app.state::())?.store.preferences()?; + let path = match which.as_str() { + "source" => prefs.source, + "destination" => prefs.destination, + _ => return Err("Unknown folder".into()), + }; + if !Path::new(&path).is_dir() { + return Err( + t("This folder doesn't exist yet. It's created when files are organized.").into(), + ); + } + explore(&path) + }) + .await +} + +/// Shows a moved file selected in File Explorer. The path comes from the history, not from the page. +#[tauri::command] +async fn reveal_movement(app: AppHandle, operation_id: i64, movement_id: i64) -> Result<()> { + use std::os::windows::process::CommandExt; + blocking(move || { + let path = moved_destination( + &lock(&app.state::())?.store, + operation_id, + movement_id, + )?; + // The full path keeps a program named explorer.exe elsewhere from being run; /select never opens the file. + let windows = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()); + std::process::Command::new(Path::new(&windows).join("explorer.exe")) + .raw_arg(format!("/select,\"{path}\"")) + .spawn() + .map_err(|_| t("Could not open the folder."))?; + Ok(()) + }) + .await +} + +/// Where a movement still recorded as moved left its file, if the file is still there. +fn moved_destination(store: &Store, operation_id: i64, movement_id: i64) -> Result { + let missing = t("This file is no longer at the destination."); + let path = store + .operation(operation_id)? + .movements + .into_iter() + .find(|movement| movement.id == movement_id && movement.status == "moved") + .map(|movement| movement.destination) + .ok_or(missing)?; + if !Path::new(&path).is_file() { + return Err(missing.into()); + } + // The history keeps the \\?\ form, which Explorer doesn't read. + Ok(file_preview::plain_path(&path)) +} + +fn explore(path: &str) -> Result<()> { + use windows_sys::Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL}; + let wide = |text: &str| text.encode_utf16().chain(Some(0)).collect::>(); + let (verb, file) = (wide("explore"), wide(path)); + // "explore" only opens folders: a path swapped for a program is never run. + let code = unsafe { + ShellExecuteW( + std::ptr::null_mut(), + verb.as_ptr(), + file.as_ptr(), + std::ptr::null(), + std::ptr::null(), + SW_SHOWNORMAL, + ) + }; + if code as isize > 32 { + Ok(()) + } else { + Err(t("Could not open the folder.").into()) + } +} + #[tauri::command] async fn retry_monitoring(app: AppHandle) -> Result<()> { blocking(move || { @@ -910,7 +1035,10 @@ fn run_application() -> std::result::Result<(), startup::StartupError> { save_preferences, check_update, install_update, - retry_monitoring + retry_monitoring, + open_folder, + reveal_movement, + search_history ]) .build(tauri::generate_context!()) .map_err(|_| startup::StartupError::Runtime)?; @@ -954,6 +1082,13 @@ fn run_application() -> std::result::Result<(), startup::StartupError> { media_previews: Mutex::new(media_preview::Sessions::default()), update: Mutex::new(None), }); + { + use tauri_plugin_notification::NotificationExt; + let handle = app.handle().clone(); + let _ = app + .notification() + .on_action(move |performed| open_from_notification(&handle, performed)); + } let handle = app.handle().clone(); std::thread::Builder::new() .spawn(move || monitor::worker(handle, receiver)) diff --git a/src-tauri/src/store.rs b/src-tauri/src/store.rs index 7264230..f22cac8 100644 --- a/src-tauri/src/store.rs +++ b/src-tauri/src/store.rs @@ -26,6 +26,17 @@ pub struct Movement { pub digest: String, } +/// A move found by a search of the whole history, with the operation it belongs to. +#[derive(Serialize)] +pub struct FoundMovement { + pub id: i64, + pub operation_id: i64, + pub created: i64, + pub source: String, + pub destination: String, + pub status: String, +} + #[derive(Serialize)] pub struct Operation { pub id: i64, @@ -211,6 +222,42 @@ impl Store { Ok(()) } + /// Up to `limit` moves whose file name contains `query`, newest first. The match ignores case + /// in every language, which SQLite's LIKE only does for ASCII, so the names are compared here. + pub fn search_movements(&self, query: &str, limit: usize) -> Result> { + let query = query.trim().to_lowercase(); + if query.is_empty() { + return Ok(Vec::new()); + } + let mut statement = self.db.prepare("SELECT m.id,m.operation_id,o.created,m.source,m.destination,m.status FROM movements m JOIN operations o ON o.id=m.operation_id ORDER BY m.id DESC").map_err(|e| e.to_string())?; + let rows = statement + .query_map([], |r| { + Ok(FoundMovement { + id: r.get(0)?, + operation_id: r.get(1)?, + created: r.get(2)?, + source: r.get(3)?, + destination: r.get(4)?, + status: r.get(5)?, + }) + }) + .map_err(|e| e.to_string())?; + let mut found = Vec::new(); + for row in rows { + let row = row.map_err(|e| e.to_string())?; + let name = Path::new(&row.source) + .file_name() + .map(|name| name.to_string_lossy().to_lowercase()); + if name.is_some_and(|name| name.contains(&query)) { + found.push(row); + if found.len() == limit { + break; + } + } + } + Ok(found) + } + pub fn movements(&self, operation: i64) -> Result> { let mut query = self.db.prepare("SELECT id,source,destination,status,error,size,modified,digest FROM movements WHERE operation_id=?1 ORDER BY id").map_err(|e| e.to_string())?; query diff --git a/src-tauri/src/tests.rs b/src-tauri/src/tests.rs index 297fe01..3e7890c 100644 --- a/src-tauri/src/tests.rs +++ b/src-tauri/src/tests.rs @@ -2257,3 +2257,127 @@ fn undo_waits_for_an_unplugged_source_and_retries_later() { assert_eq!(fs::read(usb.join("notes.txt")).unwrap(), b"notes"); assert!(!organized.exists()); } + +#[test] +fn reveal_only_finds_files_still_moved_and_present() { + let (temp, runtime, _) = fixture(); + let store = &runtime.store; + let file = fs::canonicalize(temp.path()).unwrap().join("a.txt"); + fs::write(&file, b"a").unwrap(); + let verbatim = file.to_string_lossy().into_owned(); + assert!(verbatim.starts_with(r"\\?\")); + let stamp = Stamp { + size: 1, + modified: 0, + }; + let operation = store.begin("manual").unwrap(); + let moved = store + .record( + operation, + "/isolated/a.txt", + &verbatim, + "moved", + &stamp, + "x", + ) + .unwrap(); + let undone = store + .record( + operation, + "/isolated/b.txt", + &verbatim, + "undone", + &stamp, + "x", + ) + .unwrap(); + // Explorer gets the plain form of the recorded path. + assert_eq!( + moved_destination(store, operation, moved).unwrap(), + file_preview::plain_path(&verbatim) + ); + assert!( + !moved_destination(store, operation, moved) + .unwrap() + .starts_with(r"\\?\") + ); + assert!(moved_destination(store, operation, undone).is_err()); + assert!(moved_destination(store, operation + 1, moved).is_err()); + fs::remove_file(&file).unwrap(); + assert!(moved_destination(store, operation, moved).is_err()); +} + +#[test] +fn plain_path_drops_only_the_verbatim_prefix() { + assert_eq!( + file_preview::plain_path(r"\\?\D:\Organized\a.pdf"), + r"D:\Organized\a.pdf" + ); + assert_eq!( + file_preview::plain_path(r"\\?\UNC\server\share\a.pdf"), + r"\\server\share\a.pdf" + ); + assert_eq!( + file_preview::plain_path(r"D:\Organized\a.pdf"), + r"D:\Organized\a.pdf" + ); +} + +#[test] +fn history_search_matches_file_names_in_any_case_newest_first() { + let (_temp, runtime, _) = fixture(); + let store = &runtime.store; + let stamp = Stamp { + size: 1, + modified: 0, + }; + let first = store.begin("manual").unwrap(); + let older = store + .record( + first, + r"C:\contratos\Contrato-Ação.pdf", + r"D:\Org\Documentos\Contrato-Ação.pdf", + "moved", + &stamp, + "x", + ) + .unwrap(); + let second = store.begin("automatic").unwrap(); + let newer = store + .record( + second, + r"C:\Downloads\CONTRATO-AÇÃO (2).pdf", + r"D:\Org\Documentos\CONTRATO-AÇÃO (2).pdf", + "undone", + &stamp, + "x", + ) + .unwrap(); + // The folder name matches, but the search is about file names. + store + .record( + second, + r"C:\contratos\foto.png", + r"D:\Org\Imagens\foto.png", + "moved", + &stamp, + "x", + ) + .unwrap(); + let found = |query: &str, limit: usize| { + store + .search_movements(query, limit) + .unwrap() + .iter() + .map(|movement| (movement.id, movement.operation_id)) + .collect::>() + }; + // Non-ASCII letters match in any case, which SQLite's LIKE would miss. + assert_eq!( + found(" contrato-ação ", 50), + [(newer, second), (older, first)] + ); + assert_eq!(found("contrato", 1), [(newer, second)]); + assert!(found(" ", 50).is_empty()); + assert!(found("inexistente", 50).is_empty()); +} diff --git a/src/App.css b/src/App.css index 3ac48b7..6ac5540 100644 --- a/src/App.css +++ b/src/App.css @@ -60,22 +60,38 @@ h1:focus { outline: none; } .app-shell { min-height: 100dvh; } .sidebar { width: var(--sidebar-width); position: fixed; inset: 0 auto 0 0; display: flex; flex-direction: column; padding: var(--space-4) var(--space-3); background: var(--sidebar); border-right: 1px solid var(--border); overflow-y: auto; z-index: 10; } -.brand { display: flex; align-items: center; gap: var(--space-2); min-height: 32px; padding: 0 var(--space-2); font-size: var(--text-body); font-weight: 500; line-height: 1.25; } -.brand-icon { display: grid; place-items: center; width: 24px; height: 24px; flex-shrink: 0; } -.brand-icon img { display: block; width: 24px; height: 24px; } -.sidebar nav { position: relative; margin-top: var(--space-4); display: grid; gap: 2px; } -.nav-item { position: relative; display: flex; align-items: center; gap: var(--space-2); width: 100%; min-height: 32px; padding: var(--space-1) var(--space-2); border-radius: var(--radius); background: transparent; color: var(--muted); font-size: var(--text-control); text-align: left; } +.brand { display: flex; align-items: center; gap: 10px; min-height: 36px; padding: 0 var(--space-2); font-size: var(--text-body); font-weight: 600; letter-spacing: -0.01em; line-height: 1.25; } +.brand-icon { display: grid; place-items: center; width: 28px; height: 28px; flex-shrink: 0; } +.brand-icon img { display: block; width: 28px; height: 28px; } +.sidebar nav { position: relative; margin-top: var(--space-4); padding-top: var(--space-4); border-top: 1px solid var(--border); display: grid; gap: 2px; } +.nav-item { position: relative; display: flex; align-items: center; gap: 10px; width: 100%; min-height: 34px; padding: var(--space-1) 10px; border-radius: var(--radius); background: transparent; color: var(--muted); font-size: var(--text-control); text-align: left; } +.nav-item > svg { color: var(--faint); } .nav-item:hover { background: var(--accent); color: var(--foreground); } -.nav-item.active { background: var(--surface-selected); color: var(--foreground); font-weight: 500; } +.nav-item:hover > svg { color: var(--foreground); } +.nav-item.active { background: color-mix(in srgb, var(--brand) 12%, var(--sidebar)); color: var(--foreground); font-weight: 500; } .nav-indicator { position: absolute; z-index: 1; top: 0; left: 0; width: 2px; border-radius: 2px; background: var(--brand); pointer-events: none; } .motion-collapse { overflow: hidden; } .nav-item.active > svg { color: var(--brand); } .nav-item:focus-visible { outline-offset: -2px; } -.nav-count { margin-left: auto; color: var(--faint); font-family: var(--font-code); font-size: var(--text-meta); font-variant-numeric: tabular-nums; } +.nav-count { margin-left: auto; min-width: 22px; padding: 0 6px; border-radius: 999px; background: var(--accent); color: var(--muted); font-family: var(--font-code); font-size: var(--text-meta); font-weight: 400; line-height: 18px; text-align: center; font-variant-numeric: tabular-nums; } +.nav-item.active .nav-count { background: color-mix(in srgb, var(--brand) 22%, transparent); color: var(--foreground); } .draft-dot { width: 6px; height: 6px; border-radius: 50%; margin-left: auto; background: var(--warning-foreground); } -.sidebar-bottom { margin-top: auto; padding: var(--space-6) var(--space-2) 0; display: grid; gap: var(--space-2); font-size: var(--text-meta); } +.sidebar-bottom { margin-top: auto; padding-top: var(--space-6); display: grid; gap: var(--space-2); font-size: var(--text-meta); } +/* The folder being organized and its watch, in view from every page. */ +.sidebar-folder { display: grid; gap: var(--space-2); padding: var(--space-2); border: 1px solid var(--border); border-radius: var(--radius-panel); background: var(--card); } +.sidebar-route { display: grid; gap: 2px; min-width: 0; padding: var(--space-1) 6px; border: 0; border-radius: var(--radius); background: transparent; color: var(--foreground); text-align: left; } +.sidebar-route:hover { background: var(--accent); } +.route-from, .route-to { display: flex; align-items: center; gap: 6px; min-width: 0; } +.route-from { font-size: var(--text-control); font-weight: 500; } +.route-to { color: var(--muted); } +.route-from svg, .route-to svg { color: var(--faint); } +.ellipsis { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sidebar-bottom .app-version { padding: 0 var(--space-2); } .app-version { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); color: var(--faint); flex-wrap: wrap; } -.app-version > span:last-child { font-family: var(--font-code); } +.app-version > button { padding: 2px var(--space-1); border: 0; border-radius: var(--radius-sm); background: transparent; color: inherit; font-family: var(--font-code); font-size: inherit; } +.app-version > button:hover, .sidebar-bottom .monitor-status:hover { color: var(--foreground); background: var(--accent); } +.sidebar-bottom .monitor-status { border: 0; font: inherit; } +.sidebar-bottom .monitor-status.online:hover { color: var(--success-foreground); background: color-mix(in srgb, var(--success-surface) 70%, var(--accent)); } .small-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; display: inline-block; flex-shrink: 0; } .main-shell { min-width: 0; margin-left: var(--sidebar-width); } .content { max-width: 1440px; margin: 0 auto; padding: var(--space-6) var(--content-gutter); } @@ -96,6 +112,11 @@ h1:focus { outline: none; } .source-meta { display: flex; align-items: center; gap: var(--space-4); margin-top: var(--space-2); flex-wrap: wrap; font-size: var(--text-meta); color: var(--muted); } .monitor-status { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--muted); } .monitor-status.online { color: var(--success-foreground); } +/* A slow ring around the dot says the folder is being watched right now. */ +.monitor-status.online .small-dot { animation: monitor-pulse 2.4s ease-out infinite; } +@keyframes monitor-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 50%, transparent); } 70%, 100% { box-shadow: 0 0 0 5px transparent; } } +.sidebar-bottom .monitor-status { justify-self: start; padding: 3px var(--space-2); border-radius: 999px; background: var(--accent); } +.sidebar-bottom .monitor-status.online { background: var(--success-surface); } .source-destination { flex: 1; min-width: 140px; overflow-wrap: anywhere; } .source-destination code { display: inline; margin-left: var(--space-1); color: var(--faint); } .source-meta > [data-slot=button] { margin-left: auto; } @@ -120,6 +141,7 @@ h1:focus { outline: none; } .file-summary dt { font-size: var(--text-control); color: var(--muted); } .file-summary dd { font-size: var(--text-figure); font-weight: 500; line-height: 1.25; font-variant-numeric: tabular-nums; } .file-summary span { display: block; font-weight: 400; font-size: var(--text-meta); line-height: 1.5; color: var(--faint); } +.file-summary .stat-link { padding: 0; border: 0; background: none; color: var(--brand); font: inherit; text-decoration: underline; text-underline-offset: 3px; } .file-summary .animated-count { display: inline-grid; position: relative; min-width: 3ch; font: inherit; line-height: inherit; color: inherit; } .file-summary .animated-count > span { font: inherit; line-height: inherit; color: inherit; } .count-width { visibility: hidden; } @@ -146,6 +168,23 @@ h1:focus { outline: none; } .activity:focus-visible { outline-offset: -2px; } .activity[aria-expanded=true] { background: var(--surface-selected); } .activity-icon { color: var(--faint); display: grid; place-items: center; } +/* A thin mark on the newest operation, and a tint that fades on one that arrives while the page is open. */ +.activity.latest, .history-operation.latest > .history-header { box-shadow: inset 2px 0 0 var(--brand); } +.activity.arrived, .history-operation.arrived { animation: arrive 2.4s ease-out; } +@keyframes arrive { from { opacity: 0; transform: translateY(-6px); background-color: color-mix(in srgb, var(--brand) 16%, transparent); } 25% { opacity: 1; transform: none; } to { background-color: transparent; } } +.preview-tree { overflow-y: auto; padding: var(--space-2) var(--space-3); } +.preview-tree-root { display: flex; align-items: center; gap: 6px; padding: var(--space-1) 0 var(--space-2); color: var(--muted); font-family: var(--font-code); font-size: var(--text-meta); } +.preview-tree-root svg, .preview-tree summary > svg { color: var(--brand); flex-shrink: 0; } +.preview-tree summary { display: flex; align-items: center; gap: var(--space-2); padding: var(--space-1) var(--space-2); border-radius: var(--radius); cursor: default; font-size: var(--text-control); } +.preview-tree summary:hover { background: var(--accent); } +.preview-tree summary:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; } +.preview-tree-count { color: var(--muted); } +.preview-tree summary > .preview-tree-chevron { color: var(--faint); } +.preview-tree details[open] > summary > .preview-tree-chevron { transform: rotate(90deg); } +.preview-tree details ul { margin: 0 0 var(--space-2) 37px; padding-left: var(--space-3); border-left: 1px solid var(--border); } +.preview-tree details li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px var(--space-2); padding: 3px 0; font-size: var(--text-control); } +.preview-tree details li small { flex-basis: 100%; color: var(--muted); font-size: var(--text-meta); } +.preview-tree .excluded .preview-tree-name { color: var(--faint); text-decoration: line-through; } .activity-icon.warning { color: var(--warning-foreground); } .activity-copy { flex: 1; min-width: 0; } .activity strong { font-size: var(--text-control); font-weight: 500; display: block; } @@ -154,6 +193,11 @@ h1:focus { outline: none; } .operation-id { font-family: var(--font-code); font-variant-numeric: tabular-nums; } .recent-list > .activity + .activity { border-top: 1px solid var(--border); } .history-list { margin-top: var(--space-3); border-top: 1px solid var(--border); } +.history-search .search-field { display: block; max-width: 480px; } +.history-search-results { margin-top: var(--space-2); border-top: 1px solid var(--border); } +.history-search-results small { color: var(--faint); font-size: var(--text-meta); } +.history-search-route { display: flex; align-items: center; gap: 6px; margin-top: 2px; color: var(--muted); font-family: var(--font-code); font-size: var(--text-meta); overflow-wrap: anywhere; } +.history-search-note { margin-top: var(--space-2); color: var(--muted); font-size: var(--text-control); } .history-operation { border-bottom: 1px solid var(--border); } .history-header { display: flex; align-items: center; gap: var(--space-3); padding-right: var(--space-2); } .history-header > .activity { flex: 1; } @@ -185,7 +229,8 @@ h1:focus { outline: none; } .banner { display: flex; align-items: flex-start; gap: var(--space-3); padding: var(--space-4); margin-bottom: var(--space-4); border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); color: var(--muted); } .banner > div { flex: 1; min-width: 0; } -.banner > svg { margin-top: 2px; } +.banner > svg { margin-top: 2px; color: var(--brand); } +.error-banner > svg, .success-banner > svg { color: inherit; } .banner strong { font-size: var(--text-control); font-weight: 500; color: var(--foreground); } .banner p { font-size: var(--text-control); overflow-wrap: anywhere; margin-top: var(--space-1); } .error-banner { background: var(--error-surface); border-color: color-mix(in srgb,var(--error-foreground) 40%,var(--border)); color: var(--error-foreground); } @@ -198,6 +243,9 @@ h1:focus { outline: none; } .empty h2, .empty h3 { color: var(--foreground); font-size: var(--text-body); font-weight: 500; } .empty p { font-size: var(--text-control); max-width: 380px; } .empty.compact { padding: var(--space-8) var(--space-3); } +/* A faint dot grid that fades out toward the edges gives empty space a shape, without content. */ +.empty { position: relative; isolation: isolate; } +.empty::before { content: ""; position: absolute; inset: 0; z-index: -1; pointer-events: none; background-image: radial-gradient(circle, color-mix(in srgb, var(--foreground) 22%, transparent) 1px, transparent 1.5px); background-size: 16px 16px; background-position: center; mask-image: radial-gradient(ellipse at center, #000 10%, transparent 70%); } .progress-panel { display: flex; gap: var(--space-3); padding: var(--space-4); border: 1px solid var(--border); border-left: 2px solid var(--brand); background: var(--card); border-radius: var(--radius); margin-bottom: var(--space-4); } .progress-panel > svg { color: var(--brand); margin-top: 2px; } .progress-panel > div { flex: 1; min-width: 0; } @@ -217,7 +265,9 @@ progress::-moz-progress-bar { background: var(--brand); } .explorer-toolbar .search-field > span:first-child, .explorer-toolbar .filter-select > span { display: block; color: var(--muted); font-size: var(--text-meta); margin-bottom: var(--space-1); } .search-input { position: relative; display: block; } .search-input > svg { position: absolute; top: 8px; left: 8px; color: var(--faint); pointer-events: none; } -.search-input input { padding-left: 32px; } +.search-input input { padding-left: 32px; padding-right: 32px; } +.search-clear { position: absolute; top: 4px; right: 4px; display: grid; place-items: center; width: 24px; height: 24px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--faint); } +.search-clear:hover { background: var(--accent); color: var(--foreground); } .filter-select select { height: 32px; background: var(--card); border: 1px solid var(--control-border); color: var(--foreground); padding: 0 var(--space-2); border-radius: var(--radius); font-size: var(--text-control); max-width: 100%; } .file-count { margin-left: auto; color: var(--faint); font-family: var(--font-code); font-size: var(--text-meta); white-space: nowrap; } .table-scroll { overflow: auto; overflow-anchor: none; max-height: max(280px,calc(100dvh - 212px)); border-block: 1px solid var(--border); } @@ -256,6 +306,7 @@ tbody tr:has(.file-disclosure[aria-expanded=true]) { background: var(--surface-s .file-disclosure:focus-visible { outline-offset: 0; } .file-disclosure[aria-expanded=true] > svg { transform: rotate(90deg); } .file-details p { overflow-wrap: anywhere; margin-top: var(--space-1); } +.file-details [data-slot=button] { height: auto; min-height: 28px; max-width: 100%; margin-top: var(--space-2); font-family: var(--font-ui); white-space: normal; text-align: left; } .destination { position: relative; display: flex; align-items: flex-start; gap: var(--space-2); font-family: var(--font-code); font-size: var(--text-meta); line-height: 16px; padding-block: var(--space-1); overflow-wrap: anywhere; } .destination > svg { color: var(--brand); } .table-footer { display: flex; align-items: center; gap: var(--space-2); padding-top: var(--space-3); color: var(--faint); font-size: var(--text-meta); } @@ -324,7 +375,7 @@ tbody tr:has(.file-disclosure[aria-expanded=true]) { background: var(--surface-s [data-slot=dialog-footer] { flex-wrap: wrap; padding-top: var(--space-4); border-top: 1px solid var(--border); } [data-slot=dialog-content] .progress-panel { margin-bottom: 0; } .preview-dialog { width: min(1080px,calc(100vw - 48px)); max-width: min(1080px,calc(100vw - 48px)); } -.result-dialog { width: min(560px,calc(100vw - 48px)); max-width: min(560px,calc(100vw - 48px)); } +.result-dialog { width: min(680px,calc(100vw - 48px)); max-width: min(680px,calc(100vw - 48px)); } .result-dialog .progress-panel strong, .result-dialog .progress-panel p { font-size: var(--text-body); } .file-view-button { width: 24px; height: 24px; flex-shrink: 0; color: var(--faint); } .file-preview-dialog { width: min(800px,calc(100vw - 48px)); max-width: min(800px,calc(100vw - 48px)); } @@ -335,8 +386,8 @@ tbody tr:has(.file-disclosure[aria-expanded=true]) { background: var(--surface-s .file-preview-metadata dt { color: var(--muted); } .file-preview-metadata dd { overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } .preview-files { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius); } -.preview-files .table-scroll { max-height: max(200px,calc(100dvh - 340px)); border: 0; } -.preview-dialog:has(.progress-panel) .preview-files .table-scroll { max-height: max(160px,calc(100dvh - 420px)); } +.preview-files .table-scroll, .preview-tree { max-height: max(200px,calc(100dvh - 340px)); border: 0; } +.preview-dialog:has(.progress-panel) .preview-files .table-scroll, .preview-dialog:has(.progress-panel) .preview-tree { max-height: max(160px,calc(100dvh - 420px)); } .preview-files th { background: var(--card); } .preview-check { width: 16px; height: 16px; margin: 2px var(--space-2) 0 0; accent-color: var(--brand); flex-shrink: 0; vertical-align: text-bottom; } .preview-check:focus-visible { outline: 2px solid var(--ring); outline-offset: 3px; } @@ -367,6 +418,14 @@ tbody tr:has(.file-disclosure[aria-expanded=true]) { background: var(--surface-s /* Radix Presence owns exit/unmount and focus restoration through animationend. */ @keyframes dialog-close { to { opacity: 0; transform: translateY(4px) scale(.99); } } .spin { animation: spin 1s linear infinite; } +/* Settings: one tab per group of options; the save bar below still covers all of them. */ +.settings-nav { position: sticky; top: 0; z-index: 5; display: flex; gap: var(--space-1); margin: 0 calc(var(--space-2) * -1) var(--space-2); padding: var(--space-2); overflow-x: auto; background: var(--background); border-bottom: 1px solid var(--border); scrollbar-width: none; } +.settings-nav [role=tab] { display: inline-flex; border: 0; background: transparent; align-items: center; gap: 6px; flex-shrink: 0; min-height: 30px; padding: 0 var(--space-3); border-radius: var(--radius); color: var(--muted); font-size: var(--text-control); text-decoration: none; white-space: nowrap; } +.settings-nav [role=tab]:hover { background: var(--accent); color: var(--foreground); } +.settings-nav [role=tab][data-state=active] { background: var(--surface-selected); color: var(--foreground); font-weight: 500; } +.settings-nav [role=tab][data-state=active] svg { color: var(--brand); } +.settings-nav [role=tab]:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; } +.settings-panel:focus-visible { outline: none; } .update-check { display: flex; align-items: center; flex-wrap: wrap; gap: var(--space-3); padding-top: var(--space-2); } @keyframes spin { to { transform: rotate(360deg); } } @media (max-width: 1100px) { :root { --content-gutter: 24px; }.overview-lists { gap: var(--space-6); grid-template-columns: minmax(0,1fr) minmax(0,1fr); }.settings-section { grid-template-columns: 150px minmax(0,1fr); gap: var(--space-4); } } diff --git a/src/App.test.tsx b/src/App.test.tsx index af1ce61..ba24ff3 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -12,7 +12,7 @@ import type { ReactNode } from "react"; const mocks = vi.hoisted(() => ({ snapshot: vi.fn(), history: vi.fn(), operation: vi.fn(), operationSummary: vi.fn(), destinations: vi.fn(), filePreview: vi.fn(), preview: vi.fn(), organize: vi.fn(), undo: vi.fn(), save: vi.fn(), retryMonitoring: vi.fn(), - installUpdate: vi.fn().mockResolvedValue(undefined), close: vi.fn(), hide: vi.fn().mockResolvedValue(undefined), choose: vi.fn(), + installUpdate: vi.fn().mockResolvedValue(undefined), openFolder: vi.fn().mockResolvedValue(undefined), close: vi.fn(), hide: vi.fn().mockResolvedValue(undefined), choose: vi.fn(), events: new Map void>(), closeHandler: null as null | ((event: { preventDefault: () => void }) => void), sound: vi.fn(), soundStop: vi.fn(), @@ -29,7 +29,7 @@ vi.mock("@web-kits/audio/react", () => ({ })); vi.mock("./lib/api", async importOriginal => ({ ...await importOriginal(), native: true, - api: { snapshot: mocks.snapshot, history: mocks.history, operation: mocks.operation, operationSummary: mocks.operationSummary, destinations: mocks.destinations, filePreview: mocks.filePreview, preview: mocks.preview, organize: mocks.organize, undo: mocks.undo, save: mocks.save, retryMonitoring: mocks.retryMonitoring, installUpdate: mocks.installUpdate }, + api: { snapshot: mocks.snapshot, history: mocks.history, operation: mocks.operation, operationSummary: mocks.operationSummary, destinations: mocks.destinations, filePreview: mocks.filePreview, preview: mocks.preview, organize: mocks.organize, undo: mocks.undo, save: mocks.save, retryMonitoring: mocks.retryMonitoring, installUpdate: mocks.installUpdate, openFolder: mocks.openFolder }, })); vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async (name, callback) => { mocks.events.set(name, callback); return () => mocks.events.delete(name); @@ -58,6 +58,17 @@ function navigate(name: string) { const navigation = screen.getByRole("navigation", { name: "Navegação principal" }); fireEvent.click(within(navigation).getByRole("button", { name })); } +// Settings show one tab at a time: find a control on whichever tab holds it. +function setting(role: string, name: string) { + const found = screen.queryByRole(role, { name }); + if (found) return found; + for (const tab of screen.getAllByRole("tab")) { + fireEvent.mouseDown(tab); + const element = screen.queryByRole(role, { name }); + if (element) return element; + } + return screen.getByRole(role, { name }); +} function progress(payload: Progress) { act(() => mocks.events.get("organizer-progress")?.({ payload })); } async function updateSnapshot() { act(() => mocks.events.get("organizer-changed")?.({ payload: null })); @@ -148,7 +159,7 @@ describe("histórico paginado", () => { expect(within(returned).getByRole("button", { name: /1 arquivo restaurado/, expanded: true })).toBeTruthy(); expect((within(returned).getByRole("button", { name: "Desfazer" }) as HTMLButtonElement).disabled).toBe(true); }, 10_000); - it("mantém a página após erro, oferece nova tentativa e sinaliza chegadas sem inserir duplicatas", async () => { + it("mantém a página após erro, oferece nova tentativa e insere chegadas no topo sem duplicatas", async () => { seedHistory(5); mocks.snapshot.mockResolvedValueOnce({ ...snapshotPayload(), history: snapshot.history.slice(0, 2).map(summarizeOperation), history_cursor: 4 }); await start(); navigate("Histórico"); @@ -162,14 +173,10 @@ describe("histórico paginado", () => { fireEvent.click(within(row).getByRole("button", { name: /1 arquivo organizado/ })); snapshot.history.unshift({ ...structuredClone(operation), id: 6 }); await updateSnapshot(); - expect(screen.queryByRole("region", { name: "Operação 6" })).toBeNull(); - expect(screen.getByRole("region", { name: "Operação 1" })).toBe(row); - mocks.history.mockResolvedValueOnce({ operations: snapshot.history.slice(0, 2).map(summarizeOperation), next_cursor: 5 }); - fireEvent.click(screen.getByRole("button", { name: "Novas operações — atualizar lista" })); + // The new operation joins the top on its own; the open one stays open. await screen.findByRole("region", { name: "Operação 6" }); expect(screen.getByRole("region", { name: "Operação 1" })).toBe(row); - fireEvent.click(screen.getByRole("button", { name: "Carregar mais" })); - await screen.findByRole("region", { name: "Operação 4" }); + expect(within(row).getByRole("button", { name: /1 arquivo organizado/ }).getAttribute("aria-expanded")).toBe("true"); const ids = [...document.querySelectorAll(".history-operation")].map(row => row.getAttribute("aria-label")); expect(ids).toHaveLength(new Set(ids).size); }); @@ -181,7 +188,7 @@ describe("destinos recusados pelo aplicativo", () => { it("recusa salvar um destino incompatível e preserva o rascunho até descartar", async () => { await start(); navigate("Configurações"); mocks.choose.mockResolvedValueOnce("/isolated/unavailable"); - fireEvent.click(screen.getByRole("button", { name: "Selecionar destino da organização" })); + fireEvent.click(setting("button", "Selecionar destino da organização")); await screen.findByText("/isolated/unavailable"); mocks.save.mockRejectedValueOnce(folderError); const save = screen.getByRole("button", { name: "Salvar preferências" }); @@ -212,7 +219,7 @@ describe("destinos recusados pelo aplicativo", () => { fireEvent.click(within(warning).getByRole("button", { name: "Revisar pastas" })); expect(screen.getByText("/isolated/unavailable")).toBeTruthy(); mocks.choose.mockResolvedValueOnce(initial.destination); - fireEvent.click(screen.getByRole("button", { name: "Selecionar destino da organização" })); + fireEvent.click(setting("button", "Selecionar destino da organização")); await screen.findByText(initial.destination); mocks.save.mockImplementationOnce(async prefs => { snapshot.preferences = prefs; snapshot.scan_error = null; return prefs; @@ -290,6 +297,14 @@ describe("feedback sonoro de ações reais", () => { await start(); await confirmOrganization(); await waitFor(() => expect(mocks.sound).toHaveBeenCalledExactlyOnceWith(sounds.warning)); }); + it("desfaz direto pela janela de resultado", async () => { + mocks.organize.mockImplementationOnce(async () => { snapshot.history = [structuredClone(operation)]; return 42; }); + await start(); + const dialog = await confirmOrganization(); + fireEvent.click(await within(dialog).findByRole("button", { name: "Desfazer" })); + expect(await screen.findByRole("dialog", { name: "Restaurar os arquivos para a origem?" })).toBeTruthy(); + expect(mocks.operation).toHaveBeenCalledWith(42); + }); it.each([true, false])("restauração completa=%s utiliza apenas o feedback adequado", async complete => { snapshot.history = [structuredClone(operation)]; mocks.undo.mockImplementationOnce(async () => { @@ -305,17 +320,17 @@ describe("feedback sonoro de ações reais", () => { }); it.each([true, false])("salvar preferências combinadas com sucesso=%s preserva áudio pendente até confirmar", async success => { await start(); navigate("Configurações"); - fireEvent.change(screen.getByRole("slider", { name: "Volume" }), { target: { value: "30" } }); + fireEvent.change(setting("slider", "Volume"), { target: { value: "30" } }); expect((screen.getByRole("button", { name: "Salvar preferências" }) as HTMLButtonElement).disabled).toBe(false); expect(localStorage.getItem(audioStorageKey)).toBeNull(); - fireEvent.click(screen.getByRole("switch", { name: "Organizar novos arquivos" })); + fireEvent.click(setting("switch", "Organizar novos arquivos")); if (!success) mocks.save.mockRejectedValueOnce("Não foi possível salvar"); fireEvent.click(screen.getByRole("button", { name: "Salvar preferências" })); await waitFor(() => expect(mocks.sound).toHaveBeenCalledExactlyOnceWith(success ? sounds.saved : sounds.warning)); if (success) expect(localStorage.getItem(audioStorageKey)).toContain('"volume":0.3'); else { expect(localStorage.getItem(audioStorageKey)).toBeNull(); - expect((screen.getByRole("slider", { name: "Volume" }) as HTMLInputElement).value).toBe("30"); + expect((setting("slider", "Volume") as HTMLInputElement).value).toBe("30"); expect((screen.getByRole("button", { name: "Salvar preferências" }) as HTMLButtonElement).disabled).toBe(false); } }); @@ -324,7 +339,7 @@ describe("feedback sonoro de ações reais", () => { for (const phase of ["preparing", "organizing", "completed"] as const) progress({ kind: "automatic", phase, total: 1, completed: phase === "completed" ? 1 : 0, name: "", operation_id: phase === "preparing" ? null : 42 }); await waitFor(() => expect((screen.getByRole("button", { name: "Atualizar arquivos" }) as HTMLButtonElement).disabled).toBe(false)); navigate("Histórico"); navigate("Configurações"); - fireEvent.click(screen.getByRole("switch", { name: "Organizar novos arquivos" })); + fireEvent.click(setting("switch", "Organizar novos arquivos")); fireEvent.click(screen.getByRole("button", { name: "Descartar alterações" })); navigate("Visão geral"); await openPreview(); expect(mocks.sound).not.toHaveBeenCalled(); @@ -352,7 +367,7 @@ describe("feedback sonoro de ações reais", () => { }); it("salvamento confirmado não toca aviso extra se a atualização posterior falhar", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("switch", { name: "Organizar novos arquivos" })); + fireEvent.click(setting("switch", "Organizar novos arquivos")); mocks.snapshot.mockRejectedValueOnce("Falha ao consultar estado"); fireEvent.click(screen.getByRole("button", { name: "Salvar preferências" })); await screen.findAllByText("Falha ao consultar estado"); @@ -371,7 +386,7 @@ describe("feedback sonoro de ações reais", () => { it("mute não interrompe o salvamento principal", async () => { localStorage.setItem(audioStorageKey, JSON.stringify({ enabled: false, volume: 0.25 })); await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("switch", { name: "Organizar novos arquivos" })); + fireEvent.click(setting("switch", "Organizar novos arquivos")); fireEvent.click(screen.getByRole("button", { name: "Salvar preferências" })); await screen.findByText("Preferências salvas. Confira também o estado do monitoramento."); expect(mocks.save).toHaveBeenCalledOnce(); expect(mocks.sound).not.toHaveBeenCalled(); @@ -381,10 +396,10 @@ describe("feedback sonoro de ações reais", () => { describe("rascunho de áudio no fluxo global", () => { const saveButton = () => screen.getByRole("button", { name: "Salvar preferências" }) as HTMLButtonElement; const discardButton = () => screen.getByRole("button", { name: "Descartar alterações" }) as HTMLButtonElement; - function volume(value: number) { fireEvent.change(screen.getByRole("slider", { name: "Volume" }), { target: { value: String(value) } }); } + function volume(value: number) { fireEvent.change(setting("slider", "Volume"), { target: { value: String(value) } }); } it.each(["volume", "switch"])("apenas %s habilita ações globais e salva sem comandos Rust", async control => { await start(); navigate("Configurações"); - if (control === "volume") volume(60); else fireEvent.click(screen.getByRole("switch", { name: "Efeitos sonoros" })); + if (control === "volume") volume(60); else fireEvent.click(setting("switch", "Efeitos sonoros")); expect(saveButton().disabled).toBe(false); expect(discardButton().disabled).toBe(false); expect(screen.getByRole("button", { name: "Configurações" }).getAttribute("aria-describedby")).toBe("pending-preferences"); expect(localStorage.getItem(audioStorageKey)).toBeNull(); @@ -400,18 +415,18 @@ describe("rascunho de áudio no fluxo global", () => { it("restaurar manualmente o valor original remove dirty sem persistência", async () => { await start(); navigate("Configurações"); volume(80); volume(25); expect(saveButton().disabled).toBe(true); - fireEvent.click(screen.getByRole("switch", { name: "Efeitos sonoros" })); expect(saveButton().disabled).toBe(false); - fireEvent.click(screen.getByRole("switch", { name: "Efeitos sonoros" })); expect(saveButton().disabled).toBe(true); + fireEvent.click(setting("switch", "Efeitos sonoros")); expect(saveButton().disabled).toBe(false); + fireEvent.click(setting("switch", "Efeitos sonoros")); expect(saveButton().disabled).toBe(true); expect(localStorage.getItem(audioStorageKey)).toBeNull(); expect(mocks.sound).not.toHaveBeenCalled(); }); it("descartar restaura todos os rascunhos, inclusive áudio salvo anteriormente", async () => { const stored = JSON.stringify({ enabled: false, volume: 0.4 }); localStorage.setItem(audioStorageKey, stored); await start(); navigate("Configurações"); - volume(70); fireEvent.click(screen.getByRole("switch", { name: "Efeitos sonoros" })); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); fireEvent.click(discardButton()); - expect((screen.getByRole("slider", { name: "Volume" }) as HTMLInputElement).value).toBe("40"); - expect(screen.getByRole("switch", { name: "Efeitos sonoros" }).getAttribute("aria-checked")).toBe("false"); - expect(screen.getByRole("button", { name: "Escuro" }).getAttribute("aria-pressed")).toBe("true"); + volume(70); fireEvent.click(setting("switch", "Efeitos sonoros")); + fireEvent.click(setting("button", "Claro")); fireEvent.click(discardButton()); + expect((setting("slider", "Volume") as HTMLInputElement).value).toBe("40"); + expect(setting("switch", "Efeitos sonoros").getAttribute("aria-checked")).toBe("false"); + expect(setting("button", "Escuro").getAttribute("aria-pressed")).toBe("true"); expect(saveButton().disabled).toBe(true); expect(localStorage.getItem(audioStorageKey)).toBe(stored); expect(mocks.sound).not.toHaveBeenCalled(); }); it("navegação e refresh preservam áudio pendente e a proteção de beforeunload", async () => { @@ -420,7 +435,7 @@ describe("rascunho de áudio no fluxo global", () => { fireEvent.click(screen.getByRole("button", { name: "Atualizar arquivos" })); await waitFor(() => expect((screen.getByRole("button", { name: "Atualizar arquivos" }) as HTMLButtonElement).disabled).toBe(false)); navigate("Histórico"); navigate("Configurações"); - expect((screen.getByRole("slider", { name: "Volume" }) as HTMLInputElement).value).toBe("75"); + expect((setting("slider", "Volume") as HTMLInputElement).value).toBe("75"); const event = new Event("beforeunload", { cancelable: true }); window.dispatchEvent(event); expect(event.defaultPrevented).toBe(true); expect(saveButton().disabled).toBe(false); expect(localStorage.getItem(audioStorageKey)).toBeNull(); expect(mocks.sound).not.toHaveBeenCalled(); }); @@ -450,9 +465,9 @@ describe("rascunho de áudio no fluxo global", () => { }); it("salva as opções de notificações, atualizações e iniciar com o Windows", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("switch", { name: "Mostrar notificações" })); - fireEvent.click(screen.getByRole("switch", { name: "Iniciar com o Windows" })); - fireEvent.click(screen.getByRole("switch", { name: "Atualizar automaticamente" })); + fireEvent.click(setting("switch", "Mostrar notificações")); + fireEvent.click(setting("switch", "Iniciar com o Windows")); + fireEvent.click(setting("switch", "Atualizar automaticamente")); fireEvent.click(screen.getByRole("button", { name: "Salvar preferências" })); await waitFor(() => expect(mocks.save).toHaveBeenCalledOnce()); expect(mocks.save.mock.calls[0][0]).toMatchObject({ notifications: false, updates: false, autostart: true }); @@ -462,10 +477,10 @@ describe("rascunho de áudio no fluxo global", () => { expect(screen.queryByRole("button", { name: "Instalar agora" })).toBeNull(); snapshot.update_version = "9.9.9"; await updateSnapshot(); screen.getByText(/9\.9\.9/); - navigate("Configurações"); fireEvent.click(screen.getByRole("switch", { name: "Mostrar notificações" })); + navigate("Configurações"); fireEvent.click(setting("switch", "Mostrar notificações")); const install = screen.getByRole("button", { name: "Instalar agora" }) as HTMLButtonElement; expect(install.disabled).toBe(true); - fireEvent.click(screen.getByRole("switch", { name: "Mostrar notificações" })); + fireEvent.click(setting("switch", "Mostrar notificações")); expect(install.disabled).toBe(false); fireEvent.click(install); await waitFor(() => expect(mocks.installUpdate).toHaveBeenCalledOnce()); @@ -514,12 +529,12 @@ describe("rascunho de áudio no fluxo global", () => { } else { expect(localStorage.getItem(audioStorageKey)).toBeNull(); expect(mocks.sound).not.toHaveBeenCalled(); } }); it("falha local após salvar principais mantém somente áudio pendente, permitindo repetir sem salvar Rust", async () => { - await start(); navigate("Configurações"); volume(70); fireEvent.click(screen.getByRole("button", { name: "Claro" })); + await start(); navigate("Configurações"); volume(70); fireEvent.click(setting("button", "Claro")); const original = Storage.prototype.setItem; const write = vi.spyOn(Storage.prototype, "setItem").mockImplementationOnce(() => { throw new Error("Quota"); }); fireEvent.click(saveButton()); await screen.findAllByText(/Não foi possível salvar o áudio neste dispositivo/); expect(snapshot.preferences.theme).toBe("light"); expect(mocks.save).toHaveBeenCalledOnce(); - expect(localStorage.getItem(audioStorageKey)).toBeNull(); expect((screen.getByRole("slider", { name: "Volume" }) as HTMLInputElement).value).toBe("70"); + expect(localStorage.getItem(audioStorageKey)).toBeNull(); expect((setting("slider", "Volume") as HTMLInputElement).value).toBe("70"); expect(saveButton().disabled).toBe(false); expect(screen.queryByText("Todas as alterações estão salvas.")).toBeNull(); expect(mocks.sound).toHaveBeenCalledExactlyOnceWith(sounds.warning); write.mockImplementation(original); fireEvent.click(saveButton()); await waitFor(() => expect(saveButton().disabled).toBe(true)); @@ -534,11 +549,11 @@ describe("rascunho de áudio no fluxo global", () => { await screen.findAllByText(/Não foi possível salvar o áudio neste dispositivo/); expect(mocks.close).not.toHaveBeenCalled(); expect(localStorage.getItem(audioStorageKey)).toBeNull(); fireEvent.click(screen.getByRole("button", { name: "Continuar no aplicativo" })); - expect((screen.getByRole("slider", { name: "Volume" }) as HTMLInputElement).value).toBe("50"); + expect((setting("slider", "Volume") as HTMLInputElement).value).toBe("50"); }); it("ativar áudio salvo como desabilitado prepara a confirmação somente no gesto de salvar", async () => { localStorage.setItem(audioStorageKey, JSON.stringify({ enabled: false, volume: 0.25 })); - await start(); navigate("Configurações"); fireEvent.click(screen.getByRole("switch", { name: "Efeitos sonoros" })); + await start(); navigate("Configurações"); fireEvent.click(setting("switch", "Efeitos sonoros")); expect(mocks.sound).not.toHaveBeenCalled(); fireEvent.click(saveButton()); await waitFor(() => expect(saveButton().disabled).toBe(true)); expect(mocks.sound).toHaveBeenCalledExactlyOnceWith(sounds.saved); expect(mocks.save).not.toHaveBeenCalled(); @@ -547,7 +562,7 @@ describe("rascunho de áudio no fluxo global", () => { await start(); navigate("Configurações"); volume(80); fireEvent.click(screen.getByRole("button", { name: "Testar som de organização" })); expect(localStorage.getItem(audioStorageKey)).toBeNull(); mocks.sound.mockClear(); - fireEvent.click(screen.getByRole("switch", { name: "Efeitos sonoros" })); navigate("Visão geral"); + fireEvent.click(setting("switch", "Efeitos sonoros")); navigate("Visão geral"); mocks.organize.mockImplementationOnce(async () => { snapshot.history = [structuredClone(operation)]; return 42; }); const dialog = await openPreview(); fireEvent.click(within(dialog).getByRole("checkbox", { name: "Conferi os arquivos e destinos desta prévia" })); fireEvent.click(within(dialog).getByRole("button", { name: "Confirmar organização" })); @@ -665,7 +680,7 @@ describe("composição desktop", () => { fireEvent.change(screen.getByRole("textbox", { name: "Buscar arquivos" }), { target: { value: "" } }); fireEvent.change(screen.getByRole("combobox", { name: "Filtrar por categoria" }), { target: { value: "images" } }); expect(screen.getByText("5000 arquivos")).toBeTruthy(); - navigate("Configurações"); fireEvent.click(screen.getByRole("button", { name: "Claro" })); navigate("Arquivos"); + navigate("Configurações"); fireEvent.click(setting("button", "Claro")); navigate("Arquivos"); expect(normalizedFiles()).toBe(10000); expect(screen.getByText("5000 arquivos")).toBeTruthy(); fireEvent.change(screen.getByRole("textbox", { name: "Buscar arquivos" }), { target: { value: "inexistente" } }); @@ -673,6 +688,75 @@ describe("composição desktop", () => { expect(screen.getByText("10000 arquivos")).toBeTruthy(); expect(document.querySelectorAll("tr[data-file-path]").length).toBeLessThan(25); }); + it("leva aos conflitos, salva com Ctrl+S e visualiza com duplo clique", async () => { + snapshot.files = [snapshot.files[0], { ...snapshot.files[0], name: "b.txt", path: "/isolated/source/b.txt", status: "conflict", reason: "Já existe" }]; + await start(); + fireEvent.click(screen.getByRole("button", { name: "Ver conflitos" })); + expect((screen.getByRole("combobox", { name: "Filtrar por categoria" }) as HTMLSelectElement).value).toBe("status:conflict"); + expect(screen.getByRole("option", { name: "Conflitos (1)" })).toBeTruthy(); + expect([...document.querySelectorAll("tr[data-file-path] strong")].map(cell => cell.textContent)).toEqual(["b.txt"]); + // A double click on the row opens the preview; on the details button it doesn't. + fireEvent.doubleClick(document.querySelector(".file-disclosure")!); + expect(screen.queryByRole("dialog")).toBeNull(); + fireEvent.doubleClick(document.querySelector("tr[data-file-path]")!); + expect(await screen.findByRole("dialog")).toBeTruthy(); + fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + navigate("Configurações"); + fireEvent.click(setting("button", "Claro")); + fireEvent.keyDown(window, { key: "s", ctrlKey: true }); + await waitFor(() => expect(mocks.save).toHaveBeenCalledOnce()); + }); + it("cria pela linha uma regra que mantém o arquivo na origem, antes das outras e só uma vez", async () => { + snapshot.preferences.rules = [{ pattern: "*.txt", folder: "Textos", keep: false }]; + await start(); navigate("Arquivos"); + fireEvent.click(document.querySelector(".file-disclosure")!); + fireEvent.click(screen.getByRole("button", { name: "Nunca organizar este arquivo" })); + expect(screen.getByRole("tab", { name: "Regras personalizadas" }).getAttribute("aria-selected")).toBe("true"); + expect(screen.getAllByRole("textbox", { name: "Padrão do nome do arquivo" }).map(input => (input as HTMLInputElement).value)).toEqual(["a.txt", "*.txt"]); + expect((screen.getAllByRole("checkbox", { name: "Deixar no lugar" })[0] as HTMLInputElement).checked).toBe(true); + navigate("Arquivos"); + fireEvent.click(document.querySelector(".file-disclosure")!); + fireEvent.click(screen.getByRole("button", { name: "Nunca organizar este arquivo" })); + expect(screen.getAllByRole("textbox", { name: "Padrão do nome do arquivo" })).toHaveLength(2); + }); + it("abre a pasta de destino pelo Explorer e explica quando ela ainda não existe", async () => { + await start(); + fireEvent.click(screen.getByRole("button", { name: "Abrir pasta de destino" })); + expect(mocks.openFolder).toHaveBeenCalledWith("destination"); + mocks.openFolder.mockRejectedValueOnce("Esta pasta ainda não existe. Ela é criada quando os arquivos são organizados."); + fireEvent.click(screen.getByRole("button", { name: "Abrir pasta de destino" })); + expect(await screen.findByText("Esta pasta ainda não existe. Ela é criada quando os arquivos são organizados.")).toBeTruthy(); + }); + it("lembra a ordem dos arquivos depois de reiniciar", async () => { + await start(); navigate("Arquivos"); + fireEvent.change(screen.getByRole("combobox", { name: "Ordenar arquivos" }), { target: { value: "largest" } }); + cleanup(); + await start(); navigate("Arquivos"); + expect((screen.getByRole("combobox", { name: "Ordenar arquivos" }) as HTMLSelectElement).value).toBe("largest"); + }); + it("ordena a lista, limpa a busca e conta os arquivos de cada categoria", async () => { + snapshot.files = [["a.txt", 1, 300], ["b.txt", 3, 100], ["c.txt", 2, 200]].map(([name, modified, size]) => ({ ...snapshot.files[0], name: name as string, path: "/isolated/source/" + name, modified: modified as number, size: size as number })); + await start(); navigate("Arquivos"); + const names = () => [...document.querySelectorAll("tr[data-file-path] strong")].map(cell => cell.textContent); + expect(names()).toEqual(["a.txt", "b.txt", "c.txt"]); + const sort = screen.getByRole("combobox", { name: "Ordenar arquivos" }); + fireEvent.change(sort, { target: { value: "newest" } }); + expect(names()).toEqual(["b.txt", "c.txt", "a.txt"]); + fireEvent.change(sort, { target: { value: "largest" } }); + expect(names()).toEqual(["a.txt", "c.txt", "b.txt"]); + expect(screen.getByRole("option", { name: "Documentos (3)" })).toBeTruthy(); + const search = screen.getByRole("textbox", { name: "Buscar arquivos" }); + fireEvent.change(search, { target: { value: "b" } }); + expect(names()).toEqual(["b.txt"]); + fireEvent.keyDown(search, { key: "Escape" }); + expect((search as HTMLInputElement).value).toBe(""); + fireEvent.change(search, { target: { value: "c" } }); + fireEvent.click(screen.getByRole("button", { name: "Limpar busca" })); + expect((search as HTMLInputElement).value).toBe(""); + expect(document.activeElement).toBe(search); + expect(screen.queryByRole("button", { name: "Limpar busca" })).toBeNull(); + }); it("leva da categoria real à tabela filtrada e mantém os nomes de navegação estáveis", async () => { await start(); expect(screen.getByRole("heading", { name: "source" })).toBeTruthy(); @@ -682,7 +766,7 @@ describe("composição desktop", () => { expect(screen.getByRole("table", { name: "Arquivos da pasta de origem" })).toBeTruthy(); expect(screen.getAllByRole("columnheader").every(header => header.getAttribute("scope") === "col")).toBe(true); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); const settings = screen.getByRole("button", { name: "Configurações" }); expect(settings.getAttribute("aria-describedby")).toBe("pending-preferences"); expect(document.getElementById("pending-preferences")?.textContent).toBe("Alterações não salvas"); @@ -717,11 +801,11 @@ describe("rascunho de configurações", () => { const discard = within(dock).getByRole("button", { name: "Descartar alterações" }) as HTMLButtonElement; expect(save.disabled).toBe(true); expect(discard.disabled).toBe(true); expect(dock.closest(".page-content")).toBeNull(); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); expect(save.disabled).toBe(false); expect(discard.disabled).toBe(false); fireEvent.click(discard); expect(save.disabled).toBe(true); - fireEvent.click(screen.getByRole("switch", { name: "Documentos" })); + fireEvent.click(setting("switch", "Documentos")); fireEvent.click(save); await screen.findByText("Todas as alterações estão salvas."); expect(save.disabled).toBe(true); expect(discard.disabled).toBe(true); @@ -736,7 +820,7 @@ describe("rascunho de configurações", () => { }); it("bloqueia ações durante o salvamento e mantém o rascunho após uma falha", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); const pending = deferred(); mocks.save.mockReturnValueOnce(pending.promise); const dock = screen.getByRole("region", { name: "Ações das configurações" }); fireEvent.click(within(dock).getByRole("button", { name: "Salvar preferências" })); @@ -746,29 +830,29 @@ describe("rascunho de configurações", () => { fireEvent.click(save); expect(mocks.save).toHaveBeenCalledOnce(); await act(async () => pending.reject("Falha isolada ao salvar")); await screen.findAllByText("Falha isolada ao salvar"); - expect(screen.getByRole("button", { name: "Claro" }).getAttribute("aria-pressed")).toBe("true"); + expect(setting("button", "Claro").getAttribute("aria-pressed")).toBe("true"); expect(save.disabled).toBe(false); expect(screen.getByRole("region", { name: "Ações das configurações" })).toBe(dock); }); it("preserva alterações ao navegar e só descarta explicitamente", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); navigate("Histórico"); expect(screen.getByText("Você tem configurações não salvas")).toBeTruthy(); navigate("Configurações"); - expect(screen.getByRole("button", { name: "Claro" }).getAttribute("aria-pressed")).toBe("true"); + expect(setting("button", "Claro").getAttribute("aria-pressed")).toBe("true"); fireEvent.click(screen.getByRole("button", { name: "Descartar alterações" })); - expect(screen.getByRole("button", { name: "Escuro" }).getAttribute("aria-pressed")).toBe("true"); + expect(setting("button", "Escuro").getAttribute("aria-pressed")).toBe("true"); expect((screen.getByRole("button", { name: "Salvar preferências" }) as HTMLButtonElement).disabled).toBe(true); expect(mocks.save).not.toHaveBeenCalled(); }); it("preserva o rascunho externo e exige revisão antes de sobrescrever", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); snapshot.preferences = { ...initial, automatic: true }; await updateSnapshot(); expect(screen.getByText("As configurações salvas foram atualizadas")).toBeTruthy(); - expect(screen.getByRole("button", { name: "Claro" }).getAttribute("aria-pressed")).toBe("true"); + expect(setting("button", "Claro").getAttribute("aria-pressed")).toBe("true"); expect((screen.getByRole("button", { name: "Salvar preferências" }) as HTMLButtonElement).disabled).toBe(true); fireEvent.click(screen.getByRole("button", { name: "Manter meu rascunho no lugar desta versão" })); fireEvent.click(screen.getByRole("button", { name: "Salvar preferências" })); @@ -777,17 +861,17 @@ describe("rascunho de configurações", () => { }); it("não anuncia um rascunho salvo enquanto a versão externa ainda precisa de revisão", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); snapshot.preferences = { ...initial, automatic: true }; await updateSnapshot(); - fireEvent.click(screen.getByRole("button", { name: "Escuro" })); + fireEvent.click(setting("button", "Escuro")); expect(screen.getByText("As configurações salvas mudaram. Revise seu rascunho antes de salvar.")).toBeTruthy(); expect(screen.queryByText("Todas as alterações estão salvas.")).toBeNull(); expect((screen.getByRole("button", { name: "Salvar preferências" }) as HTMLButtonElement).disabled).toBe(true); }); it("mantém alterações pendentes e não fecha o app se salvar falhar", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); const preventDefault = vi.fn(); act(() => mocks.closeHandler?.({ preventDefault })); expect(preventDefault).toHaveBeenCalledOnce(); @@ -799,7 +883,7 @@ describe("rascunho de configurações", () => { }); it("salva antes de permitir fechar e intercepta beforeunload", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); const event = new Event("beforeunload", { cancelable: true }); window.dispatchEvent(event); expect(event.defaultPrevented).toBe(true); act(() => mocks.closeHandler?.({ preventDefault: vi.fn() })); @@ -809,7 +893,7 @@ describe("rascunho de configurações", () => { }); it("informa preferências salvas sem esconder falha de monitoramento", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); mocks.save.mockImplementationOnce(async prefs => { snapshot.preferences = prefs; snapshot.watch_error = "Monitoramento indisponível"; return prefs; }); @@ -1085,7 +1169,7 @@ describe("avisos e clareza", () => { }); it("ignora respostas de leitura antigas sem substituir a versão atual ou o rascunho", async () => { await start(); navigate("Configurações"); - fireEvent.click(screen.getByRole("button", { name: "Claro" })); + fireEvent.click(setting("button", "Claro")); const oldSnapshot = structuredClone(snapshotPayload()); const delayed = deferred(); mocks.snapshot.mockReturnValueOnce(delayed.promise); fireEvent.click(screen.getByRole("button", { name: "Atualizar arquivos" })); @@ -1094,7 +1178,7 @@ describe("avisos e clareza", () => { expect(screen.getByText("As configurações salvas foram atualizadas")).toBeTruthy(); await act(async () => delayed.resolve(oldSnapshot)); expect(screen.getByText("As configurações salvas foram atualizadas")).toBeTruthy(); - expect(screen.getByRole("button", { name: "Claro" }).getAttribute("aria-pressed")).toBe("true"); + expect(setting("button", "Claro").getAttribute("aria-pressed")).toBe("true"); }); it("mantém todos os problemas visíveis e recolhe sem anunciar resolução", async () => { snapshot.scan_error = "Pasta removida"; snapshot.watch_error = "Watcher parou"; @@ -1144,3 +1228,37 @@ it("mostra o guia na primeira abertura e não repete na seguinte", async () => { await start(); expect(screen.queryByRole("dialog")).toBeNull(); }); + +it("abre o histórico quando a notificação de arquivos organizados é clicada", async () => { + await start(); + await waitFor(() => expect(mocks.events.has("open-history")).toBe(true)); + act(() => mocks.events.get("open-history")!({ payload: null })); + expect(screen.getByRole("heading", { name: "Histórico", level: 1 })).toBeTruthy(); +}); + +it("troca de página pelo teclado e abre a aba certa pelo rodapé da barra lateral", async () => { + await start(); + fireEvent.keyDown(window, { key: "2", ctrlKey: true }); + expect(screen.getByRole("heading", { name: "Arquivos", level: 1 })).toBeTruthy(); + fireEvent.keyDown(window, { key: "4", ctrlKey: true }); + expect(screen.getByRole("heading", { name: "Configurações", level: 1 })).toBeTruthy(); + // Without Ctrl, a digit is just typing. + fireEvent.keyDown(window, { key: "1" }); + expect(screen.getByRole("heading", { name: "Configurações", level: 1 })).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: `Verificar atualizações (v${version})` })); + expect(screen.getByRole("tab", { name: "Sistema" }).getAttribute("aria-selected")).toBe("true"); + fireEvent.click(screen.getByRole("button", { name: "Monitoramento pausado" })); + expect(screen.getByRole("tab", { name: "Organização automática" }).getAttribute("aria-selected")).toBe("true"); + fireEvent.click(screen.getByRole("button", { name: /^source.*destination$/ })); + expect(screen.getByRole("tab", { name: "Pastas" }).getAttribute("aria-selected")).toBe("true"); + // "Configure" is about the folders, whatever tab was open last. + fireEvent.mouseDown(screen.getByRole("tab", { name: "Aparência" })); + fireEvent.keyDown(window, { key: "1", ctrlKey: true }); + fireEvent.click(screen.getByRole("button", { name: "Configurar" })); + expect(screen.getByRole("tab", { name: "Pastas" }).getAttribute("aria-selected")).toBe("true"); + // Never behind a dialog. + fireEvent.keyDown(window, { key: "1", ctrlKey: true }); + await openPreview(); + fireEvent.keyDown(window, { key: "4", ctrlKey: true }); + expect(screen.getByRole("heading", { name: "Visão geral", level: 1, hidden: true })).toBeTruthy(); +}); diff --git a/src/App.tsx b/src/App.tsx index 83e0534..7cbc970 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { Tooltip } from "radix-ui"; -import { FolderDown, FolderOpen, History, LayoutDashboard, Loader2, RefreshCw, Search, Settings2, ShieldCheck } from "lucide-react"; +import { ArrowDownToLine, ArrowRight, FolderDown, FolderOpen, History, LayoutDashboard, Loader2, PencilLine, RefreshCw, Search, Settings2, ShieldCheck, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; @@ -10,7 +10,7 @@ import { Overview } from "@/components/overview"; import { HistoryView } from "@/components/history"; import { FileTable } from "@/components/file-table"; import { FilePreviewDialog } from "@/components/file-preview-dialog"; -import { Settings } from "@/components/settings"; +import { Settings, type SettingsTab } from "@/components/settings"; import { SettingsActions } from "@/components/settings-actions"; import { OperationDialogs } from "@/components/operation-dialogs"; import { Guide, welcomeFor } from "@/components/guide"; @@ -18,9 +18,10 @@ import { OperationFeedback } from "@/components/operation-feedback"; import { ProblemNotice } from "@/components/problem-notice"; import { NavigationIndicator, PageTransition, useContentMotion, usePagePosition } from "@/components/motion/transitions"; import { useMotionAllowed } from "@/components/motion/feedback"; +import { MotionConfig } from "motion/react"; import { SuccessNotice } from "@/components/success-notice"; import { errorMessage, isRunning, previewIssue, reconcileDraft, samePreferences, type Action, type PreferencesDraft } from "@/lib/experience"; -import { api, native, summarizeOperation, type FileEntry, type Operation, type OperationSummary, type Preview, type Progress, type Snapshot } from "@/lib/api"; +import { api, basename, displayPath, native, summarizeOperation, type FileEntry, type Operation, type OperationSummary, type Preview, type Progress, type Snapshot } from "@/lib/api"; import { useHistoryPages } from "@/lib/use-history"; import { createProgressPresenter } from "@/lib/progress"; import { plural } from "@/lib/utils"; @@ -35,13 +36,16 @@ import "./App.css"; const pages = [{ id: "dashboard", name: () => t("Overview"), icon: LayoutDashboard }, { id: "files", name: () => t("Files"), icon: FolderOpen }, { id: "history", name: () => t("History"), icon: History }, { id: "settings", name: () => t("Settings"), icon: Settings2 }] as const; const noFiles: FileEntry[] = []; export default function App() { - return ; + // Motion 14 reads the OS setting once; this follows it live, like the app's own animations. + return ; } function OrganizerApp() { useLanguage(); const audio = useAudioFeedback(); const [page, setCurrentPage] = useState<(typeof pages)[number]["id"]>("dashboard"); const [data, setData] = useState(null); + // Kept here, so Settings reopens on the tab it was left on, and notices can open the right one. + const [settingsTab, setSettingsTab] = useState("folders"); const [draft, setDraft] = useState(null); const [loading, setLoading] = useState(native); const [busy, setBusy] = useState(false); @@ -65,6 +69,15 @@ function OrganizerApp() { const [closeRequested, setCloseRequested] = useState(false); const [filter, setFilter] = useState("all"); const [search, setSearch] = useState(""); + // The order is a habit, so it outlives a restart. + const [sort, setSort] = useState<"name" | "newest" | "largest">(() => { const saved = localStorage.getItem("download-organizer-sort"); return saved === "newest" || saved === "largest" ? saved : "name"; }); + useEffect(() => { localStorage.setItem("download-organizer-sort", sort); }, [sort]); + // Rules match in order, so the new one goes first to win over broader rules. An exact name never holds * or ?. + const keepFile = (file: FileEntry) => { + setDraft(current => current && !current.value.rules.some(rule => rule.keep && rule.pattern === file.name) ? { ...current, value: { ...current.value, rules: [{ pattern: file.name, folder: "", keep: true }, ...current.value.rules] } } : current); + openSettings("rules"); + }; + const openDestination = () => { api.openFolder("destination").catch(e => setError(errorMessage(e))); }; const [expanded, setExpanded] = useState(null); const timer = useRef | null>(null); const feedbackTimer = useRef | undefined>(undefined); @@ -85,6 +98,37 @@ function OrganizerApp() { const refreshVersion = useRef(0); const mainHeading = useRef(null); const setPage = usePagePosition(page, mainHeading, setCurrentPage); + const openSettings = (tab: SettingsTab) => { setSettingsTab(tab); setPage("settings"); }; + // A click on the "files organized" notification lands on the history. + useEffect(() => { + if (!native) return; + let disposed = false; + let stop: UnlistenFn | undefined; + listen("open-history", () => setPage("history")).then(fn => { if (disposed) fn(); else stop = fn; }).catch(() => {}); + return () => { disposed = true; stop?.(); }; + }, [setPage]); + // Ctrl+S saves the settings draft, as in any editor. + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if (!event.ctrlKey || event.altKey || event.shiftKey || event.key.toLowerCase() !== "s") return; + // WebView2 would otherwise offer to save the page. + event.preventDefault(); + if (page === "settings" && !document.querySelector("[role=dialog]")) void saveDraft(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }); + // Ctrl+1 to Ctrl+4 switch pages, but never behind an open dialog. + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + const index = Number(event.key) - 1; + if (!event.ctrlKey || event.altKey || event.shiftKey || event.metaKey || !pages[index] || document.querySelector("[role=dialog]")) return; + event.preventDefault(); + setPage(pages[index].id); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [setPage]); const themeRef = useContentMotion(data?.preferences.theme ?? "dark", useMotionAllowed(), false, "theme"); const mainDirty = !!draft && !samePreferences(draft.base, draft.value); const dirty = mainDirty || audio.dirty; @@ -296,9 +340,16 @@ function OrganizerApp() { const searchable = useMemo(() => files.map(file => ({ file, name: file.name.toLocaleLowerCase() })), [files]); const query = search.toLocaleLowerCase(); const visible = useMemo(() => { - if (filter === "all" && !query) return files; - return searchable.filter(({ file, name }) => (filter === "all" || file.category === filter) && name.includes(query)).map(({ file }) => file); - }, [files, searchable, filter, query]); + const matching = filter === "all" && !query ? files : searchable.filter(({ file, name }) => (filter === "all" || file.category === filter || "status:" + file.status === filter) && name.includes(query)).map(({ file }) => file); + // The backend lists by name; the other orders sort a copy. + return sort === "name" ? matching : [...matching].sort(sort === "newest" ? (a, b) => b.modified - a.modified : (a, b) => b.size - a.size); + }, [files, searchable, filter, query, sort]); + const conflicts = useMemo(() => files.reduce((count, file) => count + Number(file.status === "conflict"), 0), [files]); + const categoryCounts = useMemo(() => { + const counts = new Map(); + for (const file of files) counts.set(file.category, (counts.get(file.category) ?? 0) + 1); + return counts; + }, [files]); const current = pages.find(p => p.id === page)!; function showCategory(id: string) { setSearch(""); setFilter(id); setPage("files"); } function showOperation(op: OperationSummary) { upsertHistory(op); setPage("history"); setExpanded(op.id); } @@ -306,25 +357,25 @@ function OrganizerApp() { return

{current.name()}

{page === "dashboard" ? t("What arrived, where it goes and what has moved") : page === "files" ? t("Files in the source folder and where each one goes") : page === "history" ? t("Every recorded move, with the option to undo") : t("Folders, rules and organization preferences")}

{page !== "settings" && }
{!native &&
} - {dirty && page !== "settings" &&
{t("You have unsaved settings")}

{t("Your draft was kept. Operations use the saved settings.")}

} - {data?.update_version &&
{t("New version ready to install")}: {data.update_version}

{dirty ? t("Save or discard your changes before installing.") : t("The app closes, installs the new version and opens again.")}

} + {dirty && page !== "settings" &&
} + {data?.update_version &&
} {error && !preview && !undoTarget && void run(async () => { await refresh(true); })} onDismiss={() => setError("")} />} - {data?.scan_error && setPage("settings")} />} - {data?.watch_error && data.preferences.automatic ? void run(async () => { await api.retryMonitoring(); }, "monitor") : setPage("settings")} />} + {data?.scan_error && openSettings("folders")} />} + {data?.watch_error && { if (data.preferences.automatic) void run(async () => { await api.retryMonitoring(); }, "monitor"); else openSettings("automation"); }} />} {message && setMessage("")} />} {!preview && !undoTarget && isRunning(action) && } {automatic &&

{t("Automatic organization")}

op.id === automatic.operationId)} />
} {loading ?
: - {page === "dashboard" && setPage("files")} onSettings={() => setPage("settings")} onCategory={showCategory} onHistory={() => setPage("history")} onOperation={showOperation} />} - {page === "files" &&
{plural(visible.length, t("file"), t("files"))}
{ filePreviewFocus.current = trigger; setViewedFile(file); }} filterKey={filter + ":" + query} files={visible} categories={categories} filtered={filter !== "all" || !!search} onClearFilters={() => { setFilter("all"); setSearch(""); }} />
} - {page === "history" && void openUndo(op)} hasMore={historyPages.next_cursor !== null} loading={historyPages.loading} pageError={historyPages.error} onLoadMore={() => void historyPages.loadMore()} onRetry={() => void historyPages.retry()} newAvailable={historyPages.newAvailable} onReload={() => void historyPages.reload(expanded)} />} - {page === "settings" && (data && draft ? setDraft(current => current ? { ...current, value: update(current.value) } : current)} onDiscard={discardDraft} onAcceptExternal={() => setDraft(current => current && data ? { ...current, base: data.preferences } : current)} /> :
)} + {page === "dashboard" && setPage("files")} onSettings={() => openSettings("folders")} onCategory={showCategory} onHistory={() => setPage("history")} onOperation={showOperation} onOpenDestination={openDestination} counts={categoryCounts} onConflicts={() => showCategory("status:conflict")} />} + {page === "files" &&
{plural(visible.length, t("file"), t("files"))}
{ filePreviewFocus.current = trigger; setViewedFile(file); }} filterKey={filter + ":" + query + ":" + sort} files={visible} categories={categories} filtered={filter !== "all" || !!search} onClearFilters={() => { setFilter("all"); setSearch(""); }} />
} + {page === "history" && void openUndo(op)} hasMore={historyPages.next_cursor !== null} loading={historyPages.loading} pageError={historyPages.error} onLoadMore={() => void historyPages.loadMore()} onRetry={() => void historyPages.retry()} />} + {page === "settings" && (data && draft ? setDraft(current => current ? { ...current, value: update(current.value) } : current)} onDiscard={discardDraft} onAcceptExternal={() => setDraft(current => current && data ? { ...current, base: data.preferences } : current)} /> :
)}
} {page === "settings" && data && draft && void saveDraft()} onDiscard={discardDraft} />}
@@ -334,8 +385,8 @@ function OrganizerApp() { onReviewed={setReviewed} onUpdate={() => void updatePreview()} onClose={closeDialogs} onRestoreFocus={() => mainHeading.current?.focus()} onOrganize={(excluded, renameConflicts, count) => { if (!preview || issue || !reviewed) return; const id = preview.id; organizeCount.current = count; void run(() => api.organize(id, excluded, renameConflicts), "organize"); }} onUndo={() => { if (!undoTarget) return; const id = undoTarget.id; void run(async () => { await api.undo(id); return id; }, "undo"); }} - onViewResult={() => { const id = action?.operationId; const operation = resultOperation ?? data?.history.find(op => op.id === id); if (operation) upsertHistory(summarizeOperation(operation)); closeDialogs(); setPage("history"); if (id !== undefined) setExpanded(id); }} /> - {welcome && setWelcome(null)} onFinish={() => { setWelcome(null); setPage("settings"); }} />} + onOpenDestination={openDestination} onUndoResult={() => { const id = action?.operationId; const operation = resultOperation ?? data?.history.find(op => op.id === id); if (!operation) return; closeDialogs(); void openUndo(operation); }} onViewResult={() => { const id = action?.operationId; const operation = resultOperation ?? data?.history.find(op => op.id === id); if (operation) upsertHistory(summarizeOperation(operation)); closeDialogs(); setPage("history"); if (id !== undefined) setExpanded(id); }} /> + {welcome && setWelcome(null)} onFinish={() => { setWelcome(null); openSettings("folders"); }} />} {working ? t("An operation is in progress") : dirty ? t("You have unsaved changes") : t("Close the app?")}{working ? t("Wait for it to finish before closing the app.") : dirty ? t("You can save or discard the draft before leaving.") : t("The operation finished. See the history to check the results.")} {working && } {external &&

{t("The saved settings changed. Review the versions in Settings before saving.")}

} diff --git a/src/components/file-table.test.tsx b/src/components/file-table.test.tsx index f483490..20dd318 100644 --- a/src/components/file-table.test.tsx +++ b/src/components/file-table.test.tsx @@ -1,5 +1,6 @@ import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Tooltip } from "radix-ui"; import { FileTable } from "./file-table"; import type { FileEntry } from "@/lib/api"; @@ -42,7 +43,7 @@ describe("tabela virtual", () => { it("oferece visualização apenas nas linhas montadas e navega entre ambos os controles", () => { const onView = vi.fn(); const files = filesOf(10000); - const view = render(); + const view = render(, { wrapper: Tooltip.Provider }); const table = scroller(); const first = within(table).getByRole("button", { name: "Visualizar Arquivo-0.pdf" }); expect(first.getAttribute("aria-haspopup")).toBe("dialog"); @@ -167,3 +168,14 @@ it("mostra a pasta de origem só quando os arquivos vêm de mais de uma", () => rerender(); expect(sources()).toEqual(["Origem: C:/Users/Ana/Downloads", "Origem: D:/Downloads"]); }); + +it("não oferece manter na origem um nome que a regra não aceitaria", () => { + const [plain, spaced] = filesOf(2).map((file, index) => ({ ...file, status: "ready" as const, name: index ? " relatório.pdf" : file.name })); + const onKeep = vi.fn(); + render(); + document.querySelectorAll(".file-disclosure").forEach(button => fireEvent.click(button)); + // Windows allows a leading space; a rule pattern can't have one. + expect(screen.getAllByRole("button", { name: "Nunca organizar este arquivo" })).toHaveLength(1); + fireEvent.click(screen.getByRole("button", { name: "Nunca organizar este arquivo" })); + expect(onKeep).toHaveBeenCalledWith(plain); +}); diff --git a/src/components/file-table.tsx b/src/components/file-table.tsx index 2308476..af4513d 100644 --- a/src/components/file-table.tsx +++ b/src/components/file-table.tsx @@ -1,8 +1,9 @@ -import { File, ArrowRight, ChevronRight, Eye, SearchX } from "lucide-react"; +import { Tooltip } from "radix-ui"; +import { File, ArrowRight, ChevronRight, Eye, Pin, SearchX } from "lucide-react"; import { basename, displayPath, bytes, date, statusLabel, type Category, type FileEntry } from "@/lib/api"; import { t, useLanguage } from "@/lib/i18n"; import { Button } from "@/components/ui/button"; -import { Fragment, useCallback, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type Ref } from "react"; +import { Fragment, useCallback, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type Ref } from "react"; import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual"; import { Collapse } from "@/components/motion/collapse"; import { useContentMotion } from "@/components/motion/transitions"; @@ -17,10 +18,10 @@ function FileName({ file, source }: { file: FileEntry; source?: string }) { return <>{file.name}{!file.extension && {t("No extension")}}{source && {t("Source")}: {source}}; } -function FileDetails({ file, source, open, onToggle }: { file: FileEntry; source?: string; open: boolean; onToggle: () => void }) { +function FileDetails({ file, source, open, onToggle, onKeep }: { file: FileEntry; source?: string; open: boolean; onToggle: () => void; onKeep?: (file: FileEntry) => void }) { const interacted = useRef(false); const id = useId(); - return

{t("Source")}: {displayPath(file.path)}

{t("Planned destination")}: {displayPath(file.destination)}

; + return

{t("Source")}: {displayPath(file.path)}

{t("Planned destination")}: {displayPath(file.destination)}

{onKeep && file.status !== "ignored" && file.name === file.name.trim() && }
; } function RowSpace({ height, columns }: { height: number; columns: number }) { @@ -29,23 +30,28 @@ function RowSpace({ height, columns }: { height: number; columns: number }) { export interface PreviewSelection { excluded: Set; selected: number; ready: number; disabled: boolean; onToggle: (path: string) => void; onToggleAll: (all: boolean) => void } -function FileRow({ file, source, index, preview, fullPaths, category, open, onToggle, onView, rowRef, selection }: { +function FileRow({ file, source, index, preview, fullPaths, category, open, onToggle, onView, onKeep, rowRef, selection }: { file: FileEntry; source?: string; index: number; preview: boolean; fullPaths: boolean; category?: string; open: boolean; onToggle: (path: string) => void; rowRef?: Ref; - onView?: (file: FileEntry, trigger: HTMLButtonElement) => void; selection?: PreviewSelection; + onView?: (file: FileEntry, trigger: HTMLButtonElement) => void; onKeep?: (file: FileEntry) => void; selection?: PreviewSelection; }) { const language = useLanguage(); const size = useMemo(() => bytes(file.size), [file.size, language]); const modified = useMemo(() => preview ? "" : date(file.modified), [file.modified, preview, language]); - return - {preview ?
{selection && file.status === "ready" ? selection.onToggle(file.path)} /> : }
: onToggle(file.path)} />} + // A double click opens the preview, like in File Explorer; the eye button stays the keyboard path. + const openOnDoubleClick = !preview && onView ? (event: MouseEvent) => { + const trigger = event.currentTarget.querySelector(".file-view-button"); + if (trigger && !(event.target as HTMLElement).closest("button, input")) onView(file, trigger); + } : undefined; + return + {preview ?
{selection && file.status === "ready" ? selection.onToggle(file.path)} /> : }
: onToggle(file.path)} onKeep={onKeep} />} {!preview && } {size}{preview && file.status === "ignored" ? {t("Stays where it is")} : preview ? : {modified}} -
{statusLabel(file.status)}{file.reason && {file.reason}}
{!preview && onView && }
+
{statusLabel(file.status)}{file.reason && {file.reason}}
{!preview && onView && {t("View")}}
; } -export function FileTable({ files, categories, preview = false, fullPaths = false, filtered = false, onClearFilters, filterKey = "all", onView, selection }: { files: FileEntry[]; categories: Category[]; preview?: boolean; fullPaths?: boolean; filtered?: boolean; onClearFilters?: () => void; filterKey?: string; onView?: (file: FileEntry, trigger: HTMLButtonElement) => void; selection?: PreviewSelection }) { +export function FileTable({ files, categories, preview = false, fullPaths = false, filtered = false, onClearFilters, filterKey = "all", onView, onKeep, selection }: { files: FileEntry[]; categories: Category[]; preview?: boolean; fullPaths?: boolean; filtered?: boolean; onClearFilters?: () => void; filterKey?: string; onView?: (file: FileEntry, trigger: HTMLButtonElement) => void; onKeep?: (file: FileEntry) => void; selection?: PreviewSelection }) { const motionRef = useContentMotion(filterKey + ":" + (files.length ? "results" : "empty"), useMotionAllowed() && !preview); const scrollRef = useRef(null); const headerRef = useRef(null); @@ -155,7 +161,7 @@ export function FileTable({ files, categories, preview = false, fullPaths = fals previousEnd = item.end; return - + ; }); return
({ operation: vi.fn(), destinations: vi.fn() })); +const queries = vi.hoisted(() => ({ operation: vi.fn(), destinations: vi.fn(), revealMovement: vi.fn(), searchHistory: vi.fn() })); vi.mock("@/lib/api", async original => ({ ...await original(), api: queries })); vi.mock("@/components/motion/feedback", () => ({ useMotionAllowed: () => false, useFeedbackMotion: () => ({ current: null }) })); @@ -171,3 +171,63 @@ it("mantém 5.000 arquivos virtualizados durante a saída e reabre com movimento view.rerender(); const reopened = explore(); expect(within(reopened).getByText("latest.txt")).toBeTruthy(); expect(within(reopened).queryByText("File-0.txt")).toBeNull(); }); + +it("mostra na pasta só os arquivos que ainda estão no destino e explica a falha", async () => { + const operation = operationOf(2); + operation.movements[1].status = "undone"; + queries.destinations.mockResolvedValue({ folders: [["/isolated/destination/Documents/", 2]], other_folders: 0, other_files: 0 }); + queries.operation.mockResolvedValue(operation); + queries.revealMovement.mockResolvedValueOnce(undefined).mockRejectedValueOnce("Este arquivo não está mais no destino."); + render(); + const dialog = explore(); + await within(dialog).findByText("File-0.txt"); + expect(within(dialog).queryByRole("button", { name: "Mostrar na pasta: File-1.txt" })).toBeNull(); + const reveal = within(dialog).getByRole("button", { name: "Mostrar na pasta: File-0.txt" }); + fireEvent.click(reveal); + expect(queries.revealMovement).toHaveBeenCalledWith(42, 1); + fireEvent.click(reveal); + expect(await within(dialog).findByRole("alert")).toHaveProperty("textContent", "Este arquivo não está mais no destino."); +}); + +it("busca um arquivo no histórico inteiro e mostra para onde ele foi", async () => { + const operation = operationOf(1); + queries.destinations.mockResolvedValue({ folders: [], other_folders: 0, other_files: 0 }); + queries.searchHistory.mockImplementation(async (query: string) => query === "contrato" ? [ + { id: 7, operation_id: 3, created: 1700000000, source: "/isolated/source/Contrato.pdf", destination: "/isolated/destination/Documents/Contrato.pdf", status: "moved" }, + { id: 5, operation_id: 2, created: 1690000000, source: "/isolated/source/contrato-antigo.pdf", destination: "/isolated/destination/Documents/contrato-antigo.pdf", status: "undone" }, + ] : []); + queries.revealMovement.mockResolvedValue(undefined); + render(); + const search = screen.getByRole("textbox", { name: "Buscar no histórico" }); + fireEvent.change(search, { target: { value: "contrato" } }); + const list = await screen.findByRole("list", { name: "Arquivos encontrados no histórico" }); + expect(screen.getByRole("status").textContent).toBe("2 arquivos"); + expect(list.closest("[role=status]")).toBeNull(); + expect(queries.searchHistory).toHaveBeenCalledExactlyOnceWith("contrato"); + expect(within(list).getByText("/isolated/destination/Documents/Contrato.pdf")).toBeTruthy(); + expect(within(list).queryByRole("button", { name: "Mostrar na pasta: contrato-antigo.pdf" })).toBeNull(); + fireEvent.click(within(list).getByRole("button", { name: "Mostrar na pasta: Contrato.pdf" })); + expect(queries.revealMovement).toHaveBeenCalledWith(3, 7); + queries.revealMovement.mockRejectedValueOnce("Este arquivo não está mais no destino."); + fireEvent.click(within(list).getByRole("button", { name: "Mostrar na pasta: Contrato.pdf" })); + expect(await screen.findByRole("alert")).toBeTruthy(); + fireEvent.change(search, { target: { value: "nada" } }); + // The old error belongs to the old search. + expect(screen.queryByRole("alert")).toBeNull(); + await waitFor(() => expect(screen.getByRole("status").textContent).toBe("Nenhum arquivo movido tem esse nome.")); + fireEvent.keyDown(search, { key: "Escape" }); + expect((search as HTMLInputElement).value).toBe(""); + expect(screen.getByRole("status").textContent).toBe(""); + expect(screen.queryByText("Nenhum arquivo movido tem esse nome.")).toBeNull(); +}); + +it("destaca a operação mais recente e anima só a que chega com a página aberta", () => { + const first = { ...summarizeOperation(operationOf(1)), id: 41 }; + queries.destinations.mockResolvedValue({ folders: [], other_folders: 0, other_files: 0 }); + const view = render(); + const section = (id: number) => screen.getByRole("region", { name: "Operação " + id }); + expect(section(41).className).toBe("history-operation latest"); + view.rerender(); + expect(section(42).className).toBe("history-operation arrived latest"); + expect(section(41).className).toBe("history-operation"); +}); diff --git a/src/components/history.tsx b/src/components/history.tsx index ca6d0da..1ad0d1a 100644 --- a/src/components/history.tsx +++ b/src/components/history.tsx @@ -1,9 +1,10 @@ -import { ChevronDown, ChevronRight, CircleCheck, History, Undo2 } from "lucide-react"; +import { ArrowRight, ChevronDown, ChevronRight, CircleCheck, FolderSearch, History, Search, Undo2 } from "lucide-react"; +import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { useFeedbackMotion, useMotionAllowed } from "@/components/motion/feedback"; import { Collapse } from "@/components/motion/collapse"; import { useContentMotion } from "@/components/motion/transitions"; -import { displayPath, api, date, summarizeOperation, type DestinationSummary, type Operation, type OperationSummary as Summary } from "@/lib/api"; +import { displayPath, api, basename, date, statusLabel, summarizeOperation, type DestinationSummary, type FoundMovement, type Operation, type OperationSummary as Summary } from "@/lib/api"; import { plural } from "@/lib/utils"; import { t } from "@/lib/i18n"; import { useEffect, useMemo, useState } from "react"; @@ -42,10 +43,10 @@ function OperationSummary({ operation }: { operation: Operation | Summary }) {
; } -export function Activity({ operation, onOpen, expanded, motionAllowed = false }: { operation: Operation | Summary; onOpen: () => void; expanded?: boolean; motionAllowed?: boolean }) { +export function Activity({ operation, onOpen, expanded, motionAllowed = false, className = "" }: { operation: Operation | Summary; onOpen: () => void; expanded?: boolean; motionAllowed?: boolean; className?: string }) { const { moved, undone, errors } = useMemo(() => summarizeOperation(operation), [operation]); const mark = useFeedbackMotion(`${operation.id}:${moved}:${undone}:${errors}`, motionAllowed && errors === 0); - return ; } -export function HistoryView({ history, expanded, working, openingUndo, onExpand, onUndo, hasMore, loading, pageError, onLoadMore, onRetry, newAvailable, onReload }: { +// The newest operation when the page opened: anything newer arrived while it was on screen. +export function useSeenOperation(history: readonly { id: number }[]) { + const [seen] = useState(() => history[0]?.id ?? 0); + return seen; +} +export const arrivalClass = (id: number, index: number, seen: number) => (id > seen ? " arrived" : "") + (index === 0 ? " latest" : ""); + +// Matches the backend's SEARCH_LIMIT: a full page means older matches may exist. +const searchLimit = 50; + +// Finds a file by name across every operation, to see where it went. +function HistorySearch() { + const [query, setQuery] = useState(""); + const [found, setFound] = useState<{ query: string; results: FoundMovement[]; error: string } | null>(null); + const [revealError, setRevealError] = useState(""); + const text = query.trim(); + useEffect(() => { + if (!text) return; + let stale = false; + const timer = setTimeout(() => api.searchHistory(text) + .then(results => { if (!stale) setFound({ query: text, results, error: "" }); }) + .catch(error => { if (!stale) setFound({ query: text, results: [], error: String(error) }); }), 250); + return () => { stale = true; clearTimeout(timer); }; + }, [text]); + const shown = text && found?.query === text ? found : null; + // Only a short summary is live: the list itself would be read out at every keystroke. + const summary = !shown || shown.error ? "" : shown.results.length ? plural(shown.results.length, t("file"), t("files")) : t("No moved file has this name."); + return
+ +

{summary}

+ {shown &&
+ {shown.error ?

{shown.error}

: !shown.results.length ?

{t("No moved file has this name.")}

: <> + {revealError &&

{revealError}

} +
    {shown.results.map(found =>
  • +
    {basename(found.source)}

    #{found.operation_id} · {date(found.created * 1000)}
    + {statusLabel(found.status)} + {found.status === "moved" && } +
  • )}
+ {shown.results.length === searchLimit &&

{t("Showing the 50 most recent matches. Type more of the name to narrow them.")}

} + } +
} +
; +} + +export function HistoryView({ history, expanded, working, openingUndo, onExpand, onUndo, hasMore, loading, pageError, onLoadMore, onRetry }: { history: (Operation | Summary)[]; expanded: number | null; working: boolean; onExpand: (id: number | null) => void; onUndo: (operation: Operation | Summary) => void; - hasMore?: boolean; loading?: boolean; pageError?: string; onLoadMore?: () => void; onRetry?: () => void; newAvailable?: boolean; onReload?: () => void; + hasMore?: boolean; loading?: boolean; pageError?: string; onLoadMore?: () => void; onRetry?: () => void; openingUndo?: number | null; }) { const motionAllowed = useMotionAllowed(); const ref = useContentMotion(history.slice(0, 4).map(op => op.id).join(":"), motionAllowed); + const seen = useSeenOperation(history); if (!history.length) return
; - return <>
{plural(history.length, t("operation loaded"), t("operations loaded"))}{t(", newest first")}{newAvailable && }
{history.map(op =>
+ return <>
{plural(history.length, t("operation loaded"), t("operations loaded"))}{t(", newest first")}
{history.map((op, index) =>
onExpand(expanded === op.id ? null : op.id)} />
diff --git a/src/components/motion/transitions.tsx b/src/components/motion/transitions.tsx index 35c15b1..ea395e2 100644 --- a/src/components/motion/transitions.tsx +++ b/src/components/motion/transitions.tsx @@ -20,14 +20,16 @@ export function useContentMotion(identity: string, enabled: boolean, enter = fal if (!root) return; const groups = pattern === "page" ? [...root.querySelectorAll("[data-motion-group]")].slice(0, 4) : []; const elements = [root, ...groups]; - const reset = () => elements.forEach(element => { element.style.opacity = "1"; element.style.transform = "none"; }); + const reset = () => elements.forEach(element => { element.style.opacity = "1"; element.style.transform = "none"; element.style.filter = ""; }); if (!enabled || !changed) { reset(); return; } let stopped = false; const animations = elements.map((element, index) => { const preset = index ? entrances.context : entrances[pattern]; - return animate(element, { opacity: [preset.opacity, 1], y: [preset.y, 0], scale: [preset.scale, 1] }, { + const blur = pattern === "page" && !index ? { filter: ["blur(3px)", "blur(0px)"] } : {}; + return animate(element, { opacity: [preset.opacity, 1], y: [preset.y, 0], scale: [preset.scale, 1], ...blur }, { duration: preset.duration, delay: index ? (index - 1) * timing.stagger : 0, ease: "easeOut", - onComplete: () => { if (!stopped) element.style.transform = "none"; }, + // A leftover filter would blur text and create a stacking context, so it is cleared too. + onComplete: () => { if (!stopped) { element.style.transform = "none"; element.style.filter = ""; } }, }); }); return () => { diff --git a/src/components/operation-dialogs.test.tsx b/src/components/operation-dialogs.test.tsx index 45d04ee..e701e1e 100644 --- a/src/components/operation-dialogs.test.tsx +++ b/src/components/operation-dialogs.test.tsx @@ -1,12 +1,12 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { act, cleanup, fireEvent, render, waitFor, within } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { OperationDialogs } from "./operation-dialogs"; import type { Operation, Preview } from "@/lib/api"; vi.mock("@/components/motion/feedback", () => ({ useMotionAllowed: () => false, useFeedbackMotion: () => ({ current: null }) })); const operation: Operation = { id: 42, kind: "manual", created: 1700000000, movements: [{ id: 1, source: "/isolated/file.txt", destination: "/isolated/destination/file.txt", status: "moved", size: 1, error: null }] }; const preview: Preview = { id: 1, created: 1700000000, files: [{ name: "file.txt", path: "/isolated/file.txt", destination: "/isolated/destination/file.txt", size: 1, extension: "txt", category: "documents", modified: 1700000000000, status: "ready", reason: null }] }; -const props = { preview: null, undoTarget: null, categories: [], action: null, busy: false, working: false, issue: "", reviewed: true, onReviewed: vi.fn(), onUpdate: vi.fn(), onOrganize: vi.fn(), onUndo: vi.fn(), onClose: vi.fn(), onViewResult: vi.fn(), onRestoreFocus: vi.fn() }; +const props = { preview: null, undoTarget: null, categories: [], action: null, busy: false, working: false, issue: "", reviewed: true, onReviewed: vi.fn(), onUpdate: vi.fn(), onOrganize: vi.fn(), onUndo: vi.fn(), onClose: vi.fn(), onViewResult: vi.fn(), onOpenDestination: vi.fn(), onUndoResult: vi.fn(), onRestoreFocus: vi.fn() }; const operationOf = (count: number): Operation => ({ ...operation, movements: Array.from({ length: count }, (_, index) => ({ ...operation.movements[0], id: index + 1, source: `/isolated/source/File-${index}.txt`, destination: `/isolated/destination/File-${index}.txt` })) }); const originalScrollTo = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollTo"); const observers: { elements: Set; callback: ResizeObserverCallback }[] = []; @@ -183,3 +183,40 @@ it("preserva os arquivos de Desfazer ao fechar por Escape e aceita uma reabertur expect(panel()).toBe(old); expect(old.hasAttribute("inert")).toBe(false); expect(within(old).getByText("new.txt")).toBeTruthy(); expect(within(old).queryByText("file.txt")).toBeNull(); }); + +it("só oferece Desfazer no resultado quando nada mais está rodando", () => { + const view = render(); + fireEvent.click(screen.getByRole("button", { name: "Desfazer" })); + expect(props.onUndoResult).toHaveBeenCalledOnce(); + // An automatic batch would make the undo give up after the dialog closed. + view.rerender(); + expect((screen.getByRole("button", { name: "Desfazer" }) as HTMLButtonElement).disabled).toBe(true); +}); + +it("mostra a prévia por pasta de destino, com conflitos, ignorados e desmarcados", () => { + const file = preview.files[0]; + const files = [ + { ...file, name: "a.pdf", path: "/isolated/a.pdf", destination: "/isolated/destination/Documents/a.pdf" }, + { ...file, name: "b.pdf", path: "/isolated/b.pdf", destination: "/isolated/destination/Documents/b.pdf", status: "conflict" as const, reason: "Já existe" }, + { ...file, name: "c.png", path: "/isolated/c.png", destination: "/isolated/destination/Images/c.png" }, + { ...file, name: "d.tmp", path: "/isolated/d.tmp", destination: "/isolated/d.tmp", status: "ignored" as const, reason: "Temporário" }, + ]; + render(); + fireEvent.click(screen.getByRole("checkbox", { name: "Organizar c.png" })); + fireEvent.click(screen.getByRole("button", { name: "Por pasta" })); + expect(screen.getByRole("button", { name: "Por pasta" }).getAttribute("aria-pressed")).toBe("true"); + expect(screen.queryByRole("table")).toBeNull(); + const folders = screen.getByRole("list", { name: "Pastas de destino" }); + expect([...folders.querySelectorAll("summary")].map(summary => summary.textContent)).toEqual(["Documents/2 arquivos1 conflito", "Images/1 arquivo", "Fica onde está1 arquivo"]); + expect(screen.getByText("/isolated/destination")).toBeTruthy(); + // Closed folders render no rows. + expect(screen.queryByText("a.pdf")).toBeNull(); + const [documents, images] = folders.querySelectorAll("details"); + documents.open = true; fireEvent(documents, new Event("toggle")); + images.open = true; fireEvent(images, new Event("toggle")); + expect(screen.getByText("a.pdf")).toBeTruthy(); + expect(screen.getByText("Já existe")).toBeTruthy(); + expect(screen.getByText("c.png").closest("li")!.textContent).toContain("Não selecionado"); + fireEvent.click(screen.getByRole("button", { name: "Lista" })); + expect(screen.getByRole("table")).toBeTruthy(); +}); diff --git a/src/components/operation-dialogs.tsx b/src/components/operation-dialogs.tsx index fe3856b..8d5fe80 100644 --- a/src/components/operation-dialogs.tsx +++ b/src/components/operation-dialogs.tsx @@ -1,28 +1,30 @@ -import { FolderDown, Loader2, Undo2 } from "lucide-react"; +import { FolderDown, FolderOpen, FolderTree, List, Loader2, Undo2 } from "lucide-react"; import { useMemo, useState } from "react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { FileTable, plannedFolder } from "@/components/file-table"; +import { PreviewTree } from "@/components/preview-tree"; import { OperationFeedback } from "@/components/operation-feedback"; import { UndoFileList } from "@/components/undo-file-list"; import { TriageLegend } from "@/components/triage"; import { plural } from "@/lib/utils"; import { t } from "@/lib/i18n"; -import type { Category, Operation, OperationSummary, Preview } from "@/lib/api"; +import { summarizeOperation, type Category, type Operation, type OperationSummary, type Preview } from "@/lib/api"; import type { Action } from "@/lib/experience"; interface Selection { id: number | null; excluded: Set; rename: boolean } const noneExcluded = new Set(); const statusOrder = { conflict: 0, ready: 1, ignored: 2 }; -export function OperationDialogs({ preview, undoTarget, categories, action, busy, working, issue, reviewed, operation, onReviewed, onUpdate, onOrganize, onUndo, onClose, onViewResult, onRestoreFocus }: { +export function OperationDialogs({ preview, undoTarget, categories, action, busy, working, issue, reviewed, operation, onReviewed, onUpdate, onOrganize, onUndo, onClose, onViewResult, onOpenDestination, onUndoResult, onRestoreFocus }: { preview: Preview | null; undoTarget: Operation | null; categories: Category[]; action: Action | null; busy: boolean; working: boolean; issue: string; reviewed: boolean; operation?: Operation | OperationSummary; - onReviewed: (value: boolean) => void; onUpdate: () => void; onOrganize: (excluded: string[], renameConflicts: boolean, count: number) => void; onUndo: () => void; onClose: () => void; onViewResult: () => void; + onReviewed: (value: boolean) => void; onUpdate: () => void; onOrganize: (excluded: string[], renameConflicts: boolean, count: number) => void; onUndo: () => void; onClose: () => void; onViewResult: () => void; onOpenDestination: () => void; onUndoResult: () => void; onRestoreFocus: () => void; }) { // Tied to the preview's id, so a refreshed preview starts with everything selected again. const [fullPaths, setFullPaths] = useState(false); + const [layout, setLayout] = useState<"list" | "folders">("list"); const [choice, setChoice] = useState(() => ({ id: null, excluded: new Set(), rename: false })); const selection = choice.id === (preview?.id ?? null) ? choice : { id: preview?.id ?? null, excluded: noneExcluded, rename: false }; // Conflicts need a decision, so they come first; the rest group by destination folder. @@ -57,11 +59,11 @@ export function OperationDialogs({ preview, undoTarget, categories, action, busy {!done(previewAction) && <> {issue &&

{issue}

} -
{hasConflicts && }
-
+
{(["list", "folders"] as const).map(value => )}
{layout === "list" && }{hasConflicts && }
+
{layout === "folders" ? : }

{selected} {t("of")} {counts.ready} {t("selected")}

} - {done(previewAction) ? footer : <> + {done(previewAction) ? <>{operation && summarizeOperation(operation).moved > 0 && }{footer} : <> {previewAction?.phase === "error" && operation && } diff --git a/src/components/operation-explorer.tsx b/src/components/operation-explorer.tsx index 127ea4a..82c8ee5 100644 --- a/src/components/operation-explorer.tsx +++ b/src/components/operation-explorer.tsx @@ -4,6 +4,7 @@ import { displayPath, api, basename, statusLabel, type Movement, type Operation, import { t } from "@/lib/i18n"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; +import { FolderSearch } from "lucide-react"; import { plural } from "@/lib/utils"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; @@ -11,8 +12,9 @@ export function movementProblem(movement: Movement) { return !!movement.error || ["failed", "uncertain", "pending", "undo_pending"].includes(movement.status); } -function MovementList({ movements }: { movements: Movement[] }) { +function MovementList({ operationId, movements }: { operationId: number; movements: Movement[] }) { const [search, setSearch] = useState(""); + const [revealError, setRevealError] = useState(""); const [status, setStatus] = useState("all"); const scrollRef = useRef(null); const indexed = useMemo(() => { @@ -42,6 +44,7 @@ function MovementList({ movements }: { movements: Movement[] }) {
+ {revealError &&

{revealError}

}

{results.length} {t("of")} {plural(movements.length, t("file"), t("files"))} · {t("Issues first")}

{ if (event.target !== event.currentTarget || !results.length || !["Home", "End"].includes(event.key)) return; @@ -57,6 +60,7 @@ function MovementList({ movements }: { movements: Movement[] }) {
  • {name}
    {t("Source")}
    {displayPath(movement.source)}
    {t("Destination")}
    {displayPath(movement.destination)}
    {movement.error &&

    {movement.error}

    }
    {statusLabel(movement.status)} + {movement.status === "moved" && }
  • ; })}{virtual && virtualizer.getTotalSize() > previousEnd &&
    ; } diff --git a/src/components/overview.tsx b/src/components/overview.tsx index ac291cc..3657c77 100644 --- a/src/components/overview.tsx +++ b/src/components/overview.tsx @@ -1,35 +1,35 @@ import { Tooltip } from "radix-ui"; -import { ArrowRight, History, ShieldCheck } from "lucide-react"; +import { ArrowRight, FolderOpen, History, ShieldCheck } from "lucide-react"; import { Button } from "@/components/ui/button"; -import { Activity } from "@/components/history"; +import { Activity, arrivalClass, useSeenOperation } from "@/components/history"; import { AnimatedCount } from "@/components/motion/animated-count"; import { useMotionAllowed } from "@/components/motion/feedback"; import { TriageBar, triageCounts } from "@/components/triage"; import { t } from "@/lib/i18n"; +import type { ReactNode } from "react"; import { displayPath, basename, bytes, type OperationSummary, type Snapshot } from "@/lib/api"; -export function Overview({ data, onFiles, onSettings, onCategory, onHistory, onOperation }: { - data: Snapshot | null; onFiles: () => void; onSettings: () => void; onCategory: (id: string) => void; - onHistory: () => void; onOperation: (operation: OperationSummary) => void; +export function Overview({ data, counts, onConflicts, onFiles, onSettings, onCategory, onHistory, onOperation, onOpenDestination }: { + data: Snapshot | null; counts: Map; onConflicts: () => void; onFiles: () => void; onSettings: () => void; onCategory: (id: string) => void; + onHistory: () => void; onOperation: (operation: OperationSummary) => void; onOpenDestination: () => void; }) { const motionAllowed = useMotionAllowed(); const files = data?.files ?? []; const history = data?.history ?? []; - const counts = new Map(); - for (const file of files) counts.set(file.category, (counts.get(file.category) ?? 0) + 1); const triage = triageCounts(files); + const seen = useSeenOperation(history); const fullest = Math.max(1, ...counts.values()); - const stats: [string, number, string, boolean][] = [ + const stats: [string, number, ReactNode, boolean][] = [ [t("Available"), files.length, bytes(files.reduce((sum, f) => sum + f.size, 0)), true], [t("Ready (plural)"), triage.ready, t("After review"), true], - [t("Conflicts"), triage.conflict, t("Preserved"), false], + [t("Conflicts"), triage.conflict, triage.conflict ? : t("Preserved"), false], [t("Organized (plural)"), history.reduce((sum, op) => sum + op.moved, 0), t("Last 100 operations"), true], ]; return
    {t("Source folder")}

    {data?.preferences.source ? displayPath(basename(data.preferences.source)) + (data.preferences.extra_sources.length ? ` +${data.preferences.extra_sources.length}` : "") : t("No folder connected")}

    {data?.preferences.source && data.preferences.destination && <>
    {data?.preferences.source ? {displayPath(data.preferences.source)}{[data.preferences.source, ...data.preferences.extra_sources].map(path =>
    {displayPath(path)}
    )}
    :

    {t("Select a folder in Settings to get started.")}

    } -
    {data?.monitoring ? t("Monitoring on") : t("Monitoring paused")}{data && {t("Destination")} {displayPath(data.preferences.destination)}}
    +
    {data?.monitoring ? t("Monitoring on") : t("Monitoring paused")}{data && {t("Destination")} {displayPath(data.preferences.destination)}}{data && }
    {data && }
    {stats.map(([label, value, description, animated]) =>
    {label}
    {data ? animated ? : value : "—"}{data ? description : t("Waiting for desktop")}
    )}

    @@ -39,7 +39,7 @@ export function Overview({ data, onFiles, onSettings, onCategory, onHistory, onO
    {data?.categories.length ? data.categories.map(category => { const count = counts.get(category.id) ?? 0; return ; }) :

    {t("Categories will appear when you open the desktop app.")}

    }

    {t("Recent activity")}

    -
    {history.length ? history.slice(0, 4).map(op => onOperation(op)} />) :
    }
    +
    {history.length ? history.slice(0, 4).map((op, index) => onOperation(op)} />) :
    }
    ; diff --git a/src/components/preview-tree.tsx b/src/components/preview-tree.tsx new file mode 100644 index 0000000..8928d18 --- /dev/null +++ b/src/components/preview-tree.tsx @@ -0,0 +1,51 @@ +import { useMemo, useState } from "react"; +import { ChevronRight, Folder, FolderOpen } from "lucide-react"; +import { displayPath, statusLabel, type FileEntry } from "@/lib/api"; +import { plannedFolder } from "@/components/file-table"; +import { plural } from "@/lib/utils"; +import { t } from "@/lib/i18n"; + +// The destination as it will look: one folder per group, with the files that will arrive there. +// Files stay in the order they come in, so conflicts still lead each folder. +export function PreviewTree({ files, excluded }: { files: FileEntry[]; excluded: Set }) { + const [open, setOpen] = useState>(() => new Set()); + const { root, groups, stays } = useMemo(() => { + const byFolder = new Map(); + const stays: FileEntry[] = []; + for (const file of files) { + if (file.status === "ignored") { stays.push(file); continue; } + const folder = plannedFolder(file); + const list = byFolder.get(folder); + if (list) list.push(file); else byFolder.set(folder, [file]); + } + // Every destination is \\. + const sample = files.find(file => file.status !== "ignored"); + return { root: sample?.destination.replace(/[\\/][^\\/]+[\\/][^\\/]+$/, "") ?? "", groups: [...byFolder].sort(([a], [b]) => a.localeCompare(b)), stays }; + }, [files]); + const toggle = (key: string, now: boolean) => setOpen(previous => { + if (previous.has(key) === now) return previous; + const next = new Set(previous); + if (now) next.add(key); else next.delete(key); + return next; + }); + const folder = (key: string, label: string, list: FileEntry[]) => { + const conflicts = list.reduce((count, file) => count + Number(file.status === "conflict"), 0); + // Closed folders render no rows, so a large preview stays light. + return
  • toggle(key, event.currentTarget.open)}> + + {open.has(key) &&
      {list.map(file =>
    • + {file.name} + {file.status === "conflict" && {statusLabel(file.status)}} + {excluded.has(file.path) && {t("Not selected")}} + {file.reason && {file.reason}} +
    • )}
    } +
  • ; + }; + return
    + {root &&

    } +
      + {groups.map(([name, list]) => folder(name, name + "/", list))} + {stays.length > 0 && folder("", t("Stays where it is"), stays)} +
    +
    ; +} diff --git a/src/components/problem-notice.tsx b/src/components/problem-notice.tsx index 1f914ff..7ed8c21 100644 --- a/src/components/problem-notice.tsx +++ b/src/components/problem-notice.tsx @@ -1,5 +1,5 @@ import { useId, useState } from "react"; -import { ChevronDown, ShieldCheck, X } from "lucide-react"; +import { ChevronDown, TriangleAlert, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { t } from "@/lib/i18n"; @@ -10,7 +10,7 @@ export function ProblemNotice({ title, message, persistent = false, busy, action const messageId = useId(); const collapsed = persistent && collapsedMessage === message; return
    -