-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard-context.tsx
More file actions
701 lines (649 loc) · 24.6 KB
/
Copy pathdashboard-context.tsx
File metadata and controls
701 lines (649 loc) · 24.6 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import React, { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useConnection } from './connection-context';
import { useToast } from './toast-context';
import { ColumnInfo } from '@/types';
import { type MutationRequest } from '@/lib/mutation';
import { type Filter } from '@/lib/filters';
import type { SavedQuery } from '@/types';
import { useSavedQueries } from '../hooks/use-saved-queries';
import { db } from '@/lib/db';
import { type TableStatsData } from '../components/table-stats';
import { type Tab } from '../components/tab-bar';
interface DashboardContextType {
openTabs: Tab[];
activeTabId: string | undefined;
openTab: (name: string, type?: Tab['type']) => void;
closeTab: (tabId: string) => void;
setActiveTab: (tabId: string) => void;
closeAllTabs: () => void;
closeOtherTabs: (tabId: string) => void;
reorderTabs: (fromId: string, toId: string) => void;
toggleTabPin: (tabId: string) => void;
tables: string[];
schemas: string[];
selectedSchema: string;
selectedTable: string | undefined;
tableData: any[];
columns: string[];
schema: ColumnInfo[];
views: string[];
materializedViews: string[];
dbFunctions: any[];
relationships: any[];
indexes: any[];
isLoadingTables: boolean;
isLoading: boolean;
isLoadingSchema: boolean;
currentPage: number;
totalItems: number;
countIsEstimate: boolean;
sortColumn: string | null;
sortDirection: 'asc' | 'desc' | null;
visibleColumns: string[];
tableSearch: string;
tableFilters: Filter[];
setTableFilters: React.Dispatch<React.SetStateAction<Filter[]>>;
addTableFilter: (filter: Filter) => void;
removeTableFilter: (column: string) => void;
clearTableFilters: () => void;
error: string | null;
itemsPerPage: number;
setItemsPerPage: (size: number) => void;
primaryKeys: string[];
tableStats: TableStatsData | null;
isLoadingStats: boolean;
schemaMap: Record<string, string[]>;
tableRowCounts: Record<string, number>;
setSelectedSchema: (schema: string) => void;
setSelectedTable: (table: string | undefined) => void;
setCurrentPage: (page: number) => void;
setSortColumn: (col: string | null) => void;
setSortDirection: (dir: 'asc' | 'desc' | null) => void;
setVisibleColumns: React.Dispatch<React.SetStateAction<string[]>>;
setTableSearch: (search: string) => void;
loadTables: (schema?: string) => Promise<void>;
loadTableData: (tableName: string, page: number) => Promise<void>;
loadTableSchema: (tableName: string) => Promise<void>;
loadRelationships: (tableName: string) => Promise<void>;
handleSchemaChange: (schema: string) => void;
handleTableSelect: (table: string) => void;
handleSort: (column: string) => void;
mutateRow: (request: MutationRequest) => Promise<void>;
refreshTableData: () => Promise<void>;
openQueryTab: (label: string, rows: any[], cols: string[], executionTime: number) => void;
queryTabResults: Record<string, { rows: any[]; columns: string[]; executionTime: number }>;
isQueryTab: boolean;
openEditorTab: (initialQuery?: string) => void;
isEditorTab: boolean;
savedQueries: SavedQuery[];
saveQuery: (name: string, query: string, tags: string[]) => void;
updateSavedQuery: (id: string, updates: Partial<Pick<SavedQuery, 'name' | 'query' | 'tags'>>) => void;
deleteSavedQuery: (id: string) => void;
}
const DashboardContext = createContext<DashboardContextType | undefined>(undefined);
// Per-tab UI state (not data — TanStack caches the data)
interface TabUIState {
currentPage: number;
sortColumn: string | null;
sortDirection: 'asc' | 'desc' | null;
visibleColumns: string[];
tableSearch: string;
tableFilters: Filter[];
}
export function DashboardProvider({ children }: { children: React.ReactNode }) {
const { isConnected, databaseType, databaseName } = useConnection();
const { addToast } = useToast();
const queryClient = useQueryClient();
const [itemsPerPage, setItemsPerPage] = useState(100);
const {
savedQueries,
saveQuery,
updateQuery: updateSavedQuery,
deleteQuery: deleteSavedQuery,
} = useSavedQueries();
// UI state
const [selectedTable, setSelectedTable] = useState<string | undefined>();
const [selectedSchema, setSelectedSchema] = useState('public');
const [currentPage, setCurrentPage] = useState(1);
const [sortColumn, setSortColumn] = useState<string | null>(null);
const [sortDirection, setSortDirection] = useState<'asc' | 'desc' | null>(null);
const [visibleColumns, setVisibleColumns] = useState<string[]>([]);
const [tableSearch, setTableSearch] = useState('');
const [tableFilters, setTableFilters] = useState<Filter[]>([]);
const [openTabs, setOpenTabs] = useState<Tab[]>([]);
const [activeTabId, setActiveTabId] = useState<string | undefined>();
const [queryTabResults, setQueryTabResults] = useState<Record<string, { rows: any[]; columns: string[]; executionTime: number }>>({});
// Per-tab UI state cache
const tabUIStateRef = useRef<Record<string, TabUIState>>({});
const saveCurrentTabUIState = useCallback(() => {
if (!activeTabId) return;
tabUIStateRef.current[activeTabId] = {
currentPage,
sortColumn,
sortDirection,
visibleColumns,
tableSearch,
tableFilters,
};
}, [activeTabId, currentPage, sortColumn, sortDirection, visibleColumns, tableSearch, tableFilters]);
const restoreTabUIState = useCallback((tabId: string): boolean => {
const cached = tabUIStateRef.current[tabId];
if (!cached) return false;
setCurrentPage(cached.currentPage);
setSortColumn(cached.sortColumn);
setSortDirection(cached.sortDirection);
setVisibleColumns(cached.visibleColumns);
setTableSearch(cached.tableSearch);
setTableFilters(cached.tableFilters ?? []);
return true;
}, []);
const clearTabUIState = useCallback((tabId: string) => {
delete tabUIStateRef.current[tabId];
}, []);
// Tracks which database we've already restored tabs for, so we can gate
// localStorage writes until the one-shot restore has completed.
const tabsRestoredForRef = useRef<string | null>(null);
// Track which database we last set the default schema for. Resetting on
// databaseName change (not just on isConnected toggling off) is what
// makes Connections→another-DB without an explicit Disconnect work
// correctly. Previously `hasLoadedRef` was a once-per-session gate that
// never re-fired when the user swapped from a SQLite session to a
// Postgres one — `selectedSchema` stayed stuck at `main` against
// Postgres and every catalog query came back empty.
// Track the (databaseName, databaseType) tuple we last initialized for.
// Resetting on either change covers both "switched to a different DB"
// and "the backend kind changed underneath us" (e.g. saved connection
// round-trip lost the type and is now corrected).
const schemaInitializedForRef = useRef<string | null>(null);
useEffect(() => {
if (isConnected && databaseName) {
const key = `${databaseType}::${databaseName}`;
if (schemaInitializedForRef.current !== key) {
schemaInitializedForRef.current = key;
const defaultSchema = databaseType === 'sqlite'
? 'main'
: databaseType === 'mysql' && databaseName ? databaseName : 'public';
setSelectedSchema(defaultSchema);
}
}
if (!isConnected) {
schemaInitializedForRef.current = null;
tabsRestoredForRef.current = null;
setSelectedTable(undefined);
setOpenTabs([]);
setActiveTabId(undefined);
queryClient.clear();
}
}, [isConnected, databaseType, databaseName, queryClient]);
// Restore persisted tabs once per database connection. Tabs are stored
// per-database so switching DBs swaps the whole set; if the target DB has
// no saved tabs we clear the bar instead of leaking the previous DB's
// tabs (which point at tables that may not exist in the new schema).
useEffect(() => {
if (!isConnected || !databaseName) return;
if (tabsRestoredForRef.current === databaseName) return;
const isSwitching = tabsRestoredForRef.current !== null;
tabsRestoredForRef.current = databaseName;
// Switching DBs — drop any cached table data from the previous one so
// a same-named table in the new DB doesn't render stale rows.
if (isSwitching) queryClient.clear();
let restored = false;
try {
const raw = localStorage.getItem(`dbview-tabs-${databaseName}`);
if (raw) {
const parsed = JSON.parse(raw) as { openTabs?: Tab[]; activeTabId?: string };
if (Array.isArray(parsed.openTabs)) {
setOpenTabs(parsed.openTabs);
setActiveTabId(parsed.activeTabId);
const active = parsed.openTabs.find((t) => t.id === parsed.activeTabId);
if (active && active.type === 'table') {
setSelectedTable(active.label);
} else {
setSelectedTable(undefined);
}
restored = true;
}
}
} catch {
// corrupt entry — fall through to the clean-slate path below
}
if (!restored) {
setOpenTabs([]);
setActiveTabId(undefined);
setSelectedTable(undefined);
tabUIStateRef.current = {};
}
}, [isConnected, databaseName, queryClient]);
// Persist tab bar whenever it changes (after restore has completed).
useEffect(() => {
if (!isConnected || !databaseName) return;
if (tabsRestoredForRef.current !== databaseName) return;
try {
localStorage.setItem(
`dbview-tabs-${databaseName}`,
JSON.stringify({ openTabs, activeTabId })
);
} catch {
// quota exceeded or storage disabled — best effort
}
}, [openTabs, activeTabId, isConnected, databaseName]);
const schemasQuery = useQuery({
queryKey: ['schemas'],
queryFn: () => db.listSchemas(),
enabled: isConnected,
});
const tablesQuery = useQuery({
queryKey: ['tables', selectedSchema],
queryFn: () => db.listTables(selectedSchema),
enabled: isConnected,
});
const viewsQuery = useQuery({
queryKey: ['views', selectedSchema],
queryFn: () => db.listViews(selectedSchema),
enabled: isConnected,
});
const functionsQuery = useQuery({
queryKey: ['functions', selectedSchema],
queryFn: () => db.listFunctions(selectedSchema),
enabled: isConnected,
});
const schemaMapQuery = useQuery({
queryKey: ['schemaMap', selectedSchema],
queryFn: () => db.schemaMap(selectedSchema),
enabled: isConnected,
});
const tableCountsQuery = useQuery({
queryKey: ['tableCounts', selectedSchema],
queryFn: () => db.tableCounts(selectedSchema),
enabled: isConnected,
// Counts are estimates (Postgres reltuples / MySQL TABLE_ROWS) — keep
// them cached aggressively to avoid hammering the catalog on every
// sidebar mount.
staleTime: 1000 * 60 * 5,
});
const tableDataQuery = useQuery({
queryKey: ['tableData', selectedTable, selectedSchema, currentPage, sortColumn, sortDirection, itemsPerPage, tableFilters],
queryFn: async () => {
const offset = (currentPage - 1) * itemsPerPage;
const data = await db.tableRows({
table: selectedTable!,
schema: selectedSchema,
limit: itemsPerPage,
offset,
sortColumn: sortColumn ?? undefined,
sortDirection: sortDirection ?? undefined,
filters: tableFilters,
});
const rows = data.rows || [];
const cols = rows.length > 0 ? Object.keys(rows[0]) : [];
return {
rows,
columns: cols,
total: data.total || 0,
countIsEstimate: data.countIsEstimate || false,
};
},
enabled: isConnected && !!selectedTable,
});
const tableSchemaQuery = useQuery({
queryKey: ['tableSchema', selectedTable, selectedSchema],
queryFn: async () => {
const cols = await db.tableSchema(selectedTable!, selectedSchema);
return (cols as any[]).map((row: any) => ({
name: row.column_name ?? row.name,
type: row.data_type ?? row.type,
nullable: row.is_nullable === 'YES' || row.nullable === true,
default: row.column_default ?? row.default ?? null,
isPrimaryKey: row.is_primary_key ?? row.isPrimaryKey ?? false,
})) as ColumnInfo[];
},
enabled: isConnected && !!selectedTable,
});
const relationshipsQuery = useQuery({
queryKey: ['relationships', selectedTable, selectedSchema],
queryFn: () => db.relationships(selectedTable!, selectedSchema),
enabled: isConnected && !!selectedTable,
});
const tableStatsQuery = useQuery({
queryKey: ['tableStats', selectedTable, selectedSchema],
queryFn: () => db.tableStats(selectedTable!, selectedSchema) as Promise<TableStatsData | null>,
enabled: isConnected && !!selectedTable,
});
const tables = tablesQuery.data ?? [];
const schemas = schemasQuery.data ?? [];
const tableData = tableDataQuery.data?.rows ?? [];
// Prefer columns inferred from the first row (preserves the actual return
// order from the DB). For empty tables there are no rows to infer from, so
// fall back to the schema metadata — without this DataTable receives an
// empty columns array and renders neither headers nor the empty-row
// affordance, leaving a blank panel.
const columns = useMemo(() => {
const fromRows = tableDataQuery.data?.columns ?? [];
if (fromRows.length > 0) return fromRows;
return (tableSchemaQuery.data ?? []).map((c) => c.name);
}, [tableDataQuery.data?.columns, tableSchemaQuery.data]);
const totalItems = tableDataQuery.data?.total ?? 0;
const countIsEstimate = tableDataQuery.data?.countIsEstimate ?? false;
const schema = useMemo(() => tableSchemaQuery.data ?? [], [tableSchemaQuery.data]);
const views = viewsQuery.data?.views ?? [];
const materializedViews = viewsQuery.data?.materializedViews ?? [];
const dbFunctions = functionsQuery.data ?? [];
const relationships = relationshipsQuery.data?.relationships ?? [];
const indexes = relationshipsQuery.data?.indexes ?? [];
const schemaMap = schemaMapQuery.data ?? {};
const tableRowCounts = tableCountsQuery.data ?? {};
const tableStats = tableStatsQuery.data ?? null;
const isLoadingTables = tablesQuery.isLoading;
// `isFetching` covers reload-button refetches (when there's already
// cached data); `isLoading` alone would only spin on first load.
const isLoading = tableDataQuery.isLoading || tableDataQuery.isFetching;
const isLoadingSchema = tableSchemaQuery.isLoading;
const isLoadingStats = tableStatsQuery.isLoading;
const error = tableDataQuery.error?.message ?? tablesQuery.error?.message ?? null;
// Set visibleColumns when table data loads
useEffect(() => {
if (columns.length > 0 && visibleColumns.length === 0) {
setVisibleColumns(columns);
}
}, [columns, visibleColumns.length]);
const primaryKeys = useMemo(() => {
return schema.filter((col) => col.isPrimaryKey).map((col) => col.name);
}, [schema]);
const addTableFilter = useCallback((filter: Filter) => {
setTableFilters((prev) => {
// Replace any existing filter on the same column — single filter per
// column for v1 keeps the UI simple. Multi-condition is a follow-up.
const without = prev.filter((f) => f.column !== filter.column);
return [...without, filter];
});
setCurrentPage(1);
}, []);
const removeTableFilter = useCallback((column: string) => {
setTableFilters((prev) => prev.filter((f) => f.column !== column));
setCurrentPage(1);
}, []);
const clearTableFilters = useCallback(() => {
setTableFilters([]);
setCurrentPage(1);
}, []);
const loadTables = useCallback(async (schemaName?: string) => {
if (schemaName && schemaName !== selectedSchema) {
// Will be handled by query key change after setSelectedSchema
return;
}
await queryClient.invalidateQueries({ queryKey: ['tables', schemaName || selectedSchema] });
}, [queryClient, selectedSchema]);
const loadTableData = useCallback(async (tableName: string, _page: number) => {
await queryClient.invalidateQueries({ queryKey: ['tableData', tableName] });
}, [queryClient]);
const loadTableSchema = useCallback(async (tableName: string) => {
await queryClient.invalidateQueries({ queryKey: ['tableSchema', tableName] });
}, [queryClient]);
const loadRelationshipsImperative = useCallback(async (tableName: string) => {
await queryClient.invalidateQueries({ queryKey: ['relationships', tableName] });
}, [queryClient]);
const refreshTableData = useCallback(async () => {
if (!selectedTable) return;
// Use refetchQueries (not invalidateQueries) so the network call fires
// synchronously. invalidateQueries only marks the cache stale, which
// races against component-mount observation — feels broken to users
// who click the reload button on a table they're already viewing.
await queryClient.refetchQueries({ queryKey: ['tableData', selectedTable] });
}, [selectedTable, queryClient]);
const mutateRow = useCallback(async (request: MutationRequest) => {
await db.mutate(request);
addToast(`${request.type} successful`, 'success');
await refreshTableData();
}, [addToast, refreshTableData]);
const openTab = useCallback((name: string, type: Tab['type'] = 'table') => {
const tabId = `${type}:${name}`;
if (tabId === activeTabId) return;
saveCurrentTabUIState();
setOpenTabs((prev) => {
if (prev.some((t) => t.id === tabId)) return prev;
return [...prev, { id: tabId, label: name, type }];
});
setActiveTabId(tabId);
setSelectedTable(name);
if (!restoreTabUIState(tabId)) {
setCurrentPage(1);
setSortColumn(null);
setSortDirection(null);
setVisibleColumns([]);
setTableSearch('');
setTableFilters([]);
}
}, [activeTabId, saveCurrentTabUIState, restoreTabUIState]);
const closeTab = useCallback((tabId: string) => {
clearTabUIState(tabId);
if (tabId.startsWith('query:')) {
setQueryTabResults((prev) => {
const next = { ...prev };
delete next[tabId];
return next;
});
}
if (tabId.startsWith('editor:') && typeof window !== 'undefined') {
try {
localStorage.removeItem(`dbview-editor-${tabId}`);
} catch {
// ignore
}
}
setOpenTabs((prev) => {
const next = prev.filter((t) => t.id !== tabId);
if (tabId === activeTabId) {
const closedIndex = prev.findIndex((t) => t.id === tabId);
const newActive = next[Math.min(closedIndex, next.length - 1)];
if (newActive) {
setActiveTabId(newActive.id);
if (newActive.type === 'query' || newActive.type === 'editor') {
setSelectedTable(undefined);
} else {
setSelectedTable(newActive.label);
if (!restoreTabUIState(newActive.id)) {
setCurrentPage(1);
setSortColumn(null);
setSortDirection(null);
setVisibleColumns([]);
setTableSearch('');
setTableFilters([]);
}
}
} else {
setActiveTabId(undefined);
setSelectedTable(undefined);
}
}
return next;
});
}, [activeTabId, clearTabUIState, restoreTabUIState]);
const setActiveTab = useCallback((tabId: string) => {
if (tabId === activeTabId) return;
saveCurrentTabUIState();
setActiveTabId(tabId);
setOpenTabs((prev) => {
const tab = prev.find((t) => t.id === tabId);
if (tab) {
if (tab.type === 'query' || tab.type === 'editor') {
setSelectedTable(undefined);
} else {
setSelectedTable(tab.label);
if (!restoreTabUIState(tabId)) {
setCurrentPage(1);
setSortColumn(null);
setSortDirection(null);
setVisibleColumns([]);
setTableSearch('');
setTableFilters([]);
}
}
}
return prev;
});
}, [activeTabId, saveCurrentTabUIState, restoreTabUIState]);
const editorCounterRef = useRef(0);
const openEditorTab = useCallback((initialQuery?: string) => {
editorCounterRef.current += 1;
const tabId = `editor:${Date.now()}_${editorCounterRef.current}`;
const label = `SQL Editor ${editorCounterRef.current}`;
if (initialQuery && typeof window !== 'undefined') {
// Seed the per-tab editor storage so QueryEditor reads it on mount.
try {
localStorage.setItem(`dbview-editor-${tabId}`, initialQuery);
} catch {
// ignore
}
}
saveCurrentTabUIState();
setOpenTabs((prev) => [...prev, { id: tabId, label, type: 'editor' }]);
setActiveTabId(tabId);
setSelectedTable(undefined);
}, [saveCurrentTabUIState]);
const openQueryTab = useCallback((label: string, rows: any[], cols: string[], executionTime: number) => {
const tabId = `query:${label}_${Date.now()}`;
saveCurrentTabUIState();
setOpenTabs((prev) => [...prev, { id: tabId, label, type: 'query' }]);
setActiveTabId(tabId);
setSelectedTable(undefined);
setQueryTabResults((prev) => ({ ...prev, [tabId]: { rows, columns: cols, executionTime } }));
}, [saveCurrentTabUIState]);
const closeAllTabs = useCallback(() => {
setOpenTabs([]);
setActiveTabId(undefined);
setSelectedTable(undefined);
setQueryTabResults({});
}, []);
const closeOtherTabs = useCallback((tabId: string) => {
setOpenTabs((prev) => prev.filter((t) => t.id === tabId));
setActiveTabId(tabId);
}, []);
const reorderTabs = useCallback((fromId: string, toId: string) => {
setOpenTabs((prev) => {
const fromIdx = prev.findIndex((t) => t.id === fromId);
const toIdx = prev.findIndex((t) => t.id === toId);
if (fromIdx === -1 || toIdx === -1) return prev;
const next = [...prev];
const [moved] = next.splice(fromIdx, 1);
next.splice(toIdx, 0, moved);
return next;
});
}, []);
const toggleTabPin = useCallback((tabId: string) => {
setOpenTabs((prev) =>
prev.map((t) => (t.id === tabId ? { ...t, pinned: !t.pinned } : t))
);
}, []);
const handleSchemaChange = useCallback((newSchema: string) => {
setSelectedSchema(newSchema);
setSelectedTable(undefined);
setOpenTabs([]);
setActiveTabId(undefined);
}, []);
const handleTableSelect = useCallback((table: string) => {
openTab(table, 'table');
}, [openTab]);
const handleSort = useCallback((column: string) => {
if (sortColumn === column) {
if (sortDirection === 'asc') {
setSortDirection('desc');
} else if (sortDirection === 'desc') {
setSortColumn(null);
setSortDirection(null);
}
} else {
setSortColumn(column);
setSortDirection('asc');
}
setCurrentPage(1);
}, [sortColumn, sortDirection]);
// Reset page on sort change
useEffect(() => {
setCurrentPage(1);
}, [sortColumn, sortDirection]);
return (
<DashboardContext.Provider
value={{
openTabs,
activeTabId,
openTab,
closeTab,
setActiveTab,
closeAllTabs,
reorderTabs,
toggleTabPin,
closeOtherTabs,
tables,
schemas,
selectedSchema,
selectedTable,
tableData,
columns,
schema,
views,
materializedViews,
dbFunctions,
relationships,
indexes,
isLoadingTables,
isLoading,
isLoadingSchema,
currentPage,
totalItems,
countIsEstimate,
sortColumn,
sortDirection,
visibleColumns,
tableSearch,
error,
itemsPerPage,
setItemsPerPage,
primaryKeys,
tableStats,
isLoadingStats,
schemaMap,
tableRowCounts,
setSelectedSchema,
setSelectedTable,
setCurrentPage,
setSortColumn,
setSortDirection,
setVisibleColumns,
setTableSearch,
tableFilters,
setTableFilters,
addTableFilter,
removeTableFilter,
clearTableFilters,
loadTables,
loadTableData,
loadTableSchema,
loadRelationships: loadRelationshipsImperative,
handleSchemaChange,
handleTableSelect,
handleSort,
mutateRow,
refreshTableData,
openQueryTab,
queryTabResults,
isQueryTab: activeTabId?.startsWith('query:') ?? false,
openEditorTab,
isEditorTab: activeTabId?.startsWith('editor:') ?? false,
savedQueries,
saveQuery,
updateSavedQuery,
deleteSavedQuery,
}}
>
{children}
</DashboardContext.Provider>
);
}
export function useDashboard() {
const context = useContext(DashboardContext);
if (context === undefined) {
throw new Error('useDashboard must be used within a DashboardProvider');
}
return context;
}