aboutsummaryrefslogtreecommitdiff
path: root/users/ryan/modules/simple-bar/simple-bar-source/lib/components/data/netstats.jsx
blob: ef3d7be91f6cb12019997f64960b47a1aeca63c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import * as Uebersicht from "uebersicht";
import * as DataWidget from "./data-widget.jsx";
import * as DataWidgetLoader from "./data-widget-loader.jsx";
import * as Icons from "../icons/icons.jsx";
import { SuspenseIcon } from "../icons/icon.jsx";
import Graph from "./graph.jsx";
import useWidgetRefresh from "../../hooks/use-widget-refresh.js";
import useServerSocket from "../../hooks/use-server-socket";
import { useSimpleBarContext } from "../simple-bar-context.jsx";
import * as Utils from "../../utils.js";

export { netstatsStyles as styles } from "../../styles/components/data/netstats";

const { React } = Uebersicht;

const DEFAULT_REFRESH_FREQUENCY = 2000;
const GRAPH_LENGTH = 30;

/**
 * Netstats widget component.
 * @returns {JSX.Element|null} The rendered component.
 */
export const Widget = React.memo(() => {
  const { displayIndex, settings } = useSimpleBarContext();
  const { widgets, netstatsWidgetOptions } = settings;
  const { netstatsWidget } = widgets;
  const {
    refreshFrequency,
    showOnDisplay,
    displayAsGraph,
    showIcon,
    netstatsThreshold,
  } = netstatsWidgetOptions;

  const isDisabled = React.useRef(false);

  // Determine the refresh frequency for the widget
  const refresh = React.useMemo(
    () =>
      Utils.getRefreshFrequency(refreshFrequency, DEFAULT_REFRESH_FREQUENCY),
    [refreshFrequency],
  );

  // Determine if the widget should be visible
  const visible =
    Utils.isVisibleOnDisplay(displayIndex, showOnDisplay) && netstatsWidget;

  const [graph, setGraph] = React.useState([]);
  const [state, setState] = React.useState();
  const [loading, setLoading] = React.useState(visible);

  /**
   * Resets the widget state.
   */
  const resetWidget = () => {
    setState(undefined);
    setLoading(false);
    setGraph([]);
  };

  /**
   * Fetches network statistics.
   */
  const getNetstats = React.useCallback(async () => {
    if (!visible) return;
    try {
      const output = await Utils.cachedRun(
        `bash ./simple-bar/lib/scripts/netstats.sh 2>&1`,
        refresh,
      );
      if (!visible || isDisabled.current) {
        return;
      }
      const data = Utils.cleanupOutput(output);
      const json = JSON.parse(data);
      setState(json);
      if (displayAsGraph) {
        Utils.addToGraphHistory(json, setGraph, GRAPH_LENGTH);
      }
      setLoading(false);
    } catch {
      setTimeout(getNetstats, 1000);
    }
  }, [displayAsGraph, setGraph, visible, refresh]);

  // Update the disabled state based on visibility
  React.useEffect(() => {
    isDisabled.current = !visible;
  }, [visible]);

  // Set up server socket and widget refresh hooks
  useServerSocket("netstats", visible, getNetstats, resetWidget, setLoading);
  useWidgetRefresh(visible, getNetstats, refresh);

  if (loading)
    return (
      <React.Fragment>
        <DataWidgetLoader.Widget className="netstats" />
        {!displayAsGraph && <DataWidgetLoader.Widget className="netstats" />}
      </React.Fragment>
    );

  if (!state) {
    return null;
  }

  const { download, upload } = state;

  if (download === undefined || upload === undefined) {
    return null;
  }

  const threshold = (Number(netstatsThreshold) || 0) * 1024;
  const isBelowThreshold =
    threshold > 0 &&
    Math.abs(download) < threshold &&
    Math.abs(upload) < threshold;

  if (isBelowThreshold) {
    return null;
  }

  const formattedDownload = Utils.formatBytes(download);
  const formattedUpload = Utils.formatBytes(upload);

  if (displayAsGraph) {
    return (
      <DataWidget.Widget classes="netstats netstats--graph" disableSlider>
        <Graph
          className="netstats__graph"
          caption={{
            download: {
              value: formattedDownload,
              icon: showIcon ? Icons.Download : null,
              color: "var(--magenta)",
            },
            upload: {
              value: formattedUpload,
              icon: showIcon ? Icons.Upload : null,
              color: "var(--blue)",
            },
          }}
          values={graph}
          maxLength={GRAPH_LENGTH}
        />
      </DataWidget.Widget>
    );
  }

  return (
    <React.Fragment>
      <DataWidget.Widget classes="netstats" disableSlider>
        <div className="netstats__item">
          {showIcon && (
            <SuspenseIcon>
              <Icons.Download className="netstats__icon netstats__icon--download" />
            </SuspenseIcon>
          )}
          <span
            className="netstats__value"
            dangerouslySetInnerHTML={{ __html: formattedDownload }}
          />
        </div>
      </DataWidget.Widget>
      <DataWidget.Widget classes="netstats" disableSlider>
        <div className="netstats__item">
          {showIcon && (
            <SuspenseIcon>
              <Icons.Upload className="netstats__icon netstats__icon--upload" />
            </SuspenseIcon>
          )}
          <span
            className="netstats__value"
            dangerouslySetInnerHTML={{ __html: formattedUpload }}
          />
        </div>
      </DataWidget.Widget>
    </React.Fragment>
  );
});

Widget.displayName = "Netstats";