-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathList.js
More file actions
415 lines (381 loc) · 11.3 KB
/
Copy pathList.js
File metadata and controls
415 lines (381 loc) · 11.3 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useTable, defaultRenderer as Cell, useFlexLayout, useRowState, useSortBy } from 'react-table'
import { theme, Flex } from 'ooni-components'
import styled from 'styled-components'
import { MdDelete, MdEdit, MdClose, MdCheck, MdArrowUpward, MdArrowDownward } from 'react-icons/md'
import { updateRule, deleteRule } from './lib/api'
import { useRouter } from 'next/router'
const BORDER_COLOR = theme.colors.gray6
const ODD_ROW_BG = theme.colors.gray2
const EVEN_ROW_BG = theme.colors.gray0
const Table = styled.table`
width: 100%;
`
const TableHeader = styled.thead`
background-color: white;
& th {
display: flex;
align-items: center;
text-align: start;
padding: 12px;
}
`
const TableRow = styled.tr`
:nth-child(odd) {
background-color: ${ODD_ROW_BG};
}
:nth-child(even) {
background-color: ${EVEN_ROW_BG};
}
:first-child {
border-top: 1px solid ${BORDER_COLOR};
}
:last-child {
border-bottom: 1px solid ${props => props.theme.colors.gray6};
}
`
const TableCell = styled.td`
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid ${props => props.theme.colors.gray6};
:last-child {
border-right: 1px solid ${props => props.theme.colors.gray6};
}
:first-child {
border-left: 1px solid ${props => props.theme.colors.gray6};
}
input {
font-size: 1rem;
padding: 0;
margin: 0;
border: 0;
}
/* TODO: Input validation styling */
`
// Dynamic Cell renderer shows either raw value or an editable HTMLInput element when editing the row
const EditableCell = ({
value: initialValue,
row: { index, original, state: { isEditing }, setState },
column: { id, inputAttrs = {} },
updateCellData
}) => {
// We need to keep and update the state of the cell normally
const [value, setValue] = React.useState(initialValue)
const onChange = e => {
setValue(e.target.value)
}
// Update table data onBlur and use row.values to send updates to API
const onBlur = () => {
let inputValue = value
// Reformat values based on column type
switch (inputAttrs.type) {
case 'number':
inputValue = Number(value)
break
}
// Update table data only if value changes
if (inputValue !== original[id]) {
setState({ isEditing, dirty: true })
// TODO: This is not very optimal because it alters the table data before sending changes to the API.
// Technically, this means that it is possible that, at times, table state doesn't reflect backend state.
updateCellData(index, id, inputValue)
}
}
// If the initialValue is changed external, sync it up with our state
React.useEffect(() => {
setValue(initialValue)
}, [initialValue])
if (isEditing) {
return <input {...inputAttrs} value={value} onChange={onChange} onBlur={onBlur} />
} else {
return <Cell value={value} />
}
}
// Set our editable cell renderer as the default Cell renderer
const defaultColumn = {
Cell: EditableCell
}
const Button = styled.button`
background-color: transparent;
border: 0;
padding: 0;
cursor: ${props => props.disabled ? 'not-allowed' : 'pointer'}
`
// Dynamic button
// * Starts editing a row
// * Switches to a two button component to confirm or cancel a row edit operation.
const EditButton = ({ resetRow, onRowUpdate, row: { index, values, state: { isEditing, /* dirty */ }, setState } }) => {
const onEdit = useCallback(() => {
// TODO: Don't edit if another row is still being edited
setState(state => ({ ...state, isEditing: true }))
}, [setState])
const onCancel = useCallback(() => {
// TODO: Ensure row state is reset before cancelling edit
resetRow(index)
setState(state => ({ ...state, isEditing: false, dirty: false }))
}, [resetRow, index, setState])
const onUpdate = useCallback(() => {
async function updateRow () {
await onRowUpdate(index, values)
setState(state => ({ ...state, isEditing: false, dirty: false }))
}
updateRow()
}, [onRowUpdate, index, values, setState])
return (
<Flex flexDirection='row' justifyContent='space-around'>
{!isEditing && <Button mx='auto'><MdEdit onClick={onEdit} size={20} /></Button>}
{isEditing && (
<>
<Button title='Discard Changes'><MdClose onClick={onCancel} size={20} /></Button>
<Button title={'Apply Changes'}><MdCheck onClick={onUpdate} size={20} /></Button>
</>
)}
</Flex>
)
}
const DeleteButton = ({ onClick }) => (
<Button onClick={onClick}><MdDelete size={18} /></Button>
)
const TableSortLabel = ({ active = false, direction = 'desc', size = 16 }) => (
active
? (
direction === 'asc'
? (
<MdArrowUpward size={size} />
)
: (
<MdArrowDownward size={size} />
)
)
: null
)
const List = ({ data, mutateRules }) => {
const [originalData, setOriginalData] = useState(data)
const updateOriginalData = useCallback(() => setOriginalData(data), [data])
const skipPageResetRef = React.useRef()
const router = useRouter()
const columns = useMemo(() => [
{
Header: 'Category Code',
accessor: 'category_code',
width: 50,
// minWidth: 100,
inputAttrs: {
type: 'text',
maxLength: 5,
size: 10,
id: 'category_code'
}
},
{
Header: 'Country Code',
accessor: 'cc',
width: 50,
inputAttrs: {
type: 'text',
maxLength: 2,
size: 4
}
},
{
Header: 'Domain',
accessor: 'domain',
width: 100,
inputAttrs: {
type: 'url',
size: 28
}
},
{
Header: 'URL',
accessor: 'url',
// maxWidth: 400,
inputAttrs: {
type: 'url',
size: 44
}
},
{
Header: 'Priority',
accessor: 'priority',
type: 'number',
maxWidth: 40,
inputAttrs: {
type: 'number',
maxLength: 2,
min: 0,
size: 6
}
}
], [])
// Called whenever a cell is changed so that the table data
// and controlled inputs are in sync
const updateCellData = useCallback((rowIndex, columnId, value) => {
skipPageResetRef.current = true
const locallyChangedData = data.map((row, index) => {
if (index === rowIndex) {
return {
...data[rowIndex],
[columnId]: value
}
}
return row
})
console.debug('locallyChanged row:', locallyChangedData[0])
// Update local swr cache, but do not fetch fresh data because editing must be in progress
mutateRules(locallyChangedData, false)
}, [data, mutateRules])
// Called to reverse the changes by updateCellData for the whole row
// based on data stored in originalData received from API
const resetRow = useCallback((rowIndex) => {
console.debug('Restoring to: ', originalData[rowIndex])
skipPageResetRef.current = true
const restoredData = originalData.map((row, index) => {
if (index === rowIndex) {
return originalData[rowIndex]
}
return row
})
// Restore local swr cache, but also fetch fresh data
mutateRules(restoredData, false)
}, [originalData, mutateRules])
const onRowUpdate = useCallback((rowIndex, updatedEntry) => {
if (rowIndex in originalData) {
return updateRule(originalData[rowIndex], updatedEntry).then(async () => {
try {
await mutateRules(data, true)
updateOriginalData()
} catch (e) {
console.error('Failed to mutate after successful update. Table state could be broken. Reloading page.')
router.reload()
}
}).catch(e => {
// TODO: Update failed. Now what?
console.log(e.response.data.error)
router.reload()
})
}
}, [originalData, mutateRules, data, updateOriginalData, router])
// TODO: Maybe this can be merged with onRowUpdate
const onRowDelete = useCallback((rowIndex) => {
if (rowIndex in originalData) {
return deleteRule(originalData[rowIndex]).then(async () => {
try {
await mutateRules(originalData.filter((_, i) => i !== rowIndex), true)
updateOriginalData()
} catch (e) {
console.error('Failed to mutate after successful delete. Table state could be broken. Reloading page.')
router.reload()
}
}).catch(e => {
console.log(e.response.data.error)
router.reload()
})
}
}, [mutateRules, originalData, router, updateOriginalData])
// This allows useTable to reset the table when data changes
// https://react-table.tanstack.com/docs/faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes
// it should be set to true whenever table data is being altered
useEffect(() => {
skipPageResetRef.current = false
})
const tableInstance = useTable({
columns,
data,
defaultColumn,
updateCellData,
onRowUpdate,
onRowDelete,
resetRow,
initialState: {
sortBy: [
{
id: 'priority',
desc: true
}
]
},
initialRowStateAccessor: () => ({ isEditing: false, dirty: false }),
autoResetRowState: !skipPageResetRef.current,
autoResetSortBy: !skipPageResetRef.current
},
useFlexLayout,
useRowState,
useSortBy,
hooks => {
hooks.visibleColumns.push(columns => [
{
id: 'edit',
maxWidth: 32,
Cell: EditButton
},
...columns,
{
id: 'delete',
maxWidth: 16,
// eslint-disable-next-line react/display-name
Cell: ({ row: { index } }) => (
<DeleteButton onClick={() => onRowDelete(index)} />
)
}
])
}
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = tableInstance
return (
// apply the table props
<Table
{...getTableProps()}
>
<TableHeader>
{// Loop over the header rows
/* eslint-disable react/jsx-key */
headerGroups.map(headerGroup => (
// Apply the header row props
<tr {...headerGroup.getHeaderGroupProps()}>
{// Loop over the headers in each row
headerGroup.headers.map(column => (
// Apply the header cell props
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{// Render the header
column.render('Header')}
<TableSortLabel active={column.isSorted} direction={column.isSortedDesc ? 'desc' : 'asc'} />
</th>
))}
</tr>
))}
</TableHeader>
{/* Apply the table body props */}
<tbody {...getTableBodyProps()}>
{// Loop over the table rows
rows.map(row => {
// Prepare the row for display
prepareRow(row)
return (
// Apply the row props
<TableRow {...row.getRowProps()} index={row.index}>
{// Loop over the rows cells
row.cells.map(cell => {
// Apply the cell props
return (
<TableCell {...cell.getCellProps()}>
{// Render the cell contents
cell.render('Cell')}
</TableCell>
)
})}
</TableRow>
)
/* eslint-enable react/jsx-key */
})}
</tbody>
</Table>
)
}
export default List