-
Notifications
You must be signed in to change notification settings - Fork 3
/
MultiText.jsx
124 lines (116 loc) · 2.88 KB
/
MultiText.jsx
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
import { Box, IconButton } from "@mui/material";
import AddCircleIcon from "@mui/icons-material/AddCircle";
import { DataGrid } from "@mui/x-data-grid";
import DeleteIcon from "@mui/icons-material/Delete";
import PropTypes from "prop-types";
import React from "react";
/**
* Label setter component are used to manage a table for value-label states
*/
export default function LabelSetter({ onChange = () => {}, rows = [] }) {
// add an id for each label/value
const rowsWithID = rows.map((item, index) => ({ ...item, id: index }));
// set column definition
const columns = [
{
align: "center",
editable: true,
field: "value",
headerAlign: "center",
headerName: "Value",
sortable: false,
type: "number",
width: 80
},
{
align: "center",
editable: true,
field: "label",
headerAlign: "center",
headerName: "Label",
sortable: false,
width: 150
},
{
align: "center",
disableClickEventBubbling: true,
field: "actions",
headerName: "Action",
renderCell: params => (
<IconButton
color="primary"
data-testid="deleteButton"
onClick={event => handleOnDeleteClick(event, params)}
>
<DeleteIcon />
</IconButton>
),
sortable: false,
width: 85
}
];
// handle row deletion
const handleOnDeleteClick = (event, params) => {
const updatedRows = JSON.parse(JSON.stringify(rowsWithID)).filter(item => {
return item.id !== params.row.id;
});
onChange(updatedRows);
};
// handle row addition
const handleOnAddClick = () => {
const newRow = { label: "", value: null };
const updatedRows = JSON.parse(JSON.stringify(rows));
updatedRows.push(newRow);
onChange(updatedRows);
};
// handle edit cell
const handleEditCell = params => {
const updatedRows = JSON.parse(JSON.stringify(rows));
updatedRows[params.id][params.field] = params.value;
onChange(updatedRows);
};
// return components
return (
<Box
display="flex"
flexDirection="column"
key={rows.length}
sx={{ height: "100%", width: "100%" }}
>
<DataGrid
data-testid="dataGrid"
disableColumnMenu
disableColumnSelector
hideFooter
rows={rowsWithID}
columns={columns}
onCellEditCommit={handleEditCell}
/>
<Box>
<IconButton
color="primary"
data-testid="addButton"
onClick={handleOnAddClick}
>
<AddCircleIcon />
</IconButton>
</Box>
</Box>
);
}
LabelSetter.propTypes = {
/**
* Callback fired when the cell values are changed.
*
* **Signature**
* ```
* function(rows: object) => void
* ```
* _rows_: The updated rows.
*/
onChange: PropTypes.func,
/**
* Set of rows.
*/
rows: PropTypes.array
};