-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathstore-context.tsx
More file actions
403 lines (380 loc) · 11.4 KB
/
Copy pathstore-context.tsx
File metadata and controls
403 lines (380 loc) · 11.4 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
import React, { createContext, useContext, useRef, useState } from 'react';
import type {
MapStateToProps,
ReactReduxContextValue,
TypedUseSelectorHook,
} from 'react-redux';
import {
connect as reduxConnect,
createStoreHook,
createDispatchHook,
createSelectorHook,
} from 'react-redux';
import type {
configureStore,
ConnectionId,
ConnectionsEventEmitter,
ConnectionState,
State,
} from './connections-store-redux';
import {
cancelEditConnection,
connect as connectionsConnect,
connectInNewWindow,
saveAndConnect,
connectionsEventEmitter,
createNewConnection,
disconnect,
duplicateConnection,
editConnection,
getDataServiceForConnection,
removeAllRecentConnections,
removeConnection,
saveEditedConnectionInfo,
showNonGenuineMongoDBWarningModal,
toggleConnectionFavoritedStatus,
importConnections,
refreshConnections,
} from './connections-store-redux';
import type { Store } from 'redux';
import {
getConnectionTitle,
type ConnectionInfo,
} from '@mongodb-js/connection-info';
import { createServiceLocator } from '@mongodb-js/compass-app-registry';
import { isEqual, memoize } from 'lodash';
import type { ImportConnectionOptions } from '@mongodb-js/connection-storage/provider';
import { useInitialValue } from '@mongodb-js/compass-components';
type ConnectionsStore = ReturnType<typeof configureStore> extends Store<
infer S,
infer A
> & { dispatch: infer D }
? { state: S; actions: A; dispatch: D }
: never;
export const ConnectionsStoreContext = React.createContext<
ReactReduxContextValue<ConnectionsStore['state']>
// @ts-expect-error not possible to correctly pass default value here
>(null);
/**
* @internal should not be directly exported from this package
*/
export const useStore = createStoreHook(
ConnectionsStoreContext
) as () => ReturnType<typeof configureStore>;
/**
* @internal should not be directly exported from this package
*/
export const useDispatch = createDispatchHook(
ConnectionsStoreContext
) as () => ConnectionsStore['dispatch'];
/**
* @internal should not be directly exported from this package
*/
export const useSelector: TypedUseSelectorHook<ConnectionsStore['state']> =
createSelectorHook(ConnectionsStoreContext);
export const connect = ((
mapState: MapStateToProps<unknown, unknown, unknown>,
mapDispatch = null,
mergeProps = null
) => {
return reduxConnect(mapState, mapDispatch, mergeProps, {
context: ConnectionsStoreContext,
});
}) as typeof reduxConnect;
function getConnectionsActions(dispatch: ConnectionsStore['dispatch']) {
return {
connect: (connectionInfo: ConnectionInfo) => {
return dispatch(connectionsConnect(connectionInfo));
},
connectInNewWindow: (connectionInfo: ConnectionInfo) => {
return dispatch(connectInNewWindow(connectionInfo));
},
saveAndConnect: (connectionInfo: ConnectionInfo) => {
return dispatch(saveAndConnect(connectionInfo));
},
disconnect: (connectionId: ConnectionId) => {
return dispatch(disconnect(connectionId));
},
createNewConnection: () => {
return dispatch(createNewConnection());
},
editConnection: (connectionId: ConnectionId) => {
return dispatch(editConnection(connectionId));
},
duplicateConnection: (
connectionId: ConnectionId,
options?: {
autoDuplicate: boolean;
}
) => {
return dispatch(duplicateConnection(connectionId, options));
},
saveEditedConnection: (connectionInfo: ConnectionInfo) => {
return dispatch(saveEditedConnectionInfo(connectionInfo));
},
cancelEditConnection: (connectionId: ConnectionId) => {
dispatch(cancelEditConnection(connectionId));
},
toggleFavoritedConnectionStatus: (connectionId: ConnectionId) => {
return dispatch(toggleConnectionFavoritedStatus(connectionId));
},
removeConnection: (connectionId: ConnectionId) => {
return dispatch(removeConnection(connectionId));
},
removeAllRecentConnections: () => {
return dispatch(removeAllRecentConnections());
},
showNonGenuineMongoDBWarningModal: (connectionId: ConnectionId) => {
return dispatch(showNonGenuineMongoDBWarningModal(connectionId));
},
importConnections: (options: {
content: string;
options?: ImportConnectionOptions;
signal?: AbortSignal;
}) => {
return dispatch(importConnections(options));
},
refreshConnections: () => {
return dispatch(refreshConnections());
},
};
}
const ConnectionActionsContext = createContext<ReturnType<
typeof getConnectionsActions
> | null>(null);
/**
* @internal We're using a provider here so that in test environment we can make
* sure we're using the same object reference in all renders and so can safely
* spy on the actions if test requires it. Should not be exported from this
* package
*/
export const ConnectionActionsProvider: React.FunctionComponent = ({
children,
}) => {
const dispatch = useDispatch();
const [actions] = useState(() => {
return getConnectionsActions(dispatch);
});
return (
<ConnectionActionsContext.Provider value={actions}>
{children}
</ConnectionActionsContext.Provider>
);
};
export function useConnectionActions() {
const actions = useContext(ConnectionActionsContext);
if (!actions) {
throw new Error(
"Can't find connection actions in context. Are you using useConnectionActions hook in correct environment?"
);
}
return actions;
}
export function useConnectionsListRef(): {
getConnectionById(
this: void,
connectionId: string
): (ConnectionState & { title: string }) | undefined;
current: readonly (ConnectionState & { title: string })[];
} {
const storeRef = useRef(useStore());
const [ref] = useState(() => {
return {
getConnectionById(connectionId: string) {
const conn = storeRef.current.getState().connections.byId[connectionId];
if (conn) {
return { ...conn, title: getConnectionTitle(conn.info) };
}
return undefined;
},
get current() {
return Object.values(storeRef.current.getState().connections.byId).map(
(conn) => {
return { ...conn, title: getConnectionTitle(conn.info) };
}
);
},
};
});
return ref;
}
export type ConnectionsService = Omit<ConnectionsEventEmitter, 'emit'> & {
getDataServiceForConnection: typeof getDataServiceForConnection;
} & ReturnType<typeof useConnectionsListRef> &
ReturnType<typeof useConnectionActions>;
function useConnections(): ConnectionsService {
const actions = useConnectionActions();
const connectionsListRef = useConnectionsListRef();
return useInitialValue({
...actions,
...connectionsListRef,
getDataServiceForConnection,
on: connectionsEventEmitter.on,
off: connectionsEventEmitter.off,
once: connectionsEventEmitter.once,
removeListener: connectionsEventEmitter.removeListener,
});
}
export const connectionsLocator: () => ConnectionsService =
createServiceLocator(useConnections, 'connectionsLocator');
function isShallowEqual(
a: Record<string, unknown> | null,
b: Record<string, unknown> | null
) {
if (a === null || b === null) {
return a === b;
}
const keys = new Set(Object.keys(a).concat(Object.keys(b)));
for (const key of keys) {
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
/**
* Returns (optionally filtered) list of connection ids. If you need to render a
* list of connections in the app, this hook allows us to subscribe to a list of
* connection items without subscribing to the actual state of those
* connections (subscription to those is usually required on a deeper level of
* the rendering)
*/
export function useConnectionIds(
filter?: (connection: ConnectionState) => boolean
): ConnectionId[] {
return useSelector<ConnectionId[]>(
(state) => {
return state.connections.ids.filter((id) => {
return filter?.(state.connections.byId[id]) ?? true;
});
},
(a, b) => {
return isEqual(a, b);
}
);
}
/**
* Returns (optionally filtered) list of connection state and subscribes to
* changes of all the connection state
*
* @deprecated should be avoided unless your component depends on literally all
* the state of all the connections in the list at once which is very rarely the
* case
*/
export function useConnectionsList(
filter?: (connection: ConnectionState) => boolean
) {
return useSelector<(ConnectionState & { title: string })[]>(
(state) => {
return state.connections.ids
.filter((id) => {
return filter?.(state.connections.byId[id]) ?? true;
})
.map((id) => {
const connection = state.connections.byId[id];
return { ...connection, title: getConnectionTitle(connection.info) };
});
},
(a, b) => {
if (a.length !== b.length) {
return false;
}
if (a.length === 0) {
return true;
}
return a.every((connA, index) => {
return isShallowEqual(connA, b[index]);
});
}
);
}
/**
* Returns single connection state for a certain connection id and subscribes to
* changes
*/
export function useConnectionForId(
connectionId: ConnectionId
): (ConnectionState & { title: string }) | null {
return useSelector(
(state) => {
const connection = state.connections.byId[connectionId];
return connection
? { ...connection, title: getConnectionTitle(connection.info) }
: null;
},
(a, b) => {
return isShallowEqual(a, b);
}
);
}
/**
* Returns only connection info state and a title and subscribes to changes
*/
export function useConnectionInfoForId(
connectionId?: ConnectionId
): (ConnectionInfo & { title: string }) | null {
return useSelector(
(state) => {
if (!connectionId) {
return null;
}
const connection = state.connections.byId[connectionId];
return connection
? { ...connection.info, title: getConnectionTitle(connection.info) }
: null;
},
(a, b) => {
return isShallowEqual(a, b);
}
);
}
/**
* Returns a stable reference for the connection info when you need to access
* the value without triggering the render
*/
export function useConnectionInfoRefForId(connectionId: ConnectionId): {
current: (ConnectionInfo & { title: string }) | null;
} {
const store = useStore();
const [ref] = useState(() => {
return {
get current() {
const connection = store.getState().connections.byId[connectionId];
return connection
? { ...connection.info, title: getConnectionTitle(connection.info) }
: null;
},
};
});
return ref;
}
export function useConnectionsColorList(): {
id: ConnectionId;
color: string | undefined;
}[] {
return useSelector((state) => {
return Object.values(state.connections.byId).map((connection) => {
return {
id: connection.info.id,
color: connection.info.favorite?.color,
};
});
}, isEqual);
}
export function useConnectionsListLoadingStatus() {
return useSelector((state) => {
const status = state.connections.status;
return {
status,
error: state.connections.error?.message ?? null,
isInitialLoad: status === 'initial' || status === 'loading',
};
}, isEqual);
}
export const selectActiveConnections = memoize(
(connectionsById: State['connections']['byId']) => {
return Object.values(connectionsById).filter((connection) => {
return connection.status === 'connected';
});
}
);