tulipan
Version:
Tulipan.js is a simple minimalistic and progressive JavaScript Framework for building Single Page Applications on the web
1,435 lines (1,287 loc) • 467 kB
JavaScript
/*!
* Tulipan.js v1.7.0
* (c) 2022 Nelson Carrasquel
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Navigo = factory());
}(this, (function () { 'use strict';
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; };
function isPushStateAvailable() {
return !!(typeof window !== 'undefined' && window.history && window.history.pushState);
}
function Navigo(r, useHash, hash) {
this.root = null;
this._routes = [];
this._useHash = useHash;
this._hash = typeof hash === 'undefined' ? '#' : hash;
this._paused = false;
this._destroyed = false;
this._lastRouteResolved = null;
this._notFoundHandler = null;
this._defaultHandler = null;
this._usePushState = !useHash && isPushStateAvailable();
this._onLocationChange = this._onLocationChange.bind(this);
this._genericHooks = null;
this._historyAPIUpdateMethod = 'pushState';
if (r) {
this.root = useHash ? r.replace(/\/$/, '/' + this._hash) : r.replace(/\/$/, '');
} else if (useHash) {
this.root = this._cLoc().split(this._hash)[0].replace(/\/$/, '/' + this._hash);
}
this._listen();
this.updatePageLinks();
}
function clean(s) {
if (s instanceof RegExp) return s;
return s.replace(/\/+$/, '').replace(/^\/+/, '^/');
}
function regExpResultToParams(match, names) {
if (names.length === 0) return null;
if (!match) return null;
return match.slice(1, match.length).reduce(function (params, value, index) {
if (params === null) params = {};
params[names[index]] = decodeURIComponent(value);
return params;
}, null);
}
function replaceDynamicURLParts(route) {
var paramNames = [],
regexp;
if (route instanceof RegExp) {
regexp = route;
} else {
regexp = new RegExp(route.replace(Navigo.PARAMETER_REGEXP, function (full, dots, name) {
paramNames.push(name);
return Navigo.REPLACE_VARIABLE_REGEXP;
}).replace(Navigo.WILDCARD_REGEXP, Navigo.REPLACE_WILDCARD) + Navigo.FOLLOWED_BY_SLASH_REGEXP, Navigo.MATCH_REGEXP_FLAGS);
}
return { regexp: regexp, paramNames: paramNames };
}
function getUrlDepth(url) {
return url.replace(/\/$/, '').split('/').length;
}
function compareUrlDepth(urlA, urlB) {
return getUrlDepth(urlB) - getUrlDepth(urlA);
}
function findMatchedRoutes(url) {
var routes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return routes.map(function (route) {
var _replaceDynamicURLPar = replaceDynamicURLParts(clean(route.route)),
regexp = _replaceDynamicURLPar.regexp,
paramNames = _replaceDynamicURLPar.paramNames;
var match = url.replace(/^\/+/, '/').match(regexp);
var params = regExpResultToParams(match, paramNames);
return match ? { match: match, route: route, params: params } : false;
}).filter(function (m) {
return m;
});
}
function match(url, routes) {
return findMatchedRoutes(url, routes)[0] || false;
}
function root(url, routes) {
var matched = routes.map(function (route) {
return route.route === '' || route.route === '*' ? url : url.split(new RegExp(route.route + '($|\/)'))[0];
});
var fallbackURL = clean(url);
if (matched.length > 1) {
return matched.reduce(function (result, url) {
if (result.length > url.length) result = url;
return result;
}, matched[0]);
} else if (matched.length === 1) {
return matched[0];
}
return fallbackURL;
}
function isHashChangeAPIAvailable() {
return typeof window !== 'undefined' && 'onhashchange' in window;
}
function extractGETParameters(url) {
return url.split(/\?(.*)?$/).slice(1).join('');
}
function getOnlyURL(url, useHash, hash) {
var onlyURL = url,
split;
var cleanGETParam = function cleanGETParam(str) {
return str.split(/\?(.*)?$/)[0];
};
if (typeof hash === 'undefined') {
// To preserve BC
hash = '#';
}
if (isPushStateAvailable() && !useHash) {
onlyURL = cleanGETParam(url).split(hash)[0];
} else {
split = url.split(hash);
onlyURL = split.length > 1 ? cleanGETParam(split[1]) : cleanGETParam(split[0]);
}
return onlyURL;
}
function manageHooks(handler, hooks, params) {
if (hooks && (typeof hooks === 'undefined' ? 'undefined' : _typeof(hooks)) === 'object') {
if (hooks.before) {
hooks.before(function () {
var shouldRoute = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
if (!shouldRoute) return;
handler();
hooks.after && hooks.after(params);
}, params);
return;
} else if (hooks.after) {
handler();
hooks.after && hooks.after(params);
return;
}
}
handler();
}
function isHashedRoot(url, useHash, hash) {
if (isPushStateAvailable() && !useHash) {
return false;
}
if (!url.match(hash)) {
return false;
}
var split = url.split(hash);
return split.length < 2 || split[1] === '';
}
Navigo.prototype = {
helpers: {
match: match,
root: root,
clean: clean,
getOnlyURL: getOnlyURL
},
navigate: function navigate(path, absolute) {
var to;
path = path || '';
if (this._usePushState) {
to = (!absolute ? this._getRoot() + '/' : '') + path.replace(/^\/+/, '/');
to = to.replace(/([^:])(\/{2,})/g, '$1/');
history[this._historyAPIUpdateMethod]({}, '', to);
this.resolve();
} else if (typeof window !== 'undefined') {
path = path.replace(new RegExp('^' + this._hash), '');
window.location.href = window.location.href.replace(/#$/, '').replace(new RegExp(this._hash + '.*$'), '') + this._hash + path;
}
return this;
},
on: function on() {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (typeof args[0] === 'function') {
this._defaultHandler = { handler: args[0], hooks: args[1] };
} else if (args.length >= 2) {
if (args[0] === '/') {
var func = args[1];
if (_typeof(args[1]) === 'object') {
func = args[1].uses;
}
this._defaultHandler = { handler: func, hooks: args[2] };
} else {
this._add(args[0], args[1], args[2]);
}
} else if (_typeof(args[0]) === 'object') {
var orderedRoutes = Object.keys(args[0]).sort(compareUrlDepth);
orderedRoutes.forEach(function (route) {
_this.on(route, args[0][route]);
});
}
return this;
},
off: function off(handler) {
if (this._defaultHandler !== null && handler === this._defaultHandler.handler) {
this._defaultHandler = null;
} else if (this._notFoundHandler !== null && handler === this._notFoundHandler.handler) {
this._notFoundHandler = null;
}
this._routes = this._routes.reduce(function (result, r) {
if (r.handler !== handler) result.push(r);
return result;
}, []);
return this;
},
notFound: function notFound(handler, hooks) {
this._notFoundHandler = { handler: handler, hooks: hooks };
return this;
},
resolve: function resolve(current) {
var _this2 = this;
var handler, m;
var url = (current || this._cLoc()).replace(this._getRoot(), '');
if (this._useHash) {
url = url.replace(new RegExp('^\/' + this._hash), '/');
}
var GETParameters = extractGETParameters(current || this._cLoc());
var onlyURL = getOnlyURL(url, this._useHash, this._hash);
if (this._paused) return false;
if (this._lastRouteResolved && onlyURL === this._lastRouteResolved.url && GETParameters === this._lastRouteResolved.query) {
if (this._lastRouteResolved.hooks && this._lastRouteResolved.hooks.already) {
this._lastRouteResolved.hooks.already(this._lastRouteResolved.params);
}
return false;
}
m = match(onlyURL, this._routes);
if (m) {
this._callLeave();
this._lastRouteResolved = {
url: onlyURL,
query: GETParameters,
hooks: m.route.hooks,
params: m.params,
name: m.route.name
};
handler = m.route.handler;
manageHooks(function () {
manageHooks(function () {
m.route.route instanceof RegExp ? handler.apply(undefined, m.match.slice(1, m.match.length)) : handler(m.params, GETParameters);
}, m.route.hooks, m.params, _this2._genericHooks);
}, this._genericHooks, m.params);
return m;
} else if (this._defaultHandler && (onlyURL === '' || onlyURL === '/' || onlyURL === this._hash || isHashedRoot(onlyURL, this._useHash, this._hash))) {
manageHooks(function () {
manageHooks(function () {
_this2._callLeave();
_this2._lastRouteResolved = { url: onlyURL, query: GETParameters, hooks: _this2._defaultHandler.hooks };
_this2._defaultHandler.handler(GETParameters);
}, _this2._defaultHandler.hooks);
}, this._genericHooks);
return true;
} else if (this._notFoundHandler) {
manageHooks(function () {
manageHooks(function () {
_this2._callLeave();
_this2._lastRouteResolved = { url: onlyURL, query: GETParameters, hooks: _this2._notFoundHandler.hooks };
_this2._notFoundHandler.handler(GETParameters);
}, _this2._notFoundHandler.hooks);
}, this._genericHooks);
}
return false;
},
destroy: function destroy() {
this._routes = [];
this._destroyed = true;
this._lastRouteResolved = null;
this._genericHooks = null;
clearTimeout(this._listeningInterval);
if (typeof window !== 'undefined') {
window.removeEventListener('popstate', this._onLocationChange);
window.removeEventListener('hashchange', this._onLocationChange);
}
},
updatePageLinks: function updatePageLinks() {
var self = this;
if (typeof document === 'undefined') return;
this._findLinks().forEach(function (link) {
if (!link.hasListenerAttached) {
link.addEventListener('click', function (e) {
if ((e.ctrlKey || e.metaKey) && e.target.tagName.toLowerCase() == 'a') {
return false;
}
var location = self.getLinkPath(link);
if (!self._destroyed) {
e.preventDefault();
self.navigate(location.replace(/\/+$/, '').replace(/^\/+/, '/'));
}
});
link.hasListenerAttached = true;
}
});
},
generate: function generate(name) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var result = this._routes.reduce(function (result, route) {
var key;
if (route.name === name) {
result = route.route;
for (key in data) {
result = result.toString().replace(':' + key, data[key]);
}
}
return result;
}, '');
return this._useHash ? this._hash + result : result;
},
link: function link(path) {
return this._getRoot() + path;
},
pause: function pause() {
var status = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
this._paused = status;
if (status) {
this._historyAPIUpdateMethod = 'replaceState';
} else {
this._historyAPIUpdateMethod = 'pushState';
}
},
resume: function resume() {
this.pause(false);
},
historyAPIUpdateMethod: function historyAPIUpdateMethod(value) {
if (typeof value === 'undefined') return this._historyAPIUpdateMethod;
this._historyAPIUpdateMethod = value;
return value;
},
disableIfAPINotAvailable: function disableIfAPINotAvailable() {
if (!isPushStateAvailable()) {
this.destroy();
}
},
lastRouteResolved: function lastRouteResolved() {
return this._lastRouteResolved;
},
getLinkPath: function getLinkPath(link) {
return link.getAttribute('href');
},
hooks: function hooks(_hooks) {
this._genericHooks = _hooks;
},
_add: function _add(route) {
var handler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var hooks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (typeof route === 'string') {
route = encodeURI(route);
}
this._routes.push((typeof handler === 'undefined' ? 'undefined' : _typeof(handler)) === 'object' ? {
route: route,
handler: handler.uses,
name: handler.as,
hooks: hooks || handler.hooks
} : { route: route, handler: handler, hooks: hooks });
return this._add;
},
_getRoot: function _getRoot() {
if (this.root !== null) return this.root;
this.root = root(this._cLoc().split('?')[0], this._routes);
return this.root;
},
_listen: function _listen() {
var _this3 = this;
if (this._usePushState) {
window.addEventListener('popstate', this._onLocationChange);
} else if (isHashChangeAPIAvailable()) {
window.addEventListener('hashchange', this._onLocationChange);
} else {
var cached = this._cLoc(),
current = void 0,
_check = void 0;
_check = function check() {
current = _this3._cLoc();
if (cached !== current) {
cached = current;
_this3.resolve();
}
_this3._listeningInterval = setTimeout(_check, 200);
};
_check();
}
},
_cLoc: function _cLoc() {
if (typeof window !== 'undefined') {
if (typeof window.__NAVIGO_WINDOW_LOCATION_MOCK__ !== 'undefined') {
return window.__NAVIGO_WINDOW_LOCATION_MOCK__;
}
return clean(window.location.href);
}
return '';
},
_findLinks: function _findLinks() {
return [].slice.call(document.querySelectorAll('[data-navigo]'));
},
_onLocationChange: function _onLocationChange() {
this.resolve();
},
_callLeave: function _callLeave() {
var lastRouteResolved = this._lastRouteResolved;
if (lastRouteResolved && lastRouteResolved.hooks && lastRouteResolved.hooks.leave) {
lastRouteResolved.hooks.leave(lastRouteResolved.params);
}
}
};
Navigo.PARAMETER_REGEXP = /([:*])(\w+)/g;
Navigo.WILDCARD_REGEXP = /\*/g;
Navigo.REPLACE_VARIABLE_REGEXP = '([^\/]+)';
Navigo.REPLACE_WILDCARD = '(?:.*)';
Navigo.FOLLOWED_BY_SLASH_REGEXP = '(?:\/$|$)';
Navigo.MATCH_REGEXP_FLAGS = '';
return Navigo;
})));
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.store = factory());
}(this, (function () { 'use strict';
// Store.js
var store = {},
win = (typeof window != 'undefined' ? window : global),
doc = win.document,
localStorageName = 'localStorage',
scriptTag = 'script',
storage
store.disabled = false
store.version = '1.3.20'
store.set = function(key, value) {}
store.get = function(key, defaultVal) {}
store.has = function(key) { return store.get(key) !== undefined }
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (defaultVal == null) {
defaultVal = {}
}
var val = store.get(key, defaultVal)
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.forEach = function() {}
store.serialize = function(value) {
return JSON.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return JSON.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key, defaultVal) {
var val = store.deserialize(storage.getItem(key))
return (val === undefined ? defaultVal : val)
}
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
store.forEach(function(key, val) {
ret[key] = val
})
return ret
}
store.forEach = function(callback) {
for (var i=0; i<storage.length; i++) {
var key = storage.key(i)
callback(key, store.get(key))
}
}
} else if (doc && doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
var withIEStorage = function(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys cannot start with a digit or contain certain chars.
// See https://github.com/marcuswestin/store.js/issues/40
// See https://github.com/marcuswestin/store.js/issues/83
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
var ieKeyFix = function(key) {
return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key, defaultVal) {
key = ieKeyFix(key)
var val = store.deserialize(storage.getAttribute(key))
return (val === undefined ? defaultVal : val)
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=attributes.length-1; i>=0; i--) {
storage.removeAttribute(attributes[i].name)
}
storage.save(localStorageName)
})
store.getAll = function(storage) {
var ret = {}
store.forEach(function(key, val) {
ret[key] = val
})
return ret
}
store.forEach = withIEStorage(function(storage, callback) {
var attributes = storage.XMLDocument.documentElement.attributes
for (var i=0, attr; attr=attributes[i]; ++i) {
callback(attr.name, store.deserialize(storage.getAttribute(attr.name)))
}
})
}
try {
var testKey = '__storejs__'
store.set(testKey, testKey)
if (store.get(testKey) != testKey) { store.disabled = true }
store.remove(testKey)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
return store
})));
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define('underscore', factory) :
(function() {
var current = global._;
var exports = factory();
global._ = exports;
exports.noConflict = function() { global._ = current; return exports; };
})();
}(this, (function () {
// Underscore.js 1.10.2
// https://underscorejs.org
// (c) 2009-2020 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
// Baseline setup
// --------------
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
Function('return this')() ||
{};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeCreate = Object.create;
// Create references to these builtin functions because we override them.
var _isNaN = root.isNaN,
_isFinite = root.isFinite;
// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
// The Underscore object. All exported functions below are added to it in the
// modules/index-all.js using the mixin function.
function _(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
}
// Current version.
var VERSION = _.VERSION = '1.10.2';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
function optimizeCb(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
// The 2-argument case is omitted because we’re not using it.
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
}
// An internal function to generate callbacks that can be applied to each
// element in a collection, returning the desired result — either `identity`,
// an arbitrary callback, a property matcher, or a property accessor.
function baseIteratee(value, context, argCount) {
if (value == null) return identity;
if (isFunction(value)) return optimizeCb(value, context, argCount);
if (isObject(value) && !isArray(value)) return matcher(value);
return property(value);
}
// External wrapper for our callback generator. Users may customize
// `_.iteratee` if they want additional predicate/iteratee shorthand styles.
// This abstraction hides the internal-only argCount argument.
_.iteratee = iteratee;
function iteratee(value, context) {
return baseIteratee(value, context, Infinity);
}
// The function we actually call internally. It invokes _.iteratee if
// overridden, otherwise baseIteratee.
function cb(value, context, argCount) {
if (_.iteratee !== iteratee) return _.iteratee(value, context);
return baseIteratee(value, context, argCount);
}
// Some functions take a variable number of arguments, or a few expected
// arguments at the beginning and then a variable number of values to operate
// on. This helper accumulates all remaining arguments past the function’s
// argument length (or an explicit `startIndex`), into an array that becomes
// the last argument. Similar to ES6’s "rest parameter".
function restArguments(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0;
for (; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
case 2: return func.call(this, arguments[0], arguments[1], rest);
}
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
}
// An internal function for creating a new object that inherits from another.
function baseCreate(prototype) {
if (!isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
}
function shallowProperty(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
}
function _has(obj, path) {
return obj != null && hasOwnProperty.call(obj, path);
}
function deepGet(obj, path) {
var length = path.length;
for (var i = 0; i < length; i++) {
if (obj == null) return void 0;
obj = obj[path[i]];
}
return length ? obj : void 0;
}
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object.
// Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = shallowProperty('length');
function isArrayLike(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
}
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
function each(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var _keys = keys(obj);
for (i = 0, length = _keys.length; i < length; i++) {
iteratee(obj[_keys[i]], _keys[i], obj);
}
}
return obj;
}
// Return the results of applying the iteratee to each element.
function map(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var _keys = !isArrayLike(obj) && keys(obj),
length = (_keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = _keys ? _keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
}
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Wrap code that reassigns argument variables in a separate function than
// the one that accesses `arguments.length` to avoid a perf hit. (#1991)
var reducer = function(obj, iteratee, memo, initial) {
var _keys = !isArrayLike(obj) && keys(obj),
length = (_keys || obj).length,
index = dir > 0 ? 0 : length - 1;
if (!initial) {
memo = obj[_keys ? _keys[index] : index];
index += dir;
}
for (; index >= 0 && index < length; index += dir) {
var currentKey = _keys ? _keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
return function(obj, iteratee, memo, context) {
var initial = arguments.length >= 3;
return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
var reduce = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
var reduceRight = createReduce(-1);
// Return the first value which passes a truth test.
function find(obj, predicate, context) {
var keyFinder = isArrayLike(obj) ? findIndex : findKey;
var key = keyFinder(obj, predicate, context);
if (key !== void 0 && key !== -1) return obj[key];
}
// Return all the elements that pass a truth test.
function filter(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
}
// Return all the elements for which a truth test fails.
function reject(obj, predicate, context) {
return filter(obj, negate(cb(predicate)), context);
}
// Determine whether all of the elements match a truth test.
function every(obj, predicate, context) {
predicate = cb(predicate, context);
var _keys = !isArrayLike(obj) && keys(obj),
length = (_keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = _keys ? _keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
}
// Determine if at least one element in the object matches a truth test.
function some(obj, predicate, context) {
predicate = cb(predicate, context);
var _keys = !isArrayLike(obj) && keys(obj),
length = (_keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = _keys ? _keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
}
// Determine if the array or object contains a given item (using `===`).
function contains(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return indexOf(obj, item, fromIndex) >= 0;
}
// Invoke a method (with arguments) on every item in a collection.
var invoke = restArguments(function(obj, path, args) {
var contextPath, func;
if (isFunction(path)) {
func = path;
} else if (isArray(path)) {
contextPath = path.slice(0, -1);
path = path[path.length - 1];
}
return map(obj, function(context) {
var method = func;
if (!method) {
if (contextPath && contextPath.length) {
context = deepGet(context, contextPath);
}
if (context == null) return void 0;
method = context[path];
}
return method == null ? method : method.apply(context, args);
});
});
// Convenience version of a common use case of `map`: fetching a property.
function pluck(obj, key) {
return map(obj, property(key));
}
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
function where(obj, attrs) {
return filter(obj, matcher(attrs));
}
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
function findWhere(obj, attrs) {
return find(obj, matcher(attrs));
}
// Return the maximum element (or element-based computation).
function max(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
obj = isArrayLike(obj) ? obj : values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value != null && value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
each(obj, function(v, index, list) {
computed = iteratee(v, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = v;
lastComputed = computed;
}
});
}
return result;
}
// Return the minimum element (or element-based computation).
function min(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
obj = isArrayLike(obj) ? obj : values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value != null && value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
each(obj, function(v, index, list) {
computed = iteratee(v, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = v;
lastComputed = computed;
}
});
}
return result;
}
// Shuffle a collection.
function shuffle(obj) {
return sample(obj, Infinity);
}
// Sample **n** random values from a collection using the modern version of the
// [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
function sample(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = values(obj);
return obj[random(obj.length - 1)];
}
var sample = isArrayLike(obj) ? clone(obj) : values(obj);
var length = getLength(sample);
n = Math.max(Math.min(n, length), 0);
var last = length - 1;
for (var index = 0; index < n; index++) {
var rand = random(index, last);
var temp = sample[index];
sample[index] = sample[rand];
sample[rand] = temp;
}
return sample.slice(0, n);
}
// Sort the object's values by a criterion produced by an iteratee.
function sortBy(obj, iteratee, context) {
var index = 0;
iteratee = cb(iteratee, context);
return pluck(map(obj, function(value, key, list) {
return {
value: value,
index: index++,
criteria: iteratee(value, key, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
}
// An internal function used for aggregate "group by" operations.
function group(behavior, partition) {
return function(obj, iteratee, context) {
var result = partition ? [[], []] : {};
iteratee = cb(iteratee, context);
each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
}
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
var groupBy = group(function(result, value, key) {
if (_has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
var indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
var countBy = group(function(result, value, key) {
if (_has(result, key)) result[key]++; else result[key] = 1;
});
var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
// Safely create a real, live array from anything iterable.
function toArray(obj) {
if (!obj) return [];
if (isArray(obj)) return slice.call(obj);
if (isString(obj)) {
// Keep surrogate pair characters together
return obj.match(reStrSymbol);
}
if (isArrayLike(obj)) return map(obj, identity);
return values(obj);
}
// Return the number of elements in an object.
function size(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : keys(obj).length;
}
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
var partition = group(function(result, value, pass) {
result[pass ? 0 : 1].push(value);
}, true);
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. The **guard** check allows it to work with `map`.
function first(array, n, guard) {
if (array == null || array.length < 1) return n == null ? void 0 : [];
if (n == null || guard) return array[0];
return initial(array, array.length - n);
}
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
function initial(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
}
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
function last(array, n, guard) {
if (array == null || array.length < 1) return n == null ? void 0 : [];
if (n == null || guard) return array[array.length - 1];
return rest(array, Math.max(0, array.length - n));
}
// Returns everything but the first entry of the array. Especially useful on
// the arguments object. Passing an **n** will return the rest N values in the
// array.
function rest(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
}
// Trim out all falsy values from an array.
function compact(array) {
return filter(array, Boolean);
}
// Internal implementation of a recursive `flatten` function.
function _flatten(input, shallow, strict, output) {
output = output || [];
var idx = output.length;
for (var i = 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (isArray(value) || isArguments(value))) {
// Flatten current level of array or arguments object.
if (shallow) {
var j = 0, len = value.length;
while (j < len) output[idx++] = value[j++];
} else {
_flatten(value, shallow, strict, output);
idx = output.length;
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
}
// Flatten out an array, either recursively (by default), or just one level.
function flatten(array, shallow) {
return _flatten(array, shallow, false);
}
// Return a version of the array that does not contain the specified value(s).
var without = restArguments(function(array, otherArrays) {
return difference(array, otherArrays);
});
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// The faster algorithm will not work with an iteratee if the iteratee
// is not a one-to-one function, so providing an iteratee will disable
// the faster algorithm.
function uniq(array, isSorted, iteratee, context) {
if (!isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted && !iteratee) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!contains(result, value)) {
result.push(value);
}
}
return result;
}
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
var union = restArguments(function(arrays) {
return uniq(_flatten(arrays, true, true));
});
// Produce an array that contains every item shared between all the
// passed-in arrays.
function intersection(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (contains(result, item)) continue;
var j;
for (j = 1; j < argsLength; j++) {
if (!contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
}
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
var difference = restArguments(function(array, rest) {
rest = _flatten(rest, true, true);
return filter(array, function(value){
return !contains(rest, value);
});
});
// Complement of zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices.
function unzip(array) {
var length = array && max(array, getLength).length || 0;
var result = Array(length);
for (var index = 0; index < length; index++) {
result[index] = pluck(array, index);
}
return result;
}
// Zip together multiple lists into a single array -- elements that share
// an index go together.
var zip = restArguments(unzip);
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values. Passing by pairs is the reverse of pairs.
function object(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
}
// Generator function to create the findIndex and findLastIndex functions.
function createPredicateIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test.
var findIndex = createPredicateIndexFinder(1);
var findLastIndex = createPredicateIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
function sortedIndex(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
}
// Generator function to create the indexOf and lastIndexOf functions.
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
var indexOf = createIndexFinder(1, findIndex, sortedIndex);
var lastIndexOf = createIndexFinder(-1, findLastIndex);
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](https://docs.python.org/library/functions.html#range).
function range(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
if (!step) {
step = stop < start ? -1 : 1;
}
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
}
// Chunk a single array into multiple arrays, each containing `count` or fewer
// items.
function chunk(array, count) {
if (count == null || count < 1) return [];
var result = [];
var i = 0, length = array.length;
while (i < length) {
result.push(slice.call(array, i, i += count));
}
return result;
}
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments.
function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (isObject(result)) return result;
return self;
}
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
var bind = restArguments(function(func, context, args) {
if (!isFunction(func)) throw new TypeError('Bind must be called on a function');
var bound = restArguments(function(callArgs) {
return executeBound(func, bound, context, this, args.concat(callArgs));
});
return bound;
});
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder by default, allowing any combination of arguments to be
// pre-filled. Set `partial.placeholder` for a custom placeholder argument.
var partial = restArguments(function(func, boundArgs) {
var placeholder = partial.placeholder;
var