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 1 commit
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.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)
})
})
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
55 changes: 47 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,21 @@ 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?: F
) => [
F extends Selector<Get<MT, 'state'>, any>
? Equals<F, Selector<Get<MT, 'state'>, any>> 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 +142,36 @@ interface API<MT extends ModelType = ModelType<any, any, {}>> {
}

interface APIs<M extends Models> {
useStore: <K extends keyof M>(
useStore: // | (<K extends keyof M>(
// name: K
// ) => M[K] extends API
// ? ReturnType<Get<M[K], 'useStore'>>
// : M[K] extends ModelType
// ? [Get<M[K], 'state'>, getConsumerActionsType<Get<M[K], 'actions'>>]
// : any)
<
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'>, any>
: 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
10 changes: 6 additions & 4 deletions src/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,18 +142,20 @@ 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 if (
setter.selector(Global.State[modelName]) !== setter.selectorRef
) {
setter.selectorRef = setter.selector(Global.State[modelName])
Copy link
Contributor

Choose a reason for hiding this comment

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

React will check state as shadowEq, double check here is heavy.

setter.setState(Global.State[modelName])
}
}
Expand Down