导航合并:空间清理/系统维护改三页签 hub,存储空间整页移除;小工具改位置守护心跳

- 方案①:空间清理 = 垃圾清理 / 重复文件 / 大文件 三页签(页签带实时计数徽标,面板保活切换不丢状态;懒扫描:进入哪个页签才扫哪个)
- 方案②:系统维护 = 一键修复 / 隐私清理 / 系统优化 三页签;隐私、优化从桌面组并入,桌面组只剩桌面小工具
- 一级目录「存储空间」整页删除(用户判定与大文件重叠):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)
dev
lijunjie 2026-11-24 17:34:00 +08:00
parent 79b2e1df49
commit c660443613
21 changed files with 504 additions and 976 deletions

View File

@ -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"

View File

@ -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}"
);
}

View File

@ -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",

View File

@ -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"

View File

@ -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::<WidgetState>() 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) {}

View File

@ -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": {

View File

@ -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<PageId, [string, string]> = {
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<SpaceTab>("junk");
const [maintTab, setMaintTab] = useState<MaintTab>("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" ? (
<SpacePage
<SpaceHubPage
cleanup={cleanup}
purge={purge}
bootstrap={bootstrap}
deleteMode={deleteMode}
onHistory={() => setPage("history")}
initialTab={spaceTab}
/>
) : null}
{page === "applications" ? (
@ -408,12 +377,9 @@ export default function App() {
) : null}
{page === "permissions" ? <PermissionsPage workspace={permissions} /> : null}
{page === "widget" ? <WidgetPage /> : null}
{page === "storage" ? <StoragePage bootstrap={bootstrap} /> : null}
{page === "duplicates" ? <DuplicateFilesPage /> : null}
{page === "large-files" ? <LargeFilesPage /> : null}
{page === "maintenance" ? <MaintenancePage /> : null}
{page === "privacy" ? <PrivacyPage /> : null}
{page === "optimization" ? <OptimizationPage /> : null}
{page === "maintenance" ? (
<MaintenanceHubPage initialTab={maintTab} />
) : null}
{page === "system" ? (
<SystemPage
snapshot={system.snapshot}

View File

@ -1,144 +0,0 @@
import { useMemo } from "react";
import { formatBytes } from "../lib/format";
/** Squarified treemap (Bruls et al.) over the storage tree's children.
* ~100 lines, no dependency: the layout works on the measured node list the
* storage page already has, so switching views costs nothing. */
export interface TreemapItem {
label: string;
value: number;
/** Fill intensity 0..1 — darker means larger share. */
tone: number;
id: string;
}
export interface TreemapRect {
x: number;
y: number;
w: number;
h: number;
item: TreemapItem;
}
function worst(row: TreemapItem[], length: number, total: number, area: number): number {
// Normalise row values to the same scale as the rectangle area.
let sum = 0;
let max = 0;
let min = Number.POSITIVE_INFINITY;
for (const item of row) {
const a = (item.value / total) * area;
sum += a;
if (a > 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 (
<div className="treemap" style={{ width, height }}>
{rects.map((rect) => {
const roomy = rect.w > 84 && rect.h > 42;
const midSized = rect.w > 46 && rect.h > 20;
return (
<button
key={rect.item.id}
type="button"
className="treemap-cell"
style={{
left: rect.x,
top: rect.y,
width: Math.max(rect.w - 2, 0),
height: Math.max(rect.h - 2, 0),
background: `color-mix(in oklab, var(--nex-accent, #e05f21) ${Math.round(28 + rect.item.tone * 68)}%, #f6e8d2)`,
color: rect.item.tone > 0.55 ? "#fff" : "var(--ink)",
}}
title={`${rect.item.label} · ${formatBytes(rect.item.value)}`}
onClick={() => onSelect(rect.item.id)}
>
{roomy ? (
<span className="treemap-label">
<b>{rect.item.label}</b>
<small>{formatBytes(rect.item.value)}</small>
</span>
) : midSized ? (
<span className="treemap-label is-tiny">{rect.item.label}</span>
) : null}
</button>
);
})}
</div>
);
}

View File

@ -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<void>;
largestFiles: (path: string) => Promise<void>;
cancel: () => Promise<void>;
clearError: () => void;
clearFiles: () => void;
}
export function useStorageWorkspace(): StorageWorkspace {
const [node, setNode] = useState<StorageNode | null>(null);
const [cached, setCached] = useState(false);
const [measuredAtMs, setMeasuredAtMs] = useState<number | null>(null);
const [files, setFiles] = useState<LargestFile[]>([]);
const [progress, setProgress] = useState<JobProgress | null>(null);
const [exploring, setExploring] = useState(false);
const [scanningFiles, setScanningFiles] = useState(false);
const [error, setError] = useState<string | null>(null);
const activeJob = useRef<string | null>(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([]),
};
}

View File

@ -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 (
<div className="page dup-page">
<PageHeader
title={t("Duplicate files", "重复文件")}
description={t(
"Byte-identical copies proven by a three-stage hash funnel. Deletions land in the Recycle Bin.",
"大小分组 → 头中尾采样 → 全量校验,三级漏斗逐字节确认。删除全部走回收站,可撤销。",
)}
/>
<div className={`page dup-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("Duplicate files", "重复文件")}
description={t(
"Byte-identical copies proven by a three-stage hash funnel. Deletions land in the Recycle Bin.",
"大小分组 → 头中尾采样 → 全量校验,三级漏斗逐字节确认。删除全部走回收站,可撤销。",
)}
/>
)}
{workspace.error ? <InlineError message={workspace.error} onDismiss={workspace.clearError} /> : null}
<section className="dup-config">

View File

@ -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<LargeFile["class"], typeof HardDrive> = {
/** 休眠判定沿用清理页口径: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<LargeFile[] | null>(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 (
<div className="page bigfiles-page">
<PageHeader
title={t("Large files", "大文件")}
description={t(
"Everything heavy across your drives, with dormancy and lock hints before anything goes to the Recycle Bin.",
"全盘范围的大文件清单,附休眠与占用提示;删除同样进回收站、可撤销。",
)}
/>
<div className={`page bigfiles-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("Large files", "大文件")}
description={t(
"Everything heavy across your drives, with dormancy and lock hints before anything goes to the Recycle Bin.",
"全盘范围的大文件清单,附休眠与占用提示;删除同样进回收站、可撤销。",
)}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<section className="bigfiles-config">

View File

@ -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<MaintTab>(initialTab);
useEffect(() => setTab(initialTab), [initialTab]);
const [badges, setBadges] = useState<Partial<Record<MaintTab, string | null>>>({});
const report = (id: MaintTab) => (value: string | null) =>
setBadges((current) => (current[id] === value ? current : { ...current, [id]: value }));
return (
<div className="page hub-page">
<PageHeader
title={t("System maintenance", "系统维护")}
description={t(
"Fix everyday complaints, wipe privacy traces, flip reversible tweaks — every step auditable or revertable.",
"修小毛病、清隐私痕迹、开可逆优化开关——每一步都可回退、可审计。",
)}
/>
<div className="hub-tabs" role="tablist">
{TABS.map((item) => {
const Icon = item.icon;
const badge = badges[item.id];
return (
<button
key={item.id}
type="button"
role="tab"
aria-selected={tab === item.id}
className={`hub-tab ${tab === item.id ? "is-active" : ""}`}
onClick={() => setTab(item.id)}
>
<Icon size={15} />
{t(item.en, item.zh)}
{badge ? <b>{badge}</b> : null}
</button>
);
})}
</div>
<div className="hub-pane" style={{ display: tab === "repair" ? undefined : "none" }}>
<MaintenancePage embedded onBadge={report("repair")} />
</div>
<div className="hub-pane" style={{ display: tab === "privacy" ? undefined : "none" }}>
<PrivacyPage embedded onBadge={report("privacy")} />
</div>
<div className="hub-pane" style={{ display: tab === "optimize" ? undefined : "none" }}>
<OptimizationPage embedded onBadge={report("optimize")} />
</div>
</div>
);
}

View File

@ -27,7 +27,14 @@ const RISK_CHIP: Record<MaintenanceTask["risk"], [string, string, string]> = {
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<MaintenanceTask[]>([]);
@ -38,6 +45,10 @@ export function MaintenancePage() {
const [error, setError] = useState<string | null>(null);
const job = useRef<string | null>(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 (
<div className="page maintenance-page">
<PageHeader
title={t("System maintenance", "系统维护")}
description={t(
"One-click repairs for the everyday complaints. Every command comes from a fixed whitelist — nothing here accepts free-form input.",
"常见故障一键修复。所有命令来自固定白名单,可显示原始输出;同类任务互斥执行。",
)}
/>
<div className={`page maintenance-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("System maintenance", "系统维护")}
description={t(
"One-click repairs for the everyday complaints. Every command comes from a fixed whitelist — nothing here accepts free-form input.",
"常见故障一键修复。所有命令来自固定白名单,可显示原始输出;同类任务互斥执行。",
)}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<div className="maint-summary">

View File

@ -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<TweakState[]>([]);
@ -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 (
<div className="page optimize-page">
<PageHeader
title={t("System optimisation", "系统优化")}
description={t(
"A small, curated set of reversible switches. The first write records the system's original value; one button puts every change back.",
"少而稳的可逆开关目录。首次修改前记录系统原值,顶部一键「恢复全部默认」。每一项都先在真机验证后才会上架。",
)}
actions={
<Button variant="secondary" icon={<RotateCcw size={14} />} disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}>
{t("Restore all defaults", "恢复全部默认")}
</Button>
}
/>
<div className={`page optimize-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("System optimisation", "系统优化")}
description={t(
"A small, curated set of reversible switches. The first write records the system's original value; one button puts every change back.",
"少而稳的可逆开关目录。首次修改前记录系统原值,顶部一键「恢复全部默认」。每一项都先在真机验证后才会上架。",
)}
actions={
<Button variant="secondary" icon={<RotateCcw size={14} />} disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}>
{t("Restore all defaults", "恢复全部默认")}
</Button>
}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<section className="optimize-group">
@ -84,6 +99,19 @@ export function OptimizationPage() {
? t(`${changed} changed · revertable`, `已更改 ${changed} 项 · 可随时恢复`)
: t("Nothing changed yet", "尚未更改任何项")}
</span>
{/* Embedded (维护 hub): the page header — and with it the restore
button — is hidden, so the group head carries it instead. */}
{embedded ? (
<Button
variant="ghost"
size="sm"
icon={<RotateCcw size={13} />}
disabled={busy !== null || changed === 0}
onClick={() => void restoreAll()}
>
{t("Restore all defaults", "恢复全部默认")}
</Button>
) : null}
</div>
<ul className="optimize-list">
{states.map((state) => (

View File

@ -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({
</span>
<ChevronRight size={17} />
</button>
<button className="quick-card tone-indigo" onClick={() => onNavigate("storage")}>
<button
className="quick-card tone-indigo"
onClick={() => onOpenSpaceTab?.("big")}
>
<span className="quick-icon">
<Boxes size={22} />
<HardDrive size={22} />
</span>
<span className="quick-copy">
<strong>{t("Explore storage", "浏览存储空间")}</strong>
<strong>{t("Large files", "大文件")}</strong>
<small>{t("See what is taking up space", "查看空间都被什么占用")}</small>
</span>
<ChevronRight size={17} />

View File

@ -41,7 +41,14 @@ interface SpecGroup {
locked: string | null;
}
export function PrivacyPage() {
export function PrivacyPage({
embedded = false,
onBadge,
}: {
/** Rendered inside 系统维护 hub: page title hides, trace count flows up. */
embedded?: boolean;
onBadge?: (value: string | null) => void;
} = {}) {
const { t, lang } = useI18n();
const { push } = useToast();
const [items, setItems] = useState<CleanupItem[]>([]);
@ -109,6 +116,12 @@ export function PrivacyPage() {
const pickedBytes = [...picked].reduce((sum, index) => sum + (items[index]?.onDisk ?? 0), 0);
// Hub badge: trace groups found by the auto-scan, or null when clean.
useEffect(() => {
if (!embedded || !onBadge) return;
onBadge(groups.length > 0 ? `${groups.length} 类痕迹` : null);
}, [embedded, groups.length, onBadge]);
const clean = async () => {
if (!scanId || picked.size === 0) return;
setCleaning(true);
@ -129,14 +142,16 @@ export function PrivacyPage() {
};
return (
<div className="page privacy-page">
<PageHeader
title={t("Privacy cleaning", "隐私清理")}
description={t(
"History and traces leave the machine for good — this page never uses the Recycle Bin, but every run is written to History.",
"历史与痕迹「删了就回不来」:本页删除不进回收站(浏览器 profile 半恢复反而更糟),但同样逐条写入历史记录审计。",
)}
/>
<div className={`page privacy-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("Privacy cleaning", "隐私清理")}
description={t(
"History and traces leave the machine for good — this page never uses the Recycle Bin, but every run is written to History.",
"历史与痕迹「删了就回不来」:本页删除不进回收站(浏览器 profile 半恢复反而更糟),但同样逐条写入历史记录审计。",
)}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<section className="privacy-grid">

View File

@ -0,0 +1,95 @@
import { CopyX, Eraser, FileArchive } from "lucide-react";
import { useEffect, useState } from "react";
import { useI18n } from "../i18n";
import { PageHeader } from "../components/ui";
import { SpacePage } from "./SpacePage";
import { DuplicateFilesPage } from "./DuplicateFilesPage";
import { LargeFilesPage } from "./LargeFilesPage";
import type { Bootstrap, DeleteMode } from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
/* 空间清理 hub(方案①):垃圾清理 / 重复文件 / 大文件 三页签。
* 三个面板全部保持挂载(display 切换),扫描结果与勾选状态在切页签
* 时不丢失;每个面板自己决定何时扫描(懒扫描),页签徽标由面板回报。 */
export type SpaceTab = "junk" | "dups" | "big";
const TABS: { id: SpaceTab; icon: typeof Eraser; en: string; zh: string }[] = [
{ id: "junk", icon: Eraser, en: "Junk cleaning", zh: "垃圾清理" },
{ id: "dups", icon: CopyX, en: "Duplicate files", zh: "重复文件" },
{ id: "big", icon: FileArchive, en: "Large files", zh: "大文件" },
];
export function SpaceHubPage({
cleanup,
purge,
bootstrap,
deleteMode,
onHistory,
initialTab = "junk",
}: {
cleanup: ScanWorkspace;
purge: ScanWorkspace;
bootstrap: Bootstrap;
deleteMode: DeleteMode;
onHistory: () => void;
/** Deep-link from the overview quick cards (重复文件 / 大文件). */
initialTab?: SpaceTab;
}) {
const { t } = useI18n();
const [tab, setTab] = useState<SpaceTab>(initialTab);
// A fresh deep-link wins over the last manually chosen tab.
useEffect(() => setTab(initialTab), [initialTab]);
const [badges, setBadges] = useState<Partial<Record<SpaceTab, string | null>>>({});
const report = (id: SpaceTab) => (value: string | null) =>
setBadges((current) => (current[id] === value ? current : { ...current, [id]: value }));
return (
<div className="page hub-page">
<PageHeader
title={t("Space cleaning", "空间清理")}
description={t(
"Junk, duplicates, heavyweights — three views of the same disk. Everything deleted lands in the Recycle Bin, undoable.",
"垃圾、重复、大块头——三个视角看清同一块磁盘,删除都走回收站、可撤销。",
)}
/>
<div className="hub-tabs" role="tablist">
{TABS.map((item) => {
const Icon = item.icon;
const badge = badges[item.id];
return (
<button
key={item.id}
type="button"
role="tab"
aria-selected={tab === item.id}
className={`hub-tab ${tab === item.id ? "is-active" : ""}`}
onClick={() => setTab(item.id)}
>
<Icon size={15} />
{t(item.en, item.zh)}
{badge ? <b>{badge}</b> : null}
</button>
);
})}
</div>
<div className="hub-pane" style={{ display: tab === "junk" ? undefined : "none" }}>
<SpacePage
embedded
onBadge={report("junk")}
cleanup={cleanup}
purge={purge}
bootstrap={bootstrap}
deleteMode={deleteMode}
onHistory={onHistory}
/>
</div>
<div className="hub-pane" style={{ display: tab === "dups" ? undefined : "none" }}>
<DuplicateFilesPage embedded onBadge={report("dups")} />
</div>
<div className="hub-pane" style={{ display: tab === "big" ? undefined : "none" }}>
<LargeFilesPage embedded onBadge={report("big")} />
</div>
</div>
);
}

View File

@ -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<Entry[]>(() => {
const all: Entry[] = [];
for (const source of [cleanup, purge]) {
@ -1003,7 +1023,21 @@ export function SpacePage({
}
return (
<div className="page">
<div className={`page ${embedded ? "is-embedded" : ""}`}>
{embedded ? (
<div className="space-embedded-head">
<Button
variant={cleanup.result || purge.result ? "secondary" : "primary"}
icon={<ScanSearch size={15} />}
onClick={() => void runScan()}
disabled={scanning || deleting}
>
{cleanup.result || purge.result
? t("Rescan", "重新扫描")
: t("Start scan", "开始扫描")}
</Button>
</div>
) : (
<div className="space-head">
<div>
<div className="eyebrow">{t("Space cleaning", "空间清理")}</div>
@ -1028,6 +1062,7 @@ export function SpacePage({
: t("Start scan", "开始扫描")}
</Button>
</div>
)}
<div className="space-config">
<span className="space-config-label">
@ -1137,6 +1172,13 @@ export function SpacePage({
"尚未扫描。点击「开始扫描」,Squid 会检查已知缓存位置,并自动发现本机各处的项目构建目录。",
)}
</span>
{/* Embedded: the head button is hidden inside the hub, so the
empty stage carries its own entry point. */}
{embedded ? (
<Button variant="primary" icon={<ScanSearch size={15} />} onClick={() => void runScan()}>
{t("Start scan", "开始扫描")}
</Button>
) : null}
</div>
) : null}

View File

@ -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<SpaceInsight[] | null>(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<HTMLDivElement | null>(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 (
<div className="page storage-page">
<PageHeader
eyebrow={t("Storage", "存储空间")}
title={t("See space clearly.", "看清每一寸空间。")}
description={t(
"Drill into folders, find the heavyweight files, and open anything in Finder.",
"逐层查看文件夹,找到占用最大的文件,并直接在访达中打开。",
)}
actions={
<>
{parent ? (
<Button variant="ghost" icon={<ArrowLeft size={15} />} onClick={() => explore(parent)}>
{t("Up", "上一级")}
</Button>
) : null}
<Button variant="secondary" icon={<FolderOpen size={15} />} onClick={() => void chooseFolder()}>
{t("Choose folder", "选择文件夹")}
</Button>
</>
}
/>
<div className="storage-pathbar">
<span className="pathbar-icon">
<HardDrive size={17} />
</span>
<input
value={pathInput}
onChange={(event) => {
setPathInput(event.target.value);
setManualPath(true);
}}
onKeyDown={(event) => {
if (event.key === "Enter" && pathInput.trim()) explore(pathInput.trim());
}}
spellCheck={false}
aria-label={t("Folder path", "文件夹路径")}
/>
<Button
variant="primary"
size="sm"
icon={<ScanSearch size={14} />}
onClick={() => explore(pathInput.trim() || null)}
disabled={workspace.exploring || workspace.scanningFiles}
>
{t("Analyse", "分析")}
</Button>
</div>
{workspace.error ? (
<InlineError message={workspace.error} onDismiss={workspace.clearError} />
) : null}
{workspace.exploring ? (
<ProgressCard
progress={workspace.progress}
title={t("Measuring folders…", "正在测量文件夹…")}
onCancel={() => void workspace.cancel()}
/>
) : null}
{workspace.node && !workspace.exploring ? (
<>
<section className="storage-overview">
<div className="storage-overview-head">
<div>
<span className="field-label">{t("Current folder", "当前文件夹")}</span>
<h2 title={workspace.node.path}>{shortPath(workspace.node.path, 72)}</h2>
</div>
<div className="storage-total">
<strong>{formatBytes(nodeSize(workspace.node))}</strong>
<span>
{t(
`${formatCount(workspace.node.files)} files · ${formatCount(
workspace.node.dirs,
)} folders`,
`${formatCount(workspace.node.files)} 个文件 · ${formatCount(
workspace.node.dirs,
)} 个文件夹`,
)}
</span>
</div>
</div>
{workspace.cached ? (
<div className="storage-fresh">
<TimerReset size={13} />
<span>
{t(
`Instant open · cached measurement${
workspace.measuredAtMs
? ` · taken ${agoLabel(workspace.measuredAtMs, lang)}`
: ""
}`,
`秒开 · 缓存数据${
workspace.measuredAtMs
? ` · 上次测量 ${agoLabel(workspace.measuredAtMs, lang)}`
: ""
}`,
)}
</span>
<button
type="button"
onClick={() => void workspace.explore(workspace.node?.path, true)}
>
{t("Re-measure", "重新测量")}
</button>
</div>
) : null}
{children.length > 0 ? (
<>
<div className="storage-viewseg" role="group">
<button
type="button"
className={view === "list" ? "is-active" : ""}
onClick={() => setView("list")}
>
{t("List", "列表")}
</button>
<button
type="button"
className={view === "map" ? "is-active" : ""}
onClick={() => setView("map")}
>
{t("Treemap", "矩形图")}
</button>
<span className="storage-viewseg-note">
{t("Sunburst coming later", "旭日图(后期)")}
</span>
</div>
<div className="storage-map" aria-label={t("Folder distribution", "文件夹占比")}>
{children.map((child, index) => (
<span
key={`${child.path}-${index}`}
className={`tone-${BAR_TONES[index % BAR_TONES.length]}`}
style={{ width: `${percent(nodeSize(child), nodeTotal)}%` }}
title={`${basename(child.path)} · ${formatBytes(nodeSize(child))}`}
/>
))}
<span className="storage-map-rest" />
</div>
{workspace.node.folded > 0 ? (
<p className="storage-folded">
{t(
`${workspace.node.folded} smaller folders (${formatBytes(
workspace.node.foldedSize,
)}) are folded into the remainder.`,
`${workspace.node.folded} 个较小文件夹(${formatBytes(
workspace.node.foldedSize,
)})已合并显示。`,
)}
</p>
) : null}
{view === "map" ? (
<div className="storage-treemap" ref={mapRef}>
<Treemap
width={mapWidth}
height={360}
items={treemapItems}
onSelect={(id) => {
const child = children.find((_, index) => String(index) === id);
if (child?.isDir) drill(child);
}}
/>
<p className="storage-treemap-hint">
{t(
"Click a block to drill into that folder (shares the same measurement cache; nothing re-scans). Darker = bigger share.",
"点击矩形 = 下钻该目录(与列表共用同一份测量缓存,不重新扫描);颜色越深占比越大。",
)}
</p>
</div>
) : (
<div className="storage-children">
{children.map((child, index) => {
const share = percent(nodeSize(child), nodeTotal);
return (
<button
key={`${child.path}-${index}`}
className={`storage-child ${
child.isDir && child.path !== workspace.node?.path
? "is-navigable"
: ""
}`}
onClick={() => drill(child)}
>
<span className={`storage-child-dot tone-${BAR_TONES[index % BAR_TONES.length]}`} />
<span className="storage-child-icon">
{child.isDir ? <FolderOpen size={19} /> : <FileArchive size={19} />}
</span>
<span className="storage-child-copy">
<strong>{basename(child.path)}</strong>
<small title={child.path}>
{shortPath(child.path, 62)}
{!child.readable ? ` · ${t("partially unreadable", "部分不可读")}` : ""}
</small>
<span className="storage-mini-track">
<span
className={`tone-${BAR_TONES[index % BAR_TONES.length]}`}
style={{ width: `${share}%` }}
/>
</span>
</span>
<span className="storage-child-size">
<strong>{formatBytes(nodeSize(child))}</strong>
<small>{share.toFixed(1)}%</small>
</span>
<span className="storage-child-actions">
<span
role="button"
tabIndex={0}
className="row-reveal"
title={t("Show in Finder", "在访达中显示")}
onClick={(event) => {
event.stopPropagation();
reveal(child.path);
}}
onKeyDown={(event) => {
if (event.key === "Enter") reveal(child.path);
}}
>
<ExternalLink size={14} />
</span>
{child.isDir && child.path !== workspace.node?.path ? (
<ChevronRight size={15} />
) : null}
</span>
</button>
);
})}
{rest < 100 ? (
<div className="storage-child is-muted">
<span className="storage-child-dot" />
<span className="storage-child-icon">
<BoxesIcon />
</span>
<span className="storage-child-copy">
<strong>{t("Other folders", "其他文件夹")}</strong>
<small>{t("Not among the largest entries", "不在最大项目之列")}</small>
</span>
<span className="storage-child-size">
<strong>
{formatBytes(Math.max(0, nodeSize(workspace.node) - visibleShare))}
</strong>
<small>{(100 - rest).toFixed(1)}%</small>
</span>
</div>
) : null}
</div>
)}
</>
) : (
<div className="empty-inline">
<FolderSearch size={21} />
<span>{t("This folder has no measurable children.", "此文件夹没有可测量的子项。")}</span>
</div>
)}
</section>
<section className="storage-large">
<SectionTitle
title={t("Largest files", "最大文件")}
subtitle={t(
"Files over 1 MB in the current folder, largest first.",
"当前文件夹中大于 1 MB 的文件,按大小排序。",
)}
action={
<Button
variant="secondary"
size="sm"
icon={
workspace.scanningFiles ? (
<LoaderCircle size={14} className="spin" />
) : (
<ScanSearch size={14} />
)
}
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", "查找大文件")}
</Button>
}
/>
{workspace.scanningFiles ? (
<ProgressCard
progress={workspace.progress}
title={t("Searching for the largest files…", "正在查找最大文件…")}
compact
onCancel={() => void workspace.cancel()}
/>
) : null}
{workspace.files.length > 0 ? (
<div className="large-file-list">
{workspace.files.map((file, index) => (
<div className="large-file-row" key={`${file.path}-${index}`}>
<span className="large-file-rank">{String(index + 1).padStart(2, "0")}</span>
<span className="large-file-icon">
<FileArchive size={16} />
</span>
<span className="large-file-copy">
<strong>{basename(file.path)}</strong>
<small title={file.path}>{shortPath(file.path, 76)}</small>
</span>
<span className="large-file-size">
{formatBytes(file.allocated || file.logical)}
</span>
<button className="row-reveal" onClick={() => reveal(file.path)}>
<ExternalLink size={14} />
</button>
</div>
))}
</div>
) : null}
</section>
</>
) : null}
{insights && insights.length > 0 ? (
<section className="storage-insights">
<SectionTitle
title={t("Hidden space hogs", "隐藏的吃空间大户")}
subtitle={t(
"Things a folder scan never shows you — measured just now.",
"文件夹扫描永远看不到的占用 — 刚刚测量过。",
)}
/>
<div className="storage-insight-list">
{insights.map((insight) => (
<div className="storage-insight" key={insight.id}>
<span className="storage-insight-icon">
<Lightbulb size={16} />
</span>
<span className="storage-insight-copy">
<strong>{insight.title}</strong>
<small title={insight.path}>{shortPath(insight.path, 68)}</small>
<small className="storage-insight-hint">{insight.hint}</small>
</span>
<span className="storage-insight-size">
{insight.size > 0 ? formatBytes(insight.size) : "—"}
</span>
<span className="storage-insight-acts">
{insight.path ? (
<button
className="row-reveal"
title={t("Show in Explorer", "在资源管理器中显示")}
onClick={() => reveal(insight.path)}
>
<ExternalLink size={14} />
</button>
) : null}
{insight.action === "cleanable" ? (
<button
type="button"
className="storage-insight-cta"
onClick={() => explore(insight.path)}
>
{t("Inspect", "查看")}
</button>
) : null}
{insight.action === "command" && insight.command ? (
<button
type="button"
className="storage-insight-cta"
title={insight.command}
onClick={() => void copyCommand(insight.command!)}
>
<Copy size={13} />
{t("Copy command", "复制命令")}
</button>
) : null}
</span>
</div>
))}
</div>
</section>
) : null}
{!workspace.node && !workspace.exploring ? (
<button className="storage-start" onClick={() => explore(null)}>
<span>
<RefreshCw size={25} />
</span>
<strong>{t("Start with your home folder", "从用户主目录开始")}</strong>
<small>{bootstrap.settings.purgeRoots[0] || t("Home", "用户主目录")}</small>
</button>
) : null}
</div>
);
}
function BoxesIcon() {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="m12 3 8 4.5v9L12 21l-8-4.5v-9L12 3Z" stroke="currentColor" strokeWidth="1.7" />
<path d="m4.5 7.8 7.5 4.3 7.5-4.3M12 12.1V21" stroke="currentColor" strokeWidth="1.7" />
</svg>
);
}

View File

@ -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;
}

View File

@ -5,13 +5,8 @@ export type PageId =
| "applications"
| "permissions"
| "widget"
| "storage"
| "duplicates"
| "large-files"
| "system"
| "maintenance"
| "privacy"
| "optimization"
| "history"
| "settings";