From ec97f987b71eada6fa3c58bc6fcae6ec4a007721 Mon Sep 17 00:00:00 2001 From: CodeDead Date: Sat, 5 Dec 2026 22:37:02 +0100 Subject: [PATCH 1/5] feat: improve hashing, comparison, and clipboard workflows - Parallelize file hashing, validate file paths, and standardize CRC output widths. - Improve hash comparison diagnostics, clipboard interactions, export handling, and formatting. - Add localized messages and tests for comparison, formatting, and locale consistency. --- eslint.config.js | 2 +- package.json | 1 + src-tauri/src/hasher.rs | 122 ++++++++++++++++++++++----- src-tauri/src/lib.rs | 35 ++++++-- src-tauri/tauri.conf.json | 4 +- src/App.jsx | 38 ++++++--- src/components/AppNavbar.jsx | 6 +- src/components/CompareHashInput.jsx | 24 ++++-- src/components/ContextMenuArea.jsx | 8 +- src/components/DropZone.jsx | 1 + src/components/ExportButton.jsx | 26 ++++-- src/components/HashResultList.jsx | 30 ++++--- src/components/UpdateCheckModals.jsx | 4 +- src/components/UpdateModal.jsx | 28 ++++-- src/constants/version.js | 3 + src/hooks/useUpdateCheck.js | 24 ++++-- src/i18n/locales/de.js | 3 + src/i18n/locales/en.js | 2 + src/i18n/locales/es.js | 2 + src/i18n/locales/fr.js | 3 + src/i18n/locales/it.js | 2 + src/i18n/locales/ja.js | 3 + src/i18n/locales/nl.js | 3 + src/i18n/locales/pt.js | 2 + src/i18n/locales/ru.js | 2 + src/i18n/locales/tr.js | 2 + src/i18n/locales/uk.js | 2 + src/pages/AboutPage.jsx | 30 ++++--- src/pages/FileHashPage.jsx | 26 ++++-- src/pages/SettingsPage.jsx | 4 +- src/pages/TextHashPage.jsx | 67 ++++++++++++--- src/services/updater.js | 41 +++++++-- src/state/HashProvider.jsx | 115 +++++++++++++++++++------ src/state/SettingsProvider.jsx | 11 +-- src/state/hashContext.js | 9 ++ src/utils/clipboard.js | 37 ++++++++ src/utils/compare.js | 15 +++- src/utils/format.js | 18 +++- tests/compare.test.js | 52 ++++++++++++ tests/format.test.js | 56 ++++++++++++ tests/i18n.test.js | 35 ++++++++ tests/updater.test.js | 97 +++++++++++++++++++++ tests/virustotal.test.js | 14 +++ 43 files changed, 848 insertions(+), 161 deletions(-) create mode 100644 src/constants/version.js create mode 100644 src/utils/clipboard.js create mode 100644 tests/compare.test.js create mode 100644 tests/format.test.js create mode 100644 tests/i18n.test.js create mode 100644 tests/updater.test.js create mode 100644 tests/virustotal.test.js diff --git a/eslint.config.js b/eslint.config.js index 152d91d..aa58911 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -36,7 +36,7 @@ export default [ }, }, { - files: ['*.config.js'], + files: ['*.config.js', 'tests/**/*.js'], languageOptions: { globals: { ...globals.node, diff --git a/package.json b/package.json index 940ac22..a4457e1 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "tauri:build": "tauri build", "lint": "eslint .", "lint:fix": "eslint . --fix", + "test": "node --test", "format": "prettier --write .", "format:check": "prettier --check ." }, diff --git a/src-tauri/src/hasher.rs b/src-tauri/src/hasher.rs index 04dd9ec..d2eaac9 100644 --- a/src-tauri/src/hasher.rs +++ b/src-tauri/src/hasher.rs @@ -238,23 +238,23 @@ impl SingleHasher { }, Self::Crc1(val) => HashResult { hash_type: "CRC1".into(), - hash: format!("{val:x}"), + hash: format!("{val:02x}"), }, Self::Crc8(h) => HashResult { hash_type: "CRC8".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:02x}", h.finalize()), }, Self::Crc16(h) => HashResult { hash_type: "CRC16".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:04x}", h.finalize()), }, Self::Crc24(h) => HashResult { hash_type: "CRC24".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:06x}", h.finalize()), }, Self::Crc32(h) => HashResult { hash_type: "CRC32".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:08x}", h.finalize()), }, Self::Xxh3_64(h) => HashResult { hash_type: "XXH3-64".into(), @@ -346,7 +346,10 @@ fn hash_file_sequential( where F: FnMut(HashProgress), { - let mut buffer = vec![0u8; CHUNK_SIZE.min((total_bytes as usize).max(64 * 1024))]; + let buffer_len = usize::try_from(total_bytes) + .unwrap_or(CHUNK_SIZE) + .clamp(64 * 1024, CHUNK_SIZE); + let mut buffer = vec![0u8; buffer_len]; let mut bytes_processed: u64 = 0; let mut last_emit = Instant::now(); @@ -401,24 +404,49 @@ fn hash_file_parallel( where F: FnMut(HashProgress), { + let total_hashers = hashers.len(); + let worker_count = thread::available_parallelism() + .map(std::num::NonZeroUsize::get) + .unwrap_or(4) + .min(total_hashers) + .max(1); + + let mut buckets: Vec> = + (0..worker_count).map(|_| Vec::new()).collect(); + for (index, hasher) in hashers.into_iter().enumerate() { + buckets[index % worker_count].push((index, hasher)); + } + + let read_aborted = AtomicBool::new(false); + thread::scope(|scope| { - let mut senders = Vec::with_capacity(hashers.len()); - let mut handles = Vec::with_capacity(hashers.len()); + let mut senders = Vec::with_capacity(worker_count); + let mut handles = Vec::with_capacity(worker_count); - for mut hasher in hashers { - let (tx, rx) = mpsc::sync_channel::>(CHANNEL_DEPTH); + for mut bucket in buckets { + let (tx, rx) = mpsc::sync_channel::>>(CHANNEL_DEPTH); + let read_aborted_ref = &read_aborted; senders.push(tx); handles.push(scope.spawn(move || { while let Ok(chunk) = rx.recv() { - if cancel_flag.load(Ordering::Relaxed) { + if cancel_flag.load(Ordering::Relaxed) + || read_aborted_ref.load(Ordering::Relaxed) + { return None; } - hasher.update(&chunk); + for (_, hasher) in &mut bucket { + hasher.update(&chunk); + } } - if cancel_flag.load(Ordering::Relaxed) { + if cancel_flag.load(Ordering::Relaxed) || read_aborted_ref.load(Ordering::Relaxed) { return None; } - Some(hasher.finalize()) + Some( + bucket + .into_iter() + .map(|(index, hasher)| (index, hasher.finalize())) + .collect::>(), + ) })); } @@ -438,7 +466,7 @@ where Ok(0) => break, Ok(bytes_read) => { buffer.truncate(bytes_read); - let chunk: Arc<[u8]> = Arc::from(buffer); + let chunk = Arc::new(buffer); for tx in &senders { if tx.send(Arc::clone(&chunk)).is_err() { @@ -463,6 +491,7 @@ where } } Err(err) => { + read_aborted.store(true, Ordering::Relaxed); read_error = Some(format!("Failed to read file: {err}")); break; } @@ -471,10 +500,14 @@ where drop(senders); - let mut hashes = Vec::with_capacity(handles.len()); + let mut indexed_hashes: Vec> = vec![None; total_hashers]; for handle in handles { match handle.join() { - Ok(Some(result)) => hashes.push(result), + Ok(Some(results)) => { + for (index, result) in results { + indexed_hashes[index] = Some(result); + } + } Ok(None) => cancelled = true, Err(_) => return Err("Hash worker thread panicked".to_string()), } @@ -488,6 +521,8 @@ where return Ok(None); } + let hashes: Vec = indexed_hashes.into_iter().flatten().collect(); + let final_total = total_bytes.max(bytes_processed); on_progress(HashProgress { bytes_processed, @@ -509,10 +544,16 @@ where F: FnMut(HashProgress), { let mut file = File::open(path).map_err(|err| format!("Failed to open file: {err}"))?; - let total_bytes = file + let metadata = file .metadata() - .map_err(|err| format!("Failed to read file metadata: {err}"))? - .len(); + .map_err(|err| format!("Failed to read file metadata: {err}"))?; + if metadata.is_dir() { + return Err("Selected path is a directory, not a file".to_string()); + } + if !metadata.is_file() { + return Err("Selected path is not a regular file".to_string()); + } + let total_bytes = metadata.len(); let hashers = build_hashers(options); if hashers.is_empty() { @@ -870,4 +911,45 @@ mod tests { assert_eq!(outcome, FileHashOutcome::Cancelled); } + + #[test] + fn zero_pads_crc_outputs_to_fixed_hex_widths() { + let opts = HashOptions { + crc1: true, + crc8: true, + crc16: true, + crc24: true, + crc32: true, + ..Default::default() + }; + let empty = hash_bytes(b"", &opts); + fn find<'a>(results: &'a [HashResult], kind: &str) -> &'a str { + results + .iter() + .find(|r| r.hash_type == kind) + .map(|r| r.hash.as_str()) + .unwrap() + } + + assert_eq!(find(&empty, "CRC1"), "00"); + assert_eq!(find(&empty, "CRC8"), "00"); + assert_eq!(find(&empty, "CRC16"), "0000"); + assert_eq!(find(&empty, "CRC24"), "b704ce"); + assert_eq!(find(&empty, "CRC32"), "00000000"); + + let single_zero = hash_bytes(&[0x05], &opts); + assert_eq!(find(&single_zero, "CRC1"), "05"); + assert_eq!(find(&single_zero, "CRC8").len(), 2); + assert_eq!(find(&single_zero, "CRC16").len(), 4); + assert_eq!(find(&single_zero, "CRC24").len(), 6); + assert_eq!(find(&single_zero, "CRC32").len(), 8); + } + + #[test] + fn rejects_directory_path_cleanly() { + let dir = std::env::temp_dir(); + let cancel = AtomicBool::new(false); + let err = hash_file_with_progress(&dir, &all_options(), &cancel, |_| {}).unwrap_err(); + assert!(err.contains("directory")); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b977fee..18323bc 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -31,12 +31,24 @@ fn escape_html(input: &str) -> String { escaped } +fn escape_csv_field(input: &str) -> String { + if input.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", input.replace('"', "\"\"")) + } else { + input.to_string() + } +} + fn serialize_hashes(format: &str, hashes: &[HashResult]) -> Result { match format { "csv" => { let mut csv_content = String::new(); for item in hashes { - csv_content.push_str(&format!("{},{}\n", item.hash_type, item.hash)); + csv_content.push_str(&format!( + "{},{}\n", + escape_csv_field(&item.hash_type), + escape_csv_field(&item.hash) + )); } Ok(csv_content) } @@ -111,13 +123,12 @@ async fn calculate_file_hash( } let task_cancel = Arc::clone(&cancel_flag); - let result = tokio::task::spawn_blocking(move || { + let join_result = tokio::task::spawn_blocking(move || { hash_file_with_progress(&PathBuf::from(file_path), &options, &task_cancel, |p| { let _ = on_progress.send(p); }) }) - .await - .map_err(|err| format!("Hash task failed: {err}"))?; + .await; if let Ok(mut guard) = cancel_state.0.lock() && guard @@ -127,7 +138,7 @@ async fn calculate_file_hash( *guard = None; } - result + join_result.map_err(|err| format!("Hash task failed: {err}"))? } #[tauri::command] @@ -174,10 +185,16 @@ fn open_help_documentation(app: tauri::AppHandle) -> Result<(), String> { .ok() .filter(|path| path.is_file()); - let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/help.pdf"); + #[cfg(debug_assertions)] + let help_path = resource_path.or_else(|| { + let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/help.pdf"); + dev_path.is_file().then_some(dev_path) + }); + + #[cfg(not(debug_assertions))] + let help_path = resource_path; - let help_path = resource_path - .or_else(|| dev_path.is_file().then_some(dev_path)) + let help_path = help_path .ok_or_else(|| "Help documentation file (docs/help.pdf) could not be found".to_string())?; app.opener() @@ -230,6 +247,8 @@ mod tests { ); assert_eq!(escape_html(""), "<a&"'>"); + assert_eq!(escape_csv_field("MD5"), "MD5"); + assert_eq!(escape_csv_field("a,b\"c\nd"), "\"a,b\"\"c\nd\""); assert!(serialize_hashes("xml", &sample).is_err()); } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index b4ebbda..9d26476 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -15,12 +15,14 @@ "title": "DeadHash", "width": 960, "height": 560, + "minWidth": 640, + "minHeight": 420, "decorations": true, "dragDropEnabled": true } ], "security": { - "csp": null + "csp": "default-src 'self'; connect-src 'self' https://api.codedead.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; object-src 'none'; base-uri 'self'" } }, "bundle": { diff --git a/src/App.jsx b/src/App.jsx index 43d4fb4..4d7c6f9 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,13 +1,14 @@ -import { Suspense, lazy, useEffect, useState } from 'react'; +import { Suspense, lazy, useEffect, useRef, useState } from 'react'; import { BrowserRouter, Route, Routes } from 'react-router'; import { AppShell, Center, Loader, MantineProvider } from '@mantine/core'; import { useDisclosure } from '@mantine/hooks'; +import { AlertModal } from './components/AlertModal'; import { AppHeader } from './components/AppHeader'; import { AppNavbar } from './components/AppNavbar'; import { DropZone } from './components/DropZone'; import { UpdateModal } from './components/UpdateModal'; import { checkForAppUpdates } from './services/updater'; -import { useHash } from './state/hashContext'; +import { useHashActions } from './state/hashContext'; import { useSettings } from './state/settingsContext'; const FileHashPage = lazy(() => import('./pages/FileHashPage')); @@ -16,24 +17,31 @@ const SettingsPage = lazy(() => import('./pages/SettingsPage')); const AboutPage = lazy(() => import('./pages/AboutPage')); const App = () => { - const { canDragDrop, autoUpdate, updateChecked, setUpdateChecked } = useSettings(); - const { setFilePath } = useHash(); + const { canDragDrop, autoUpdate, t } = useSettings(); + const { setFilePath } = useHashActions(); + const updateCheckedRef = useRef(false); const [startupUpdate, setStartupUpdate] = useState(null); + const [appError, setAppError] = useState(null); const [navOpened, { toggle: toggleNav, close: closeNav }] = useDisclosure(false); useEffect(() => { - if (!autoUpdate || updateChecked) return; + if (!autoUpdate || updateCheckedRef.current) return undefined; - setUpdateChecked(true); + updateCheckedRef.current = true; + let active = true; checkForAppUpdates() .then((res) => { - if (res?.updateAvailable) setStartupUpdate(res); + if (active && res?.updateAvailable) setStartupUpdate(res); }) .catch(() => { // Silently ignore startup update network errors }); - }, [autoUpdate, updateChecked, setUpdateChecked]); + + return () => { + active = false; + }; + }, [autoUpdate]); return ( @@ -47,10 +55,20 @@ const App = () => { - + - setStartupUpdate(null)} /> + setAppError(null)} + /> + setStartupUpdate(null)} + onError={setAppError} + /> diff --git a/src/components/AppNavbar.jsx b/src/components/AppNavbar.jsx index 18115e2..e9a6c76 100644 --- a/src/components/AppNavbar.jsx +++ b/src/components/AppNavbar.jsx @@ -11,7 +11,7 @@ import { import { openHelpDocumentation } from '../services/tauri'; import { useSettings } from '../state/settingsContext'; -export const AppNavbar = ({ onNavigate }) => { +export const AppNavbar = ({ onNavigate, onError }) => { const { t } = useSettings(); const navigate = useNavigate(); const { pathname } = useLocation(); @@ -27,8 +27,8 @@ export const AppNavbar = ({ onNavigate }) => { const openHelp = () => { onNavigate?.(); - openHelpDocumentation().catch(() => { - // Ignore if no PDF viewer is available + openHelpDocumentation().catch((error) => { + onError?.(String(error)); }); }; diff --git a/src/components/CompareHashInput.jsx b/src/components/CompareHashInput.jsx index af454b4..62c84b0 100644 --- a/src/components/CompareHashInput.jsx +++ b/src/components/CompareHashInput.jsx @@ -1,26 +1,40 @@ +import { useRef } from 'react'; import { Stack, Text, TextInput } from '@mantine/core'; import { useHash } from '../state/hashContext'; import { useSettings } from '../state/settingsContext'; +import { copyFromInputOrValue, readClipboardText } from '../utils/clipboard'; import { analyzeCompareHash } from '../utils/compare'; import { ContextMenuArea } from './ContextMenuArea'; -export const CompareHashInput = ({ value, onChange }) => { +export const CompareHashInput = ({ value, onChange, onError }) => { const { t } = useSettings(); const { algorithms } = useHash(); + const inputRef = useRef(null); - const handlePaste = () => { - navigator.clipboard.readText().then((text) => { - onChange(text); + const handleCopy = () => { + copyFromInputOrValue(inputRef.current, value).catch((error) => { + onError?.(String(error)); }); }; + const handlePaste = () => { + readClipboardText() + .then((text) => { + onChange(text); + }) + .catch((error) => { + onError?.(String(error)); + }); + }; + const analysis = analyzeCompareHash(value, algorithms); const candidateLabels = analysis?.candidates.map((alg) => alg.label).join(', ') ?? ''; return ( - navigator.clipboard.writeText(value)} onPaste={handlePaste}> + onChange(e.currentTarget.value)} diff --git a/src/components/ContextMenuArea.jsx b/src/components/ContextMenuArea.jsx index d7a7631..a654680 100644 --- a/src/components/ContextMenuArea.jsx +++ b/src/components/ContextMenuArea.jsx @@ -3,23 +3,27 @@ import { Box, Menu, Portal } from '@mantine/core'; import { IconClipboard, IconCopy } from '@tabler/icons-react'; import { useSettings } from '../state/settingsContext'; -export const ContextMenuArea = ({ children, onCopy, onPaste }) => { +export const ContextMenuArea = ({ children, onCopy, onPaste, disabled = false }) => { const { t } = useSettings(); const [menuPos, setMenuPos] = useState(null); + const hasActions = !disabled && Boolean(onCopy || onPaste); useEffect(() => { if (!menuPos) return undefined; const close = () => setMenuPos(null); window.addEventListener('click', close); + window.addEventListener('contextmenu', close, true); window.addEventListener('scroll', close, true); return () => { window.removeEventListener('click', close); + window.removeEventListener('contextmenu', close, true); window.removeEventListener('scroll', close, true); }; }, [menuPos]); const handleContextMenu = (event) => { + if (!hasActions) return; event.preventDefault(); setMenuPos({ x: event.clientX, y: event.clientY }); }; @@ -29,7 +33,7 @@ export const ContextMenuArea = ({ children, onCopy, onPaste }) => { {children} - {menuPos ? ( + {hasActions && menuPos ? ( setMenuPos(null)} shadow="md" width={160}> diff --git a/src/components/DropZone.jsx b/src/components/DropZone.jsx index d3418c9..0a8de4e 100644 --- a/src/components/DropZone.jsx +++ b/src/components/DropZone.jsx @@ -45,6 +45,7 @@ export const DropZone = ({ children, onDrop, enabled, reRoute }) => { return () => { active = false; + setDragging(false); unlisten?.(); }; }, [enabled, onDrop, reRoute, navigate]); diff --git a/src/components/ExportButton.jsx b/src/components/ExportButton.jsx index 400a95a..4439ab7 100644 --- a/src/components/ExportButton.jsx +++ b/src/components/ExportButton.jsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useRef, useState } from 'react'; import { Button, Menu } from '@mantine/core'; import { IconBraces, @@ -10,6 +10,7 @@ import { } from '@tabler/icons-react'; import { exportHashes } from '../services/tauri'; import { useSettings } from '../state/settingsContext'; +import { readStoredString, writeStoredValue } from '../state/storage'; import { formatHashesCase } from '../utils/format'; const EXPORT_FORMATS = [ @@ -19,32 +20,47 @@ const EXPORT_FORMATS = [ { id: 'txt', label: 'TXT', icon: IconFileText }, ]; +const VALID_FORMAT_IDS = new Set(EXPORT_FORMATS.map(({ id }) => id)); + +const loadInitialFormat = () => { + const stored = readStoredString('exportFormat', 'csv'); + return VALID_FORMAT_IDS.has(stored) ? stored : 'csv'; +}; + export const ExportButton = ({ hashes, onError }) => { const { t, uppercaseHashes } = useSettings(); - const [format, setFormat] = useState('csv'); + const [format, setFormat] = useState(loadInitialFormat); + const [exporting, setExporting] = useState(false); + const exportingRef = useRef(false); const handleExport = async (targetFormat = format) => { - if (!hashes?.length) return; + if (!hashes?.length || exportingRef.current) return; + exportingRef.current = true; + setExporting(true); try { await exportHashes(targetFormat, formatHashesCase(hashes, uppercaseHashes)); } catch (error) { onError?.(String(error)); + } finally { + exportingRef.current = false; + setExporting(false); } }; const handleSelectFormat = (nextFormat) => { setFormat(nextFormat); + writeStoredValue('exportFormat', nextFormat); handleExport(nextFormat); }; return ( - - diff --git a/src/components/HashResultList.jsx b/src/components/HashResultList.jsx index a8269c2..bed5f03 100644 --- a/src/components/HashResultList.jsx +++ b/src/components/HashResultList.jsx @@ -42,15 +42,23 @@ export const HashResultList = ({ hashes, compareHash, stats }) => { const comparison = evaluateComparison(hashes, compareHash, algorithms); const throughput = stats ? formatThroughput(stats.totalBytes, stats.elapsedMs) : null; - let mismatchDetail = null; + const mismatchDetails = []; if (comparison && !comparison.matched) { if (!comparison.analysis.isValidHex) { - mismatchDetail = t.compareInvalidHex; - } else if (comparison.missingDisabledCandidates.length > 0) { - const disabledLabels = comparison.missingDisabledCandidates - .map((alg) => alg.label) - .join(', '); - mismatchDetail = t.compareDisabledHint.replace('{x}', disabledLabels); + mismatchDetails.push(t.compareInvalidHex); + } else { + if (comparison.missingUncalculatedCandidates.length > 0) { + const uncalculatedLabels = comparison.missingUncalculatedCandidates + .map((alg) => alg.label) + .join(', '); + mismatchDetails.push(t.compareRecalculateHint.replace('{x}', uncalculatedLabels)); + } + if (comparison.missingDisabledCandidates.length > 0) { + const disabledLabels = comparison.missingDisabledCandidates + .map((alg) => alg.label) + .join(', '); + mismatchDetails.push(t.compareDisabledHint.replace('{x}', disabledLabels)); + } } } @@ -115,11 +123,11 @@ export const HashResultList = ({ hashes, compareHash, stats }) => { {t.compareNoMatch} - {mismatchDetail ? ( - - {mismatchDetail} + {mismatchDetails.map((detail) => ( + + {detail} - ) : null} + ))} ) ) : null} diff --git a/src/components/UpdateCheckModals.jsx b/src/components/UpdateCheckModals.jsx index 6ce429d..70eca61 100644 --- a/src/components/UpdateCheckModals.jsx +++ b/src/components/UpdateCheckModals.jsx @@ -2,13 +2,13 @@ import { useSettings } from '../state/settingsContext'; import { AlertModal } from './AlertModal'; import { UpdateModal } from './UpdateModal'; -export const UpdateCheckModals = ({ result, error, onClearResult, onClearError }) => { +export const UpdateCheckModals = ({ result, error, onClearResult, onClearError, onError }) => { const { t } = useSettings(); const isUnsupportedPlatform = Boolean(result && result.platformSupported === false); return ( <> - + { +export const UpdateModal = ({ update, onClose, onError }) => { const { t } = useSettings(); if (!update?.updateAvailable) return null; - const handleDownload = () => { - if (update.downloadUrl) openExternalUrl(update.downloadUrl); + const hasActions = Boolean(update.downloadUrl || update.infoUrl); + + const handleDownload = async () => { + if (update.downloadUrl) { + try { + await openExternalUrl(update.downloadUrl); + } catch (error) { + onError?.(String(error)); + } + } onClose(); }; - const handleInfo = () => { - if (update.infoUrl) openExternalUrl(update.infoUrl); + const handleInfo = async () => { + if (update.infoUrl) { + try { + await openExternalUrl(update.infoUrl); + } catch (error) { + onError?.(String(error)); + } + } }; return ( @@ -22,8 +36,8 @@ export const UpdateModal = ({ update, onClose }) => { {t.newVersion.replace('{x}', update.version)} - {update.infoUrl ? ( - diff --git a/src/pages/FileHashPage.jsx b/src/pages/FileHashPage.jsx index 3a3b1df..22a7925 100644 --- a/src/pages/FileHashPage.jsx +++ b/src/pages/FileHashPage.jsx @@ -23,6 +23,7 @@ import { formatBytes } from '../utils/format'; const FileHashPage = () => { const { t } = useSettings(); const { + hasEnabledAlgorithms, file, setFilePath, setFileComparing, @@ -44,6 +45,7 @@ const FileHashPage = () => { }; const progressPercentage = file.progress?.percentage ?? 0; + const canClear = Boolean(file.path || file.hashes?.length > 0 || file.compareHash); return ( <> @@ -62,10 +64,12 @@ const FileHashPage = () => { + ) : null} {file.hashes?.length > 0 ? ( <> - ) : null} - diff --git a/src/pages/SettingsPage.jsx b/src/pages/SettingsPage.jsx index bb7b794..407a2a0 100644 --- a/src/pages/SettingsPage.jsx +++ b/src/pages/SettingsPage.jsx @@ -53,7 +53,8 @@ const SettingsPage = () => { } = useSettings(); const { algorithms, setAlgorithmEnabled, resetAlgorithms } = useHash(); const { colorScheme, setColorScheme } = useMantineColorScheme(); - const { loading, result, error, checkUpdates, clearResult, clearError } = useUpdateCheck(); + const { loading, result, error, checkUpdates, clearResult, clearError, setError } = + useUpdateCheck(); const [confirmOpen, setConfirmOpen] = useState(false); const handleResetAll = () => { @@ -71,6 +72,7 @@ const SettingsPage = () => { error={error} onClearResult={clearResult} onClearError={clearError} + onError={setError} /> diff --git a/src/pages/TextHashPage.jsx b/src/pages/TextHashPage.jsx index 3c19c8d..f000ea6 100644 --- a/src/pages/TextHashPage.jsx +++ b/src/pages/TextHashPage.jsx @@ -1,4 +1,15 @@ -import { Button, Card, Checkbox, Container, Group, Loader, Stack, Textarea } from '@mantine/core'; +import { useRef } from 'react'; +import { + Button, + Card, + Checkbox, + Container, + Group, + Loader, + Stack, + Text, + Textarea, +} from '@mantine/core'; import { AlertModal } from '../components/AlertModal'; import { CompareHashInput } from '../components/CompareHashInput'; import { ContextMenuArea } from '../components/ContextMenuArea'; @@ -7,10 +18,12 @@ import { HashResultList } from '../components/HashResultList'; import { PageHeader } from '../components/PageHeader'; import { useHash } from '../state/hashContext'; import { useSettings } from '../state/settingsContext'; +import { copyFromInputOrValue, mergePastedText, readClipboardText } from '../utils/clipboard'; const TextHashPage = () => { const { t } = useSettings(); const { + hasEnabledAlgorithms, text, setTextInput, setTextComparing, @@ -19,13 +32,27 @@ const TextHashPage = () => { clearText, runTextCalculation, } = useHash(); + const textareaRef = useRef(null); - const handlePasteText = () => { - navigator.clipboard.readText().then((clipboardText) => { - setTextInput(clipboardText); + const handleCopyText = () => { + copyFromInputOrValue(textareaRef.current, text.input).catch((error) => { + setTextError(String(error)); }); }; + const handlePasteText = () => { + if (text.loading) return; + readClipboardText() + .then((clipboardText) => { + setTextInput(mergePastedText(textareaRef.current, text.input, clipboardText)); + }) + .catch((error) => { + setTextError(String(error)); + }); + }; + + const canClear = Boolean(text.input || text.hashes?.length > 0 || text.compareHash); + return ( <> @@ -41,10 +68,12 @@ const TextHashPage = () => { navigator.clipboard.writeText(text.input)} - onPaste={handlePasteText} + onCopy={handleCopyText} + onPaste={text.loading ? undefined : handlePasteText} >