-
Notifications
You must be signed in to change notification settings - Fork 399
Expand file tree
/
Copy pathGrid.tsx
More file actions
101 lines (91 loc) · 3.08 KB
/
Grid.tsx
File metadata and controls
101 lines (91 loc) · 3.08 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
import { useCallback, useState } from "react";
import _ from "lodash";
import "@glideapps/glide-data-grid/dist/index.css";
import { DataEditor, GridCell, GridCellKind, GridColumn, Item } from "@glideapps/glide-data-grid";
// Define the shape of the data
interface Person {
firstName: string;
lastName: string;
id: number;
}
const data: Person[] = [
{
firstName: "John",
lastName: "Doe",
id: 100002,
},
{
firstName: "Maria",
lastName: "Garcia",
id: 100002,
},
{
firstName: "Nancy",
lastName: "Jones",
id: 100002,
},
{
firstName: "James",
lastName: "Smith",
id: 100002,
},
];
// Grid columns may also provide icon, overlayIcon, menu, style, and theme overrides
const columns: GridColumn[] = [
{ title: "First Name", width: 100, id: "firstName" },
{ title: "Last Name", width: 100, id: "lastName" },
{ title: "Id", width: 100, id: "id" },
];
export default function Grid() {
const [rows, setRows] = useState<Person[]>(data);
const onCellEdited = useCallback(
(cell: readonly [number, number], newValue: GridCell) => {
const [col_id, row_id] = cell;
const column = _.get(columns, col_id, {}) as GridColumn; // Type assertion here
// Check if newValue is of type GridCell and has a data property
if (newValue.kind === GridCellKind.Text || newValue.kind === GridCellKind.Number) {
const value = newValue.data;
if (column.id && value !== undefined) {
const key = column.id as keyof Person; // Type assertion
rows[row_id][key] = value as never; // Use `as never` to bypass assignment restrictions
setRows([...rows]);
}
}
},
[rows]
);
const onCellData = useCallback(
function getData([col, row]: Item): GridCell {
const person = rows[row];
if (col === 0) {
return {
kind: GridCellKind.Text,
data: person.firstName,
allowOverlay: false,
readonly: false,
displayData: person.firstName,
};
} else if (col === 1) {
return {
kind: GridCellKind.Text,
data: person.lastName,
allowOverlay: false,
displayData: person.lastName,
readonly: true,
};
} else if (col === 2) {
return {
kind: GridCellKind.Number,
data: person.id,
allowOverlay: true,
displayData: person.id.toString(),
readonly: false,
};
} else {
throw new Error("Invalid column index");
}
},
[rows]
);
return <DataEditor columns={columns} onCellEdited={onCellEdited} getCellContent={onCellData} rows={rows.length} />;
}