summaryrefslogtreecommitdiff
path: root/src/components/TrafficNow.tsx
blob: ae69910797854e32fa2145d4a691634fa1251f3b (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
import * as React from 'react';
import { useTranslation } from 'react-i18next';

import * as connAPI from '../api/connections';
import { fetchData } from '../api/traffic';
import prettyBytes from '../misc/pretty-bytes';
import { getClashAPIConfig } from '../store/app';
import { connect } from './StateProvider';
import s0 from './TrafficNow.module.scss';

const { useState, useEffect, useCallback } = React;

const mapState = (s) => ({
  apiConfig: getClashAPIConfig(s),
});
export default connect(mapState)(TrafficNow);

function TrafficNow({ apiConfig }) {
  const { t } = useTranslation();
  const { upStr, downStr } = useSpeed(apiConfig);
  const { upTotal, dlTotal, connNumber, mUsage } = useConnection(apiConfig);
  return (
    <div className={s0.TrafficNow}>
      <div className={s0.sec}>
        <div>{t('Upload')}</div>
        <div>{upStr}</div>
      </div>
      <div className={s0.sec}>
        <div>{t('Download')}</div>
        <div>{downStr}</div>
      </div>
      <div className={s0.sec}>
        <div>{t('Upload Total')}</div>
        <div>{upTotal}</div>
      </div>
      <div className={s0.sec}>
        <div>{t('Download Total')}</div>
        <div>{dlTotal}</div>
      </div>
      <div className={s0.sec}>
        <div>{t('Active Connections')}</div>
        <div>{connNumber}</div>
      </div>
      <div className={s0.sec}>
        <div>{t('Memory Usage')}</div>
        <div>{mUsage}</div>
      </div>
    </div>
  );
}

function useSpeed(apiConfig) {
  const [speed, setSpeed] = useState({ upStr: '0 B/s', downStr: '0 B/s' });
  useEffect(() => {
    return fetchData(apiConfig).subscribe((o) =>
      setSpeed({
        upStr: prettyBytes(o.up) + '/s',
        downStr: prettyBytes(o.down) + '/s',
      })
    );
  }, [apiConfig]);
  return speed;
}

function useConnection(apiConfig) {
  const [state, setState] = useState({
    upTotal: '0 B',
    dlTotal: '0 B',
    connNumber: 0,
    mUsage: '0 B',
  });
  const read = useCallback(
    ({ downloadTotal, uploadTotal, connections, memory }) => {
      setState({
        upTotal: prettyBytes(uploadTotal),
        dlTotal: prettyBytes(downloadTotal),
        connNumber: connections.length,
        mUsage: prettyBytes(memory),
      });
    },
    [setState]
  );
  useEffect(() => {
    return connAPI.fetchData(apiConfig, read);
  }, [apiConfig, read]);
  return state;
}