Comparing version 0.1.0 to 0.1.1
'use strict'; | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var React = require('react'); | ||
var React__default = _interopDefault(React); | ||
@@ -52,15 +49,6 @@ function _extends() { | ||
}; | ||
return React__default.createElement(Context.Provider, Object.assign({}, props, { | ||
return React.createElement(Context.Provider, Object.assign({}, props, { | ||
value: value | ||
})); | ||
}; | ||
function createStore(_ref2) { | ||
var initialState = _ref2.initialState, | ||
actions = _ref2.actions; | ||
return _extends({}, actions, { | ||
initialState: initialState, | ||
id: Symbol(), | ||
subscriptions: new Set() | ||
}); | ||
} | ||
function useStateContext() { | ||
@@ -76,151 +64,58 @@ var ctx = React.useContext(Context); | ||
function isStateUpdaterFunction(updater) { | ||
return typeof updater === 'function'; | ||
} | ||
function isPromise(p) { | ||
return 'then' in p && typeof p.then === 'function'; | ||
} | ||
function createDispatcher(context, opt) { | ||
function dispatch(store, actionName) { | ||
var autoCommit = !opt; | ||
var changesSet = opt ? opt.changesSet : new Set(); | ||
var changesMap = opt ? opt.changesMap : new WeakMap(); | ||
var commit = opt ? opt.commit : function () { | ||
var allSubscription = new Set(); | ||
changesSet.forEach(function (id) { | ||
context.states.set(id, changesMap.get(id)); | ||
var subscriptions = context.subscriptions.get(id); | ||
if (subscriptions) { | ||
subscriptions.forEach(function (fn) { | ||
return allSubscription.add(fn); | ||
}); | ||
} | ||
}); | ||
allSubscription.forEach(function (fn) { | ||
try { | ||
fn(); | ||
} catch (e) { | ||
console.error('Error when calling subscription', e); | ||
} | ||
}); | ||
changesSet.clear(); | ||
changesMap = new WeakMap(); | ||
}; | ||
var getState = function getState() { | ||
return changesMap.get(store) || getOrFillState(context, store); | ||
}; | ||
var setState = function setState(updater, forceCommit) { | ||
if (forceCommit === void 0) { | ||
forceCommit = false; | ||
function createStore(_ref) { | ||
var initialState = _ref.initialState, | ||
actions = _ref.actions; | ||
var data = { | ||
initialState: initialState | ||
}; | ||
var transformedAction = Object.keys(actions).reduce(function (result, key) { | ||
result[key] = function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var state; | ||
var fn = function fn(ctx) { | ||
return actions[key].apply(actions, [ctx].concat(args)); | ||
}; | ||
if (isStateUpdaterFunction(updater)) { | ||
state = updater(getState()); | ||
} else { | ||
state = updater; | ||
} | ||
changesSet.add(store); | ||
changesMap.set(store, state); | ||
if (forceCommit) { | ||
commit(); | ||
} | ||
fn.store = data; | ||
return fn; | ||
}; | ||
var childDispatcher = createDispatcher(context, { | ||
changesMap: changesMap, | ||
commit: commit, | ||
changesSet: changesSet | ||
}); | ||
var actionContext = { | ||
state: getState(), | ||
getState: getState, | ||
setState: setState, | ||
commit: commit, | ||
disableAutoCommit: function disableAutoCommit() { | ||
autoCommit = false; | ||
}, | ||
call: function call(action) { | ||
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
args[_key2 - 1] = arguments[_key2]; | ||
} | ||
return action.apply(void 0, [actionContext].concat(args)); | ||
}, | ||
getStore: function getStore(otherStore) { | ||
return changesMap.get(otherStore) || getOrFillState(context, otherStore); | ||
}, | ||
dispatch: childDispatcher | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { | ||
args[_key - 2] = arguments[_key]; | ||
} | ||
var result = store[actionName].apply(store, [actionContext].concat(args)); | ||
if (autoCommit) { | ||
if (isPromise(result)) { | ||
result.then(function () { | ||
return commit(); | ||
}); | ||
} else { | ||
commit(); | ||
} | ||
} | ||
return result; | ||
} | ||
return dispatch; | ||
}, {}); | ||
return _extends({}, transformedAction, { | ||
_storeData: data | ||
}); | ||
} | ||
function useDispatcher() { | ||
var ctx = useStateContext(); | ||
return React.useMemo(function () { | ||
return createDispatcher(ctx); | ||
}, [ctx]); | ||
} | ||
function useAction(store, action) { | ||
var dispatch = useDispatcher(); | ||
return React.useCallback(function () { | ||
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | ||
args[_key3] = arguments[_key3]; | ||
} | ||
var defaultMapState = function defaultMapState(state) { | ||
return state; | ||
}; | ||
return dispatch.apply(void 0, [store, action].concat(args)); | ||
}, [dispatch]); | ||
} | ||
function defaultMapState(s) { | ||
return s; | ||
} | ||
function defaultStateComparator(prev, current) { | ||
if (typeof prev !== typeof current) { | ||
function deepEqual(a, b) { | ||
if (typeof a !== typeof b) { | ||
return false; | ||
} | ||
if (Array.isArray(prev) && Array.isArray(current)) { | ||
return prev.length === current.length && prev.every(function (item, i) { | ||
return defaultStateComparator(item, current[i]); | ||
if (Array.isArray(a) && Array.isArray(b)) { | ||
return a.length === b.length && a.every(function (item, i) { | ||
return deepEqual(item, b[i]); | ||
}); | ||
} else if (typeof prev === 'object' && typeof current === 'object') { | ||
var prevKeys = Object.keys(prev); | ||
return defaultStateComparator(prevKeys, Object.keys(current)) && prevKeys.every(function (key) { | ||
return defaultStateComparator(prev[key], current[key]); | ||
} else if (typeof a === 'object' && typeof b === 'object') { | ||
var keys = Object.keys(a); | ||
return deepEqual(keys, Object.keys(b)) && keys.every(function (key) { | ||
return deepEqual(a[key], b[key]); | ||
}); | ||
} | ||
return prev === current; | ||
return a === b; | ||
} | ||
function defaultStateComparator(prev, current) { | ||
return !deepEqual(prev, current); | ||
} // export function defaultStateComparator(): boolean { | ||
// return true; | ||
// } | ||
function subscribeToStateChange(ctx, store, fn) { | ||
@@ -239,12 +134,10 @@ var set = ctx.subscriptions.get(store); | ||
} | ||
function getOrFillState(ctx, store) { | ||
var state = ctx.states.get(store); | ||
if (!state) { | ||
state = store.initialState; | ||
if (!ctx.states.has(store)) { | ||
var state = store.initialState; | ||
ctx.states.set(store, state); | ||
return state; | ||
} | ||
return state; | ||
return ctx.states.get(store); | ||
} | ||
@@ -264,3 +157,3 @@ | ||
var _useState = React.useState(function () { | ||
return mapState(getOrFillState(ctx, store)); | ||
return mapState(getOrFillState(ctx, store._storeData)); | ||
}), | ||
@@ -272,3 +165,3 @@ current = _useState[0], | ||
var subscription = function subscription() { | ||
var newState = getOrFillState(ctx, store); | ||
var newState = getOrFillState(ctx, store._storeData); | ||
var newRes = mapState(newState); | ||
@@ -282,6 +175,7 @@ var shouldUpdate = mapState === defaultMapState && comparator === defaultStateComparator ? current !== newRes : comparator(current, newRes); | ||
return subscribeToStateChange(ctx, store, subscription); | ||
}, []); | ||
return subscribeToStateChange(ctx, store._storeData, subscription); | ||
}, [ctx, current]); | ||
return current; | ||
} | ||
function useStores(stores, mapState, comparator) { | ||
@@ -298,7 +192,7 @@ if (mapState === void 0) { | ||
var _useState2 = React.useState(function () { | ||
var _useState = React.useState(function () { | ||
return mapState(getOrFileStateObject(ctx, stores)); | ||
}), | ||
current = _useState2[0], | ||
setCurrentValue = _useState2[1]; | ||
current = _useState[0], | ||
setCurrentValue = _useState[1]; | ||
@@ -317,3 +211,3 @@ React.useEffect(function () { | ||
var unsubscribeFunctions = Object.values(stores).map(function (store) { | ||
return subscribeToStateChange(ctx, store, subscriptionFn); | ||
return subscribeToStateChange(ctx, store._storeData, subscriptionFn); | ||
}); | ||
@@ -325,3 +219,3 @@ return function () { | ||
}; | ||
}, []); | ||
}, [ctx, current]); | ||
return current; | ||
@@ -332,3 +226,3 @@ } | ||
return Object.keys(stores).reduce(function (result, key) { | ||
result[key] = getOrFillState(ctx, stores[key]); | ||
result[key] = getOrFillState(ctx, stores[key]._storeData); | ||
return result; | ||
@@ -338,2 +232,107 @@ }, {}); | ||
function isStateUpdaterFunction(updater) { | ||
return typeof updater === 'function'; | ||
} | ||
function isPromise(p) { | ||
return 'then' in p && typeof p.then === 'function'; | ||
} | ||
function createDispatcher(context, opt) { | ||
return function (dispatchFn) { | ||
var autoCommit = !opt; | ||
var changesSet = opt ? opt.changesSet : new Set(); | ||
var changesMap = opt ? opt.changesMap : new WeakMap(); | ||
var commit = opt ? opt.commit : function () { | ||
var allSubscription = new Set(); | ||
changesSet.forEach(function (id) { | ||
context.states.set(id, changesMap.get(id)); | ||
var subscriptions = context.subscriptions.get(id); | ||
if (subscriptions) { | ||
subscriptions.forEach(function (fn) { | ||
return allSubscription.add(fn); | ||
}); | ||
} | ||
}); | ||
allSubscription.forEach(function (fn) { | ||
try { | ||
fn(); | ||
} catch (e) { | ||
console.error('Error when calling subscription', e); | ||
} | ||
}); | ||
changesSet.clear(); | ||
changesMap = new WeakMap(); | ||
}; | ||
var getState = function getState() { | ||
return changesMap.get(dispatchFn.store) || getOrFillState(context, dispatchFn.store); | ||
}; | ||
var result = dispatchFn({ | ||
state: getState(), | ||
getState: getState, | ||
setState: function setState(updater, forceCommit) { | ||
if (forceCommit === void 0) { | ||
forceCommit = false; | ||
} | ||
var state = isStateUpdaterFunction(updater) ? updater(getState()) : updater; | ||
changesSet.add(dispatchFn.store); | ||
changesMap.set(dispatchFn.store, state); | ||
if (forceCommit) { | ||
commit(); | ||
} | ||
}, | ||
commit: commit, | ||
disableAutoCommit: function disableAutoCommit() { | ||
autoCommit = false; | ||
}, | ||
getStore: function getStore(otherStore) { | ||
return changesMap.get(otherStore._storeData) || getOrFillState(context, otherStore._storeData); | ||
}, | ||
dispatch: createDispatcher(context, { | ||
changesMap: changesMap, | ||
commit: commit, | ||
changesSet: changesSet | ||
}) | ||
}); | ||
if (autoCommit) { | ||
if (result && isPromise(result)) { | ||
result.then(function () { | ||
return commit(); | ||
}); | ||
} else { | ||
commit(); | ||
} | ||
} | ||
return result; | ||
}; | ||
} | ||
function useDispatcher() { | ||
var ctx = useStateContext(); | ||
return React.useMemo(function () { | ||
return createDispatcher(ctx); | ||
}, [ctx]); | ||
} | ||
function useAction(action) { | ||
var dispatch = useDispatcher(); | ||
return React.useMemo(function () { | ||
if ('store' in action) { | ||
return function () { | ||
return dispatch(action); | ||
}; | ||
} else { | ||
return function () { | ||
return dispatch(action.apply(void 0, arguments)); | ||
}; | ||
} | ||
}, [dispatch]); | ||
} | ||
exports.StoreProvider = StoreProvider; | ||
@@ -343,5 +342,4 @@ exports.createStore = createStore; | ||
exports.useDispatcher = useDispatcher; | ||
exports.useStateContext = useStateContext; | ||
exports.useStore = useStore; | ||
exports.useStores = useStores; | ||
//# sourceMappingURL=el-state.cjs.development.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";var t,e=require("react"),n=(t=e)&&"object"==typeof t&&"default"in t?t.default:t;function r(){return(r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}var o=e.createContext(void 0);function i(){var t=e.useContext(o);if(!t)throw new Error("Not inside provider");return t}function u(){var t=i();return e.useMemo(function(){return function t(e,n){return function(r,o){for(var i=!n,u=n?n.changesSet:new Set,a=n?n.changesMap:new WeakMap,c=n?n.commit:function(){var t=new Set;u.forEach(function(n){e.states.set(n,a.get(n));var r=e.subscriptions.get(n);r&&r.forEach(function(e){return t.add(e)})}),t.forEach(function(t){try{t()}catch(t){console.error("Error when calling subscription",t)}}),u.clear(),a=new WeakMap},s=function(){return a.get(r)||f(e,r)},p=t(e,{changesMap:a,commit:c,changesSet:u}),v={state:s(),getState:s,setState:function(t,e){var n;void 0===e&&(e=!1),n=function(t){return"function"==typeof t}(t)?t(s()):t,u.add(r),a.set(r,n),e&&c()},commit:c,disableAutoCommit:function(){i=!1},call:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return t.apply(void 0,[v].concat(n))},getStore:function(t){return a.get(t)||f(e,t)},dispatch:p},l=arguments.length,y=new Array(l>2?l-2:0),d=2;d<l;d++)y[d-2]=arguments[d];var h,g=r[o].apply(r,[v].concat(y));return i&&("then"in(h=g)&&"function"==typeof h.then?g.then(function(){return c()}):c()),g}}(t)},[t])}function a(t){return t}function c(t,e){if(typeof t!=typeof e)return!1;if(Array.isArray(t)&&Array.isArray(e))return t.length===e.length&&t.every(function(t,n){return c(t,e[n])});if("object"==typeof t&&"object"==typeof e){var n=Object.keys(t);return c(n,Object.keys(e))&&n.every(function(n){return c(t[n],e[n])})}return t===e}function s(t,e,n){var r=t.subscriptions.get(e);return r||(r=new Set,t.subscriptions.set(e,r)),r.add(n),function(){r.delete(n)}}function f(t,e){var n=t.states.get(e);return n||t.states.set(e,n=e.initialState),n}function p(t,e){return Object.keys(e).reduce(function(n,r){return n[r]=f(t,e[r]),n},{})}exports.StoreProvider=function(t){var e=t.initialStates,r=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)e.indexOf(n=i[r])>=0||(o[n]=t[n]);return o}(t,["initialStates"]),i={states:e||new WeakMap,subscriptions:new WeakMap};return n.createElement(o.Provider,Object.assign({},r,{value:i}))},exports.createStore=function(t){return r({},t.actions,{initialState:t.initialState,id:Symbol(),subscriptions:new Set})},exports.useAction=function(t,n){var r=u();return e.useCallback(function(){for(var e=arguments.length,o=new Array(e),i=0;i<e;i++)o[i]=arguments[i];return r.apply(void 0,[t,n].concat(o))},[r])},exports.useDispatcher=u,exports.useStateContext=i,exports.useStore=function(t,n,r){void 0===n&&(n=a),void 0===r&&(r=c);var o=i(),u=e.useState(function(){return n(f(o,t))}),p=u[0],v=u[1];return e.useEffect(function(){return s(o,t,function(){var e=f(o,t),i=n(e);(n===a&&r===c?p!==i:r(p,i))&&v(i)})},[]),p},exports.useStores=function(t,n,r){void 0===n&&(n=a),void 0===r&&(r=c);var o=i(),u=e.useState(function(){return n(p(o,t))}),f=u[0],v=u[1];return e.useEffect(function(){var e=function(){var e=p(o,t),i=n(e);r(f,i)&&v(i)},i=Object.values(t).map(function(t){return s(o,t,e)});return function(){i.map(function(t){return t()})}},[]),f}; | ||
"use strict";var t=require("react");function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}var r=t.createContext(void 0);function n(){var e=t.useContext(r);if(!e)throw new Error("Not inside provider");return e}var o=function(t){return t};function u(t,e){return!function t(e,r){if(typeof e!=typeof r)return!1;if(Array.isArray(e)&&Array.isArray(r))return e.length===r.length&&e.every(function(e,n){return t(e,r[n])});if("object"==typeof e&&"object"==typeof r){var n=Object.keys(e);return t(n,Object.keys(r))&&n.every(function(n){return t(e[n],r[n])})}return e===r}(t,e)}function i(t,e,r){var n=t.subscriptions.get(e);return n||(n=new Set,t.subscriptions.set(e,n)),n.add(r),function(){n.delete(r)}}function a(t,e){if(!t.states.has(e)){var r=e.initialState;return t.states.set(e,r),r}return t.states.get(e)}function c(t,e){return Object.keys(e).reduce(function(r,n){return r[n]=a(t,e[n]._storeData),r},{})}function s(){var e=n();return t.useMemo(function(){return function t(e,r){return function(n){var o,u=!r,i=r?r.changesSet:new Set,c=r?r.changesMap:new WeakMap,s=r?r.commit:function(){var t=new Set;i.forEach(function(r){e.states.set(r,c.get(r));var n=e.subscriptions.get(r);n&&n.forEach(function(e){return t.add(e)})}),t.forEach(function(t){try{t()}catch(t){console.error("Error when calling subscription",t)}}),i.clear(),c=new WeakMap},f=function(){return c.get(n.store)||a(e,n.store)},v=n({state:f(),getState:f,setState:function(t,e){void 0===e&&(e=!1);var r=function(t){return"function"==typeof t}(t)?t(f()):t;i.add(n.store),c.set(n.store,r),e&&s()},commit:s,disableAutoCommit:function(){u=!1},getStore:function(t){return c.get(t._storeData)||a(e,t._storeData)},dispatch:t(e,{changesMap:c,commit:s,changesSet:i})});return u&&(v&&"then"in(o=v)&&"function"==typeof o.then?v.then(function(){return s()}):s()),v}}(e)},[e])}exports.StoreProvider=function(e){var n=e.initialStates,o=function(t,e){if(null==t)return{};var r,n,o={},u=Object.keys(t);for(n=0;n<u.length;n++)e.indexOf(r=u[n])>=0||(o[r]=t[r]);return o}(e,["initialStates"]),u={states:n||new WeakMap,subscriptions:new WeakMap};return t.createElement(r.Provider,Object.assign({},o,{value:u}))},exports.createStore=function(t){var r=t.actions,n={initialState:t.initialState};return e({},Object.keys(r).reduce(function(t,e){return t[e]=function(){for(var t=arguments.length,o=new Array(t),u=0;u<t;u++)o[u]=arguments[u];var i=function(t){return r[e].apply(r,[t].concat(o))};return i.store=n,i},t},{}),{_storeData:n})},exports.useAction=function(e){var r=s();return t.useMemo(function(){return"store"in e?function(){return r(e)}:function(){return r(e.apply(void 0,arguments))}},[r])},exports.useDispatcher=s,exports.useStore=function(e,r,c){void 0===r&&(r=o),void 0===c&&(c=u);var s=n(),f=t.useState(function(){return r(a(s,e._storeData))}),v=f[0],p=f[1];return t.useEffect(function(){return i(s,e._storeData,function(){var t=a(s,e._storeData),n=r(t);(r===o&&c===u?v!==n:c(v,n))&&p(n)})},[s,v]),v},exports.useStores=function(e,r,a){void 0===r&&(r=o),void 0===a&&(a=u);var s=n(),f=t.useState(function(){return r(c(s,e))}),v=f[0],p=f[1];return t.useEffect(function(){var t=function(){var t=c(s,e),n=r(t);a(v,n)&&p(n)},n=Object.values(e).map(function(e){return i(s,e._storeData,t)});return function(){n.map(function(t){return t()})}},[s,v]),v}; | ||
//# sourceMappingURL=el-state.cjs.production.min.js.map |
@@ -1,2 +0,2 @@ | ||
import React, { useContext, useMemo, useCallback, useState, useEffect, createContext } from 'react'; | ||
import { createElement, createContext, useContext, useState, useEffect, useMemo } from 'react'; | ||
@@ -47,15 +47,6 @@ function _extends() { | ||
}; | ||
return React.createElement(Context.Provider, Object.assign({}, props, { | ||
return createElement(Context.Provider, Object.assign({}, props, { | ||
value: value | ||
})); | ||
}; | ||
function createStore(_ref2) { | ||
var initialState = _ref2.initialState, | ||
actions = _ref2.actions; | ||
return _extends({}, actions, { | ||
initialState: initialState, | ||
id: Symbol(), | ||
subscriptions: new Set() | ||
}); | ||
} | ||
function useStateContext() { | ||
@@ -71,151 +62,58 @@ var ctx = useContext(Context); | ||
function isStateUpdaterFunction(updater) { | ||
return typeof updater === 'function'; | ||
} | ||
function isPromise(p) { | ||
return 'then' in p && typeof p.then === 'function'; | ||
} | ||
function createDispatcher(context, opt) { | ||
function dispatch(store, actionName) { | ||
var autoCommit = !opt; | ||
var changesSet = opt ? opt.changesSet : new Set(); | ||
var changesMap = opt ? opt.changesMap : new WeakMap(); | ||
var commit = opt ? opt.commit : function () { | ||
var allSubscription = new Set(); | ||
changesSet.forEach(function (id) { | ||
context.states.set(id, changesMap.get(id)); | ||
var subscriptions = context.subscriptions.get(id); | ||
if (subscriptions) { | ||
subscriptions.forEach(function (fn) { | ||
return allSubscription.add(fn); | ||
}); | ||
} | ||
}); | ||
allSubscription.forEach(function (fn) { | ||
try { | ||
fn(); | ||
} catch (e) { | ||
console.error('Error when calling subscription', e); | ||
} | ||
}); | ||
changesSet.clear(); | ||
changesMap = new WeakMap(); | ||
}; | ||
var getState = function getState() { | ||
return changesMap.get(store) || getOrFillState(context, store); | ||
}; | ||
var setState = function setState(updater, forceCommit) { | ||
if (forceCommit === void 0) { | ||
forceCommit = false; | ||
function createStore(_ref) { | ||
var initialState = _ref.initialState, | ||
actions = _ref.actions; | ||
var data = { | ||
initialState: initialState | ||
}; | ||
var transformedAction = Object.keys(actions).reduce(function (result, key) { | ||
result[key] = function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var state; | ||
var fn = function fn(ctx) { | ||
return actions[key].apply(actions, [ctx].concat(args)); | ||
}; | ||
if (isStateUpdaterFunction(updater)) { | ||
state = updater(getState()); | ||
} else { | ||
state = updater; | ||
} | ||
changesSet.add(store); | ||
changesMap.set(store, state); | ||
if (forceCommit) { | ||
commit(); | ||
} | ||
fn.store = data; | ||
return fn; | ||
}; | ||
var childDispatcher = createDispatcher(context, { | ||
changesMap: changesMap, | ||
commit: commit, | ||
changesSet: changesSet | ||
}); | ||
var actionContext = { | ||
state: getState(), | ||
getState: getState, | ||
setState: setState, | ||
commit: commit, | ||
disableAutoCommit: function disableAutoCommit() { | ||
autoCommit = false; | ||
}, | ||
call: function call(action) { | ||
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
args[_key2 - 1] = arguments[_key2]; | ||
} | ||
return action.apply(void 0, [actionContext].concat(args)); | ||
}, | ||
getStore: function getStore(otherStore) { | ||
return changesMap.get(otherStore) || getOrFillState(context, otherStore); | ||
}, | ||
dispatch: childDispatcher | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { | ||
args[_key - 2] = arguments[_key]; | ||
} | ||
var result = store[actionName].apply(store, [actionContext].concat(args)); | ||
if (autoCommit) { | ||
if (isPromise(result)) { | ||
result.then(function () { | ||
return commit(); | ||
}); | ||
} else { | ||
commit(); | ||
} | ||
} | ||
return result; | ||
} | ||
return dispatch; | ||
}, {}); | ||
return _extends({}, transformedAction, { | ||
_storeData: data | ||
}); | ||
} | ||
function useDispatcher() { | ||
var ctx = useStateContext(); | ||
return useMemo(function () { | ||
return createDispatcher(ctx); | ||
}, [ctx]); | ||
} | ||
function useAction(store, action) { | ||
var dispatch = useDispatcher(); | ||
return useCallback(function () { | ||
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | ||
args[_key3] = arguments[_key3]; | ||
} | ||
var defaultMapState = function defaultMapState(state) { | ||
return state; | ||
}; | ||
return dispatch.apply(void 0, [store, action].concat(args)); | ||
}, [dispatch]); | ||
} | ||
function defaultMapState(s) { | ||
return s; | ||
} | ||
function defaultStateComparator(prev, current) { | ||
if (typeof prev !== typeof current) { | ||
function deepEqual(a, b) { | ||
if (typeof a !== typeof b) { | ||
return false; | ||
} | ||
if (Array.isArray(prev) && Array.isArray(current)) { | ||
return prev.length === current.length && prev.every(function (item, i) { | ||
return defaultStateComparator(item, current[i]); | ||
if (Array.isArray(a) && Array.isArray(b)) { | ||
return a.length === b.length && a.every(function (item, i) { | ||
return deepEqual(item, b[i]); | ||
}); | ||
} else if (typeof prev === 'object' && typeof current === 'object') { | ||
var prevKeys = Object.keys(prev); | ||
return defaultStateComparator(prevKeys, Object.keys(current)) && prevKeys.every(function (key) { | ||
return defaultStateComparator(prev[key], current[key]); | ||
} else if (typeof a === 'object' && typeof b === 'object') { | ||
var keys = Object.keys(a); | ||
return deepEqual(keys, Object.keys(b)) && keys.every(function (key) { | ||
return deepEqual(a[key], b[key]); | ||
}); | ||
} | ||
return prev === current; | ||
return a === b; | ||
} | ||
function defaultStateComparator(prev, current) { | ||
return !deepEqual(prev, current); | ||
} // export function defaultStateComparator(): boolean { | ||
// return true; | ||
// } | ||
function subscribeToStateChange(ctx, store, fn) { | ||
@@ -234,12 +132,10 @@ var set = ctx.subscriptions.get(store); | ||
} | ||
function getOrFillState(ctx, store) { | ||
var state = ctx.states.get(store); | ||
if (!state) { | ||
state = store.initialState; | ||
if (!ctx.states.has(store)) { | ||
var state = store.initialState; | ||
ctx.states.set(store, state); | ||
return state; | ||
} | ||
return state; | ||
return ctx.states.get(store); | ||
} | ||
@@ -259,3 +155,3 @@ | ||
var _useState = useState(function () { | ||
return mapState(getOrFillState(ctx, store)); | ||
return mapState(getOrFillState(ctx, store._storeData)); | ||
}), | ||
@@ -267,3 +163,3 @@ current = _useState[0], | ||
var subscription = function subscription() { | ||
var newState = getOrFillState(ctx, store); | ||
var newState = getOrFillState(ctx, store._storeData); | ||
var newRes = mapState(newState); | ||
@@ -277,6 +173,7 @@ var shouldUpdate = mapState === defaultMapState && comparator === defaultStateComparator ? current !== newRes : comparator(current, newRes); | ||
return subscribeToStateChange(ctx, store, subscription); | ||
}, []); | ||
return subscribeToStateChange(ctx, store._storeData, subscription); | ||
}, [ctx, current]); | ||
return current; | ||
} | ||
function useStores(stores, mapState, comparator) { | ||
@@ -293,7 +190,7 @@ if (mapState === void 0) { | ||
var _useState2 = useState(function () { | ||
var _useState = useState(function () { | ||
return mapState(getOrFileStateObject(ctx, stores)); | ||
}), | ||
current = _useState2[0], | ||
setCurrentValue = _useState2[1]; | ||
current = _useState[0], | ||
setCurrentValue = _useState[1]; | ||
@@ -312,3 +209,3 @@ useEffect(function () { | ||
var unsubscribeFunctions = Object.values(stores).map(function (store) { | ||
return subscribeToStateChange(ctx, store, subscriptionFn); | ||
return subscribeToStateChange(ctx, store._storeData, subscriptionFn); | ||
}); | ||
@@ -320,3 +217,3 @@ return function () { | ||
}; | ||
}, []); | ||
}, [ctx, current]); | ||
return current; | ||
@@ -327,3 +224,3 @@ } | ||
return Object.keys(stores).reduce(function (result, key) { | ||
result[key] = getOrFillState(ctx, stores[key]); | ||
result[key] = getOrFillState(ctx, stores[key]._storeData); | ||
return result; | ||
@@ -333,3 +230,108 @@ }, {}); | ||
export { StoreProvider, createStore, useAction, useDispatcher, useStateContext, useStore, useStores }; | ||
function isStateUpdaterFunction(updater) { | ||
return typeof updater === 'function'; | ||
} | ||
function isPromise(p) { | ||
return 'then' in p && typeof p.then === 'function'; | ||
} | ||
function createDispatcher(context, opt) { | ||
return function (dispatchFn) { | ||
var autoCommit = !opt; | ||
var changesSet = opt ? opt.changesSet : new Set(); | ||
var changesMap = opt ? opt.changesMap : new WeakMap(); | ||
var commit = opt ? opt.commit : function () { | ||
var allSubscription = new Set(); | ||
changesSet.forEach(function (id) { | ||
context.states.set(id, changesMap.get(id)); | ||
var subscriptions = context.subscriptions.get(id); | ||
if (subscriptions) { | ||
subscriptions.forEach(function (fn) { | ||
return allSubscription.add(fn); | ||
}); | ||
} | ||
}); | ||
allSubscription.forEach(function (fn) { | ||
try { | ||
fn(); | ||
} catch (e) { | ||
console.error('Error when calling subscription', e); | ||
} | ||
}); | ||
changesSet.clear(); | ||
changesMap = new WeakMap(); | ||
}; | ||
var getState = function getState() { | ||
return changesMap.get(dispatchFn.store) || getOrFillState(context, dispatchFn.store); | ||
}; | ||
var result = dispatchFn({ | ||
state: getState(), | ||
getState: getState, | ||
setState: function setState(updater, forceCommit) { | ||
if (forceCommit === void 0) { | ||
forceCommit = false; | ||
} | ||
var state = isStateUpdaterFunction(updater) ? updater(getState()) : updater; | ||
changesSet.add(dispatchFn.store); | ||
changesMap.set(dispatchFn.store, state); | ||
if (forceCommit) { | ||
commit(); | ||
} | ||
}, | ||
commit: commit, | ||
disableAutoCommit: function disableAutoCommit() { | ||
autoCommit = false; | ||
}, | ||
getStore: function getStore(otherStore) { | ||
return changesMap.get(otherStore._storeData) || getOrFillState(context, otherStore._storeData); | ||
}, | ||
dispatch: createDispatcher(context, { | ||
changesMap: changesMap, | ||
commit: commit, | ||
changesSet: changesSet | ||
}) | ||
}); | ||
if (autoCommit) { | ||
if (result && isPromise(result)) { | ||
result.then(function () { | ||
return commit(); | ||
}); | ||
} else { | ||
commit(); | ||
} | ||
} | ||
return result; | ||
}; | ||
} | ||
function useDispatcher() { | ||
var ctx = useStateContext(); | ||
return useMemo(function () { | ||
return createDispatcher(ctx); | ||
}, [ctx]); | ||
} | ||
function useAction(action) { | ||
var dispatch = useDispatcher(); | ||
return useMemo(function () { | ||
if ('store' in action) { | ||
return function () { | ||
return dispatch(action); | ||
}; | ||
} else { | ||
return function () { | ||
return dispatch(action.apply(void 0, arguments)); | ||
}; | ||
} | ||
}, [dispatch]); | ||
} | ||
export { StoreProvider, createStore, useAction, useDispatcher, useStore, useStores }; | ||
//# sourceMappingURL=el-state.esm.js.map |
@@ -1,55 +0,5 @@ | ||
import React from 'react'; | ||
declare type SubscriptionFn = () => void; | ||
declare type SubscriptionSet = Set<SubscriptionFn>; | ||
declare type ContextType = { | ||
states: WeakMap<Store<any, ActionMap<any>>, unknown>; | ||
subscriptions: WeakMap<Store<any, ActionMap<any>>, SubscriptionSet>; | ||
}; | ||
declare type ProviderProps = { | ||
initialStates?: WeakMap<Store<any, ActionMap<any>>, unknown>; | ||
}; | ||
export declare const StoreProvider: React.FC<ProviderProps>; | ||
declare type StateUpdaterFunction<State> = (prev: State) => State; | ||
declare type StateUpdater<State> = State | StateUpdaterFunction<State>; | ||
declare type ActionFuncContext<State> = { | ||
state: State; | ||
getState(): State; | ||
setState(updater: StateUpdater<State>, forceCommit?: boolean): void; | ||
disableAutoCommit(): void; | ||
commit(): void; | ||
getStore<OtherState>(store: Store<OtherState, ActionMap<any>>): OtherState; | ||
dispatch: Dispatcher; | ||
call<R, Args extends unknown[]>(action: ActionFunction<State, Args, R>, ...args: Args): R; | ||
}; | ||
declare type ActionFunction<State, Args extends any[] = any[], R = any> = (ctx: ActionFuncContext<State>, ...args: Args) => R; | ||
declare type ActionReturn<Action extends ActionFunction<any>> = Action extends ActionFunction<any, any, infer R> ? R : unknown; | ||
declare type ActionParameters<Action extends ActionFunction<any>> = Action extends ActionFunction<any, infer Args, any> ? Args : unknown[]; | ||
declare type ActionMap<State> = Record<string, ActionFunction<State>>; | ||
declare type CreateStoreOption<State, Actions extends ActionMap<State>> = { | ||
initialState: State; | ||
actions: Actions; | ||
}; | ||
declare type Store<State, Actions extends ActionMap<State>> = { | ||
initialState: State; | ||
} & Actions; | ||
export declare function createStore<State, Actions extends ActionMap<State>>({ initialState, actions, }: CreateStoreOption<State, Actions>): Store<State, Actions>; | ||
export declare function useStateContext(): ContextType; | ||
declare type DispatcherOption = { | ||
changesSet: Set<Store<any, ActionMap<any>>>; | ||
changesMap: WeakMap<Store<any, ActionMap<any>>, unknown>; | ||
commit(): void; | ||
}; | ||
declare function createDispatcher(context: ContextType, opt?: DispatcherOption): <State, Actions extends Record<string, ActionFunction<State, any[], any>>, ActionName extends keyof Actions>(store: Store<State, Actions>, actionName: ActionName, ...args: ActionParameters<Actions[ActionName]>) => ActionReturn<Actions[ActionName]>; | ||
export declare type Dispatcher = ReturnType<typeof createDispatcher>; | ||
export declare function useDispatcher(): Dispatcher; | ||
export declare function useAction<State, Actions extends ActionMap<State>, ActionName extends keyof Actions>(store: Store<State, Actions>, action: ActionName): (...args: ActionParameters<Actions[ActionName]>) => ActionReturn<Actions[ActionName]>; | ||
export declare type StateComparator<T> = (prev: T, current: T) => boolean; | ||
export declare type SingleStateMapper<State, Return> = (state: State) => Return; | ||
export declare function useStore<State, Actions extends ActionMap<State>, Return>(store: Store<State, Actions>, mapState?: SingleStateMapper<State, Return>, comparator?: StateComparator<Return>): Return; | ||
declare type StoreMap = Record<string, Store<any, ActionMap<any>>>; | ||
declare type StoresState<Stores extends StoreMap> = { | ||
[i in keyof Stores]: Stores[i] extends Store<infer State, ActionMap<any>> ? State : never; | ||
}; | ||
export declare type MultiStateMapper<Stores extends StoreMap, Return> = (states: StoresState<Stores>) => Return; | ||
export declare function useStores<Stores extends StoreMap, Return>(stores: Stores, mapState?: MultiStateMapper<Stores, Return>, comparator?: StateComparator<Return>): Return; | ||
export {}; | ||
export { StoreProvider } from './provider'; | ||
export { createStore } from './createStore'; | ||
export { useStore } from './useStore'; | ||
export { useStores } from './useStores'; | ||
export { useDispatcher, useAction } from './dispatcher'; |
{ | ||
"name": "el-state", | ||
"version": "0.1.0", | ||
"version": "0.1.1", | ||
"main": "dist/index.js", | ||
@@ -5,0 +5,0 @@ "module": "dist/el-state.esm.js", |
199
README.md
@@ -1,167 +0,68 @@ | ||
# TSDX React User Guide | ||
# él-staté | ||
Congrats! You just saved yourself hours of work by bootstrapping this project with TSDX. Let’s get you oriented with what’s here and how to use it. | ||
React state management with hook | ||
> This TSDX setup is meant for developing React components (not apps!) that can be published to NPM. If you’re looking to build an app, you should use `create-react-app`, `razzle`, `nextjs`, `gatsby`, or `react-static`. | ||
## Usage | ||
> If you’re new to TypeScript and React, checkout [this handy cheatsheet](https://github.com/sw-yx/react-typescript-cheatsheet/) | ||
Please see [example](./example/index.tsx). | ||
## Commands | ||
### Use StoreProvider | ||
```js | ||
import React from 'react'; | ||
import ReactDOM from 'react-dom'; | ||
import { StoreProvider } from 'el-state'; | ||
import App from './App'; | ||
TSDX scaffolds your new library inside `/src`, and also sets up a [Parcel-based](https://parceljs.org) playground for it inside `/example`. | ||
The recommended workflow is to run TSDX in one terminal: | ||
ReactDOM.render(<StoreProvider><App /></StoreProvider>, document.getElementById('root')); | ||
``` | ||
npm start # or yarn start | ||
``` | ||
This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`. | ||
### Define a store | ||
```ts | ||
import { createStore, createState } from 'el-state'; | ||
Then run the example inside another: | ||
type CounterState = { | ||
counter: number; | ||
}; | ||
const counterStore = createStore({ | ||
initialState: createState<CounterState>({ counter: 0 }), | ||
actions: { | ||
increase(ctx) { | ||
// ctx.state.counter++; // => compile error: counter is readonly | ||
ctx.setState(state => ({ counter: state.counter + 1 })); | ||
}, | ||
set(ctx, counter: number) { | ||
ctx.setState({ counter }); | ||
}, | ||
reset(ctx) { | ||
this.set(ctx, 0); | ||
}, | ||
}, | ||
}); | ||
``` | ||
cd example | ||
npm i # or yarn to install dependencies | ||
npm start # or yarn start | ||
``` | ||
The default example imports and live reloads whatever is in `/dist`, so if you are seeing an out of date component, make sure TSDX is running in watch mode like we recommend above. **No symlinking required**, [we use Parcel's aliasing](https://github.com/palmerhq/tsdx/pull/88/files). | ||
### Use the store | ||
```js | ||
const MyComononent: React.FC = () => { | ||
const counter = useStore(counterStore, state => state.counter); | ||
To do a one-off build, use `npm run build` or `yarn build`. | ||
To run tests, use `npm test` or `yarn test`. | ||
## Configuration | ||
Code quality is [set up for you](https://github.com/palmerhq/tsdx/pull/45/files) with `prettier`, `husky`, and `lint-staged`. Adjust the respective fields in `package.json` accordingly. | ||
### Jest | ||
Jest tests are set up to run with `npm test` or `yarn test`. This runs the test watcher (Jest) in an interactive mode. By default, runs tests related to files changed since the last commit. | ||
#### Setup Files | ||
This is the folder structure we set up for you: | ||
// use the counter | ||
} | ||
``` | ||
/example | ||
index.html | ||
index.tsx # test your component here in a demo app | ||
package.json | ||
tsconfig.json | ||
/src | ||
index.tsx # EDIT THIS | ||
/test | ||
blah.test.tsx # EDIT THIS | ||
.gitignore | ||
package.json | ||
README.md # EDIT THIS | ||
tsconfig.json | ||
``` | ||
#### React Testing Library | ||
We do not set up `react-testing-library` for you yet, we welcome contributions and documentation on this. | ||
### Rollup | ||
TSDX uses [Rollup v1.x](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats and build settings. See [Optimizations](#optimizations) for details. | ||
### TypeScript | ||
`tsconfig.json` is set up to interpret `dom` and `esnext` types, as well as `react` for `jsx`. Adjust according to your needs. | ||
## Continuous Integration | ||
### Travis | ||
_to be completed_ | ||
### Circle | ||
_to be completed_ | ||
## Optimizations | ||
Please see the main `tsdx` [optimizations docs](https://github.com/palmerhq/tsdx#optimizations). In particular, know that you can take advantage of development-only optimizations: | ||
### Call an action | ||
```js | ||
// ./types/index.d.ts | ||
declare var __DEV__: boolean; | ||
// inside your code... | ||
if (__DEV__) { | ||
console.log('foo'); | ||
const MyComononent: React.FC = () => { | ||
const increaseCounter = useAction(counterStore.increase); | ||
// use this function as onClick handle | ||
} | ||
``` | ||
You can also choose to install and use [invariant](https://github.com/palmerhq/tsdx#invariant) and [warning](https://github.com/palmerhq/tsdx#warning) functions. | ||
### Use dispatcher | ||
```js | ||
const MyComononent: React.FC = () => { | ||
const dispatch = useDispatcher(); | ||
## Module Formats | ||
CJS, ESModules, and UMD module formats are supported. | ||
The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are found. | ||
## Using the Playground | ||
``` | ||
cd example | ||
npm i # or yarn to install dependencies | ||
npm start # or yarn start | ||
``` | ||
The default example imports and live reloads whatever is in `/dist`, so if you are seeing an out of date component, make sure TSDX is running in watch mode like we recommend above. **No symlinking required**! | ||
## Deploying the Playground | ||
The Playground is just a simple [Parcel](https://parceljs.org) app, you can deploy it anywhere you would normally deploy that. Here are some guidelines for **manually** deploying with the Netlify CLI (`npm i -g netlify-cli`): | ||
```bash | ||
cd example # if not already in the example folder | ||
npm run build # builds to dist | ||
netlify deploy # deploy the dist folder | ||
``` | ||
Alternatively, if you already have a git repo connected, you can set up continuous deployment with Netlify: | ||
```bash | ||
netlify init | ||
# build command: cd example && yarn && yarn build | ||
# directory to deploy: example/dist | ||
# pick yes for netlify.toml | ||
``` | ||
## Named Exports | ||
Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split inside your React app instead of your React library. | ||
## Including Styles | ||
There are many ways to ship styles, including with CSS-in-JS. TSDX has no opinion on this, configure how you like. | ||
For vanilla CSS, you can include it at the root directory and add it to the `files` section in your `package.json`, so that it can be imported separately by your users and run through their bundler's loader. | ||
## Publishing to NPM | ||
We recommend using https://github.com/sindresorhus/np. | ||
## Usage with Lerna | ||
When creating a new package with TSDX within a project set up with Lerna, you might encounter a `Cannot resolve dependency` error when trying to run the `example` project. To fix that you will need to make changes to the `package.json` file _inside the `example` directory_. | ||
The problem is that due to the nature of how dependencies are installed in Lerna projects, the aliases in the example project's `package.json` might not point to the right place, as those dependencies might have been installed in the root of your Lerna project. | ||
Change the `alias` to point to where those packages are actually installed. This depends on the directory structure of your Lerna project, so the actual path might be different from the diff below. | ||
```diff | ||
"alias": { | ||
- "react": "../node_modules/react", | ||
- "react-dom": "../node_modules/react-dom" | ||
+ "react": "../../../node_modules/react", | ||
+ "react-dom": "../../../node_modules/react-dom" | ||
}, | ||
``` | ||
An alternative to fixing this problem would be to remove aliases altogether and define the dependencies referenced as aliases as dev dependencies instead. [However, that might cause other problems.](https://github.com/palmerhq/tsdx/issues/64) | ||
const onBtnIncreasePressed = () => dispatch(counterStore.increase()); | ||
// use this function as onClick handle | ||
} | ||
``` |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
17
662
76145
68
1