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
1.9 KB
Raw Blame
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 };
}