Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(#285): add composeWithStateSync to resolve issues with enhancer order #296

Merged
merged 5 commits into from
Feb 16, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"node": ">= 12"
},
"dependencies": {
"electron-process-type": "^4.2.0",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1"
},
Expand Down
47 changes: 47 additions & 0 deletions src/composeWithStateSync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* eslint-disable @typescript-eslint/ban-types */

import { StoreEnhancer, StoreEnhancerStoreCreator } from 'redux'
import { forwardAction } from './forwardAction'
import { MainStateSyncEnhancerOptions } from './options/MainStateSyncEnhancerOptions'
import { RendererStateSyncEnhancerOptions } from './options/RendererStateSyncEnhancerOptions'
import { stateSyncEnhancer } from './stateSyncEnhancer'

export type StateSyncOptions = MainStateSyncEnhancerOptions | RendererStateSyncEnhancerOptions
sneljo1 marked this conversation as resolved.
Show resolved Hide resolved

const forwardActionEnhancer = (options?: StateSyncOptions): StoreEnhancer => (createStore) => (
reducer,
preloadedState
) => {
const store = createStore(reducer, preloadedState)

return forwardAction(store, options)
}

const extensionCompose = (options: StateSyncOptions) => <D extends StoreEnhancerStoreCreator>(
...funcs: Function[]
) => {
return (createStore: D) => {
return [
stateSyncEnhancer({ ...options, preventActionReplay: true }),
...funcs,
forwardActionEnhancer(options),
].reduceRight((composed, f) => f(composed), createStore)
}
}

export function composeWithStateSync<R>(
options: StateSyncOptions
): (...funcs: Function[]) => (...args: any[]) => R
export function composeWithStateSync<R>(...funcs: Function[]): (...args: any[]) => R
export function composeWithStateSync(
firstFuncOrOpts: Function | StateSyncOptions,
...funcs: Function[]
) {
if (arguments.length === 0) {
return stateSyncEnhancer()
}
if (arguments.length === 1 && typeof firstFuncOrOpts === 'object') {
return extensionCompose(firstFuncOrOpts)
}
return extensionCompose({})(firstFuncOrOpts as Function, ...funcs)
}
51 changes: 51 additions & 0 deletions src/forwardAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { ipcRenderer, webContents } from 'electron'
import { Store } from 'redux'
import { StateSyncOptions } from './composeWithStateSync'
import { IPCEvents } from './constants'
import { MainStateSyncEnhancerOptions } from './options/MainStateSyncEnhancerOptions'
import { RendererStateSyncEnhancerOptions } from './options/RendererStateSyncEnhancerOptions'
import { isMain, isRenderer, validateAction } from './utils'

export const processActionMain = <A>(
action: A,
options: MainStateSyncEnhancerOptions = {}
): void => {
if (validateAction(action, options.denyList)) {
webContents.getAllWebContents().forEach((contents) => {
// Ignore chromium devtools
if (contents.getURL().startsWith('devtools://')) return
contents.send(IPCEvents.ACTION, action)
})
}
}

export const processActionRenderer = <A>(
action: A,
options: RendererStateSyncEnhancerOptions = {}
): void => {
if (validateAction(action, options.denyList)) {
ipcRenderer.send(IPCEvents.ACTION, action)
}
}

export const forwardAction = <S extends Store<any, any>>(
store: S,
options?: StateSyncOptions
): S => {
return {
...store,
dispatch: (action) => {
const value = store.dispatch(action)

if (!options?.preventActionReplay) {
if (isMain) {
processActionMain(action, options)
} else if (isRenderer) {
processActionRenderer(action, options)
}
}

return value
},
}
}
10 changes: 9 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { mainStateSyncEnhancer } from './mainStateSyncEnhancer'
import { stopForwarding } from './utils'
import { rendererStateSyncEnhancer } from './rendererStateSyncEnhancer'
import { stateSyncEnhancer } from './stateSyncEnhancer'
import { composeWithStateSync } from './composeWithStateSync'

export { mainStateSyncEnhancer, rendererStateSyncEnhancer, stopForwarding }
export {
mainStateSyncEnhancer,
rendererStateSyncEnhancer,
stopForwarding,
stateSyncEnhancer,
composeWithStateSync,
}
74 changes: 17 additions & 57 deletions src/mainStateSyncEnhancer.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import { ipcMain, webContents } from 'electron'
import {
Action,
compose,
Dispatch,
Middleware,
MiddlewareAPI,
StoreCreator,
StoreEnhancer,
} from 'redux'
import { Action, StoreEnhancer } from 'redux'
import { IPCEvents } from './constants'
import {
defaultMainOptions,
MainStateSyncEnhancerOptions,
} from './options/MainStateSyncEnhancerOptions'
import { preventDoubleInitialization, stopForwarding, validateAction } from './utils'
import { forwardAction } from './forwardAction'
import { MainStateSyncEnhancerOptions } from './options/MainStateSyncEnhancerOptions'
import { stopForwarding } from './utils'

/**
* Creates new instance of main process redux enhancer.
* @param {MainStateSyncEnhancerOptions} options Additional enhancer options
* @returns StoreEnhancer
*/
export const mainStateSyncEnhancer = (
options: MainStateSyncEnhancerOptions = {}
): StoreEnhancer => (createStore) => {
return (reducer, preloadedState) => {
const store = createStore(reducer, preloadedState)

function createMiddleware(options: MainStateSyncEnhancerOptions) {
const middleware: Middleware = (store) => {
ipcMain.handle(IPCEvents.INIT_STATE_ASYNC, async () => {
return JSON.stringify(store.getState(), options.serializer)
})
Expand All @@ -28,6 +27,7 @@ function createMiddleware(options: MainStateSyncEnhancerOptions) {
// When receiving an action from a renderer
ipcMain.on(IPCEvents.ACTION, (event, action: Action) => {
const localAction = stopForwarding(action)

store.dispatch(localAction)

// Forward it to all of the other renderers
Expand All @@ -42,46 +42,6 @@ function createMiddleware(options: MainStateSyncEnhancerOptions) {
})
})

return (next) => (action) => {
if (validateAction(action, options.denyList)) {
webContents.getAllWebContents().forEach((contents) => {
// Ignore chromium devtools
if (contents.getURL().startsWith('devtools://')) return
contents.send(IPCEvents.ACTION, action)
})
}

return next(action)
}
}
return middleware
}

/**
* Creates new instance of main process redux enhancer.
* @param {MainStateSyncEnhancerOptions} options Additional enhancer options
* @returns StoreEnhancer
*/
export const mainStateSyncEnhancer = (options = defaultMainOptions): StoreEnhancer => (
createStore: StoreCreator
) => {
preventDoubleInitialization()
const middleware = createMiddleware(options)
return (reducer, preloadedState) => {
const store = createStore(reducer, preloadedState)

let dispatch = store.dispatch

const middlewareAPI: MiddlewareAPI<Dispatch<any>> = {
getState: store.getState,
dispatch,
}

dispatch = compose<Dispatch>(middleware(middlewareAPI))(dispatch)

return {
...store,
dispatch,
}
return forwardAction(store, options)
}
}
11 changes: 3 additions & 8 deletions src/options/MainStateSyncEnhancerOptions.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
export type MainStateSyncEnhancerOptions = {
import { StateSyncOptions } from './StateSyncOptions'

export interface MainStateSyncEnhancerOptions extends StateSyncOptions {
/**
* Custom store serialization function.
* This function is called for each member of the object. If a member contains nested objects,
* the nested objects are transformed before the parent object is.
*/
serializer?: (this: unknown, key: string, value: unknown) => unknown

/**
* Custom list for actions that should never replay across stores
*/
denyList?: RegExp[]
}

export const defaultMainOptions: MainStateSyncEnhancerOptions = {}
11 changes: 3 additions & 8 deletions src/options/RendererStateSyncEnhancerOptions.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
export type RendererStateSyncEnhancerOptions = {
import { StateSyncOptions } from './StateSyncOptions'

export interface RendererStateSyncEnhancerOptions extends StateSyncOptions {
/**
* Custom function used during de-serialization of the redux store to transform the object.
* This function is called for each member of the object. If a member contains nested objects,
* the nested objects are transformed before the parent object is.
*/
deserializer?: (this: unknown, key: string, value: unknown) => unknown

/**
* Custom list for actions that should never replay across stores
*/
denyList?: RegExp[]

/**
* By default, the renderer store is initialized from the main store synchronously.
* Since the synchronous fetching of the state is blocking the renderer process until it gets the state
Expand All @@ -19,5 +16,3 @@ export type RendererStateSyncEnhancerOptions = {
*/
lazyInit?: boolean
}

export const defaultRendererOptions: RendererStateSyncEnhancerOptions = {}
11 changes: 11 additions & 0 deletions src/options/StateSyncOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface StateSyncOptions {
/**
* Custom list for actions that should never replay across stores
*/
denyList?: RegExp[]

/**
* Prevent replaying actions in the current process
*/
preventActionReplay?: boolean
}
61 changes: 13 additions & 48 deletions src/rendererStateSyncEnhancer.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,11 @@
import { ipcRenderer } from 'electron'
import {
Action,
compose,
Dispatch,
Middleware,
MiddlewareAPI,
StoreCreator,
StoreEnhancer,
} from 'redux'
import { Action, StoreEnhancer } from 'redux'
import { IPCEvents } from './constants'
import { forwardAction } from './forwardAction'
import { fetchInitialState, fetchInitialStateAsync } from './fetchState'
import { replaceState, withStoreReplacer } from './fetchState/replaceState'
import {
defaultRendererOptions,
RendererStateSyncEnhancerOptions,
} from './options/RendererStateSyncEnhancerOptions'
import { preventDoubleInitialization, stopForwarding, validateAction } from './utils'

const createMiddleware = (options: RendererStateSyncEnhancerOptions): Middleware => (store) => {
// When receiving an action from main
ipcRenderer.on(IPCEvents.ACTION, (_, action: Action) => {
store.dispatch(stopForwarding(action))
})

return (next) => (action) => {
if (validateAction(action, options.denyList)) {
ipcRenderer.send(IPCEvents.ACTION, action)
}

return next(action)
}
}
import { RendererStateSyncEnhancerOptions } from './options/RendererStateSyncEnhancerOptions'
import { stopForwarding } from './utils'

/**
* Creates new instance of renderer process redux enhancer.
Expand All @@ -39,15 +14,12 @@ const createMiddleware = (options: RendererStateSyncEnhancerOptions): Middleware
* @param {RendererStateSyncEnhancerOptions} options Additional settings for enhancer
* @returns StoreEnhancer
*/
export const rendererStateSyncEnhancer = (options = defaultRendererOptions): StoreEnhancer => (
createStore: StoreCreator
) => {
preventDoubleInitialization()

export const rendererStateSyncEnhancer = (
options: RendererStateSyncEnhancerOptions = {}
): StoreEnhancer => (createStore) => {
return (reducer, state) => {
const middleware = createMiddleware(options)

const initialState = options.lazyInit ? state : fetchInitialState<typeof state>(options)

const store = createStore(
options.lazyInit ? withStoreReplacer(reducer) : reducer,
initialState
Expand All @@ -59,18 +31,11 @@ export const rendererStateSyncEnhancer = (options = defaultRendererOptions): Sto
})
}

let dispatch = store.dispatch

const middlewareAPI: MiddlewareAPI<Dispatch<any>> = {
getState: store.getState,
dispatch,
}

dispatch = compose<Dispatch>(middleware(middlewareAPI))(dispatch)
// When receiving an action from main
ipcRenderer.on(IPCEvents.ACTION, (_, action: Action) => {
store.dispatch(stopForwarding(action))
})

return {
...store,
dispatch,
}
return forwardAction(store, options)
}
}
17 changes: 17 additions & 0 deletions src/stateSyncEnhancer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { StoreEnhancer } from 'redux'
import { StateSyncOptions } from './composeWithStateSync'
import { mainStateSyncEnhancer } from './mainStateSyncEnhancer'
import { rendererStateSyncEnhancer } from './rendererStateSyncEnhancer'
import { isMain, isRenderer, preventDoubleInitialization } from './utils'

export const stateSyncEnhancer = (config: StateSyncOptions = {}): StoreEnhancer => {
preventDoubleInitialization()

if (isRenderer) {
return rendererStateSyncEnhancer(config)
} else if (isMain) {
return mainStateSyncEnhancer(config)
}

throw new Error(`Unsupported process: ${process?.type}`)
}
4 changes: 2 additions & 2 deletions src/utils/actions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isFSA, FluxStandardAction } from './isFSA'
import { FluxStandardAction, isFSA } from './isFSA'

// Gives us just enough action type info to work for the functions below
export type ActionMeta = {
Expand All @@ -9,7 +9,7 @@ export type ActionMeta = {
* stopForwarding allows you to give it an action, and it will return an
* equivalent action that will only play in the current process
*/
export const stopForwarding = (action: FluxStandardAction<ActionMeta>) => ({
export const stopForwarding = (action: FluxStandardAction<ActionMeta>): any => ({
matmalkowski marked this conversation as resolved.
Show resolved Hide resolved
...action,
meta: {
...action.meta,
Expand Down
Loading