From 27774a12dc87229ac2743812a43619a02ffa724d Mon Sep 17 00:00:00 2001 From: thonyydev <105062764+thonyydev@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:01:14 -0300 Subject: [PATCH 1/7] feat: redesign the base, settings and sidebar, and open the destination folder - Base: one MotionConfig for reduced motion, a light blur on page entry, warning icons on problem notices and a dotted backdrop on empty states. - Settings: one tab per section, showing only that section's options. - Sidebar: Ctrl+1 to Ctrl+4 switch pages; the footer card shows the folders, the monitoring status and the version, each opening the matching tab. - Files: sort by name, newest or largest (remembered), clear the search with a button or Esc, and file counts in the category filter. - Open the destination folder in File Explorer from the overview and the organization result. The command only opens the saved source or destination, and only as a folder. Co-Authored-By: Claude Opus 5.5 --- i18n/en.json | 11 +- i18n/es.json | 11 +- i18n/fr.json | 11 +- i18n/it.json | 11 +- i18n/pt-BR.json | 11 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/lib.rs | 45 +++++- src/App.css | 57 ++++++-- src/App.test.tsx | 171 ++++++++++++++++------ src/App.tsx | 62 +++++--- src/components/motion/transitions.tsx | 8 +- src/components/operation-dialogs.test.tsx | 2 +- src/components/operation-dialogs.tsx | 8 +- src/components/overview.tsx | 12 +- src/components/problem-notice.tsx | 4 +- src/components/settings.test.tsx | 34 ++++- src/components/settings.tsx | 107 +++++++++----- src/i18n.test.tsx | 4 +- src/lib/api.ts | 1 + 19 files changed, 427 insertions(+), 145 deletions(-) diff --git a/i18n/en.json b/i18n/en.json index 9f5f171..2e59d3d 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -84,6 +84,14 @@ "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", + "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.", @@ -546,5 +554,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..15e61a8 100644 --- a/i18n/es.json +++ b/i18n/es.json @@ -84,6 +84,14 @@ "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", + "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.", @@ -546,5 +554,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..8ca2f7a 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -84,6 +84,14 @@ "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", + "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.", @@ -546,5 +554,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..334b6a3 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -84,6 +84,14 @@ "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", + "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.", @@ -546,5 +554,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..8ee2079 100644 --- a/i18n/pt-BR.json +++ b/i18n/pt-BR.json @@ -84,6 +84,14 @@ "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", + "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.", @@ -546,5 +554,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/lib.rs b/src-tauri/src/lib.rs index c099da8..42b0209 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -799,6 +799,48 @@ 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 +} + +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 +952,8 @@ fn run_application() -> std::result::Result<(), startup::StartupError> { save_preferences, check_update, install_update, - retry_monitoring + retry_monitoring, + open_folder ]) .build(tauri::generate_context!()) .map_err(|_| startup::StartupError::Runtime)?; diff --git a/src/App.css b/src/App.css index 3ac48b7..0b4e3f1 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; transition: background-color .15s, color .15s; } +.nav-item > svg { color: var(--faint); transition: color .15s; } .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; } @@ -185,7 +206,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 +220,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 +242,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); } @@ -367,6 +394,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..4064687 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 })); @@ -181,7 +192,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 +223,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; @@ -305,17 +316,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 +335,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 +363,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 +382,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 +392,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 +411,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 +431,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 +461,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 +473,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 +525,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 +545,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 +558,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 +676,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 +684,43 @@ describe("composição desktop", () => { expect(screen.getByText("10000 arquivos")).toBeTruthy(); expect(document.querySelectorAll("tr[data-file-path]").length).toBeLessThan(25); }); + 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 +730,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 +765,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 +784,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 +794,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 +825,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 +847,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 +857,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 +1133,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 +1142,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 +1192,30 @@ it("mostra o guia na primeira abertura e não repete na seguinte", async () => { await start(); expect(screen.queryByRole("dialog")).toBeNull(); }); + +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..2c37e32 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,10 @@ 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]); + 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 +93,18 @@ function OrganizerApp() { const refreshVersion = useRef(0); const mainHeading = useRef(null); const setPage = usePagePosition(page, mainHeading, setCurrentPage); + const openSettings = (tab: SettingsTab) => { setSettingsTab(tab); setPage("settings"); }; + // 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 +316,15 @@ 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) && 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 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 +332,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 === "dashboard" && setPage("files")} onSettings={() => openSettings("folders")} onCategory={showCategory} onHistory={() => setPage("history")} onOperation={showOperation} onOpenDestination={openDestination} counts={categoryCounts} />} + {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()} 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 === "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 +360,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} 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/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..5052a2b 100644 --- a/src/components/operation-dialogs.test.tsx +++ b/src/components/operation-dialogs.test.tsx @@ -6,7 +6,7 @@ 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(), 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 }[] = []; diff --git a/src/components/operation-dialogs.tsx b/src/components/operation-dialogs.tsx index fe3856b..57291ce 100644 --- a/src/components/operation-dialogs.tsx +++ b/src/components/operation-dialogs.tsx @@ -1,4 +1,4 @@ -import { FolderDown, Loader2, Undo2 } from "lucide-react"; +import { FolderDown, FolderOpen, 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"; @@ -15,10 +15,10 @@ 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, 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; onRestoreFocus: () => void; }) { // Tied to the preview's id, so a refreshed preview starts with everything selected again. @@ -61,7 +61,7 @@ export function OperationDialogs({ preview, undoTarget, categories, action, busy

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

} - {done(previewAction) ? footer : <> + {done(previewAction) ? <>{footer} : <> {previewAction?.phase === "error" && operation && } diff --git a/src/components/overview.tsx b/src/components/overview.tsx index ac291cc..5072caa 100644 --- a/src/components/overview.tsx +++ b/src/components/overview.tsx @@ -1,5 +1,5 @@ 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 { AnimatedCount } from "@/components/motion/animated-count"; @@ -8,15 +8,13 @@ import { TriageBar, triageCounts } from "@/components/triage"; import { t } from "@/lib/i18n"; 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, onFiles, onSettings, onCategory, onHistory, onOperation, onOpenDestination }: { + data: Snapshot | null; counts: Map; 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 fullest = Math.max(1, ...counts.values()); const stats: [string, number, string, boolean][] = [ @@ -29,7 +27,7 @@ export function Overview({ data, onFiles, onSettings, onCategory, onHistory, onO
{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")}
)}

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
-
+ {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 5072caa..17484dd 100644 --- a/src/components/overview.tsx +++ b/src/components/overview.tsx @@ -6,10 +6,11 @@ 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, counts, onFiles, onSettings, onCategory, onHistory, onOperation, onOpenDestination }: { - data: Snapshot | null; counts: Map; onFiles: () => void; onSettings: () => void; onCategory: (id: string) => 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(); @@ -17,10 +18,10 @@ export function Overview({ data, counts, onFiles, onSettings, onCategory, onHist const history = data?.history ?? []; const triage = triageCounts(files); 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
    diff --git a/src/components/settings.test.tsx b/src/components/settings.test.tsx index ab81039..b6c80e4 100644 --- a/src/components/settings.test.tsx +++ b/src/components/settings.test.tsx @@ -24,7 +24,7 @@ function Tabbed({ start, ...props }: Omit, "tab" function renderSettings(start: SettingsTab = "rules") { let draft = preferences; const onChange = vi.fn((update: (value: Preferences) => Preferences) => { draft = update(draft); }); - render( {}} onAcceptExternal={() => {}} />); + render( {}} onAcceptExternal={() => {}} />); return () => draft; } @@ -146,3 +146,13 @@ it("mostra só as opções da aba escolhida", () => { expect(screen.getByRole("group", { name: "Idioma" })).toBeTruthy(); expect(screen.getByRole("switch", { name: "Efeitos sonoros" })).toBeTruthy(); }); + +it("marca só as abas com alterações não salvas", () => { + // The same categories in another order are not a change. + const saved = { ...preferences, enabled_categories: ["images", "documents"] }; + render( {}} onDiscard={() => {}} onAcceptExternal={() => {}} />); + const marked = screen.getAllByRole("tab").filter(tab => tab.getAttribute("aria-describedby")).map(tab => tab.textContent); + expect(marked).toEqual(["Regras personalizadas", "Aparência"]); + expect(screen.getByRole("tab", { name: "Aparência" }).getAttribute("aria-describedby")).toBeTruthy(); + expect(document.getElementById(screen.getByRole("tab", { name: "Aparência" }).getAttribute("aria-describedby")!)?.textContent).toBe("Alterações não salvas"); +}); diff --git a/src/components/settings.tsx b/src/components/settings.tsx index f7a6b18..e52f7c2 100644 --- a/src/components/settings.tsx +++ b/src/components/settings.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useId, useState } from "react"; import { Tabs } from "radix-ui"; import { open } from "@tauri-apps/plugin-dialog"; import { CircleHelp, FolderOpen, ListFilter, Moon, Palette, Plus, Power, RefreshCw, Shapes, Sun, ShieldCheck, Trash2, Zap } from "lucide-react"; @@ -7,6 +7,8 @@ import { Input } from "@/components/ui/input"; import { Switch } from "@/components/ui/switch"; import { api, displayPath, type Category, type Preferences, type Rule } from "@/lib/api"; import { t } from "@/lib/i18n"; +import { samePreferences } from "@/lib/experience"; +import { useAudioFeedback } from "@/components/audio/audio-provider"; import { useMotionAllowed } from "@/components/motion/feedback"; import { useContentMotion } from "@/components/motion/transitions"; import { version } from "../../package.json"; @@ -18,21 +20,25 @@ import { firstRuleTutorial, RulesTutorial } from "@/components/rules-tutorial"; // The page's groups. Language and sounds belong to Appearance. export type SettingsTab = "folders" | "automation" | "categories" | "rules" | "appearance" | "system"; +// Each tab lists the preferences it edits, so it can show its own unsaved changes. const tabs = () => [ - { id: "folders", label: t("Folders"), icon: FolderOpen }, - { id: "automation", label: t("Automatic organization"), icon: Zap }, - { id: "categories", label: t("Categories"), icon: Shapes }, - { id: "rules", label: t("Custom rules"), icon: ListFilter }, - { id: "appearance", label: t("Appearance"), icon: Palette }, - { id: "system", label: t("System"), icon: Power }, + { id: "folders", label: t("Folders"), icon: FolderOpen, fields: ["source", "destination", "extra_sources"] }, + { id: "automation", label: t("Automatic organization"), icon: Zap, fields: ["automatic"] }, + { id: "categories", label: t("Categories"), icon: Shapes, fields: ["enabled_categories"] }, + { id: "rules", label: t("Custom rules"), icon: ListFilter, fields: ["rules"] }, + { id: "appearance", label: t("Appearance"), icon: Palette, fields: ["theme", "language"] }, + { id: "system", label: t("System"), icon: Power, fields: ["autostart", "notifications", "updates"] }, ] as const; -export function Settings({ draft, categories, busy, dirty, external, tab, onTab, onChange: setDraft, onDiscard, onAcceptExternal }: { - draft: Preferences; categories: Category[]; busy: boolean; dirty: boolean; external: Preferences | null; +export function Settings({ draft, saved, categories, busy, dirty, external, tab, onTab, onChange: setDraft, onDiscard, onAcceptExternal }: { + draft: Preferences; saved: Preferences; categories: Category[]; busy: boolean; dirty: boolean; external: Preferences | null; tab: SettingsTab; onTab: (tab: SettingsTab) => void; onChange: (update: (value: Preferences) => Preferences) => void; onDiscard: () => void; onAcceptExternal: () => void; }) { const [pickerError, setPickerError] = useState(""); + const pendingId = useId(); + const audioDirty = useAudioFeedback().dirty; + const pending = (id: SettingsTab, fields: readonly (keyof Preferences)[]) => (id === "appearance" && audioDirty) || !samePreferences(saved, { ...saved, ...Object.fromEntries(fields.map(field => [field, draft[field]])) }); const [tutorial, setTutorial] = useState(false); // Kept as data, so the message follows the language at render. const [updateCheck, setUpdateCheck] = useState<{ state: "checking" } | { state: "found"; version: string } | { state: "latest" } | { state: "error"; error: string } | null>(null); @@ -63,7 +69,7 @@ export function Settings({ draft, categories, busy, dirty, external, tab, onTab, {external &&
    {t("The saved settings were updated")}

    {t("Your draft was kept. Compare the current version before deciding which to save.")}

    {t("Saved source")}
    {[external.source, ...external.extra_sources].map(displayPath).join(", ")}
    {t("Saved destination")}
    {displayPath(external.destination)}
    {t("Saved automation")}
    {external.automatic ? t("On") : t("Off")}
    {t("Saved categories")}
    {categories.filter(c => external.enabled_categories.includes(c.id)).map(c => c.name).join(", ") || t("None")}
    {t("Saved theme")}
    {external.theme === "dark" ? t("Dark") : t("Light")}
    {t("Saved language")}
    {languages().find(item => item.id === external.language)?.name}
    {t("Saved notifications")}
    {external.notifications ? t("On (plural)") : t("Off (plural)")}
    {t("Saved updates")}
    {external.updates ? t("On (plural)") : t("Off (plural)")}
    {t("Saved startup")}
    {external.autostart ? t("On") : t("Off")}
    {t("Saved rules")}
    {external.rules.length}
    }

    {external ? t("The saved settings changed. Review your draft before saving.") : dirty ? t("Unsaved changes. The saved settings are still in use.") : t("All changes are saved.")}

    onTab(value as SettingsTab)}> - {tabs().map(({ id, label, icon: Icon }) => )} + {tabs().map(({ id, label, icon: Icon, fields }) => { const changed = pending(id, fields); return ; })}{t("Unsaved changes")}
    diff --git a/src/i18n.test.tsx b/src/i18n.test.tsx index 632c05b..d5f3700 100644 --- a/src/i18n.test.tsx +++ b/src/i18n.test.tsx @@ -126,7 +126,7 @@ describe("idioma", () => { describe("interface em inglês", () => { it("mostra a visão geral sem texto em português", () => { setLanguage("en"); - render( {}} onSettings={() => {}} onCategory={() => {}} onHistory={() => {}} onOperation={() => {}} onOpenDestination={() => {}} counts={new Map()} />); + render( {}} onSettings={() => {}} onCategory={() => {}} onHistory={() => {}} onOperation={() => {}} onOpenDestination={() => {}} counts={new Map()} onConflicts={() => {}} />); expect(screen.getByRole("button", { name: /Documents.*Enabled/ })).toBeTruthy(); expect(screen.getByRole("img").getAttribute("aria-label")).toBe("1 ready, 1 conflict, 0 ignored"); expectEnglish(); @@ -134,7 +134,7 @@ describe("interface em inglês", () => { it("mostra a tabela e a prévia sem texto em português", () => { setLanguage("en"); - render( {}} />); + render( {}} />, { wrapper: Tooltip.Provider }); expect(screen.getByRole("columnheader", { name: "Modified" })).toBeTruthy(); expect(screen.getByRole("button", { name: "View a.pdf" })).toBeTruthy(); fireEvent.click(screen.getAllByRole("button", { name: "View path and destination" })[0]); @@ -171,7 +171,7 @@ describe("interface em inglês", () => { describe("seletor de idioma", () => { const renderSettings = (onChange = vi.fn()) => { - render( {}} onChange={onChange} onDiscard={() => {}} onAcceptExternal={() => {}} />); + render( {}} onChange={onChange} onDiscard={() => {}} onAcceptExternal={() => {}} />); return onChange; }; diff --git a/src/lib/api.ts b/src/lib/api.ts index ac437f9..5ff3473 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -34,6 +34,7 @@ export const api = { checkUpdate: () => invoke("check_update"), installUpdate: () => invoke("install_update"), openFolder: (which: "source" | "destination") => invoke("open_folder", { which }), + revealMovement: (operationId: number, movementId: number) => invoke("reveal_movement", { operationId, movementId }), }; export function summarizeOperation(operation: Operation | OperationSummary): OperationSummary { From 8faa1af5a3c1348fd0ee94008865063f37c20f91 Mon Sep 17 00:00:00 2001 From: thonyydev <105062764+thonyydev@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:14:10 -0300 Subject: [PATCH 4/7] feat: undo from the result, relative dates and keep a file in place - The organization result offers Undo, which opens the same restore review as the history. It is off while an automatic batch runs. - Dates read "Today, 10:04" and "Yesterday, 23:50" by the calendar; the words come from Intl, so every language gets them without new strings. - "Never organize this file" in a file's details adds a "Keep in place" rule for its exact name at the top of the draft rules, so broader rules don't win, and opens the rules tab to review and save. Names with spaces at the ends, which a rule can't hold, don't offer it. Co-Authored-By: Claude Opus 5.5 --- i18n/en.json | 1 + i18n/es.json | 1 + i18n/fr.json | 1 + i18n/it.json | 1 + i18n/pt-BR.json | 1 + src/App.css | 1 + src/App.test.tsx | 21 +++++++++++++++++++++ src/App.tsx | 9 +++++++-- src/components/file-table.test.tsx | 11 +++++++++++ src/components/file-table.tsx | 16 ++++++++-------- src/components/operation-dialogs.test.tsx | 13 +++++++++++-- src/components/operation-dialogs.tsx | 8 ++++---- src/lib/api.ts | 9 ++++++++- src/lib/date.test.ts | 12 ++++++++++++ 14 files changed, 88 insertions(+), 17 deletions(-) create mode 100644 src/lib/date.test.ts diff --git a/i18n/en.json b/i18n/en.json index 756cd8f..739f22b 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -84,6 +84,7 @@ "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", + "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", diff --git a/i18n/es.json b/i18n/es.json index c100879..01fdd38 100644 --- a/i18n/es.json +++ b/i18n/es.json @@ -84,6 +84,7 @@ "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", + "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", diff --git a/i18n/fr.json b/i18n/fr.json index 2c37a0b..c27c101 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -84,6 +84,7 @@ "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", + "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", diff --git a/i18n/it.json b/i18n/it.json index 4f9cae6..ac610e8 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -84,6 +84,7 @@ "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", + "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", diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json index e85fae8..e2b28eb 100644 --- a/i18n/pt-BR.json +++ b/i18n/pt-BR.json @@ -84,6 +84,7 @@ "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", + "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", diff --git a/src/App.css b/src/App.css index 077ba3a..c7a5d07 100644 --- a/src/App.css +++ b/src/App.css @@ -284,6 +284,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); } diff --git a/src/App.test.tsx b/src/App.test.tsx index e018261..2e60d65 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -301,6 +301,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 () => { @@ -703,6 +711,19 @@ describe("composição desktop", () => { 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" })); diff --git a/src/App.tsx b/src/App.tsx index 644c9f5..21875c8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -72,6 +72,11 @@ function OrganizerApp() { // 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); @@ -360,7 +365,7 @@ function OrganizerApp() { {automatic &&

    {t("Automatic organization")}

    op.id === automatic.operationId)} />
    } {loading ?
    : {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 === "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()} 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)} /> :
    )}
    } @@ -372,7 +377,7 @@ 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"); }} - onOpenDestination={openDestination} 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); }} /> + 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 && } diff --git a/src/components/file-table.test.tsx b/src/components/file-table.test.tsx index c285651..20dd318 100644 --- a/src/components/file-table.test.tsx +++ b/src/components/file-table.test.tsx @@ -168,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 fde0b1b..af4513d 100644 --- a/src/components/file-table.tsx +++ b/src/components/file-table.tsx @@ -1,5 +1,5 @@ import { Tooltip } from "radix-ui"; -import { File, ArrowRight, ChevronRight, Eye, SearchX } from "lucide-react"; +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"; @@ -18,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 }) { @@ -30,10 +30,10 @@ 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]); @@ -44,14 +44,14 @@ function FileRow({ file, source, index, preview, fullPaths, category, open, onTo 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)} />} + {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 && {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); @@ -161,7 +161,7 @@ export function FileTable({ files, categories, preview = false, fullPaths = fals previousEnd = item.end; return - + ; }); return
    ({ 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(), onOpenDestination: 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,12 @@ 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); +}); diff --git a/src/components/operation-dialogs.tsx b/src/components/operation-dialogs.tsx index 57291ce..13997de 100644 --- a/src/components/operation-dialogs.tsx +++ b/src/components/operation-dialogs.tsx @@ -8,17 +8,17 @@ 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, onOpenDestination, 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; onOpenDestination: () => 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. @@ -61,7 +61,7 @@ export function OperationDialogs({ preview, undoTarget, categories, action, busy

    {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/lib/api.ts b/src/lib/api.ts index 5ff3473..1d5a8f9 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -53,7 +53,14 @@ export function bytes(value: number) { const unit = Math.min(Math.floor(Math.log(value) / Math.log(1024)), 3); return `${new Intl.NumberFormat(locale(), { maximumFractionDigits: 1 }).format(value / 1024 ** unit)} ${["B", "KB", "MB", "GB"][unit]}`; } -export function date(value: number) { return new Intl.DateTimeFormat(locale(), { dateStyle: "short", timeStyle: "short" }).format(value); } +export function date(value: number, now = Date.now()) { + const midnight = (time: number) => new Date(time).setHours(0, 0, 0, 0); + const days = Math.round((midnight(now) - midnight(value)) / 86_400_000); + if (days !== 0 && days !== 1) return new Intl.DateTimeFormat(locale(), { dateStyle: "short", timeStyle: "short" }).format(value); + // "today" and "yesterday" come from the platform in every language. + const day = new Intl.RelativeTimeFormat(locale(), { numeric: "auto" }).format(-days, "day"); + return `${day[0].toLocaleUpperCase(locale()) + day.slice(1)}, ${new Intl.DateTimeFormat(locale(), { timeStyle: "short" }).format(value)}`; +} export function basename(path: string) { return path.split(/[\\/]/).pop() || path; } // Presentation only: keep original paths for identities, persistence and native commands. export function displayPath(path: string): string { diff --git a/src/lib/date.test.ts b/src/lib/date.test.ts new file mode 100644 index 0000000..c4f0b80 --- /dev/null +++ b/src/lib/date.test.ts @@ -0,0 +1,12 @@ +import { expect, it } from "vitest"; +import { date } from "./api"; + +it("diz hoje e ontem pelo calendário, e a data curta nos outros dias", () => { + const now = new Date(2026, 10, 9, 0, 30).getTime(); + expect(date(new Date(2026, 10, 9, 0, 5).getTime(), now)).toBe("Hoje, 00:05"); + // Yesterday at 23:50 is twenty minutes ago, but still yesterday. + expect(date(new Date(2026, 10, 8, 23, 50).getTime(), now)).toBe("Ontem, 23:50"); + expect(date(new Date(2026, 10, 7, 9, 0).getTime(), now)).toBe("07/11/2026, 09:00"); + // A clock running ahead never reads as "tomorrow". + expect(date(new Date(2026, 10, 10, 9, 0).getTime(), now)).toBe("10/11/2026, 09:00"); +}); From 66b1e8fd41eee20d73885c4cced95c9f1ac966e5 Mon Sep 17 00:00:00 2001 From: thonyydev <105062764+thonyydev@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:24:37 -0300 Subject: [PATCH 5/7] feat: search the whole history and open it from the notification - History search: type part of a file name to see, across every operation, where each match went, newest first and up to 50, with "Show in folder" for files still moved. The backend compares file names only, ignoring case in every language (SQLite's LIKE only does so for ASCII). Screen readers hear a short count, not the whole list. - A click on the "files organized" notification shows the window on the history; other notifications only show the window. Windows reports the click only while the toast is on screen. Co-Authored-By: Claude Opus 5.5 --- i18n/en.json | 5 +++ i18n/es.json | 5 +++ i18n/fr.json | 5 +++ i18n/it.json | 5 +++ i18n/pt-BR.json | 5 +++ src-tauri/src/lib.rs | 61 ++++++++++++++++++++++++++++++--- src-tauri/src/store.rs | 47 +++++++++++++++++++++++++ src-tauri/src/tests.rs | 59 +++++++++++++++++++++++++++++++ src/App.css | 5 +++ src/App.test.tsx | 7 ++++ src/App.tsx | 8 +++++ src/components/history.test.tsx | 34 +++++++++++++++++- src/components/history.tsx | 44 ++++++++++++++++++++++-- src/lib/api.ts | 2 ++ 14 files changed, 284 insertions(+), 8 deletions(-) diff --git a/i18n/en.json b/i18n/en.json index 739f22b..77d16c8 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -84,6 +84,11 @@ "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", + "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.", diff --git a/i18n/es.json b/i18n/es.json index 01fdd38..95ea9e5 100644 --- a/i18n/es.json +++ b/i18n/es.json @@ -84,6 +84,11 @@ "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", + "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.", diff --git a/i18n/fr.json b/i18n/fr.json index c27c101..c1eb3b7 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -84,6 +84,11 @@ "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", + "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.", diff --git a/i18n/it.json b/i18n/it.json index ac610e8..01917c6 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -84,6 +84,11 @@ "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", + "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.", diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json index e2b28eb..61f79e5 100644 --- a/i18n/pt-BR.json +++ b/i18n/pt-BR.json @@ -84,6 +84,11 @@ "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", + "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.", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8060a47..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 || { @@ -992,7 +1037,8 @@ fn run_application() -> std::result::Result<(), startup::StartupError> { install_update, retry_monitoring, open_folder, - reveal_movement + reveal_movement, + search_history ]) .build(tauri::generate_context!()) .map_err(|_| startup::StartupError::Runtime)?; @@ -1036,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 b279ad9..3e7890c 100644 --- a/src-tauri/src/tests.rs +++ b/src-tauri/src/tests.rs @@ -2322,3 +2322,62 @@ fn plain_path_drops_only_the_verbatim_prefix() { 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 c7a5d07..d6d0bd8 100644 --- a/src/App.css +++ b/src/App.css @@ -176,6 +176,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; } diff --git a/src/App.test.tsx b/src/App.test.tsx index 2e60d65..eca18f9 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -1233,6 +1233,13 @@ it("mostra o guia na primeira abertura e não repete na seguinte", async () => { 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 }); diff --git a/src/App.tsx b/src/App.tsx index 21875c8..d2f25dd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -99,6 +99,14 @@ function OrganizerApp() { 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) => { diff --git a/src/components/history.test.tsx b/src/components/history.test.tsx index e8f236b..731bf71 100644 --- a/src/components/history.test.tsx +++ b/src/components/history.test.tsx @@ -4,7 +4,7 @@ import { HistoryView } from "./history"; import type { Operation } from "@/lib/api"; import { summarizeOperation } from "@/lib/api"; -const queries = vi.hoisted(() => ({ operation: vi.fn(), destinations: vi.fn(), revealMovement: 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 }) })); @@ -188,3 +188,35 @@ it("mostra na pasta só os arquivos que ainda estão no destino e explica a falh 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(); +}); diff --git a/src/components/history.tsx b/src/components/history.tsx index ca6d0da..271125b 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"; @@ -58,6 +59,43 @@ export function Activity({ operation, onOpen, expanded, motionAllowed = false }: ; } +// 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, newAvailable, onReload }: { history: (Operation | Summary)[]; expanded: number | null; working: boolean; onExpand: (id: number | null) => void; onUndo: (operation: Operation | Summary) => void; @@ -67,7 +105,7 @@ export function HistoryView({ history, expanded, working, openingUndo, onExpand, const motionAllowed = useMotionAllowed(); const ref = useContentMotion(history.slice(0, 4).map(op => op.id).join(":"), motionAllowed); 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")}{newAvailable && }
    {history.map(op =>
    onExpand(expanded === op.id ? null : op.id)} />
    diff --git a/src/lib/api.ts b/src/lib/api.ts index 1d5a8f9..f6cd4d6 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -5,6 +5,7 @@ export interface Category { id: string; name: string; extensions: string[] } export interface Rule { pattern: string; folder: string; keep: boolean } export interface Preferences { source: string; destination: string; automatic: boolean; enabled_categories: string[]; theme: "dark" | "light"; language: "system" | Language; notifications: boolean; updates: boolean; autostart: boolean; rules: Rule[]; extra_sources: string[] } export interface FileEntry { name: string; path: string; extension: string; category: string; size: number; modified: number; destination: string; status: "ready" | "ignored" | "conflict"; reason: string | null; rename_to?: string | null } +export interface FoundMovement { id: number; operation_id: number; created: number; source: string; destination: string; status: string } export interface Movement { id: number; source: string; destination: string; status: string; error: string | null; size: number } export interface Operation { id: number; created: number; kind: string; movements: Movement[] } export interface OperationSummary { id: number; created: number; kind: string; total: number; moved: number; undone: number; errors: number } @@ -35,6 +36,7 @@ export const api = { installUpdate: () => invoke("install_update"), openFolder: (which: "source" | "destination") => invoke("open_folder", { which }), revealMovement: (operationId: number, movementId: number) => invoke("reveal_movement", { operationId, movementId }), + searchHistory: (query: string) => invoke("search_history", { query }), }; export function summarizeOperation(operation: Operation | OperationSummary): OperationSummary { From e135e8f1654aee5f0eea4f7a49dc8912bde56e8d Mon Sep 17 00:00:00 2001 From: thonyydev <105062764+thonyydev@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:34:45 -0300 Subject: [PATCH 6/7] feat: preview by destination folder and mark arriving operations - The review before organizing can switch between the list and a view by destination folder: the destination root, one collapsible folder per group with its file and conflict counts, ignored files apart and files unchecked in the list marked. It opens in the list, which holds the checkboxes; closed folders render no rows. Both views share the same heights, also while the progress panel shows. - In the overview and the history, an operation that arrives while the page is open slides in with a tint that fades, and the newest one keeps a thin brand mark. Reduced motion keeps only the mark. Co-Authored-By: Claude Opus 5.5 --- i18n/en.json | 5 +++ i18n/es.json | 5 +++ i18n/fr.json | 5 +++ i18n/it.json | 5 +++ i18n/pt-BR.json | 5 +++ src/App.css | 21 +++++++++- src/components/history.test.tsx | 11 +++++ src/components/history.tsx | 14 +++++-- src/components/operation-dialogs.test.tsx | 28 +++++++++++++ src/components/operation-dialogs.tsx | 8 ++-- src/components/overview.tsx | 5 ++- src/components/preview-tree.tsx | 51 +++++++++++++++++++++++ 12 files changed, 153 insertions(+), 10 deletions(-) create mode 100644 src/components/preview-tree.tsx diff --git a/i18n/en.json b/i18n/en.json index 77d16c8..69e0b32 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -84,6 +84,11 @@ "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.", diff --git a/i18n/es.json b/i18n/es.json index 95ea9e5..a054c2d 100644 --- a/i18n/es.json +++ b/i18n/es.json @@ -84,6 +84,11 @@ "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.", diff --git a/i18n/fr.json b/i18n/fr.json index c1eb3b7..a89ad55 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -84,6 +84,11 @@ "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.", diff --git a/i18n/it.json b/i18n/it.json index 01917c6..3a720d9 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -84,6 +84,11 @@ "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.", diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json index 61f79e5..5179e10 100644 --- a/i18n/pt-BR.json +++ b/i18n/pt-BR.json @@ -84,6 +84,11 @@ "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.", diff --git a/src/App.css b/src/App.css index d6d0bd8..768bc04 100644 --- a/src/App.css +++ b/src/App.css @@ -168,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; } @@ -369,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; } diff --git a/src/components/history.test.tsx b/src/components/history.test.tsx index 731bf71..bb1dd0e 100644 --- a/src/components/history.test.tsx +++ b/src/components/history.test.tsx @@ -220,3 +220,14 @@ it("busca um arquivo no histórico inteiro e mostra para onde ele foi", async () 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 271125b..d389e90 100644 --- a/src/components/history.tsx +++ b/src/components/history.tsx @@ -43,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 ; } +// 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; @@ -104,8 +111,9 @@ export function HistoryView({ history, expanded, working, openingUndo, onExpand, }) { 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")}{newAvailable && }
    {history.map((op, index) =>
    onExpand(expanded === op.id ? null : op.id)} />
    diff --git a/src/components/operation-dialogs.test.tsx b/src/components/operation-dialogs.test.tsx index af2781d..e701e1e 100644 --- a/src/components/operation-dialogs.test.tsx +++ b/src/components/operation-dialogs.test.tsx @@ -192,3 +192,31 @@ it("só oferece Desfazer no resultado quando nada mais está rodando", () => { 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 13997de..8d5fe80 100644 --- a/src/components/operation-dialogs.tsx +++ b/src/components/operation-dialogs.tsx @@ -1,8 +1,9 @@ -import { FolderDown, FolderOpen, 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"; @@ -23,6 +24,7 @@ export function OperationDialogs({ preview, undoTarget, categories, action, busy }) { // 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,8 +59,8 @@ 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) ? <>{operation && summarizeOperation(operation).moved > 0 && }{footer} : <> diff --git a/src/components/overview.tsx b/src/components/overview.tsx index 17484dd..3657c77 100644 --- a/src/components/overview.tsx +++ b/src/components/overview.tsx @@ -1,7 +1,7 @@ import { Tooltip } from "radix-ui"; 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"; @@ -17,6 +17,7 @@ export function Overview({ data, counts, onConflicts, onFiles, onSettings, onCat const files = data?.files ?? []; const history = data?.history ?? []; const triage = triageCounts(files); + const seen = useSeenOperation(history); const fullest = Math.max(1, ...counts.values()); const stats: [string, number, ReactNode, boolean][] = [ [t("Available"), files.length, bytes(files.reduce((sum, f) => sum + f.size, 0)), true], @@ -38,7 +39,7 @@ export function Overview({ data, counts, onConflicts, onFiles, onSettings, onCat
    {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)} +
    +
    ; +} From d0115624fc042f010f3e3292088b0789082cb6f8 Mon Sep 17 00:00:00 2001 From: thonyydev <105062764+thonyydev@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:46:16 -0300 Subject: [PATCH 7/7] fix: add new operations to the history on their own The history used to keep new operations out of a loaded list and offer a "New operations - refresh the list" button. Now the newest page from each snapshot is merged in: new operations join the top (with the arrival animation) and changed ones update in place, keeping the loaded pages and the open operation. When more than a page arrived at once, the list starts over from that page, so no gap is left, and a pending "Load more" is discarded. The button, the reload path and its string are gone. The organization result dialog is wider, so its four buttons fit one row. Co-Authored-By: Claude Opus 5.5 --- i18n/en.json | 1 - i18n/es.json | 1 - i18n/fr.json | 1 - i18n/it.json | 1 - i18n/pt-BR.json | 1 - src/App.css | 2 +- src/App.test.tsx | 10 +++------- src/App.tsx | 2 +- src/components/history.tsx | 6 +++--- src/lib/use-history.test.ts | 25 ++++++++++++++++++------- src/lib/use-history.ts | 31 +++++++++++++++---------------- 11 files changed, 41 insertions(+), 40 deletions(-) diff --git a/i18n/en.json b/i18n/en.json index 69e0b32..99cbc66 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -137,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…", diff --git a/i18n/es.json b/i18n/es.json index a054c2d..48c2ce4 100644 --- a/i18n/es.json +++ b/i18n/es.json @@ -137,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…", diff --git a/i18n/fr.json b/i18n/fr.json index a89ad55..fc8f50f 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -137,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…", diff --git a/i18n/it.json b/i18n/it.json index 3a720d9..69946eb 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -137,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…", diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json index 5179e10..a368cf9 100644 --- a/i18n/pt-BR.json +++ b/i18n/pt-BR.json @@ -137,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…", diff --git a/src/App.css b/src/App.css index 768bc04..6ac5540 100644 --- a/src/App.css +++ b/src/App.css @@ -375,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)); } diff --git a/src/App.test.tsx b/src/App.test.tsx index eca18f9..ba24ff3 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -159,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"); @@ -173,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); }); diff --git a/src/App.tsx b/src/App.tsx index d2f25dd..7cbc970 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -374,7 +374,7 @@ function OrganizerApp() { {loading ?
    : {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()} newAvailable={historyPages.newAvailable} onReload={() => void historyPages.reload(expanded)} />} + {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} />} diff --git a/src/components/history.tsx b/src/components/history.tsx index d389e90..1ad0d1a 100644 --- a/src/components/history.tsx +++ b/src/components/history.tsx @@ -103,17 +103,17 @@ function HistorySearch() {
    ; } -export function HistoryView({ history, expanded, working, openingUndo, onExpand, onUndo, hasMore, loading, pageError, onLoadMore, onRetry, newAvailable, onReload }: { +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, index) =>
    + 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/lib/use-history.test.ts b/src/lib/use-history.test.ts index b4b294f..23b6d0f 100644 --- a/src/lib/use-history.test.ts +++ b/src/lib/use-history.test.ts @@ -23,17 +23,28 @@ it("inicializa vazio e consulta várias páginas sem duplicar ou reordenar IDs", expect(result.current.next_cursor).toBeNull(); }); -it("mantém o cursor e a seleção ao receber novos registros e atualizar a lista explicitamente", async () => { +it("põe as operações novas no topo sem perder as páginas carregadas", async () => { const { result } = renderHook(useHistoryPages); act(() => result.current.sync(page(200, 101))); mocks.history.mockResolvedValueOnce(page(100, 1)); await act(() => result.current.loadMore()); + // 201-203 are new; 150 was undone meanwhile. + act(() => result.current.sync({ ...page(203, 104), operations: page(203, 104).operations.map(op => op.id === 150 ? { ...op, undone: 1 } : op) })); + expect(result.current.operations.map(op => op.id)).toEqual(Array.from({ length: 203 }, (_, i) => 203 - i)); + expect(result.current.operations.find(op => op.id === 150)?.undone).toBe(1); + expect(result.current.next_cursor).toBeNull(); +}); + +it("recomeça pela página nova quando chegou mais de uma página e descarta uma consulta antiga", async () => { + const { result } = renderHook(useHistoryPages); + act(() => result.current.sync(page(200, 101))); + const stale = deferred(); mocks.history.mockReturnValueOnce(stale.promise); + let waiting: Promise; + act(() => { waiting = result.current.loadMore(); }); + // Merging 1101-1200 with 101-200 would hide 201-1100. act(() => result.current.sync(page(1200, 1101))); - expect(result.current.operations).toHaveLength(200); - expect(result.current.newAvailable).toBe(true); expect(result.current.next_cursor).toBeNull(); - mocks.history.mockResolvedValueOnce(page(1200, 1101)); await act(() => result.current.reload(1)); - expect(result.current.operations).toHaveLength(101); - expect(result.current.operations[100].id).toBe(1); - expect(result.current.next_cursor).toBe(1101); expect(result.current.newAvailable).toBe(false); + await act(async () => { stale.resolve(page(100, 1)); await waiting; }); + expect(result.current.operations.map(op => op.id)).toEqual(Array.from({ length: 100 }, (_, i) => 1200 - i)); + expect(result.current.next_cursor).toBe(1101); expect(result.current.loading).toBe(false); }); it("preserva registros e cursor após falha e permite tentar novamente sem comandos duplicados", async () => { diff --git a/src/lib/use-history.ts b/src/lib/use-history.ts index 15c7088..45b6f13 100644 --- a/src/lib/use-history.ts +++ b/src/lib/use-history.ts @@ -7,19 +7,21 @@ function merge(current: OperationSummary[], incoming: OperationSummary[]) { } export function useHistoryPages() { - const [state, setState] = useState({ operations: [] as OperationSummary[], next_cursor: null as number | null, anchor: 0, latest: 0, loading: false, error: "" }); + const [state, setState] = useState({ operations: [] as OperationSummary[], next_cursor: null as number | null, loading: false, error: "" }); const stateRef = useRef(state); stateRef.current = state; const request = useRef(0); const pending = useRef(false); - const retry = useRef({ restart: false, retain: null as number | null }); useEffect(() => () => { request.current++; }, []); + // The snapshot brings the newest page: new operations join the top of the list. const sync = useCallback((page: HistoryPage) => { - setState(current => { - if (!current.operations.length) return { ...current, ...page, anchor: page.operations[0]?.id ?? 0, latest: page.operations[0]?.id ?? 0 }; - const latest = new Map(page.operations.map(op => [op.id, op])); - return { ...current, latest: page.operations[0]?.id ?? current.latest, operations: current.operations.map(op => latest.get(op.id) ?? op) }; - }); + const newest = stateRef.current.operations[0]?.id ?? 0; + const oldestIncoming = page.operations[page.operations.length - 1]?.id ?? 0; + // More than a page arrived since: merging would leave a gap, so the list starts over from this page. + if (!newest || (page.next_cursor !== null && oldestIncoming > newest)) { + request.current++; pending.current = false; + setState(current => ({ ...current, loading: false, operations: page.operations, next_cursor: page.next_cursor })); + } else setState(current => ({ ...current, operations: merge(current.operations, page.operations) })); }, []); const upsert = useCallback((operation: OperationSummary) => { @@ -27,22 +29,19 @@ export function useHistoryPages() { setState(current => ({ ...current, loading: false, operations: merge(current.operations, [operation]) })); }, []); - const load = useCallback(async (restart = false, retain: number | null = null) => { - if (pending.current || (!restart && stateRef.current.next_cursor === null)) return; - pending.current = true; retry.current = { restart, retain }; + const load = useCallback(async () => { + if (pending.current || stateRef.current.next_cursor === null) return; + pending.current = true; const version = ++request.current; - const before = restart ? null : stateRef.current.next_cursor; + const before = stateRef.current.next_cursor; setState(current => ({ ...current, loading: true })); try { const page = await api.history(before); if (version !== request.current) return; - setState(current => ({ ...current, error: "", loading: false, next_cursor: page.next_cursor, - anchor: restart ? page.operations[0]?.id ?? 0 : current.anchor, - latest: Math.max(current.latest, page.operations[0]?.id ?? 0), - operations: merge(restart ? current.operations.filter(op => op.id === retain) : current.operations, page.operations) })); + setState(current => ({ ...current, error: "", loading: false, next_cursor: page.next_cursor, operations: merge(current.operations, page.operations) })); } catch (error) { if (version === request.current) setState(current => ({ ...current, loading: false, error: errorMessage(error) })); } finally { if (version === request.current) pending.current = false; } }, []); - return { ...state, newAvailable: state.latest > state.anchor, sync, upsert, loadMore: () => load(), reload: (retain: number | null) => load(true, retain), retry: () => load(retry.current.restart, retry.current.retain) }; + return { ...state, sync, upsert, loadMore: load, retry: load }; }