abstract-state-router
Advanced tools
Comparing version 6.2.0 to 6.2.1
841
bundle.js
'use strict'; | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var require$$2 = require('combine-arrays'); | ||
var require$$3 = require('path-to-regexp-with-reversible-keys'); | ||
var require$$9 = require('then-denodeify'); | ||
var require$$10 = require('eventemitter3'); | ||
var require$$11 = require('hash-brown-router'); | ||
var require$$13 = require('page-path-builder'); | ||
var require$$14 = require('iso-next-tick'); | ||
var combineArrays = _interopDefault(require('combine-arrays')); | ||
var pathToRegexpWithReversibleKeys = _interopDefault(require('path-to-regexp-with-reversible-keys')); | ||
var thenDenodeify = _interopDefault(require('then-denodeify')); | ||
var eventemitter3 = _interopDefault(require('eventemitter3')); | ||
var hashBrownRouter = _interopDefault(require('hash-brown-router')); | ||
var pagePathBuilder = _interopDefault(require('page-path-builder')); | ||
var isoNextTick = _interopDefault(require('iso-next-tick')); | ||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); | ||
var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3); | ||
var require$$9__default = /*#__PURE__*/_interopDefaultLegacy(require$$9); | ||
var require$$10__default = /*#__PURE__*/_interopDefaultLegacy(require$$10); | ||
var require$$11__default = /*#__PURE__*/_interopDefaultLegacy(require$$11); | ||
var require$$13__default = /*#__PURE__*/_interopDefaultLegacy(require$$13); | ||
var require$$14__default = /*#__PURE__*/_interopDefaultLegacy(require$$14); | ||
var stateStringParser = createCommonjsModule(function (module) { | ||
module.exports = function (stateString) { | ||
return stateString.split('.').reduce(function (stateNames, latestNameChunk) { | ||
stateNames.push(stateNames.length ? stateNames[stateNames.length - 1] + '.' + latestNameChunk : latestNameChunk); | ||
var stateStringParser$2 = stateString => stateString.split(`.`).reduce((stateNames, latestNameChunk) => { | ||
stateNames.push( | ||
stateNames.length | ||
? stateNames[stateNames.length - 1] + `.` + latestNameChunk | ||
: latestNameChunk, | ||
); | ||
return stateNames; | ||
}, []); | ||
}; | ||
}); | ||
return stateNames | ||
}, []); | ||
const stateStringParser$1 = stateStringParser$2; | ||
var stateState = function StateState() { | ||
var states = {}; | ||
const states = {}; | ||
function getHierarchy(name) { | ||
var names = stateStringParser(name); | ||
const names = stateStringParser$1(name); | ||
return names.map(function (name) { | ||
return names.map(name => { | ||
if (!states[name]) { | ||
throw new Error('State ' + name + ' not found'); | ||
throw new Error(`State ${ name } not found`) | ||
} | ||
return states[name]; | ||
}); | ||
return states[name] | ||
}) | ||
} | ||
function getParent(name) { | ||
var parentName = getParentName(name); | ||
const parentName = getParentName(name); | ||
return parentName && states[parentName]; | ||
return parentName && states[parentName] | ||
} | ||
function getParentName(name) { | ||
var names = stateStringParser(name); | ||
const names = stateStringParser$1(name); | ||
if (names.length > 1) { | ||
var secondToLast = names.length - 2; | ||
const secondToLast = names.length - 2; | ||
return names[secondToLast]; | ||
return names[secondToLast] | ||
} else { | ||
return null; | ||
return null | ||
} | ||
@@ -60,9 +66,7 @@ } | ||
function guaranteeAllStatesExist(newStateName) { | ||
var stateNames = stateStringParser(newStateName); | ||
var statesThatDontExist = stateNames.filter(function (name) { | ||
return !states[name]; | ||
}); | ||
const stateNames = stateStringParser$1(newStateName); | ||
const statesThatDontExist = stateNames.filter(name => !states[name]); | ||
if (statesThatDontExist.length > 0) { | ||
throw new Error('State ' + statesThatDontExist[statesThatDontExist.length - 1] + ' does not exist'); | ||
throw new Error(`State ${ statesThatDontExist[statesThatDontExist.length - 1] } does not exist`) | ||
} | ||
@@ -72,148 +76,132 @@ } | ||
function buildFullStateRoute(stateName) { | ||
return getHierarchy(stateName).map(function (state) { | ||
return '/' + (state.route || ''); | ||
}).join('').replace(/\/{2,}/g, '/'); | ||
return getHierarchy(stateName).map(state => `/${ state.route || `` }`) | ||
.join(``) | ||
.replace(/\/{2,}/g, `/`) | ||
} | ||
function applyDefaultChildStates(stateName) { | ||
var state = states[stateName]; | ||
const state = states[stateName]; | ||
var defaultChildStateName = state && (typeof state.defaultChild === 'function' ? state.defaultChild() : state.defaultChild); | ||
const defaultChildStateName = state && ( | ||
typeof state.defaultChild === `function` | ||
? state.defaultChild() | ||
: state.defaultChild | ||
); | ||
if (!defaultChildStateName) { | ||
return stateName; | ||
return stateName | ||
} | ||
var fullStateName = stateName + '.' + defaultChildStateName; | ||
const fullStateName = `${ stateName }.${ defaultChildStateName }`; | ||
return applyDefaultChildStates(fullStateName); | ||
return applyDefaultChildStates(fullStateName) | ||
} | ||
return { | ||
add: function add(name, state) { | ||
add(name, state) { | ||
states[name] = state; | ||
}, | ||
get: function get(name) { | ||
return name && states[name]; | ||
get(name) { | ||
return name && states[name] | ||
}, | ||
getHierarchy: getHierarchy, | ||
getParent: getParent, | ||
getParentName: getParentName, | ||
guaranteeAllStatesExist: guaranteeAllStatesExist, | ||
buildFullStateRoute: buildFullStateRoute, | ||
applyDefaultChildStates: applyDefaultChildStates | ||
}; | ||
getHierarchy, | ||
getParent, | ||
getParentName, | ||
guaranteeAllStatesExist, | ||
buildFullStateRoute, | ||
applyDefaultChildStates, | ||
} | ||
}; | ||
var extend = function extend() { | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var extend$2 = (...args) => Object.assign({}, ...args); | ||
return Object.assign.apply(Object, [{}].concat(args)); | ||
}; | ||
const stateStringParser = stateStringParser$2; | ||
const extend$1 = extend$2; | ||
const combine$1 = require$$2__default['default']; | ||
const pathToRegexp = require$$3__default['default']; | ||
var stateComparison_1 = function StateComparison(stateState) { | ||
var getPathParameters = pathParameters(); | ||
const getPathParameters = pathParameters(); | ||
var parametersChanged = function parametersChanged(args) { | ||
return parametersThatMatterWereChanged(extend(args, { stateState: stateState, getPathParameters: getPathParameters })); | ||
}; | ||
const parametersChanged = args => parametersThatMatterWereChanged(extend$1(args, { stateState, getPathParameters })); | ||
return function (args) { | ||
return stateComparison(extend(args, { parametersChanged: parametersChanged })); | ||
}; | ||
return args => stateComparison(extend$1(args, { parametersChanged })) | ||
}; | ||
function pathParameters() { | ||
var parameters = {}; | ||
const parameters = {}; | ||
return function (path) { | ||
return path => { | ||
if (!path) { | ||
return []; | ||
return [] | ||
} | ||
if (!parameters[path]) { | ||
parameters[path] = pathToRegexpWithReversibleKeys(path).keys.map(function (key) { | ||
return key.name; | ||
}); | ||
parameters[path] = pathToRegexp(path).keys.map(key => key.name); | ||
} | ||
return parameters[path]; | ||
}; | ||
return parameters[path] | ||
} | ||
} | ||
function parametersThatMatterWereChanged(_ref) { | ||
var stateState = _ref.stateState, | ||
getPathParameters = _ref.getPathParameters, | ||
stateName = _ref.stateName, | ||
fromParameters = _ref.fromParameters, | ||
toParameters = _ref.toParameters; | ||
function parametersThatMatterWereChanged({ stateState, getPathParameters, stateName, fromParameters, toParameters }) { | ||
const state = stateState.get(stateName); | ||
const querystringParameters = state.querystringParameters || []; | ||
const parameters = getPathParameters(state.route).concat(querystringParameters); | ||
var state = stateState.get(stateName); | ||
var querystringParameters = state.querystringParameters || []; | ||
var parameters = getPathParameters(state.route).concat(querystringParameters); | ||
return Array.isArray(parameters) && parameters.some(function (key) { | ||
return fromParameters[key] !== toParameters[key]; | ||
}); | ||
return Array.isArray(parameters) && parameters.some( | ||
key => fromParameters[key] !== toParameters[key], | ||
) | ||
} | ||
function stateComparison(_ref2) { | ||
var parametersChanged = _ref2.parametersChanged, | ||
original = _ref2.original, | ||
destination = _ref2.destination; | ||
var states = combineArrays({ | ||
function stateComparison({ parametersChanged, original, destination }) { | ||
const states = combine$1({ | ||
start: stateStringParser(original.name), | ||
end: stateStringParser(destination.name) | ||
end: stateStringParser(destination.name), | ||
}); | ||
return states.map(function (_ref3) { | ||
var start = _ref3.start, | ||
end = _ref3.end; | ||
return { | ||
nameBefore: start, | ||
nameAfter: end, | ||
stateNameChanged: start !== end, | ||
stateParametersChanged: start === end && parametersChanged({ | ||
stateName: start, | ||
fromParameters: original.parameters, | ||
toParameters: destination.parameters | ||
}) | ||
}; | ||
}); | ||
return states.map(({ start, end }) => ({ | ||
nameBefore: start, | ||
nameAfter: end, | ||
stateNameChanged: start !== end, | ||
stateParametersChanged: start === end && parametersChanged({ | ||
stateName: start, | ||
fromParameters: original.parameters, | ||
toParameters: destination.parameters, | ||
}), | ||
})) | ||
} | ||
var currentState = function CurrentState() { | ||
var current = { | ||
name: '', | ||
parameters: {} | ||
let current = { | ||
name: ``, | ||
parameters: {}, | ||
}; | ||
return { | ||
get: function get() { | ||
return current; | ||
get() { | ||
return current | ||
}, | ||
set: function set(name, parameters) { | ||
set(name, parameters) { | ||
current = { | ||
name: name, | ||
parameters: parameters | ||
name, | ||
parameters, | ||
}; | ||
} | ||
}; | ||
}, | ||
} | ||
}; | ||
var stateChangeLogic = function stateChangeLogic(stateComparisonResults) { | ||
var hitChangingState = false; | ||
var hitDestroyedState = false; | ||
var stateChangeLogic$1 = function stateChangeLogic(stateComparisonResults) { | ||
let hitChangingState = false; | ||
let hitDestroyedState = false; | ||
var output = { | ||
const output = { | ||
destroy: [], | ||
change: [], | ||
create: [] | ||
create: [], | ||
}; | ||
stateComparisonResults.forEach(function (state) { | ||
stateComparisonResults.forEach(state => { | ||
hitChangingState = hitChangingState || state.stateParametersChanged; | ||
@@ -235,8 +223,8 @@ hitDestroyedState = hitDestroyedState || state.stateNameChanged; | ||
return output; | ||
return output | ||
}; | ||
var stateTransitionManager = function stateTransitionManager(emitter) { | ||
var currentTransitionAttempt = null; | ||
var nextTransition = null; | ||
var stateTransitionManager = emitter => { | ||
let currentTransitionAttempt = null; | ||
let nextTransition = null; | ||
@@ -250,5 +238,3 @@ function doneTransitioning() { | ||
var isTransitioning = function isTransitioning() { | ||
return !!currentTransitionAttempt; | ||
}; | ||
const isTransitioning = () => !!currentTransitionAttempt; | ||
@@ -263,8 +249,8 @@ function beginNextTransitionAttempt() { | ||
currentTransitionAttempt.transition.cancelled = true; | ||
var err = new Error('State transition cancelled by the state transition manager'); | ||
const err = new Error(`State transition cancelled by the state transition manager`); | ||
err.wasCancelledBySomeoneElse = true; | ||
emitter.emit('stateChangeCancelled', err); | ||
emitter.emit(`stateChangeCancelled`, err); | ||
} | ||
emitter.on('stateChangeAttempt', function (beginStateChange) { | ||
emitter.on(`stateChangeAttempt`, beginStateChange => { | ||
nextTransition = createStateTransitionAttempt(beginStateChange); | ||
@@ -279,25 +265,19 @@ | ||
emitter.on('stateChangeError', doneTransitioning); | ||
emitter.on('stateChangeCancelled', doneTransitioning); | ||
emitter.on('stateChangeEnd', doneTransitioning); | ||
emitter.on(`stateChangeError`, doneTransitioning); | ||
emitter.on(`stateChangeCancelled`, doneTransitioning); | ||
emitter.on(`stateChangeEnd`, doneTransitioning); | ||
function createStateTransitionAttempt(_beginStateChange) { | ||
var transition = { | ||
function createStateTransitionAttempt(beginStateChange) { | ||
const transition = { | ||
cancelled: false, | ||
cancellable: true | ||
cancellable: true, | ||
}; | ||
return { | ||
transition: transition, | ||
beginStateChange: function beginStateChange() { | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return _beginStateChange.apply(undefined, [transition].concat(args)); | ||
} | ||
}; | ||
transition, | ||
beginStateChange: (...args) => beginStateChange(transition, ...args), | ||
} | ||
} | ||
}; | ||
var defaultRouterOptions = { reverse: false }; | ||
var defaultRouterOptions$1 = { reverse: false }; | ||
@@ -307,87 +287,70 @@ // Pulled from https://github.com/joliss/promise-map-series and prettied up a bit | ||
var promiseMapSeries = function sequence(array, iterator) { | ||
var currentPromise = Promise.resolve(); | ||
return Promise.all(array.map(function (value, i) { | ||
return currentPromise = currentPromise.then(function () { | ||
return iterator(value, i, array); | ||
}); | ||
})); | ||
let currentPromise = Promise.resolve(); | ||
return Promise.all( | ||
array.map((value, i) => currentPromise = currentPromise.then(() => iterator(value, i, array))), | ||
) | ||
}; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
return typeof obj; | ||
} : function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
const StateState = stateState; | ||
const StateComparison = stateComparison_1; | ||
const CurrentState = currentState; | ||
const stateChangeLogic = stateChangeLogic$1; | ||
const parse = stateStringParser$2; | ||
const StateTransitionManager = stateTransitionManager; | ||
const defaultRouterOptions = defaultRouterOptions$1; | ||
var getProperty = function getProperty(name) { | ||
return function (obj) { | ||
return obj[name]; | ||
}; | ||
}; | ||
var reverse = function reverse(ary) { | ||
return ary.slice().reverse(); | ||
}; | ||
var isFunction = function isFunction(property) { | ||
return function (obj) { | ||
return typeof obj[property] === 'function'; | ||
}; | ||
}; | ||
var isThenable = function isThenable(object) { | ||
return object && ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' || typeof object === 'function') && typeof object.then === 'function'; | ||
}; | ||
var promiseMe = function promiseMe(fn) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
args[_key - 1] = arguments[_key]; | ||
} | ||
const series = promiseMapSeries; | ||
const extend = extend$2; | ||
return new Promise(function (resolve) { | ||
return resolve(fn.apply(undefined, args)); | ||
}); | ||
}; | ||
const denodeify = require$$9__default['default']; | ||
const EventEmitter = require$$10__default['default']; | ||
const newHashBrownRouter = require$$11__default['default']; | ||
const combine = require$$2__default['default']; | ||
const buildPath = require$$13__default['default']; | ||
const nextTick = require$$14__default['default']; | ||
var expectedPropertiesOfAddState = ['name', 'route', 'defaultChild', 'data', 'template', 'resolve', 'activate', 'querystringParameters', 'defaultQuerystringParameters', 'defaultParameters']; | ||
const getProperty = name => obj => obj[name]; | ||
const reverse = ary => ary.slice().reverse(); | ||
const isFunction = property => obj => typeof obj[property] === `function`; | ||
const isThenable = object => object && (typeof object === `object` || typeof object === `function`) && typeof object.then === `function`; | ||
const promiseMe = (fn, ...args) => new Promise(resolve => resolve(fn(...args))); | ||
var abstractStateRouter = function StateProvider(makeRenderer, rootElement) { | ||
var stateRouterOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
const expectedPropertiesOfAddState = [ `name`, `route`, `defaultChild`, `data`, `template`, `resolve`, `activate`, `querystringParameters`, `defaultQuerystringParameters`, `defaultParameters` ]; | ||
var prototypalStateHolder = stateState(); | ||
var lastCompletelyLoadedState = currentState(); | ||
var lastStateStartedActivating = currentState(); | ||
var stateProviderEmitter = new eventemitter3(); | ||
var compareStartAndEndStates = stateComparison_1(prototypalStateHolder); | ||
var abstractStateRouter = function StateProvider(makeRenderer, rootElement, stateRouterOptions = {}) { | ||
const prototypalStateHolder = StateState(); | ||
const lastCompletelyLoadedState = CurrentState(); | ||
const lastStateStartedActivating = CurrentState(); | ||
const stateProviderEmitter = new EventEmitter(); | ||
const compareStartAndEndStates = StateComparison(prototypalStateHolder); | ||
var stateNameToArrayofStates = function stateNameToArrayofStates(stateName) { | ||
return stateStringParser(stateName).map(prototypalStateHolder.get); | ||
}; | ||
const stateNameToArrayofStates = stateName => parse(stateName).map(prototypalStateHolder.get); | ||
stateTransitionManager(stateProviderEmitter); | ||
var _extend = extend({ | ||
StateTransitionManager(stateProviderEmitter); | ||
const { throwOnError, pathPrefix } = extend({ | ||
throwOnError: true, | ||
pathPrefix: '#' | ||
}, stateRouterOptions), | ||
throwOnError = _extend.throwOnError, | ||
pathPrefix = _extend.pathPrefix; | ||
pathPrefix: `#`, | ||
}, stateRouterOptions); | ||
var router = stateRouterOptions.router || hashBrownRouter(defaultRouterOptions); | ||
const router = stateRouterOptions.router || newHashBrownRouter(defaultRouterOptions); | ||
router.on('not found', function (route, parameters) { | ||
stateProviderEmitter.emit('routeNotFound', route, parameters); | ||
router.on(`not found`, (route, parameters) => { | ||
stateProviderEmitter.emit(`routeNotFound`, route, parameters); | ||
}); | ||
var destroyDom = null; | ||
var getDomChild = null; | ||
var renderDom = null; | ||
var resetDom = null; | ||
let destroyDom = null; | ||
let getDomChild = null; | ||
let renderDom = null; | ||
let resetDom = null; | ||
var activeStateResolveContent = {}; | ||
var activeDomApis = {}; | ||
var activeEmitters = {}; | ||
let activeStateResolveContent = {}; | ||
const activeDomApis = {}; | ||
const activeEmitters = {}; | ||
function handleError(event, err) { | ||
isoNextTick(function () { | ||
nextTick(() => { | ||
stateProviderEmitter.emit(event, err); | ||
console.error(event + ' - ' + err.message); | ||
console.error(`${ event } - ${ err.message }`); | ||
if (throwOnError) { | ||
throw err; | ||
throw err | ||
} | ||
@@ -398,9 +361,9 @@ }); | ||
function destroyStateName(stateName) { | ||
var state = prototypalStateHolder.get(stateName); | ||
stateProviderEmitter.emit('beforeDestroyState', { | ||
state: state, | ||
domApi: activeDomApis[stateName] | ||
const state = prototypalStateHolder.get(stateName); | ||
stateProviderEmitter.emit(`beforeDestroyState`, { | ||
state, | ||
domApi: activeDomApis[stateName], | ||
}); | ||
activeEmitters[stateName].emit('destroy'); | ||
activeEmitters[stateName].emit(`destroy`); | ||
activeEmitters[stateName].removeAllListeners(); | ||
@@ -410,31 +373,31 @@ delete activeEmitters[stateName]; | ||
return destroyDom(activeDomApis[stateName]).then(function () { | ||
return destroyDom(activeDomApis[stateName]).then(() => { | ||
delete activeDomApis[stateName]; | ||
stateProviderEmitter.emit('afterDestroyState', { | ||
state: state | ||
stateProviderEmitter.emit(`afterDestroyState`, { | ||
state, | ||
}); | ||
}); | ||
}) | ||
} | ||
function resetStateName(parameters, stateName) { | ||
var domApi = activeDomApis[stateName]; | ||
var content = getContentObject(activeStateResolveContent, stateName); | ||
var state = prototypalStateHolder.get(stateName); | ||
const domApi = activeDomApis[stateName]; | ||
const content = getContentObject(activeStateResolveContent, stateName); | ||
const state = prototypalStateHolder.get(stateName); | ||
stateProviderEmitter.emit('beforeResetState', { | ||
domApi: domApi, | ||
content: content, | ||
state: state, | ||
parameters: parameters | ||
stateProviderEmitter.emit(`beforeResetState`, { | ||
domApi, | ||
content, | ||
state, | ||
parameters, | ||
}); | ||
activeEmitters[stateName].emit('destroy'); | ||
activeEmitters[stateName].emit(`destroy`); | ||
delete activeEmitters[stateName]; | ||
return resetDom({ | ||
domApi: domApi, | ||
content: content, | ||
domApi, | ||
content, | ||
template: state.template, | ||
parameters: parameters | ||
}).then(function (newDomApi) { | ||
parameters, | ||
}).then(newDomApi => { | ||
if (newDomApi) { | ||
@@ -444,16 +407,16 @@ activeDomApis[stateName] = newDomApi; | ||
stateProviderEmitter.emit('afterResetState', { | ||
stateProviderEmitter.emit(`afterResetState`, { | ||
domApi: activeDomApis[stateName], | ||
content: content, | ||
state: state, | ||
parameters: parameters | ||
content, | ||
state, | ||
parameters, | ||
}); | ||
}); | ||
}) | ||
} | ||
function getChildElementForStateName(stateName) { | ||
return new Promise(function (resolve) { | ||
var parent = prototypalStateHolder.getParent(stateName); | ||
return new Promise(resolve => { | ||
const parent = prototypalStateHolder.getParent(stateName); | ||
if (parent) { | ||
var parentDomApi = activeDomApis[parent.name]; | ||
const parentDomApi = activeDomApis[parent.name]; | ||
resolve(getDomChild(parentDomApi)); | ||
@@ -463,14 +426,14 @@ } else { | ||
} | ||
}); | ||
}) | ||
} | ||
function renderStateName(parameters, stateName) { | ||
return getChildElementForStateName(stateName).then(function (element) { | ||
var state = prototypalStateHolder.get(stateName); | ||
var content = getContentObject(activeStateResolveContent, stateName); | ||
return getChildElementForStateName(stateName).then(element => { | ||
const state = prototypalStateHolder.get(stateName); | ||
const content = getContentObject(activeStateResolveContent, stateName); | ||
stateProviderEmitter.emit('beforeCreateState', { | ||
state: state, | ||
content: content, | ||
parameters: parameters | ||
stateProviderEmitter.emit(`beforeCreateState`, { | ||
state, | ||
content, | ||
parameters, | ||
}); | ||
@@ -480,22 +443,20 @@ | ||
template: state.template, | ||
element: element, | ||
content: content, | ||
parameters: parameters | ||
}).then(function (domApi) { | ||
element, | ||
content, | ||
parameters, | ||
}).then(domApi => { | ||
activeDomApis[stateName] = domApi; | ||
stateProviderEmitter.emit('afterCreateState', { | ||
state: state, | ||
domApi: domApi, | ||
content: content, | ||
parameters: parameters | ||
stateProviderEmitter.emit(`afterCreateState`, { | ||
state, | ||
domApi, | ||
content, | ||
parameters, | ||
}); | ||
return domApi; | ||
}); | ||
}); | ||
return domApi | ||
}) | ||
}) | ||
} | ||
function renderAll(stateNames, parameters) { | ||
return promiseMapSeries(stateNames, function (stateName) { | ||
return renderStateName(parameters, stateName); | ||
}); | ||
return series(stateNames, stateName => renderStateName(parameters, stateName)) | ||
} | ||
@@ -505,3 +466,3 @@ | ||
try { | ||
var finalDestinationStateName = prototypalStateHolder.applyDefaultChildStates(state.name); | ||
const finalDestinationStateName = prototypalStateHolder.applyDefaultChildStates(state.name); | ||
@@ -513,4 +474,4 @@ if (finalDestinationStateName === state.name) { | ||
var theRouteWeNeedToEndUpAt = makePath(finalDestinationStateName, parameters); | ||
var currentRoute = router.location.get(); | ||
const theRouteWeNeedToEndUpAt = makePath(finalDestinationStateName, parameters); | ||
const currentRoute = router.location.get(); | ||
@@ -526,3 +487,3 @@ if (theRouteWeNeedToEndUpAt === currentRoute) { | ||
} catch (err) { | ||
handleError('stateError', err); | ||
handleError(`stateError`, err); | ||
} | ||
@@ -532,13 +493,11 @@ } | ||
function addState(state) { | ||
if (typeof state === 'undefined') { | ||
throw new Error('Expected \'state\' to be passed in.'); | ||
} else if (typeof state.name === 'undefined') { | ||
throw new Error('Expected the \'name\' option to be passed in.'); | ||
} else if (typeof state.template === 'undefined') { | ||
throw new Error('Expected the \'template\' option to be passed in.'); | ||
if (typeof state === `undefined`) { | ||
throw new Error(`Expected 'state' to be passed in.`) | ||
} else if (typeof state.name === `undefined`) { | ||
throw new Error(`Expected the 'name' option to be passed in.`) | ||
} else if (typeof state.template === `undefined`) { | ||
throw new Error(`Expected the 'template' option to be passed in.`) | ||
} | ||
Object.keys(state).filter(function (key) { | ||
return expectedPropertiesOfAddState.indexOf(key) === -1; | ||
}).forEach(function (key) { | ||
console.warn('Unexpected property passed to addState:', key); | ||
Object.keys(state).filter(key => expectedPropertiesOfAddState.indexOf(key) === -1).forEach(key => { | ||
console.warn(`Unexpected property passed to addState:`, key); | ||
}); | ||
@@ -548,25 +507,23 @@ | ||
var route = prototypalStateHolder.buildFullStateRoute(state.name); | ||
const route = prototypalStateHolder.buildFullStateRoute(state.name); | ||
router.add(route, function (parameters) { | ||
return onRouteChange(state, parameters); | ||
}); | ||
router.add(route, parameters => onRouteChange(state, parameters)); | ||
} | ||
function computeDefaultParams(defaultParams) { | ||
var computedDefaultParams = {}; | ||
const computedDefaultParams = {}; | ||
var defaultParamKeyValuePairs = Object.keys(defaultParams).forEach(function (key) { | ||
computedDefaultParams[key] = typeof defaultParams[key] === 'function' ? defaultParams[key]() : defaultParams[key]; | ||
Object.keys(defaultParams).forEach(key => { | ||
computedDefaultParams[key] = typeof defaultParams[key] === `function` ? defaultParams[key]() : defaultParams[key]; | ||
}); | ||
return computedDefaultParams; | ||
return computedDefaultParams | ||
} | ||
function getStatesToResolve(stateChanges) { | ||
return stateChanges.change.concat(stateChanges.create).map(prototypalStateHolder.get); | ||
return stateChanges.change.concat(stateChanges.create).map(prototypalStateHolder.get) | ||
} | ||
function emitEventAndAttemptStateChange(newStateName, parameters) { | ||
stateProviderEmitter.emit('stateChangeAttempt', function stateGo(transition) { | ||
stateProviderEmitter.emit(`stateChangeAttempt`, function stateGo(transition) { | ||
attemptStateChange(newStateName, parameters, transition); | ||
@@ -578,98 +535,96 @@ }); | ||
function ifNotCancelled(fn) { | ||
return function () { | ||
return (...args) => { | ||
if (transition.cancelled) { | ||
var err = new Error('The transition to ' + newStateName + ' was cancelled'); | ||
const err = new Error(`The transition to ${ newStateName } was cancelled`); | ||
err.wasCancelledBySomeoneElse = true; | ||
throw err; | ||
throw err | ||
} else { | ||
return fn.apply(undefined, arguments); | ||
return fn(...args) | ||
} | ||
}; | ||
} | ||
} | ||
return promiseMe(prototypalStateHolder.guaranteeAllStatesExist, newStateName).then(function applyDefaultParameters() { | ||
var state = prototypalStateHolder.get(newStateName); | ||
var defaultParams = state.defaultParameters || state.defaultQuerystringParameters || {}; | ||
var needToApplyDefaults = Object.keys(defaultParams).some(function missingParameterValue(param) { | ||
return typeof parameters[param] === 'undefined'; | ||
}); | ||
return promiseMe(prototypalStateHolder.guaranteeAllStatesExist, newStateName) | ||
.then(function applyDefaultParameters() { | ||
const state = prototypalStateHolder.get(newStateName); | ||
const defaultParams = state.defaultParameters || state.defaultQuerystringParameters || {}; | ||
const needToApplyDefaults = Object.keys(defaultParams).some(function missingParameterValue(param) { | ||
return typeof parameters[param] === `undefined` | ||
}); | ||
if (needToApplyDefaults) { | ||
throw redirector(newStateName, extend(computeDefaultParams(defaultParams), parameters)); | ||
} | ||
return state; | ||
}).then(ifNotCancelled(function (state) { | ||
stateProviderEmitter.emit('stateChangeStart', state, parameters, stateNameToArrayofStates(state.name)); | ||
lastStateStartedActivating.set(state.name, parameters); | ||
})).then(function getStateChanges() { | ||
var stateComparisonResults = compareStartAndEndStates({ | ||
original: lastCompletelyLoadedState.get(), | ||
destination: { | ||
name: newStateName, | ||
parameters: parameters | ||
if (needToApplyDefaults) { | ||
throw redirector(newStateName, extend(computeDefaultParams(defaultParams), parameters)) | ||
} | ||
}); | ||
return stateChangeLogic(stateComparisonResults); // { destroy, change, create } | ||
}).then(ifNotCancelled(function resolveDestroyAndActivateStates(stateChanges) { | ||
return resolveStates(getStatesToResolve(stateChanges), extend(parameters)).catch(function onResolveError(e) { | ||
e.stateChangeError = true; | ||
throw e; | ||
}).then(ifNotCancelled(function destroyAndActivate(stateResolveResultsObject) { | ||
transition.cancellable = false; | ||
return state | ||
}).then(ifNotCancelled(state => { | ||
stateProviderEmitter.emit(`stateChangeStart`, state, parameters, stateNameToArrayofStates(state.name)); | ||
lastStateStartedActivating.set(state.name, parameters); | ||
})).then(function getStateChanges() { | ||
const stateComparisonResults = compareStartAndEndStates({ | ||
original: lastCompletelyLoadedState.get(), | ||
destination: { | ||
name: newStateName, | ||
parameters, | ||
}, | ||
}); | ||
return stateChangeLogic(stateComparisonResults) // { destroy, change, create } | ||
}).then(ifNotCancelled(function resolveDestroyAndActivateStates(stateChanges) { | ||
return resolveStates(getStatesToResolve(stateChanges), extend(parameters)).catch(function onResolveError(e) { | ||
e.stateChangeError = true; | ||
throw e | ||
}).then(ifNotCancelled(function destroyAndActivate(stateResolveResultsObject) { | ||
transition.cancellable = false; | ||
var activateAll = function activateAll() { | ||
return activateStates(stateChanges.change.concat(stateChanges.create)); | ||
}; | ||
const activateAll = () => activateStates( | ||
stateChanges.change.concat(stateChanges.create), | ||
); | ||
activeStateResolveContent = extend(activeStateResolveContent, stateResolveResultsObject); | ||
activeStateResolveContent = extend(activeStateResolveContent, stateResolveResultsObject); | ||
return promiseMapSeries(reverse(stateChanges.destroy), destroyStateName).then(function () { | ||
return promiseMapSeries(reverse(stateChanges.change), function (stateName) { | ||
return resetStateName(extend(parameters), stateName); | ||
}); | ||
}).then(function () { | ||
return renderAll(stateChanges.create, extend(parameters)).then(activateAll); | ||
}); | ||
})); | ||
return series(reverse(stateChanges.destroy), destroyStateName).then(() => series( | ||
reverse(stateChanges.change), | ||
stateName => resetStateName(extend(parameters), stateName), | ||
)).then( | ||
() => renderAll(stateChanges.create, extend(parameters)).then(activateAll), | ||
) | ||
})) | ||
function activateStates(stateNames) { | ||
return stateNames.map(prototypalStateHolder.get).forEach(function (state) { | ||
var emitter = new eventemitter3(); | ||
var context = Object.create(emitter); | ||
context.domApi = activeDomApis[state.name]; | ||
context.data = state.data; | ||
context.parameters = parameters; | ||
context.content = getContentObject(activeStateResolveContent, state.name); | ||
activeEmitters[state.name] = emitter; | ||
function activateStates(stateNames) { | ||
return stateNames.map(prototypalStateHolder.get).forEach(state => { | ||
const emitter = new EventEmitter(); | ||
const context = Object.create(emitter); | ||
context.domApi = activeDomApis[state.name]; | ||
context.data = state.data; | ||
context.parameters = parameters; | ||
context.content = getContentObject(activeStateResolveContent, state.name); | ||
activeEmitters[state.name] = emitter; | ||
try { | ||
state.activate && state.activate(context); | ||
} catch (e) { | ||
isoNextTick(function () { | ||
throw e; | ||
}); | ||
} | ||
}); | ||
} | ||
})).then(function stateChangeComplete() { | ||
lastCompletelyLoadedState.set(newStateName, parameters); | ||
try { | ||
stateProviderEmitter.emit('stateChangeEnd', prototypalStateHolder.get(newStateName), parameters, stateNameToArrayofStates(newStateName)); | ||
} catch (e) { | ||
handleError('stateError', e); | ||
} | ||
}).catch(ifNotCancelled(function handleStateChangeError(err) { | ||
if (err && err.redirectTo) { | ||
stateProviderEmitter.emit('stateChangeCancelled', err); | ||
return stateProviderEmitter.go(err.redirectTo.name, err.redirectTo.params, { replace: true }); | ||
} else if (err) { | ||
handleError('stateChangeError', err); | ||
} | ||
})).catch(function handleCancellation(err) { | ||
if (err && err.wasCancelledBySomeoneElse) { | ||
// we don't care, the state transition manager has already emitted the stateChangeCancelled for us | ||
} else { | ||
throw new Error('This probably shouldn\'t happen, maybe file an issue or something ' + err); | ||
} | ||
}); | ||
try { | ||
state.activate && state.activate(context); | ||
} catch (e) { | ||
nextTick(() => { | ||
throw e | ||
}); | ||
} | ||
}) | ||
} | ||
})).then(function stateChangeComplete() { | ||
lastCompletelyLoadedState.set(newStateName, parameters); | ||
try { | ||
stateProviderEmitter.emit(`stateChangeEnd`, prototypalStateHolder.get(newStateName), parameters, stateNameToArrayofStates(newStateName)); | ||
} catch (e) { | ||
handleError(`stateError`, e); | ||
} | ||
}).catch(ifNotCancelled(function handleStateChangeError(err) { | ||
if (err && err.redirectTo) { | ||
stateProviderEmitter.emit(`stateChangeCancelled`, err); | ||
return stateProviderEmitter.go(err.redirectTo.name, err.redirectTo.params, { replace: true }) | ||
} else if (err) { | ||
handleError(`stateChangeError`, err); | ||
} | ||
})).catch(function handleCancellation(err) { | ||
if (err && err.wasCancelledBySomeoneElse) ; else { | ||
throw new Error(`This probably shouldn't happen, maybe file an issue or something ${ err }`) | ||
} | ||
}) | ||
} | ||
@@ -680,5 +635,5 @@ | ||
if (!lastStateStartedActivating.get().name) { | ||
throw new Error('makePath required a previous state to exist, and none was found'); | ||
throw new Error(`makePath required a previous state to exist, and none was found`) | ||
} | ||
return lastStateStartedActivating.get(); | ||
return lastStateStartedActivating.get() | ||
} | ||
@@ -689,6 +644,6 @@ if (options && options.inherit) { | ||
var destinationStateName = stateName === null ? getGuaranteedPreviousState().name : stateName; | ||
const destinationStateName = stateName === null ? getGuaranteedPreviousState().name : stateName; | ||
var destinationState = prototypalStateHolder.get(destinationStateName) || {}; | ||
var defaultParams = destinationState.defaultParameters || destinationState.defaultQuerystringParameters || {}; | ||
const destinationState = prototypalStateHolder.get(destinationStateName) || {}; | ||
const defaultParams = destinationState.defaultParameters || destinationState.defaultQuerystringParameters || {}; | ||
@@ -698,62 +653,48 @@ parameters = extend(computeDefaultParams(defaultParams), parameters); | ||
prototypalStateHolder.guaranteeAllStatesExist(destinationStateName); | ||
var route = prototypalStateHolder.buildFullStateRoute(destinationStateName); | ||
return pagePathBuilder(route, parameters || {}); | ||
const route = prototypalStateHolder.buildFullStateRoute(destinationStateName); | ||
return buildPath(route, parameters || {}) | ||
} | ||
var defaultOptions = { | ||
replace: false | ||
const defaultOptions = { | ||
replace: false, | ||
}; | ||
stateProviderEmitter.addState = addState; | ||
stateProviderEmitter.go = function (newStateName, parameters, options) { | ||
stateProviderEmitter.go = (newStateName, parameters, options) => { | ||
options = extend(defaultOptions, options); | ||
var goFunction = options.replace ? router.replace : router.go; | ||
const goFunction = options.replace ? router.replace : router.go; | ||
return promiseMe(makePath, newStateName, parameters, options).then(goFunction, function (err) { | ||
return handleError('stateChangeError', err); | ||
}); | ||
return promiseMe(makePath, newStateName, parameters, options) | ||
.then(goFunction, err => handleError(`stateChangeError`, err)) | ||
}; | ||
stateProviderEmitter.evaluateCurrentRoute = function (defaultState, defaultParams) { | ||
return promiseMe(makePath, defaultState, defaultParams).then(function (defaultPath) { | ||
router.evaluateCurrent(defaultPath); | ||
}).catch(function (err) { | ||
return handleError('stateError', err); | ||
}); | ||
}; | ||
stateProviderEmitter.makePath = function (stateName, parameters, options) { | ||
return pathPrefix + makePath(stateName, parameters, options); | ||
}; | ||
stateProviderEmitter.getActiveState = function () { | ||
return lastCompletelyLoadedState.get(); | ||
}; | ||
stateProviderEmitter.stateIsActive = function (stateName) { | ||
var parameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; | ||
stateProviderEmitter.evaluateCurrentRoute = (defaultState, defaultParams) => promiseMe(makePath, defaultState, defaultParams).then(defaultPath => { | ||
router.evaluateCurrent(defaultPath); | ||
}).catch(err => handleError(`stateError`, err)); | ||
stateProviderEmitter.makePath = (stateName, parameters, options) => pathPrefix + makePath(stateName, parameters, options); | ||
stateProviderEmitter.getActiveState = () => lastCompletelyLoadedState.get(); | ||
stateProviderEmitter.stateIsActive = (stateName, parameters = null) => { | ||
const currentState = lastCompletelyLoadedState.get(); | ||
const stateNameMatches = currentState.name === stateName || currentState.name.indexOf(stateName + `.`) === 0; | ||
const parametersWereNotPassedIn = !parameters; | ||
var currentState$$1 = lastCompletelyLoadedState.get(); | ||
var stateNameMatches = currentState$$1.name === stateName || currentState$$1.name.indexOf(stateName + '.') === 0; | ||
var parametersWereNotPassedIn = !parameters; | ||
return stateNameMatches && (parametersWereNotPassedIn || Object.keys(parameters).every(function (key) { | ||
return parameters[key] === currentState$$1.parameters[key]; | ||
})); | ||
return stateNameMatches | ||
&& (parametersWereNotPassedIn || Object.keys(parameters).every(key => parameters[key] === currentState.parameters[key])) | ||
}; | ||
var renderer = makeRenderer(stateProviderEmitter); | ||
const renderer = makeRenderer(stateProviderEmitter); | ||
destroyDom = thenDenodeify(renderer.destroy); | ||
getDomChild = thenDenodeify(renderer.getChildElement); | ||
renderDom = thenDenodeify(renderer.render); | ||
resetDom = thenDenodeify(renderer.reset); | ||
destroyDom = denodeify(renderer.destroy); | ||
getDomChild = denodeify(renderer.getChildElement); | ||
renderDom = denodeify(renderer.render); | ||
resetDom = denodeify(renderer.reset); | ||
return stateProviderEmitter; | ||
return stateProviderEmitter | ||
}; | ||
function getContentObject(stateResolveResultsObject, stateName) { | ||
var allPossibleResolvedStateNames = stateStringParser(stateName); | ||
const allPossibleResolvedStateNames = parse(stateName); | ||
return allPossibleResolvedStateNames.filter(function (stateName) { | ||
return stateResolveResultsObject[stateName]; | ||
}).reduce(function (obj, stateName) { | ||
return extend(obj, stateResolveResultsObject[stateName]); | ||
}, {}); | ||
return allPossibleResolvedStateNames | ||
.filter(stateName => stateResolveResultsObject[stateName]) | ||
.reduce((obj, stateName) => extend(obj, stateResolveResultsObject[stateName]), {}) | ||
} | ||
@@ -765,5 +706,5 @@ | ||
name: newStateName, | ||
params: parameters | ||
} | ||
}; | ||
params: parameters, | ||
}, | ||
} | ||
} | ||
@@ -773,31 +714,27 @@ | ||
function resolveStates(states, parameters) { | ||
var statesWithResolveFunctions = states.filter(isFunction('resolve')); | ||
var stateNamesWithResolveFunctions = statesWithResolveFunctions.map(getProperty('name')); | ||
const statesWithResolveFunctions = states.filter(isFunction(`resolve`)); | ||
const stateNamesWithResolveFunctions = statesWithResolveFunctions.map(getProperty(`name`)); | ||
var resolves = Promise.all(statesWithResolveFunctions.map(function (state) { | ||
return new Promise(function (resolve, reject) { | ||
var resolveCb = function resolveCb(err, content) { | ||
return err ? reject(err) : resolve(content); | ||
}; | ||
const resolves = Promise.all(statesWithResolveFunctions.map(state => new Promise((resolve, reject) => { | ||
const resolveCb = (err, content) => err ? reject(err) : resolve(content); | ||
resolveCb.redirect = function (newStateName, parameters) { | ||
reject(redirector(newStateName, parameters)); | ||
}; | ||
resolveCb.redirect = (newStateName, parameters) => { | ||
reject(redirector(newStateName, parameters)); | ||
}; | ||
var res = state.resolve(state.data, parameters, resolveCb); | ||
if (isThenable(res)) { | ||
resolve(res); | ||
} | ||
}); | ||
})); | ||
const res = state.resolve(state.data, parameters, resolveCb); | ||
if (isThenable(res)) { | ||
resolve(res); | ||
} | ||
}))); | ||
return resolves.then(function (resolveResults) { | ||
return combineArrays({ | ||
return resolves.then(resolveResults => | ||
combine({ | ||
stateName: stateNamesWithResolveFunctions, | ||
resolveResult: resolveResults | ||
}).reduce(function (obj, result) { | ||
resolveResult: resolveResults, | ||
}).reduce((obj, result) => { | ||
obj[result.stateName] = result.resolveResult; | ||
return obj; | ||
}, {}); | ||
}); | ||
return obj | ||
}, {}), | ||
) | ||
} | ||
@@ -804,0 +741,0 @@ |
{ | ||
"name": "abstract-state-router", | ||
"version": "6.2.0", | ||
"version": "6.2.1", | ||
"description": "Like ui-router, but without all the Angular. The best way to structure a single-page webapp.", | ||
@@ -27,25 +27,21 @@ "main": "bundle.js", | ||
"combine-arrays": "~1.0.2", | ||
"eventemitter3": "2.0.3", | ||
"hash-brown-router": "3.4.0", | ||
"eventemitter3": "4.0.7", | ||
"hash-brown-router": "~3.4.1", | ||
"iso-next-tick": "1.0.0", | ||
"page-path-builder": "~1.0.3", | ||
"page-path-builder": "~1.0.4", | ||
"path-to-regexp-with-reversible-keys": "~1.0.3", | ||
"then-denodeify": "1.0.1" | ||
"then-denodeify": "~1.0.1" | ||
}, | ||
"devDependencies": { | ||
"babel-core": "6.26.3", | ||
"babel-plugin-external-helpers": "6.22.0", | ||
"babel-preset-es2015": "6.24.1", | ||
"browserify": "16.2.3", | ||
"@rollup/plugin-commonjs": "^19.0.0", | ||
"@rollup/plugin-node-resolve": "^13.0.0", | ||
"browserify": "^17.0.0", | ||
"faucet": "0.0.1", | ||
"rollup": "0.50.0", | ||
"rollup-plugin-babel": "3.0.2", | ||
"rollup-plugin-commonjs": "8.2.1", | ||
"rollup-plugin-node-resolve": "3.0.0", | ||
"rollup-plugin-visualizer": "0.3.1", | ||
"rollup": "^2.53.1", | ||
"rollup-plugin-visualizer": "^4.2.0", | ||
"tap-browser-color": "0.1.2", | ||
"tape": "4.9.1", | ||
"tape": "^5.1.1", | ||
"tape-catch": "1.0.6", | ||
"tape-run": "4.0.0" | ||
"tape-run": "^8.0.0" | ||
} | ||
} |
@@ -19,3 +19,3 @@ **[Changelog](./changelog.md) • [Join the chat on Discord](https://discord.gg/G8FrErC) • [API documentation](#api)** | ||
The last breaking change was in October of 2017, and only involved removing some built-in polyfills. | ||
The last major version bump change was in July of 2021 when the project started shipping modern JS instead of ES5. There have been no breaking changes to the library's function APIs since 2015. | ||
@@ -22,0 +22,0 @@ abstract-state-router is extensible without much work, so very few feature additions have been necessary. |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
90018
10
5
594
1
1
+ Addedeventemitter3@4.0.7(transitive)
+ Addedhash-brown-router@3.4.1(transitive)
- Removedhash-brown-router@3.4.0(transitive)
Updatedeventemitter3@4.0.7
Updatedhash-brown-router@~3.4.1
Updatedpage-path-builder@~1.0.4
Updatedthen-denodeify@~1.0.1