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(usestore): use selector to replace depActions #161

Merged
merged 3 commits into from
May 19, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
33 changes: 0 additions & 33 deletions __test__/depActions.spec.ts

This file was deleted.

40 changes: 40 additions & 0 deletions __test__/selector/model.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/// <reference path="../index.d.ts" />
import { renderHook } from '@testing-library/react-hooks'
import { Model } from '../../src'
import { Counter } from '..'

describe('selector', () => {
test("model's selector", async () => {
let isCounterOdd: boolean = true,
state: any
let actionsFirst: any, actionsSecond: any
let renderTime = 0
const { useStore, actions } = Model(Counter)
renderHook(() => {
;[isCounterOdd, actionsFirst] = useStore(({ count }) => count % 2 !== 0)
renderTime += 1
})
renderHook(() => {
;[state, actionsSecond] = useStore()
})
expect(isCounterOdd).toBe(false)
expect(state.count).toBe(0)
expect(renderTime).toBe(1)
await actionsFirst.increment(3)
expect(isCounterOdd).toBe(true)
expect(state.count).toBe(3)
expect(renderTime).toBe(2)
await actionsSecond.increment(4)
expect(isCounterOdd).toBe(true)
expect(state.count).toBe(7)
expect(renderTime).toBe(2)
await actions.increment(4)
expect(isCounterOdd).toBe(true)
expect(state.count).toBe(11)
expect(renderTime).toBe(2)
await actions.add(1)
expect(isCounterOdd).toBe(false)
expect(state.count).toBe(12)
expect(renderTime).toBe(3)
})
})
43 changes: 43 additions & 0 deletions __test__/selector/models.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/// <reference path="../index.d.ts" />
import { renderHook } from '@testing-library/react-hooks'
import { Model } from '../../src'
import { Counter } from '..'

describe('selector', () => {
test("models' selector", async () => {
let isCounterOdd: boolean = true,
state: any
let actionsFirst: any, actionsSecond: any
let renderTime = 0
const { useStore, actions } = Model({ Counter })
renderHook(() => {
;[isCounterOdd, actionsFirst] = useStore(
'Counter',
({ count }) => count % 2 !== 0
)
renderTime += 1
})
renderHook(() => {
;[state, actionsSecond] = useStore('Counter')
})
expect(isCounterOdd).toBe(false)
expect(state.count).toBe(0)
expect(renderTime).toBe(1)
await actionsFirst.increment(3)
expect(isCounterOdd).toBe(true)
expect(state.count).toBe(3)
expect(renderTime).toBe(2)
await actionsSecond.increment(4)
expect(isCounterOdd).toBe(true)
expect(state.count).toBe(7)
expect(renderTime).toBe(2)
await actions.Counter.increment(4)
expect(isCounterOdd).toBe(true)
expect(state.count).toBe(11)
expect(renderTime).toBe(2)
await actions.Counter.add(1)
expect(isCounterOdd).toBe(false)
expect(state.count).toBe(12)
expect(renderTime).toBe(3)
})
})
52 changes: 52 additions & 0 deletions __test__/selector/shallowEqual.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/// <reference path="../index.d.ts" />
import { renderHook } from '@testing-library/react-hooks'
import { Model } from '../../src'
import { Counter } from '..'

describe('selector', () => {
test("model's selector", async () => {
let selectedState: { odd: boolean; count?: number } = { odd: true },
state: any
let actionsFirst: any, actionsSecond: any
let renderTime = 0
const { useStore, actions } = Model(Counter)
renderHook(() => {
;[selectedState, actionsFirst] = useStore(({ count }) =>
count < 10
? {
odd: count % 2 !== 0
}
: {
count,
odd: count % 2 !== 0
}
)
renderTime += 1
})
renderHook(() => {
;[state, actionsSecond] = useStore()
})
expect(selectedState.odd).toBe(false)
expect(state.count).toBe(0)
expect(renderTime).toBe(1)
await actionsFirst.increment(3)
// odd state change, rerender
expect(selectedState.odd).toBe(true)
expect(state.count).toBe(3)
expect(renderTime).toBe(2)
await actionsSecond.increment(4)
expect(selectedState.odd).toBe(true)
expect(state.count).toBe(7)
expect(renderTime).toBe(2)
await actions.increment(4)
// selected keys num + 1, rerender
expect(selectedState.odd).toBe(true)
expect(state.count).toBe(11)
expect(renderTime).toBe(3)
await actions.add(1)
// odd state change, rerender
expect(selectedState.odd).toBe(false)
expect(state.count).toBe(12)
expect(renderTime).toBe(4)
})
})
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-model",
"version": "3.1.2",
"version": "4.0.0-rc.0",
"description": "The State management library for React",
"main": "./dist/react-model.js",
"umd:main": "./dist/react-model.umd.js",
Expand Down
28 changes: 28 additions & 0 deletions src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,39 @@ const getCache = (modelName: string, actionName: string) => {
return JSONString ? JSON.parse(JSONString) : null
}

const shallowEqual = (objA: any, objB: any) => {
if (objA === objB) return true
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false
}
const keysA = Object.keys(objA)
const keysB = Object.keys(objB)

if (keysA.length !== keysB.length) return false

for (let i = 0; i < keysA.length; i++) {
if (
!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
objA[keysA[i]] !== objB[keysA[i]]
) {
return false
}
}

return true
}

export {
Consumer,
consumerActions,
GlobalContext,
setPartialState,
shallowEqual,
timeout,
getCache,
getInitialState
Expand Down
53 changes: 45 additions & 8 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ type FunctionSetter = {
[modelName: string]: {
[actionName: string]: {
setState: React.Dispatch<any>
depActions?: string[]
selector?: Function
selectorRef?: unknown
}
}
}

type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we improve here?

? 1
: 2
? true
: false

interface Global {
Actions: {
[modelName: string]: {
Expand Down Expand Up @@ -108,12 +115,26 @@ interface Models<State = any, ActionKeys = any, ExtContext extends {} = {}> {
| API<ModelType<State, ActionKeys, {}>>
}

type Selector<S, R> = (state: S) => R

interface API<MT extends ModelType = ModelType<any, any, {}>> {
__id: string
__ERROR__?: boolean
useStore: (
depActions?: Array<keyof MT['actions']>
) => [Get<MT, 'state'>, getConsumerActionsType<Get<MT, 'actions'>>]
useStore: <
F extends Selector<Get<MT, 'state'>, any> = Selector<
Get<MT, 'state'>,
unknown
>
>(
selector?: F
) => [
F extends Selector<Get<MT, 'state'>, any>
? Equals<F, Selector<Get<MT, 'state'>, unknown>> extends true
? Get<MT, 'state'>
: ReturnType<F>
: Get<MT, 'state'>,
getConsumerActionsType<Get<MT, 'actions'>>
]
getState: () => Readonly<Get<MT, 'state'>>
subscribe: (
actionName: keyof MT['actions'] | Array<keyof MT['actions']>,
Expand All @@ -126,13 +147,29 @@ interface API<MT extends ModelType = ModelType<any, any, {}>> {
}

interface APIs<M extends Models> {
useStore: <K extends keyof M>(
useStore: <
K extends keyof M,
S extends M[K] extends API
? ArgumentTypes<Get<M[K], 'useStore'>>[1]
: M[K] extends ModelType
? Selector<Get<M[K], 'state'>, unknown>
: any
>(
name: K,
depActions?: Array<keyof Get<M[K], 'actions'>>
selector?: S
) => M[K] extends API
? ReturnType<Get<M[K], 'useStore'>>
? S extends (...args: any) => void
? ReturnType<S>
: ReturnType<Get<M[K], 'useStore'>>
: M[K] extends ModelType
? [Get<M[K], 'state'>, getConsumerActionsType<Get<M[K], 'actions'>>]
? S extends (...args: any) => void
? [
Equals<ReturnType<S>, unknown> extends true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unknown => any, see: :157

? Get<M[K], 'state'>
: ReturnType<S>,
getConsumerActionsType<Get<M[K], 'actions'>>
]
: [Get<M[K], 'state'>, getConsumerActionsType<Get<M[K], 'actions'>>]
: any

getState: <K extends keyof M>(
Expand Down
12 changes: 7 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ function Model<M extends Models, MT extends ModelType, E>(
unsubscribe: (
actionName: keyof MT['actions'] | Array<keyof MT['actions']>
) => unsubscribe(hash, actionName as string | string[]),
useStore: (depActions?: Array<keyof MT['actions']>) =>
useStore(hash, depActions as string[] | undefined)
useStore: (selector?: Function) => useStore(hash, selector)
}
} else {
if (models.actions) {
Expand Down Expand Up @@ -206,7 +205,7 @@ const getActions = (
return updaters
}

const useStore = (modelName: string, depActions?: string[]) => {
const useStore = (modelName: string, selector?: Function) => {
const setState = useState({})[1]
const hash = useRef<string>('')

Expand All @@ -219,7 +218,7 @@ const useStore = (modelName: string, depActions?: string[]) => {
}
Global.Setter.functionSetter[modelName][local_hash] = {
setState,
depActions
selector
}
return function cleanup() {
delete Global.Setter.functionSetter[modelName][local_hash]
Expand All @@ -230,7 +229,10 @@ const useStore = (modelName: string, depActions?: string[]) => {
__hash: hash.current,
type: 'function'
})
return [getState(modelName), updaters]
return [
selector ? selector(getState(modelName)) : getState(modelName),
updaters
]
}

// Class API
Expand Down
15 changes: 9 additions & 6 deletions src/middlewares.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getCache, setPartialState, timeout } from './helper'
import { getCache, setPartialState, timeout, shallowEqual } from './helper'
// -- Middlewares --

const config: MiddlewareConfig = {
Expand Down Expand Up @@ -142,19 +142,22 @@ const devToolsListener: Middleware = async (context, restMiddlewares) => {
}

const communicator: Middleware = async (context, restMiddlewares) => {
const { modelName, next, actionName, Global } = context
const { modelName, next, Global } = context
if (Global.Setter.classSetter) {
Global.Setter.classSetter(Global.State)
}
if (Global.Setter.functionSetter[modelName]) {
Object.keys(Global.Setter.functionSetter[modelName]).map((key) => {
const setter = Global.Setter.functionSetter[modelName][key]
if (setter) {
if (
!setter.depActions ||
setter.depActions.indexOf(actionName) !== -1
) {
if (!setter.selector) {
setter.setState(Global.State[modelName])
} else {
const newSelectorRef = setter.selector(Global.State[modelName])
if (!shallowEqual(newSelectorRef, setter.selectorRef)) {
setter.selectorRef = newSelectorRef
setter.setState(Global.State[modelName])
}
}
}
})
Expand Down