summaryrefslogtreecommitdiff
path: root/src/components/ConnectionTable.tsx
blob: c66700308220b9faed83d18356843e9b2335f533 (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
import './ConnectionTable.scss';

import cx from 'clsx';
import { formatDistance, Locale } from 'date-fns';
import { enUS, zhCN, zhTW } from 'date-fns/locale';
import React, { useEffect, useState } from 'react';
import { ChevronDown } from 'react-feather';
import { XCircle } from 'react-feather';
import { useTranslation } from 'react-i18next';
import { useSortBy, useTable } from 'react-table';

import { State } from '~/store/types';

import * as connAPI from '../api/connections';
import prettyBytes from '../misc/pretty-bytes';
import { getClashAPIConfig } from '../store/app';
import s from './ConnectionTable.module.scss';
import MOdalCloseConnection from './ModalCloseAllConnections';
import { connect } from './StateProvider';

const sortById = { id: 'id', desc: true };

function Table({ data, columns, hiddenColumns, apiConfig }) {
  const [operationId, setOperationId] = useState('');
  const [showModalDisconnect, setShowModalDisconnect] = useState(false);

  // 从本地存储加载排序状态
  const savedSortBy = JSON.parse(localStorage.getItem('tableSortBy')) || [sortById];

  const tableState = {
    sortBy: savedSortBy,
    hiddenColumns,
  };

  const table = useTable(
    {
      columns,
      data,
      initialState: tableState,
      autoResetSortBy: false,
    },
    useSortBy
  );

  const { getTableProps, setHiddenColumns, headerGroups, rows, prepareRow } = table;
  const state = table.state;

  useEffect(() => {
    setHiddenColumns(hiddenColumns);
  }, [setHiddenColumns, hiddenColumns]);

  const { t, i18n } = useTranslation();

  let locale: Locale;

  if (i18n.language === 'zh-CN') {
    locale = zhCN;
  } else if (i18n.language === 'zh-TW') {
    locale = zhTW;
  } else {
    locale = enUS;
  }

  const disconnectOperation = () => {
    connAPI.closeConnById(apiConfig, operationId);
    setShowModalDisconnect(false);
  };

  const handlerDisconnect = (id) => {
    setOperationId(id);
    setShowModalDisconnect(true);
  };

  const renderCell = (cell, locale) => {
    switch (cell.column.id) {
      case 'ctrl':
        return (
          <XCircle
            style={{ cursor: 'pointer' }}
            onClick={() => handlerDisconnect(cell.row.original.id)}
          ></XCircle>
        );
      case 'start':
        return formatDistance(cell.value, 0, { locale: locale });
      case 'download':
      case 'upload':
        return prettyBytes(cell.value);
      case 'downloadSpeedCurr':
      case 'uploadSpeedCurr':
        return prettyBytes(cell.value) + '/s';
      default:
        return cell.value;
    }
  };

  // 当排序状态改变时,将新状态保存到本地存储
  useEffect(() => {
    localStorage.setItem('tableSortBy', JSON.stringify(state.sortBy));
  }, [state.sortBy]);

  return (
    <div style={{ marginTop: '5px' }}>
      <table {...getTableProps()} className={cx(s.table, 'connections-table')}>
        <thead>
          {headerGroups.map((headerGroup, trindex) => {
            return (
              <tr {...headerGroup.getHeaderGroupProps()} className={s.tr} key={trindex}>
                {headerGroup.headers.map((column) => (
                  <th {...column.getHeaderProps(column.getSortByToggleProps())} className={s.th}>
                    <span>{t(column.render('Header'))}</span>
                    {column.id !== 'ctrl' ? (
                      <span className={s.sortIconContainer}>
                        {column.isSorted ? (
                          <ChevronDown
                            size={16}
                            className={column.isSortedDesc ? '' : s.rotate180}
                          />
                        ) : null}
                      </span>
                    ) : null}
                  </th>
                ))}
              </tr>
            );
          })}
        </thead>
        <tbody>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <tr className={s.tr} key={i}>
                {row.cells.map((cell) => {
                  return (
                    <td
                      {...cell.getCellProps()}
                      className={cx(s.td, i % 2 === 0 ? s.odd : false, cell.column.id)}
                    >
                      {renderCell(cell, locale)}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
      <MOdalCloseConnection
        confirm={'disconnect'}
        isOpen={showModalDisconnect}
        onRequestClose={() => setShowModalDisconnect(false)}
        primaryButtonOnTap={disconnectOperation}
      ></MOdalCloseConnection>
    </div>
  );
}

const mapState = (s: State) => ({
  apiConfig: getClashAPIConfig(s),
});

export default connect(mapState)(Table);