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

WIP Rethinking actions and action creation #182

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ Returns **[store](#store)**

An observable state container, returned from [createStore](#createstore)

##### action
##### dispatch

Create a bound copy of the given action function.
The bound returned function invokes action() and persists the result back to the store.
Expand Down
11 changes: 8 additions & 3 deletions devtools.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@ module.exports = function unistoreDevTools(store) {
}
});
store.devtools.init(store.getState());
store.subscribe(function (state, action) {
var actionName = action && action.name || 'setState';
store.subscribe(function (state, action, update) {
update = update || {};
var actionName = action
? action.type ||
action.name ||
'N/A (' + (Object.keys(update).join(', ') || 'none') + ')'
: 'setState (' + (Object.keys(update).join(', ') || 'none') + ')';

if (!ignoreState) {
store.devtools.send(actionName, state);
store.devtools.send({ type: actionName, update: update }, state);
} else {
ignoreState = false;
}
Expand Down
43 changes: 31 additions & 12 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,40 @@
// K - Store state
// I - Injected props to wrapped component

export type Listener<K> = (state: K, action?: Action<K>) => void;
export type Listener<K> = (state: K, action?: Action<K>, update?: Partial<K>) => void;
export type Unsubscribe = () => void;
export type Action<K> = (state: K, ...args: any[]) => void;
export type BoundAction = (...args: any[]) => void;

export type AsyncActionFn<K> = (getState: () => K, action: (action: Action<K>) => Promise<void> | void) => Promise<Partial<K> | void>;
export type SyncActionFn<K> = (getState: () => K, action: (action: Action<K>) => Promise<void> | void) => Partial<K> | void;
export type ActionFn<K> = AsyncActionFn<K> | SyncActionFn<K>;

export type AsyncActionObject<K> = {
type: string;
action: AsyncActionFn<K>;
}
export type SyncActionObject<K> = {
type: string;
action: SyncActionFn<K>;
}
export type ActionObject<K> = AsyncActionObject<K> | SyncActionObject<K>;

export type Action<K> = ActionObject<K> | ActionFn<K>;

export type AsyncActionCreator<K> = (...args: any[]) => AsyncActionFn<K> | AsyncActionObject<K>;
export type SyncActionCreator<K> = (...args: any[]) => SyncActionFn<K> | SyncActionObject<K>;
export type ActionCreator<K> = AsyncActionCreator<K> | SyncActionCreator<K>;

export type ActionCreatorsObject<K> = {
[actionCreator: string]: ActionCreator<K>
}

export type MappedActionCreators<A> = {
[P in keyof A]: A[P] extends AsyncActionCreator<any> ? (...args: any[]) => Promise<void> : (...args: any[]) => void
}


export interface Store<K> {
action(action: Action<K>): BoundAction;
dispatch(action: Action<K>): Promise<void> | void;
setState<U extends keyof K>(update: Pick<K, U>, overwrite?: boolean, action?: Action<K>): void;
subscribe(f: Listener<K>): Unsubscribe;
unsubscribe(f: Listener<K>): void;
Expand All @@ -18,12 +45,4 @@ export interface Store<K> {

export default function createStore<K>(state?: K): Store<K>;

export type ActionFn<K> = (state: K, ...args: any[]) => Promise<Partial<K>> | Partial<K> | void;

export interface ActionMap<K> {
[actionName: string]: ActionFn<K>;
}

export type ActionCreator<K> = (store: Store<K>) => ActionMap<K>;

export type StateMapper<T, K, I> = (state: K, props: T) => I;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"eslintConfig": {
"extends": "eslint-config-developit",
"rules": {
"prefer-rest-params": 0
"prefer-rest-params": 0,
"prefer-spread": 0
}
},
"bundlesize": [
Expand Down
18 changes: 9 additions & 9 deletions preact.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@

declare module 'unistore/preact' {
import * as Preact from 'preact';
import { ActionCreator, StateMapper, Store } from 'unistore';
import { StateMapper, Store, ActionCreatorsObject, MappedActionCreators } from 'unistore';

export function connect<T, S, K, I>(
mapStateToProps: string | Array<string> | StateMapper<T, K, I>,
actions?: ActionCreator<K> | object
export function connect<T, S, K, I, A extends ActionCreatorsObject<K>>(
mapStateToProps: string | Array<string> | StateMapper<T, K, I> | null,
actions?: A,
): (
Child: Preact.ComponentConstructor<T & I, S> | Preact.AnyComponent<T & I, S>
Child: Preact.ComponentConstructor<T & I & MappedActionCreators<A>, S> | Preact.AnyComponent<T & I & MappedActionCreators<A>, S>
) => Preact.ComponentConstructor<T | T & I, S>;

export interface ProviderProps<T> {
store: Store<T>;
export interface ProviderProps<K> {
store: Store<K>;
}

export class Provider<T> extends Preact.Component<ProviderProps<T>> {
render(props: ProviderProps<T>): Preact.JSX.Element;
export class Provider<K> extends Preact.Component<ProviderProps<K>> {
render(props: ProviderProps<K>): Preact.JSX.Element;
}
}
17 changes: 9 additions & 8 deletions react.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@
// S - Wrapped component state
// K - Store state
// I - Injected props to wrapped component
// A - actions

declare module 'unistore/react' {
import * as React from 'react';
import { ActionCreator, StateMapper, Store } from 'unistore';
import { StateMapper, Store, ActionCreatorsObject, MappedActionCreators } from 'unistore';

export function connect<T, S, K, I>(
mapStateToProps: string | Array<string> | StateMapper<T, K, I>,
actions?: ActionCreator<K> | object
export function connect<T, S, K, I, A extends ActionCreatorsObject<K>>(
mapStateToProps: string | Array<string> | StateMapper<T, K, I> | null,
actions?: A,
): (
Child: ((props: T & I) => React.ReactNode) | React.ComponentClass<T & I, S> | React.FC<T & I>
Child: ((props: T & I & MappedActionCreators<A>) => React.ReactNode) | React.ComponentClass<T & I & MappedActionCreators<A>, S> | React.FC<T & I & MappedActionCreators<A>>
) => React.ComponentClass<T | T & I, S> | React.FC<T | T & I>;

export interface ProviderProps<T> {
store: Store<T>;
export interface ProviderProps<K> {
store: Store<K>;
}

export class Provider<T> extends React.Component<ProviderProps<T>, {}> {
export class Provider<K> extends React.Component<ProviderProps<K>, {}> {
render(): React.ReactNode;
}

Expand Down
38 changes: 18 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,25 @@ export default function createStore(state) {
listeners = out;
}

function dispatch(action) {
function apply(result) {
setState(result, false, action);
}
let ret = (action.action || action)(getState, dispatch);
if (ret != null) {
if (ret.then) return ret.then(apply);
return apply(ret);
}
}

function getState() {
return state;
}

function setState(update, overwrite, action) {
state = overwrite ? update : assign(assign({}, state), update);
let currentListeners = listeners;
for (let i=0; i<currentListeners.length; i++) currentListeners[i](state, action);
for (let i=0; i<currentListeners.length; i++) currentListeners[i](state, action, update);
}

/**
Expand All @@ -48,22 +63,7 @@ export default function createStore(state) {
* @param {Function} action An action of the form `action(state, ...args) -> stateUpdate`
* @returns {Function} boundAction()
*/
action(action) {
function apply(result) {
setState(result, false, action);
}

// Note: perf tests verifying this implementation: https://esbench.com/bench/5a295e6299634800a0349500
return function() {
let args = [state];
for (let i=0; i<arguments.length; i++) args.push(arguments[i]);
let ret = action.apply(this, args);
if (ret!=null) {
if (ret.then) return ret.then(apply);
return apply(ret);
}
};
},
dispatch,

/**
* Apply a partial state object to the current state, invoking registered listeners.
Expand Down Expand Up @@ -93,8 +93,6 @@ export default function createStore(state) {
* Retrieve the current state object.
* @returns {Object} state
*/
getState() {
return state;
}
getState
};
}
5 changes: 3 additions & 2 deletions src/util.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Bind an object/factory of actions to the store and wrap them.
export function mapActions(actions, store) {
if (typeof actions==='function') actions = actions(store);
let mapped = {};
for (let i in actions) {
mapped[i] = store.action(actions[i]);
mapped[i] = function () {
return store.dispatch(actions[i].apply(actions, arguments));
};
}
return mapped;
}
Expand Down
8 changes: 4 additions & 4 deletions test/preact/builds.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@ describe('build: default', () => {
describe('smoke test (preact)', () => {
it('should render', done => {
const { Provider, connect } = preact;
const actions = ({ getState, setState }) => ({
incrementTwice(state) {
setState({ count: state.count + 1 });
const actions = {
incrementTwice: () => (getState, dispatch) => {
dispatch(() => ({ count: getState().count + 1 }));
return new Promise(r =>
setTimeout(() => {
r({ count: getState().count + 1 });
}, 20)
);
}
});
};
const App = connect('count', actions)(({ count, incrementTwice }) => (
<button onClick={incrementTwice}>count: {count}</button>
));
Expand Down
8 changes: 4 additions & 4 deletions test/react/builds.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ describe('build: default', () => {
describe('smoke test (react)', () => {
it('should render', done => {
const { Provider, connect } = react;
const actions = ({ getState, setState }) => ({
incrementTwice(state) {
setState({ count: state.count + 1 });
const actions = {
incrementTwice: () => (getState, dispatch) => {
dispatch(() => ({ count: getState().count + 1 }))
return new Promise(r =>
setTimeout(() => {
r({ count: getState().count + 1 });
}, 20)
);
}
});
};
const App = connect('count', actions)(({ count, incrementTwice }) => (
<button id="some_button" onClick={incrementTwice}>
count: {count}
Expand Down
12 changes: 7 additions & 5 deletions test/unistore.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,17 @@ describe('createStore()', () => {
let rval = store.subscribe(sub1);
expect(rval).toBeInstanceOf(Function);

store.setState({ a: 'b' });
expect(sub1).toBeCalledWith(store.getState(), action);
let update1 = { a: 'b' };
store.setState(update1);
expect(sub1).toBeCalledWith(store.getState(), action, update1);

store.subscribe(sub2);
store.setState({ c: 'd' });
let update2 = { c: 'd' };
store.setState(update2);

expect(sub1).toHaveBeenCalledTimes(2);
expect(sub1).toHaveBeenLastCalledWith(store.getState(), action);
expect(sub2).toBeCalledWith(store.getState(), action);
expect(sub1).toHaveBeenLastCalledWith(store.getState(), action, update2);
expect(sub2).toBeCalledWith(store.getState(), action, update2);
});

it('should unsubscribe', () => {
Expand Down