gtfs-to-html
Version:
Build human readable transit timetables as HTML, PDF or CSV from GTFS
1,545 lines (1,313 loc) • 105 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.MaplibreGeocoder = factory());
})(this, (function () { 'use strict';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var immutable;
var hasRequiredImmutable;
function requireImmutable () {
if (hasRequiredImmutable) return immutable;
hasRequiredImmutable = 1;
immutable = extend;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {};
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target
}
return immutable;
}
var fuzzy = {exports: {}};
/*
* Fuzzy
* https://github.com/myork/fuzzy
*
* Copyright (c) 2012 Matt York
* Licensed under the MIT license.
*/
var hasRequiredFuzzy;
function requireFuzzy () {
if (hasRequiredFuzzy) return fuzzy.exports;
hasRequiredFuzzy = 1;
(function (module, exports$1) {
(function() {
var fuzzy = {};
// Use in node or in browser
{
module.exports = fuzzy;
}
// Return all elements of `array` that have a fuzzy
// match against `pattern`.
fuzzy.simpleFilter = function(pattern, array) {
return array.filter(function(str) {
return fuzzy.test(pattern, str);
});
};
// Does `pattern` fuzzy match `str`?
fuzzy.test = function(pattern, str) {
return fuzzy.match(pattern, str) !== null;
};
// If `pattern` matches `str`, wrap each matching character
// in `opts.pre` and `opts.post`. If no match, return null
fuzzy.match = function(pattern, str, opts) {
opts = opts || {};
var patternIdx = 0
, result = []
, len = str.length
, totalScore = 0
, currScore = 0
// prefix
, pre = opts.pre || ''
// suffix
, post = opts.post || ''
// String to compare against. This might be a lowercase version of the
// raw string
, compareString = opts.caseSensitive && str || str.toLowerCase()
, ch;
pattern = opts.caseSensitive && pattern || pattern.toLowerCase();
// For each character in the string, either add it to the result
// or wrap in template if it's the next string in the pattern
for(var idx = 0; idx < len; idx++) {
ch = str[idx];
if(compareString[idx] === pattern[patternIdx]) {
ch = pre + ch + post;
patternIdx += 1;
// consecutive characters should increase the score more than linearly
currScore += 1 + currScore;
} else {
currScore = 0;
}
totalScore += currScore;
result[result.length] = ch;
}
// return rendered string if we have a match for every char
if(patternIdx === pattern.length) {
// if the string is an exact match with pattern, totalScore should be maxed
totalScore = (compareString === pattern) ? Infinity : totalScore;
return {rendered: result.join(''), score: totalScore};
}
return null;
};
// The normal entry point. Filters `arr` for matches against `pattern`.
// It returns an array with matching values of the type:
//
// [{
// string: '<b>lah' // The rendered string
// , index: 2 // The index of the element in `arr`
// , original: 'blah' // The original element in `arr`
// }]
//
// `opts` is an optional argument bag. Details:
//
// opts = {
// // string to put before a matching character
// pre: '<b>'
//
// // string to put after matching character
// , post: '</b>'
//
// // Optional function. Input is an entry in the given arr`,
// // output should be the string to test `pattern` against.
// // In this example, if `arr = [{crying: 'koala'}]` we would return
// // 'koala'.
// , extract: function(arg) { return arg.crying; }
// }
fuzzy.filter = function(pattern, arr, opts) {
if(!arr || arr.length === 0) {
return [];
}
if (typeof pattern !== 'string') {
return arr;
}
opts = opts || {};
return arr
.reduce(function(prev, element, idx, arr) {
var str = element;
if(opts.extract) {
str = opts.extract(element);
}
var rendered = fuzzy.match(pattern, str, opts);
if(rendered != null) {
prev[prev.length] = {
string: rendered.rendered
, score: rendered.score
, index: idx
, original: element
};
}
return prev;
}, [])
// Sort by score. Browsers are inconsistent wrt stable/unstable
// sorting, so force stable by using the index in the case of tie.
// See http://ofb.net/~sethml/is-sort-stable.html
.sort(function(a,b) {
var compare = b.score - a.score;
if(compare) return compare;
return a.index - b.index;
});
};
}());
} (fuzzy));
return fuzzy.exports;
}
var list;
var hasRequiredList;
function requireList () {
if (hasRequiredList) return list;
hasRequiredList = 1;
var List = function(component) {
this.component = component;
this.items = [];
this.active = component.options.noInitialSelection ? -1 : 0;
this.wrapper = document.createElement('div');
this.wrapper.className = 'suggestions-wrapper';
this.element = document.createElement('ul');
this.element.className = 'suggestions';
this.wrapper.appendChild(this.element);
// selectingListItem is set to true in the time between the mousedown and mouseup when clicking an item in the list
// mousedown on a list item will cause the input to blur which normally hides the list, so this flag is used to keep
// the list open until the mouseup
this.selectingListItem = false;
component.el.parentNode.insertBefore(this.wrapper, component.el.nextSibling);
return this;
};
List.prototype.show = function() {
this.element.style.display = 'block';
};
List.prototype.hide = function() {
this.element.style.display = 'none';
};
List.prototype.add = function(item) {
this.items.push(item);
};
List.prototype.clear = function() {
this.items = [];
this.active = this.component.options.noInitialSelection ? -1 : 0;
};
List.prototype.isEmpty = function() {
return !this.items.length;
};
List.prototype.isVisible = function() {
return this.element.style.display === 'block';
};
List.prototype.draw = function() {
this.element.innerHTML = '';
if (this.items.length === 0) {
this.hide();
return;
}
for (var i = 0; i < this.items.length; i++) {
this.drawItem(this.items[i], this.active === i);
}
this.show();
};
List.prototype.drawItem = function(item, active) {
var li = document.createElement('li'),
a = document.createElement('a');
if (active) li.className += ' active';
a.innerHTML = item.string;
li.appendChild(a);
this.element.appendChild(li);
li.addEventListener('mousedown', function() {
this.selectingListItem = true;
}.bind(this));
li.addEventListener('mouseup', function() {
this.handleMouseUp.call(this, item);
}.bind(this));
};
List.prototype.handleMouseUp = function(item) {
this.selectingListItem = false;
this.component.value(item.original);
this.clear();
this.draw();
};
List.prototype.move = function(index) {
this.active = index;
this.draw();
};
List.prototype.previous = function() {
this.move(this.active <= 0 ? this.items.length - 1 : this.active - 1);
};
List.prototype.next = function() {
this.move(this.active >= this.items.length - 1 ? 0 : this.active + 1);
};
List.prototype.drawError = function(msg){
var li = document.createElement('li');
li.innerHTML = msg;
this.element.appendChild(li);
this.show();
};
list = List;
return list;
}
var suggestions;
var hasRequiredSuggestions;
function requireSuggestions () {
if (hasRequiredSuggestions) return suggestions;
hasRequiredSuggestions = 1;
var extend = requireImmutable();
var fuzzy = requireFuzzy();
var List = requireList();
var Suggestions = function(el, data, options) {
options = options || {};
this.options = extend({
minLength: 2,
limit: 5,
filter: true,
hideOnBlur: true,
noInitialSelection: true
}, options);
this.el = el;
this.data = data || [];
this.list = new List(this);
this.query = '';
this.selected = null;
this.list.draw();
this.el.addEventListener('keyup', function(e) {
this.handleKeyUp(e.keyCode, e);
}.bind(this), false);
this.el.addEventListener('keydown', function(e) {
this.handleKeyDown(e);
}.bind(this));
this.el.addEventListener('focus', function() {
this.handleFocus();
}.bind(this));
this.el.addEventListener('blur', function() {
this.handleBlur();
}.bind(this));
this.el.addEventListener('paste', function(e) {
this.handlePaste(e);
}.bind(this));
// use user-provided render function if given, otherwise just use the default
this.render = (this.options.render) ? this.options.render.bind(this) : this.render.bind(this);
this.getItemValue = (this.options.getItemValue) ? this.options.getItemValue.bind(this) : this.getItemValue.bind(this);
return this;
};
Suggestions.prototype.handleKeyUp = function(keyCode, e) {
// 40 - DOWN
// 38 - UP
// 27 - ESC
// 13 - ENTER
// 9 - TAB
if (keyCode === 40 ||
keyCode === 38 ||
keyCode === 27 ||
keyCode === 9) return;
if (keyCode === 13) {
if (this.list.items[this.list.active]) {
this.list.handleMouseUp(this.list.items[this.list.active]);
e.stopPropagation();
}
return;
}
this.handleInputChange(this.el.value);
};
Suggestions.prototype.handleKeyDown = function(e) {
switch (e.keyCode) {
case 13: // ENTER
if (this.list.active >= 0) {
this.list.selectingListItem = true;
}
break;
case 9: // TAB
if (!this.list.isEmpty()) {
if (this.list.isVisible()) {
e.preventDefault();
}
this.value(this.list.active >= 0 ? this.list.items[this.list.active].original : null);
this.list.hide();
}
break;
case 27: // ESC
if (!this.list.isEmpty()) this.list.hide();
break;
case 38: // UP
this.list.previous();
break;
case 40: // DOWN
this.list.next();
break;
}
};
Suggestions.prototype.handleBlur = function() {
if (!this.list.selectingListItem && this.options.hideOnBlur) {
this.list.hide();
}
};
Suggestions.prototype.handlePaste = function(e) {
if (e.clipboardData) {
this.handleInputChange(e.clipboardData.getData('Text'));
} else {
var self = this;
setTimeout(function () {
self.handleInputChange(e.target.value);
}, 100);
}
};
Suggestions.prototype.handleInputChange = function(query) {
this.query = this.normalize(query);
this.list.clear();
if (this.query.length < this.options.minLength) {
this.list.draw();
return;
}
this.getCandidates(function(data) {
for (var i = 0; i < data.length; i++) {
this.list.add(data[i]);
if (i === (this.options.limit - 1)) break;
}
this.list.draw();
}.bind(this));
};
Suggestions.prototype.handleFocus = function() {
if (!this.list.isEmpty()) this.list.show();
this.list.selectingListItem = false;
};
/**
* Update data previously passed
*
* @param {Array} revisedData
*/
Suggestions.prototype.update = function(revisedData) {
this.data = revisedData;
this.handleKeyUp();
};
/**
* Clears data
*/
Suggestions.prototype.clear = function() {
this.data = [];
this.list.clear();
};
/**
* Normalize the results list and input value for matching
*
* @param {String} value
* @return {String}
*/
Suggestions.prototype.normalize = function(value) {
value = value.toLowerCase();
return value;
};
/**
* Evaluates whether an array item qualifies as a match with the current query
*
* @param {String} candidate a possible item from the array passed
* @param {String} query the current query
* @return {Boolean}
*/
Suggestions.prototype.match = function(candidate, query) {
return candidate.indexOf(query) > -1;
};
Suggestions.prototype.value = function(value) {
this.selected = value;
this.el.value = this.getItemValue(value || { place_name: this.query });
if (document.createEvent) {
var e = document.createEvent('HTMLEvents');
e.initEvent('change', true, false);
this.el.dispatchEvent(e);
} else {
this.el.fireEvent('onchange');
}
};
Suggestions.prototype.getCandidates = function(callback) {
var options = {
pre: '<strong>',
post: '</strong>',
extract: function(d) { return this.getItemValue(d); }.bind(this)
};
var results;
if(this.options.filter){
results = fuzzy.filter(this.query, this.data, options);
results = results.map(function(item){
return {
original: item.original,
string: this.render(item.original, item.string)
};
}.bind(this));
}else {
results = this.data.map(function(d) {
var renderedString = this.render(d);
return {
original: d,
string: renderedString
};
}.bind(this));
}
callback(results);
};
/**
* For a given item in the data array, return what should be used as the candidate string
*
* @param {Object|String} item an item from the data array
* @return {String} item
*/
Suggestions.prototype.getItemValue = function(item) {
return item;
};
/**
* For a given item in the data array, return a string of html that should be rendered in the dropdown
* @param {Object|String} item an item from the data array
* @param {String} sourceFormatting a string that has pre-formatted html that should be passed directly through the render function
* @return {String} html
*/
Suggestions.prototype.render = function(item, sourceFormatting) {
if (sourceFormatting){
// use existing formatting on the source string
return sourceFormatting;
}
var boldString = (item.original) ? this.getItemValue(item.original) : this.getItemValue(item);
var indexString = this.normalize(boldString);
var indexOfQuery = indexString.lastIndexOf(this.query);
while (indexOfQuery > -1) {
var endIndexOfQuery = indexOfQuery + this.query.length;
boldString = boldString.slice(0, indexOfQuery) + '<strong>' + boldString.slice(indexOfQuery, endIndexOfQuery) + '</strong>' + boldString.slice(endIndexOfQuery);
indexOfQuery = indexString.slice(0, indexOfQuery).lastIndexOf(this.query);
}
return boldString
};
/**
* Render an custom error message in the suggestions list
* @param {String} msg An html string to render as an error message
*/
Suggestions.prototype.renderError = function(msg){
this.list.drawError(msg);
};
suggestions = Suggestions;
return suggestions;
}
var suggestionsList;
var hasRequiredSuggestionsList;
function requireSuggestionsList () {
if (hasRequiredSuggestionsList) return suggestionsList;
hasRequiredSuggestionsList = 1;
/**
* A typeahead component for inputs
* @class Suggestions
*
* @param {HTMLInputElement} el A valid HTML input element
* @param {Array} data An array of data used for results
* @param {Object} options
* @param {Number} [options.limit=5] Max number of results to display in the auto suggest list.
* @param {Number} [options.minLength=2] Number of characters typed into an input to trigger suggestions.
* @param {Boolean} [options.hideOnBlur=true] If `true`, hides the suggestions when focus is lost.
* @return {Suggestions} `this`
* @example
* // in the browser
* var input = document.querySelector('input');
* var data = [
* 'Roy Eldridge',
* 'Roy Hargrove',
* 'Rex Stewart'
* ];
*
* new Suggestions(input, data);
*
* // with options
* var input = document.querySelector('input');
* var data = [{
* name: 'Roy Eldridge',
* year: 1911
* }, {
* name: 'Roy Hargrove',
* year: 1969
* }, {
* name: 'Rex Stewart',
* year: 1907
* }];
*
* var typeahead = new Suggestions(input, data, {
* filter: false, // Disable filtering
* minLength: 3, // Number of characters typed into an input to trigger suggestions.
* limit: 3, // Max number of results to display.
* hideOnBlur: false // Don't hide results when input loses focus
* });
*
* // As we're passing an object of an arrays as data, override
* // `getItemValue` by specifying the specific property to search on.
* typeahead.getItemValue = function(item) { return item.name };
*
* input.addEventListener('change', function() {
* console.log(typeahead.selected); // Current selected item.
* });
*
* // With browserify
* var Suggestions = require('suggestions');
*
* new Suggestions(input, data);
*/
var Suggestions = requireSuggestions();
suggestionsList = Suggestions;
if (typeof window !== 'undefined') {
window.Suggestions = Suggestions;
}
return suggestionsList;
}
var suggestionsListExports = requireSuggestionsList();
var Typeahead = /*@__PURE__*/getDefaultExportFromCjs(suggestionsListExports);
var subtag$2 = {exports: {}};
var subtag$1 = subtag$2.exports;
var hasRequiredSubtag;
function requireSubtag () {
if (hasRequiredSubtag) return subtag$2.exports;
hasRequiredSubtag = 1;
(function (module) {
!function(root, name, make) {
if (module.exports) module.exports = make();
else root[name] = make();
}(subtag$1, 'subtag', function() {
var empty = '';
var pattern = /^([a-zA-Z]{2,3})(?:[_-]+([a-zA-Z]{3})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{4})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{2}|[0-9]{3})(?=$|[_-]+))?/;
function match(tag) {
return tag.match(pattern) || []
}
function split(tag) {
return match(tag).filter(function(v, i) { return v && i })
}
function api(tag) {
tag = match(tag);
return {
language: tag[1] || empty,
extlang: tag[2] || empty,
script: tag[3] || empty,
region: tag[4] || empty
}
}
function expose(target, key, value) {
Object.defineProperty(target, key, {
value: value,
enumerable: true
});
}
function part(position, pattern, type) {
function method(tag) {
return match(tag)[position] || empty
}
expose(method, 'pattern', pattern);
expose(api, type, method);
}
part(1, /^[a-zA-Z]{2,3}$/, 'language');
part(2, /^[a-zA-Z]{3}$/, 'extlang');
part(3, /^[a-zA-Z]{4}$/, 'script');
part(4, /^[a-zA-Z]{2}$|^[0-9]{3}$/, 'region');
expose(api, 'split', split);
return api
});
} (subtag$2));
return subtag$2.exports;
}
var subtagExports = requireSubtag();
var subtag = /*@__PURE__*/getDefaultExportFromCjs(subtagExports);
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
var lodash_debounce;
var hasRequiredLodash_debounce;
function requireLodash_debounce () {
if (hasRequiredLodash_debounce) return lodash_debounce;
hasRequiredLodash_debounce = 1;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return root.Date.now();
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
lodash_debounce = debounce;
return lodash_debounce;
}
var lodash_debounceExports = requireLodash_debounce();
var debounce = /*@__PURE__*/getDefaultExportFromCjs(lodash_debounceExports);
var immutableExports = requireImmutable();
var extend = /*@__PURE__*/getDefaultExportFromCjs(immutableExports);
var events = {exports: {}};
var hasRequiredEvents;
function requireEvents () {
if (hasRequiredEvents) return events.exports;
hasRequiredEvents = 1;
var R = typeof Reflect === 'object' ? Reflect : null;
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
};
var ReflectOwnKeys;
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys;
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
};
function EventEmitter() {
EventEmitter.init.call(this);
}
events.exports = EventEmitter;
events.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;