@mhjuma/traverse 0.1.0 → 0.2.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.
- package/CHANGELOG.md +31 -0
- package/package.json +1 -1
- package/src/components/Explorer/Explorer.spec.tsx +111 -0
- package/src/components/Explorer/Explorer.tsx +71 -6
- package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.ts +26 -0
- package/src/index.ts +2 -0
- package/src/services/state-service.spec.ts +16 -0
- package/src/services/state-service.ts +12 -5
- package/src/state/persistence.spec.ts +239 -0
- package/src/state/persistence.ts +140 -0
- package/src/state/reducer.spec.ts +134 -3
- package/src/state/reducer.ts +39 -14
- package/src/state/types.ts +6 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# @mhjuma/traverse
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 286839b: Persist Explorer tabs across sessions and accept a custom default query.
|
|
8
|
+
|
|
9
|
+
- New optional `initialQuery` prop on `<Explorer />`. When set, it seeds the
|
|
10
|
+
editor on first load if there's no persisted snapshot and no `?query=`
|
|
11
|
+
URL parameter. Falls back to the package's `DEFAULT_QUERY` when omitted.
|
|
12
|
+
- New `explorerTabs` `StateService` store (persisted to IndexedDB and
|
|
13
|
+
mirrored to localStorage for synchronous bootstrap on page load).
|
|
14
|
+
- The Explorer reducer now hydrates `tabs`, `activeTabId`, and split-pane
|
|
15
|
+
state from a versioned snapshot. Stale connection ids on restored tabs
|
|
16
|
+
are remapped to the active connection so KQL is never lost. Invalid
|
|
17
|
+
split state is reset.
|
|
18
|
+
- The `tabs[]` and split slices are saved with a 300ms debounce on every
|
|
19
|
+
reducer transition that mutates them. Pending writes are flushed on
|
|
20
|
+
component unmount and on `pagehide` so edits made just before a refresh
|
|
21
|
+
or tab close are not dropped.
|
|
22
|
+
- Deep-links with `?query=` continue to win for the initial render and
|
|
23
|
+
are now treated as ephemeral: they bypass the snapshot on load AND do
|
|
24
|
+
not write back to it, so a shared link cannot clobber the user's
|
|
25
|
+
saved workspace.
|
|
26
|
+
- New exports: `loadSnapshot`, `saveSnapshot`, `clearSnapshot`,
|
|
27
|
+
`validateAndCleanSnapshot`, `extractSnapshot`, `SNAPSHOT_VERSION`,
|
|
28
|
+
and the `ExplorerTabsSnapshot` type.
|
|
29
|
+
|
|
30
|
+
The IndexedDB schema version is bumped to `2` to create the new object
|
|
31
|
+
store for existing users; no data migration is required.
|
package/package.json
CHANGED
|
@@ -61,6 +61,7 @@ vi.mock('../ExplorerWorkspace/ExplorerWorkspace.logic', () => ({
|
|
|
61
61
|
getQueryToRunFromEditor: vi.fn(() => ''),
|
|
62
62
|
KEYBOARD_SHORTCUTS: [],
|
|
63
63
|
createTab: vi.fn((q: string, title: string) => ({ id: '1', query: q, title, kql: '', connectionId: 'test-conn' })),
|
|
64
|
+
bumpTabCounterPast: vi.fn(),
|
|
64
65
|
loadConnections: vi.fn(() => [{ id: 'test-conn', name: 'Test Cluster', clusterUrl: 'https://help.kusto.windows.net', database: 'Telemetry', color: '#909d63' }]),
|
|
65
66
|
loadActiveConnectionId: vi.fn(() => 'test-conn'),
|
|
66
67
|
saveConnections: vi.fn(),
|
|
@@ -74,6 +75,16 @@ vi.mock('../ExplorerWorkspace/ExplorerWorkspace.logic', () => ({
|
|
|
74
75
|
DEFAULT_CONNECTION: { id: 'test-conn', name: 'Test Cluster', clusterUrl: 'https://help.kusto.windows.net', database: 'Telemetry', color: '#909d63' },
|
|
75
76
|
CONNECTION_COLORS: ['#909d63', '#6a8799', '#ebc17a', '#bc5653', '#b06698'],
|
|
76
77
|
}));
|
|
78
|
+
// Stub persistence so the save effect doesn't write to a real stateService
|
|
79
|
+
// and the createInitialState hydration path returns null deterministically.
|
|
80
|
+
vi.mock('../../state/persistence', () => ({
|
|
81
|
+
SNAPSHOT_VERSION: 1,
|
|
82
|
+
loadSnapshot: vi.fn(() => null),
|
|
83
|
+
saveSnapshot: vi.fn(),
|
|
84
|
+
clearSnapshot: vi.fn(),
|
|
85
|
+
validateAndCleanSnapshot: vi.fn(() => null),
|
|
86
|
+
extractSnapshot: vi.fn((s: { tabs: unknown[]; activeTabId: string }) => ({ version: 1, tabs: s.tabs, activeTabId: s.activeTabId, splitEnabled: false, splitDirection: 'vertical', splitTabId: null, focusedPane: 'primary' })),
|
|
87
|
+
}));
|
|
77
88
|
vi.mock('../ExplorerWorkspace/kqlLanguage', () => ({
|
|
78
89
|
registerKqlLanguage: vi.fn(),
|
|
79
90
|
setKqlSchemaResolver: vi.fn(),
|
|
@@ -613,3 +624,103 @@ describe('Explorer', () => {
|
|
|
613
624
|
expect(container.innerHTML).not.toBe('');
|
|
614
625
|
});
|
|
615
626
|
});
|
|
627
|
+
|
|
628
|
+
describe('Explorer snapshot persistence', () => {
|
|
629
|
+
let container: HTMLDivElement;
|
|
630
|
+
let root: ReturnType<typeof createRoot>;
|
|
631
|
+
let originalLocation: Location;
|
|
632
|
+
let saveSpy: ReturnType<typeof vi.fn>;
|
|
633
|
+
|
|
634
|
+
beforeEach(async () => {
|
|
635
|
+
vi.useFakeTimers();
|
|
636
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
637
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
638
|
+
container = document.createElement('div');
|
|
639
|
+
document.body.appendChild(container);
|
|
640
|
+
root = createRoot(container);
|
|
641
|
+
mockExplorerState.mockReturnValue(defaultExplorerState);
|
|
642
|
+
mockActiveTabs.mockReturnValue({ activeTab: mockActiveTab, splitTab: null });
|
|
643
|
+
originalLocation = window.location;
|
|
644
|
+
|
|
645
|
+
const persistence = await import('../../state/persistence');
|
|
646
|
+
saveSpy = persistence.saveSnapshot as unknown as ReturnType<typeof vi.fn>;
|
|
647
|
+
saveSpy.mockClear();
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
afterEach(() => {
|
|
651
|
+
act(() => { root.unmount(); });
|
|
652
|
+
container.remove();
|
|
653
|
+
vi.useRealTimers();
|
|
654
|
+
Object.defineProperty(window, 'location', { value: originalLocation, writable: true });
|
|
655
|
+
vi.restoreAllMocks();
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
function setUrlQuery(query: string | null) {
|
|
659
|
+
const search = query ? `?query=${encodeURIComponent(query)}` : '';
|
|
660
|
+
Object.defineProperty(window, 'location', {
|
|
661
|
+
value: { ...originalLocation, search } as Location,
|
|
662
|
+
writable: true,
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
it('persists the tab snapshot after the debounce window', () => {
|
|
667
|
+
setUrlQuery(null);
|
|
668
|
+
act(() => { root.render(React.createElement(Explorer)); });
|
|
669
|
+
expect(saveSpy).not.toHaveBeenCalled();
|
|
670
|
+
|
|
671
|
+
act(() => { vi.advanceTimersByTime(300); });
|
|
672
|
+
|
|
673
|
+
expect(saveSpy).toHaveBeenCalledTimes(1);
|
|
674
|
+
const arg = saveSpy.mock.calls[0][0] as { version: number; tabs: unknown[] };
|
|
675
|
+
expect(arg.version).toBe(1);
|
|
676
|
+
expect(Array.isArray(arg.tabs)).toBe(true);
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
it('does not persist when in deep-link (?query=) mode', () => {
|
|
680
|
+
setUrlQuery('SomeTable | take 5');
|
|
681
|
+
act(() => { root.render(React.createElement(Explorer)); });
|
|
682
|
+
act(() => { vi.advanceTimersByTime(1000); });
|
|
683
|
+
expect(saveSpy).not.toHaveBeenCalled();
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
it('does not persist on pagehide while in deep-link mode', () => {
|
|
687
|
+
setUrlQuery('SomeTable | take 5');
|
|
688
|
+
act(() => { root.render(React.createElement(Explorer)); });
|
|
689
|
+
act(() => { window.dispatchEvent(new Event('pagehide')); });
|
|
690
|
+
act(() => { vi.advanceTimersByTime(1000); });
|
|
691
|
+
expect(saveSpy).not.toHaveBeenCalled();
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
it('flushes a pending snapshot on component unmount', () => {
|
|
695
|
+
setUrlQuery(null);
|
|
696
|
+
act(() => { root.render(React.createElement(Explorer)); });
|
|
697
|
+
// Pending in the debounce window — debounce timer not yet elapsed.
|
|
698
|
+
expect(saveSpy).not.toHaveBeenCalled();
|
|
699
|
+
|
|
700
|
+
act(() => { root.unmount(); });
|
|
701
|
+
|
|
702
|
+
expect(saveSpy).toHaveBeenCalledTimes(1);
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
it('flushes a pending snapshot on pagehide', () => {
|
|
706
|
+
setUrlQuery(null);
|
|
707
|
+
act(() => { root.render(React.createElement(Explorer)); });
|
|
708
|
+
expect(saveSpy).not.toHaveBeenCalled();
|
|
709
|
+
|
|
710
|
+
act(() => { window.dispatchEvent(new Event('pagehide')); });
|
|
711
|
+
|
|
712
|
+
expect(saveSpy).toHaveBeenCalledTimes(1);
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
it('does not double-flush after the debounce already saved', () => {
|
|
716
|
+
setUrlQuery(null);
|
|
717
|
+
act(() => { root.render(React.createElement(Explorer)); });
|
|
718
|
+
act(() => { vi.advanceTimersByTime(300); });
|
|
719
|
+
expect(saveSpy).toHaveBeenCalledTimes(1);
|
|
720
|
+
|
|
721
|
+
act(() => { window.dispatchEvent(new Event('pagehide')); });
|
|
722
|
+
|
|
723
|
+
// Debounced write already cleared pendingRef; pagehide is a no-op.
|
|
724
|
+
expect(saveSpy).toHaveBeenCalledTimes(1);
|
|
725
|
+
});
|
|
726
|
+
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useMemo, useReducer } from 'react';
|
|
1
|
+
import { useEffect, useMemo, useReducer, useRef } from 'react';
|
|
2
2
|
|
|
3
3
|
import type { ExplorerColorConfig } from '../../colors';
|
|
4
4
|
import type { KustoClient } from '../../services/kusto';
|
|
@@ -6,6 +6,8 @@ import { KustoClientContext } from '../../context/KustoClientContext';
|
|
|
6
6
|
import { ExplorerColorProvider } from '../../context/ExplorerColorContext';
|
|
7
7
|
import { ExplorerStateContext, ExplorerDispatchContext } from '../../context/ExplorerStateContext';
|
|
8
8
|
import { explorerReducer, createInitialState } from '../../state';
|
|
9
|
+
import { SNAPSHOT_VERSION, saveSnapshot } from '../../state/persistence';
|
|
10
|
+
import type { ExplorerTabsSnapshot } from '../../state/persistence';
|
|
9
11
|
import { DEFAULT_QUERY, buildWellKnownClusters } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
|
|
10
12
|
import type { WellKnownCluster } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
|
|
11
13
|
import { ExplorerWorkspace } from '../ExplorerWorkspace/ExplorerWorkspace';
|
|
@@ -17,24 +19,87 @@ export interface ExplorerProps {
|
|
|
17
19
|
colors: ExplorerColorConfig;
|
|
18
20
|
clusters?: readonly WellKnownCluster[];
|
|
19
21
|
enableTabShortcuts?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Query to seed the editor with on first load when there is no
|
|
24
|
+
* persisted tab snapshot and no `?query=` URL parameter.
|
|
25
|
+
* Falls back to the package's built-in `DEFAULT_QUERY` when omitted.
|
|
26
|
+
*/
|
|
27
|
+
initialQuery?: string;
|
|
20
28
|
}
|
|
21
29
|
|
|
30
|
+
/**
|
|
31
|
+
* Debounce window (ms) for persisting the tab snapshot. Long enough to
|
|
32
|
+
* coalesce keystrokes into a single write, short enough that a casual
|
|
33
|
+
* tab-switch or refresh after typing still captures the user's edits.
|
|
34
|
+
*/
|
|
35
|
+
const SNAPSHOT_SAVE_DEBOUNCE_MS = 300;
|
|
36
|
+
|
|
22
37
|
export function Explorer(props: ExplorerProps) {
|
|
23
|
-
const initialQuery
|
|
38
|
+
const { initialQuery: providedInitialQuery } = props;
|
|
39
|
+
|
|
40
|
+
const { initialQuery, hasUrlQuery } = useMemo(() => {
|
|
24
41
|
try {
|
|
25
42
|
const params = new URLSearchParams(window.location.search);
|
|
26
43
|
const q = params.get('query');
|
|
27
44
|
if (q) {
|
|
28
|
-
return q;
|
|
45
|
+
return { initialQuery: q, hasUrlQuery: true };
|
|
29
46
|
}
|
|
30
47
|
} catch { /* ignore */ }
|
|
31
|
-
return DEFAULT_QUERY;
|
|
32
|
-
}, []);
|
|
48
|
+
return { initialQuery: providedInitialQuery ?? DEFAULT_QUERY, hasUrlQuery: false };
|
|
49
|
+
}, [providedInitialQuery]);
|
|
33
50
|
|
|
34
51
|
const defaultClusters = useMemo(() => buildWellKnownClusters(props.clusters ?? []), [props.clusters]);
|
|
35
|
-
const initArgs = useMemo(
|
|
52
|
+
const initArgs = useMemo(
|
|
53
|
+
() => ({ initialQuery, defaultClusters, skipSnapshot: hasUrlQuery }),
|
|
54
|
+
[initialQuery, defaultClusters, hasUrlQuery],
|
|
55
|
+
);
|
|
36
56
|
const [state, dispatch] = useReducer(explorerReducer, initArgs, createInitialState);
|
|
37
57
|
|
|
58
|
+
// Persist tab/split state with a small debounce.
|
|
59
|
+
//
|
|
60
|
+
// - Deep-link mode (URL `?query=`) treats the visible workspace as
|
|
61
|
+
// ephemeral. We never write it back to the snapshot store, so the
|
|
62
|
+
// user's normal saved workspace is preserved.
|
|
63
|
+
// - On rapid unmount or page-hide (refresh, tab close), a pending
|
|
64
|
+
// debounced save would otherwise be cancelled. `pendingRef` lets
|
|
65
|
+
// us flush the latest snapshot synchronously in those moments so
|
|
66
|
+
// recent edits are not dropped.
|
|
67
|
+
const { tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane } = state;
|
|
68
|
+
const pendingRef = useRef<ExplorerTabsSnapshot | null>(null);
|
|
69
|
+
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
if (hasUrlQuery) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const snap: ExplorerTabsSnapshot = {
|
|
75
|
+
version: SNAPSHOT_VERSION,
|
|
76
|
+
tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane,
|
|
77
|
+
};
|
|
78
|
+
pendingRef.current = snap;
|
|
79
|
+
const handle = setTimeout(() => {
|
|
80
|
+
saveSnapshot(snap);
|
|
81
|
+
pendingRef.current = null;
|
|
82
|
+
}, SNAPSHOT_SAVE_DEBOUNCE_MS);
|
|
83
|
+
return () => clearTimeout(handle);
|
|
84
|
+
}, [hasUrlQuery, tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane]);
|
|
85
|
+
|
|
86
|
+
useEffect(() => {
|
|
87
|
+
if (hasUrlQuery) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const flush = () => {
|
|
91
|
+
if (pendingRef.current) {
|
|
92
|
+
saveSnapshot(pendingRef.current);
|
|
93
|
+
pendingRef.current = null;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
window.addEventListener('pagehide', flush);
|
|
97
|
+
return () => {
|
|
98
|
+
window.removeEventListener('pagehide', flush);
|
|
99
|
+
flush();
|
|
100
|
+
};
|
|
101
|
+
}, [hasUrlQuery]);
|
|
102
|
+
|
|
38
103
|
return (
|
|
39
104
|
<KustoClientContext.Provider value={props.kustoClient}>
|
|
40
105
|
<ExplorerColorProvider value={props.colors}>
|
|
@@ -53,6 +53,32 @@ export function createTab(kql = '', title?: string, connectionId = ''): QueryTab
|
|
|
53
53
|
return { id, title: title ?? `Query ${n}`, kql, connectionId };
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Bump the internal tab counter so it sits past the highest numeric suffix
|
|
58
|
+
* in the supplied tab ids. Used by snapshot hydration to ensure ids created
|
|
59
|
+
* by subsequent createTab() calls do not collide with restored ids.
|
|
60
|
+
*/
|
|
61
|
+
export function bumpTabCounterPast(tabs: readonly QueryTab[]): void {
|
|
62
|
+
let max = 0;
|
|
63
|
+
for (const t of tabs) {
|
|
64
|
+
const m = /^tab-(\d+)$/.exec(t.id);
|
|
65
|
+
if (m) {
|
|
66
|
+
const n = Number(m[1]);
|
|
67
|
+
if (Number.isFinite(n) && n > max) {
|
|
68
|
+
max = n;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (max + 1 > tabCounter) {
|
|
73
|
+
tabCounter = max + 1;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Test-only helper to reset the module-scoped tab counter. */
|
|
78
|
+
export function _resetTabCounter(n: number = 1): void {
|
|
79
|
+
tabCounter = n;
|
|
80
|
+
}
|
|
81
|
+
|
|
56
82
|
export function nextQueryTitle(existingTabs: QueryTab[]): string {
|
|
57
83
|
const used = new Set(
|
|
58
84
|
existingTabs
|
package/src/index.ts
CHANGED
|
@@ -12,3 +12,5 @@ export type { KustoClient, KustoClientConfig, KustoTarget, KustoStateService, Ku
|
|
|
12
12
|
export { useKustoQuery, useKustoMgmtQuery } from './services/useKustoQuery';
|
|
13
13
|
export { bootstrapExplorer, useExplorerTheme } from './bootstrap';
|
|
14
14
|
export type { BootstrapExplorerOptions } from './bootstrap';
|
|
15
|
+
export { loadSnapshot, saveSnapshot, clearSnapshot, validateAndCleanSnapshot, extractSnapshot, SNAPSHOT_VERSION } from './state/persistence';
|
|
16
|
+
export type { ExplorerTabsSnapshot } from './state/persistence';
|
|
@@ -67,6 +67,22 @@ describe('StateService', () => {
|
|
|
67
67
|
expect(svc.get<{ name: string }[]>('explorerConnections', 'list')).toEqual([{ name: 'test' }]);
|
|
68
68
|
});
|
|
69
69
|
|
|
70
|
+
it('bootstraps explorerTabs from localStorage', () => {
|
|
71
|
+
const snapshot = {
|
|
72
|
+
version: 1,
|
|
73
|
+
tabs: [{ id: 'tab-1', title: 'Q', kql: 'Table | take 1', connectionId: 'conn-1' }],
|
|
74
|
+
activeTabId: 'tab-1',
|
|
75
|
+
splitEnabled: false,
|
|
76
|
+
splitDirection: 'vertical',
|
|
77
|
+
splitTabId: null,
|
|
78
|
+
focusedPane: 'primary',
|
|
79
|
+
};
|
|
80
|
+
const entry: StoreEntry = { value: snapshot, timestamp: Date.now() };
|
|
81
|
+
mockLS.setItem('traverse-state:explorerTabs:snapshot', JSON.stringify(entry));
|
|
82
|
+
const svc = new StateService();
|
|
83
|
+
expect(svc.get('explorerTabs', 'snapshot')).toEqual(snapshot);
|
|
84
|
+
});
|
|
85
|
+
|
|
70
86
|
it('skips expired bootstrap entries', () => {
|
|
71
87
|
const entry: StoreEntry = { value: 'old', timestamp: Date.now() - 999999999, ttl: 1 };
|
|
72
88
|
mockLS.setItem('traverse-state:config:stale', JSON.stringify(entry));
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// Types
|
|
11
11
|
// ---------------------------------------------------------------------------
|
|
12
12
|
|
|
13
|
-
export type StoreName = 'config' | 'queryCache' | 'explorerCache' | 'explorerConnections';
|
|
13
|
+
export type StoreName = 'config' | 'queryCache' | 'explorerCache' | 'explorerConnections' | 'explorerTabs';
|
|
14
14
|
|
|
15
15
|
export interface StoreEntry<T = unknown> {
|
|
16
16
|
value: T;
|
|
@@ -53,12 +53,15 @@ const STORE_CONFIGS: Record<StoreName, StoreConfig> = {
|
|
|
53
53
|
queryCache: { defaultTtlMs: 15 * 60 * 1000, persist: true, syncBootstrap: false },
|
|
54
54
|
explorerCache: { maxEntries: 200, persist: true, syncBootstrap: false },
|
|
55
55
|
explorerConnections: { persist: true, syncBootstrap: true },
|
|
56
|
+
explorerTabs: { persist: true, syncBootstrap: true },
|
|
56
57
|
};
|
|
57
58
|
|
|
58
59
|
export const STORE_NAMES = Object.keys(STORE_CONFIGS) as StoreName[];
|
|
59
60
|
|
|
60
61
|
const IDB_NAME = 'traverse-state';
|
|
61
|
-
|
|
62
|
+
// Bump when adding new stores to STORE_CONFIGS so onupgradeneeded creates them
|
|
63
|
+
// for existing users who already have the database at the prior version.
|
|
64
|
+
const IDB_VERSION = 2;
|
|
62
65
|
const LS_PREFIX = 'traverse-state:';
|
|
63
66
|
|
|
64
67
|
// ---------------------------------------------------------------------------
|
|
@@ -173,9 +176,13 @@ export class StateService {
|
|
|
173
176
|
this.listeners.set(name, new Map());
|
|
174
177
|
this.storeVersions.set(name, 0);
|
|
175
178
|
}
|
|
176
|
-
// Synchronous bootstrap
|
|
177
|
-
|
|
178
|
-
|
|
179
|
+
// Synchronous bootstrap from localStorage for stores with syncBootstrap: true.
|
|
180
|
+
// This avoids a flash of default state on page load before IndexedDB hydrates.
|
|
181
|
+
for (const name of STORE_NAMES) {
|
|
182
|
+
if (STORE_CONFIGS[name].syncBootstrap) {
|
|
183
|
+
this.bootstrapFromLocalStorage(name);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
179
186
|
}
|
|
180
187
|
|
|
181
188
|
// --- Bootstrap (sync) ---
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const mockStore = new Map<string, unknown>();
|
|
4
|
+
|
|
5
|
+
vi.mock('../services/state-service', () => ({
|
|
6
|
+
stateService: {
|
|
7
|
+
get: (_store: string, key: string) => mockStore.get(key) ?? null,
|
|
8
|
+
set: (_store: string, key: string, value: unknown) => { mockStore.set(key, value); },
|
|
9
|
+
delete: (_store: string, key: string) => { mockStore.delete(key); },
|
|
10
|
+
subscribe: () => () => {},
|
|
11
|
+
},
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
SNAPSHOT_VERSION,
|
|
16
|
+
loadSnapshot,
|
|
17
|
+
saveSnapshot,
|
|
18
|
+
clearSnapshot,
|
|
19
|
+
extractSnapshot,
|
|
20
|
+
validateAndCleanSnapshot,
|
|
21
|
+
} from './persistence';
|
|
22
|
+
import type { ExplorerTabsSnapshot } from './persistence';
|
|
23
|
+
import type { ExplorerState } from './types';
|
|
24
|
+
import type { KustoConnection, QueryTab } from '../components/ExplorerWorkspace/ExplorerWorkspace.logic';
|
|
25
|
+
|
|
26
|
+
const conn = (id: string): KustoConnection => ({
|
|
27
|
+
id, name: id, clusterUrl: `https://${id}.kusto.windows.net`, database: 'Db', color: '#000',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const tab = (id: string, connectionId = 'conn-1', kql = ''): QueryTab => ({
|
|
31
|
+
id, title: `Title ${id}`, kql, connectionId,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const baseSnapshot: ExplorerTabsSnapshot = {
|
|
35
|
+
version: SNAPSHOT_VERSION,
|
|
36
|
+
tabs: [tab('tab-1'), tab('tab-2')],
|
|
37
|
+
activeTabId: 'tab-1',
|
|
38
|
+
splitEnabled: false,
|
|
39
|
+
splitDirection: 'vertical',
|
|
40
|
+
splitTabId: null,
|
|
41
|
+
focusedPane: 'primary',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
describe('persistence', () => {
|
|
45
|
+
beforeEach(() => { mockStore.clear(); });
|
|
46
|
+
|
|
47
|
+
describe('saveSnapshot / loadSnapshot', () => {
|
|
48
|
+
it('round-trips a valid snapshot', () => {
|
|
49
|
+
saveSnapshot(baseSnapshot);
|
|
50
|
+
expect(loadSnapshot()).toEqual(baseSnapshot);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('returns null when no snapshot exists', () => {
|
|
54
|
+
expect(loadSnapshot()).toBeNull();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('returns null for snapshot with wrong version', () => {
|
|
58
|
+
saveSnapshot({ ...baseSnapshot, version: SNAPSHOT_VERSION + 1 });
|
|
59
|
+
expect(loadSnapshot()).toBeNull();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('returns null when the persisted value is malformed', () => {
|
|
63
|
+
mockStore.set('snapshot', { foo: 'bar' });
|
|
64
|
+
expect(loadSnapshot()).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('returns null for snapshot with non-array tabs', () => {
|
|
68
|
+
mockStore.set('snapshot', { ...baseSnapshot, tabs: 'oops' });
|
|
69
|
+
expect(loadSnapshot()).toBeNull();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('returns null when a tab has the wrong shape', () => {
|
|
73
|
+
mockStore.set('snapshot', { ...baseSnapshot, tabs: [{ id: 1, title: 't', kql: '', connectionId: '' }] });
|
|
74
|
+
expect(loadSnapshot()).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('returns null for invalid splitDirection', () => {
|
|
78
|
+
mockStore.set('snapshot', { ...baseSnapshot, splitDirection: 'diagonal' });
|
|
79
|
+
expect(loadSnapshot()).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('returns null for invalid focusedPane', () => {
|
|
83
|
+
mockStore.set('snapshot', { ...baseSnapshot, focusedPane: 'tertiary' });
|
|
84
|
+
expect(loadSnapshot()).toBeNull();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('returns null for non-string activeTabId', () => {
|
|
88
|
+
mockStore.set('snapshot', { ...baseSnapshot, activeTabId: 123 });
|
|
89
|
+
expect(loadSnapshot()).toBeNull();
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('returns null for non-boolean splitEnabled', () => {
|
|
93
|
+
mockStore.set('snapshot', { ...baseSnapshot, splitEnabled: 'yes' });
|
|
94
|
+
expect(loadSnapshot()).toBeNull();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('accepts splitTabId as a string', () => {
|
|
98
|
+
const snap = { ...baseSnapshot, splitEnabled: true, splitTabId: 'tab-2' };
|
|
99
|
+
saveSnapshot(snap);
|
|
100
|
+
expect(loadSnapshot()).toEqual(snap);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('rejects splitTabId of the wrong type', () => {
|
|
104
|
+
mockStore.set('snapshot', { ...baseSnapshot, splitTabId: 42 });
|
|
105
|
+
expect(loadSnapshot()).toBeNull();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe('clearSnapshot', () => {
|
|
110
|
+
it('removes a saved snapshot', () => {
|
|
111
|
+
saveSnapshot(baseSnapshot);
|
|
112
|
+
clearSnapshot();
|
|
113
|
+
expect(loadSnapshot()).toBeNull();
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
describe('extractSnapshot', () => {
|
|
118
|
+
it('pulls only the persisted slices from full ExplorerState', () => {
|
|
119
|
+
const state = {
|
|
120
|
+
connections: [conn('conn-1')],
|
|
121
|
+
tabs: [tab('tab-1')],
|
|
122
|
+
activeTabId: 'tab-1',
|
|
123
|
+
splitEnabled: true,
|
|
124
|
+
splitDirection: 'horizontal' as const,
|
|
125
|
+
splitTabId: 'tab-2',
|
|
126
|
+
focusedPane: 'secondary' as const,
|
|
127
|
+
// ...everything else, ignored:
|
|
128
|
+
schema: [], schemaSearch: '', expandedFolders: new Set<string>(),
|
|
129
|
+
expandedTables: new Set<string>(), schemaContextMenu: null,
|
|
130
|
+
loading: false, error: null, queryStartTime: null, runningQueryKey: null,
|
|
131
|
+
rows: null, columns: [], columnTypes: {}, elapsed: null, resultTime: null,
|
|
132
|
+
queryStats: null, resultSets: [], activeResultSet: 0, resultsTab: 'results' as const,
|
|
133
|
+
history: [], editorHeight: 50, hasSelection: false, canRecall: false,
|
|
134
|
+
} satisfies ExplorerState;
|
|
135
|
+
|
|
136
|
+
expect(extractSnapshot(state)).toEqual({
|
|
137
|
+
version: SNAPSHOT_VERSION,
|
|
138
|
+
tabs: [tab('tab-1')],
|
|
139
|
+
activeTabId: 'tab-1',
|
|
140
|
+
splitEnabled: true,
|
|
141
|
+
splitDirection: 'horizontal',
|
|
142
|
+
splitTabId: 'tab-2',
|
|
143
|
+
focusedPane: 'secondary',
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('validateAndCleanSnapshot', () => {
|
|
149
|
+
it('returns null when the snapshot has no tabs', () => {
|
|
150
|
+
const result = validateAndCleanSnapshot({ ...baseSnapshot, tabs: [] }, [conn('conn-1')], 'conn-1');
|
|
151
|
+
expect(result).toBeNull();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('passes through a fully valid snapshot unchanged', () => {
|
|
155
|
+
const conns = [conn('conn-1')];
|
|
156
|
+
const result = validateAndCleanSnapshot(baseSnapshot, conns, 'conn-1');
|
|
157
|
+
expect(result).toEqual(baseSnapshot);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('remaps tabs whose connectionId is missing to the fallback', () => {
|
|
161
|
+
const conns = [conn('conn-1')];
|
|
162
|
+
const snap: ExplorerTabsSnapshot = {
|
|
163
|
+
...baseSnapshot,
|
|
164
|
+
tabs: [tab('tab-1', 'gone'), tab('tab-2', 'conn-1')],
|
|
165
|
+
};
|
|
166
|
+
const result = validateAndCleanSnapshot(snap, conns, 'conn-1');
|
|
167
|
+
expect(result?.tabs[0].connectionId).toBe('conn-1');
|
|
168
|
+
expect(result?.tabs[1].connectionId).toBe('conn-1');
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('preserves kql when remapping a tab to the fallback connection', () => {
|
|
172
|
+
const conns = [conn('conn-1')];
|
|
173
|
+
const snap: ExplorerTabsSnapshot = {
|
|
174
|
+
...baseSnapshot,
|
|
175
|
+
tabs: [tab('tab-1', 'gone', 'MyTable | take 1')],
|
|
176
|
+
};
|
|
177
|
+
const result = validateAndCleanSnapshot(snap, conns, 'conn-1');
|
|
178
|
+
expect(result?.tabs[0].kql).toBe('MyTable | take 1');
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it('resets activeTabId to the first tab when it is missing', () => {
|
|
182
|
+
const conns = [conn('conn-1')];
|
|
183
|
+
const snap: ExplorerTabsSnapshot = {
|
|
184
|
+
...baseSnapshot,
|
|
185
|
+
tabs: [tab('tab-1'), tab('tab-2')],
|
|
186
|
+
activeTabId: 'tab-99',
|
|
187
|
+
};
|
|
188
|
+
const result = validateAndCleanSnapshot(snap, conns, 'conn-1');
|
|
189
|
+
expect(result?.activeTabId).toBe('tab-1');
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it('resets the split when splitTabId is not in the tab list', () => {
|
|
193
|
+
const conns = [conn('conn-1')];
|
|
194
|
+
const snap: ExplorerTabsSnapshot = {
|
|
195
|
+
...baseSnapshot,
|
|
196
|
+
splitEnabled: true,
|
|
197
|
+
splitTabId: 'tab-99',
|
|
198
|
+
focusedPane: 'secondary',
|
|
199
|
+
};
|
|
200
|
+
const result = validateAndCleanSnapshot(snap, conns, 'conn-1');
|
|
201
|
+
expect(result?.splitEnabled).toBe(false);
|
|
202
|
+
expect(result?.splitTabId).toBeNull();
|
|
203
|
+
expect(result?.focusedPane).toBe('primary');
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it('resets the split when splitTabId equals activeTabId', () => {
|
|
207
|
+
const conns = [conn('conn-1')];
|
|
208
|
+
const snap: ExplorerTabsSnapshot = {
|
|
209
|
+
...baseSnapshot,
|
|
210
|
+
splitEnabled: true,
|
|
211
|
+
splitTabId: 'tab-1',
|
|
212
|
+
activeTabId: 'tab-1',
|
|
213
|
+
focusedPane: 'secondary',
|
|
214
|
+
};
|
|
215
|
+
const result = validateAndCleanSnapshot(snap, conns, 'conn-1');
|
|
216
|
+
expect(result?.splitEnabled).toBe(false);
|
|
217
|
+
expect(result?.splitTabId).toBeNull();
|
|
218
|
+
expect(result?.focusedPane).toBe('primary');
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it('keeps a valid split untouched', () => {
|
|
222
|
+
const conns = [conn('conn-1')];
|
|
223
|
+
const snap: ExplorerTabsSnapshot = {
|
|
224
|
+
...baseSnapshot,
|
|
225
|
+
tabs: [tab('tab-1'), tab('tab-2')],
|
|
226
|
+
activeTabId: 'tab-1',
|
|
227
|
+
splitEnabled: true,
|
|
228
|
+
splitTabId: 'tab-2',
|
|
229
|
+
splitDirection: 'horizontal',
|
|
230
|
+
focusedPane: 'secondary',
|
|
231
|
+
};
|
|
232
|
+
const result = validateAndCleanSnapshot(snap, conns, 'conn-1');
|
|
233
|
+
expect(result?.splitEnabled).toBe(true);
|
|
234
|
+
expect(result?.splitTabId).toBe('tab-2');
|
|
235
|
+
expect(result?.splitDirection).toBe('horizontal');
|
|
236
|
+
expect(result?.focusedPane).toBe('secondary');
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
});
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistence helpers for the Explorer's tab/split state.
|
|
3
|
+
*
|
|
4
|
+
* Snapshots are written to the `explorerTabs` store on the shared
|
|
5
|
+
* StateService. That store is configured with `syncBootstrap: true`,
|
|
6
|
+
* which mirrors writes to localStorage so the snapshot is available
|
|
7
|
+
* synchronously on the next page load (no flash of the default tab).
|
|
8
|
+
*
|
|
9
|
+
* The snapshot is versioned. When the persisted shape changes in a
|
|
10
|
+
* non-backward-compatible way, bump SNAPSHOT_VERSION; older snapshots
|
|
11
|
+
* are then ignored and the Explorer falls back to its default
|
|
12
|
+
* initialization path.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { QueryTab, KustoConnection } from '../components/ExplorerWorkspace/ExplorerWorkspace.logic';
|
|
16
|
+
import { stateService } from '../services/state-service';
|
|
17
|
+
import type { ExplorerState } from './types';
|
|
18
|
+
|
|
19
|
+
const SNAPSHOT_STORE = 'explorerTabs' as const;
|
|
20
|
+
const SNAPSHOT_KEY = 'snapshot';
|
|
21
|
+
export const SNAPSHOT_VERSION = 1;
|
|
22
|
+
|
|
23
|
+
export interface ExplorerTabsSnapshot {
|
|
24
|
+
version: number;
|
|
25
|
+
tabs: QueryTab[];
|
|
26
|
+
activeTabId: string;
|
|
27
|
+
splitEnabled: boolean;
|
|
28
|
+
splitDirection: 'vertical' | 'horizontal';
|
|
29
|
+
splitTabId: string | null;
|
|
30
|
+
focusedPane: 'primary' | 'secondary';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isQueryTab(value: unknown): value is QueryTab {
|
|
34
|
+
if (!value || typeof value !== 'object') {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
const t = value as Record<string, unknown>;
|
|
38
|
+
return typeof t['id'] === 'string'
|
|
39
|
+
&& typeof t['title'] === 'string'
|
|
40
|
+
&& typeof t['kql'] === 'string'
|
|
41
|
+
&& typeof t['connectionId'] === 'string';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isSnapshot(value: unknown): value is ExplorerTabsSnapshot {
|
|
45
|
+
if (!value || typeof value !== 'object') {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
const s = value as Record<string, unknown>;
|
|
49
|
+
if (s['version'] !== SNAPSHOT_VERSION) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(s['tabs']) || !s['tabs'].every(isQueryTab)) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
if (typeof s['activeTabId'] !== 'string') {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
if (typeof s['splitEnabled'] !== 'boolean') {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
if (s['splitDirection'] !== 'vertical' && s['splitDirection'] !== 'horizontal') {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (s['splitTabId'] !== null && typeof s['splitTabId'] !== 'string') {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
if (s['focusedPane'] !== 'primary' && s['focusedPane'] !== 'secondary') {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Read and shape-validate the persisted snapshot.
|
|
75
|
+
* Returns null when no snapshot exists or the shape is invalid/outdated.
|
|
76
|
+
*/
|
|
77
|
+
export function loadSnapshot(): ExplorerTabsSnapshot | null {
|
|
78
|
+
const raw = stateService.get<unknown>(SNAPSHOT_STORE, SNAPSHOT_KEY);
|
|
79
|
+
return isSnapshot(raw) ? raw : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Validate the snapshot against the current connection list and clean
|
|
84
|
+
* up any stale references. Returns null when the snapshot has no usable
|
|
85
|
+
* tabs after cleaning.
|
|
86
|
+
*
|
|
87
|
+
* - Tabs whose `connectionId` is missing from `connections` are remapped
|
|
88
|
+
* to `fallbackConnectionId` so the user does not lose their KQL.
|
|
89
|
+
* - `activeTabId` is reset to the first tab if it is missing.
|
|
90
|
+
* - Split state is reset when `splitTabId` does not exist among the
|
|
91
|
+
* restored tabs or matches `activeTabId`.
|
|
92
|
+
*/
|
|
93
|
+
export function validateAndCleanSnapshot(
|
|
94
|
+
snapshot: ExplorerTabsSnapshot,
|
|
95
|
+
connections: readonly KustoConnection[],
|
|
96
|
+
fallbackConnectionId: string,
|
|
97
|
+
): ExplorerTabsSnapshot | null {
|
|
98
|
+
if (snapshot.tabs.length === 0) {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
const knownConnIds = new Set(connections.map((c) => c.id));
|
|
102
|
+
const tabs: QueryTab[] = snapshot.tabs.map((t) => (
|
|
103
|
+
knownConnIds.has(t.connectionId) ? t : { ...t, connectionId: fallbackConnectionId }
|
|
104
|
+
));
|
|
105
|
+
|
|
106
|
+
const tabIds = new Set(tabs.map((t) => t.id));
|
|
107
|
+
const activeTabId = tabIds.has(snapshot.activeTabId) ? snapshot.activeTabId : tabs[0].id;
|
|
108
|
+
|
|
109
|
+
let { splitEnabled, splitDirection, splitTabId, focusedPane } = snapshot;
|
|
110
|
+
if (!splitTabId || !tabIds.has(splitTabId) || splitTabId === activeTabId) {
|
|
111
|
+
splitEnabled = false;
|
|
112
|
+
splitTabId = null;
|
|
113
|
+
focusedPane = 'primary';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return { version: SNAPSHOT_VERSION, tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Extract the persisted slices from a full ExplorerState. */
|
|
120
|
+
export function extractSnapshot(state: ExplorerState): ExplorerTabsSnapshot {
|
|
121
|
+
return {
|
|
122
|
+
version: SNAPSHOT_VERSION,
|
|
123
|
+
tabs: state.tabs,
|
|
124
|
+
activeTabId: state.activeTabId,
|
|
125
|
+
splitEnabled: state.splitEnabled,
|
|
126
|
+
splitDirection: state.splitDirection,
|
|
127
|
+
splitTabId: state.splitTabId,
|
|
128
|
+
focusedPane: state.focusedPane,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Persist the snapshot to the StateService (and, transparently, localStorage + IDB). */
|
|
133
|
+
export function saveSnapshot(snapshot: ExplorerTabsSnapshot): void {
|
|
134
|
+
stateService.set(SNAPSHOT_STORE, SNAPSHOT_KEY, snapshot);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Remove any persisted snapshot. Useful for tests and explicit user "reset". */
|
|
138
|
+
export function clearSnapshot(): void {
|
|
139
|
+
stateService.delete(SNAPSHOT_STORE, SNAPSHOT_KEY);
|
|
140
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
2
2
|
import { createInitialState, explorerReducer } from './reducer';
|
|
3
3
|
import type { ExplorerState, ExplorerAction } from './index';
|
|
4
4
|
|
|
@@ -13,6 +13,12 @@ vi.mock('../services/state-service', () => ({
|
|
|
13
13
|
|
|
14
14
|
const mockStore = new Map<string, unknown>();
|
|
15
15
|
|
|
16
|
+
// Clear the mock store for every test (in this file). The reducer hydrates
|
|
17
|
+
// from stateService on createInitialState, so leftover entries from one
|
|
18
|
+
// test would leak into the next.
|
|
19
|
+
beforeEach(() => { mockStore.clear(); });
|
|
20
|
+
afterEach(() => { mockStore.clear(); });
|
|
21
|
+
|
|
16
22
|
|
|
17
23
|
|
|
18
24
|
// ---------------------------------------------------------------------------
|
|
@@ -92,6 +98,129 @@ describe('createInitialState', () => {
|
|
|
92
98
|
|
|
93
99
|
expect(state.tabs[0].connectionId).toBe('conn-1');
|
|
94
100
|
});
|
|
101
|
+
|
|
102
|
+
describe('snapshot hydration', () => {
|
|
103
|
+
const conns = [
|
|
104
|
+
{ id: 'conn-1', name: 'Cluster A', clusterUrl: 'https://a.kusto.windows.net', database: 'DbA', color: '#909d63' },
|
|
105
|
+
{ id: 'conn-2', name: 'Cluster B', clusterUrl: 'https://b.kusto.windows.net', database: 'DbB', color: '#6a8799' },
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
function setSnapshot(partial: Record<string, unknown>) {
|
|
109
|
+
mockStore.set('snapshot', {
|
|
110
|
+
version: 1,
|
|
111
|
+
tabs: [{ id: 'tab-7', title: 'My Tab', kql: 'A | take 1', connectionId: 'conn-1' }],
|
|
112
|
+
activeTabId: 'tab-7',
|
|
113
|
+
splitEnabled: false,
|
|
114
|
+
splitDirection: 'vertical',
|
|
115
|
+
splitTabId: null,
|
|
116
|
+
focusedPane: 'primary',
|
|
117
|
+
...partial,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
it('restores tabs and split state from a valid snapshot', () => {
|
|
122
|
+
mockStore.set('list', conns);
|
|
123
|
+
setSnapshot({
|
|
124
|
+
tabs: [
|
|
125
|
+
{ id: 'tab-1', title: 'Q1', kql: 'A', connectionId: 'conn-1' },
|
|
126
|
+
{ id: 'tab-2', title: 'Q2', kql: 'B', connectionId: 'conn-2' },
|
|
127
|
+
],
|
|
128
|
+
activeTabId: 'tab-2',
|
|
129
|
+
splitEnabled: true,
|
|
130
|
+
splitDirection: 'horizontal',
|
|
131
|
+
splitTabId: 'tab-1',
|
|
132
|
+
focusedPane: 'secondary',
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const state = createInitialState({ initialQuery: 'IGNORED', defaultClusters: [] });
|
|
136
|
+
|
|
137
|
+
expect(state.tabs).toHaveLength(2);
|
|
138
|
+
expect(state.tabs[0].kql).toBe('A');
|
|
139
|
+
expect(state.tabs[1].kql).toBe('B');
|
|
140
|
+
expect(state.activeTabId).toBe('tab-2');
|
|
141
|
+
expect(state.splitEnabled).toBe(true);
|
|
142
|
+
expect(state.splitDirection).toBe('horizontal');
|
|
143
|
+
expect(state.splitTabId).toBe('tab-1');
|
|
144
|
+
expect(state.focusedPane).toBe('secondary');
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('uses initialQuery when no snapshot exists', () => {
|
|
148
|
+
mockStore.set('list', conns);
|
|
149
|
+
const state = createInitialState({ initialQuery: 'MyTable | take 5', defaultClusters: [] });
|
|
150
|
+
expect(state.tabs).toHaveLength(1);
|
|
151
|
+
expect(state.tabs[0].kql).toBe('MyTable | take 5');
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('uses initialQuery when skipSnapshot is true (URL deep-link)', () => {
|
|
155
|
+
mockStore.set('list', conns);
|
|
156
|
+
setSnapshot({});
|
|
157
|
+
const state = createInitialState({ initialQuery: 'FromUrl | take 1', defaultClusters: [], skipSnapshot: true });
|
|
158
|
+
expect(state.tabs).toHaveLength(1);
|
|
159
|
+
expect(state.tabs[0].kql).toBe('FromUrl | take 1');
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('falls back to initialQuery when snapshot is invalid (wrong version)', () => {
|
|
163
|
+
mockStore.set('list', conns);
|
|
164
|
+
mockStore.set('snapshot', { version: 99, tabs: [] });
|
|
165
|
+
const state = createInitialState({ initialQuery: 'fallback', defaultClusters: [] });
|
|
166
|
+
expect(state.tabs[0].kql).toBe('fallback');
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('falls back to initialQuery when snapshot has no tabs', () => {
|
|
170
|
+
mockStore.set('list', conns);
|
|
171
|
+
setSnapshot({ tabs: [] });
|
|
172
|
+
const state = createInitialState({ initialQuery: 'fallback', defaultClusters: [] });
|
|
173
|
+
expect(state.tabs[0].kql).toBe('fallback');
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('remaps stale tab connectionId to the active connection', () => {
|
|
177
|
+
mockStore.set('list', conns);
|
|
178
|
+
mockStore.set('explorer-active-connection', 'conn-2');
|
|
179
|
+
setSnapshot({
|
|
180
|
+
tabs: [{ id: 'tab-1', title: 'Q', kql: 'X', connectionId: 'gone' }],
|
|
181
|
+
activeTabId: 'tab-1',
|
|
182
|
+
});
|
|
183
|
+
const state = createInitialState({ initialQuery: '', defaultClusters: [] });
|
|
184
|
+
expect(state.tabs[0].connectionId).toBe('conn-2');
|
|
185
|
+
expect(state.tabs[0].kql).toBe('X');
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('resets the split when splitTabId is missing from restored tabs', () => {
|
|
189
|
+
mockStore.set('list', conns);
|
|
190
|
+
setSnapshot({
|
|
191
|
+
tabs: [{ id: 'tab-1', title: 'Q', kql: '', connectionId: 'conn-1' }],
|
|
192
|
+
activeTabId: 'tab-1',
|
|
193
|
+
splitEnabled: true,
|
|
194
|
+
splitTabId: 'tab-99',
|
|
195
|
+
focusedPane: 'secondary',
|
|
196
|
+
});
|
|
197
|
+
const state = createInitialState({ initialQuery: '', defaultClusters: [] });
|
|
198
|
+
expect(state.splitEnabled).toBe(false);
|
|
199
|
+
expect(state.splitTabId).toBeNull();
|
|
200
|
+
expect(state.focusedPane).toBe('primary');
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('bumps tabCounter past restored ids so subsequent ADD_TAB does not collide', () => {
|
|
204
|
+
mockStore.set('list', conns);
|
|
205
|
+
setSnapshot({
|
|
206
|
+
tabs: [
|
|
207
|
+
{ id: 'tab-5', title: 'A', kql: '', connectionId: 'conn-1' },
|
|
208
|
+
{ id: 'tab-9', title: 'B', kql: '', connectionId: 'conn-1' },
|
|
209
|
+
],
|
|
210
|
+
activeTabId: 'tab-5',
|
|
211
|
+
});
|
|
212
|
+
const state = createInitialState({ initialQuery: '', defaultClusters: [] });
|
|
213
|
+
|
|
214
|
+
const next = explorerReducer(state, { type: 'ADD_TAB' });
|
|
215
|
+
const newId = next.tabs[next.tabs.length - 1].id;
|
|
216
|
+
expect(newId).not.toBe('tab-5');
|
|
217
|
+
expect(newId).not.toBe('tab-9');
|
|
218
|
+
// New id should sit past tab-9
|
|
219
|
+
const m = /^tab-(\d+)$/.exec(newId);
|
|
220
|
+
expect(m).not.toBeNull();
|
|
221
|
+
expect(Number(m![1])).toBeGreaterThan(9);
|
|
222
|
+
});
|
|
223
|
+
});
|
|
95
224
|
});
|
|
96
225
|
|
|
97
226
|
// ---------------------------------------------------------------------------
|
|
@@ -630,14 +759,16 @@ describe('explorerReducer', () => {
|
|
|
630
759
|
});
|
|
631
760
|
|
|
632
761
|
describe('createInitialState with connections', () => {
|
|
762
|
+
const cluster = { id: 'conn-1', name: 'Cluster A', clusterUrl: 'https://a.kusto.windows.net', database: 'DbA', color: '#909d63' };
|
|
763
|
+
|
|
633
764
|
it('loads connections', () => {
|
|
634
|
-
const state = createInitialState({ initialQuery: '', defaultClusters: [] });
|
|
765
|
+
const state = createInitialState({ initialQuery: '', defaultClusters: [cluster] });
|
|
635
766
|
expect(state.connections.length).toBeGreaterThanOrEqual(1);
|
|
636
767
|
expect(state.connections[0].id).toBeTruthy();
|
|
637
768
|
});
|
|
638
769
|
|
|
639
770
|
it('first tab has a connectionId', () => {
|
|
640
|
-
const state = createInitialState({ initialQuery: '', defaultClusters: [] });
|
|
771
|
+
const state = createInitialState({ initialQuery: '', defaultClusters: [cluster] });
|
|
641
772
|
expect(state.tabs[0].connectionId).toBeTruthy();
|
|
642
773
|
});
|
|
643
774
|
});
|
package/src/state/reducer.ts
CHANGED
|
@@ -5,28 +5,23 @@
|
|
|
5
5
|
|
|
6
6
|
import type { ExplorerState, InitialStateArgs } from './types';
|
|
7
7
|
import type { ExplorerAction } from './actions';
|
|
8
|
-
import { createTab, nextQueryTitle, loadConnections, loadActiveConnectionId } from '../components/ExplorerWorkspace/ExplorerWorkspace.logic';
|
|
8
|
+
import { createTab, nextQueryTitle, loadConnections, loadActiveConnectionId, bumpTabCounterPast } from '../components/ExplorerWorkspace/ExplorerWorkspace.logic';
|
|
9
9
|
import { SUPPORTED_RENDER_TYPES } from '../components/ChartPanel/ChartPanel.logic';
|
|
10
|
+
import { loadSnapshot, validateAndCleanSnapshot } from './persistence';
|
|
10
11
|
|
|
11
|
-
export function createInitialState({ initialQuery, defaultClusters }: InitialStateArgs): ExplorerState {
|
|
12
|
+
export function createInitialState({ initialQuery, defaultClusters, skipSnapshot = false }: InitialStateArgs): ExplorerState {
|
|
12
13
|
const connections = loadConnections(defaultClusters);
|
|
13
|
-
const
|
|
14
|
-
|
|
14
|
+
const activeConnectionId = loadActiveConnectionId(connections);
|
|
15
|
+
|
|
16
|
+
const baseDefaults = {
|
|
15
17
|
connections,
|
|
16
18
|
|
|
17
19
|
schema: [],
|
|
18
20
|
schemaSearch: '',
|
|
19
|
-
expandedFolders: new Set(),
|
|
20
|
-
expandedTables: new Set(),
|
|
21
|
+
expandedFolders: new Set<string>(),
|
|
22
|
+
expandedTables: new Set<string>(),
|
|
21
23
|
schemaContextMenu: null,
|
|
22
24
|
|
|
23
|
-
tabs: [firstTab],
|
|
24
|
-
activeTabId: firstTab.id,
|
|
25
|
-
splitEnabled: false,
|
|
26
|
-
splitDirection: 'vertical',
|
|
27
|
-
splitTabId: null,
|
|
28
|
-
focusedPane: 'primary',
|
|
29
|
-
|
|
30
25
|
loading: false,
|
|
31
26
|
error: null,
|
|
32
27
|
queryStartTime: null,
|
|
@@ -40,13 +35,43 @@ export function createInitialState({ initialQuery, defaultClusters }: InitialSta
|
|
|
40
35
|
queryStats: null,
|
|
41
36
|
resultSets: [],
|
|
42
37
|
activeResultSet: 0,
|
|
43
|
-
resultsTab: 'results',
|
|
38
|
+
resultsTab: 'results' as const,
|
|
44
39
|
|
|
45
40
|
history: [],
|
|
46
41
|
|
|
47
42
|
editorHeight: 50,
|
|
48
43
|
hasSelection: false,
|
|
49
44
|
canRecall: false,
|
|
45
|
+
} satisfies Partial<ExplorerState>;
|
|
46
|
+
|
|
47
|
+
if (!skipSnapshot) {
|
|
48
|
+
const raw = loadSnapshot();
|
|
49
|
+
if (raw) {
|
|
50
|
+
const snap = validateAndCleanSnapshot(raw, connections, activeConnectionId);
|
|
51
|
+
if (snap) {
|
|
52
|
+
bumpTabCounterPast(snap.tabs);
|
|
53
|
+
return {
|
|
54
|
+
...baseDefaults,
|
|
55
|
+
tabs: snap.tabs,
|
|
56
|
+
activeTabId: snap.activeTabId,
|
|
57
|
+
splitEnabled: snap.splitEnabled,
|
|
58
|
+
splitDirection: snap.splitDirection,
|
|
59
|
+
splitTabId: snap.splitTabId,
|
|
60
|
+
focusedPane: snap.focusedPane,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const firstTab = createTab(initialQuery, 'Query 1', activeConnectionId);
|
|
67
|
+
return {
|
|
68
|
+
...baseDefaults,
|
|
69
|
+
tabs: [firstTab],
|
|
70
|
+
activeTabId: firstTab.id,
|
|
71
|
+
splitEnabled: false,
|
|
72
|
+
splitDirection: 'vertical',
|
|
73
|
+
splitTabId: null,
|
|
74
|
+
focusedPane: 'primary',
|
|
50
75
|
};
|
|
51
76
|
}
|
|
52
77
|
|
package/src/state/types.ts
CHANGED
|
@@ -51,4 +51,10 @@ export interface ExplorerState {
|
|
|
51
51
|
export interface InitialStateArgs {
|
|
52
52
|
initialQuery: string;
|
|
53
53
|
defaultClusters: KustoConnection[];
|
|
54
|
+
/**
|
|
55
|
+
* When true, ignore any persisted tab snapshot and start fresh with
|
|
56
|
+
* `initialQuery` in a single tab. The Explorer sets this when the
|
|
57
|
+
* URL contains a `?query=` parameter so deep-links always win.
|
|
58
|
+
*/
|
|
59
|
+
skipSnapshot?: boolean;
|
|
54
60
|
}
|