@sidekickdb/components 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.turbo/turbo-build.log +20 -0
  2. package/LICENSE.md +202 -0
  3. package/NOTICE +27 -0
  4. package/README.md +93 -2
  5. package/app/App.css +38 -0
  6. package/app/App.tsx +63 -0
  7. package/app/index.css +18 -0
  8. package/app/main.tsx +10 -0
  9. package/dist/components/DialogContentPrimitive.d.ts +1 -0
  10. package/dist/components/DialogContentPrimitive.d.ts.map +1 -0
  11. package/dist/components/StyleMe.d.ts +15 -0
  12. package/dist/components/StyleMe.d.ts.map +1 -0
  13. package/dist/components/error-boundary.d.ts +17 -0
  14. package/dist/components/error-boundary.d.ts.map +1 -0
  15. package/dist/components/explorer/__tests__/edit-row-dialog.test.d.ts +2 -0
  16. package/dist/components/explorer/__tests__/edit-row-dialog.test.d.ts.map +1 -0
  17. package/dist/components/explorer/__tests__/format-value.test.d.ts +2 -0
  18. package/dist/components/explorer/__tests__/format-value.test.d.ts.map +1 -0
  19. package/dist/components/explorer/edit-namespace-dialog.d.ts +17 -0
  20. package/dist/components/explorer/edit-namespace-dialog.d.ts.map +1 -0
  21. package/dist/components/explorer/edit-row-dialog.d.ts +15 -0
  22. package/dist/components/explorer/edit-row-dialog.d.ts.map +1 -0
  23. package/dist/components/explorer/expandable-deleted-attr.d.ts +15 -0
  24. package/dist/components/explorer/expandable-deleted-attr.d.ts.map +1 -0
  25. package/dist/components/explorer/explorer-layout.d.ts +9 -0
  26. package/dist/components/explorer/explorer-layout.d.ts.map +1 -0
  27. package/dist/components/explorer/format-value.d.ts +2 -0
  28. package/dist/components/explorer/format-value.d.ts.map +1 -0
  29. package/dist/components/explorer/index.d.ts +128 -0
  30. package/dist/components/explorer/index.d.ts.map +1 -0
  31. package/dist/components/explorer/inner-explorer.d.ts +17 -0
  32. package/dist/components/explorer/inner-explorer.d.ts.map +1 -0
  33. package/dist/components/explorer/new-namespace-dialog.d.ts +10 -0
  34. package/dist/components/explorer/new-namespace-dialog.d.ts.map +1 -0
  35. package/dist/components/explorer/query-inspector.d.ts +11 -0
  36. package/dist/components/explorer/query-inspector.d.ts.map +1 -0
  37. package/dist/components/explorer/recently-deleted.d.ts +36 -0
  38. package/dist/components/explorer/recently-deleted.d.ts.map +1 -0
  39. package/dist/components/explorer/search-input.d.ts +9 -0
  40. package/dist/components/explorer/search-input.d.ts.map +1 -0
  41. package/dist/components/explorer/table-components.d.ts +16 -0
  42. package/dist/components/explorer/table-components.d.ts.map +1 -0
  43. package/dist/components/explorer/view-settings.d.ts +10 -0
  44. package/dist/components/explorer/view-settings.d.ts.map +1 -0
  45. package/dist/components/rosePineDawnTheme.d.ts +13 -0
  46. package/dist/components/rosePineDawnTheme.d.ts.map +1 -0
  47. package/dist/components/select.d.ts +16 -0
  48. package/dist/components/select.d.ts.map +1 -0
  49. package/dist/components/toast.d.ts +4 -0
  50. package/dist/components/toast.d.ts.map +1 -0
  51. package/dist/components/ui.d.ts +349 -0
  52. package/dist/components/ui.d.ts.map +1 -0
  53. package/dist/config.d.ts +11 -0
  54. package/dist/config.d.ts.map +1 -0
  55. package/dist/hooks/__tests__/explorer.test.d.ts +2 -0
  56. package/dist/hooks/__tests__/explorer.test.d.ts.map +1 -0
  57. package/dist/hooks/explorer.d.ts +33 -0
  58. package/dist/hooks/explorer.d.ts.map +1 -0
  59. package/dist/hooks/useAttrNotes.d.ts +10 -0
  60. package/dist/hooks/useAttrNotes.d.ts.map +1 -0
  61. package/dist/hooks/useClickOutside.d.ts +3 -0
  62. package/dist/hooks/useClickOutside.d.ts.map +1 -0
  63. package/dist/hooks/useColumnVisibility.d.ts +12 -0
  64. package/dist/hooks/useColumnVisibility.d.ts.map +1 -0
  65. package/dist/hooks/useEditBlobConstraints.d.ts +32 -0
  66. package/dist/hooks/useEditBlobConstraints.d.ts.map +1 -0
  67. package/dist/hooks/useExplorerHistory.d.ts +1 -0
  68. package/dist/hooks/useExplorerHistory.d.ts.map +1 -0
  69. package/dist/hooks/useIsOverflow.d.ts +6 -0
  70. package/dist/hooks/useIsOverflow.d.ts.map +1 -0
  71. package/dist/hooks/useLocalStorage.d.ts +2 -0
  72. package/dist/hooks/useLocalStorage.d.ts.map +1 -0
  73. package/dist/hooks/useMonacoJSONSchema.d.ts +3 -0
  74. package/dist/hooks/useMonacoJSONSchema.d.ts.map +1 -0
  75. package/dist/hooks/useStableDB.d.ts +7 -0
  76. package/dist/hooks/useStableDB.d.ts.map +1 -0
  77. package/dist/index.cjs +15 -0
  78. package/dist/index.d.ts +7 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +9751 -0
  81. package/dist/schema.d.ts +5 -0
  82. package/dist/schema.d.ts.map +1 -0
  83. package/dist/style.css +1 -0
  84. package/dist/types.d.ts +241 -0
  85. package/dist/types.d.ts.map +1 -0
  86. package/dist/utils/format.d.ts +2 -0
  87. package/dist/utils/format.d.ts.map +1 -0
  88. package/dist/utils/indexingJobs.d.ts +24 -0
  89. package/dist/utils/indexingJobs.d.ts.map +1 -0
  90. package/dist/utils/parsePermsJSON.d.ts +11 -0
  91. package/dist/utils/parsePermsJSON.d.ts.map +1 -0
  92. package/dist/utils/renames.d.ts +3 -0
  93. package/dist/utils/renames.d.ts.map +1 -0
  94. package/dist/utils/tableWidthSize.d.ts +9 -0
  95. package/dist/utils/tableWidthSize.d.ts.map +1 -0
  96. package/index.html +13 -0
  97. package/package.json +111 -3
  98. package/src/components/DialogContentPrimitive.tsx +0 -0
  99. package/src/components/StyleMe.tsx +97 -0
  100. package/src/components/error-boundary.tsx +76 -0
  101. package/src/components/explorer/__tests__/edit-row-dialog.test.ts +31 -0
  102. package/src/components/explorer/__tests__/format-value.test.ts +9 -0
  103. package/src/components/explorer/edit-namespace-dialog.tsx +1890 -0
  104. package/src/components/explorer/edit-row-dialog.tsx +1367 -0
  105. package/src/components/explorer/expandable-deleted-attr.tsx +170 -0
  106. package/src/components/explorer/explorer-layout.tsx +196 -0
  107. package/src/components/explorer/format-value.ts +9 -0
  108. package/src/components/explorer/index.tsx +280 -0
  109. package/src/components/explorer/inner-explorer.tsx +1524 -0
  110. package/src/components/explorer/new-namespace-dialog.tsx +55 -0
  111. package/src/components/explorer/query-inspector.tsx +395 -0
  112. package/src/components/explorer/recently-deleted.tsx +349 -0
  113. package/src/components/explorer/search-input.tsx +358 -0
  114. package/src/components/explorer/table-components.tsx +416 -0
  115. package/src/components/explorer/view-settings.tsx +76 -0
  116. package/src/components/rosePineDawnTheme.ts +45 -0
  117. package/src/components/select.tsx +198 -0
  118. package/src/components/toast.tsx +18 -0
  119. package/src/components/ui.tsx +1740 -0
  120. package/src/config.ts +57 -0
  121. package/src/hooks/__tests__/explorer.test.ts +109 -0
  122. package/src/hooks/explorer.tsx +137 -0
  123. package/src/hooks/useAttrNotes.ts +27 -0
  124. package/src/hooks/useClickOutside.ts +23 -0
  125. package/src/hooks/useColumnVisibility.ts +39 -0
  126. package/src/hooks/useEditBlobConstraints.ts +185 -0
  127. package/src/hooks/useExplorerHistory.ts +0 -0
  128. package/src/hooks/useIsOverflow.ts +24 -0
  129. package/src/hooks/useLocalStorage.ts +51 -0
  130. package/src/hooks/useMonacoJSONSchema.ts +41 -0
  131. package/src/hooks/useStableDB.ts +31 -0
  132. package/src/index.tsx +12 -0
  133. package/src/schema.ts +286 -0
  134. package/src/style.css +84 -0
  135. package/src/types.ts +359 -0
  136. package/src/utils/format.ts +13 -0
  137. package/src/utils/indexingJobs.ts +126 -0
  138. package/src/utils/parsePermsJSON.ts +35 -0
  139. package/src/utils/renames.ts +42 -0
  140. package/src/utils/tableWidthSize.ts +62 -0
  141. package/tailwind.config.cjs +48 -0
  142. package/tsconfig.json +22 -0
  143. package/vite-env.d.ts +1 -0
  144. package/vite.config.ts +50 -0
@@ -0,0 +1,1524 @@
1
+ import {
2
+ closestCenter,
3
+ DndContext,
4
+ type DragEndEvent,
5
+ KeyboardSensor,
6
+ MouseSensor,
7
+ TouchSensor,
8
+ useSensor,
9
+ useSensors,
10
+ } from '@dnd-kit/core';
11
+ import { markdownTable } from 'markdown-table';
12
+
13
+ import { mkConfig, generateCsv, download } from 'export-to-csv';
14
+
15
+ import { restrictToHorizontalAxis } from '@dnd-kit/modifiers';
16
+ import {
17
+ arrayMove,
18
+ horizontalListSortingStrategy,
19
+ SortableContext,
20
+ } from '@dnd-kit/sortable';
21
+ import {
22
+ ArrowUpOnSquareIcon,
23
+ PencilSquareIcon,
24
+ TrashIcon,
25
+ XMarkIcon,
26
+ } from '@heroicons/react/24/outline';
27
+ import { coerceToDate, tx } from '@sidekickdb/core';
28
+ import { InstantReactAbstractDatabase } from '@sidekickdb/react';
29
+ import {
30
+ ColumnDef,
31
+ ColumnSizingState,
32
+ getCoreRowModel,
33
+ useReactTable,
34
+ } from '@tanstack/react-table';
35
+ import {
36
+ ArrowLeftIcon,
37
+ ArrowRightIcon,
38
+ CurlyBraces,
39
+ FileDown,
40
+ PlusIcon,
41
+ Table,
42
+ } from 'lucide-react';
43
+ import React, {
44
+ useEffect,
45
+ useLayoutEffect,
46
+ useMemo,
47
+ useRef,
48
+ useState,
49
+ } from 'react';
50
+ import { useExplorerDialog, useExplorerProps, useExplorerState } from '.';
51
+ import { SearchInput } from './search-input';
52
+
53
+ import { errorToast, successToast } from '@lib/components/toast';
54
+ import {
55
+ ActionButton,
56
+ ActionForm,
57
+ Button,
58
+ Checkbox,
59
+ cn,
60
+ Content,
61
+ Dialog,
62
+ DropdownMenu,
63
+ DropdownMenuContent,
64
+ DropdownMenuItem,
65
+ DropdownMenuSeparator,
66
+ DropdownMenuTrigger,
67
+ Fence,
68
+ IconButton,
69
+ Select,
70
+ } from '@lib/components/ui';
71
+ import {
72
+ SearchFilter,
73
+ resolveFilters,
74
+ useNamespacesQuery,
75
+ } from '@lib/hooks/explorer';
76
+ import { useColumnVisibility } from '@lib/hooks/useColumnVisibility';
77
+ import { useLocalStorage } from '@lib/hooks/useLocalStorage';
78
+ import { SchemaAttr, SchemaNamespace } from '@lib/types';
79
+ import { formatBytes } from '@lib/utils/format';
80
+ import { getTableWidthSize } from '@lib/utils/tableWidthSize';
81
+ import { ArrowRightFromLine } from 'lucide-react';
82
+ import { TableCell, TableHeader } from './table-components';
83
+ import { ViewSettings } from './view-settings';
84
+
85
+ import { isObject } from 'lodash';
86
+ import { EditNamespaceDialog } from './edit-namespace-dialog';
87
+ import { EditRowDialog, isEditableExplorerAttr } from './edit-row-dialog';
88
+ import copy from 'copy-to-clipboard';
89
+ import { formatVal } from './format-value';
90
+
91
+ const fallbackItems: any[] = [];
92
+
93
+ export type TableColMeta = {
94
+ sortable?: boolean;
95
+ disablePadding: boolean;
96
+ isLink?: boolean;
97
+ attr: SchemaAttr;
98
+ copyable?: boolean;
99
+ editable?: boolean;
100
+ };
101
+
102
+ function exportToCSV(
103
+ rows: any[],
104
+ columns: ColumnDef<any>[],
105
+ namespace: string,
106
+ downloadFile: boolean = false,
107
+ ) {
108
+ if (rows.length === 0) return;
109
+
110
+ const visibleColumns = columns.filter(
111
+ (col) =>
112
+ col.id !== 'select-col' &&
113
+ col.header !== undefined &&
114
+ !(col.meta as TableColMeta | undefined)?.isLink,
115
+ );
116
+
117
+ const data = rows.map((row) => {
118
+ const rowData: Record<string, any> = {};
119
+ visibleColumns.forEach((col: any) => {
120
+ const value = row[col.header];
121
+ // Handle different data types
122
+ if (value === null || value === undefined) {
123
+ rowData[col.header] = '';
124
+ } else if (typeof value === 'object') {
125
+ rowData[col.header] = JSON.stringify(value);
126
+ } else {
127
+ rowData[col.header] = value;
128
+ }
129
+ });
130
+ return rowData;
131
+ });
132
+
133
+ const csvConfig = mkConfig({
134
+ fieldSeparator: ',',
135
+ filename: `${namespace}_export`,
136
+ decimalSeparator: '.',
137
+ useKeysAsHeaders: true,
138
+ });
139
+
140
+ const csv = generateCsv(csvConfig)(data);
141
+
142
+ if (downloadFile) {
143
+ download(csvConfig)(csv);
144
+ successToast('CSV file downloaded');
145
+ } else {
146
+ copy(csv.toString());
147
+ successToast('CSV copied to clipboard');
148
+ }
149
+ }
150
+
151
+ function exportToMarkdown(
152
+ rows: any[],
153
+ columns: any[],
154
+ namespace: string,
155
+ downloadFile: boolean = false,
156
+ ) {
157
+ if (rows.length === 0) return;
158
+
159
+ const visibleColumns = columns.filter(
160
+ (col) =>
161
+ col.id !== 'select-col' &&
162
+ col.header !== undefined &&
163
+ !(col.meta as TableColMeta | undefined)?.isLink,
164
+ );
165
+
166
+ const headers = visibleColumns.map((col: any) => col.header as string);
167
+
168
+ const data = rows.map((row) => {
169
+ return visibleColumns.map((col: any) => {
170
+ const value = row[col.header];
171
+ if (value === null || value === undefined) {
172
+ return ' ';
173
+ } else if (typeof value === 'object') {
174
+ return JSON.stringify(value);
175
+ } else {
176
+ return String(value);
177
+ }
178
+ });
179
+ });
180
+
181
+ const markdown = markdownTable([headers, ...data]);
182
+
183
+ if (downloadFile) {
184
+ const blob = new Blob([markdown], { type: 'text/markdown' });
185
+ const url = URL.createObjectURL(blob);
186
+ const a = document.createElement('a');
187
+ a.href = url;
188
+ a.download = `${namespace}_export.md`;
189
+ document.body.appendChild(a);
190
+ a.click();
191
+ document.body.removeChild(a);
192
+ URL.revokeObjectURL(url);
193
+ successToast('Markdown file downloaded');
194
+ } else {
195
+ copy(markdown);
196
+ successToast('Markdown copied to clipboard');
197
+ }
198
+ }
199
+
200
+ function exportToJSON(
201
+ rows: any[],
202
+ columns: any[],
203
+ namespace: string,
204
+ downloadFile: boolean = false,
205
+ ) {
206
+ if (rows.length === 0) return;
207
+
208
+ const visibleColumns = columns.filter(
209
+ (col) =>
210
+ col.id !== 'select-col' &&
211
+ col.header !== undefined &&
212
+ !(col.meta as TableColMeta | undefined)?.isLink,
213
+ );
214
+
215
+ const data = rows.map((row) => {
216
+ const rowData: Record<string, any> = {};
217
+ visibleColumns.forEach((col: any) => {
218
+ const value = row[col.header];
219
+ rowData[col.header] = value;
220
+ });
221
+ return rowData;
222
+ });
223
+
224
+ const json = JSON.stringify(data, null, 2);
225
+
226
+ if (downloadFile) {
227
+ const blob = new Blob([json], { type: 'application/json' });
228
+ const url = URL.createObjectURL(blob);
229
+ const a = document.createElement('a');
230
+ a.href = url;
231
+ a.download = `${namespace}_export.json`;
232
+ document.body.appendChild(a);
233
+ a.click();
234
+ document.body.removeChild(a);
235
+ URL.revokeObjectURL(url);
236
+ successToast('JSON file downloaded');
237
+ } else {
238
+ copy(json);
239
+ successToast('JSON copied to clipboard');
240
+ }
241
+ }
242
+
243
+ export const InnerExplorer: React.FC<{
244
+ db: InstantReactAbstractDatabase<any, any>;
245
+ namespaces: SchemaNamespace[];
246
+ }> = ({ db, namespaces }) => {
247
+ const { explorerState, history } = useExplorerState();
248
+ const explorerProps = useExplorerProps();
249
+
250
+ const currentNav = explorerState;
251
+ const selectedNamespace = namespaces.find(
252
+ (ns) => ns.id === currentNav.namespace,
253
+ );
254
+
255
+ const [limit, setLimit] = useState(50);
256
+ const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
257
+ const [uploadingFile, setUploadingFile] = useState(false);
258
+ const [customPath, setCustomPath] = useState('');
259
+ const [deleteDataConfirmationOpen, setDeleteDataConfirmationOpen] =
260
+ useState(false);
261
+ const { dialog, setDialog } = useExplorerDialog();
262
+ const editNs =
263
+ dialog?.type === 'edit-schema' ? (selectedNamespace ?? null) : null;
264
+ const editableRowId = dialog?.type === 'edit-row' ? dialog.rowId : null;
265
+ const addItemDialogOpen = dialog?.type === 'add-row';
266
+ const lastSelectedIdRef = useRef<string | null>(null);
267
+ const [offsets, setOffsets] = useState<{ [namespace: string]: number }>({});
268
+
269
+ const fileInputRef = useRef<HTMLInputElement>(null);
270
+ const isSystemCatalogNs = selectedNamespace?.name?.startsWith('$') ?? false;
271
+ const sanitizedNsName = selectedNamespace?.name ?? '';
272
+ const readOnlyNs =
273
+ isSystemCatalogNs &&
274
+ !['$users', '$files', '$streams'].includes(sanitizedNsName);
275
+ const offset = offsets[sanitizedNsName] || 0;
276
+
277
+ const sortAttr = currentNav?.sortAttr || 'serverCreatedAt';
278
+ const sortAsc = currentNav?.sortAsc ?? true;
279
+
280
+ const handleRangeSelection = (currentId: string, checked: boolean) => {
281
+ const allItemIds = table.options.data.map((i) => i.id as string);
282
+ const currentIndex = allItemIds.indexOf(currentId);
283
+ const lastSelectedIndex = allItemIds.indexOf(lastSelectedIdRef.current!);
284
+ const [start, end] = [
285
+ Math.min(currentIndex, lastSelectedIndex),
286
+ Math.max(currentIndex, lastSelectedIndex),
287
+ ];
288
+
289
+ setCheckedIds((prev) => {
290
+ const newCheckedIds = { ...prev };
291
+ for (let i = start; i <= end; i++) {
292
+ const id = allItemIds[i];
293
+ if (checked) {
294
+ newCheckedIds[id] = true;
295
+ } else {
296
+ delete newCheckedIds[id];
297
+ }
298
+ }
299
+ return newCheckedIds;
300
+ });
301
+ };
302
+
303
+ const [searchFilters, setSearchFilters] = useState<SearchFilter[]>([]);
304
+
305
+ const { itemsRes, allCount } = useNamespacesQuery(
306
+ db,
307
+ selectedNamespace,
308
+ currentNav?.where,
309
+ resolveFilters(currentNav?.where, currentNav?.filters, searchFilters),
310
+ limit,
311
+ offset,
312
+ sortAttr,
313
+ sortAsc,
314
+ );
315
+
316
+ const allItems =
317
+ itemsRes.data?.[selectedNamespace?.name ?? ''] ?? fallbackItems;
318
+
319
+ function getSelectedRows(
320
+ allItems: ({ id: string } & Record<string, any>)[],
321
+ checkedIds: Record<string, true | false>,
322
+ ) {
323
+ return allItems.filter((item) => checkedIds[item.id]);
324
+ }
325
+
326
+ const numPages = allCount ? Math.ceil(allCount / limit) : 1;
327
+
328
+ const currentPage = offset / limit + 1;
329
+
330
+ const [localDates, setLocalDates] = useLocalStorage('localDates', false);
331
+
332
+ const handleUploadFile = async () => {
333
+ try {
334
+ setUploadingFile(true);
335
+ if (selectedFiles.length === 0) {
336
+ return;
337
+ }
338
+
339
+ const [file] = selectedFiles;
340
+ const success = await upload(
341
+ explorerProps.adminToken,
342
+ explorerProps.appId,
343
+ file,
344
+ customPath,
345
+ explorerProps.apiURI,
346
+ );
347
+
348
+ if (success) {
349
+ setSelectedFiles([]);
350
+ setCustomPath('');
351
+ fileInputRef.current && (fileInputRef.current.value = '');
352
+ }
353
+
354
+ // await refreshFiles();
355
+ successToast('Successfully uploaded!');
356
+ } catch (err: any) {
357
+ console.error('Failed to upload:', err);
358
+ errorToast(`Failed to upload: ${err.body.message}`);
359
+ } finally {
360
+ setUploadingFile(false);
361
+ }
362
+ };
363
+
364
+ const tableItems = useMemo(() => {
365
+ return allItems;
366
+ }, [allItems]);
367
+
368
+ const tableRef = useRef<HTMLDivElement>(null);
369
+ const [leftShadowOpacity, setLeftShadowOpacity] = useState(0);
370
+ const [rightShadowOpacity, setRightShadowOpacity] = useState(1);
371
+ const [tableSmallerThanViewport, setTableSmallerThanViewport] =
372
+ useState(false);
373
+
374
+ const setMinViableColWidth = (columnId: string) => {
375
+ // for some reason the id column wants to resize bigger
376
+ if (table?.getColumn(columnId)?.columnDef.header === 'id') {
377
+ setColumnWidth(columnId, 285);
378
+ return;
379
+ }
380
+ const size = getTableWidthSize(columnId, 800);
381
+ setColumnWidth(columnId, size);
382
+ };
383
+
384
+ const setColumnWidth = (columnId: string, width = 200) => {
385
+ if (!selectedNamespace) {
386
+ return;
387
+ }
388
+ const result: Record<string, number> = {};
389
+ selectedNamespace?.attrs.forEach((attr) => {
390
+ result[attr.id + attr.name] =
391
+ table.getColumn(attr.id + attr.name)?.getSize() || 0;
392
+ });
393
+ table.setColumnSizing({
394
+ ...result,
395
+ [columnId]: width,
396
+ });
397
+ };
398
+
399
+ const columns = useMemo(() => {
400
+ const result: ColumnDef<any>[] = [];
401
+
402
+ result.push({
403
+ id: 'select-col',
404
+ enableSorting: false,
405
+ accessorFn: () => null,
406
+ enableHiding: false,
407
+ enableResizing: false,
408
+ size: 52,
409
+ header: ({ table }) => {
410
+ return (
411
+ <Checkbox
412
+ className="relative z-10 text-[#2563EB] dark:checked:border-[#2563EB] dark:checked:bg-[#2563EB]"
413
+ style={{
414
+ pointerEvents: 'auto',
415
+ }}
416
+ checked={table.getIsAllRowsSelected()}
417
+ onChange={(checked) => {
418
+ if (checked) {
419
+ table.toggleAllRowsSelected();
420
+ // Use the first item as the last selected ID
421
+ if (allItems.length > 0) {
422
+ lastSelectedIdRef.current = allItems[0].id as string;
423
+ }
424
+ } else {
425
+ setCheckedIds({});
426
+ lastSelectedIdRef.current = null;
427
+ }
428
+ }}
429
+ />
430
+ );
431
+ },
432
+ cell: ({ row, column }) => {
433
+ return (
434
+ <div className="flex h-full w-full items-center gap-2">
435
+ <Checkbox
436
+ className="relative z-10 text-[#2563EB] dark:checked:border-[#2563EB] dark:checked:bg-[#2563EB]"
437
+ checked={row.getIsSelected()}
438
+ onChange={(_, e) => {
439
+ const isShiftPressed = e.nativeEvent
440
+ ? (e.nativeEvent as MouseEvent).shiftKey
441
+ : false;
442
+
443
+ if (isShiftPressed && lastSelectedIdRef.current) {
444
+ handleRangeSelection(row.id as string, e.target.checked);
445
+ } else {
446
+ // Regular single click selection
447
+ setCheckedIds((prev) => {
448
+ const newCheckedIds = { ...prev };
449
+ if (e.target.checked) {
450
+ newCheckedIds[row.id] = true;
451
+ } else {
452
+ delete newCheckedIds[row.id];
453
+ }
454
+ return newCheckedIds;
455
+ });
456
+ }
457
+
458
+ lastSelectedIdRef.current = row.id;
459
+ }}
460
+ />
461
+ {readOnlyNs ? null : (
462
+ <button
463
+ type="button"
464
+ title="Edit row"
465
+ className="rounded-xs p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-neutral-100 dark:hover:bg-neutral-700"
466
+ onClick={() => setDialog({ type: 'edit-row', rowId: row.id })}
467
+ >
468
+ <PencilSquareIcon className="h-4 w-4 text-neutral-500 dark:text-neutral-400" />
469
+ </button>
470
+ )}
471
+ </div>
472
+ );
473
+ },
474
+ });
475
+
476
+ selectedNamespace?.attrs?.forEach((attr) => {
477
+ result.push({
478
+ id: attr.id + attr.name,
479
+ header: attr.name,
480
+ enableSorting: true,
481
+ enableResizing: true,
482
+ accessorFn: (row) => row[attr.name],
483
+ meta: {
484
+ sortable: attr.sortable || attr.name === 'id',
485
+ copyable: true,
486
+ isLink: attr.type === 'ref',
487
+ attr,
488
+ disablePadding: attr.namespace === '$files' && attr.name === 'url',
489
+ editable:
490
+ !readOnlyNs &&
491
+ selectedNamespace != null &&
492
+ isEditableExplorerAttr(selectedNamespace, attr),
493
+ } satisfies TableColMeta,
494
+ cell: (info) => {
495
+ if (
496
+ info.row.original[attr.name] === null ||
497
+ info.row.original[attr.name] === undefined
498
+ ) {
499
+ return <div className="h-1">-</div>;
500
+ }
501
+ if (attr.type === 'ref') {
502
+ const linkCount = info.row.original[attr.name].length;
503
+ return (
504
+ <div
505
+ className={cn(
506
+ 'h-1 translate-y-0.5',
507
+ linkCount < 1 && 'opacity-50',
508
+ )}
509
+ >
510
+ {linkCount} link{linkCount === 1 ? '' : 's'}
511
+ </div>
512
+ );
513
+ }
514
+
515
+ if (attr.namespace === '$files') {
516
+ if (attr.name === 'url') {
517
+ return (
518
+ <a
519
+ className="flex h-full w-full items-center pl-2 text-xs font-bold underline hover:text-black dark:hover:text-white"
520
+ href={info.row.original['url'] as string}
521
+ target="_blank"
522
+ >
523
+ View File
524
+ </a>
525
+ );
526
+ } else if (attr.name === 'size') {
527
+ return formatBytes(info.row.original[attr.name]);
528
+ }
529
+ }
530
+
531
+ if (attr.checkedDataType === 'boolean') {
532
+ return info.row.original[attr.name] ? 'true' : 'false';
533
+ }
534
+ if (attr.checkedDataType === 'date') {
535
+ const coerced = coerceToDate(info.row.original[attr.name]);
536
+
537
+ if (localDates) {
538
+ return coerced?.toLocaleString() || info.row.original[attr.name];
539
+ } else {
540
+ return info.row.original[attr.name];
541
+ }
542
+ }
543
+ return formatVal(info.row.original[attr.name]);
544
+ },
545
+ });
546
+ });
547
+
548
+ return result;
549
+ }, [selectedNamespace, readOnlyNs, localDates]);
550
+
551
+ const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({});
552
+
553
+ const distributeRemainingWidth = () => {
554
+ const result = Object.entries(table.getState().columnSizing).reduce(
555
+ (acc, [colId, width]) => {
556
+ if (colVisiblity.visibility[colId] !== false) {
557
+ return {
558
+ ...acc,
559
+ [colId]: width,
560
+ };
561
+ } else {
562
+ return acc;
563
+ }
564
+ },
565
+ {} as Record<string, number>,
566
+ );
567
+
568
+ const fullWidth = tableRef.current?.clientWidth || -1;
569
+
570
+ const totalWidth = Object.values(result).reduce(
571
+ (acc, width) => acc + width,
572
+ 0,
573
+ );
574
+ const remainingWidth = fullWidth - 52 - totalWidth;
575
+
576
+ if (remainingWidth > 0) {
577
+ const numColumns = Object.keys(result).length;
578
+ const extraWidth = remainingWidth / numColumns;
579
+
580
+ Object.keys(result).forEach((key) => {
581
+ result[key] += extraWidth;
582
+ });
583
+ }
584
+ setTableSmallerThanViewport(false);
585
+ table.setColumnSizing(() => {
586
+ return { ...result };
587
+ });
588
+ };
589
+
590
+ const columnResizeMode = 'onChange';
591
+
592
+ const columnResizeDirection = 'ltr';
593
+
594
+ const colVisiblity = useColumnVisibility({
595
+ appId: explorerProps.appId,
596
+ attrs: selectedNamespace?.attrs,
597
+ namespaceId: selectedNamespace?.id,
598
+ });
599
+
600
+ const [columnOrder, setColumnOrder] = useState<string[]>(() =>
601
+ columns.map((c) => c.id!),
602
+ );
603
+
604
+ // Sync columnOrder when namespace changes
605
+ useLayoutEffect(() => {
606
+ if (selectedNamespace?.attrs) {
607
+ const savedOrder = localStorage.getItem(
608
+ `order-${selectedNamespace.id}-${explorerProps.appId}`,
609
+ );
610
+ if (savedOrder) {
611
+ setColumnOrder(JSON.parse(savedOrder));
612
+ } else {
613
+ const newOrder = selectedNamespace.attrs.map(
614
+ (attr) => attr.id + attr.name,
615
+ );
616
+ setColumnOrder(['select-col', ...newOrder]);
617
+ }
618
+ }
619
+ }, [selectedNamespace?.attrs]);
620
+
621
+ // Persist columnOrder to localStorage when it changes
622
+ useEffect(() => {
623
+ if (selectedNamespace?.id) {
624
+ localStorage.setItem(
625
+ `order-${selectedNamespace.id}-${explorerProps.appId}`,
626
+ JSON.stringify(columnOrder),
627
+ );
628
+ }
629
+ }, [columnOrder, selectedNamespace?.id]);
630
+
631
+ const [checkedIds, setCheckedIds] = useState<Record<string, true | false>>(
632
+ {},
633
+ );
634
+
635
+ // Clear selection & search filter when namespace changes
636
+ useEffect(() => {
637
+ setCheckedIds({});
638
+ setSearchFilters([]);
639
+ lastSelectedIdRef.current = null;
640
+ }, [selectedNamespace?.id]);
641
+
642
+ const numItemsSelected = Object.keys(checkedIds).length;
643
+ const rowText =
644
+ sanitizedNsName === '$files'
645
+ ? numItemsSelected === 1
646
+ ? 'file'
647
+ : 'files'
648
+ : numItemsSelected === 1
649
+ ? 'row'
650
+ : 'rows';
651
+
652
+ const table = useReactTable({
653
+ columnResizeDirection,
654
+ columnResizeMode,
655
+ onColumnVisibilityChange: colVisiblity.setVisibility,
656
+ columns: columns,
657
+ data: tableItems,
658
+ enableColumnResizing: true,
659
+ enableRowSelection: true,
660
+ getCoreRowModel: getCoreRowModel(),
661
+ getRowId: (row) => row.id,
662
+ onColumnOrderChange: setColumnOrder,
663
+ onRowSelectionChange: setCheckedIds,
664
+ onColumnSizingChange: setColumnSizing,
665
+ state: {
666
+ columnSizing: columnSizing,
667
+ columnOrder,
668
+ columnVisibility: colVisiblity.visibility,
669
+ rowSelection: checkedIds,
670
+ },
671
+ });
672
+
673
+ const [isShiftPressed, setIsShiftPressed] = useState(false);
674
+
675
+ useEffect(() => {
676
+ const handleKeyDown = (e: KeyboardEvent) => {
677
+ if (e.key === 'Shift') {
678
+ setIsShiftPressed(true);
679
+ }
680
+ };
681
+
682
+ const handleKeyUp = (e: KeyboardEvent) => {
683
+ if (e.key === 'Shift') {
684
+ setIsShiftPressed(false);
685
+ }
686
+ };
687
+
688
+ const handleWindowBlur = () => {
689
+ setIsShiftPressed(false);
690
+ };
691
+
692
+ window.addEventListener('keydown', handleKeyDown);
693
+ window.addEventListener('keyup', handleKeyUp);
694
+ window.addEventListener('blur', handleWindowBlur);
695
+
696
+ return () => {
697
+ window.removeEventListener('keydown', handleKeyDown);
698
+ window.removeEventListener('keyup', handleKeyUp);
699
+ window.removeEventListener('blur-sm', handleWindowBlur);
700
+ };
701
+ }, []);
702
+
703
+ const [dropdownOpen, setDropdownOpen] = useState(false);
704
+
705
+ function handleDragEnd(event: DragEndEvent) {
706
+ const { active, over } = event;
707
+ // Prevent dragging the select column or dragging over it
708
+ if (
709
+ active &&
710
+ over &&
711
+ active.id !== over.id &&
712
+ active.id !== 'select-col' &&
713
+ over.id !== 'select-col'
714
+ ) {
715
+ setColumnOrder((columnOrder) => {
716
+ const oldIndex = columnOrder.indexOf(active.id as string);
717
+ const newIndex = columnOrder.indexOf(over.id as string);
718
+ return arrayMove(columnOrder, oldIndex, newIndex); //this is just a splice util
719
+ });
720
+ }
721
+ }
722
+
723
+ const selectedEditableItem = useMemo(
724
+ () => allItems.find((i) => i.id === editableRowId),
725
+ [allItems.length, editableRowId],
726
+ );
727
+
728
+ // Handle scroll to update shadow opacity
729
+ useEffect(() => {
730
+ const tableElement = tableRef.current;
731
+ if (!tableElement) return;
732
+
733
+ const handleScroll = () => {
734
+ const tableWidth = table.getCenterTotalSize();
735
+ const viewportWidth = tableElement.clientWidth;
736
+
737
+ setTableSmallerThanViewport(tableWidth < viewportWidth - 5);
738
+
739
+ const { scrollLeft, scrollWidth, clientWidth } = tableElement;
740
+ const maxScroll = scrollWidth - clientWidth;
741
+ if (maxScroll <= 0) {
742
+ setLeftShadowOpacity(0);
743
+ setRightShadowOpacity(0);
744
+ return;
745
+ }
746
+ const leftOpacity = Math.min(scrollLeft / 30, 1);
747
+ setLeftShadowOpacity(leftOpacity);
748
+
749
+ const rightOpacity = Math.min((maxScroll - scrollLeft) / 30, 1);
750
+ setRightShadowOpacity(rightOpacity);
751
+ };
752
+
753
+ handleScroll();
754
+ tableElement.addEventListener('scroll', handleScroll);
755
+
756
+ const resizeObserver = new ResizeObserver(handleScroll);
757
+ resizeObserver.observe(tableElement);
758
+ const tableContent = tableElement.firstElementChild;
759
+ if (tableContent) {
760
+ resizeObserver.observe(tableContent);
761
+ }
762
+
763
+ window.addEventListener('resize', handleScroll);
764
+
765
+ return () => {
766
+ tableElement.removeEventListener('scroll', handleScroll);
767
+ resizeObserver.disconnect();
768
+ window.removeEventListener('resize', handleScroll);
769
+ };
770
+ }, [selectedNamespace, tableItems]);
771
+
772
+ const sensors = useSensors(
773
+ useSensor(MouseSensor, {}),
774
+ useSensor(TouchSensor, {}),
775
+ useSensor(KeyboardSensor, {}),
776
+ );
777
+
778
+ // history.items is a list of PAST histories, not including current
779
+ const showBackButton = history.items.length >= 1;
780
+
781
+ const transformAttrNameToWidth = (name: string) => {
782
+ if (name === 'id') {
783
+ return 140;
784
+ }
785
+ if (name === 'url') {
786
+ return 120;
787
+ }
788
+ return name.length * 7.2 + 50;
789
+ };
790
+ // evenly space width of columns on first render
791
+ useLayoutEffect(() => {
792
+ if (selectedNamespace?.id) {
793
+ if (
794
+ localStorage.getItem(
795
+ `$sizing-${selectedNamespace.id}-${explorerProps.appId}`,
796
+ )
797
+ ) {
798
+ const savedSizing = JSON.parse(
799
+ localStorage.getItem(
800
+ `sizing-${selectedNamespace.id}-${explorerProps.appId}`,
801
+ ) || '{}',
802
+ );
803
+ table.setColumnSizing(() => {
804
+ return { ...savedSizing };
805
+ });
806
+ return;
807
+ }
808
+
809
+ const fullWidth = tableRef.current?.clientWidth || -1;
810
+ const result: Record<string, number> = {};
811
+
812
+ selectedNamespace?.attrs.forEach((attr) => {
813
+ result[attr.id + attr.name] = transformAttrNameToWidth(attr.name);
814
+ });
815
+
816
+ const totalWidth = Object.values(result).reduce(
817
+ (acc, width) => acc + width,
818
+ 0,
819
+ );
820
+
821
+ // Distribute the remaining width equally
822
+ const remainingWidth = fullWidth - 52 - totalWidth;
823
+ if (remainingWidth > 0) {
824
+ const numColumns = Object.keys(result).length;
825
+ const extraWidth = remainingWidth / numColumns;
826
+
827
+ Object.keys(result).forEach((key) => {
828
+ result[key] += extraWidth;
829
+ });
830
+ }
831
+
832
+ table.setColumnSizing(result);
833
+ }
834
+ }, [tableRef.current, selectedNamespace]);
835
+
836
+ if (!selectedNamespace) {
837
+ return null;
838
+ }
839
+
840
+ const selectedNamespaceId = selectedNamespace.id;
841
+
842
+ return (
843
+ <>
844
+ <Dialog
845
+ title="Delete Rows"
846
+ open={deleteDataConfirmationOpen}
847
+ onClose={() => setDeleteDataConfirmationOpen(false)}
848
+ >
849
+ {selectedNamespace ? (
850
+ <ActionForm className="min flex flex-col gap-4">
851
+ <h5 className="flex text-lg font-bold">Delete {rowText}</h5>
852
+
853
+ <Content>
854
+ Deleting is an{' '}
855
+ <strong className="dark:text-white">
856
+ irreversible operation
857
+ </strong>{' '}
858
+ and will{' '}
859
+ <strong className="dark:text-white">
860
+ delete {numItemsSelected} {rowText}{' '}
861
+ </strong>
862
+ associated with{' '}
863
+ <strong className="dark:text-white">
864
+ {selectedNamespace.name}
865
+ </strong>
866
+ .
867
+ </Content>
868
+
869
+ <ActionButton
870
+ type="submit"
871
+ disabled={readOnlyNs}
872
+ label={`Delete ${rowText}`}
873
+ submitLabel={`Deleting ${rowText}...`}
874
+ errorMessage={`Failed to delete ${rowText}`}
875
+ className="border-red-500 text-red-500"
876
+ title={
877
+ readOnlyNs
878
+ ? `The ${selectedNamespace?.name} namespace is read-only.`
879
+ : undefined
880
+ }
881
+ onClick={async () => {
882
+ try {
883
+ await db.transact(
884
+ Object.keys(checkedIds).map((id) =>
885
+ tx[selectedNamespace.name][id].delete(),
886
+ ),
887
+ );
888
+ } catch (error: any) {
889
+ const errorMessage = error.message;
890
+ errorToast(
891
+ `Failed to delete ${rowText}${errorMessage ? `: ${errorMessage}` : ''}`,
892
+ );
893
+ return;
894
+ }
895
+
896
+ setCheckedIds({});
897
+ setDeleteDataConfirmationOpen(false);
898
+ }}
899
+ />
900
+ </ActionForm>
901
+ ) : null}
902
+ </Dialog>
903
+ <Dialog
904
+ title="Add Row"
905
+ open={addItemDialogOpen}
906
+ onClose={() => setDialog(null)}
907
+ className="flex max-h-[calc(100dvh-4rem)] flex-col overflow-hidden"
908
+ >
909
+ {selectedNamespace ? (
910
+ <EditRowDialog
911
+ db={db}
912
+ item={{}}
913
+ namespace={selectedNamespace}
914
+ onClose={() => setDialog(null)}
915
+ />
916
+ ) : null}
917
+ </Dialog>
918
+ <Dialog
919
+ title="Edit Row"
920
+ open={!!selectedEditableItem}
921
+ onClose={() => setDialog(null)}
922
+ className="flex max-h-[calc(100dvh-4rem)] flex-col overflow-hidden"
923
+ >
924
+ {!!selectedNamespace && !!selectedEditableItem ? (
925
+ <EditRowDialog
926
+ db={db}
927
+ namespace={selectedNamespace}
928
+ item={selectedEditableItem}
929
+ focusAttr={
930
+ dialog?.type === 'edit-row' ? dialog.focusAttr : undefined
931
+ }
932
+ onClose={() => setDialog(null)}
933
+ />
934
+ ) : null}
935
+ </Dialog>
936
+ <Dialog
937
+ title="Edit Namespace"
938
+ stopFocusPropagation={true}
939
+ open={Boolean(editNs)}
940
+ onClose={() => setDialog(null)}
941
+ >
942
+ {selectedNamespace ? (
943
+ <EditNamespaceDialog
944
+ readOnly={readOnlyNs}
945
+ isSystemCatalogNs={isSystemCatalogNs}
946
+ db={db}
947
+ namespace={selectedNamespace}
948
+ namespaces={namespaces ?? []}
949
+ screen={
950
+ dialog?.type === 'edit-schema' ? dialog.screen : { kind: 'main' }
951
+ }
952
+ onScreenChange={(s) =>
953
+ setDialog(
954
+ { type: 'edit-schema', screen: s },
955
+ { history: 'replace' },
956
+ )
957
+ }
958
+ onClose={(p) => {
959
+ setDialog(null);
960
+ if (p?.ok) {
961
+ history.push({ namespace: namespaces?.[0].id });
962
+ }
963
+ }}
964
+ />
965
+ ) : null}
966
+ </Dialog>
967
+ <div className="flex flex-1 grow flex-col overflow-hidden bg-white dark:bg-neutral-800">
968
+ <div className="flex items-center overflow-hidden border-b border-b-gray-200 dark:border-neutral-700">
969
+ <div className="flex min-w-0 flex-1 flex-col justify-between py-2 md:flex-row md:items-center">
970
+ <div className="flex min-w-0 flex-1 items-center self-stretch overflow-hidden border-b px-2 py-1 pl-4 md:border-b-0 dark:border-neutral-700">
971
+ {showBackButton ? (
972
+ <ArrowLeftIcon
973
+ className="mr-4 inline cursor-pointer"
974
+ height="1rem"
975
+ onClick={() => history.pop()}
976
+ />
977
+ ) : null}
978
+ {currentNav.where ? (
979
+ <XMarkIcon
980
+ className="mr-4 inline cursor-pointer"
981
+ height="1rem"
982
+ onClick={() => {
983
+ history.push(
984
+ {
985
+ namespace: selectedNamespace.id,
986
+ },
987
+ true,
988
+ );
989
+ }}
990
+ />
991
+ ) : null}
992
+ <div className="relative min-w-0 flex-1 self-stretch [timeline-scope:--filter-scroll]">
993
+ <div className="flex h-full items-center overflow-x-auto font-mono text-xs whitespace-nowrap [scroll-timeline:--filter-scroll_inline] dark:text-white">
994
+ <strong>{selectedNamespace.name}</strong>{' '}
995
+ {currentNav.where ? (
996
+ <>
997
+ &nbsp;where&nbsp;
998
+ <strong>{currentNav.where[0]}</strong> ={' '}
999
+ <em className="rounded-xs border bg-white px-1 dark:border-neutral-700 dark:bg-neutral-800 dark:text-white">
1000
+ {JSON.stringify(currentNav.where[1])}
1001
+ </em>
1002
+ </>
1003
+ ) : null}
1004
+ {currentNav?.filters?.length ? (
1005
+ <span
1006
+ title={currentNav.filters
1007
+ .map(([attr, op, search]) => `${attr} ${op} ${search}`)
1008
+ .join(' || ')}
1009
+ >
1010
+ {currentNav.filters.map(([attr, op, search], i) => (
1011
+ <span key={attr}>
1012
+ <em className="rounded-xs border bg-white px-1 dark:border-neutral-700 dark:bg-neutral-800 dark:text-white">
1013
+ {attr} {op} {search}
1014
+ </em>
1015
+ {currentNav?.filters?.length &&
1016
+ i < currentNav.filters.length - 1
1017
+ ? ' || '
1018
+ : null}
1019
+ </span>
1020
+ ))}
1021
+ </span>
1022
+ ) : null}
1023
+ </div>
1024
+ <div
1025
+ aria-hidden="true"
1026
+ className="filter-shadow-l pointer-events-none absolute top-0 bottom-0 left-0 w-[30px] bg-linear-to-r from-black/10 via-black/0 to-transparent"
1027
+ />
1028
+ <div
1029
+ aria-hidden="true"
1030
+ className="filter-shadow-r pointer-events-none absolute top-0 right-0 bottom-0 w-[30px] bg-linear-to-l from-black/20 via-black/5 to-transparent"
1031
+ />
1032
+ </div>
1033
+ </div>
1034
+ <div className="flex justify-between gap-2 px-2 py-1 md:justify-start">
1035
+ <Button
1036
+ className="rounded-sm dark:bg-neutral-700/50"
1037
+ variant="secondary"
1038
+ size="mini"
1039
+ onClick={() => {
1040
+ setDialog({
1041
+ type: 'edit-schema',
1042
+ screen: { kind: 'main' },
1043
+ });
1044
+ }}
1045
+ >
1046
+ Edit Schema
1047
+ </Button>
1048
+ <SearchInput
1049
+ key={selectedNamespaceId}
1050
+ onSearchChange={(filters) => {
1051
+ setSearchFilters(filters);
1052
+ history.push(
1053
+ (prev) => ({
1054
+ ...prev!,
1055
+ filters: filters.length ? filters : undefined,
1056
+ }),
1057
+ true,
1058
+ );
1059
+ }}
1060
+ attrs={selectedNamespace?.attrs}
1061
+ initialFilters={currentNav?.filters || []}
1062
+ />
1063
+ </div>
1064
+ </div>
1065
+ </div>
1066
+ {selectedNamespace.name === '$files' ? (
1067
+ <div className="flex gap-2 px-2 py-2">
1068
+ <div className="flex w-full gap-2">
1069
+ <div className="flex shrink-0 gap-2">
1070
+ <input
1071
+ ref={fileInputRef}
1072
+ type="file"
1073
+ className="flex cursor-pointer rounded-sm border border-neutral-200 bg-transparent px-1 pt-1.5 text-sm shadow-xs transition-colors file:rounded-xs file:border-none file:border-neutral-200 file:bg-transparent file:p-2 file:pt-1 file:text-sm file:font-medium file:shadow-none placeholder:text-neutral-500 focus-visible:ring-1 focus-visible:ring-neutral-950 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-700 dark:bg-neutral-800 dark:text-white dark:file:border-neutral-700 dark:file:text-white dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-400"
1074
+ onChange={(e: React.ChangeEvent<any>) => {
1075
+ const files = e.target.files;
1076
+ setSelectedFiles(files);
1077
+ if (files?.[0]) {
1078
+ setCustomPath(files[0].name);
1079
+ }
1080
+ }}
1081
+ />
1082
+ <Button
1083
+ variant="primary"
1084
+ disabled={selectedFiles.length === 0}
1085
+ size="mini"
1086
+ loading={uploadingFile}
1087
+ onClick={handleUploadFile}
1088
+ className="rounded-sm"
1089
+ >
1090
+ {uploadingFile ? 'Uploading...' : 'Upload file'}
1091
+ </Button>
1092
+ </div>
1093
+ <div className="relative flex max-w-[67vw] min-w-0 flex-1 rounded-sm border border-neutral-200 focus-within:ring-2 focus-within:ring-blue-700 dark:border-neutral-700 dark:focus-within:ring-blue-500">
1094
+ <span className="absolute inset-y-0 left-0 flex items-center rounded-l bg-neutral-100 px-3 text-sm text-neutral-500 dark:bg-neutral-700 dark:text-neutral-400">
1095
+ File Path:
1096
+ </span>
1097
+ <input
1098
+ type="text"
1099
+ placeholder="Enter a custom path (optional)"
1100
+ value={customPath}
1101
+ onChange={(e) => setCustomPath(e.target.value)}
1102
+ className="h-9 w-full rounded-sm border-0 bg-transparent py-1 pr-3 pl-24 text-sm ring-0 placeholder:text-neutral-500 focus:outline-none dark:bg-neutral-800 dark:text-white dark:placeholder:text-neutral-400"
1103
+ />
1104
+ </div>
1105
+ </div>
1106
+ </div>
1107
+ ) : null}
1108
+ <div className="flex items-center justify-start space-x-2 border-b border-b-gray-200 p-1 text-xs dark:border-neutral-700 dark:text-white">
1109
+ {selectedNamespace.name !== '$files' ? (
1110
+ <Button
1111
+ disabled={readOnlyNs}
1112
+ title={
1113
+ readOnlyNs
1114
+ ? `The ${selectedNamespace?.name} namespace is read-only.`
1115
+ : undefined
1116
+ }
1117
+ size="mini"
1118
+ variant="secondary"
1119
+ onClick={() => {
1120
+ setDialog({ type: 'add-row' });
1121
+ }}
1122
+ >
1123
+ <PlusIcon width={12} />
1124
+ Add row
1125
+ </Button>
1126
+ ) : null}
1127
+ <div
1128
+ className={cn(
1129
+ 'px-1',
1130
+ selectedNamespace.name === '$files' && 'pb-1',
1131
+ )}
1132
+ >
1133
+ <Select
1134
+ className="rounded-sm text-xs"
1135
+ onChange={(opt) => {
1136
+ if (!opt) return;
1137
+
1138
+ const newLimit = parseInt(opt.value, 10);
1139
+ setLimit(newLimit);
1140
+ history.push((prev) => ({
1141
+ ...prev,
1142
+ limit: newLimit,
1143
+ }));
1144
+ }}
1145
+ value={`${limit}`}
1146
+ options={[
1147
+ { label: '25/page', value: '25' },
1148
+ { label: '50/page', value: '50' },
1149
+ { label: '100/page', value: '100' },
1150
+ ]}
1151
+ />
1152
+ </div>
1153
+ <div className="w-[62px]">
1154
+ {allCount !== undefined &&
1155
+ (allCount === 0 ? (
1156
+ <>No Results</>
1157
+ ) : (
1158
+ <>
1159
+ {(currentPage - 1) * limit + 1} -{' '}
1160
+ {Math.min(allCount, currentPage * limit)} of {allCount}
1161
+ </>
1162
+ ))}
1163
+ </div>
1164
+ <button
1165
+ className="flex items-center justify-center"
1166
+ disabled={currentPage <= 1}
1167
+ onClick={() => {
1168
+ setOffsets({
1169
+ ...offsets,
1170
+ [selectedNamespace.name]: Math.max(0, offset - limit),
1171
+ });
1172
+ history.push((prev) => ({
1173
+ ...prev,
1174
+ page: Math.max(1, currentPage - 1),
1175
+ }));
1176
+ }}
1177
+ >
1178
+ <ArrowLeftIcon
1179
+ className={cn('inline', {
1180
+ 'opacity-40': currentPage <= 1,
1181
+ })}
1182
+ height="1rem"
1183
+ />
1184
+ </button>
1185
+ <div className="flex items-center space-x-1 overflow-hidden">
1186
+ {[...new Array(numPages)].map((_, i) => {
1187
+ const page = i + 1;
1188
+ if (
1189
+ numPages > 6 &&
1190
+ page !== 1 &&
1191
+ page !== numPages &&
1192
+ page !== currentPage &&
1193
+ page !== currentPage - 1 &&
1194
+ page !== currentPage + 1
1195
+ ) {
1196
+ if (page === currentPage - 2 || page === currentPage + 2) {
1197
+ return <div key={page}>...</div>;
1198
+ }
1199
+ return null;
1200
+ }
1201
+ return (
1202
+ <button
1203
+ key={page}
1204
+ className={cn(
1205
+ 'rounded-md px-3 py-1 text-neutral-600 dark:text-neutral-300',
1206
+ page === currentPage
1207
+ ? 'bg-neutral-200 dark:bg-neutral-700'
1208
+ : 'hover:bg-neutral-100 dark:hover:bg-neutral-800',
1209
+ )}
1210
+ onClick={() => {
1211
+ setOffsets({
1212
+ ...offsets,
1213
+ [selectedNamespace.name]: i * limit,
1214
+ });
1215
+ history.push((prev) => ({
1216
+ ...prev,
1217
+ page,
1218
+ }));
1219
+ }}
1220
+ disabled={page === currentPage}
1221
+ >
1222
+ {page}
1223
+ </button>
1224
+ );
1225
+ })}
1226
+ </div>
1227
+ <button
1228
+ className="flex items-center justify-center"
1229
+ disabled={currentPage >= numPages}
1230
+ onClick={() => {
1231
+ setOffsets({
1232
+ ...offsets,
1233
+ [selectedNamespace.name]: offset + limit,
1234
+ });
1235
+ history.push((prev) => ({
1236
+ ...prev,
1237
+ page: Math.min(numPages, currentPage + 1),
1238
+ }));
1239
+ }}
1240
+ >
1241
+ <ArrowRightIcon
1242
+ className={cn('inline', {
1243
+ 'opacity-40': currentPage >= numPages,
1244
+ })}
1245
+ height="1rem"
1246
+ />
1247
+ </button>
1248
+ {numItemsSelected > 0 && (
1249
+ <div className="flex items-center gap-2 pl-4">
1250
+ <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
1251
+ <DropdownMenuTrigger>
1252
+ <Button
1253
+ onClick={() => {
1254
+ setDropdownOpen(true);
1255
+ }}
1256
+ variant="secondary"
1257
+ >
1258
+ <ArrowUpOnSquareIcon width={14} />
1259
+ Export ({numItemsSelected})
1260
+ </Button>
1261
+ </DropdownMenuTrigger>
1262
+ <DropdownMenuContent
1263
+ className="z-100"
1264
+ align="end"
1265
+ side="bottom"
1266
+ sideOffset={5}
1267
+ >
1268
+ <DropdownMenuItem
1269
+ onSelect={(e) => {
1270
+ e.preventDefault();
1271
+ const selectedRows = getSelectedRows(
1272
+ allItems,
1273
+ checkedIds,
1274
+ );
1275
+ exportToCSV(
1276
+ selectedRows,
1277
+ columns,
1278
+ selectedNamespace.name,
1279
+ isShiftPressed,
1280
+ );
1281
+ setDropdownOpen(false);
1282
+ }}
1283
+ className="flex items-center gap-2"
1284
+ >
1285
+ <Table width={12} />
1286
+ {isShiftPressed ? 'Download as CSV' : 'Copy as CSV'}
1287
+ </DropdownMenuItem>
1288
+ <DropdownMenuItem
1289
+ onSelect={(e) => {
1290
+ e.preventDefault();
1291
+ const selectedRows = getSelectedRows(
1292
+ allItems,
1293
+ checkedIds,
1294
+ );
1295
+ exportToMarkdown(
1296
+ selectedRows,
1297
+ columns,
1298
+ selectedNamespace.name,
1299
+ isShiftPressed,
1300
+ );
1301
+ setDropdownOpen(false);
1302
+ }}
1303
+ className="flex items-center gap-2"
1304
+ >
1305
+ <FileDown width={12} />
1306
+ {isShiftPressed
1307
+ ? 'Download as Markdown'
1308
+ : 'Copy as Markdown'}
1309
+ </DropdownMenuItem>
1310
+ <DropdownMenuItem
1311
+ onSelect={(e) => {
1312
+ e.preventDefault();
1313
+ const selectedRows = getSelectedRows(
1314
+ allItems,
1315
+ checkedIds,
1316
+ );
1317
+ exportToJSON(
1318
+ selectedRows,
1319
+ columns,
1320
+ selectedNamespace.name,
1321
+ isShiftPressed,
1322
+ );
1323
+ setDropdownOpen(false);
1324
+ }}
1325
+ className="flex items-center gap-2"
1326
+ >
1327
+ <CurlyBraces width={12} />
1328
+ {isShiftPressed ? 'Download as JSON' : 'Copy as JSON'}
1329
+ </DropdownMenuItem>
1330
+ {!isShiftPressed && (
1331
+ <>
1332
+ <DropdownMenuSeparator />
1333
+ <DropdownMenuItem
1334
+ className="text-xs text-neutral-500 dark:text-neutral-400"
1335
+ disabled
1336
+ >
1337
+ Hold shift to download as file
1338
+ </DropdownMenuItem>
1339
+ </>
1340
+ )}
1341
+ </DropdownMenuContent>
1342
+ </DropdownMenu>
1343
+ <Button
1344
+ onClick={() => {
1345
+ setDeleteDataConfirmationOpen(true);
1346
+ }}
1347
+ className="px-2"
1348
+ variant="destructive"
1349
+ >
1350
+ <TrashIcon width={14} />
1351
+ Delete Selected Rows
1352
+ </Button>
1353
+ </div>
1354
+ )}
1355
+ <div className="grow" />
1356
+ <div className="px-2">
1357
+ <ViewSettings
1358
+ localDates={localDates}
1359
+ setLocalDates={setLocalDates}
1360
+ visiblity={colVisiblity}
1361
+ />
1362
+ </div>
1363
+ </div>
1364
+
1365
+ <DndContext
1366
+ collisionDetection={closestCenter}
1367
+ modifiers={[restrictToHorizontalAxis]}
1368
+ onDragEnd={handleDragEnd}
1369
+ sensors={sensors}
1370
+ >
1371
+ <div className="relative flex-1 overflow-hidden bg-neutral-100 dark:bg-neutral-900/50">
1372
+ {!tableSmallerThanViewport && (
1373
+ <div
1374
+ className="absolute top-0 right-0 bottom-0 z-50 w-[30px] bg-linear-to-l from-black/20 via-black/5 to-transparent transition-opacity duration-150"
1375
+ style={{
1376
+ pointerEvents: 'none',
1377
+ opacity: rightShadowOpacity,
1378
+ display: rightShadowOpacity == 0 ? 'none' : undefined,
1379
+ }}
1380
+ />
1381
+ )}
1382
+ <div
1383
+ className="absolute top-0 bottom-0 left-0 z-50 w-[30px] bg-linear-to-r from-black/10 via-black/0 to-transparent transition-opacity duration-150"
1384
+ style={{
1385
+ pointerEvents: 'none',
1386
+ opacity: leftShadowOpacity,
1387
+ display: leftShadowOpacity == 0 ? 'none' : undefined,
1388
+ }}
1389
+ />
1390
+ <div ref={tableRef} className="h-full w-full overflow-auto">
1391
+ <div className="flex w-max items-start">
1392
+ <div
1393
+ style={{
1394
+ width: table.getCenterTotalSize(),
1395
+ }}
1396
+ className="z-0 text-left font-mono text-xs text-neutral-500 dark:text-neutral-400"
1397
+ >
1398
+ <div className="sticky top-0 z-10 border-r border-b border-gray-200 border-r-gray-200 bg-white text-neutral-700 shadow-sm dark:border-r-neutral-700 dark:border-b-neutral-600 dark:bg-[#303030] dark:text-neutral-300">
1399
+ {table.getHeaderGroups().map((headerGroup) => (
1400
+ <div className={'flex w-full'} key={headerGroup.id}>
1401
+ <SortableContext
1402
+ items={columnOrder}
1403
+ strategy={horizontalListSortingStrategy}
1404
+ >
1405
+ {headerGroup.headers.map((header, i) => (
1406
+ <TableHeader
1407
+ key={header.id}
1408
+ header={header}
1409
+ table={table}
1410
+ headerGroup={headerGroup}
1411
+ index={i}
1412
+ setMinViableColWidth={setMinViableColWidth}
1413
+ onSort={(attrName, currentAttr, currentAsc) => {
1414
+ history.push((prev) => ({
1415
+ ...prev,
1416
+ sortAttr: attrName,
1417
+ sortAsc:
1418
+ currentAttr !== attrName
1419
+ ? true
1420
+ : !currentAsc,
1421
+ }));
1422
+ }}
1423
+ currentSortAttr={currentNav?.sortAttr}
1424
+ currentSortAsc={currentNav?.sortAsc}
1425
+ />
1426
+ ))}
1427
+ </SortableContext>
1428
+ </div>
1429
+ ))}
1430
+ </div>
1431
+ <div>
1432
+ {table.getRowModel().rows.map((row) => (
1433
+ <div
1434
+ className="group flex border-r border-b border-r-gray-200 border-b-gray-200 bg-white dark:border-neutral-700 dark:border-r-neutral-700 dark:bg-neutral-800"
1435
+ key={row.id}
1436
+ >
1437
+ {row.getVisibleCells().map((cell) => (
1438
+ <SortableContext
1439
+ key={cell.id}
1440
+ items={columnOrder}
1441
+ strategy={horizontalListSortingStrategy}
1442
+ >
1443
+ <TableCell key={cell.id} cell={cell} />
1444
+ </SortableContext>
1445
+ ))}
1446
+ </div>
1447
+ ))}
1448
+ </div>
1449
+ </div>
1450
+ {tableSmallerThanViewport && (
1451
+ <div className="sticky top-0">
1452
+ <IconButton
1453
+ className="opacity-60"
1454
+ labelDirection="bottom"
1455
+ label="Fill Width"
1456
+ icon={<ArrowRightFromLine />}
1457
+ onClick={distributeRemainingWidth}
1458
+ />
1459
+ </div>
1460
+ )}
1461
+ </div>
1462
+ </div>
1463
+ </div>
1464
+ </DndContext>
1465
+ </div>
1466
+ </>
1467
+ );
1468
+ };
1469
+
1470
+ function Val({ data, pretty }: { data: any; pretty?: boolean }) {
1471
+ const props = useExplorerProps();
1472
+ const sanitized = formatVal(data, pretty);
1473
+
1474
+ if (pretty && isObject(data)) {
1475
+ return <Fence darkMode={props.darkMode} code={sanitized} language="json" />;
1476
+ }
1477
+
1478
+ return <>{sanitized}</>;
1479
+ }
1480
+
1481
+ // Storage
1482
+ export async function jsonFetch(
1483
+ input: RequestInfo,
1484
+ init: RequestInit | undefined,
1485
+ ): Promise<any> {
1486
+ const res = await fetch(input, init);
1487
+ const json = await res.json();
1488
+ return res.status === 200
1489
+ ? Promise.resolve(json)
1490
+ : Promise.reject({ status: res.status, body: json });
1491
+ }
1492
+
1493
+ function isHeaderSafe(value: string): boolean {
1494
+ return /^[\x20-\x7e\xa0-\xff]*$/.test(value);
1495
+ }
1496
+
1497
+ async function upload(
1498
+ token: string,
1499
+ appId: string,
1500
+ file: File,
1501
+ customFilename: string,
1502
+ apiUri: string,
1503
+ ): Promise<boolean> {
1504
+ const path = customFilename || file.name;
1505
+ const headers: Record<string, string> = {
1506
+ 'app-id': appId,
1507
+ app_id: appId,
1508
+ authorization: `Bearer ${token}`,
1509
+ 'content-type': file.type,
1510
+ };
1511
+ if (isHeaderSafe(path)) {
1512
+ headers['path'] = path;
1513
+ }
1514
+
1515
+ const url = `${apiUri}/dash/apps/${appId}/storage/upload?path=${encodeURIComponent(path)}`;
1516
+
1517
+ const data = await jsonFetch(url, {
1518
+ method: 'PUT',
1519
+ headers,
1520
+ body: file,
1521
+ });
1522
+
1523
+ return data;
1524
+ }