-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDataTable.tsx
372 lines (344 loc) · 11.2 KB
/
DataTable.tsx
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
import { PlusOutlined } from '@ant-design/icons';
import { Button, Table } from 'antd';
import {
ColumnsType,
ExpandableConfig,
SorterResult,
} from 'antd/lib/table/interface';
import { Layout, Spinner, usePlugin, useValue } from 'flipper-plugin';
import React, { useEffect, useState } from 'react';
import { plugin } from '..';
import InfiniteScroll from 'react-infinite-scroller';
import { InspectionDataType } from './RealmDataInspector';
import { renderValue } from '../utils/Renderer';
import { ColumnTitle } from './ColumnTitle';
import { DropdownPropertyType, MenuItemGenerator, PlainRealmObject, DeserializedRealmObject, SortedObjectSchema, RealmObjectReference } from '../CommonTypes';
import { ClickableText } from './ClickableText';
export type ColumnType = {
optional: boolean;
name: string;
objectType?: string;
type: string;
isPrimaryKey: boolean;
};
type DataTableProps = {
objects: DeserializedRealmObject[];
schemas: SortedObjectSchema[];
currentSchema: SortedObjectSchema;
sortingDirection: 'ascend' | 'descend' | null;
sortingColumn: string | null;
generateMenuItems?: MenuItemGenerator;
style?: Record<string, unknown>;
dropdownProp: DropdownPropertyType;
setdropdownProp: React.Dispatch<React.SetStateAction<DropdownPropertyType>>;
scrollX: number;
scrollY: number;
enableSort: boolean;
hasMore: boolean;
totalObjects?: number;
fetchMore: () => void;
setNewInspectionData: (
inspectionData: InspectionDataType,
wipeStacks?: boolean,
) => void;
clickAction?: (object: DeserializedRealmObject) => void;
getObject: (object: RealmObjectReference, objectSchemaName: string) => Promise<DeserializedRealmObject | null>;
};
// Receives a schema and returns column objects for the table.
const schemaObjectToColumns = (
schema: SortedObjectSchema,
): ColumnType[] => {
return schema.order.map((propertyName) => {
const obj = schema.properties[propertyName];
const isPrimaryKey = obj.name === schema.primaryKey;
return {
name: obj.name,
optional: obj.optional,
objectType: obj.objectType,
type: obj.type,
isPrimaryKey: isPrimaryKey,
};
});
};
export const DataTable = (dataTableProps: DataTableProps) => {
const {
objects,
schemas,
currentSchema,
generateMenuItems,
setdropdownProp,
dropdownProp,
scrollX,
scrollY,
setNewInspectionData,
enableSort,
hasMore,
totalObjects = 0,
fetchMore = () => undefined,
clickAction,
getObject,
} = dataTableProps;
const instance = usePlugin(plugin);
const state = useValue(instance.state);
const sortableTypes = new Set([
'string',
'int',
'uuid',
'date',
'decimal128',
'decimal',
'float',
'bool',
]);
const [rowExpansionProp, setRowExpansionProp] = useState({
expandedRowRender: () => {
return <></>;
},
showExpandColumn: false,
} as ExpandableConfig<DeserializedRealmObject>);
/** Hook to close the nested Table when clicked outside of it. */
useEffect(() => {
const closeNestedTable = () => {
setRowExpansionProp({ ...rowExpansionProp });
};
document.body.addEventListener('click', closeNestedTable);
return () => document.body.removeEventListener('click', closeNestedTable);
}, []);
if (!currentSchema) {
return <Layout.Container style={{padding: 20}}>Please select schema.</Layout.Container>;
}
if (currentSchema.embedded) {
return <Layout.Container style={{padding: 20}}>Embedded objects cannot be queried. Please view them from their parent schema or select a different schema.</Layout.Container>;
}
if (!schemas || !schemas.length) {
return <Layout.Container style={{padding: 20}}>No schemas found. Check selected Realm.</Layout.Container>;
}
/** Definition of antd-specific columns. This constant is passed to the antd table as a property. */
const antdColumns:ColumnsType<DeserializedRealmObject> = schemaObjectToColumns(currentSchema).map((column) => {
const property: Realm.CanonicalObjectSchemaProperty =
currentSchema.properties[column.name];
const linkedSchema = schemas.find(
(schema) => property && schema.name === property.objectType,
);
/* A function that is applied for every cell to specify what to render in each cell
on top of the pure value specified in the 'dataSource' property of the antd table.*/
const render = (value: PlainRealmObject | RealmObjectReference, row: DeserializedRealmObject) => {
/** Apply the renderValue function on the value in the cell to create a standard cell. */
const cellValue = renderValue(value, property, schemas, {
downloadData: instance.downloadData,
inspectValue: (value: any) => {
setNewInspectionData({
data: { [`${currentSchema.name}.${column.name}`]: value},
view: "property",
isReference: false,
}, true)
}
});
/** Render buttons to expand the row and a clickable text if the cell contains a linked or embedded Realm object. */
if (value !== null && linkedSchema && property.type === 'object') {
const isEmbedded = linkedSchema.embedded;
return (
<Layout.Container
style={{
display: 'flex',
flexDirection: 'row',
gap: '5px',
}}
>
{/* Embedded objects cannot be queried in the row. */
!isEmbedded && <Button
shape="circle"
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={async (event) => {
event.stopPropagation();
// Fetch the linked object and if found, expand the table with the row.
let linkedObject = await getObject(value as RealmObjectReference, linkedSchema.name)
if(linkedObject) {
expandRow(
row.objectKey,
linkedSchema,
linkedObject,
);
}
}}
ghost
/>}
{
<ClickableText
displayValue={cellValue}
onClick={() => {
setNewInspectionData({
data: isEmbedded ? { [`${currentSchema.name}.${column.name}`]: value} : value,
view: isEmbedded ? "property" : "object",
isReference: !isEmbedded
}, true);
}}/>
}
</Layout.Container>
);
}
return cellValue;
}
return {
/** Simple antd table props defined in their documentation */
key: property.name,
dataIndex: ["realmObject", property.name],
/** The title appearing in the tables title row. */
title: createTitle(column),
/** The function that defines how each cell is rendered. */
render,
property,
/** The function listening for onCell events, here listening for left-clicks on the cell to render the context menu.*/
onCell: (object: DeserializedRealmObject) => {
if (generateMenuItems) {
return {
onContextMenu: (env: React.MouseEvent) => {
env.preventDefault();
setdropdownProp({
...dropdownProp,
record: object,
schemaProperty: property,
currentSchema: currentSchema,
visible: true,
pointerX: env.clientX - 290,
pointerY: env.clientY - 225,
scrollX,
scrollY,
});
},
};
}
return {}
},
/** Enabling/Disabling sorting if the property.type is a sortable type */
sorter: enableSort && sortableTypes.has(property.type),
/** Defining the sorting order. */
sortOrder:
state.sortingColumn === property.name ? state.sortingDirection : null,
};
});
/** Updating the rowExpansion property of the antd table to expand the correct row and render a nested table inside of it. */
const expandRow = (
rowToExpandKey: any,
linkedSchema: SortedObjectSchema,
objectToRender: DeserializedRealmObject,
) => {
const newRowExpansionProp = {
...rowExpansionProp,
expandedRowKeys: [rowToExpandKey],
expandedRowRender: () => {
return (
<NestedTable
{ ...dataTableProps }
objects={[objectToRender]}
currentSchema={linkedSchema}
/>
);
},
};
setRowExpansionProp(newRowExpansionProp);
};
/** Loading new objects if the end of the table is reached. */
const handleInfiniteOnLoad = () => {
if (state.loading) {
return;
}
if (objects.length >= totalObjects) {
return;
}
fetchMore();
};
/** Handling sorting. Is called when the 'state' of the Ant D Table changes, ie. you sort on a column. */
const handleOnChange = (
sorter: SorterResult<any> | SorterResult<any>[],
extra: any,
) => {
if (extra.action === 'sort') {
if (state.loading) {
return;
}
// TODO: properly handle SorterResult<any>[] case
const sortedField = Array.isArray(sorter) ? sorter[0].field : sorter.field
if (state.sortingColumn !== sortedField) {
instance.setSortingDirection('ascend');
instance.setSortingColumn(sortedField as string);
} else {
instance.toggleSortingDirection();
}
instance.getObjects();
}
};
return (
<InfiniteScroll
initialLoad={false}
pageStart={0}
loadMore={handleInfiniteOnLoad}
hasMore={state.loading && hasMore}
useWindow={false}
loader={
<div
style={{
marginTop: '20px',
marginBottom: '100px',
display: 'inline-block',
}}
key={0}
>
<Spinner size={30} />
</div>
}
>
<Table
style={{
wordBreak: "break-all",
}}
bordered={true}
showSorterTooltip={false}
dataSource={objects}
onRow={(object: DeserializedRealmObject) => {
if (clickAction) {
return {
onClick: () => {
clickAction(object);
},
};
}
return {}
}}
rowKey={(record) => {
return record.objectKey;
}}
expandable={rowExpansionProp}
columns={antdColumns}
onChange={(_, __, sorter, extra) => handleOnChange(sorter, extra)}
pagination={false}
scroll={{ scrollToFirstRowOnChange: false }}
/>
</InfiniteScroll>
);
};
const createTitle = (column: ColumnType) => {
return (
<ColumnTitle
optional={column.optional}
name={column.name}
objectType={column.objectType}
type={column.type}
isPrimaryKey={column.isPrimaryKey}
/>
);
};
/** Internal component to render a nested table for exploring linked objects. */
const NestedTable = (props: DataTableProps) => {
return (
<div
style={{
boxShadow: '0px 0px 15px grey',
}}
>
<DataTable {...props} />
</div>
);
};