refract-redux-xstream
Version:
Refract bindings for Redux with xstream: harness the power of reactive programming to supercharge your components!
88 lines (80 loc) • 3.44 kB
JavaScript
import xs from 'xstream';
import dropRepeats from 'xstream/extra/dropRepeats';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var __assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
var observeFactory = function (store) {
return function (actionOrSelector) {
if (typeof actionOrSelector === 'string') {
var unsubscribe_1;
return xs.create({
start: function (listener) {
unsubscribe_1 = store.addActionListener(actionOrSelector, listener.next.bind(listener));
},
stop: function () {
unsubscribe_1();
}
});
}
if (typeof actionOrSelector === 'function') {
return xs
.from(store)
.map(actionOrSelector)
.compose(dropRepeats());
}
};
};
var defaultOptions = {
eventsPrefix: '@@event/',
methodName: 'observe'
};
function refractStoreEnhancer(options) {
if (options === void 0) { options = {}; }
var opts = __assign({}, defaultOptions, options);
return function (createStore) { return function (reducer, initialState, enhancer) {
var actionListeners = {};
var store = createStore(reducer, initialState, enhancer);
var dispatch = store.dispatch;
store.dispatch = function (action) {
var result;
var hasType = action && action.type;
var isEvent = opts.eventsPrefix &&
hasType &&
action.type.indexOf(opts.eventsPrefix) === 0;
if (!isEvent) {
result = dispatch(action);
}
if (hasType && actionListeners[action.type]) {
actionListeners[action.type].forEach(function (listener) {
return listener(action);
});
}
return result;
};
store.addActionListener = function (actionType, listener) {
actionListeners[actionType] = (actionListeners[actionType] || []).concat(listener);
return function () {
actionListeners[actionType] = actionListeners[actionType].filter(function (l) { return listener !== l; });
};
};
store[opts.methodName] = observeFactory(store);
return store;
}; };
}
export { refractStoreEnhancer as refractEnhancer };