fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: add web UI (#617)d672bf4

ignore
5.3 KiB172 linesraw
1import { useCallback, useEffect, useMemo, useState } from 'react';
2import type { Node, NodeResponse, SortKey, SortOrder, Status } from './types';
3import { fetchNode, fetchStatus, subscribeStatus } from './api';
4import { colorMapFor, computeSlices } from './slices';
5import { formatSize } from './format';
6import { DonutChart } from './components/DonutChart';
7import { FileTable } from './components/FileTable';
8import { Breadcrumbs } from './components/Breadcrumbs';
9import { ProgressBar } from './components/ProgressBar';
10
11export function App() {
12  const [status, setStatus] = useState<Status | null>(null);
13  const [currentPath, setCurrentPath] = useState<string | null>(null);
14  const [nodeResp, setNodeResp] = useState<NodeResponse | null>(null);
15  const [sort, setSort] = useState<SortKey>('size');
16  const [order, setOrder] = useState<SortOrder>('desc');
17  const [apparent, setApparent] = useState<boolean | null>(null);
18  const [hoveredPath, setHoveredPath] = useState<string | null>(null);
19  const [loadError, setLoadError] = useState<string | null>(null);
20
21  // Initial status + live updates over SSE.
22  useEffect(() => {
23    fetchStatus().then(setStatus).catch(() => undefined);
24    return subscribeStatus(setStatus);
25  }, []);
26
27  // Adopt the display default for size metric once, from the server flags.
28  useEffect(() => {
29    if (status && apparent === null) {
30      setApparent(status.showApparentSize);
31    }
32  }, [status, apparent]);
33
34  // Once a scan is done, default into the root directory.
35  useEffect(() => {
36    if (status?.state === 'done' && currentPath === null && status.rootPath) {
37      setCurrentPath(status.rootPath);
38    }
39  }, [status, currentPath]);
40
41  // Load the current node whenever the path, sort, or scan completion changes.
42  useEffect(() => {
43    if (currentPath === null) {
44      return;
45    }
46    let cancelled = false;
47    fetchNode(currentPath, sort, order)
48      .then((resp) => {
49        if (!cancelled) {
50          setNodeResp(resp);
51          setLoadError(null);
52        }
53      })
54      .catch((err: unknown) => {
55        if (!cancelled) {
56          setLoadError(err instanceof Error ? err.message : String(err));
57        }
58      });
59    return () => {
60      cancelled = true;
61    };
62  }, [currentPath, sort, order, status?.state]);
63
64  const effectiveApparent = apparent ?? status?.showApparentSize ?? false;
65  const useSIPrefix = status?.useSIPrefix ?? false;
66  const children = nodeResp?.children ?? [];
67
68  const { total } = useMemo(
69    () => computeSlices(children, effectiveApparent),
70    [children, effectiveApparent],
71  );
72  const colorMap = useMemo(
73    () => colorMapFor(children, effectiveApparent),
74    [children, effectiveApparent],
75  );
76
77  const handleSortChange = useCallback(
78    (key: SortKey) => {
79      if (key === sort) {
80        setOrder((o) => (o === 'asc' ? 'desc' : 'asc'));
81      } else {
82        setSort(key);
83        setOrder(key === 'name' ? 'asc' : 'desc');
84      }
85    },
86    [sort],
87  );
88
89  const handleSelect = useCallback((node: Node) => {
90    if (node.isDir) {
91      setCurrentPath(node.path);
92      setHoveredPath(null);
93    }
94  }, []);
95
96  const handleNavigate = useCallback((node: Node) => {
97    setCurrentPath(node.path);
98    setHoveredPath(null);
99  }, []);
100
101  if (!status) {
102    return <div className="loading">Connecting…</div>;
103  }
104
105  if (status.state === 'error') {
106    return (
107      <div className="error-screen">
108        <h2>Scan failed</h2>
109        <p>{status.error ?? 'Unknown error'}</p>
110      </div>
111    );
112  }
113
114  if (currentPath === null || (status.state === 'scanning' && !nodeResp)) {
115    return <ProgressBar progress={status.progress} useSIPrefix={useSIPrefix} />;
116  }
117
118  return (
119    <div className="app">
120      <header className="app-header">
121        <div className="app-title">
122          <span className="logo">gdu</span>
123          {nodeResp && (
124            <Breadcrumbs breadcrumbs={nodeResp.breadcrumbs} onNavigate={handleNavigate} />
125          )}
126        </div>
127        <div className="app-actions">
128          <span className="total">{formatSize(total, useSIPrefix)}</span>
129          <button
130            type="button"
131            className="toggle"
132            onClick={() => setApparent((a) => !(a ?? status.showApparentSize))}
133            title="Toggle between disk usage and apparent size"
134          >
135            {effectiveApparent ? 'Apparent size' : 'Disk usage'}
136          </button>
137          {status.state === 'scanning' && <span className="scanning-badge">scanning…</span>}
138        </div>
139      </header>
140
141      {loadError && <div className="banner error">{loadError}</div>}
142
143      <main className="content">
144        <section className="chart-panel">
145          <DonutChart
146            children={children}
147            apparent={effectiveApparent}
148            useSIPrefix={useSIPrefix}
149            hoveredPath={hoveredPath}
150            onHover={setHoveredPath}
151            onSelect={handleSelect}
152          />
153        </section>
154        <section className="table-panel">
155          <FileTable
156            children={children}
157            colorMap={colorMap}
158            apparent={effectiveApparent}
159            useSIPrefix={useSIPrefix}
160            total={total}
161            sort={sort}
162            order={order}
163            onSortChange={handleSortChange}
164            hoveredPath={hoveredPath}
165            onHover={setHoveredPath}
166            onSelect={handleSelect}
167          />
168        </section>
169      </main>
170    </div>
171  );
172}