Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Preserve keyboard focus when paging through scan analyses (#230)

Vishnu Srivatsavac50bed27696d
diff --git a/src/AppUsage.tsx b/src/AppUsage.tsx
index d13a161..5c17f30 100644
--- a/src/AppUsage.tsx
+++ b/src/AppUsage.tsx
@@ -3,12 +3,15 @@ import { getAppUsage } from "./scanIpc";
import type { AppUsageResponse } from "./appUsageSummary";
import type { ScanResponse } from "./scanView";
import { formatBytes } from "./formatBytes";
+import { usePagingFocus } from "./usePagingFocus";
export function AppUsage({ scope, busy }: { scope: ScanResponse; busy: boolean }) {
const { generation, revision, total_size, errors, skipped } = scope;
const [skip, setSkip] = useState(0);
const [retry, setRetry] = useState(0);
- const key = JSON.stringify([generation, revision, total_size, errors, skipped, skip, retry]);
+ const pageKey = (offset: number, attempt: number) =>
+ JSON.stringify([generation, revision, total_size, errors, skipped, offset, attempt]);
+ const key = pageKey(skip, retry);
const [state, setState] = useState<{ key: string; data?: AppUsageResponse; error?: string }>({ key: "" });
useEffect(() => {
let current = true;
@@ -21,16 +24,25 @@ export function AppUsage({ scope, busy }: { scope: ScanResponse; busy: boolean }
}, [generation, revision, total_size, errors, skipped, skip, key]);
const data = state.key === key ? state.data : undefined;
const error = state.key === key ? state.error : undefined;
- return <section aria-label="Package-folder usage" className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
+ const { region, rememberFocus } = usePagingFocus(key, data ? "ready" : error ? "error" : "loading");
+ const goToPage = (offset: number, trigger: HTMLButtonElement) => {
+ rememberFocus(pageKey(offset, retry), trigger);
+ setSkip(offset);
+ };
+ return <section ref={region} aria-label="Package-folder usage" className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
<p className="text-xs text-zinc-400 pt-3">Values cover scanned package folders. Full app totals remain unknown.
Missing and unreadable locations remain unknown.</p>
<p className="text-xs text-zinc-500 py-2">Package IDs come from folder names and may include leftovers from uninstalled apps.</p>
<p className="text-xs text-zinc-500 break-all">Scan root: <span className="font-mono">{scope.root_path}</span></p>
<p className="text-xs text-zinc-500 py-2">{errors.toLocaleString("en-US")} access errors · {skipped.toLocaleString("en-US")} excluded or duplicate entries</p>
- <p role="status" className="text-xs text-zinc-300 py-2">{data
+ <p role="status" data-page-status tabIndex={-1} className="text-xs text-zinc-300 py-2">{data
? `${formatBytes(data.attributed_size)} in package folders · ${formatBytes(data.unattributed_size)} unattributed · ${data.total_packages.toLocaleString("en-US")} package IDs`
: error ? "Package-folder usage unavailable" : "Loading package folders…"}</p>
- {error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button disabled={busy} onClick={() => setRetry(value => value + 1)} className="underline">Retry</button></div>}
+ {error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button data-page-action="retry" disabled={busy}
+ onClick={event => {
+ rememberFocus(pageKey(skip, retry + 1), event.currentTarget);
+ setRetry(retry + 1);
+ }} className="underline">Retry</button></div>}
{data?.total_packages === 0 && <p className="text-sm text-zinc-400 py-4">No package folders were recognized in this scanned scope.</p>}
<table aria-busy={!data && !error} className="w-full text-xs text-left">
<caption className="sr-only">Scanned package-folder bytes, sorted by package ID</caption>
@@ -42,9 +54,11 @@ export function AppUsage({ scope, busy }: { scope: ScanResponse; busy: boolean }
</tr>)}</tbody>
</table>
{data && <div className="flex gap-2 items-center py-3 text-xs">
- <button disabled={busy || skip === 0} onClick={() => setSkip(Math.max(0, skip - 100))} className="rounded bg-zinc-800 px-3 py-2 disabled:opacity-40">Previous</button>
+ <button data-page-action="previous" disabled={busy || skip === 0}
+ onClick={event => goToPage(Math.max(0, skip - 100), event.currentTarget)} className="rounded bg-zinc-800 px-3 py-2 disabled:opacity-40">Previous</button>
<span className="text-zinc-500">{data.packages.length} entries on this page</span>
- <button disabled={busy || data.next_skip === null} onClick={() => { if (data.next_skip !== null) setSkip(data.next_skip); }} className="rounded bg-zinc-800 px-3 py-2 disabled:opacity-40">Next</button>
+ <button data-page-action="next" disabled={busy || data.next_skip === null}
+ onClick={event => { if (data.next_skip !== null) goToPage(data.next_skip, event.currentTarget); }} className="rounded bg-zinc-800 px-3 py-2 disabled:opacity-40">Next</button>
</div>}
</section>;
}
diff --git a/src/SearchFiles.tsx b/src/SearchFiles.tsx
index c383663..dc3cba7 100644
--- a/src/SearchFiles.tsx
+++ b/src/SearchFiles.tsx
@@ -5,6 +5,7 @@ import type { FileType } from "./fileTypeSummary";
import type { SearchFolder, SearchResponse } from "./searchResults";
import type { ScanNode, ScanResponse } from "./scanView";
import { formatBytes } from "./formatBytes";
+import { usePagingFocus } from "./usePagingFocus";
const isSelectableFile = (node: ScanNode) => node.type === "file" && node.counted;
@@ -34,7 +35,9 @@ export function SearchFiles({ scope, folder, category, busy, onZoom, onNuke }: {
const offsets = pagination.scope === pageScope ? pagination.offsets : [0];
const skip = offsets[offsets.length - 1];
const [retry, setRetry] = useState(0);
- const key = JSON.stringify([pageScope, root_path, read_only, total_size, query, skip, retry]);
+ const pageKey = (offset: number, attempt: number) =>
+ JSON.stringify([pageScope, root_path, read_only, total_size, query, offset, attempt]);
+ const key = pageKey(skip, retry);
const [state, setState] = useState<{ key: string; data?: SearchResponse; error?: string }>({ key: "" });
useEffect(() => {
if (!query && !fileType) return;
@@ -49,6 +52,11 @@ export function SearchFiles({ scope, folder, category, busy, onZoom, onNuke }: {
// Hide the previous query/revision/page synchronously, before its effect cleans up.
const data = state.key === key ? state.data : undefined;
const error = state.key === key ? state.error : undefined;
+ const { region, rememberFocus } = usePagingFocus(key, data ? "ready" : error ? "error" : "loading");
+ const goToPage = (nextOffsets: number[], trigger: HTMLButtonElement) => {
+ rememberFocus(pageKey(nextOffsets[nextOffsets.length - 1], retry), trigger);
+ setPagination({ scope: pageScope, offsets: nextOffsets });
+ };
const submit = () => {
if (!input) return;
if (input !== query) setSelection(null);
@@ -81,7 +89,7 @@ export function SearchFiles({ scope, folder, category, busy, onZoom, onNuke }: {
? data ? `Showing ${range} files` : error ? "Files unavailable" : "Loading files…"
: data ? `Showing ${range} matches for “${query}”` : error ? "Search unavailable"
: activeFolder ? "Search names in this folder." : "Search names in the completed scan.";
- return <section aria-label={category ? "Files by type" : "Search"} className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
+ return <section ref={region} aria-label={category ? "Files by type" : "Search"} className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
{category ? <div className="flex items-center gap-3 py-3">
<h2 className="text-sm font-semibold text-zinc-200">{FILE_TYPE_LABELS[category.kind]}</h2>
<button type="button" autoFocus disabled={busy} onClick={category.clear}
@@ -102,7 +110,7 @@ export function SearchFiles({ scope, folder, category, busy, onZoom, onNuke }: {
</div>}
<div className="flex flex-wrap items-center justify-between gap-3 pb-3">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-zinc-400">
- <p role="status" className="break-all">{status}</p>
+ <p role="status" data-page-status tabIndex={-1} className="break-all">{status}</p>
{!category && <span id="search-selection-count" role="status" className={selectedCount ? "text-accent-300" : "sr-only"}>
{selectedCount === 1 ? "1 file selected" : selectedCount > 1 ? `${selectedCount.toLocaleString("en-US")} files selected` : ""}
</span>}
@@ -113,13 +121,19 @@ export function SearchFiles({ scope, folder, category, busy, onZoom, onNuke }: {
className="text-accent-400 hover:underline">Clear selection</button>}
</div>
<div className="flex gap-2 shrink-0 text-xs">
- <button disabled={busy || !data || skip === 0} onClick={() => setPagination({ scope: pageScope, offsets: offsets.slice(0, -1) })}
+ <button data-page-action="previous" disabled={busy || !data || skip === 0}
+ onClick={event => goToPage(offsets.slice(0, -1), event.currentTarget)}
className="text-zinc-300 hover:underline disabled:text-zinc-600">Previous</button>
- <button disabled={busy || !data?.has_more} onClick={() => setPagination({ scope: pageScope, offsets: [...offsets, skip + results.length] })}
+ <button data-page-action="next" disabled={busy || !data?.has_more}
+ onClick={event => goToPage([...offsets, skip + results.length], event.currentTarget)}
className="text-zinc-300 hover:underline disabled:text-zinc-600">Next</button>
</div>
</div>
- {error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button onClick={() => setRetry(value => value + 1)} className="underline">Retry</button></div>}
+ {error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button data-page-action="retry" disabled={busy}
+ onClick={event => {
+ rememberFocus(pageKey(skip, retry + 1), event.currentTarget);
+ setRetry(retry + 1);
+ }} className="underline">Retry</button></div>}
{data && results.length === 0 && <p className="text-sm text-zinc-400 py-4">
{category ? "No files of this type in the scan." : `No matching names in this ${activeFolder ? "folder" : "scan"}.`}
</p>}
diff --git a/src/usePagingFocus.ts b/src/usePagingFocus.ts
new file mode 100644
index 0000000..800f3d4
--- /dev/null
+++ b/src/usePagingFocus.ts
@@ -0,0 +1,52 @@
+import { useLayoutEffect, useRef } from "react";
+
+type PagingState = "loading" | "ready" | "error";
+
+export function usePagingFocus(key: string, state: PagingState) {
+ const region = useRef<HTMLElement>(null);
+ const pending = useRef<{
+ key: string;
+ trigger: HTMLButtonElement;
+ release: () => void;
+ } | null>(null);
+
+ useLayoutEffect(() => () => pending.current?.release(), []);
+ useLayoutEffect(() => {
+ const focus = pending.current;
+ if (!focus) return;
+ if (focus.key !== key || !region.current) {
+ focus.release();
+ return;
+ }
+ if (state === "loading") return;
+ const active = document.activeElement;
+ const container = region.current;
+ focus.release();
+ if (active !== focus.trigger && active !== document.body) return;
+
+ const action = state === "error" ? "retry"
+ : focus.trigger.dataset.pageAction === "previous" ? "previous" : "next";
+ const target = container.querySelector<HTMLElement>(`button[data-page-action="${action}"]:enabled`)
+ ?? container.querySelector<HTMLElement>("button[data-page-action]:enabled")
+ ?? container.querySelector<HTMLElement>("[data-page-status]");
+ target?.focus();
+ });
+
+ const rememberFocus = (nextKey: string, trigger: HTMLButtonElement) => {
+ pending.current?.release();
+ if (document.activeElement !== trigger) return;
+ const release = () => {
+ document.removeEventListener("focusin", leave);
+ pending.current = null;
+ };
+ // The browser may fall back to the document body when the control is
+ // disabled or removed. Any other focus change belongs to the user.
+ const leave = (event: FocusEvent) => {
+ if (event.target !== trigger && event.target !== document.body) release();
+ };
+ document.addEventListener("focusin", leave);
+ pending.current = { key: nextKey, trigger, release };
+ };
+
+ return { region, rememberFocus };
+}
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index f28d419..d582cc4 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -305,7 +305,7 @@
const report = (passed, error) => {
const output = document.createElement("pre");
output.id = "scan-test-report";
- output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, wide_paging: widePaging, expanded_tree: expandedTree, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "usable file workspace", "keyboard storage map visibility", "collapsible diagnostics", "complete paging", "directory paging focus and retries", "expanded-tree row growth and keyboard focus", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded package-folder paging and coverage", "package query retries and stale replies", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "file-type drilldown paging, keyboard and revision", "bounded largest files", "late largest response", "largest query retry", "malformed largest response recovery", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "bounded search results", "scoped search selection", "search page selection", "late search response", "search retry and malformed response", "search ID-only deletion", "read-only search deletion disabled", "late zoom", "Other tile", "stale confirmation", "exact confirmation whitespace", "reachable long-path confirmation", "native modal keyboard focus and cancellation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, wide_paging: widePaging, expanded_tree: expandedTree, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "usable file workspace", "keyboard storage map visibility", "collapsible diagnostics", "complete paging", "directory paging focus and retries", "expanded-tree row growth and keyboard focus", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded package-folder paging and coverage", "analysis paging keyboard focus", "package query retries and stale replies", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "file-type drilldown paging, keyboard and revision", "bounded largest files", "late largest response", "largest query retry", "malformed largest response recovery", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "bounded search results", "scoped search selection", "search page selection", "late search response", "search retry and malformed response", "search ID-only deletion", "read-only search deletion disabled", "late zoom", "Other tile", "stale confirmation", "exact confirmation whitespace", "reachable long-path confirmation", "native modal keyboard focus and cancellation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
document.body.append(output);
void fetch("/report", { method: "POST", body: output.textContent }).then(() => {
if (passed) location.replace("/tests/toast_lifecycle_fixture.html");
@@ -461,12 +461,33 @@
check(appsPanel().textContent.includes("Full app totals remain unknown") && appsPanel().textContent.includes("Missing and unreadable"),
"Package coverage was presented as complete");
check(appRows()[0].textContent.includes("0.0 B") || appRows()[0].textContent.includes("0 B"), "Zero scanned bytes were lost");
- button("Next").click();
+ holdApps = true;
+ resolveApps = undefined;
+ button("Next").focus();
+ await pressKey("Enter");
+ await waitFor(() => resolveApps && appRows().length === 0, "Package page did not enter its loading state");
+ resolveApps();
await waitFor(() => appRows()[0]?.textContent.includes("com.fixture100"), "Second package page missing");
- button("Next").click();
- await waitFor(() => appRows().length === 5, "Last package page missing");
- button("Previous").click();
+ check(document.activeElement === button("Next"), "Next package page lost keyboard focus");
+ failApps = true;
+ await pressKey("Enter");
+ await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed package page did not focus Retry");
+ await pressKey("Enter");
+ await waitFor(() => appRows().length === 5, "Last package page missing after retry");
+ check(document.activeElement === button("Previous"), "Last package page did not focus Previous");
+ await pressKey("Enter");
await waitFor(() => appRows()[0]?.textContent.includes("com.fixture100"), "Previous package page missing");
+ check(document.activeElement === button("Previous"), "Previous package page lost keyboard focus");
+ holdApps = true;
+ resolveApps = undefined;
+ button("Next").focus();
+ await pressKey("Enter");
+ await waitFor(() => resolveApps, "Pending last package page missing");
+ const packageTab = button("Package folders");
+ packageTab.focus();
+ resolveApps();
+ await waitFor(() => appRows().length === 5, "Pending last package page did not load");
+ check(document.activeElement === packageTab, "Loaded package page stole focus from the tab");
check(!appsPanel().querySelector('[aria-label^="Delete "]'), "Package summary exposed a deletion target");
for (const failure of ["error", "malformed"]) {
button("Storage map").click();
@@ -694,14 +715,18 @@
await pressKey("Space");
check(searchCheckbox().checked && selectionCount() === "1 file selected", "Space did not select a search result");
holdSearch = true;
- searchNext().click();
+ searchNext().focus();
+ await pressKey("Enter");
await waitFor(() => typeof resolveSearch === "function", "Second folder page did not start");
- button("Search entire scan").click();
+ const entireScanButton = button("Search entire scan");
+ entireScanButton.focus();
+ entireScanButton.click();
await waitFor(() => searchRows()[0]?.textContent.includes("nested-0"), "Scope switch retained the page offset");
resolveSearch();
resolveSearch = undefined;
await pause(30);
check(searchRows()[0]?.textContent.includes("nested-0"), "Late folder page replaced whole-scan results");
+ check(document.activeElement === entireScanButton, "Late folder page took focus from the scope control");
check(!searchCheckbox().checked && !selectionCount(), "Folder selection leaked into the whole scan");
searchFor("file");
await waitFor(() => searchRows().length === 100, "Whole-scan results missing");
@@ -742,8 +767,13 @@
const nestedCount = searchRows().length;
searchCheckbox().click();
const firstNestedNames = searchRows().map(row => row.textContent);
- searchNext().click();
+ failSearch = true;
+ searchNext().focus();
+ await pressKey("Enter");
+ await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed search page did not focus Retry");
+ await pressKey("Enter");
await waitFor(() => searchRows()[0]?.textContent.includes("nested-37"), "Short-page continuation skipped matches");
+ check(document.activeElement === searchNext(), "Retried search page did not restore paging focus");
check(calls.filter(call => call.command === "get_search_results").at(-1).args.skip === 37, "Short-page continuation used a fixed offset");
check(!searchCheckbox().checked && selectionCount() === "1 file selected", "Paging lost or applied selection to the wrong row");
searchCheckbox().click();
@@ -760,8 +790,10 @@
&& selectionCount() === "1 file selected", "Deselecting the page changed the selection on another page");
searchCheckbox().click();
check(selectionCount() === "2 files selected", "Selection count did not include both pages");
- button("Previous").click();
+ button("Previous").focus();
+ await pressKey("Enter");
await waitFor(() => searchRows()[0]?.textContent.includes("nested-0"), "Short-page Previous failed");
+ check(document.activeElement === searchNext(), "First search page did not focus Next");
check(JSON.stringify(searchRows().map(row => row.textContent)) === JSON.stringify(firstNestedNames), "Previous changed short-page boundaries");
check(searchCheckbox().checked && selectionCount() === "2 files selected", "Previous lost cross-page selection");
button("Clear selection").focus();
@@ -948,7 +980,8 @@
"File-type drilldown sent the wrong first-page filter");
holdSearch = true;
resolveSearch = undefined;
- button("Next").click();
+ button("Next").focus();
+ await pressKey("Enter");
await waitFor(() => resolveSearch && categoryQuery().skip === 37, "File-type continuation skipped the short first page");
button("Clear filter").focus();
await pressKey("Enter");
@@ -961,12 +994,18 @@
await pause(30);
check(searchRows().length === 0 && categoryQuery().fileType === "images" && categoryQuery().skip === 0,
"A late category page crossed filters");
+ check(document.activeElement === button("Clear filter"), "A late category page took focus from the new filter");
button("Clear filter").click();
await waitFor(typesReady, "File-type summary did not return");
typeButton("no_extension").click();
await waitFor(() => searchRows().length === 37 && categoryQuery().skip === 0, "Reopened category retained an old offset");
- button("Next").click();
+ failSearch = true;
+ button("Next").focus();
+ await pressKey("Enter");
+ await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed category page did not focus Retry");
+ await pressKey("Enter");
await waitFor(() => searchRows()[0]?.textContent.includes(" file-38 ") && categoryQuery().skip === 37, "Second category page lost its first match");
+ check(document.activeElement === button("Next"), "Retried category page did not restore paging focus");
const revisionBeforeCategoryDelete = revision;
filteredPanel().querySelector('[aria-label="Delete file-38 "]').click();
await waitFor(() => button("NUKE IT"), "Category file did not open the existing confirmation");