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

feat(middleware/devtools): Better redux devtools. One connection for all zustand stores #1435

Merged
merged 18 commits into from
Jan 1, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion .codesandbox/ci.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"simple-react-browserify-x9yni",
"simple-snowpack-react-o1gmx",
"react-parcel-onewf",
"next-js-uo1h0"
"next-js-uo1h0",
"pavlobu-zustand-demo-frutec"
],
"node": "14"
}
13 changes: 13 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,19 @@ const usePlainStore = create(devtools(store))
const useReduxStore = create(devtools(redux(reducer, initialState)))
```

One redux devtools connection for multiple stores
```jsx
import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const usePlainStore1 = create(devtools(store), { name, store: storeName1 })
pavlobu marked this conversation as resolved.
Show resolved Hide resolved
const usePlainStore2 = create(devtools(store), { name, store: storeName2 })
// Usage with a redux store, it will log full action types
const useReduxStore = create(devtools(redux(reducer, initialState)), , { name, store: storeName3 })
const useReduxStore = create(devtools(redux(reducer, initialState)), , { name, store: storeName4 })
```
Assingning different connection names, will separate stores in redux devtools. This also helps grouping different stores into separate redux devtools connections.

devtools takes the store function as its first argument, optionally you can name the store or configure [serialize](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md#serialize) options with a second argument.

Name store: `devtools(store, {name: "MyStore"})`, which will create a separate instance named "MyStore" in the devtools.
Expand Down
153 changes: 130 additions & 23 deletions src/middleware/devtools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ type StoreDevtools<S> = S extends {
export interface DevtoolsOptions extends Config {
enabled?: boolean
anonymousActionType?: string
store?: string
}

type Devtools = <
Expand All @@ -147,13 +148,37 @@ type DevtoolsImpl = <T>(

export type NamedSet<T> = WithDevtools<StoreApi<T>>['setState']

type ConnectResponse = ReturnType<
NonNullable<Window['__REDUX_DEVTOOLS_EXTENSION__']>['connect']
>
const connections: Record<string, ConnectResponse> = {}
pavlobu marked this conversation as resolved.
Show resolved Hide resolved

const storeApis: (StoreApi<any> & { store: string })[] = []
const initialStoreStates: (any & { store: string })[] = []

const getCurrentStoresStates = () => {
const storesStates = storeApis.map((storeApi) => ({
...storeApi.getState(),
store: storeApi.store,
}))
const currentStates: Record<
string,
ReturnType<StoreApi<any>['getState']>
> = {}
storesStates.forEach((storeState) => {
currentStates[storeState.store] = storeState
})
return currentStates
}

const devtoolsImpl: DevtoolsImpl =
(fn, devtoolsOptions = {}) =>
(set, get, api) => {
type S = ReturnType<typeof fn>
const { enabled, anonymousActionType, store, ...options } = devtoolsOptions

type S = ReturnType<typeof fn> & { [store: string]: S }
type PartialState = Partial<S> | ((s: S) => Partial<S>)

const { enabled, anonymousActionType, ...options } = devtoolsOptions
let extensionConnector:
| typeof window['__REDUX_DEVTOOLS_EXTENSION__']
| false
Expand All @@ -173,22 +198,57 @@ const devtoolsImpl: DevtoolsImpl =
return fn(set, get, api)
}

const extension = extensionConnector.connect(options)
const name = options.name ?? ''
let connection = connections[name]
if (store !== undefined && connections[name] === undefined) {
const connectResponse = extensionConnector.connect(options)
connections[name] = connectResponse
connection = connectResponse
}
if (store === undefined) {
connection = extensionConnector.connect(options)
}

let isRecording = true
;(api.setState as NamedSet<S>) = (state, replace, nameOrAction) => {
const r = set(state, replace)
if (!isRecording) return r
extension.send(
nameOrAction === undefined
? { type: anonymousActionType || 'anonymous' }
: typeof nameOrAction === 'string'
? { type: nameOrAction }
: nameOrAction,
get()
)
if (store === undefined) {
connection?.send(
nameOrAction === undefined
? { type: anonymousActionType || 'anonymous' }
: typeof nameOrAction === 'string'
? { type: nameOrAction }
: nameOrAction,
get()
)
return r
}
function getNameOrAction(
name?: string | { type: unknown }
): Action<unknown> {
if (name !== undefined && typeof name === 'string') {
return { type: name }
}
if (
name !== undefined &&
typeof name !== 'string' &&
store !== undefined
) {
return { type: `${store}/${name.type}` }
}
if (name !== undefined) {
return name
}
return { type: anonymousActionType || 'anonymous' }
}
connection?.send(getNameOrAction(nameOrAction), {
...getCurrentStoresStates(),
[store]: { ...api.getState(), store },
})
return r
}

const setStateFromDevtools: StoreApi<S>['setState'] = (...a) => {
const originalIsRecording = isRecording
isRecording = false
Expand All @@ -197,7 +257,18 @@ const devtoolsImpl: DevtoolsImpl =
}

const initialState = fn(api.setState, get, api)
extension.init(initialState)
if (store === undefined) {
connection?.init(initialState)
} else {
storeApis.push({ ...api, store })
initialStoreStates.push({ ...initialState, store })
const inits: Record<string, S> = {}
initialStoreStates.forEach((storeState) => {
inits[storeState.store] = storeState
})
connection?.init(inits)
console.warn('zustand initialized with initial state', inits)
}

if (
(api as any).dispatchFromDevtools &&
Expand All @@ -222,7 +293,7 @@ const devtoolsImpl: DevtoolsImpl =
}

;(
extension as unknown as {
connection as unknown as {
// FIXME https://github.com/reduxjs/redux-devtools/issues/1097
subscribe: (
listener: (message: Message) => void
Expand All @@ -241,8 +312,19 @@ const devtoolsImpl: DevtoolsImpl =
message.payload,
(action) => {
if (action.type === '__setState') {
setStateFromDevtools(action.state as PartialState)
return
if (action.type === '__setState') {
if (store === undefined) {
setStateFromDevtools(action.state as PartialState)
return
}
if (
JSON.stringify(api.getState()) !==
JSON.stringify((action.state as S)[store])
) {
setStateFromDevtools(action.state as S)
}
return
}
}

if (!(api as any).dispatchFromDevtools) return
Expand All @@ -254,31 +336,56 @@ const devtoolsImpl: DevtoolsImpl =
case 'DISPATCH':
switch (message.payload.type) {
case 'RESET':
setStateFromDevtools(initialState)
return extension.init(api.getState())
setStateFromDevtools(initialState as S)
if (store === undefined) {
return connection?.init(api.getState())
}
return connection?.init(getCurrentStoresStates())

case 'COMMIT':
return extension.init(api.getState())
if (store === undefined) {
connection?.init(api.getState())
return
}
return connection?.init(getCurrentStoresStates())

case 'ROLLBACK':
return parseJsonThen<S>(message.state, (state) => {
setStateFromDevtools(state)
extension.init(api.getState())
if (store === undefined) {
setStateFromDevtools(state)
connection?.init(api.getState())
return
}
setStateFromDevtools(state[store] as S)
connection?.init(getCurrentStoresStates())
})

case 'JUMP_TO_STATE':
case 'JUMP_TO_ACTION':
return parseJsonThen<S>(message.state, (state) => {
setStateFromDevtools(state)
if (store === undefined) {
setStateFromDevtools(state)
return
}
if (
JSON.stringify(api.getState()) !==
JSON.stringify(state[store])
) {
setStateFromDevtools(state[store] as S)
}
})

case 'IMPORT_STATE': {
const { nextLiftedState } = message.payload
const lastComputedState =
nextLiftedState.computedStates.slice(-1)[0]?.state
if (!lastComputedState) return
setStateFromDevtools(lastComputedState)
extension.send(
if (store === undefined) {
setStateFromDevtools(lastComputedState)
} else {
setStateFromDevtools(lastComputedState[store])
}
connection?.send(
null as any, // FIXME no-any
nextLiftedState
)
Expand Down