| 1 | import { Message } from '../types'; |
| 2 | import { ReduxExtension } from './getReduxExtension'; |
| 3 | |
| 4 | // Original but incomplete type of the redux extension package |
| 5 | type ConnectResponse = ReturnType<NonNullable<ReduxExtension>['connect']>; |
| 6 | |
| 7 | export type Connection = { |
| 8 | /** Mark the connection as not initiated, so it can be initiated before using it. */ |
| 9 | shouldInit?: boolean; |
| 10 | |
| 11 | /** Initiate the connection and add it to the extension connections. |
| 12 | * Should only be executed once in the live time of the connection. |
| 13 | */ |
| 14 | init: ConnectResponse['init']; |
| 15 | |
| 16 | // FIXME https://github.com/reduxjs/redux-devtools/issues/1097 |
| 17 | /** Add a subscription to the connection. |
| 18 | * The provided listener will be executed when the user interacts with the extension |
| 19 | * with actions like time traveling, importing a state or the likes. |
| 20 | * |
| 21 | * @param listener function to be executed when an action is submitted |
| 22 | * @returns function to unsubscribe the applied listener |
| 23 | */ |
| 24 | subscribe: (listener: (message: Message) => void) => (() => void) | undefined; |
| 25 | |
| 26 | /** Send a new action to the connection to display the state change in the extension. |
| 27 | * For example when the value of the store changes. |
| 28 | */ |
| 29 | send: ConnectResponse['send']; |
| 30 | }; |
| 31 | |
| 32 | /** Wrapper for creating connections to the redux extension |
| 33 | * Connections are used to display the stores value and value changes within the extension |
| 34 | * as well as reacting to extension actions like time traveling. |
| 35 | **/ |
| 36 | export const createReduxConnection = ( |
| 37 | extension: ReduxExtension | undefined, |
| 38 | name: string, |
| 39 | ) => { |
| 40 | if (!extension) return undefined; |
| 41 | const connection = extension.connect({ name }); |
| 42 | |
| 43 | return Object.assign(connection, { |
| 44 | shouldInit: true, |
| 45 | }) as Connection; |
| 46 | }; |
| 47 | |