From c660443613734e9476683e36a9b97038773695a0 Mon Sep 17 00:00:00 2001 From: lijunjie Date: Tue, 24 Nov 2026 17:34:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=BC=E8=88=AA=E5=90=88=E5=B9=B6=EF=BC=9A?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E6=B8=85=E7=90=86/=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E7=BB=B4=E6=8A=A4=E6=94=B9=E4=B8=89=E9=A1=B5=E7=AD=BE=20hub?= =?UTF-8?q?=EF=BC=8C=E5=AD=98=E5=82=A8=E7=A9=BA=E9=97=B4=E6=95=B4=E9=A1=B5?= =?UTF-8?q?=E7=A7=BB=E9=99=A4=EF=BC=9B=E5=B0=8F=E5=B7=A5=E5=85=B7=E6=94=B9?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE=E5=AE=88=E6=8A=A4=E5=BF=83=E8=B7=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 方案①:空间清理 = 垃圾清理 / 重复文件 / 大文件 三页签(页签带实时计数徽标,面板保活切换不丢状态;懒扫描:进入哪个页签才扫哪个) - 方案②:系统维护 = 一键修复 / 隐私清理 / 系统优化 三页签;隐私、优化从桌面组并入,桌面组只剩桌面小工具 - 一级目录「存储空间」整页删除(用户判定与大文件重叠):StoragePage/useStorageWorkspace/Treemap 组件移除,概览快速卡片改跳「大文件」页签;后端 storage_* 命令暂保留(前端已无调用方) - 快捷键重排:1概览 2空间清理 3应用卸载 4权限管理 5系统维护 6实时监控 7小工具 8历史 9设置,0小工具开关 - 方案③(小组件居中问题的对因修复):上一版只监听主屏分辨率变化,但 RDP 接入→本机断会话→回本机登录全程分辨率不变,Windows 会话重连时按旧几何重摆窗口没人察觉;心跳改为每秒比对「实际位置 vs 应在位置」,不一致即归位并压回桌面层,拖动中 3.5 秒宽限不与手打架 - demo 点击测试重写为 hub 场景 26 项全过(含页签徽标、面板保活、内联确认、隐私锁定、恢复默认) - 修 squid-tui 稀疏文件测试的宿主环境 flake:断言从「全屏无 TB」改为「不出现 1.0 TB/1 TiB/1024 GB」(本机 6TB NAS 盘会在磁盘面板合法显示 TB) --- Cargo.toml | 2 +- crates/squid-tui/src/views.rs | 6 +- package.json | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/widget.rs | 78 +++-- src-tauri/tauri.conf.json | 2 +- src/App.tsx | 86 ++--- src/components/Treemap.tsx | 144 -------- src/hooks/useStorageWorkspace.ts | 112 ------ src/pages/DuplicateFilesPage.tsx | 35 +- src/pages/LargeFilesPage.tsx | 39 ++- src/pages/MaintenanceHubPage.tsx | 69 ++++ src/pages/MaintenancePage.tsx | 31 +- src/pages/OptimizationPage.tsx | 56 ++- src/pages/OverviewPage.tsx | 12 +- src/pages/PrivacyPage.tsx | 33 +- src/pages/SpaceHubPage.tsx | 95 +++++ src/pages/SpacePage.tsx | 44 ++- src/pages/StoragePage.tsx | 571 ------------------------------- src/styles.css | 56 +++ src/types.ts | 5 - 21 files changed, 504 insertions(+), 976 deletions(-) delete mode 100644 src/components/Treemap.tsx delete mode 100644 src/hooks/useStorageWorkspace.ts create mode 100644 src/pages/MaintenanceHubPage.tsx create mode 100644 src/pages/SpaceHubPage.tsx delete mode 100644 src/pages/StoragePage.tsx diff --git a/Cargo.toml b/Cargo.toml index 1d87007..4b419db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] exclude = ["src-tauri"] [workspace.package] -version = "0.1.11" +version = "0.1.12" edition = "2021" rust-version = "1.80" license = "GPL-3.0-only" diff --git a/crates/squid-tui/src/views.rs b/crates/squid-tui/src/views.rs index 61e7409..6dd3a60 100644 --- a/crates/squid-tui/src/views.rs +++ b/crates/squid-tui/src/views.rs @@ -2378,8 +2378,12 @@ mod tests { screen.contains("12.0 GB"), "the row and the header should both read 12.0 GB:\n{screen}" ); + // The bug this guards: the 1 TiB logical size leaking into the row + // or the header. Assert the file's *own* inflated numbers are gone — + // never "no TB anywhere": the host's real volumes (6 TB NAS drives) + // legitimately print TB in the disk panel and made this flaky. assert!( - !screen.contains("TB"), + !screen.contains("1.0 TB") && !screen.contains("1 TiB") && !screen.contains("1024 GB"), "a sparse file must not inflate the total past the physical disk:\n{screen}" ); } diff --git a/package.json b/package.json index 4b81493..951c63e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "squid-desktop", "private": true, - "version": "0.1.11", + "version": "0.1.12", "type": "module", "scripts": { "dev": "vite --port 1420 --strictPort", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index af552f3..1244686 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "squid-desktop" -version = "0.1.11" +version = "0.1.12" description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor." authors = ["squid contributors"] edition = "2021" diff --git a/src-tauri/src/widget.rs b/src-tauri/src/widget.rs index b9311e4..a894966 100644 --- a/src-tauri/src/widget.rs +++ b/src-tauri/src/widget.rs @@ -125,19 +125,30 @@ pub fn lower_window(app: &AppHandle) { } } -/// Win+D proof, Pulsar-style heartbeat: if the shell put the wanted widget -/// away, bring it back within a beat and repaint it once (the transparent -/// webview can stay blank after a cloak round-trip). +/// Desktop residency (Windows): heartbeat that both counters Win+D and +/// guards the docked position. +/// +/// Two jobs, one loop: +/// 1. If the shell put the widget away (Win+D / 显示桌面), bring it back +/// within a beat and repaint once (as before). +/// 2. Position guard: compare the window's actual position with where the +/// prefs say it belongs (docked corner, or the remembered drag point). +/// Any mismatch re-docks and re-parks the widget. This catches *every* +/// way the window can end up mid-desktop: an RDP peer connecting +/// disconnects the console session and Windows re-lays-out top-level +/// windows on the next local unlock, a resolution switch, or another +/// program nudging it. The previous fix only watched the monitor size — +/// an RDP round-trip keeps the console resolution constant, so the +/// re-layout went unnoticed. A grace window suppresses re-docking while +/// the user is dragging (position still moving between ticks; the drag +/// persists `position` through widget_set, after which the expected spot +/// *is* the new location, so the guard never fights the pointer). #[cfg(windows)] pub fn spawn_desktop_watch(app: &AppHandle) { let app = app.clone(); std::thread::spawn(move || { - // Last desktop size the widget was parked against. An RDP logon - // rebuilds the console display device and Windows repositions - // top-level windows by that older, smaller geometry; when the native - // resolution returns the widget lands mid-desktop instead of its - // corner. Tracking the size re-docks it on every such shift. - let mut last_screen: Option<(u32, u32)> = None; + let mut last_pos: Option<(i32, i32)> = None; + let mut grace = std::time::Instant::now(); loop { std::thread::sleep(std::time::Duration::from_millis(1_500)); let Some(state) = app.try_state::() else { @@ -161,22 +172,24 @@ pub fn spawn_desktop_watch(app: &AppHandle) { }; let Ok(hwnd) = window.hwnd() else { continue }; let raw: *mut std::ffi::c_void = hwnd.0.cast(); - let screen = window - .primary_monitor() - .ok() - .flatten() - .map(|m| (m.size().width, m.size().height)); - if screen.is_some() && screen != last_screen { - let first = last_screen.is_some(); - last_screen = screen; - // The very first observation only records the baseline; after - // that every change (RDP in, RDP out, hot-plug, resolution - // switch) re-docks and re-parks the widget. - if first { - place_window(&app, &prefs); - desktop_layer::lower(raw); + // ── position guard ──────────────────────────────────────────── + let position = window.outer_position().ok().map(|p| (p.x, p.y)); + if let Some(pos) = position { + if last_pos != Some(pos) { + // The window just moved: someone (the user, most likely) + // is working on it. Re-check shortly instead of yanking + // it mid-drag; the loop's cadence doubles as the grace. + last_pos = Some(pos); + grace = std::time::Instant::now() + std::time::Duration::from_millis(3_500); + } else if std::time::Instant::now() >= grace { + let settled = is_settled(&window, &prefs); + if !settled { + place_window(&app, &prefs); + desktop_layer::lower(raw); + } } } + // ── Win+D recovery ──────────────────────────────────────────── let mut took_down = false; if !desktop_layer::shell_hidden(raw, &mut took_down) { continue; @@ -196,6 +209,25 @@ pub fn spawn_desktop_watch(app: &AppHandle) { }); } +/// Whether the widget currently sits where the prefs say it belongs +/// (tolerating a couple of pixels of DPI rounding). False when the geometry +/// cannot be queried — a failed query re-docks rather than strands. +#[cfg(windows)] +fn is_settled(window: &tauri::WebviewWindow, prefs: &WidgetPrefs) -> bool { + let Ok(Some(monitor)) = window.primary_monitor() else { + return false; + }; + let Ok(pos) = window.outer_position() else { + return false; + }; + let outer = window + .outer_size() + .map(|s| (s.width as i32, s.height as i32)) + .unwrap_or((350, 620)); + let want = dock_position((monitor.size().width, monitor.size().height), outer, prefs); + (pos.x - want.0).abs() <= 2 && (pos.y - want.1).abs() <= 2 +} + #[cfg(not(windows))] pub fn spawn_desktop_watch(_app: &AppHandle) {} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 4d40c28..b052d5a 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Squid", - "version": "0.1.11", + "version": "0.1.12", "identifier": "app.nex.squid", "mainBinaryName": "squid-desktop", "build": { diff --git a/src/App.tsx b/src/App.tsx index ec1d761..dff1b71 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,19 +1,14 @@ import { AppWindow, - Boxes, ChevronDown, CircleGauge, - CopyX, Eraser, - EyeOff, - FileArchive, History, LayoutDashboard, MonitorSmartphone, RefreshCw, Settings, ShieldCheck, - SlidersHorizontal, Sparkles, Wrench, } from "lucide-react"; @@ -37,17 +32,12 @@ import { useToast } from "./components/ui"; import { SetupPanel } from "./components/SetupPanel"; import appIconUrl from "../src-tauri/icons/128x128.png"; import { ApplicationsPage } from "./pages/ApplicationsPage"; -import { DuplicateFilesPage } from "./pages/DuplicateFilesPage"; import { HistoryPage } from "./pages/HistoryPage"; -import { LargeFilesPage } from "./pages/LargeFilesPage"; -import { MaintenancePage } from "./pages/MaintenancePage"; -import { OptimizationPage } from "./pages/OptimizationPage"; +import { MaintenanceHubPage, type MaintTab } from "./pages/MaintenanceHubPage"; import { OverviewPage } from "./pages/OverviewPage"; import { PermissionsPage } from "./pages/PermissionsPage"; -import { PrivacyPage } from "./pages/PrivacyPage"; import { SettingsPage } from "./pages/SettingsPage"; -import { SpacePage } from "./pages/SpacePage"; -import { StoragePage } from "./pages/StoragePage"; +import { SpaceHubPage, type SpaceTab } from "./pages/SpaceHubPage"; import { SystemPage } from "./pages/SystemPage"; import { WidgetPage } from "./pages/WidgetPage"; @@ -101,24 +91,6 @@ const NAV_GROUPS: { labelEn: "Insights", labelZh: "洞察", items: [ - { - id: "storage", - labelEn: "Storage", - labelZh: "存储空间", - icon: Boxes, - }, - { - id: "duplicates", - labelEn: "Duplicate files", - labelZh: "重复文件", - icon: CopyX, - }, - { - id: "large-files", - labelEn: "Large files", - labelZh: "大文件", - icon: FileArchive, - }, { id: "system", labelEn: "Real-time monitor", @@ -137,18 +109,6 @@ const NAV_GROUPS: { labelZh: "桌面小工具", icon: MonitorSmartphone, }, - { - id: "privacy", - labelEn: "Privacy cleaning", - labelZh: "隐私清理", - icon: EyeOff, - }, - { - id: "optimization", - labelEn: "System optimisation", - labelZh: "系统优化", - icon: SlidersHorizontal, - }, ], }, ]; @@ -159,12 +119,7 @@ const PAGE_TITLES: Record = { applications: ["Uninstall apps", "应用卸载"], permissions: ["Permissions", "权限管理"], widget: ["Desktop widget", "桌面小工具"], - storage: ["Storage", "存储空间"], - duplicates: ["Duplicate files", "重复文件"], - "large-files": ["Large files", "大文件"], maintenance: ["System maintenance", "系统维护"], - privacy: ["Privacy cleaning", "隐私清理"], - optimization: ["System optimisation", "系统优化"], system: ["Real-time monitor", "实时监控"], history: ["History", "历史记录"], settings: ["Settings", "设置"], @@ -238,6 +193,10 @@ export default function App() { const [setupOpen, setSetupOpen] = useState(false); // The 托盘驻留 case: a hidden main window must stop sampling the machine. const [windowVisible, setWindowVisible] = useState(true); + // Hub deep-links: the overview quick-cards and tray can request a specific + // tab; the selection resets on every navigate so a later click re-arms it. + const [spaceTab, setSpaceTab] = useState("junk"); + const [maintTab, setMaintTab] = useState("repair"); // 空间清理 defaults: daily groups pre-checked, opt-in groups untouched. const cleanup = useScanWorkspace("cleanup", spaceDefaults); const purge = useScanWorkspace("purge", spaceDefaults); @@ -275,7 +234,10 @@ export default function App() { let unlisten: (() => void) | null = null; void api .onNavigate((next) => { - if (!cancelled) setPage(next); + if (cancelled) return; + setPage(next); + if (next === "space") setSpaceTab("junk"); + if (next === "maintenance") setMaintTab("repair"); }) .then((stop) => { if (cancelled) stop(); @@ -311,18 +273,20 @@ export default function App() { "applications", "permissions", "maintenance", - "storage", - "duplicates", - "large-files", "system", "widget", "history", "settings", ]; - // Ctrl/Cmd+1..9 map to the first nine pages in order; 0 opens the widget. + // Ctrl/Cmd+1..9 map to the nine pages in order; 0 opens the widget. const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; - const index = event.key === "0" ? 9 : Number(event.key) - 1; + if (event.key === "0") { + event.preventDefault(); + setPage("widget"); + return; + } + const index = Number(event.key) - 1; if (!Number.isInteger(index) || index < 0 || index >= order.length) return; event.preventDefault(); setPage(order[index]); @@ -392,15 +356,20 @@ export default function App() { cleanup={cleanup} purge={purge} onNavigate={setPage} + onOpenSpaceTab={(tab) => { + setSpaceTab(tab); + setPage("space"); + }} /> ) : null} {page === "space" ? ( - setPage("history")} + initialTab={spaceTab} /> ) : null} {page === "applications" ? ( @@ -408,12 +377,9 @@ export default function App() { ) : null} {page === "permissions" ? : null} {page === "widget" ? : null} - {page === "storage" ? : null} - {page === "duplicates" ? : null} - {page === "large-files" ? : null} - {page === "maintenance" ? : null} - {page === "privacy" ? : null} - {page === "optimization" ? : null} + {page === "maintenance" ? ( + + ) : null} {page === "system" ? ( max) max = a; - if (a < min) min = a; - } - const s2 = sum * sum; - const l2 = length * length; - return Math.max((l2 * max) / s2, s2 / (l2 * min)); -} - -function squarify( - items: TreemapItem[], - rect: { x: number; y: number; w: number; h: number }, - total: number, - out: TreemapRect[], -) { - const area = rect.w * rect.h; - if (items.length === 0 || area <= 0 || total <= 0) return; - if (items.length === 1) { - out.push({ ...rect, item: items[0] }); - return; - } - // Greedy squarify: extend a row along the shorter side while the worst - // aspect ratio improves; lay the row down and recurse the remainder. - const shorter = Math.min(rect.w, rect.h); - let row: TreemapItem[] = []; - let rest = items; - for (let i = 0; i < items.length; i += 1) { - const candidate = [...row, items[i]]; - if (row.length === 0 || worst(candidate, shorter, total, area) <= worst(row, shorter, total, area)) { - row = candidate; - rest = items.slice(i + 1); - } else { - break; - } - } - const rowValue = row.reduce((sum, item) => sum + item.value, 0); - if (rowValue <= 0) { - row.forEach((item) => out.push({ ...rect, item })); - return; - } - const thickness = (rowValue / total) * area / shorter; - let offset = 0; - for (const item of row) { - const span = ((item.value / total) * area) / Math.max(thickness, 1e-9); - if (rect.w >= rect.h) { - out.push({ x: rect.x, y: rect.y + offset, w: thickness, h: span, item }); - } else { - out.push({ x: rect.x + offset, y: rect.y, w: span, h: thickness, item }); - } - offset += span; - } - const consumed = (rowValue / total) * area / shorter; - const remainder = - rect.w >= rect.h - ? { x: rect.x + consumed, y: rect.y, w: rect.w - consumed, h: rect.h } - : { x: rect.x, y: rect.y + consumed, w: rect.w, h: rect.h - consumed }; - const restTotal = total - rowValue; - squarify(rest, remainder, restTotal, out); -} - -export function Treemap({ - items, - width, - height, - onSelect, -}: { - items: TreemapItem[]; - width: number; - height: number; - onSelect: (id: string) => void; -}) { - const rects = useMemo(() => { - const sorted = [...items].filter((item) => item.value > 0).sort((a, b) => b.value - a.value); - const total = sorted.reduce((sum, item) => sum + item.value, 0); - const out: TreemapRect[] = []; - squarify(sorted, { x: 0, y: 0, w: width, h: height }, total, out); - return out; - }, [items, width, height]); - - return ( -
- {rects.map((rect) => { - const roomy = rect.w > 84 && rect.h > 42; - const midSized = rect.w > 46 && rect.h > 20; - return ( - - ); - })} -
- ); -} diff --git a/src/hooks/useStorageWorkspace.ts b/src/hooks/useStorageWorkspace.ts deleted file mode 100644 index d7022de..0000000 --- a/src/hooks/useStorageWorkspace.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { useCallback, useRef, useState } from "react"; -import { api, subscribeJobProgress } from "../lib/api"; -import { isCancelled, messageFrom } from "../lib/format"; -import type { ExploreResult, JobProgress, LargestFile, StorageNode } from "../types"; - -function jobId(): string { - return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`; -} - -export interface StorageWorkspace { - node: StorageNode | null; - /** Freshness of the current node (A⑥ size cache). */ - cached: boolean; - measuredAtMs: number | null; - files: LargestFile[]; - progress: JobProgress | null; - exploring: boolean; - scanningFiles: boolean; - error: string | null; - explore: (path?: string | null, force?: boolean) => Promise; - largestFiles: (path: string) => Promise; - cancel: () => Promise; - clearError: () => void; - clearFiles: () => void; -} - -export function useStorageWorkspace(): StorageWorkspace { - const [node, setNode] = useState(null); - const [cached, setCached] = useState(false); - const [measuredAtMs, setMeasuredAtMs] = useState(null); - const [files, setFiles] = useState([]); - const [progress, setProgress] = useState(null); - const [exploring, setExploring] = useState(false); - const [scanningFiles, setScanningFiles] = useState(false); - const [error, setError] = useState(null); - const activeJob = useRef(null); - - const explore = useCallback(async (path?: string | null, force = false) => { - if (exploring || scanningFiles) return; - const id = jobId(); - activeJob.current = id; - setExploring(true); - setError(null); - setProgress(null); - setFiles([]); - const stop = await subscribeJobProgress(id, setProgress); - try { - const next: ExploreResult = await api.storageExplore(id, path ?? null, 1, 16, force); - if (activeJob.current !== id) return; - setNode(next.node); - setCached(next.cached); - setMeasuredAtMs(next.measuredAtMs); - } catch (reason) { - if (!isCancelled(reason)) setError(messageFrom(reason)); - } finally { - stop(); - if (activeJob.current === id) { - setExploring(false); - setProgress(null); - activeJob.current = null; - } - } - }, [exploring, scanningFiles]); - - const largestFiles = useCallback( - async (path: string) => { - if (exploring || scanningFiles) return; - const id = jobId(); - activeJob.current = id; - setScanningFiles(true); - setError(null); - setProgress(null); - setFiles([]); - const stop = await subscribeJobProgress(id, setProgress); - try { - const next = await api.storageLargestFiles(id, path, 40); - if (activeJob.current !== id) return; - setFiles(next); - } catch (reason) { - if (!isCancelled(reason)) setError(messageFrom(reason)); - } finally { - stop(); - if (activeJob.current === id) { - setScanningFiles(false); - setProgress(null); - activeJob.current = null; - } - } - }, - [exploring, scanningFiles], - ); - - const cancel = useCallback(async () => { - if (activeJob.current) await api.cancelJob(activeJob.current).catch(() => false); - }, []); - - return { - node, - cached, - measuredAtMs, - files, - progress, - exploring, - scanningFiles, - error, - explore, - largestFiles, - cancel, - clearError: () => setError(null), - clearFiles: () => setFiles([]), - }; -} diff --git a/src/pages/DuplicateFilesPage.tsx b/src/pages/DuplicateFilesPage.tsx index 1fdfa1b..767ec72 100644 --- a/src/pages/DuplicateFilesPage.tsx +++ b/src/pages/DuplicateFilesPage.tsx @@ -9,7 +9,7 @@ import { Trash2, X, } from "lucide-react"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import * as apiClient from "../lib/api"; import { useI18n } from "../i18n"; @@ -142,7 +142,14 @@ function DupGroupCard({ ); } -export function DuplicateFilesPage() { +export function DuplicateFilesPage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { const { t, lang } = useI18n(); const { push } = useToast(); const workspace = useDuplicatesWorkspace(); @@ -186,15 +193,23 @@ export function DuplicateFilesPage() { // stops counting toward what the page offers to reclaim. const visibleWasted = groups.reduce((sum, g) => sum + g.size * (g.copies.length - 1), 0); + // Hub badge: confirmed groups after ignores, or null before a scan. + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge(groups.length > 0 ? `${groups.length} 组 · ${formatBytes(visibleWasted)}` : null); + }, [embedded, groups.length, onBadge, visibleWasted]); + return ( -
- +
+ {embedded ? null : ( + + )} {workspace.error ? : null}
diff --git a/src/pages/LargeFilesPage.tsx b/src/pages/LargeFilesPage.tsx index 15609bb..097a37a 100644 --- a/src/pages/LargeFilesPage.tsx +++ b/src/pages/LargeFilesPage.tsx @@ -10,7 +10,7 @@ import { ShieldAlert, Trash2, } from "lucide-react"; -import { useCallback, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import * as apiClient from "../lib/api"; import { subscribeJobProgress } from "../lib/api"; import { useI18n } from "../i18n"; @@ -51,7 +51,14 @@ const CLASS_ICON: Record = { /** 休眠判定沿用清理页口径:180 天无修改即值得标记。 */ const DORMANT_SECS = 180 * 86_400; -export function LargeFilesPage() { +export function LargeFilesPage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { const { t, lang } = useI18n(); const { push } = useToast(); const [files, setFiles] = useState(null); @@ -113,6 +120,16 @@ export function LargeFilesPage() { .reduce((sum, file) => sum + file.size, 0) ?? 0; const pickedCount = picked.size; + // Hub badge: found files, or null before a scan. + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge( + visible && visible.length > 0 + ? `${formatCount(visible.length)} 个 · ${formatBytes(totalBytes)}` + : null, + ); + }, [embedded, onBadge, totalBytes, visible]); + const toggle = (path: string) => { setPicked((current) => { const next = new Set(current); @@ -146,14 +163,16 @@ export function LargeFilesPage() { const now = Date.now(); return ( -
- +
+ {embedded ? null : ( + + )} {error ? setError(null)} /> : null}
diff --git a/src/pages/MaintenanceHubPage.tsx b/src/pages/MaintenanceHubPage.tsx new file mode 100644 index 0000000..0e68c47 --- /dev/null +++ b/src/pages/MaintenanceHubPage.tsx @@ -0,0 +1,69 @@ +import { EyeOff, SlidersHorizontal, Wrench } from "lucide-react"; +import { useEffect, useState } from "react"; +import { useI18n } from "../i18n"; +import { PageHeader } from "../components/ui"; +import { MaintenancePage } from "./MaintenancePage"; +import { PrivacyPage } from "./PrivacyPage"; +import { OptimizationPage } from "./OptimizationPage"; + +/* 系统维护 hub(方案②):一键修复 / 隐私清理 / 系统优化 三页签。 + * 面板全部保持挂载(display 切换),修复任务运行中切页签不会打断 + * 日志流;徽标由面板回报(隐私=痕迹数、优化=已更改数)。 */ + +export type MaintTab = "repair" | "privacy" | "optimize"; + +const TABS: { id: MaintTab; icon: typeof Wrench; en: string; zh: string }[] = [ + { id: "repair", icon: Wrench, en: "One-click repairs", zh: "一键修复" }, + { id: "privacy", icon: EyeOff, en: "Privacy cleaning", zh: "隐私清理" }, + { id: "optimize", icon: SlidersHorizontal, en: "System optimisation", zh: "系统优化" }, +]; + +export function MaintenanceHubPage({ initialTab = "repair" }: { initialTab?: MaintTab }) { + const { t } = useI18n(); + const [tab, setTab] = useState(initialTab); + useEffect(() => setTab(initialTab), [initialTab]); + const [badges, setBadges] = useState>>({}); + const report = (id: MaintTab) => (value: string | null) => + setBadges((current) => (current[id] === value ? current : { ...current, [id]: value })); + + return ( +
+ +
+ {TABS.map((item) => { + const Icon = item.icon; + const badge = badges[item.id]; + return ( + + ); + })} +
+
+ +
+
+ +
+
+ +
+
+ ); +} diff --git a/src/pages/MaintenancePage.tsx b/src/pages/MaintenancePage.tsx index a659c28..75d1110 100644 --- a/src/pages/MaintenancePage.tsx +++ b/src/pages/MaintenancePage.tsx @@ -27,7 +27,14 @@ const RISK_CHIP: Record = { slow: ["is-slow", "较慢", "Slow"], }; -export function MaintenancePage() { +export function MaintenancePage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 系统维护 hub: page title hides, task count flows up. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { const { t, lang } = useI18n(); const { push } = useToast(); const [tasks, setTasks] = useState([]); @@ -38,6 +45,10 @@ export function MaintenancePage() { const [error, setError] = useState(null); const job = useRef(null); + useEffect(() => { + if (embedded && onBadge) onBadge(tasks.length > 0 ? `${tasks.length} 项` : null); + }, [embedded, onBadge, tasks.length]); + useEffect(() => { let alive = true; void api @@ -96,14 +107,16 @@ export function MaintenancePage() { ); return ( -
- +
+ {embedded ? null : ( + + )} {error ? setError(null)} /> : null}
diff --git a/src/pages/OptimizationPage.tsx b/src/pages/OptimizationPage.tsx index 32f18b2..8c93080 100644 --- a/src/pages/OptimizationPage.tsx +++ b/src/pages/OptimizationPage.tsx @@ -6,7 +6,14 @@ import { messageFrom } from "../lib/format"; import { Button, InlineError, PageHeader, Toggle, useToast } from "../components/ui"; import type { TweakState } from "../types"; -export function OptimizationPage() { +export function OptimizationPage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 系统维护 hub: page title hides, changed count flows up. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { const { t, lang } = useI18n(); const { push } = useToast(); const [states, setStates] = useState([]); @@ -40,6 +47,12 @@ export function OptimizationPage() { const changed = states.filter((state) => state.recorded).length; + // Hub badge: how many tweaks have been flipped so far (null when none). + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge(changed > 0 ? `已更改 ${changed} 项` : null); + }, [changed, embedded, onBadge]); + const restoreAll = async () => { setBusy("__all__"); try { @@ -59,19 +72,21 @@ export function OptimizationPage() { }; return ( -
- } disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}> - {t("Restore all defaults", "恢复全部默认")} - - } - /> +
+ {embedded ? null : ( + } disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}> + {t("Restore all defaults", "恢复全部默认")} + + } + /> + )} {error ? setError(null)} /> : null}
@@ -84,6 +99,19 @@ export function OptimizationPage() { ? t(`${changed} changed · revertable`, `已更改 ${changed} 项 · 可随时恢复`) : t("Nothing changed yet", "尚未更改任何项")} + {/* Embedded (维护 hub): the page header — and with it the restore + button — is hidden, so the group head carries it instead. */} + {embedded ? ( + + ) : null}
    {states.map((state) => ( diff --git a/src/pages/OverviewPage.tsx b/src/pages/OverviewPage.tsx index 7b9dd45..e2bebb5 100644 --- a/src/pages/OverviewPage.tsx +++ b/src/pages/OverviewPage.tsx @@ -73,12 +73,15 @@ export function OverviewPage({ cleanup, purge, onNavigate, + onOpenSpaceTab, }: { bootstrap: Bootstrap; snapshot: SystemSnapshot | null; cleanup: ScanWorkspace; purge: ScanWorkspace; onNavigate: (page: PageId) => void; + /** Deep-link into a 空间清理 hub tab (重复文件 / 大文件). */ + onOpenSpaceTab?: (tab: "junk" | "dups" | "big") => void; }) { const { t, lang } = useI18n(); const volumes = snapshot?.volumes ?? []; @@ -437,12 +440,15 @@ export function OverviewPage({ - + ); + })} +
+
+ +
+
+ +
+
+ +
+
+ ); +} diff --git a/src/pages/SpacePage.tsx b/src/pages/SpacePage.tsx index 3bf98b3..3d824b9 100644 --- a/src/pages/SpacePage.tsx +++ b/src/pages/SpacePage.tsx @@ -454,12 +454,17 @@ export function SpacePage({ bootstrap, deleteMode, onHistory, + embedded = false, + onBadge, }: { cleanup: ScanWorkspace; purge: ScanWorkspace; bootstrap: Bootstrap; deleteMode: DeleteMode; onHistory: () => void; + /** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; }) { const { t, lang, bin } = useI18n(); const { push } = useToast(); @@ -508,6 +513,21 @@ export function SpacePage({ // Default checking is seeded at scan time by the workspaces' selection // policy (App.tsx spaceDefaults): daily groups on, opt-in groups off. + // Hub badge: live count/size of the scan result, or null before one lands. + useEffect(() => { + if (!embedded || !onBadge) return; + const items = (cleanup.result?.items.length ?? 0) + (purge.result?.items.length ?? 0); + if (items === 0) { + onBadge(null); + return; + } + let total = 0; + for (const source of [cleanup, purge]) { + for (const item of source.result?.items ?? []) total += item.onDisk; + } + onBadge(`${t(`${formatCount(items)} items`, `${formatCount(items)} 项`)} · ${formatBytes(total)}`); + }, [cleanup.result, embedded, onBadge, purge.result, t]); + const entries = useMemo(() => { const all: Entry[] = []; for (const source of [cleanup, purge]) { @@ -1003,7 +1023,21 @@ export function SpacePage({ } return ( -
+
+ {embedded ? ( +
+ +
+ ) : (
{t("Space cleaning", "空间清理")}
@@ -1028,6 +1062,7 @@ export function SpacePage({ : t("Start scan", "开始扫描")}
+ )}
@@ -1137,6 +1172,13 @@ export function SpacePage({ "尚未扫描。点击「开始扫描」,Squid 会检查已知缓存位置,并自动发现本机各处的项目构建目录。", )} + {/* Embedded: the head button is hidden inside the hub, so the + empty stage carries its own entry point. */} + {embedded ? ( + + ) : null}
) : null} diff --git a/src/pages/StoragePage.tsx b/src/pages/StoragePage.tsx deleted file mode 100644 index 83a4560..0000000 --- a/src/pages/StoragePage.tsx +++ /dev/null @@ -1,571 +0,0 @@ -import { - ArrowLeft, - ChevronRight, - Copy, - ExternalLink, - FileArchive, - FolderOpen, - FolderSearch, - HardDrive, - Lightbulb, - LoaderCircle, - RefreshCw, - ScanSearch, - TimerReset, -} from "lucide-react"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { open } from "@tauri-apps/plugin-dialog"; -import * as apiClient from "../lib/api"; -import { useI18n } from "../i18n"; -import { - agoLabel, - basename, - formatBytes, - formatCount, - percent, - shortPath, -} from "../lib/format"; -import type { Bootstrap, SpaceInsight, StorageNode } from "../types"; -import { useStorageWorkspace } from "../hooks/useStorageWorkspace"; -import { Treemap, type TreemapItem } from "../components/Treemap"; -import { - Button, - InlineError, - PageHeader, - ProgressCard, - SectionTitle, - useToast, -} from "../components/ui"; - -const BAR_TONES = ["blue", "violet", "cyan", "teal", "orange", "pink", "indigo", "slate"]; - -function nodeSize(node: { allocated: number; logical: number }): number { - return node.allocated || node.logical; -} - -function parentDirectory(path: string): string | null { - const normalized = path.replace(/[\\/]+$/, ""); - const index = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\")); - if (index <= 0) return null; - if (/^[A-Za-z]:[\\/]/.test(normalized) && index === 2) { - return `${normalized.slice(0, 2)}\\`; - } - return normalized.slice(0, index); -} - -export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { - const { t, lang } = useI18n(); - const { push } = useToast(); - const workspace = useStorageWorkspace(); - const [pathInput, setPathInput] = useState(""); - const [manualPath, setManualPath] = useState(false); - const [insights, setInsights] = useState(null); - // D4: list ⇄ squarified treemap over the same measured tree (no re-scan). - const [view, setView] = useState<"list" | "map">("list"); - const [mapWidth, setMapWidth] = useState(860); - const mapRef = useRef(null); - useEffect(() => { - if (view !== "map" || !mapRef.current) return; - const node = mapRef.current; - const measure = () => setMapWidth(Math.max(node.clientWidth, 320)); - measure(); - const observer = new ResizeObserver(measure); - observer.observe(node); - return () => observer.disconnect(); - }, [view]); - - // A⑤: hidden space hogs measured quietly once per page visit. - useEffect(() => { - let alive = true; - void apiClient.api - .storageInsights() - .then((rows) => { - if (alive) setInsights(rows); - }) - .catch(() => { - if (alive) setInsights([]); - }); - return () => { - alive = false; - }; - }, []); - - useEffect(() => { - if (workspace.node && !manualPath) setPathInput(workspace.node.path); - }, [manualPath, workspace.node]); - - const children = useMemo( - () => - workspace.node - ? [...workspace.node.children].sort((a, b) => nodeSize(b) - nodeSize(a)) - : [], - [workspace.node], - ); - const nodeTotal = workspace.node - ? Math.max(nodeSize(workspace.node), 1) - : 1; - const visibleShare = children.reduce((sum, child) => sum + nodeSize(child), 0); - const rest = percent(visibleShare, nodeTotal); - - // Treemap wants flat weighted cells, biggest-tone-darkest. - const treemapItems: TreemapItem[] = useMemo(() => { - if (!workspace.node || children.length === 0) return []; - const biggest = Math.max(nodeSize(children[0]), 1); - const cells: TreemapItem[] = children.map((child, index) => ({ - id: String(index), - label: basename(child.path), - value: nodeSize(child), - tone: Math.min(1, Math.sqrt(nodeSize(child) / biggest)), - })); - if (workspace.node.folded > 0 && nodeSize(workspace.node) - visibleShare > 0) { - cells.push({ - id: "rest", - label: t("Other folders", "其他文件夹"), - value: nodeSize(workspace.node) - visibleShare, - tone: 0.08, - }); - } - return cells; - }, [children, t, visibleShare, workspace.node]); - - const explore = (path?: string | null) => { - setManualPath(false); - void workspace.explore(path); - }; - - const chooseFolder = async () => { - const chosen = await open({ - directory: true, - multiple: false, - title: t("Choose a folder to analyse", "选择要分析的文件夹"), - }); - if (typeof chosen === "string") explore(chosen); - }; - - const reveal = (path: string) => { - void apiClient.api.revealPath(path).catch(() => undefined); - }; - - const drill = (node: StorageNode) => { - if (!node.isDir || node.path === workspace.node?.path) return; - explore(node.path); - }; - - const copyCommand = async (command: string) => { - try { - await navigator.clipboard.writeText(command); - push(t("Command copied to the clipboard", "命令已复制到剪贴板"), "success"); - } catch { - push(t(`Copy failed: ${command}`, `复制失败:${command}`), "danger"); - } - }; - - const parent = workspace.node ? parentDirectory(workspace.node.path) : null; - - return ( -
- - {parent ? ( - - ) : null} - - - } - /> - -
- - - - { - setPathInput(event.target.value); - setManualPath(true); - }} - onKeyDown={(event) => { - if (event.key === "Enter" && pathInput.trim()) explore(pathInput.trim()); - }} - spellCheck={false} - aria-label={t("Folder path", "文件夹路径")} - /> - -
- - {workspace.error ? ( - - ) : null} - - {workspace.exploring ? ( - void workspace.cancel()} - /> - ) : null} - - {workspace.node && !workspace.exploring ? ( - <> -
-
-
- {t("Current folder", "当前文件夹")} -

{shortPath(workspace.node.path, 72)}

-
-
- {formatBytes(nodeSize(workspace.node))} - - {t( - `${formatCount(workspace.node.files)} files · ${formatCount( - workspace.node.dirs, - )} folders`, - `${formatCount(workspace.node.files)} 个文件 · ${formatCount( - workspace.node.dirs, - )} 个文件夹`, - )} - -
-
- - {workspace.cached ? ( -
- - - {t( - `Instant open · cached measurement${ - workspace.measuredAtMs - ? ` · taken ${agoLabel(workspace.measuredAtMs, lang)}` - : "" - }`, - `秒开 · 缓存数据${ - workspace.measuredAtMs - ? ` · 上次测量 ${agoLabel(workspace.measuredAtMs, lang)}` - : "" - }`, - )} - - -
- ) : null} - - {children.length > 0 ? ( - <> -
- - - - {t("Sunburst coming later", "旭日图(后期)")} - -
-
- {children.map((child, index) => ( - - ))} - -
- {workspace.node.folded > 0 ? ( -

- {t( - `${workspace.node.folded} smaller folders (${formatBytes( - workspace.node.foldedSize, - )}) are folded into the remainder.`, - `${workspace.node.folded} 个较小文件夹(${formatBytes( - workspace.node.foldedSize, - )})已合并显示。`, - )} -

- ) : null} - - {view === "map" ? ( -
- { - const child = children.find((_, index) => String(index) === id); - if (child?.isDir) drill(child); - }} - /> -

- {t( - "Click a block to drill into that folder (shares the same measurement cache; nothing re-scans). Darker = bigger share.", - "点击矩形 = 下钻该目录(与列表共用同一份测量缓存,不重新扫描);颜色越深占比越大。", - )} -

-
- ) : ( -
- {children.map((child, index) => { - const share = percent(nodeSize(child), nodeTotal); - return ( - - ); - })} - {rest < 100 ? ( -
- - - - - - {t("Other folders", "其他文件夹")} - {t("Not among the largest entries", "不在最大项目之列")} - - - - {formatBytes(Math.max(0, nodeSize(workspace.node) - visibleShare))} - - {(100 - rest).toFixed(1)}% - -
- ) : null} -
- )} - - ) : ( -
- - {t("This folder has no measurable children.", "此文件夹没有可测量的子项。")} -
- )} -
- -
- - ) : ( - - ) - } - onClick={() => - workspace.files.length > 0 - ? workspace.clearFiles() - : void workspace.largestFiles(workspace.node!.path) - } - disabled={workspace.exploring || workspace.scanningFiles} - > - {workspace.files.length > 0 - ? t("Hide", "隐藏") - : t("Find large files", "查找大文件")} - - } - /> - {workspace.scanningFiles ? ( - void workspace.cancel()} - /> - ) : null} - {workspace.files.length > 0 ? ( -
- {workspace.files.map((file, index) => ( -
- {String(index + 1).padStart(2, "0")} - - - - - {basename(file.path)} - {shortPath(file.path, 76)} - - - {formatBytes(file.allocated || file.logical)} - - -
- ))} -
- ) : null} -
- - ) : null} - - {insights && insights.length > 0 ? ( -
- -
- {insights.map((insight) => ( -
- - - - - {insight.title} - {shortPath(insight.path, 68)} - {insight.hint} - - - {insight.size > 0 ? formatBytes(insight.size) : "—"} - - - {insight.path ? ( - - ) : null} - {insight.action === "cleanable" ? ( - - ) : null} - {insight.action === "command" && insight.command ? ( - - ) : null} - -
- ))} -
-
- ) : null} - - {!workspace.node && !workspace.exploring ? ( - - ) : null} -
- ); -} - -function BoxesIcon() { - return ( - - ); -} diff --git a/src/styles.css b/src/styles.css index 7f078eb..2bbd101 100644 --- a/src/styles.css +++ b/src/styles.css @@ -8054,3 +8054,59 @@ html.widget-mode body { font-size: var(--nex-text-3xs); white-space: nowrap; } + +/* ── Hub pages(空间清理/系统维护 三页签容器,方案①②)────────────── */ + +.hub-page .hub-tabs { + display: flex; + gap: 8px; + margin: 18px 0 4px; +} + +.hub-tab { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 18px; + border: 1px solid var(--nex-line); + border-radius: 12px; + background: transparent; + color: var(--nex-muted); + font-size: var(--nex-text-sm); + cursor: pointer; + transition: all 0.16s ease; +} + +.hub-tab b { + padding: 1px 8px; + border-radius: 999px; + background: var(--nex-cream); + color: var(--nex-muted); + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-semibold); +} + +.hub-tab.is-active { + border-color: color-mix(in oklab, var(--nex-accent) 35%, transparent); + background: color-mix(in oklab, var(--nex-accent) 8%, #fff); + color: #2b2620; + font-weight: var(--nex-weight-semibold); +} + +.hub-tab.is-active b { + background: color-mix(in oklab, var(--nex-accent) 14%, #fff); + color: var(--nex-accent); +} + +/* Embedded panels keep their DOM alive (display toggle) so scans, picks + and running repairs survive tab switches; the nesting padding collapses. */ +.hub-pane > .page.is-embedded { + padding: 0; +} + +.space-embedded-head { + display: flex; + justify-content: flex-end; + gap: 10px; + margin-top: 14px; +} diff --git a/src/types.ts b/src/types.ts index 7835a81..b59e8fe 100644 --- a/src/types.ts +++ b/src/types.ts @@ -5,13 +5,8 @@ export type PageId = | "applications" | "permissions" | "widget" - | "storage" - | "duplicates" - | "large-files" | "system" | "maintenance" - | "privacy" - | "optimization" | "history" | "settings";