You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

22238 lines
4.6 MiB

3 years ago
'use strict';
var obsidian = require('obsidian');
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn) {
var module = { exports: {} };
return fn(module, module.exports), module.exports;
}
/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.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 = createCommonjsModule(function (module, exports) {
3 years ago
(function(){/** Used as a safe reference for `undefined` in pre-ES5 environments. */var undefined$1;/** Used as the semantic version number. */var VERSION='4.17.21';/** Used as the size to enable large array optimizations. */var LARGE_ARRAY_SIZE=200;/** Error message constants. */var CORE_ERROR_TEXT='Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',FUNC_ERROR_TEXT='Expected a function',INVALID_TEMPL_VAR_ERROR_TEXT='Invalid `variable` option passed into `_.template`';/** Used to stand-in for `undefined` hash values. */var HASH_UNDEFINED='__lodash_hash_undefined__';/** Used as the maximum memoize cache size. */var MAX_MEMOIZE_SIZE=500;/** Used as the internal argument placeholder. */var PLACEHOLDER='__lodash_placeholder__';/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4;/** Used to compose bitmasks for value comparisons. */var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;/** Used to compose bitmasks for function metadata. */var WRAP_BIND_FLAG=1,WRAP_BIND_KEY_FLAG=2,WRAP_CURRY_BOUND_FLAG=4,WRAP_CURRY_FLAG=8,WRAP_CURRY_RIGHT_FLAG=16,WRAP_PARTIAL_FLAG=32,WRAP_PARTIAL_RIGHT_FLAG=64,WRAP_ARY_FLAG=128,WRAP_REARG_FLAG=256,WRAP_FLIP_FLAG=512;/** Used as default options for `_.truncate`. */var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION='...';/** Used to detect hot functions by number of calls within a span of milliseconds. */var HOT_COUNT=800,HOT_SPAN=16;/** Used to indicate the type of lazy iteratees. */var LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3;/** Used as references for various `Number` constants. */var INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e+308,NAN=0/0;/** Used as references for the maximum length and index of an array. */var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;/** Used to associate wrap methods with their bit flags. */var wrapFlags=[['ary',WRAP_ARY_FLAG],['bind',WRAP_BIND_FLAG],['bindKey',WRAP_BIND_KEY_FLAG],['curry',WRAP_CURRY_FLAG],['curryRight',WRAP_CURRY_RIGHT_FLAG],['flip',WRAP_FLIP_FLAG],['partial',WRAP_PARTIAL_FLAG],['partialRight',WRAP_PARTIAL_RIGHT_FLAG],['rearg',WRAP_REARG_FLAG]];/** `Object#toString` result references. */var argsTag='[object Arguments]',arrayTag='[object Array]',asyncTag='[object AsyncFunction]',boolTag='[object Boolean]',dateTag='[object Date]',domExcTag='[object DOMException]',errorTag='[object Error]',funcTag='[object Function]',genTag='[object GeneratorFunction]',mapTag='[object Map]',numberTag='[object Number]',nullTag='[object Null]',objectTag='[object Object]',promiseTag='[object Promise]',proxyTag='[object Proxy]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',symbolTag='[object Symbol]',undefinedTag='[object Undefined]',weakMapTag='[object WeakMap]',weakSetTag='[object WeakSet]';var arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]';/** Used to match empty string literals in compiled template source. */var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;/** Used to match HTML entities and HTML characters. */var reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);/** Used to match template delimiters. */var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;/** Used to match property names within property paths. */var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;/
3 years ago
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
3 years ago
*/var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);/** Used to match leading whitespace. */var reTrimStart=/^\s+/;/** Used to match a single whitespace character. */var reWhitespace=/\s/;/** Used to match wrap detail comments. */var reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /;/** Used to match words composed of alphanumeric characters. */var reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;/**
3 years ago
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
3 years ago
*/var reForbiddenIdentifierChars=/[()=,{}\[\]\/\s]/;/** Used to match backslashes in property paths. */var reEscapeChar=/\\(\\)?/g;/**
3 years ago
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
3 years ago
*/var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;/** Used to match `RegExp` flags from their coerced string values. */var reFlags=/\w*$/;/** 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 host constructors (Safari). */var reIsHostCtor=/^\[object .+?Constructor\]$/;/** Used to detect octal string values. */var reIsOctal=/^0o[0-7]+$/i;/** Used to detect unsigned integer values. */var reIsUint=/^(?:0|[1-9]\d*)$/;/** Used to match Latin Unicode letters (excluding mathematical operators). */var reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;/** Used to ensure capturing order of template delimiters. */var reNoMatch=/($^)/;/** Used to match unescaped characters in compiled string literals. */var reUnescapedString=/['\n\r\u2028\u2029\\]/g;/** Used to compose unicode character classes. */var rsAstralRange='\\ud800-\\udfff',rsComboMarksRange='\\u0300-\\u036f',reComboHalfMarksRange='\\ufe20-\\ufe2f',rsComboSymbolsRange='\\u20d0-\\u20ff',rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsDingbatRange='\\u2700-\\u27bf',rsLowerRange='a-z\\xdf-\\xf6\\xf8-\\xff',rsMathOpRange='\\xac\\xb1\\xd7\\xf7',rsNonCharRange='\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',rsPunctuationRange='\\u2000-\\u206f',rsSpaceRange=' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',rsUpperRange='A-Z\\xc0-\\xd6\\xd8-\\xde',rsVarRange='\\ufe0e\\ufe0f',rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange;/** Used to compose unicode capture groups. */var rsApos="['\u2019]",rsAstral='['+rsAstralRange+']',rsBreak='['+rsBreakRange+']',rsCombo='['+rsComboRange+']',rsDigits='\\d+',rsDingbat='['+rsDingbatRange+']',rsLower='['+rsLowerRange+']',rsMisc='[^'+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+']',rsFitz='\\ud83c[\\udffb-\\udfff]',rsModifier='(?:'+rsCombo+'|'+rsFitz+')',rsNonAstral='[^'+rsAstralRange+']',rsRegional='(?:\\ud83c[\\udde6-\\uddff]){2}',rsSurrPair='[\\ud800-\\udbff][\\udc00-\\udfff]',rsUpper='['+rsUpperRange+']',rsZWJ='\\u200d';/** Used to compose unicode regexes. */var rsMiscLower='(?:'+rsLower+'|'+rsMisc+')',rsMiscUpper='(?:'+rsUpper+'|'+rsMisc+')',rsOptContrLower='(?:'+rsApos+'(?:d|ll|m|re|s|t|ve))?',rsOptContrUpper='(?:'+rsApos+'(?:D|LL|M|RE|S|T|VE))?',reOptMod=rsModifier+'?',rsOptVar='['+rsVarRange+']?',rsOptJoin='(?:'+rsZWJ+'(?:'+[rsNonAstral,rsRegional,rsSurrPair].join('|')+')'+rsOptVar+reOptMod+')*',rsOrdLower='\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',rsOrdUpper='\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji='(?:'+[rsDingbat,rsRegional,rsSurrPair].join('|')+')'+rsSeq,rsSymbol='(?:'+[rsNonAstral+rsCombo+'?',rsCombo,rsRegional,rsSurrPair,rsAstral].join('|')+')';/** Used to match apostrophes. */var reApos=RegExp(rsApos,'g');/**
3 years ago
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
3 years ago
*/var reComboMark=RegExp(rsCombo,'g');/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */var reUnicode=RegExp(rsFitz+'(?='+rsFitz+')|'+rsSymbol+rsSeq,'g');/** Used to match complex or compound words. */var reUnicodeWord=RegExp([rsUpper+'?'+rsLower+'+'+rsOptContrLower+'(?='+[rsBreak,rsUpper,'$'].join('|')+')',rsMiscUpper+'+'+rsOptContrUpper+'(?='+[rsBreak,rsUpper+rsMiscLower,'$'].join('|')+')',rsUpper+'?'+rsMiscLower+'+'+rsOptContrLower,rsUpper+'+'+rsOptContrUpper,rsOrdUpper,rsOrdLower,rsDigits,rsEmoji].join('|'),'g');/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */var reHasUnicode=RegExp('['+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+']');/** Used to detect strings that need a more robust regexp to match words. */var reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;/** Used to assign default `context` object properties. */var contextProps=['Array','Buffer','DataView','Date','Error','Float32Array','Float64Array','Function','Int8Array','Int16Array','Int32Array','Map','Math','Object','Promise','RegExp','Set','String','Symbol','TypeError','Uint8Array','Uint8ClampedArray','Uint16Array','Uint32Array','WeakMap','_','clearTimeout','isFinite','parseInt','setTimeout'];/** Used to make template sourceURLs easier to identify. */var templateCounter=-1;/** Used to identify `toStringTag` values of typed arrays. */var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;/** Used to identify `toStringTag` values supported by `_.clone`. */var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=false;/** Used to map Latin Unicode letters to basic Latin letters. */var deburredLetters={// Latin-1 Supplement block.
'\xc0':'A','\xc1':'A','\xc2':'A','\xc3':'A','\xc4':'A','\xc5':'A','\xe0':'a','\xe1':'a','\xe2':'a','\xe3':'a','\xe4':'a','\xe5':'a','\xc7':'C','\xe7':'c','\xd0':'D','\xf0':'d','\xc8':'E','\xc9':'E','\xca':'E','\xcb':'E','\xe8':'e','\xe9':'e','\xea':'e','\xeb':'e','\xcc':'I','\xcd':'I','\xce':'I','\xcf':'I','\xec':'i','\xed':'i','\xee':'i','\xef':'i','\xd1':'N','\xf1':'n','\xd2':'O','\xd3':'O','\xd4':'O','\xd5':'O','\xd6':'O','\xd8':'O','\xf2':'o','\xf3':'o','\xf4':'o','\xf5':'o','\xf6':'o','\xf8':'o','\xd9':'U','\xda':'U','\xdb':'U','\xdc':'U','\xf9':'u','\xfa':'u','\xfb':'u','\xfc':'u','\xdd':'Y','\xfd':'y','\xff':'y','\xc6':'Ae','\xe6':'ae','\xde':'Th','\xfe':'th','\xdf':'ss',// Latin Extended-A block.
'\u0100':'A','\u0102':'A','\u0104':'A','\u0101':'a','\u0103':'a','\u0105':'a','\u0106':'C','\u0108':'C','\u010a':'C','\u010c':'C','\u0107':'c','\u0109':'c','\u010b':'c','\u010d':'c','\u010e':'D','\u0110':'D','\u010f':'d','\u0111':'d','\u0112':'E','\u0114':'E','\u0116':'E','\u0118':'E','\u011a':'E','\u0113':'e','\u0115':'e','\u0117':'e','\u0119':'e','\u011b':'e','\u011c':'G','\u011e':'G','\u0120':'G','\u0122':'G','\u011d':'g','\u011f':'g','\u0121':'g','\u0123':'g','\u0124':'H','\u0126':'H','\u0125':'h','\u0127':'h','\u0128':'I','\u012a':'I','\u012c':'I','\u012e':'I','\u0130':'I','\u0129':'i','\u012b':'i','\u012d':'i','\u012f':'i','\u0131':'i','\u0134':'J','\u0135':'j','\u0136':'K','\u0137':'k','\u0138':'k','\u0139':'L','\u013b':'L','\u013d':'L','\u013f':'L','\u0141':'L','\u013a':'l','\u013c':'l','\u013e':'l','\u0140':'l','\u0142':'l','\u0143':'N','\u0145':'N','\u0147':'N','\u014a':'N','\u0144':'n','\u0146':'n','\u0148':'n','\u014b':'n','\u014c':'O','\u014e':'O','\u0150':'O','\u014d':'o','\u014f':'o','\u0151':'o','\u0154':'R','\u0156':'R','\u0158':'R','\u0155':'r','\u0157':'r','\u0159':'r','\u015a':'S','\u015c':'S','\u015e':'S','\u0160':'S','\u015b':'s','\u015d':'s','\u015f':'s','\u0161':'s','\u0162':'T','\u0164':'T','\u0166':'T','\u0163':'t','\u0165':'t','\u0167':'t','\u0168':'U','\u016a':'U','\u016c':'U','\u016e':'U','\u0170':'U','\u0172':'U','\u0169':'u','\u016b':'u','\u016d':'u','\u016f':'u','\u0171':'u','\u0173':'u','\u0174':'W','\u0175':'w','\u0176':'Y','\u0177':'y','\u0178':'Y','\u0179':'Z','\u017b':'Z','\u017d':'Z','\u017a':'z','\u017c':'z','\u017e':'z','\u0132':'IJ','\u0133':'ij','\u0152':'Oe','\u0153':'oe','\u0149':"'n",'\u017f':'s'};/** Used to map characters to HTML entities. */var htmlEscapes={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};/** Used to map HTML entities to characters. */var htmlUnescapes={'&amp;':'&','&lt;':'<','&gt;':'>','&quot;':'"','&#39;':"'"};/** Used to escape characters for inclusion in compiled string literals. */var stringEscapes={'\\':'\\',"'":"'",'\n':'n','\r':'r','\u2028':'u2028','\u2029':'u2029'};/** Built-in method references without a dependency on `root`. */var freeParseFloat=parseFloat,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')();/** Detect free variable `exports`. */var freeExports=exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&'object'=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Detect free variable `process` from Node.js. */var freeProcess=moduleExports&&freeGlobal.process;/** Used to access faster Node.js helpers. */var nodeUtil=function(){try{// Use `util.types` for Node.js 10+.
var types=freeModule&&freeModule.require&&freeModule.require('util').types;if(types){return types;}// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}();/* Node.js helper references. */var nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;/*--------------------------------------------------------------------------*/ /**
3 years ago
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
3 years ago
*/function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2]);}return func.apply(thisArg,args);}/**
3 years ago
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
3 years ago
*/function arrayAggregator(array,setter,iteratee,accumulator){var index=-1,length=array==null?0:array.length;while(++index<length){var value=array[index];setter(accumulator,value,iteratee(value),array);}return accumulator;}/**
3 years ago
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
3 years ago
*/function arrayEach(array,iteratee){var index=-1,length=array==null?0:array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break;}}return array;}/**
3 years ago
* A specialized version of `_.forEachRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
3 years ago
*/function arrayEachRight(array,iteratee){var length=array==null?0:array.length;while(length--){if(iteratee(array[length],length,array)===false){break;}}return array;}/**
3 years ago
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
3 years ago
*/function arrayEvery(array,predicate){var index=-1,length=array==null?0:array.length;while(++index<length){if(!predicate(array[index],index,array)){return false;}}return true;}/**
3 years ago
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
3 years ago
*/function arrayFilter(array,predicate){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[resIndex++]=value;}}return result;}/**
3 years ago
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
3 years ago
*/function arrayIncludes(array,value){var length=array==null?0:array.length;return !!length&&baseIndexOf(array,value,0)>-1;}/**
3 years ago
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
3 years ago
*/function arrayIncludesWith(array,value,comparator){var index=-1,length=array==null?0:array.length;while(++index<length){if(comparator(value,array[index])){return true;}}return false;}/**
3 years ago
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
3 years ago
*/function arrayMap(array,iteratee){var index=-1,length=array==null?0:array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array);}return result;}/**
3 years ago
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
3 years ago
*/function arrayPush(array,values){var index=-1,length=values.length,offset=array.length;while(++index<length){array[offset+index]=values[index];}return array;}/**
3 years ago
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
3 years ago
*/function arrayReduce(array,iteratee,accumulator,initAccum){var index=-1,length=array==null?0:array.length;if(initAccum&&length){accumulator=array[++index];}while(++index<length){accumulator=iteratee(accumulator,array[index],index,array);}return accumulator;}/**
3 years ago
* A specialized version of `_.reduceRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
3 years ago
*/function arrayReduceRight(array,iteratee,accumulator,initAccum){var length=array==null?0:array.length;if(initAccum&&length){accumulator=array[--length];}while(length--){accumulator=iteratee(accumulator,array[length],length,array);}return accumulator;}/**
3 years ago
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
3 years ago
*/function arraySome(array,predicate){var index=-1,length=array==null?0:array.length;while(++index<length){if(predicate(array[index],index,array)){return true;}}return false;}/**
3 years ago
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
3 years ago
*/var asciiSize=baseProperty('length');/**
3 years ago
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
3 years ago
*/function asciiToArray(string){return string.split('');}/**
3 years ago
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
3 years ago
*/function asciiWords(string){return string.match(reAsciiWord)||[];}/**
3 years ago
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
3 years ago
*/function baseFindKey(collection,predicate,eachFunc){var result;eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection)){result=key;return false;}});return result;}/**
3 years ago
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
3 years ago
*/function baseFindIndex(array,predicate,fromIndex,fromRight){var length=array.length,index=fromIndex+(fromRight?1:-1);while(fromRight?index--:++index<length){if(predicate(array[index],index,array)){return index;}}return -1;}/**
3 years ago
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
3 years ago
*/function baseIndexOf(array,value,fromIndex){return value===value?strictIndexOf(array,value,fromIndex):baseFindIndex(array,baseIsNaN,fromIndex);}/**
3 years ago
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
3 years ago
*/function baseIndexOfWith(array,value,fromIndex,comparator){var index=fromIndex-1,length=array.length;while(++index<length){if(comparator(array[index],value)){return index;}}return -1;}/**
3 years ago
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
3 years ago
*/function baseIsNaN(value){return value!==value;}/**
3 years ago
* The base implementation of `_.mean` and `_.meanBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the mean.
3 years ago
*/function baseMean(array,iteratee){var length=array==null?0:array.length;return length?baseSum(array,iteratee)/length:NAN;}/**
3 years ago
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
3 years ago
*/function baseProperty(key){return function(object){return object==null?undefined$1:object[key];};}/**
3 years ago
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
3 years ago
*/function basePropertyOf(object){return function(key){return object==null?undefined$1:object[key];};}/**
3 years ago
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
3 years ago
*/function baseReduce(collection,iteratee,accumulator,initAccum,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initAccum?(initAccum=false,value):iteratee(accumulator,value,index,collection);});return accumulator;}/**
3 years ago
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
3 years ago
*/function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value;}return array;}/**
3 years ago
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
3 years ago
*/function baseSum(array,iteratee){var result,index=-1,length=array.length;while(++index<length){var current=iteratee(array[index]);if(current!==undefined$1){result=result===undefined$1?current:result+current;}}return result;}/**
3 years ago
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
3 years ago
*/function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index);}return result;}/**
3 years ago
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the key-value pairs.
3 years ago
*/function baseToPairs(object,props){return arrayMap(props,function(key){return [key,object[key]];});}/**
3 years ago
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
3 years ago
*/function baseTrim(string){return string?string.slice(0,trimmedEndIndex(string)+1).replace(reTrimStart,''):string;}/**
3 years ago
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
3 years ago
*/function baseUnary(func){return function(value){return func(value);};}/**
3 years ago
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
3 years ago
*/function baseValues(object,props){return arrayMap(props,function(key){return object[key];});}/**
3 years ago
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3 years ago
*/function cacheHas(cache,key){return cache.has(key);}/**
3 years ago
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
3 years ago
*/function charsStartIndex(strSymbols,chrSymbols){var index=-1,length=strSymbols.length;while(++index<length&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index;}/**
3 years ago
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
3 years ago
*/function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index;}/**
3 years ago
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
3 years ago
*/function countHolders(array,placeholder){var length=array.length,result=0;while(length--){if(array[length]===placeholder){++result;}}return result;}/**
3 years ago
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
3 years ago
*/var deburrLetter=basePropertyOf(deburredLetters);/**
3 years ago
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
3 years ago
*/var escapeHtmlChar=basePropertyOf(htmlEscapes);/**
3 years ago
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
3 years ago
*/function escapeStringChar(chr){return '\\'+stringEscapes[chr];}/**
3 years ago
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
3 years ago
*/function getValue(object,key){return object==null?undefined$1:object[key];}/**
3 years ago
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
3 years ago
*/function hasUnicode(string){return reHasUnicode.test(string);}/**
3 years ago
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
3 years ago
*/function hasUnicodeWord(string){return reHasUnicodeWord.test(string);}/**
3 years ago
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
3 years ago
*/function iteratorToArray(iterator){var data,result=[];while(!(data=iterator.next()).done){result.push(data.value);}return result;}/**
3 years ago
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
3 years ago
*/function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value];});return result;}/**
3 years ago
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
3 years ago
*/function overArg(func,transform){return function(arg){return func(transform(arg));};}/**
3 years ago
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
3 years ago
*/function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(value===placeholder||value===PLACEHOLDER){array[index]=PLACEHOLDER;result[resIndex++]=index;}}return result;}/**
3 years ago
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
3 years ago
*/function setToArray(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=value;});return result;}/**
3 years ago
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
3 years ago
*/function setToPairs(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=[value,value];});return result;}/**
3 years ago
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
3 years ago
*/function strictIndexOf(array,value,fromIndex){var index=fromIndex-1,length=array.length;while(++index<length){if(array[index]===value){return index;}}return -1;}/**
3 years ago
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
3 years ago
*/function strictLastIndexOf(array,value,fromIndex){var index=fromIndex+1;while(index--){if(array[index]===value){return index;}}return index;}/**
3 years ago
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
3 years ago
*/function stringSize(string){return hasUnicode(string)?unicodeSize(string):asciiSize(string);}/**
3 years ago
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
3 years ago
*/function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string);}/**
3 years ago
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
3 years ago
*/function trimmedEndIndex(string){var index=string.length;while(index--&&reWhitespace.test(string.charAt(index))){}return index;}/**
3 years ago
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
3 years ago
*/var unescapeHtmlChar=basePropertyOf(htmlUnescapes);/**
3 years ago
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
3 years ago
*/function unicodeSize(string){var result=reUnicode.lastIndex=0;while(reUnicode.test(string)){++result;}return result;}/**
3 years ago
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
3 years ago
*/function unicodeToArray(string){return string.match(reUnicode)||[];}/**
3 years ago
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
3 years ago
*/function unicodeWords(string){return string.match(reUnicodeWord)||[];}/*--------------------------------------------------------------------------*/ /**
3 years ago
* Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
3 years ago
*/var runInContext=function runInContext(context){context=context==null?root:_.defaults(root.Object(),context,_.pick(root,contextProps));/** Built-in constructor references. */var Array=context.Array,Date=context.Date,Error=context.Error,Function=context.Function,Math=context.Math,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;/** Used for built-in method references. */var arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype;/** Used to detect overreaching core-js shims. */var coreJsData=context['__core-js_shared__'];/** Used to resolve the decompiled source of functions. */var funcToString=funcProto.toString;/** Used to check objects for own properties. */var hasOwnProperty=objectProto.hasOwnProperty;/** Used to generate unique IDs. */var idCounter=0;/** Used to detect methods masquerading as native. */var maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||'');return uid?'Symbol(src)_1.'+uid:'';}();/**
3 years ago
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
3 years ago
*/var nativeObjectToString=objectProto.toString;/** Used to infer the `Object` constructor. */var objectCtorString=funcToString.call(Object);/** Used to restore the original `_` reference in `_.noConflict`. */var oldDash=root._;/** Used to detect if a method is native. */var reIsNative=RegExp('^'+funcToString.call(hasOwnProperty).replace(reRegExpChar,'\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$');/** Built-in value references. */var Buffer=moduleExports?context.Buffer:undefined$1,Symbol=context.Symbol,Uint8Array=context.Uint8Array,allocUnsafe=Buffer?Buffer.allocUnsafe:undefined$1,getPrototype=overArg(Object.getPrototypeOf,Object),objectCreate=Object.create,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:undefined$1,symIterator=Symbol?Symbol.iterator:undefined$1,symToStringTag=Symbol?Symbol.toStringTag:undefined$1;var defineProperty=function(){try{var func=getNative(Object,'defineProperty');func({},'',{});return func;}catch(e){}}();/** Mocked built-ins. */var ctxClearTimeout=context.clearTimeout!==root.clearTimeout&&context.clearTimeout,ctxNow=Date&&Date.now!==root.Date.now&&Date.now,ctxSetTimeout=context.setTimeout!==root.setTimeout&&context.setTimeout;/* Built-in method references for those with the same name as other `lodash` methods. */var nativeCeil=Math.ceil,nativeFloor=Math.floor,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:undefined$1,nativeIsFinite=context.isFinite,nativeJoin=arrayProto.join,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,nativeMin=Math.min,nativeNow=Date.now,nativeParseInt=context.parseInt,nativeRandom=Math.random,nativeReverse=arrayProto.reverse;/* Built-in method references that are verified to be native. */var DataView=getNative(context,'DataView'),Map=getNative(context,'Map'),Promise=getNative(context,'Promise'),Set=getNative(context,'Set'),WeakMap=getNative(context,'WeakMap'),nativeCreate=getNative(Object,'create');/** Used to store function metadata. */var metaMap=WeakMap&&new WeakMap();/** Used to lookup unminified function names. */var realNames={};/** Used to detect maps, sets, and weakmaps. */var dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap);/** Used to convert symbols to primitives and strings. */var symbolProto=Symbol?Symbol.prototype:undefined$1,symbolValueOf=symbolProto?symbolProto.valueOf:undefined$1,symbolToString=symbolProto?symbolProto.toString:undefined$1;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
3 years ago
*/function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper){return value;}if(hasOwnProperty.call(value,'__wrapped__')){return wrapperClone(value);}}return new LodashWrapper(value);}/**
3 years ago
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
3 years ago
*/var baseCreate=function(){function object(){}return function(proto){if(!isObject(proto)){return {};}if(objectCreate){return objectCreate(proto);}object.prototype=proto;var result=new object();object.prototype=undefined$1;return result;};}();/**
3 years ago
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
3 years ago
*/function baseLodash(){// No operation performed.
}/**
3 years ago
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
3 years ago
*/function LodashWrapper(value,chainAll){this.__wrapped__=value;this.__actions__=[];this.__chain__=!!chainAll;this.__index__=0;this.__values__=undefined$1;}/**
3 years ago
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
3 years ago
*/lodash.templateSettings={/**
3 years ago
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
3 years ago
*/'escape':reEscape,/**
3 years ago
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
3 years ago
*/'evaluate':reEvaluate,/**
3 years ago
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
3 years ago
*/'interpolate':reInterpolate,/**
3 years ago
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
3 years ago
*/'variable':'',/**
3 years ago
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
3 years ago
*/'imports':{/**
3 years ago
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
3 years ago
*/'_':lodash}};// Ensure wrappers are instances of `baseLodash`.
lodash.prototype=baseLodash.prototype;lodash.prototype.constructor=lodash;LodashWrapper.prototype=baseCreate(baseLodash.prototype);LodashWrapper.prototype.constructor=LodashWrapper;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
3 years ago
*/function LazyWrapper(value){this.__wrapped__=value;this.__actions__=[];this.__dir__=1;this.__filtered__=false;this.__iteratees__=[];this.__takeCount__=MAX_ARRAY_LENGTH;this.__views__=[];}/**
3 years ago
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
3 years ago
*/function lazyClone(){var result=new LazyWrapper(this.__wrapped__);result.__actions__=copyArray(this.__actions__);result.__dir__=this.__dir__;result.__filtered__=this.__filtered__;result.__iteratees__=copyArray(this.__iteratees__);result.__takeCount__=this.__takeCount__;result.__views__=copyArray(this.__views__);return result;}/**
3 years ago
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
3 years ago
*/function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1;result.__filtered__=true;}else {result=this.clone();result.__dir__*=-1;}return result;}/**
3 years ago
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
3 years ago
*/function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||!isRight&&arrLength==length&&takeCount==length){return baseWrapperValue(array,this.__actions__);}var result=[];outer:while(length--&&resIndex<takeCount){index+=dir;var iterIndex=-1,value=array[index];while(++iterIndex<iterLength){var data=iteratees[iterIndex],iteratee=data.iteratee,type=data.type,computed=iteratee(value);if(type==LAZY_MAP_FLAG){value=computed;}else if(!computed){if(type==LAZY_FILTER_FLAG){continue outer;}else {break outer;}}}result[resIndex++]=value;}return result;}// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype=baseCreate(baseLodash.prototype);LazyWrapper.prototype.constructor=LazyWrapper;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
3 years ago
*/function Hash(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}/**
3 years ago
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
3 years ago
*/function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{};this.size=0;}/**
3 years ago
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
3 years ago
*/function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];this.size-=result?1:0;return result;}/**
3 years ago
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
3 years ago
*/function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?undefined$1:result;}return hasOwnProperty.call(data,key)?data[key]:undefined$1;}/**
3 years ago
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3 years ago
*/function hashHas(key){var data=this.__data__;return nativeCreate?data[key]!==undefined$1:hasOwnProperty.call(data,key);}/**
3 years ago
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
3 years ago
*/function hashSet(key,value){var data=this.__data__;this.size+=this.has(key)?0:1;data[key]=nativeCreate&&value===undefined$1?HASH_UNDEFINED:value;return this;}// Add methods to `Hash`.
Hash.prototype.clear=hashClear;Hash.prototype['delete']=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
3 years ago
*/function ListCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}/**
3 years ago
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
3 years ago
*/function listCacheClear(){this.__data__=[];this.size=0;}/**
3 years ago
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
3 years ago
*/function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){return false;}var lastIndex=data.length-1;if(index==lastIndex){data.pop();}else {splice.call(data,index,1);}--this.size;return true;}/**
3 years ago
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
3 years ago
*/function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?undefined$1:data[index][1];}/**
3 years ago
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3 years ago
*/function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1;}/**
3 years ago
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
3 years ago
*/function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value]);}else {data[index][1]=value;}return this;}// Add methods to `ListCache`.
ListCache.prototype.clear=listCacheClear;ListCache.prototype['delete']=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
3 years ago
*/function MapCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}/**
3 years ago
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
3 years ago
*/function mapCacheClear(){this.size=0;this.__data__={'hash':new Hash(),'map':new(Map||ListCache)(),'string':new Hash()};}/**
3 years ago
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
3 years ago
*/function mapCacheDelete(key){var result=getMapData(this,key)['delete'](key);this.size-=result?1:0;return result;}/**
3 years ago
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
3 years ago
*/function mapCacheGet(key){return getMapData(this,key).get(key);}/**
3 years ago
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3 years ago
*/function mapCacheHas(key){return getMapData(this,key).has(key);}/**
3 years ago
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
3 years ago
*/function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;data.set(key,value);this.size+=data.size==size?0:1;return this;}// Add methods to `MapCache`.
MapCache.prototype.clear=mapCacheClear;MapCache.prototype['delete']=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;/*------------------------------------------------------------------------*/ /**
3 years ago
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
3 years ago
*/function SetCache(values){var index=-1,length=values==null?0:values.length;this.__data__=new MapCache();while(++index<length){this.add(values[index]);}}/**
3 years ago
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
3 years ago
*/function setCacheAdd(value){this.__data__.set(value,HASH_UNDEFINED);return this;}/**
3 years ago
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
3 years ago
*/function setCacheHas(value){return this.__data__.has(value);}// Add methods to `SetCache`.
SetCache.prototype.add=SetCache.prototype.push=setCacheAdd;SetCache.prototype.has=setCacheHas;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
3 years ago
*/function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size;}/**
3 years ago
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
3 years ago
*/function stackClear(){this.__data__=new ListCache();this.size=0;}/**
3 years ago
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
3 years ago
*/function stackDelete(key){var data=this.__data__,result=data['delete'](key);this.size=data.size;return result;}/**
3 years ago
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
3 years ago
*/function stackGet(key){return this.__data__.get(key);}/**
3 years ago
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3 years ago
*/function stackHas(key){return this.__data__.has(key);}/**
3 years ago
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
3 years ago
*/function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length<LARGE_ARRAY_SIZE-1){pairs.push([key,value]);this.size=++data.size;return this;}data=this.__data__=new MapCache(pairs);}data.set(key,value);this.size=data.size;return this;}// Add methods to `Stack`.
Stack.prototype.clear=stackClear;Stack.prototype['delete']=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
3 years ago
*/function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value){if((inherited||hasOwnProperty.call(value,key))&&!(skipIndexes&&(// Safari 9 has enumerable `arguments.length` in strict mode.
key=='length'||// Node.js 0.10 has enumerable non-index properties on buffers.
isBuff&&(key=='offset'||key=='parent')||// PhantomJS 2 has enumerable non-index properties on typed arrays.
isType&&(key=='buffer'||key=='byteLength'||key=='byteOffset')||// Skip index properties.
isIndex(key,length)))){result.push(key);}}return result;}/**
3 years ago
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
3 years ago
*/function arraySample(array){var length=array.length;return length?array[baseRandom(0,length-1)]:undefined$1;}/**
3 years ago
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
3 years ago
*/function arraySampleSize(array,n){return shuffleSelf(copyArray(array),baseClamp(n,0,array.length));}/**
3 years ago
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
3 years ago
*/function arrayShuffle(array){return shuffleSelf(copyArray(array));}/**
3 years ago
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
3 years ago
*/function assignMergeValue(object,key,value){if(value!==undefined$1&&!eq(object[key],value)||value===undefined$1&&!(key in object)){baseAssignValue(object,key,value);}}/**
3 years ago
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
3 years ago
*/function assignValue(object,key,value){var objValue=object[key];if(!(hasOwnProperty.call(object,key)&&eq(objValue,value))||value===undefined$1&&!(key in object)){baseAssignValue(object,key,value);}}/**
3 years ago
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
3 years ago
*/function assocIndexOf(array,key){var length=array.length;while(length--){if(eq(array[length][0],key)){return length;}}return -1;}/**
3 years ago
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
3 years ago
*/function baseAggregator(collection,setter,iteratee,accumulator){baseEach(collection,function(value,key,collection){setter(accumulator,value,iteratee(value),collection);});return accumulator;}/**
3 years ago
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
3 years ago
*/function baseAssign(object,source){return object&&copyObject(source,keys(source),object);}/**
3 years ago
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
3 years ago
*/function baseAssignIn(object,source){return object&&copyObject(source,keysIn(source),object);}/**
3 years ago
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
3 years ago
*/function baseAssignValue(object,key,value){if(key=='__proto__'&&defineProperty){defineProperty(object,key,{'configurable':true,'enumerable':true,'value':value,'writable':true});}else {object[key]=value;}}/**
3 years ago
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
3 years ago
*/function baseAt(object,paths){var index=-1,length=paths.length,result=Array(length),skip=object==null;while(++index<length){result[index]=skip?undefined$1:get(object,paths[index]);}return result;}/**
3 years ago
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
3 years ago
*/function baseClamp(number,lower,upper){if(number===number){if(upper!==undefined$1){number=number<=upper?number:upper;}if(lower!==undefined$1){number=number>=lower?number:lower;}}return number;}/**
3 years ago
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
3 years ago
*/function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,isFull=bitmask&CLONE_SYMBOLS_FLAG;if(customizer){result=object?customizer(value,key,object,stack):customizer(value);}if(result!==undefined$1){return result;}if(!isObject(value)){return value;}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result);}}else {var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value)){return cloneBuffer(value,isDeep);}if(tag==objectTag||tag==argsTag||isFunc&&!object){result=isFlat||isFunc?{}:initCloneObject(value);if(!isDeep){return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value));}}else {if(!cloneableTags[tag]){return object?value:{};}result=initCloneByTag(value,tag,isDeep);}}// Check for circular references and return its corresponding clone.
stack||(stack=new Stack());var stacked=stack.get(value);if(stacked){return stacked;}stack.set(value,result);if(isSet(value)){value.forEach(function(subValue){result.add(baseClone(subValue,bitmask,customizer,subValue,value,stack));});}else if(isMap(value)){value.forEach(function(subValue,key){result.set(key,baseClone(subValue,bitmask,customizer,key,value,stack));});}var keysFunc=isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys;var props=isArr?undefined$1:keysFunc(value);arrayEach(props||value,function(subValue,key){if(props){key=subValue;subValue=value[key];}// Recursively populate clone (susceptible to call stack limits).
assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack));});return result;}/**
3 years ago
* The base implementation of `_.conforms` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
3 years ago
*/function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props);};}/**
3 years ago
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
3 years ago
*/function baseConformsTo(object,source,props){var length=props.length;if(object==null){return !length;}object=Object(object);while(length--){var key=props[length],predicate=source[key],value=object[key];if(value===undefined$1&&!(key in object)||!predicate(value)){return false;}}return true;}/**
3 years ago
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
3 years ago
*/function baseDelay(func,wait,args){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return setTimeout(function(){func.apply(undefined$1,args);},wait);}/**
3 years ago
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
3 years ago
*/function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=true,length=array.length,result=[],valuesLength=values.length;if(!length){return result;}if(iteratee){values=arrayMap(values,baseUnary(iteratee));}if(comparator){includes=arrayIncludesWith;isCommon=false;}else if(values.length>=LARGE_ARRAY_SIZE){includes=cacheHas;isCommon=false;values=new SetCache(values);}outer:while(++index<length){var value=array[index],computed=iteratee==null?value:iteratee(value);value=comparator||value!==0?value:0;if(isCommon&&computed===computed){var valuesIndex=valuesLength;while(valuesIndex--){if(values[valuesIndex]===computed){continue outer;}}result.push(value);}else if(!includes(values,computed,comparator)){result.push(value);}}return result;}/**
3 years ago
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
3 years ago
*/var baseEach=createBaseEach(baseForOwn);/**
3 years ago
* The base implementation of `_.forEachRight` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
3 years ago
*/var baseEachRight=createBaseEach(baseForOwnRight,true);/**
3 years ago
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
3 years ago
*/function baseEvery(collection,predicate){var result=true;baseEach(collection,function(value,index,collection){result=!!predicate(value,index,collection);return result;});return result;}/**
3 years ago
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
3 years ago
*/function baseExtremum(array,iteratee,comparator){var index=-1,length=array.length;while(++index<length){var value=array[index],current=iteratee(value);if(current!=null&&(computed===undefined$1?current===current&&!isSymbol(current):comparator(current,computed))){var computed=current,result=value;}}return result;}/**
3 years ago
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
3 years ago
*/function baseFill(array,value,start,end){var length=array.length;start=toInteger(start);if(start<0){start=-start>length?0:length+start;}end=end===undefined$1||end>length?length:toInteger(end);if(end<0){end+=length;}end=start>end?0:toLength(end);while(start<end){array[start++]=value;}return array;}/**
3 years ago
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
3 years ago
*/function baseFilter(collection,predicate){var result=[];baseEach(collection,function(value,index,collection){if(predicate(value,index,collection)){result.push(value);}});return result;}/**
3 years ago
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
3 years ago
*/function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;predicate||(predicate=isFlattenable);result||(result=[]);while(++index<length){var value=array[index];if(depth>0&&predicate(value)){if(depth>1){// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value,depth-1,predicate,isStrict,result);}else {arrayPush(result,value);}}else if(!isStrict){result[result.length]=value;}}return result;}/**
3 years ago
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
3 years ago
*/var baseFor=createBaseFor();/**
3 years ago
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
3 years ago
*/var baseForRight=createBaseFor(true);/**
3 years ago
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
3 years ago
*/function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}/**
3 years ago
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
3 years ago
*/function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys);}/**
3 years ago
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
3 years ago
*/function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key]);});}/**
3 years ago
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
3 years ago
*/function baseGet(object,path){path=castPath(path,object);var index=0,length=path.length;while(object!=null&&index<length){object=object[toKey(path[index++])];}return index&&index==length?object:undefined$1;}/**
3 years ago
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
3 years ago
*/function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object));}/**
3 years ago
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
3 years ago
*/function baseGetTag(value){if(value==null){return value===undefined$1?undefinedTag:nullTag;}return symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value);}/**
3 years ago
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
3 years ago
*/function baseGt(value,other){return value>other;}/**
3 years ago
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
3 years ago
*/function baseHas(object,key){return object!=null&&hasOwnProperty.call(object,key);}/**
3 years ago
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
3 years ago
*/function baseHasIn(object,key){return object!=null&&key in Object(object);}/**
3 years ago
* The base implementation of `_.inRange` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to check.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
3 years ago
*/function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number<nativeMax(start,end);}/**
3 years ago
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
3 years ago
*/function baseIntersection(arrays,iteratee,comparator){var includes=comparator?arrayIncludesWith:arrayIncludes,length=arrays[0].length,othLength=arrays.length,othIndex=othLength,caches=Array(othLength),maxLength=Infinity,result=[];while(othIndex--){var array=arrays[othIndex];if(othIndex&&iteratee){array=arrayMap(array,baseUnary(iteratee));}maxLength=nativeMin(array.length,maxLength);caches[othIndex]=!comparator&&(iteratee||length>=120&&array.length>=120)?new SetCache(othIndex&&array):undefined$1;}array=arrays[0];var index=-1,seen=caches[0];outer:while(++index<length&&result.length<maxLength){var value=array[index],computed=iteratee?iteratee(value):value;value=comparator||value!==0?value:0;if(!(seen?cacheHas(seen,computed):includes(result,computed,comparator))){othIndex=othLength;while(--othIndex){var cache=caches[othIndex];if(!(cache?cacheHas(cache,computed):includes(arrays[othIndex],computed,comparator))){continue outer;}}if(seen){seen.push(computed);}result.push(value);}}return result;}/**
3 years ago
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
3 years ago
*/function baseInverter(object,setter,iteratee,accumulator){baseForOwn(object,function(value,key,object){setter(accumulator,iteratee(value),key,object);});return accumulator;}/**
3 years ago
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
3 years ago
*/function baseInvoke(object,path,args){path=castPath(path,object);object=parent(object,path);var func=object==null?object:object[toKey(last(path))];return func==null?undefined$1:apply(func,object,args);}/**
3 years ago
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
3 years ago
*/function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag;}/**
3 years ago
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
3 years ago
*/function baseIsArrayBuffer(value){return isObjectLike(value)&&baseGetTag(value)==arrayBufferTag;}/**
3 years ago
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
3 years ago
*/function baseIsDate(value){return isObjectLike(value)&&baseGetTag(value)==dateTag;}/**
3 years ago
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
3 years ago
*/function baseIsEqual(value,other,bitmask,customizer,stack){if(value===other){return true;}if(value==null||other==null||!isObjectLike(value)&&!isObjectLike(other)){return value!==value&&other!==other;}return baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack);}/**
3 years ago
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
3 years ago
*/function baseIsEqualDeep(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=objIsArr?arrayTag:getTag(object),othTag=othIsArr?arrayTag:getTag(other);objTag=objTag==argsTag?objectTag:objTag;othTag=othTag==argsTag?objectTag:othTag;var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer(object)){if(!isBuffer(other)){return false;}objIsArr=true;objIsObj=false;}if(isSameTag&&!objIsObj){stack||(stack=new Stack());return objIsArr||isTypedArray(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack);}if(!(bitmask&COMPARE_PARTIAL_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,'__wrapped__'),othIsWrapped=othIsObj&&hasOwnProperty.call(other,'__wrapped__');if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;stack||(stack=new Stack());return equalFunc(objUnwrapped,othUnwrapped,bitmask,customizer,stack);}}if(!isSameTag){return false;}stack||(stack=new Stack());return equalObjects(object,other,bitmask,customizer,equalFunc,stack);}/**
3 years ago
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
3 years ago
*/function baseIsMap(value){return isObjectLike(value)&&getTag(value)==mapTag;}/**
3 years ago
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
3 years ago
*/function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(object==null){return !length;}object=Object(object);while(index--){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object)){return false;}}while(++index<length){data=matchData[index];var key=data[0],objValue=object[key],srcValue=data[1];if(noCustomizer&&data[2]){if(objValue===undefined$1&&!(key in object)){return false;}}else {var stack=new Stack();if(customizer){var result=customizer(objValue,srcValue,key,object,source,stack);}if(!(result===undefined$1?baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG,customizer,stack):result)){return false;}}}return true;}/**
3 years ago
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
3 years ago
*/function baseIsNative(value){if(!isObject(value)||isMasked(value)){return false;}var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value));}/**
3 years ago
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
3 years ago
*/function baseIsRegExp(value){return isObjectLike(value)&&baseGetTag(value)==regexpTag;}/**
3 years ago
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
3 years ago
*/function baseIsSet(value){return isObjectLike(value)&&getTag(value)==setTag;}/**
3 years ago
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
3 years ago
*/function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)];}/**
3 years ago
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
3 years ago
*/function baseIteratee(value){// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if(typeof value=='function'){return value;}if(value==null){return identity;}if(typeof value=='object'){return isArray(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value);}return property(value);}/**
3 years ago
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
3 years ago
*/function baseKeys(object){if(!isPrototype(object)){return nativeKeys(object);}var result=[];for(var key in Object(object)){if(hasOwnProperty.call(object,key)&&key!='constructor'){result.push(key);}}return result;}/**
3 years ago
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
3 years ago
*/function baseKeysIn(object){if(!isObject(object)){return nativeKeysIn(object);}var isProto=isPrototype(object),result=[];for(var key in object){if(!(key=='constructor'&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key);}}return result;}/**
3 years ago
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
3 years ago
*/function baseLt(value,other){return value<other;}/**
3 years ago
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
3 years ago
*/function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection);});return result;}/**
3 years ago
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
3 years ago
*/function baseMatches(source){var matchData=getMatchData(source);if(matchData.length==1&&matchData[0][2]){return matchesStrictComparable(matchData[0][0],matchData[0][1]);}return function(object){return object===source||baseIsMatch(object,source,matchData);};}/**
3 years ago
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
3 years ago
*/function baseMatchesProperty(path,srcValue){if(isKey(path)&&isStrictComparable(srcValue)){return matchesStrictComparable(toKey(path),srcValue);}return function(object){var objValue=get(object,path);return objValue===undefined$1&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG);};}/**
3 years ago
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
3 years ago
*/function baseMerge(object,source,srcIndex,customizer,stack){if(object===source){return;}baseFor(source,function(srcValue,key){stack||(stack=new Stack());if(isObject(srcValue)){baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);}else {var newValue=customizer?customizer(safeGet(object,key),srcValue,key+'',object,source,stack):undefined$1;if(newValue===undefined$1){newValue=srcValue;}assignMergeValue(object,key,newValue);}},keysIn);}/**
3 years ago
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
3 years ago
*/function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=safeGet(object,key),srcValue=safeGet(source,key),stacked=stack.get(srcValue);if(stacked){assignMergeValue(object,key,stacked);return;}var newValue=customizer?customizer(objValue,srcValue,key+'',object,source,stack):undefined$1;var isCommon=newValue===undefined$1;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue;if(isArr||isBuff||isTyped){if(isArray(objValue)){newValue=objValue;}else if(isArrayLikeObject(objValue)){newValue=copyArray(objValue);}else if(isBuff){isCommon=false;newValue=cloneBuffer(srcValue,true);}else if(isTyped){isCommon=false;newValue=cloneTypedArray(srcValue,true);}else {newValue=[];}}else if(isPlainObject(srcValue)||isArguments(srcValue)){newValue=objValue;if(isArguments(objValue)){newValue=toPlainObject(objValue);}else if(!isObject(objValue)||isFunction(objValue)){newValue=initCloneObject(srcValue);}}else {isCommon=false;}}if(isCommon){// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue,newValue);mergeFunc(newValue,srcValue,srcIndex,customizer,stack);stack['delete'](srcValue);}assignMergeValue(object,key,newValue);}/**
3 years ago
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
3 years ago
*/function baseNth(array,n){var length=array.length;if(!length){return;}n+=n<0?length:0;return isIndex(n,length)?array[n]:undefined$1;}/**
3 years ago
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
3 years ago
*/function baseOrderBy(collection,iteratees,orders){if(iteratees.length){iteratees=arrayMap(iteratees,function(iteratee){if(isArray(iteratee)){return function(value){return baseGet(value,iteratee.length===1?iteratee[0]:iteratee);};}return iteratee;});}else {iteratees=[identity];}var index=-1;iteratees=arrayMap(iteratees,baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value);});return {'criteria':criteria,'index':++index,'value':value};});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders);});}/**
3 years ago
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
3 years ago
*/function basePick(object,paths){return basePickBy(object,paths,function(value,path){return hasIn(object,path);});}/**
3 years ago
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
3 years ago
*/function basePickBy(object,paths,predicate){var index=-1,length=paths.length,result={};while(++index<length){var path=paths[index],value=baseGet(object,path);if(predicate(value,path)){baseSet(result,castPath(path,object),value);}}return result;}/**
3 years ago
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
3 years ago
*/function basePropertyDeep(path){return function(object){return baseGet(object,path);};}/**
3 years ago
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
3 years ago
*/function basePullAll(array,values,iteratee,comparator){var indexOf=comparator?baseIndexOfWith:baseIndexOf,index=-1,length=values.length,seen=array;if(array===values){values=copyArray(values);}if(iteratee){seen=arrayMap(array,baseUnary(iteratee));}while(++index<length){var fromIndex=0,value=values[index],computed=iteratee?iteratee(value):value;while((fromIndex=indexOf(seen,computed,fromIndex,comparator))>-1){if(seen!==array){splice.call(seen,fromIndex,1);}splice.call(array,fromIndex,1);}}return array;}/**
3 years ago
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
3 years ago
*/function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index)){splice.call(array,index,1);}else {baseUnset(array,index);}}}return array;}/**
3 years ago
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
3 years ago
*/function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1));}/**
3 years ago
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
3 years ago
*/function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step;}return result;}/**
3 years ago
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
3 years ago
*/function baseRepeat(string,n){var result='';if(!string||n<1||n>MAX_SAFE_INTEGER){return result;}// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do{if(n%2){result+=string;}n=nativeFloor(n/2);if(n){string+=string;}}while(n);return result;}/**
3 years ago
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
3 years ago
*/function baseRest(func,start){return setToString(overRest(func,start,identity),func+'');}/**
3 years ago
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
3 years ago
*/function baseSample(collection){return arraySample(values(collection));}/**
3 years ago
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
3 years ago
*/function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length));}/**
3 years ago
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
3 years ago
*/function baseSet(object,path,value,customizer){if(!isObject(object)){return object;}path=castPath(path,object);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++index<length){var key=toKey(path[index]),newValue=value;if(key==='__proto__'||key==='constructor'||key==='prototype'){return object;}if(index!=lastIndex){var objValue=nested[key];newValue=customizer?customizer(objValue,key,nested):undefined$1;if(newValue===undefined$1){newValue=isObject(objValue)?objValue:isIndex(path[index+1])?[]:{};}}assignValue(nested,key,newValue);nested=nested[key];}return object;}/**
3 years ago
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
3 years ago
*/var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func;};/**
3 years ago
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
3 years ago
*/var baseSetToString=!defineProperty?identity:function(func,string){return defineProperty(func,'toString',{'configurable':true,'enumerable':false,'value':constant(string),'writable':true});};/**
3 years ago
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
3 years ago
*/function baseShuffle(collection){return shuffleSelf(values(collection));}/**
3 years ago
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
3 years ago
*/function baseSlice(array,start,end){var index=-1,length=array.length;if(start<0){start=-start>length?0:length+start;}end=end>length?length:end;if(end<0){end+=length;}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index<length){result[index]=array[index+start];}return result;}/**
3 years ago
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
3 years ago
*/function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return !result;});return !!result;}/**
3 years ago
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
3 years ago
*/function baseSortedIndex(array,value,retHighest){var low=0,high=array==null?low:array.length;if(typeof value=='number'&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){while(low<high){var mid=low+high>>>1,computed=array[mid];if(computed!==null&&!isSymbol(computed)&&(retHighest?computed<=value:computed<value)){low=mid+1;}else {high=mid;}}return high;}return baseSortedIndexBy(array,value,identity,retHighest);}/**
3 years ago
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
3 years ago
*/function baseSortedIndexBy(array,value,iteratee,retHighest){var low=0,high=array==null?0:array.length;if(high===0){return 0;}value=iteratee(value);var valIsNaN=value!==value,valIsNull=value===null,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined$1;while(low<high){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined$1,othIsNull=computed===null,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN){var setLow=retHighest||othIsReflexive;}else if(valIsUndefined){setLow=othIsReflexive&&(retHighest||othIsDefined);}else if(valIsNull){setLow=othIsReflexive&&othIsDefined&&(retHighest||!othIsNull);}else if(valIsSymbol){setLow=othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol);}else if(othIsNull||othIsSymbol){setLow=false;}else {setLow=retHighest?computed<=value:computed<value;}if(setLow){low=mid+1;}else {high=mid;}}return nativeMin(high,MAX_ARRAY_INDEX);}/**
3 years ago
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
3 years ago
*/function baseSortedUniq(array,iteratee){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;if(!index||!eq(computed,seen)){var seen=computed;result[resIndex++]=value===0?0:value;}}return result;}/**
3 years ago
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
3 years ago
*/function baseToNumber(value){if(typeof value=='number'){return value;}if(isSymbol(value)){return NAN;}return +value;}/**
3 years ago
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
3 years ago
*/function baseToString(value){// Exit early for strings to avoid a performance hit in some environments.
if(typeof value=='string'){return value;}if(isArray(value)){// Recursively convert values (susceptible to call stack limits).
return arrayMap(value,baseToString)+'';}if(isSymbol(value)){return symbolToString?symbolToString.call(value):'';}var result=value+'';return result=='0'&&1/value==-INFINITY?'-0':result;}/**
3 years ago
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
3 years ago
*/function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=true,result=[],seen=result;if(comparator){isCommon=false;includes=arrayIncludesWith;}else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set);}isCommon=false;includes=cacheHas;seen=new SetCache();}else {seen=iteratee?[]:result;}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;value=comparator||value!==0?value:0;if(isCommon&&computed===computed){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer;}}if(iteratee){seen.push(computed);}result.push(value);}else if(!includes(seen,computed,comparator)){if(seen!==result){seen.push(computed);}result.push(value);}}return result;}/**
3 years ago
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
3 years ago
*/function baseUnset(object,path){path=castPath(path,object);object=parent(object,path);return object==null||delete object[toKey(last(path))];}/**
3 years ago
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
3 years ago
*/function baseUpdate(object,path,updater,customizer){return baseSet(object,path,updater(baseGet(object,path)),customizer);}/**
3 years ago
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
3 years ago
*/function baseWhile(array,predicate,isDrop,fromRight){var length=array.length,index=fromRight?length:-1;while((fromRight?index--:++index<length)&&predicate(array[index],index,array)){}return isDrop?baseSlice(array,fromRight?0:index,fromRight?index+1:length):baseSlice(array,fromRight?index+1:0,fromRight?length:index);}/**
3 years ago
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
3 years ago
*/function baseWrapperValue(value,actions){var result=value;if(result instanceof LazyWrapper){result=result.value();}return arrayReduce(actions,function(result,action){return action.func.apply(action.thisArg,arrayPush([result],action.args));},result);}/**
3 years ago
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
3 years ago
*/function baseXor(arrays,iteratee,comparator){var length=arrays.length;if(length<2){return length?baseUniq(arrays[0]):[];}var index=-1,result=Array(length);while(++index<length){var array=arrays[index],othIndex=-1;while(++othIndex<length){if(othIndex!=index){result[index]=baseDifference(result[index]||array,arrays[othIndex],iteratee,comparator);}}}return baseUniq(baseFlatten(result,1),iteratee,comparator);}/**
3 years ago
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
3 years ago
*/function baseZipObject(props,values,assignFunc){var index=-1,length=props.length,valsLength=values.length,result={};while(++index<length){var value=index<valsLength?values[index]:undefined$1;assignFunc(result,props[index],value);}return result;}/**
3 years ago
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
3 years ago
*/function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[];}/**
3 years ago
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
3 years ago
*/function castFunction(value){return typeof value=='function'?value:identity;}/**
3 years ago
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
3 years ago
*/function castPath(value,object){if(isArray(value)){return value;}return isKey(value,object)?[value]:stringToPath(toString(value));}/**
3 years ago
* A `baseRest` alias which can be replaced with `identity` by module
* replacement plugins.
*
* @private
* @type {Function}
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
3 years ago
*/var castRest=baseRest;/**
3 years ago
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
3 years ago
*/function castSlice(array,start,end){var length=array.length;end=end===undefined$1?length:end;return !start&&end>=length?array:baseSlice(array,start,end);}/**
3 years ago
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
3 years ago
*/var clearTimeout=ctxClearTimeout||function(id){return root.clearTimeout(id);};/**
3 years ago
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
3 years ago
*/function cloneBuffer(buffer,isDeep){if(isDeep){return buffer.slice();}var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);buffer.copy(result);return result;}/**
3 years ago
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
3 years ago
*/function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);new Uint8Array(result).set(new Uint8Array(arrayBuffer));return result;}/**
3 years ago
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
3 years ago
*/function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength);}/**
3 years ago
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
3 years ago
*/function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result;}/**
3 years ago
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
3 years ago
*/function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{};}/**
3 years ago
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
3 years ago
*/function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length);}/**
3 years ago
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
3 years ago
*/function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined$1,valIsNull=value===null,valIsReflexive=value===value,valIsSymbol=isSymbol(value);var othIsDefined=other!==undefined$1,othIsNull=other===null,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive){return 1;}if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value<other||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive){return -1;}}return 0;}/**
3 years ago
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
3 years ago
*/function compareMultiple(object,other,orders){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;while(++index<length){var result=compareAscending(objCriteria[index],othCriteria[index]);if(result){if(index>=ordersLength){return result;}var order=orders[index];return result*(order=='desc'?-1:1);}}// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index-other.index;}/**
3 years ago
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
3 years ago
*/function composeArgs(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;while(++leftIndex<leftLength){result[leftIndex]=partials[leftIndex];}while(++argsIndex<holdersLength){if(isUncurried||argsIndex<argsLength){result[holders[argsIndex]]=args[argsIndex];}}while(rangeLength--){result[leftIndex++]=args[argsIndex++];}return result;}/**
3 years ago
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
3 years ago
*/function composeArgsRight(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;while(++argsIndex<rangeLength){result[argsIndex]=args[argsIndex];}var offset=argsIndex;while(++rightIndex<rightLength){result[offset+rightIndex]=partials[rightIndex];}while(++holdersIndex<holdersLength){if(isUncurried||argsIndex<argsLength){result[offset+holders[holdersIndex]]=args[argsIndex++];}}return result;}/**
3 years ago
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
3 years ago
*/function copyArray(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index];}return array;}/**
3 years ago
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
3 years ago
*/function copyObject(source,props,object,customizer){var isNew=!object;object||(object={});var index=-1,length=props.length;while(++index<length){var key=props[index];var newValue=customizer?customizer(object[key],source[key],key,object,source):undefined$1;if(newValue===undefined$1){newValue=source[key];}if(isNew){baseAssignValue(object,key,newValue);}else {assignValue(object,key,newValue);}}return object;}/**
3 years ago
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
3 years ago
*/function copySymbols(source,object){return copyObject(source,getSymbols(source),object);}/**
3 years ago
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
3 years ago
*/function copySymbolsIn(source,object){return copyObject(source,getSymbolsIn(source),object);}/**
3 years ago
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
3 years ago
*/function createAggregator(setter,initializer){return function(collection,iteratee){var func=isArray(collection)?arrayAggregator:baseAggregator,accumulator=initializer?initializer():{};return func(collection,setter,getIteratee(iteratee,2),accumulator);};}/**
3 years ago
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
3 years ago
*/function createAssigner(assigner){return baseRest(function(object,sources){var index=-1,length=sources.length,customizer=length>1?sources[length-1]:undefined$1,guard=length>2?sources[2]:undefined$1;customizer=assigner.length>3&&typeof customizer=='function'?(length--,customizer):undefined$1;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined$1:customizer;length=1;}object=Object(object);while(++index<length){var source=sources[index];if(source){assigner(object,source,index,customizer);}}return object;});}/**
3 years ago
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
3 years ago
*/function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){if(collection==null){return collection;}if(!isArrayLike(collection)){return eachFunc(collection,iteratee);}var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);while(fromRight?index--:++index<length){if(iteratee(iterable[index],index,iterable)===false){break;}}return collection;};}/**
3 years ago
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
3 years ago
*/function createBaseFor(fromRight){return function(object,iteratee,keysFunc){var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;while(length--){var key=props[fromRight?length:++index];if(iteratee(iterable[key],key,iterable)===false){break;}}return object;};}/**
3 years ago
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createBind(func,bitmask,thisArg){var isBind=bitmask&WRAP_BIND_FLAG,Ctor=createCtor(func);function wrapper(){var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return fn.apply(isBind?thisArg:this,arguments);}return wrapper;}/**
3 years ago
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
3 years ago
*/function createCaseFirst(methodName){return function(string){string=toString(string);var strSymbols=hasUnicode(string)?stringToArray(string):undefined$1;var chr=strSymbols?strSymbols[0]:string.charAt(0);var trailing=strSymbols?castSlice(strSymbols,1).join(''):string.slice(1);return chr[methodName]()+trailing;};}/**
3 years ago
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
3 years ago
*/function createCompounder(callback){return function(string){return arrayReduce(words(deburr(string).replace(reApos,'')),callback,'');};}/**
3 years ago
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createCtor(Ctor){return function(){// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args=arguments;switch(args.length){case 0:return new Ctor();case 1:return new Ctor(args[0]);case 2:return new Ctor(args[0],args[1]);case 3:return new Ctor(args[0],args[1],args[2]);case 4:return new Ctor(args[0],args[1],args[2],args[3]);case 5:return new Ctor(args[0],args[1],args[2],args[3],args[4]);case 6:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5]);case 7:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);}var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,args);// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result)?result:thisBinding;};}/**
3 years ago
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createCurry(func,bitmask,arity){var Ctor=createCtor(func);function wrapper(){var length=arguments.length,args=Array(length),index=length,placeholder=getHolder(wrapper);while(index--){args[index]=arguments[index];}var holders=length<3&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);length-=holders.length;if(length<arity){return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined$1,args,holders,undefined$1,undefined$1,arity-length);}var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args);}return wrapper;}/**
3 years ago
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
3 years ago
*/function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection);predicate=function(key){return iteratee(iterable[key],key,iterable);};}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined$1;};}/**
3 years ago
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
3 years ago
*/function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;if(fromRight){funcs.reverse();}while(index--){var func=funcs[index];if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(prereq&&!wrapper&&getFuncName(func)=='wrapper'){var wrapper=new LodashWrapper([],true);}}index=wrapper?index:length;while(++index<length){func=funcs[index];var funcName=getFuncName(func),data=funcName=='wrapper'?getData(func):undefined$1;if(data&&isLaziable(data[0])&&data[1]==(WRAP_ARY_FLAG|WRAP_CURRY_FLAG|WRAP_PARTIAL_FLAG|WRAP_REARG_FLAG)&&!data[4].length&&data[9]==1){wrapper=wrapper[getFuncName(data[0])].apply(wrapper,data[3]);}else {wrapper=func.length==1&&isLaziable(func)?wrapper[funcName]():wrapper.thru(func);}}return function(){var args=arguments,value=args[0];if(wrapper&&args.length==1&&isArray(value)){return wrapper.plant(value).value();}var index=0,result=length?funcs[index].apply(this,args):value;while(++index<length){result=funcs[index].call(this,result);}return result;};});}/**
3 years ago
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createHybrid(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=bitmask&WRAP_ARY_FLAG,isBind=bitmask&WRAP_BIND_FLAG,isBindKey=bitmask&WRAP_BIND_KEY_FLAG,isCurried=bitmask&(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG),isFlip=bitmask&WRAP_FLIP_FLAG,Ctor=isBindKey?undefined$1:createCtor(func);function wrapper(){var length=arguments.length,args=Array(length),index=length;while(index--){args[index]=arguments[index];}if(isCurried){var placeholder=getHolder(wrapper),holdersCount=countHolders(args,placeholder);}if(partials){args=composeArgs(args,partials,holders,isCurried);}if(partialsRight){args=composeArgsRight(args,partialsRight,holdersRight,isCurried);}length-=holdersCount;if(isCurried&&length<arity){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length);}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;length=args.length;if(argPos){args=reorder(args,argPos);}else if(isFlip&&length>1){args.reverse();}if(isAry&&ary<length){args.length=ary;}if(this&&this!==root&&this instanceof wrapper){fn=Ctor||createCtor(fn);}return fn.apply(thisBinding,args);}return wrapper;}/**
3 years ago
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
3 years ago
*/function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{});};}/**
3 years ago
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
3 years ago
*/function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined$1&&other===undefined$1){return defaultValue;}if(value!==undefined$1){result=value;}if(other!==undefined$1){if(result===undefined$1){return other;}if(typeof value=='string'||typeof other=='string'){value=baseToString(value);other=baseToString(other);}else {value=baseToNumber(value);other=baseToNumber(other);}result=operator(value,other);}return result;};}/**
3 years ago
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
3 years ago
*/function createOver(arrayFunc){return flatRest(function(iteratees){iteratees=arrayMap(iteratees,baseUnary(getIteratee()));return baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args);});});});}/**
3 years ago
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
3 years ago
*/function createPadding(length,chars){chars=chars===undefined$1?' ':baseToString(chars);var charsLength=chars.length;if(charsLength<2){return charsLength?baseRepeat(chars,length):chars;}var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(''):result.slice(0,length);}/**
3 years ago
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createPartial(func,bitmask,thisArg,partials){var isBind=bitmask&WRAP_BIND_FLAG,Ctor=createCtor(func);function wrapper(){var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;while(++leftIndex<leftLength){args[leftIndex]=partials[leftIndex];}while(argsLength--){args[leftIndex++]=arguments[++argsIndex];}return apply(fn,isBind?thisArg:this,args);}return wrapper;}/**
3 years ago
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
3 years ago
*/function createRange(fromRight){return function(start,end,step){if(step&&typeof step!='number'&&isIterateeCall(start,end,step)){end=step=undefined$1;}// Ensure the sign of `-0` is preserved.
start=toFinite(start);if(end===undefined$1){end=start;start=0;}else {end=toFinite(end);}step=step===undefined$1?start<end?1:-1:toFinite(step);return baseRange(start,end,step,fromRight);};}/**
3 years ago
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
3 years ago
*/function createRelationalOperation(operator){return function(value,other){if(!(typeof value=='string'&&typeof other=='string')){value=toNumber(value);other=toNumber(other);}return operator(value,other);};}/**
3 years ago
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&WRAP_CURRY_FLAG,newHolders=isCurry?holders:undefined$1,newHoldersRight=isCurry?undefined$1:holders,newPartials=isCurry?partials:undefined$1,newPartialsRight=isCurry?undefined$1:partials;bitmask|=isCurry?WRAP_PARTIAL_FLAG:WRAP_PARTIAL_RIGHT_FLAG;bitmask&=~(isCurry?WRAP_PARTIAL_RIGHT_FLAG:WRAP_PARTIAL_FLAG);if(!(bitmask&WRAP_CURRY_BOUND_FLAG)){bitmask&=~(WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG);}var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity];var result=wrapFunc.apply(undefined$1,newData);if(isLaziable(func)){setData(result,newData);}result.placeholder=placeholder;return setWrapToString(result,func,bitmask);}/**
3 years ago
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
3 years ago
*/function createRound(methodName){var func=Math[methodName];return function(number,precision){number=toNumber(number);precision=precision==null?0:nativeMin(toInteger(precision),292);if(precision&&nativeIsFinite(number)){// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair=(toString(number)+'e').split('e'),value=func(pair[0]+'e'+(+pair[1]+precision));pair=(toString(value)+'e').split('e');return +(pair[0]+'e'+(+pair[1]-precision));}return func(number);};}/**
3 years ago
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
3 years ago
*/var createSet=!(Set&&1/setToArray(new Set([,-0]))[1]==INFINITY)?noop:function(values){return new Set(values);};/**
3 years ago
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
3 years ago
*/function createToPairs(keysFunc){return function(object){var tag=getTag(object);if(tag==mapTag){return mapToArray(object);}if(tag==setTag){return setToPairs(object);}return baseToPairs(object,keysFunc(object));};}/**
3 years ago
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
3 years ago
*/function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&WRAP_BIND_KEY_FLAG;if(!isBindKey&&typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var length=partials?partials.length:0;if(!length){bitmask&=~(WRAP_PARTIAL_FLAG|WRAP_PARTIAL_RIGHT_FLAG);partials=holders=undefined$1;}ary=ary===undefined$1?ary:nativeMax(toInteger(ary),0);arity=arity===undefined$1?arity:toInteger(arity);length-=holders?holders.length:0;if(bitmask&WRAP_PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined$1;}var data=isBindKey?undefined$1:getData(func);var newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data){mergeData(newData,data);}func=newData[0];bitmask=newData[1];thisArg=newData[2];partials=newData[3];holders=newData[4];arity=newData[9]=newData[9]===undefined$1?isBindKey?0:func.length:nativeMax(newData[9]-length,0);if(!arity&&bitmask&(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG)){bitmask&=~(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG);}if(!bitmask||bitmask==WRAP_BIND_FLAG){var result=createBind(func,bitmask,thisArg);}else if(bitmask==WRAP_CURRY_FLAG||bitmask==WRAP_CURRY_RIGHT_FLAG){result=createCurry(func,bitmask,arity);}else if((bitmask==WRAP_PARTIAL_FLAG||bitmask==(WRAP_BIND_FLAG|WRAP_PARTIAL_FLAG))&&!holders.length){result=createPartial(func,bitmask,thisArg,partials);}else {result=createHybrid.apply(undefined$1,newData);}var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask);}/**
3 years ago
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
3 years ago
*/function customDefaultsAssignIn(objValue,srcValue,key,object){if(objValue===undefined$1||eq(objValue,objectProto[key])&&!hasOwnProperty.call(object,key)){return srcValue;}return objValue;}/**
3 years ago
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
3 years ago
*/function customDefaultsMerge(objValue,srcValue,key,object,source,stack){if(isObject(objValue)&&isObject(srcValue)){// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue,objValue);baseMerge(objValue,srcValue,undefined$1,customDefaultsMerge,stack);stack['delete'](srcValue);}return objValue;}/**
3 years ago
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
3 years ago
*/function customOmitClone(value){return isPlainObject(value)?undefined$1:value;}/**
3 years ago
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
3 years ago
*/function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength)){return false;}// Check that cyclic values are equal.
var arrStacked=stack.get(array);var othStacked=stack.get(other);if(arrStacked&&othStacked){return arrStacked==other&&othStacked==array;}var index=-1,result=true,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache():undefined$1;stack.set(array,other);stack.set(other,array);// Ignore non-index properties.
while(++index<arrLength){var arrValue=array[index],othValue=other[index];if(customizer){var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack);}if(compared!==undefined$1){if(compared){continue;}result=false;break;}// Recursively compare arrays (susceptible to call stack limits).
if(seen){if(!arraySome(other,function(othValue,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){return seen.push(othIndex);}})){result=false;break;}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){result=false;break;}}stack['delete'](array);stack['delete'](other);return result;}/**
3 years ago
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
3 years ago
*/function equalByTag(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case dataViewTag:if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset){return false;}object=object.buffer;other=other.buffer;case arrayBufferTag:if(object.byteLength!=other.byteLength||!equalFunc(new Uint8Array(object),new Uint8Array(other))){return false;}return true;case boolTag:case dateTag:case numberTag:// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object,+other);case errorTag:return object.name==other.name&&object.message==other.message;case regexpTag:case stringTag:// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object==other+'';case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&COMPARE_PARTIAL_FLAG;convert||(convert=setToArray);if(object.size!=other.size&&!isPartial){return false;}// Assume cyclic values are equal.
var stacked=stack.get(object);if(stacked){return stacked==other;}bitmask|=COMPARE_UNORDERED_FLAG;// Recursively compare objects (susceptible to call stack limits).
stack.set(object,other);var result=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);stack['delete'](object);return result;case symbolTag:if(symbolValueOf){return symbolValueOf.call(object)==symbolValueOf.call(other);}}return false;}/**
3 years ago
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
3 years ago
*/function equalObjects(object,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,objProps=getAllKeys(object),objLength=objProps.length,othProps=getAllKeys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial){return false;}var index=objLength;while(index--){var key=objProps[index];if(!(isPartial?key in other:hasOwnProperty.call(other,key))){return false;}}// Check that cyclic values are equal.
var objStacked=stack.get(object);var othStacked=stack.get(other);if(objStacked&&othStacked){return objStacked==other&&othStacked==object;}var result=true;stack.set(object,other);stack.set(other,object);var skipCtor=isPartial;while(++index<objLength){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer){var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack);}// Recursively compare objects (susceptible to call stack limits).
if(!(compared===undefined$1?objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack):compared)){result=false;break;}skipCtor||(skipCtor=key=='constructor');}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;// Non `Object` object instances with different constructors are not equal.
if(objCtor!=othCtor&&'constructor'in object&&'constructor'in other&&!(typeof objCtor=='function'&&objCtor instanceof objCtor&&typeof othCtor=='function'&&othCtor instanceof othCtor)){result=false;}}stack['delete'](object);stack['delete'](other);return result;}/**
3 years ago
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
3 years ago
*/function flatRest(func){return setToString(overRest(func,undefined$1,flatten),func+'');}/**
3 years ago
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
3 years ago
*/function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols);}/**
3 years ago
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
3 years ago
*/function getAllKeysIn(object){return baseGetAllKeys(object,keysIn,getSymbolsIn);}/**
3 years ago
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
3 years ago
*/var getData=!metaMap?noop:function(func){return metaMap.get(func);};/**
3 years ago
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
3 years ago
*/function getFuncName(func){var result=func.name+'',array=realNames[result],length=hasOwnProperty.call(realNames,result)?array.length:0;while(length--){var data=array[length],otherFunc=data.func;if(otherFunc==null||otherFunc==func){return data.name;}}return result;}/**
3 years ago
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
3 years ago
*/function getHolder(func){var object=hasOwnProperty.call(lodash,'placeholder')?lodash:func;return object.placeholder;}/**
3 years ago
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
3 years ago
*/function getIteratee(){var result=lodash.iteratee||iteratee;result=result===iteratee?baseIteratee:result;return arguments.length?result(arguments[0],arguments[1]):result;}/**
3 years ago
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
3 years ago
*/function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data[typeof key=='string'?'string':'hash']:data.map;}/**
3 years ago
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
3 years ago
*/function getMatchData(object){var result=keys(object),length=result.length;while(length--){var key=result[length],value=object[key];result[length]=[key,value,isStrictComparable(value)];}return result;}/**
3 years ago
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
3 years ago
*/function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:undefined$1;}/**
3 years ago
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
3 years ago
*/function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=undefined$1;var unmasked=true;}catch(e){}var result=nativeObjectToString.call(value);if(unmasked){if(isOwn){value[symToStringTag]=tag;}else {delete value[symToStringTag];}}return result;}/**
3 years ago
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
3 years ago
*/var getSymbols=!nativeGetSymbols?stubArray:function(object){if(object==null){return [];}object=Object(object);return arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol);});};/**
3 years ago
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
3 years ago
*/var getSymbolsIn=!nativeGetSymbols?stubArray:function(object){var result=[];while(object){arrayPush(result,getSymbols(object));object=getPrototype(object);}return result;};/**
3 years ago
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
3 years ago
*/var getTag=baseGetTag;// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map())!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set())!=setTag||WeakMap&&getTag(new WeakMap())!=weakMapTag){getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:undefined$1,ctorString=Ctor?toSource(Ctor):'';if(ctorString){switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag;}}return result;};}/**
3 years ago
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
3 years ago
*/function getView(start,end,transforms){var index=-1,length=transforms.length;while(++index<length){var data=transforms[index],size=data.size;switch(data.type){case'drop':start+=size;break;case'dropRight':end-=size;break;case'take':end=nativeMin(end,start+size);break;case'takeRight':start=nativeMax(start,end-size);break;}}return {'start':start,'end':end};}/**
3 years ago
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
3 years ago
*/function getWrapDetails(source){var match=source.match(reWrapDetails);return match?match[1].split(reSplitDetails):[];}/**
3 years ago
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
3 years ago
*/function hasPath(object,path,hasFunc){path=castPath(path,object);var index=-1,length=path.length,result=false;while(++index<length){var key=toKey(path[index]);if(!(result=object!=null&&hasFunc(object,key))){break;}object=object[key];}if(result||++index!=length){return result;}length=object==null?0:object.length;return !!length&&isLength(length)&&isIndex(key,length)&&(isArray(object)||isArguments(object));}/**
3 years ago
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
3 years ago
*/function initCloneArray(array){var length=array.length,result=new array.constructor(length);// Add properties assigned by `RegExp#exec`.
if(length&&typeof array[0]=='string'&&hasOwnProperty.call(array,'index')){result.index=array.index;result.input=array.input;}return result;}/**
3 years ago
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
3 years ago
*/function initCloneObject(object){return typeof object.constructor=='function'&&!isPrototype(object)?baseCreate(getPrototype(object)):{};}/**
3 years ago
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
3 years ago
*/function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return cloneArrayBuffer(object);case boolTag:case dateTag:return new Ctor(+object);case dataViewTag:return cloneDataView(object,isDeep);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:return cloneTypedArray(object,isDeep);case mapTag:return new Ctor();case numberTag:case stringTag:return new Ctor(object);case regexpTag:return cloneRegExp(object);case setTag:return new Ctor();case symbolTag:return cloneSymbol(object);}}/**
3 years ago
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
3 years ago
*/function insertWrapDetails(source,details){var length=details.length;if(!length){return source;}var lastIndex=length-1;details[lastIndex]=(length>1?'& ':'')+details[lastIndex];details=details.join(length>2?', ':' ');return source.replace(reWrapComment,'{\n/* [wrapped with '+details+'] */\n');}/**
3 years ago
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
3 years ago
*/function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol]);}/**
3 years ago
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
3 years ago
*/function isIndex(value,length){var type=typeof value;length=length==null?MAX_SAFE_INTEGER:length;return !!length&&(type=='number'||type!='symbol'&&reIsUint.test(value))&&value>-1&&value%1==0&&value<length;}/**
3 years ago
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
3 years ago
*/function isIterateeCall(value,index,object){if(!isObject(object)){return false;}var type=typeof index;if(type=='number'?isArrayLike(object)&&isIndex(index,object.length):type=='string'&&index in object){return eq(object[index],value);}return false;}/**
3 years ago
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
3 years ago
*/function isKey(value,object){if(isArray(value)){return false;}var type=typeof value;if(type=='number'||type=='symbol'||type=='boolean'||value==null||isSymbol(value)){return true;}return reIsPlainProp.test(value)||!reIsDeepProp.test(value)||object!=null&&value in Object(object);}/**
3 years ago
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
3 years ago
*/function isKeyable(value){var type=typeof value;return type=='string'||type=='number'||type=='symbol'||type=='boolean'?value!=='__proto__':value===null;}/**
3 years ago
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
3 years ago
*/function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if(typeof other!='function'||!(funcName in LazyWrapper.prototype)){return false;}if(func===other){return true;}var data=getData(other);return !!data&&func===data[0];}/**
3 years ago
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
3 years ago
*/function isMasked(func){return !!maskSrcKey&&maskSrcKey in func;}/**
3 years ago
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
3 years ago
*/var isMaskable=coreJsData?isFunction:stubFalse;/**
3 years ago
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
3 years ago
*/function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=='function'&&Ctor.prototype||objectProto;return value===proto;}/**
3 years ago
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
3 years ago
*/function isStrictComparable(value){return value===value&&!isObject(value);}/**
3 years ago
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
3 years ago
*/function matchesStrictComparable(key,srcValue){return function(object){if(object==null){return false;}return object[key]===srcValue&&(srcValue!==undefined$1||key in Object(object));};}/**
3 years ago
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
3 years ago
*/function memoizeCapped(func){var result=memoize(func,function(key){if(cache.size===MAX_MEMOIZE_SIZE){cache.clear();}return key;});var cache=result.cache;return result;}/**
3 years ago
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
3 years ago
*/function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=newBitmask<(WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG|WRAP_ARY_FLAG);var isCombo=srcBitmask==WRAP_ARY_FLAG&&bitmask==WRAP_CURRY_FLAG||srcBitmask==WRAP_ARY_FLAG&&bitmask==WRAP_REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(WRAP_ARY_FLAG|WRAP_REARG_FLAG)&&source[7].length<=source[8]&&bitmask==WRAP_CURRY_FLAG;// Exit early if metadata can't be merged.
if(!(isCommon||isCombo)){return data;}// Use source `thisArg` if available.
if(srcBitmask&WRAP_BIND_FLAG){data[2]=source[2];// Set when currying a bound function.
newBitmask|=bitmask&WRAP_BIND_FLAG?0:WRAP_CURRY_BOUND_FLAG;}// Compose partial arguments.
var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value;data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4];}// Compose partial right arguments.
value=source[5];if(value){partials=data[5];data[5]=partials?composeArgsRight(partials,value,source[6]):value;data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6];}// Use source `argPos` if available.
value=source[7];if(value){data[7]=value;}// Use source `ary` if it's smaller.
if(srcBitmask&WRAP_ARY_FLAG){data[8]=data[8]==null?source[8]:nativeMin(data[8],source[8]);}// Use source `arity` if one is not provided.
if(data[9]==null){data[9]=source[9];}// Use source `func` and merge bitmasks.
data[0]=source[0];data[1]=newBitmask;return data;}/**
3 years ago
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
3 years ago
*/function nativeKeysIn(object){var result=[];if(object!=null){for(var key in Object(object)){result.push(key);}}return result;}/**
3 years ago
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
3 years ago
*/function objectToString(value){return nativeObjectToString.call(value);}/**
3 years ago
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
3 years ago
*/function overRest(func,start,transform){start=nativeMax(start===undefined$1?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index<length){array[index]=args[start+index];}index=-1;var otherArgs=Array(start+1);while(++index<start){otherArgs[index]=args[index];}otherArgs[start]=transform(array);return apply(func,this,otherArgs);};}/**
3 years ago
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
3 years ago
*/function parent(object,path){return path.length<2?object:baseGet(object,baseSlice(path,0,-1));}/**
3 years ago
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
3 years ago
*/function reorder(array,indexes){var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=copyArray(array);while(length--){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:undefined$1;}return array;}/**
3 years ago
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
3 years ago
*/function safeGet(object,key){if(key==='constructor'&&typeof object[key]==='function'){return;}if(key=='__proto__'){return;}return object[key];}/**
3 years ago
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
3 years ago
*/var setData=shortOut(baseSetData);/**
3 years ago
* A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @returns {number|Object} Returns the timer id or timeout object.
3 years ago
*/var setTimeout=ctxSetTimeout||function(func,wait){return root.setTimeout(func,wait);};/**
3 years ago
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
3 years ago
*/var setToString=shortOut(baseSetToString);/**
3 years ago
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
3 years ago
*/function setWrapToString(wrapper,reference,bitmask){var source=reference+'';return setToString(wrapper,insertWrapDetails(source,updateWrapDetails(getWrapDetails(source),bitmask)));}/**
3 years ago
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
3 years ago
*/function shortOut(func){var count=0,lastCalled=0;return function(){var stamp=nativeNow(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return arguments[0];}}else {count=0;}return func.apply(undefined$1,arguments);};}/**
3 years ago
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
3 years ago
*/function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;size=size===undefined$1?length:size;while(++index<size){var rand=baseRandom(index,lastIndex),value=array[rand];array[rand]=array[index];array[index]=value;}array.length=size;return array;}/**
3 years ago
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
3 years ago
*/var stringToPath=memoizeCapped(function(string){var result=[];if(string.charCodeAt(0)===46/* . */){result.push('');}string.replace(rePropName,function(match,number,quote,subString){result.push(quote?subString.replace(reEscapeChar,'$1'):number||match);});return result;});/**
3 years ago
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
3 years ago
*/function toKey(value){if(typeof value=='string'||isSymbol(value)){return value;}var result=value+'';return result=='0'&&1/value==-INFINITY?'-0':result;}/**
3 years ago
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
3 years ago
*/function toSource(func){if(func!=null){try{return funcToString.call(func);}catch(e){}try{return func+'';}catch(e){}}return '';}/**
3 years ago
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
3 years ago
*/function updateWrapDetails(details,bitmask){arrayEach(wrapFlags,function(pair){var value='_.'+pair[0];if(bitmask&pair[1]&&!arrayIncludes(details,value)){details.push(value);}});return details.sort();}/**
3 years ago
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
3 years ago
*/function wrapperClone(wrapper){if(wrapper instanceof LazyWrapper){return wrapper.clone();}var result=new LodashWrapper(wrapper.__wrapped__,wrapper.__chain__);result.__actions__=copyArray(wrapper.__actions__);result.__index__=wrapper.__index__;result.__values__=wrapper.__values__;return result;}/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
3 years ago
*/function chunk(array,size,guard){if(guard?isIterateeCall(array,size,guard):size===undefined$1){size=1;}else {size=nativeMax(toInteger(size),0);}var length=array==null?0:array.length;if(!length||size<1){return [];}var index=0,resIndex=0,result=Array(nativeCeil(length/size));while(index<length){result[resIndex++]=baseSlice(array,index,index+=size);}return result;}/**
3 years ago
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
3 years ago
*/function compact(array){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(value){result[resIndex++]=value;}}return result;}/**
3 years ago
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
3 years ago
*/function concat(){var length=arguments.length;if(!length){return [];}var args=Array(length-1),array=arguments[0],index=length;while(index--){args[index-1]=arguments[index];}return arrayPush(isArray(array)?copyArray(array):[array],baseFlatten(args,1));}/**
3 years ago
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
3 years ago
*/var difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true)):[];});/**
3 years ago
* This method is like `_.difference` except that it accepts `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `_.pullAllBy`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2]
*
* // The `_.property` iteratee shorthand.
* _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
3 years ago
*/var differenceBy=baseRest(function(array,values){var iteratee=last(values);if(isArrayLikeObject(iteratee)){iteratee=undefined$1;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),getIteratee(iteratee,2)):[];});/**
3 years ago
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
3 years ago
*/var differenceWith=baseRest(function(array,values){var comparator=last(values);if(isArrayLikeObject(comparator)){comparator=undefined$1;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),undefined$1,comparator):[];});/**
3 years ago
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
3 years ago
*/function drop(array,n,guard){var length=array==null?0:array.length;if(!length){return [];}n=guard||n===undefined$1?1:toInteger(n);return baseSlice(array,n<0?0:n,length);}/**
3 years ago
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
3 years ago
*/function dropRight(array,n,guard){var length=array==null?0:array.length;if(!length){return [];}n=guard||n===undefined$1?1:toInteger(n);n=length-n;return baseSlice(array,0,n<0?0:n);}/**
3 years ago
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
3 years ago
*/function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true,true):[];}/**
3 years ago
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
3 years ago
*/function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true):[];}/**
3 years ago
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
3 years ago
*/function fill(array,value,start,end){var length=array==null?0:array.length;if(!length){return [];}if(start&&typeof start!='number'&&isIterateeCall(array,value,start)){start=0;end=length;}return baseFill(array,value,start,end);}/**
3 years ago
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
3 years ago
*/function findIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return -1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseFindIndex(array,getIteratee(predicate,3),index);}/**
3 years ago
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
3 years ago
*/function findLastIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return -1;}var index=length-1;if(fromIndex!==undefined$1){index=toInteger(fromIndex);index=fromIndex<0?nativeMax(length+index,0):nativeMin(index,length-1);}return baseFindIndex(array,getIteratee(predicate,3),index,true);}/**
3 years ago
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
3 years ago
*/function flatten(array){var length=array==null?0:array.length;return length?baseFlatten(array,1):[];}/**
3 years ago
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
3 years ago
*/function flattenDeep(array){var length=array==null?0:array.length;return length?baseFlatten(array,INFINITY):[];}/**
3 years ago
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
3 years ago
*/function flattenDepth(array,depth){var length=array==null?0:array.length;if(!length){return [];}depth=depth===undefined$1?1:toInteger(depth);return baseFlatten(array,depth);}/**
3 years ago
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
3 years ago
*/function fromPairs(pairs){var index=-1,length=pairs==null?0:pairs.length,result={};while(++index<length){var pair=pairs[index];result[pair[0]]=pair[1];}return result;}/**
3 years ago
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
3 years ago
*/function head(array){return array&&array.length?array[0]:undefined$1;}/**
3 years ago
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
3 years ago
*/function indexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return -1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseIndexOf(array,value,index);}/**
3 years ago
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
3 years ago
*/function initial(array){var length=array==null?0:array.length;return length?baseSlice(array,0,-1):[];}/**
3 years ago
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
3 years ago
*/var intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[];});/**
3 years ago
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
3 years ago
*/var intersectionBy=baseRest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);if(iteratee===last(mapped)){iteratee=undefined$1;}else {mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,getIteratee(iteratee,2)):[];});/**
3 years ago
* This method is like `_.intersection` except that it accepts `comparator`
* which is invoked to compare elements of `arrays`. The order and references
* of result values are determined by the first array. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.intersectionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }]
3 years ago
*/var intersectionWith=baseRest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);comparator=typeof comparator=='function'?comparator:undefined$1;if(comparator){mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,undefined$1,comparator):[];});/**
3 years ago
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
3 years ago
*/function join(array,separator){return array==null?'':nativeJoin.call(array,separator);}/**
3 years ago
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
3 years ago
*/function last(array){var length=array==null?0:array.length;return length?array[length-1]:undefined$1;}/**
3 years ago
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
3 years ago
*/function lastIndexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return -1;}var index=length;if(fromIndex!==undefined$1){index=toInteger(fromIndex);index=index<0?nativeMax(length+index,0):nativeMin(index,length-1);}return value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,true);}/**
3 years ago
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
3 years ago
*/function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined$1;}/**
3 years ago
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
3 years ago
*/var pull=baseRest(pullAll);/**
3 years ago
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
3 years ago
*/function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array;}/**
3 years ago
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
3 years ago
*/function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array;}/**
3 years ago
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
3 years ago
*/function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined$1,comparator):array;}/**
3 years ago
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
3 years ago
*/var pullAt=flatRest(function(array,indexes){var length=array==null?0:array.length,result=baseAt(array,indexes);basePullAt(array,arrayMap(indexes,function(index){return isIndex(index,length)?+index:index;}).sort(compareAscending));return result;});/**
3 years ago
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
3 years ago
*/function remove(array,predicate){var result=[];if(!(array&&array.length)){return result;}var index=-1,indexes=[],length=array.length;predicate=getIteratee(predicate,3);while(++index<length){var value=array[index];if(predicate(value,index,array)){result.push(value);indexes.push(index);}}basePullAt(array,indexes);return result;}/**
3 years ago
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
3 years ago
*/function reverse(array){return array==null?array:nativeReverse.call(array);}/**
3 years ago
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
3 years ago
*/function slice(array,start,end){var length=array==null?0:array.length;if(!length){return [];}if(end&&typeof end!='number'&&isIterateeCall(array,start,end)){start=0;end=length;}else {start=start==null?0:toInteger(start);end=end===undefined$1?length:toInteger(end);}return baseSlice(array,start,end);}/**
3 years ago
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
3 years ago
*/function sortedIndex(array,value){return baseSortedIndex(array,value);}/**
3 years ago
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
3 years ago
*/function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2));}/**
3 years ago
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
3 years ago
*/function sortedIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value);if(index<length&&eq(array[index],value)){return index;}}return -1;}/**
3 years ago
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
3 years ago
*/function sortedLastIndex(array,value){return baseSortedIndex(array,value,true);}/**
3 years ago
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
3 years ago
*/function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),true);}/**
3 years ago
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
3 years ago
*/function sortedLastIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value,true)-1;if(eq(array[index],value)){return index;}}return -1;}/**
3 years ago
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
3 years ago
*/function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[];}/**
3 years ago
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
3 years ago
*/function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[];}/**
3 years ago
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
3 years ago
*/function tail(array){var length=array==null?0:array.length;return length?baseSlice(array,1,length):[];}/**
3 years ago
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
3 years ago
*/function take(array,n,guard){if(!(array&&array.length)){return [];}n=guard||n===undefined$1?1:toInteger(n);return baseSlice(array,0,n<0?0:n);}/**
3 years ago
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
3 years ago
*/function takeRight(array,n,guard){var length=array==null?0:array.length;if(!length){return [];}n=guard||n===undefined$1?1:toInteger(n);n=length-n;return baseSlice(array,n<0?0:n,length);}/**
3 years ago
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
3 years ago
*/function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),false,true):[];}/**
3 years ago
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
3 years ago
*/function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[];}/**
3 years ago
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
3 years ago
*/var union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true));});/**
3 years ago
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. Result values are chosen from the first
* array in which the value occurs. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
3 years ago
*/var unionBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined$1;}return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),getIteratee(iteratee,2));});/**
3 years ago
* This method is like `_.union` except that it accepts `comparator` which
* is invoked to compare elements of `arrays`. Result values are chosen from
* the first array in which the value occurs. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.unionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
3 years ago
*/var unionWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined$1;return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),undefined$1,comparator);});/**
3 years ago
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
3 years ago
*/function uniq(array){return array&&array.length?baseUniq(array):[];}/**
3 years ago
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
3 years ago
*/function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[];}/**
3 years ago
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
3 years ago
*/function uniqWith(array,comparator){comparator=typeof comparator=='function'?comparator:undefined$1;return array&&array.length?baseUniq(array,undefined$1,comparator):[];}/**
3 years ago
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
3 years ago
*/function unzip(array){if(!(array&&array.length)){return [];}var length=0;array=arrayFilter(array,function(group){if(isArrayLikeObject(group)){length=nativeMax(group.length,length);return true;}});return baseTimes(length,function(index){return arrayMap(array,baseProperty(index));});}/**
3 years ago
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
3 years ago
*/function unzipWith(array,iteratee){if(!(array&&array.length)){return [];}var result=unzip(array);if(iteratee==null){return result;}return arrayMap(result,function(group){return apply(iteratee,undefined$1,group);});}/**
3 years ago
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
3 years ago
*/var without=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[];});/**
3 years ago
* Creates an array of unique values that is the
* [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the given arrays. The order of result values is determined by the order
* they occur in the arrays.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.without
* @example
*
* _.xor([2, 1], [2, 3]);
* // => [1, 3]
3 years ago
*/var xor=baseRest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject));});/**
3 years ago
* This method is like `_.xor` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which by which they're compared. The order of result values is determined
* by the order they occur in the arrays. The iteratee is invoked with one
* argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2, 3.4]
*
* // The `_.property` iteratee shorthand.
* _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
3 years ago
*/var xorBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined$1;}return baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee,2));});/**
3 years ago
* This method is like `_.xor` except that it accepts `comparator` which is
* invoked to compare elements of `arrays`. The order of result values is
* determined by the order they occur in the arrays. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.xorWith(objects, others, _.isEqual);
* // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
3 years ago
*/var xorWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined$1;return baseXor(arrayFilter(arrays,isArrayLikeObject),undefined$1,comparator);});/**
3 years ago
* Creates an array of grouped elements, the first of which contains the
* first elements of the given arrays, the second of which contains the
* second elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
3 years ago
*/var zip=baseRest(unzip);/**
3 years ago
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
3 years ago
*/function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue);}/**
3 years ago
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
3 years ago
*/function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet);}/**
3 years ago
* This method is like `_.zip` except that it accepts `iteratee` to specify
* how grouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee=_.identity] The function to combine
* grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
* return a + b + c;
* });
* // => [111, 222]
3 years ago
*/var zipWith=baseRest(function(arrays){var length=arrays.length,iteratee=length>1?arrays[length-1]:undefined$1;iteratee=typeof iteratee=='function'?(arrays.pop(),iteratee):undefined$1;return unzipWith(arrays,iteratee);});/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
3 years ago
*/function chain(value){var result=lodash(value);result.__chain__=true;return result;}/**
3 years ago
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
3 years ago
*/function tap(value,interceptor){interceptor(value);return value;}/**
3 years ago
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
3 years ago
*/function thru(value,interceptor){return interceptor(value);}/**
3 years ago
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
3 years ago
*/var wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths);};if(length>1||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)){return this.thru(interceptor);}value=value.slice(start,+start+(length?1:0));value.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined$1});return new LodashWrapper(value,this.__chain__).thru(function(array){if(length&&!array.length){array.push(undefined$1);}return array;});});/**
3 years ago
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
3 years ago
*/function wrapperChain(){return chain(this);}/**
3 years ago
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
3 years ago
*/function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__);}/**
3 years ago
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
3 years ago
*/function wrapperNext(){if(this.__values__===undefined$1){this.__values__=toArray(this.value());}var done=this.__index__>=this.__values__.length,value=done?undefined$1:this.__values__[this.__index__++];return {'done':done,'value':value};}/**
3 years ago
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
3 years ago
*/function wrapperToIterator(){return this;}/**
3 years ago
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
3 years ago
*/function wrapperPlant(value){var result,parent=this;while(parent instanceof baseLodash){var clone=wrapperClone(parent);clone.__index__=0;clone.__values__=undefined$1;if(result){previous.__wrapped__=clone;}else {result=clone;}var previous=clone;parent=parent.__wrapped__;}previous.__wrapped__=value;return result;}/**
3 years ago
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
3 years ago
*/function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;if(this.__actions__.length){wrapped=new LazyWrapper(this);}wrapped=wrapped.reverse();wrapped.__actions__.push({'func':thru,'args':[reverse],'thisArg':undefined$1});return new LodashWrapper(wrapped,this.__chain__);}return this.thru(reverse);}/**
3 years ago
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
3 years ago
*/function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__);}/*------------------------------------------------------------------------*/ /**
3 years ago
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
3 years ago
*/var countBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){++result[key];}else {baseAssignValue(result,key,1);}});/**
3 years ago
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
3 years ago
*/function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined$1;}return func(collection,getIteratee(predicate,3));}/**
3 years ago
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
3 years ago
*/function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3));}/**
3 years ago
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
3 years ago
*/var find=createFind(findIndex);/**
3 years ago
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
3 years ago
*/var findLast=createFind(findLastIndex);/**
3 years ago
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
3 years ago
*/function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1);}/**
3 years ago
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
3 years ago
*/function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY);}/**
3 years ago
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
3 years ago
*/function flatMapDepth(collection,iteratee,depth){depth=depth===undefined$1?1:toInteger(depth);return baseFlatten(map(collection,iteratee),depth);}/**
3 years ago
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
3 years ago
*/function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3));}/**
3 years ago
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
3 years ago
*/function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3));}/**
3 years ago
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
3 years ago
*/var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value);}else {baseAssignValue(result,key,[value]);}});/**
3 years ago
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
3 years ago
*/function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection);fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0);}return isString(collection)?fromIndex<=length&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1;}/**
3 years ago
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `path` is a function, it's invoked
* for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
3 years ago
*/var invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc=typeof path=='function',result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value){result[++index]=isFunc?apply(path,value,args):baseInvoke(value,path,args);});return result;});/**
3 years ago
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
3 years ago
*/var keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value);});/**
3 years ago
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
3 years ago
*/function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3));}/**
3 years ago
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
3 years ago
*/function orderBy(collection,iteratees,orders,guard){if(collection==null){return [];}if(!isArray(iteratees)){iteratees=iteratees==null?[]:[iteratees];}orders=guard?undefined$1:orders;if(!isArray(orders)){orders=orders==null?[]:[orders];}return baseOrderBy(collection,iteratees,orders);}/**
3 years ago
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
3 years ago
*/var partition=createAggregator(function(result,value,key){result[key?0:1].push(value);},function(){return [[],[]];});/**
3 years ago
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
3 years ago
*/function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach);}/**
3 years ago
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
3 years ago
*/function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight);}/**
3 years ago
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
3 years ago
*/function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)));}/**
3 years ago
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
3 years ago
*/function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection);}/**
3 years ago
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
3 years ago
*/function sampleSize(collection,n,guard){if(guard?isIterateeCall(collection,n,guard):n===undefined$1){n=1;}else {n=toInteger(n);}var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n);}/**
3 years ago
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
3 years ago
*/function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection);}/**
3 years ago
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
3 years ago
*/function size(collection){if(collection==null){return 0;}if(isArrayLike(collection)){return isString(collection)?stringSize(collection):collection.length;}var tag=getTag(collection);if(tag==mapTag||tag==setTag){return collection.size;}return baseKeys(collection).length;}/**
3 years ago
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
3 years ago
*/function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined$1;}return func(collection,getIteratee(predicate,3));}/**
3 years ago
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
3 years ago
*/var sortBy=baseRest(function(collection,iteratees){if(collection==null){return [];}var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[];}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees=[iteratees[0]];}return baseOrderBy(collection,baseFlatten(iteratees,1),[]);});/*------------------------------------------------------------------------*/ /**
3 years ago
* 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.
3 years ago
*/var now=ctxNow||function(){return root.Date.now();};/*------------------------------------------------------------------------*/ /**
3 years ago
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
3 years ago
*/function after(n,func){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n<1){return func.apply(this,arguments);}};}/**
3 years ago
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
3 years ago
*/function ary(func,n,guard){n=guard?undefined$1:n;n=func&&n==null?func.length:n;return createWrap(func,WRAP_ARY_FLAG,undefined$1,undefined$1,undefined$1,undefined$1,n);}/**
3 years ago
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
3 years ago
*/function before(n,func){var result;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n>0){result=func.apply(this,arguments);}if(n<=1){func=undefined$1;}return result;};}/**
3 years ago
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
3 years ago
*/var bind=baseRest(function(func,thisArg,partials){var bitmask=WRAP_BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(func,bitmask,thisArg,partials,holders);});/**
3 years ago
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @since 0.10.0
* @category Function
* @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
3 years ago
*/var bindKey=baseRest(function(object,key,partials){var bitmask=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(key,bitmask,object,partials,holders);});/**
3 years ago
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
3 years ago
*/function curry(func,arity,guard){arity=guard?undefined$1:arity;var result=createWrap(func,WRAP_CURRY_FLAG,undefined$1,undefined$1,undefined$1,undefined$1,undefined$1,arity);result.placeholder=curry.placeholder;return result;}/**
3 years ago
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
3 years ago
*/function curryRight(func,arity,guard){arity=guard?undefined$1:arity;var result=createWrap(func,WRAP_CURRY_RIGHT_FLAG,undefined$1,undefined$1,undefined$1,undefined$1,undefined$1,arity);result.placeholder=curryRight.placeholder;return result;}/**
3 years ago
* 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);
3 years ago
*/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$1;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,timeWaiting=wait-timeSinceLastCall;return maxing?nativeMin(timeWaiting,maxWait-timeSinceLastInvoke):timeWaiting;}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$1||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$1;// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if(trailing&&lastArgs){return invokeFunc(time);}lastArgs=lastThis=undefined$1;return result;}function cancel(){if(timerId!==undefined$1){clearTimeout(timerId);}lastInvokeTime=0;lastArgs=lastCallTime=lastThis=timerId=undefined$1;}function flush(){return timerId===undefined$1?result:trailingEdge(now());}function debounced(){var time=now(),isInvoking=shouldInvoke(time);lastArgs=arguments;lastThis=this;lastCallTime=time;if(isInvoking){if(timerId===undefined$1){return leadingEdge(lastCallTime);}if(maxing){// Handle invocations in a tight loop.
clearTimeout(timerId);timerId=setTimeout(timerExpired,wait);return invokeFunc(lastCallTime);}}if(timerId===undefined$1){timerId=setTimeout(timerExpired,wait);}return result;}debounced.cancel=cancel;debounced.flush=flush;return debounced;}/**
3 years ago
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
3 years ago
*/var defer=baseRest(function(func,args){return baseDelay(func,1,args);});/**
3 years ago
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => Logs 'later' after one second.
3 years ago
*/var delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args);});/**
3 years ago
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
3 years ago
*/function flip(func){return createWrap(func,WRAP_FLIP_FLAG);}/**
3 years ago
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
3 years ago
*/function memoize(func,resolver){if(typeof func!='function'||resolver!=null&&typeof resolver!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize.Cache||MapCache)();return memoized;}// Expose `MapCache`.
memoize.Cache=MapCache;/**
3 years ago
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
3 years ago
*/function negate(predicate){if(typeof predicate!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return function(){var args=arguments;switch(args.length){case 0:return !predicate.call(this);case 1:return !predicate.call(this,args[0]);case 2:return !predicate.call(this,args[0],args[1]);case 3:return !predicate.call(this,args[0],args[1],args[2]);}return !predicate.apply(this,args);};}/**
3 years ago
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
3 years ago
*/function once(func){return before(2,func);}/**
3 years ago
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
3 years ago
*/var overArgs=castRest(function(func,transforms){transforms=transforms.length==1&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){var index=-1,length=nativeMin(args.length,funcsLength);while(++index<length){args[index]=transforms[index].call(this,args[index]);}return apply(func,this,args);});});/**
3 years ago
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
3 years ago
*/var partial=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partial));return createWrap(func,WRAP_PARTIAL_FLAG,undefined$1,partials,holders);});/**
3 years ago
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
3 years ago
*/var partialRight=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrap(func,WRAP_PARTIAL_RIGHT_FLAG,undefined$1,partials,holders);});/**
3 years ago
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
3 years ago
*/var rearg=flatRest(function(func,indexes){return createWrap(func,WRAP_REARG_FLAG,undefined$1,undefined$1,undefined$1,indexes);});/**
3 years ago
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
3 years ago
*/function rest(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start===undefined$1?start:toInteger(start);return baseRest(func,start);}/**
3 years ago
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
3 years ago
*/function spread(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start==null?0:nativeMax(toInteger(start),0);return baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);if(array){arrayPush(otherArgs,array);}return apply(func,this,otherArgs);});}/**
3 years ago
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled 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
* throttled function. Subsequent calls to the throttled 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 throttled 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 `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
3 years ago
*/function throttle(func,wait,options){var leading=true,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(isObject(options)){leading='leading'in options?!!options.leading:leading;trailing='trailing'in options?!!options.trailing:trailing;}return debounce(func,wait,{'leading':leading,'maxWait':wait,'trailing':trailing});}/**
3 years ago
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
3 years ago
*/function unary(func){return ary(func,1);}/**
3 years ago
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, &amp; pebbles</p>'
3 years ago
*/function wrap(value,wrapper){return partial(castFunction(wrapper),value);}/*------------------------------------------------------------------------*/ /**
3 years ago
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
3 years ago
*/function castArray(){if(!arguments.length){return [];}var value=arguments[0];return isArray(value)?value:[value];}/**
3 years ago
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
3 years ago
*/function clone(value){return baseClone(value,CLONE_SYMBOLS_FLAG);}/**
3 years ago
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
3 years ago
*/function cloneWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined$1;return baseClone(value,CLONE_SYMBOLS_FLAG,customizer);}/**
3 years ago
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
3 years ago
*/function cloneDeep(value){return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG);}/**
3 years ago
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
3 years ago
*/function cloneDeepWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined$1;return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG,customizer);}/**
3 years ago
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
3 years ago
*/function conformsTo(object,source){return source==null||baseConformsTo(object,source,keys(source));}/**
3 years ago
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
3 years ago
*/function eq(value,other){return value===other||value!==value&&other!==other;}/**
3 years ago
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
3 years ago
*/var gt=createRelationalOperation(baseGt);/**
3 years ago
* Checks if `value` is greater than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than or equal to
* `other`, else `false`.
* @see _.lte
* @example
*
* _.gte(3, 1);
* // => true
*
* _.gte(3, 3);
* // => true
*
* _.gte(1, 3);
* // => false
3 years ago
*/var gte=createRelationalOperation(function(value,other){return value>=other;});/**
3 years ago
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
3 years ago
*/var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};/**
3 years ago
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
3 years ago
*/var isArray=Array.isArray;/**
3 years ago
* Checks if `value` is classified as an `ArrayBuffer` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
* @example
*
* _.isArrayBuffer(new ArrayBuffer(2));
* // => true
*
* _.isArrayBuffer(new Array(2));
* // => false
3 years ago
*/var isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer;/**
3 years ago
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
3 years ago
*/function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}/**
3 years ago
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
3 years ago
*/function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value);}/**
3 years ago
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
3 years ago
*/function isBoolean(value){return value===true||value===false||isObjectLike(value)&&baseGetTag(value)==boolTag;}/**
3 years ago
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
3 years ago
*/var isBuffer=nativeIsBuffer||stubFalse;/**
3 years ago
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
3 years ago
*/var isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate;/**
3 years ago
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
3 years ago
*/function isElement(value){return isObjectLike(value)&&value.nodeType===1&&!isPlainObject(value);}/**
3 years ago
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
3 years ago
*/function isEmpty(value){if(value==null){return true;}if(isArrayLike(value)&&(isArray(value)||typeof value=='string'||typeof value.splice=='function'||isBuffer(value)||isTypedArray(value)||isArguments(value))){return !value.length;}var tag=getTag(value);if(tag==mapTag||tag==setTag){return !value.size;}if(isPrototype(value)){return !baseKeys(value).length;}for(var key in value){if(hasOwnProperty.call(value,key)){return false;}}return true;}/**
3 years ago
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
3 years ago
*/function isEqual(value,other){return baseIsEqual(value,other);}/**
3 years ago
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
3 years ago
*/function isEqualWith(value,other,customizer){customizer=typeof customizer=='function'?customizer:undefined$1;var result=customizer?customizer(value,other):undefined$1;return result===undefined$1?baseIsEqual(value,other,undefined$1,customizer):!!result;}/**
3 years ago
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
3 years ago
*/function isError(value){if(!isObjectLike(value)){return false;}var tag=baseGetTag(value);return tag==errorTag||tag==domExcTag||typeof value.message=='string'&&typeof value.name=='string'&&!isPlainObject(value);}/**
3 years ago
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
3 years ago
*/function isFinite(value){return typeof value=='number'&&nativeIsFinite(value);}/**
3 years ago
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
3 years ago
*/function isFunction(value){if(!isObject(value)){return false;}// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}/**
3 years ago
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
3 years ago
*/function isInteger(value){return typeof value=='number'&&value==toInteger(value);}/**
3 years ago
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
3 years ago
*/function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}/**
3 years ago
* 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
3 years ago
*/function isObject(value){var type=typeof value;return value!=null&&(type=='object'||type=='function');}/**
3 years ago
* 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
3 years ago
*/function isObjectLike(value){return value!=null&&typeof value=='object';}/**
3 years ago
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
3 years ago
*/var isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap;/**
3 years ago
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
3 years ago
*/function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source));}/**
3 years ago
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
3 years ago
*/function isMatchWith(object,source,customizer){customizer=typeof customizer=='function'?customizer:undefined$1;return baseIsMatch(object,source,getMatchData(source),customizer);}/**
3 years ago
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
3 years ago
*/function isNaN(value){// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value)&&value!=+value;}/**
3 years ago
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
3 years ago
*/function isNative(value){if(isMaskable(value)){throw new Error(CORE_ERROR_TEXT);}return baseIsNative(value);}/**
3 years ago
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
3 years ago
*/function isNull(value){return value===null;}/**
3 years ago
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
3 years ago
*/function isNil(value){return value==null;}/**
3 years ago
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
3 years ago
*/function isNumber(value){return typeof value=='number'||isObjectLike(value)&&baseGetTag(value)==numberTag;}/**
3 years ago
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
3 years ago
*/function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag){return false;}var proto=getPrototype(value);if(proto===null){return true;}var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}/**
3 years ago
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
3 years ago
*/var isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp;/**
3 years ago
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
3 years ago
*/function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER;}/**
3 years ago
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
3 years ago
*/var isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet;/**
3 years ago
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
3 years ago
*/function isString(value){return typeof value=='string'||!isArray(value)&&isObjectLike(value)&&baseGetTag(value)==stringTag;}/**
3 years ago
* 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
3 years ago
*/function isSymbol(value){return typeof value=='symbol'||isObjectLike(value)&&baseGetTag(value)==symbolTag;}/**
3 years ago
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
3 years ago
*/var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;/**
3 years ago
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
3 years ago
*/function isUndefined(value){return value===undefined$1;}/**
3 years ago
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
3 years ago
*/function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag;}/**
3 years ago
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
3 years ago
*/function isWeakSet(value){return isObjectLike(value)&&baseGetTag(value)==weakSetTag;}/**
3 years ago
* Checks if `value` is less than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
* @see _.gt
* @example
*
* _.lt(1, 3);
* // => true
*
* _.lt(3, 3);
* // => false
*
* _.lt(3, 1);
* // => false
3 years ago
*/var lt=createRelationalOperation(baseLt);/**
3 years ago
* Checks if `value` is less than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than or equal to
* `other`, else `false`.
* @see _.gte
* @example
*
* _.lte(1, 3);
* // => true
*
* _.lte(3, 3);
* // => true
*
* _.lte(3, 1);
* // => false
3 years ago
*/var lte=createRelationalOperation(function(value,other){return value<=other;});/**
3 years ago
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
3 years ago
*/function toArray(value){if(!value){return [];}if(isArrayLike(value)){return isString(value)?stringToArray(value):copyArray(value);}if(symIterator&&value[symIterator]){return iteratorToArray(value[symIterator]());}var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value);}/**
3 years ago
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
3 years ago
*/function toFinite(value){if(!value){return value===0?value:0;}value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER;}return value===value?value:0;}/**
3 years ago
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
3 years ago
*/function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0;}/**
3 years ago
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
3 years ago
*/function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0;}/**
3 years ago
* 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
3 years ago
*/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=baseTrim(value);var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value;}/**
3 years ago
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
3 years ago
*/function toPlainObject(value){return copyObject(value,keysIn(value));}/**
3 years ago
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
3 years ago
*/function toSafeInteger(value){return value?baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER):value===0?value:0;}/**
3 years ago
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
3 years ago
*/function toString(value){return value==null?'':baseToString(value);}/*------------------------------------------------------------------------*/ /**
3 years ago
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
3 years ago
*/var assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source)){copyObject(source,keys(source),object);return;}for(var key in source){if(hasOwnProperty.call(source,key)){assignValue(object,key,source[key]);}}});/**
3 years ago
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
3 years ago
*/var assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object);});/**
3 years ago
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
3 years ago
*/var assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer);});/**
3 years ago
* This method is like `_.assign` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignInWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
3 years ago
*/var assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer);});/**
3 years ago
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Array} Returns the picked values.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
3 years ago
*/var at=flatRest(baseAt);/**
3 years ago
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
3 years ago
*/function create(prototype,properties){var result=baseCreate(prototype);return properties==null?result:baseAssign(result,properties);}/**
3 years ago
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
3 years ago
*/var defaults=baseRest(function(object,sources){object=Object(object);var index=-1;var length=sources.length;var guard=length>2?sources[2]:undefined$1;if(guard&&isIterateeCall(sources[0],sources[1],guard)){length=1;}while(++index<length){var source=sources[index];var props=keysIn(source);var propsIndex=-1;var propsLength=props.length;while(++propsIndex<propsLength){var key=props[propsIndex];var value=object[key];if(value===undefined$1||eq(value,objectProto[key])&&!hasOwnProperty.call(object,key)){object[key]=source[key];}}}return object;});/**
3 years ago
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
3 years ago
*/var defaultsDeep=baseRest(function(args){args.push(undefined$1,customDefaultsMerge);return apply(mergeWith,undefined$1,args);});/**
3 years ago
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
3 years ago
*/function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn);}/**
3 years ago
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
3 years ago
*/function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight);}/**
3 years ago
* Iterates over own and inherited enumerable string keyed properties of an
* object and invokes `iteratee` for each property. The iteratee is invoked
* with three arguments: (value, key, object). Iteratee functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
3 years ago
*/function forIn(object,iteratee){return object==null?object:baseFor(object,getIteratee(iteratee,3),keysIn);}/**
3 years ago
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
3 years ago
*/function forInRight(object,iteratee){return object==null?object:baseForRight(object,getIteratee(iteratee,3),keysIn);}/**
3 years ago
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
3 years ago
*/function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3));}/**
3 years ago
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
3 years ago
*/function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3));}/**
3 years ago
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
3 years ago
*/function functions(object){return object==null?[]:baseFunctions(object,keys(object));}/**
3 years ago
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
3 years ago
*/function functionsIn(object){return object==null?[]:baseFunctions(object,keysIn(object));}/**
3 years ago
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
3 years ago
*/function get(object,path,defaultValue){var result=object==null?undefined$1:baseGet(object,path);return result===undefined$1?defaultValue:result;}/**
3 years ago
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
3 years ago
*/function has(object,path){return object!=null&&hasPath(object,path,baseHas);}/**
3 years ago
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
3 years ago
*/function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn);}/**
3 years ago
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
3 years ago
*/var invert=createInverter(function(result,value,key){if(value!=null&&typeof value.toString!='function'){value=nativeObjectToString.call(value);}result[value]=key;},constant(identity));/**
3 years ago
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
3 years ago
*/var invertBy=createInverter(function(result,value,key){if(value!=null&&typeof value.toString!='function'){value=nativeObjectToString.call(value);}if(hasOwnProperty.call(result,value)){result[value].push(key);}else {result[value]=[key];}},getIteratee);/**
3 years ago
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
3 years ago
*/var invoke=baseRest(baseInvoke);/**
3 years ago
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
3 years ago
*/function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}/**
3 years ago
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
3 years ago
*/function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,true):baseKeysIn(object);}/**
3 years ago
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
3 years ago
*/function mapKeys(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value);});return result;}/**
3 years ago
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
3 years ago
*/function mapValues(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object));});return result;}/**
3 years ago
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
3 years ago
*/var merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex);});/**
3 years ago
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
3 years ago
*/var mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer);});/**
3 years ago
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
3 years ago
*/var omit=flatRest(function(object,paths){var result={};if(object==null){return result;}var isDeep=false;paths=arrayMap(paths,function(path){path=castPath(path,object);isDeep||(isDeep=path.length>1);return path;});copyObject(object,getAllKeysIn(object),result);if(isDeep){result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone);}var length=paths.length;while(length--){baseUnset(result,paths[length]);}return result;});/**
3 years ago
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return truthy for. The predicate is invoked with two
* arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
3 years ago
*/function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)));}/**
3 years ago
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
3 years ago
*/var pick=flatRest(function(object,paths){return object==null?{}:basePick(object,paths);});/**
3 years ago
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
3 years ago
*/function pickBy(object,predicate){if(object==null){return {};}var props=arrayMap(getAllKeysIn(object),function(prop){return [prop];});predicate=getIteratee(predicate);return basePickBy(object,props,function(value,path){return predicate(value,path[0]);});}/**
3 years ago
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
3 years ago
*/function result(object,path,defaultValue){path=castPath(path,object);var index=-1,length=path.length;// Ensure the loop is entered when path is empty.
if(!length){length=1;object=undefined$1;}while(++index<length){var value=object==null?undefined$1:object[toKey(path[index])];if(value===undefined$1){index=length;value=defaultValue;}object=isFunction(value)?value.call(object):value;}return object;}/**
3 years ago
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
3 years ago
*/function set(object,path,value){return object==null?object:baseSet(object,path,value);}/**
3 years ago
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
3 years ago
*/function setWith(object,path,value,customizer){customizer=typeof customizer=='function'?customizer:undefined$1;return object==null?object:baseSet(object,path,value,customizer);}/**
3 years ago
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
3 years ago
*/var toPairs=createToPairs(keys);/**
3 years ago
* Creates an array of own and inherited enumerable string keyed-value pairs
* for `object` which can be consumed by `_.fromPairs`. If `object` is a map
* or set, its entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entriesIn
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairsIn(new Foo);
* // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
3 years ago
*/var toPairsIn=createToPairs(keysIn);/**
3 years ago
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
3 years ago
*/function transform(object,iteratee,accumulator){var isArr=isArray(object),isArrLike=isArr||isBuffer(object)||isTypedArray(object);iteratee=getIteratee(iteratee,4);if(accumulator==null){var Ctor=object&&object.constructor;if(isArrLike){accumulator=isArr?new Ctor():[];}else if(isObject(object)){accumulator=isFunction(Ctor)?baseCreate(getPrototype(object)):{};}else {accumulator={};}}(isArrLike?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object);});return accumulator;}/**
3 years ago
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
3 years ago
*/function unset(object,path){return object==null?true:baseUnset(object,path);}/**
3 years ago
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
3 years ago
*/function update(object,path,updater){return object==null?object:baseUpdate(object,path,castFunction(updater));}/**
3 years ago
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
3 years ago
*/function updateWith(object,path,updater,customizer){customizer=typeof customizer=='function'?customizer:undefined$1;return object==null?object:baseUpdate(object,path,castFunction(updater),customizer);}/**
3 years ago
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
3 years ago
*/function values(object){return object==null?[]:baseValues(object,keys(object));}/**
3 years ago
* Creates an array of the own and inherited enumerable string keyed property
* values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
3 years ago
*/function valuesIn(object){return object==null?[]:baseValues(object,keysIn(object));}/*------------------------------------------------------------------------*/ /**
3 years ago
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
3 years ago
*/function clamp(number,lower,upper){if(upper===undefined$1){upper=lower;lower=undefined$1;}if(upper!==undefined$1){upper=toNumber(upper);upper=upper===upper?upper:0;}if(lower!==undefined$1){lower=toNumber(lower);lower=lower===lower?lower:0;}return baseClamp(toNumber(number),lower,upper);}/**
3 years ago
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
3 years ago
*/function inRange(number,start,end){start=toFinite(start);if(end===undefined$1){end=start;start=0;}else {end=toFinite(end);}number=toNumber(number);return baseInRange(number,start,end);}/**
3 years ago
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
3 years ago
*/function random(lower,upper,floating){if(floating&&typeof floating!='boolean'&&isIterateeCall(lower,upper,floating)){upper=floating=undefined$1;}if(floating===undefined$1){if(typeof upper=='boolean'){floating=upper;upper=undefined$1;}else if(typeof lower=='boolean'){floating=lower;lower=undefined$1;}}if(lower===undefined$1&&upper===undefined$1){lower=0;upper=1;}else {lower=toFinite(lower);if(upper===undefined$1){upper=lower;lower=0;}else {upper=toFinite(upper);}}if(lower>upper){var temp=lower;lower=upper;upper=temp;}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat('1e-'+((rand+'').length-1))),upper);}return baseRandom(lower,upper);}/*------------------------------------------------------------------------*/ /**
3 years ago
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
3 years ago
*/var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return result+(index?capitalize(word):word);});/**
3 years ago
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
3 years ago
*/function capitalize(string){return upperFirst(toString(string).toLowerCase());}/**
3 years ago
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
3 years ago
*/function deburr(string){string=toString(string);return string&&string.replace(reLatin,deburrLetter).replace(reComboMark,'');}/**
3 years ago
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
3 years ago
*/function endsWith(string,target,position){string=toString(string);target=baseToString(target);var length=string.length;position=position===undefined$1?length:baseClamp(toInteger(position),0,length);var end=position;position-=target.length;return position>=0&&string.slice(position,end)==target;}/**
3 years ago
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, &amp; pebbles'
3 years ago
*/function escape(string){string=toString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string;}/**
3 years ago
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
3 years ago
*/function escapeRegExp(string){string=toString(string);return string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,'\\$&'):string;}/**
3 years ago
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
3 years ago
*/var kebabCase=createCompounder(function(result,word,index){return result+(index?'-':'')+word.toLowerCase();});/**
3 years ago
* Converts `string`, as space separated words, to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.lowerCase('--Foo-Bar--');
* // => 'foo bar'
*
* _.lowerCase('fooBar');
* // => 'foo bar'
*
* _.lowerCase('__FOO_BAR__');
* // => 'foo bar'
3 years ago
*/var lowerCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toLowerCase();});/**
3 years ago
* Converts the first character of `string` to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.lowerFirst('Fred');
* // => 'fred'
*
* _.lowerFirst('FRED');
* // => 'fRED'
3 years ago
*/var lowerFirst=createCaseFirst('toLowerCase');/**
3 years ago
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
3 years ago
*/function pad(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length){return string;}var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars);}/**
3 years ago
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
3 years ago
*/function padEnd(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength<length?string+createPadding(length-strLength,chars):string;}/**
3 years ago
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
3 years ago
*/function padStart(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength<length?createPadding(length-strLength,chars)+string:string;}/**
3 years ago
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
3 years ago
*/function parseInt(string,radix,guard){if(guard||radix==null){radix=0;}else if(radix){radix=+radix;}return nativeParseInt(toString(string).replace(reTrimStart,''),radix||0);}/**
3 years ago
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
3 years ago
*/function repeat(string,n,guard){if(guard?isIterateeCall(string,n,guard):n===undefined$1){n=1;}else {n=toInteger(n);}return baseRepeat(toString(string),n);}/**
3 years ago
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
3 years ago
*/function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2]);}/**
3 years ago
* Converts `string` to
* [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--FOO-BAR--');
* // => 'foo_bar'
3 years ago
*/var snakeCase=createCompounder(function(result,word,index){return result+(index?'_':'')+word.toLowerCase();});/**
3 years ago
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
3 years ago
*/function split(string,separator,limit){if(limit&&typeof limit!='number'&&isIterateeCall(string,separator,limit)){separator=limit=undefined$1;}limit=limit===undefined$1?MAX_ARRAY_LENGTH:limit>>>0;if(!limit){return [];}string=toString(string);if(string&&(typeof separator=='string'||separator!=null&&!isRegExp(separator))){separator=baseToString(separator);if(!separator&&hasUnicode(string)){return castSlice(stringToArray(string),0,limit);}}return string.split(separator,limit);}/**
3 years ago
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
3 years ago
*/var startCase=createCompounder(function(result,word,index){return result+(index?' ':'')+upperFirst(word);});/**
3 years ago
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
3 years ago
*/function startsWith(string,target,position){string=toString(string);position=position==null?0:baseClamp(toInteger(position),0,string.length);target=baseToString(target);return string.slice(position,position+target.length)==target;}/**
3 years ago
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b>&lt;script&gt;</b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
3 years ago
*/function template(string,options,guard){// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings=lodash.templateSettings;if(guard&&isIterateeCall(string,options,guard)){options=undefined$1;}string=toString(string);options=assignInWith({},options,settings,customDefaultsAssignIn);var imports=assignInWith({},options.imports,settings.imports,customDefaultsAssignIn),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys);var isEscaping,isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";// Compile the regexp to match each delimiter.
var reDelimiters=RegExp((options.escape||reNoMatch).source+'|'+interpolate.source+'|'+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+'|'+(options.evaluate||reNoMatch).source+'|$','g');// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL='//# sourceURL='+(hasOwnProperty.call(options,'sourceURL')?(options.sourceURL+'').replace(/\s/g,' '):'lodash.templateSources['+ ++templateCounter+']')+'\n';string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);// Escape characters that can't be included in string literals.
source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar);// Replace delimiters with snippets.
if(escapeValue){isEscaping=true;source+="' +\n__e("+escapeValue+") +\n'";}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '";}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'";}index=offset+match.length;// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;});source+="';\n";// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable=hasOwnProperty.call(options,'variable')&&options.variable;if(!variable){source='with (obj) {\n'+source+'\n}\n';}// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if(reForbiddenIdentifierChars.test(variable)){throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);}// Cleanup code by stripping empty strings.
source=(isEvaluating?source.replace(reEmptyStringLeading,''):source).replace(reEmptyStringMiddle,'$1').replace(reEmptyStringTrailing,'$1;');// Frame code as the function body.
source='function('+(variable||'obj')+') {\n'+(variable?'':'obj || (obj = {});\n')+"var __t, __p = ''"+(isEscaping?', __e = _.escape':'')+(isEvaluating?', __j = Array.prototype.join;\n'+"function print() { __p += __j.call(arguments, '') }\n":';\n')+source+'return __p\n}';var result=attempt(function(){return Function(importsKeys,sourceURL+'return '+source).apply(undefined$1,importsValues);});// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source=source;if(isError(result)){throw result;}return result;}/**
3 years ago
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
3 years ago
*/function toLower(value){return toString(value).toLowerCase();}/**
3 years ago
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
3 years ago
*/function toUpper(value){return toString(value).toUpperCase();}/**
3 years ago
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
3 years ago
*/function trim(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined$1)){return baseTrim(string);}if(!string||!(chars=baseToString(chars))){return string;}var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join('');}/**
3 years ago
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
3 years ago
*/function trimEnd(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined$1)){return string.slice(0,trimmedEndIndex(string)+1);}if(!string||!(chars=baseToString(chars))){return string;}var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join('');}/**
3 years ago
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
3 years ago
*/function trimStart(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined$1)){return string.replace(reTrimStart,'');}if(!string||!(chars=baseToString(chars))){return string;}var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join('');}/**
3 years ago
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
3 years ago
*/function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator='separator'in options?options.separator:separator;length='length'in options?toInteger(options.length):length;omission='omission'in options?baseToString(options.omission):omission;}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length;}if(length>=strLength){return string;}var end=length-stringSize(omission);if(end<1){return omission;}var result=strSymbols?castSlice(strSymbols,0,end).join(''):string.slice(0,end);if(separator===undefined$1){return result+omission;}if(strSymbols){end+=result.length-end;}if(isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;if(!separator.global){separator=RegExp(separator.source,toString(reFlags.exec(separator))+'g');}separator.lastIndex=0;while(match=separator.exec(substring)){var newEnd=match.index;}result=result.slice(0,newEnd===undefined$1?end:newEnd);}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);if(index>-1){result=result.slice(0,index);}}return result+omission;}/**
3 years ago
* The inverse of `_.escape`; this method converts the HTML entities
* `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, &amp; pebbles');
* // => 'fred, barney, & pebbles'
3 years ago
*/function unescape(string){string=toString(string);return string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string;}/**
3 years ago
* Converts `string`, as space separated words, to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.upperCase('--foo-bar');
* // => 'FOO BAR'
*
* _.upperCase('fooBar');
* // => 'FOO BAR'
*
* _.upperCase('__foo_bar__');
* // => 'FOO BAR'
3 years ago
*/var upperCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toUpperCase();});/**
3 years ago
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
3 years ago
*/var upperFirst=createCaseFirst('toUpperCase');/**
3 years ago
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
3 years ago
*/function words(string,pattern,guard){string=toString(string);pattern=guard?undefined$1:pattern;if(pattern===undefined$1){return hasUnicodeWord(string)?unicodeWords(string):asciiWords(string);}return string.match(pattern)||[];}/*------------------------------------------------------------------------*/ /**
3 years ago
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
3 years ago
*/var attempt=baseRest(function(func,args){try{return apply(func,undefined$1,args);}catch(e){return isError(e)?e:new Error(e);}});/**
3 years ago
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
3 years ago
*/var bindAll=flatRest(function(object,methodNames){arrayEach(methodNames,function(key){key=toKey(key);baseAssignValue(object,key,bind(object[key],object));});return object;});/**
3 years ago
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
3 years ago
*/function cond(pairs){var length=pairs==null?0:pairs.length,toIteratee=getIteratee();pairs=!length?[]:arrayMap(pairs,function(pair){if(typeof pair[1]!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return [toIteratee(pair[0]),pair[1]];});return baseRest(function(args){var index=-1;while(++index<length){var pair=pairs[index];if(apply(pair[0],this,args)){return apply(pair[1],this,args);}}});}/**
3 years ago
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
3 years ago
*/function conforms(source){return baseConforms(baseClone(source,CLONE_DEEP_FLAG));}/**
3 years ago
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
3 years ago
*/function constant(value){return function(){return value;};}/**
3 years ago
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
3 years ago
*/function defaultTo(value,defaultValue){return value==null||value!==value?defaultValue:value;}/**
3 years ago
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
3 years ago
*/var flow=createFlow();/**
3 years ago
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
3 years ago
*/var flowRight=createFlow(true);/**
3 years ago
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
3 years ago
*/function identity(value){return value;}/**
3 years ago
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
3 years ago
*/function iteratee(func){return baseIteratee(typeof func=='function'?func:baseClone(func,CLONE_DEEP_FLAG));}/**
3 years ago
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
3 years ago
*/function matches(source){return baseMatches(baseClone(source,CLONE_DEEP_FLAG));}/**
3 years ago
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
3 years ago
*/function matchesProperty(path,srcValue){return baseMatchesProperty(path,baseClone(srcValue,CLONE_DEEP_FLAG));}/**
3 years ago
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
3 years ago
*/var method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args);};});/**
3 years ago
* The opposite of `_.method`; this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var array = _.times(3, _.constant),
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
3 years ago
*/var methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args);};});/**
3 years ago
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
3 years ago
*/function mixin(object,source,options){var props=keys(source),methodNames=baseFunctions(source,props);if(options==null&&!(isObject(source)&&(methodNames.length||!props.length))){options=source;source=object;object=this;methodNames=baseFunctions(source,keys(source));}var chain=!(isObject(options)&&'chain'in options)||!!options.chain,isFunc=isFunction(object);arrayEach(methodNames,function(methodName){var func=source[methodName];object[methodName]=func;if(isFunc){object.prototype[methodName]=function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__),actions=result.__actions__=copyArray(this.__actions__);actions.push({'func':func,'args':arguments,'thisArg':object});result.__chain__=chainAll;return result;}return func.apply(object,arrayPush([this.value()],arguments));};}});return object;}/**
3 years ago
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
3 years ago
*/function noConflict(){if(root._===this){root._=oldDash;}return this;}/**
3 years ago
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
3 years ago
*/function noop(){// No operation performed.
}/**
3 years ago
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
3 years ago
*/function nthArg(n){n=toInteger(n);return baseRest(function(args){return baseNth(args,n);});}/**
3 years ago
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
3 years ago
*/var over=createOver(arrayMap);/**
3 years ago
* Creates a function that checks if **all** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overEvery([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => false
*
* func(NaN);
* // => false
3 years ago
*/var overEvery=createOver(arrayEvery);/**
3 years ago
* Creates a function that checks if **any** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overSome([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => true
*
* func(NaN);
* // => false
*
* var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
* var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
3 years ago
*/var overSome=createOver(arraySome);/**
3 years ago
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
3 years ago
*/function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path);}/**
3 years ago
* The opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
3 years ago
*/function propertyOf(object){return function(path){return object==null?undefined$1:baseGet(object,path);};}/**
3 years ago
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
3 years ago
*/var range=createRange();/**
3 years ago
* This method is like `_.range` except that it populates values in
* descending order.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.range
* @example
*
* _.rangeRight(4);
* // => [3, 2, 1, 0]
*
* _.rangeRight(-4);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 5);
* // => [4, 3, 2, 1]
*
* _.rangeRight(0, 20, 5);
* // => [15, 10, 5, 0]
*
* _.rangeRight(0, -4, -1);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 4, 0);
* // => [1, 1, 1]
*
* _.rangeRight(0);
* // => []
3 years ago
*/var rangeRight=createRange(true);/**
3 years ago
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
3 years ago
*/function stubArray(){return [];}/**
3 years ago
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
3 years ago
*/function stubFalse(){return false;}/**
3 years ago
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
3 years ago
*/function stubObject(){return {};}/**
3 years ago
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
3 years ago
*/function stubString(){return '';}/**
3 years ago
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
3 years ago
*/function stubTrue(){return true;}/**
3 years ago
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
3 years ago
*/function times(n,iteratee){n=toInteger(n);if(n<1||n>MAX_SAFE_INTEGER){return [];}var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee);n-=MAX_ARRAY_LENGTH;var result=baseTimes(length,iteratee);while(++index<n){iteratee(index);}return result;}/**
3 years ago
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
3 years ago
*/function toPath(value){if(isArray(value)){return arrayMap(value,toKey);}return isSymbol(value)?[value]:copyArray(stringToPath(toString(value)));}/**
3 years ago
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
3 years ago
*/function uniqueId(prefix){var id=++idCounter;return toString(prefix)+id;}/*------------------------------------------------------------------------*/ /**
3 years ago
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
3 years ago
*/var add=createMathOperation(function(augend,addend){return augend+addend;},0);/**
3 years ago
* Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
3 years ago
*/var ceil=createRound('ceil');/**
3 years ago
* Divide two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} dividend The first number in a division.
* @param {number} divisor The second number in a division.
* @returns {number} Returns the quotient.
* @example
*
* _.divide(6, 4);
* // => 1.5
3 years ago
*/var divide=createMathOperation(function(dividend,divisor){return dividend/divisor;},1);/**
3 years ago
* Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
*
* _.floor(4.006);
* // => 4
*
* _.floor(0.046, 2);
* // => 0.04
*
* _.floor(4060, -2);
* // => 4000
3 years ago
*/var floor=createRound('floor');/**
3 years ago
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
3 years ago
*/function max(array){return array&&array.length?baseExtremum(array,identity,baseGt):undefined$1;}/**
3 years ago
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
3 years ago
*/function maxBy(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee,2),baseGt):undefined$1;}/**
3 years ago
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
3 years ago
*/function mean(array){return baseMean(array,identity);}/**
3 years ago
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
3 years ago
*/function meanBy(array,iteratee){return baseMean(array,getIteratee(iteratee,2));}/**
3 years ago
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
3 years ago
*/function min(array){return array&&array.length?baseExtremum(array,identity,baseLt):undefined$1;}/**
3 years ago
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
3 years ago
*/function minBy(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee,2),baseLt):undefined$1;}/**
3 years ago
* Multiply two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} multiplier The first number in a multiplication.
* @param {number} multiplicand The second number in a multiplication.
* @returns {number} Returns the product.
* @example
*
* _.multiply(6, 4);
* // => 24
3 years ago
*/var multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand;},1);/**
3 years ago
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
3 years ago
*/var round=createRound('round');/**
3 years ago
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
3 years ago
*/var subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend;},0);/**
3 years ago
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
3 years ago
*/function sum(array){return array&&array.length?baseSum(array,identity):0;}/**
3 years ago
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
3 years ago
*/function sumBy(array,iteratee){return array&&array.length?baseSum(array,getIteratee(iteratee,2)):0;}/*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences.
lodash.after=after;lodash.ary=ary;lodash.assign=assign;lodash.assignIn=assignIn;lodash.assignInWith=assignInWith;lodash.assignWith=assignWith;lodash.at=at;lodash.before=before;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.castArray=castArray;lodash.chain=chain;lodash.chunk=chunk;lodash.compact=compact;lodash.concat=concat;lodash.cond=cond;lodash.conforms=conforms;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.curry=curry;lodash.curryRight=curryRight;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defaultsDeep=defaultsDeep;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.differenceBy=differenceBy;lodash.differenceWith=differenceWith;lodash.drop=drop;lodash.dropRight=dropRight;lodash.dropRightWhile=dropRightWhile;lodash.dropWhile=dropWhile;lodash.fill=fill;lodash.filter=filter;lodash.flatMap=flatMap;lodash.flatMapDeep=flatMapDeep;lodash.flatMapDepth=flatMapDepth;lodash.flatten=flatten;lodash.flattenDeep=flattenDeep;lodash.flattenDepth=flattenDepth;lodash.flip=flip;lodash.flow=flow;lodash.flowRight=flowRight;lodash.fromPairs=fromPairs;lodash.functions=functions;lodash.functionsIn=functionsIn;lodash.groupBy=groupBy;lodash.initial=initial;lodash.intersection=intersection;lodash.intersectionBy=intersectionBy;lodash.intersectionWith=intersectionWith;lodash.invert=invert;lodash.invertBy=invertBy;lodash.invokeMap=invokeMap;lodash.iteratee=iteratee;lodash.keyBy=keyBy;lodash.keys=keys;lodash.keysIn=keysIn;lodash.map=map;lodash.mapKeys=mapKeys;lodash.mapValues=mapValues;lodash.matches=matches;lodash.matchesProperty=matchesProperty;lodash.memoize=memoize;lodash.merge=merge;lodash.mergeWith=mergeWith;lodash.method=method;lodash.methodOf=methodOf;lodash.mixin=mixin;lodash.negate=negate;lodash.nthArg=nthArg;lodash.omit=omit;lodash.omitBy=omitBy;lodash.once=once;lodash.orderBy=orderBy;lodash.over=over;lodash.overArgs=overArgs;lodash.overEvery=overEvery;lodash.overSome=overSome;lodash.partial=partial;lodash.partialRight=partialRight;lodash.partition=partition;lodash.pick=pick;lodash.pickBy=pickBy;lodash.property=property;lodash.propertyOf=propertyOf;lodash.pull=pull;lodash.pullAll=pullAll;lodash.pullAllBy=pullAllBy;lodash.pullAllWith=pullAllWith;lodash.pullAt=pullAt;lodash.range=range;lodash.rangeRight=rangeRight;lodash.rearg=rearg;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.reverse=reverse;lodash.sampleSize=sampleSize;lodash.set=set;lodash.setWith=setWith;lodash.shuffle=shuffle;lodash.slice=slice;lodash.sortBy=sortBy;lodash.sortedUniq=sortedUniq;lodash.sortedUniqBy=sortedUniqBy;lodash.split=split;lodash.spread=spread;lodash.tail=tail;lodash.take=take;lodash.takeRight=takeRight;lodash.takeRightWhile=takeRightWhile;lodash.takeWhile=takeWhile;lodash.tap=tap;lodash.throttle=throttle;lodash.thru=thru;lodash.toArray=toArray;lodash.toPairs=toPairs;lodash.toPairsIn=toPairsIn;lodash.toPath=toPath;lodash.toPlainObject=toPlainObject;lodash.transform=transform;lodash.unary=unary;lodash.union=union;lodash.unionBy=unionBy;lodash.unionWith=unionWith;lodash.uniq=uniq;lodash.uniqBy=uniqBy;lodash.uniqWith=uniqWith;lodash.unset=unset;lodash.unzip=unzip;lodash.unzipWith=unzipWith;lodash.update=update;lodash.updateWith=updateWith;lodash.values=values;lodash.valuesIn=valuesIn;lodash.without=without;lodash.words=words;lodash.wrap=wrap;lodash.xor=xor;lodash.xorBy=xorBy;lodash.xorWith=xorWith;lodash.zip=zip;lodash.zipObject=zipObject;lodash.zipObjectDeep=zipObjectDeep;lodash.zipWith=zipWith;// Add aliases.
lodash.entries=toPairs;lodash.entriesIn=toPairsIn;lodash.extend=assignIn;lodash.extendWith=assignInWith;// Add methods to `lodash.prototype`.
mixin(lodash,lodash);/*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences.
lodash.add=add;lodash.attempt=attempt;lodash.camelCase=camelCase;lodash.capitalize=capitalize;lodash.ceil=ceil;lodash.clamp=clamp;lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.cloneDeepWith=cloneDeepWith;lodash.cloneWith=cloneWith;lodash.conformsTo=conformsTo;lodash.deburr=deburr;lodash.defaultTo=defaultTo;lodash.divide=divide;lodash.endsWith=endsWith;lodash.eq=eq;lodash.escape=escape;lodash.escapeRegExp=escapeRegExp;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.floor=floor;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.get=get;lodash.gt=gt;lodash.gte=gte;lodash.has=has;lodash.hasIn=hasIn;lodash.head=head;lodash.identity=identity;lodash.includes=includes;lodash.indexOf=indexOf;lodash.inRange=inRange;lodash.invoke=invoke;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isArrayBuffer=isArrayBuffer;lodash.isArrayLike=isArrayLike;lodash.isArrayLikeObject=isArrayLikeObject;lodash.isBoolean=isBoolean;lodash.isBuffer=isBuffer;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isEqualWith=isEqualWith;lodash.isError=isError;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isInteger=isInteger;lodash.isLength=isLength;lodash.isMap=isMap;lodash.isMatch=isMatch;lodash.isMatchWith=isMatchWith;lodash.isNaN=isNaN;lodash.isNative=isNative;lodash.isNil=isNil;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isObjectLike=isObjectLike;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isSafeInteger=isSafeInteger;lodash.isSet=isSet;lodash.isString=isString;lodash.isSymbol=isSymbol;lodash.isTypedArray=isTypedArray;lodash.isUndefined=isUndefined;lodash.isWeakMap=isWeakMap;lodash.isWeakSet=isWeakSet;lodash.join=join;lodash.kebabCase=kebabCase;lodash.last=last;lodash.lastIndexOf=lastIndexOf;lodash.lowerCase=lowerCase;lodash.lowerFirst=lowerFirst;lodash.lt=lt;lodash.lte=lte;lodash.max=max;lodash.maxBy=maxBy;lodash.mean=mean;lodash.meanBy=meanBy;lodash.min=min;lodash.minBy=minBy;lodash.stubArray=stubArray;lodash.stubFalse=stubFalse;lodash.stubObject=stubObject;lodash.stubString=stubString;lodash.stubTrue=stubTrue;lodash.multiply=multiply;lodash.nth=nth;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.pad=pad;lodash.padEnd=padEnd;lodash.padStart=padStart;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.repeat=repeat;lodash.replace=replace;lodash.result=result;lodash.round=round;lodash.runInContext=runInContext;lodash.sample=sample;lodash.size=size;lodash.snakeCase=snakeCase;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.sortedIndexBy=sortedIndexBy;lodash.sortedIndexOf=sortedIndexOf;lodash.sortedLastIndex=sortedLastIndex;lodash.sortedLastIndexBy=sortedLastIndexBy;lodash.sortedLastIndexOf=sortedLastIndexOf;lodash.startCase=startCase;lodash.startsWith=startsWith;lodash.subtract=subtract;lodash.sum=sum;lodash.sumBy=sumBy;lodash.template=template;lodash.times=times;lodash.toFinite=toFinite;lodash.toInteger=toInteger;lodash.toLength=toLength;lodash.toLower=toLower;lodash.toNumber=toNumber;lodash.toSafeInteger=toSafeInteger;lodash.toString=toString;lodash.toUpper=toUpper;lodash.trim=trim;lodash.trimEnd=trimEnd;lodash.trimStart=trimStart;lodash.truncate=truncate;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.upperCase=upperCase;lodash.upperFirst=upperFirst;// Add aliases.
lodash.each=forEach;lodash.eachRight=forEachRight;lodash.first=head;mixin(lodash,function(){var source={};baseForOwn(lodash,function(func,methodName){if(!hasOwnProperty.call(lodash.prototype,methodName)){source[methodName]=func;}});return source;}(),{'chain':false});/*------------------------------------------------------------------------*/ /**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/lodash.VERSION=VERSION;// Assign default placeholders.
arrayEach(['bind','bindKey','curry','curryRight','partial','partialRight'],function(methodName){lodash[methodName].placeholder=lodash;});// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop','take'],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){n=n===undefined$1?1:nativeMax(toInteger(n),0);var result=this.__filtered__&&!index?new LazyWrapper(this):this.clone();if(result.__filtered__){result.__takeCount__=nativeMin(n,result.__takeCount__);}else {result.__views__.push({'size':nativeMin(n,MAX_ARRAY_LENGTH),'type':methodName+(result.__dir__<0?'Right':'')});}return result;};LazyWrapper.prototype[methodName+'Right']=function(n){return this.reverse()[methodName](n).reverse();};});// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter','map','takeWhile'],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();result.__iteratees__.push({'iteratee':getIteratee(iteratee,3),'type':type});result.__filtered__=result.__filtered__||isFilter;return result;};});// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head','last'],function(methodName,index){var takeName='take'+(index?'Right':'');LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0];};});// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial','tail'],function(methodName,index){var dropName='drop'+(index?'':'Right');LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1);};});LazyWrapper.prototype.compact=function(){return this.filter(identity);};LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head();};LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate);};LazyWrapper.prototype.invokeMap=baseRest(function(path,args){if(typeof path=='function'){return new LazyWrapper(this);}return this.map(function(value){return baseInvoke(value,path,args);});});LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)));};LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;if(result.__filtered__&&(start>0||end<0)){return new LazyWrapper(result);}if(start<0){result=result.takeRight(-start);}else if(start){result=result.drop(start);}if(end!==undefined$1){end=toInteger(end);result=end<0?result.dropRight(-end):result.take(end-start);}return result;};LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse();};LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH);};// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?'take'+(methodName=='last'?'Right':''):methodName],retUnwrapped=isTaker||/^find/.test(methodName);if(!lodashFunc){return;}lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value);var interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result;};if(useLazy&&checkIteratee&&typeof iteratee=='function'&&iteratee.length!=1){// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy=useLazy=false;}var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);result.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined$1});return new LodashWrapper(result,chainAll);}if(isUnwrapped&&onlyLazy){return func.apply(this,args);}result=this.thru(interceptor);return isUnwrapped?isTaker?result.value()[0]:result.value():result;};});// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop','push','shift','sort','splice','unshift'],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?'tap':'thru',retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args);}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args);});};});// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+'';if(!hasOwnProperty.call(realNames,key)){realNames[key]=[];}realNames[key].push({'name':methodName,'func':lodashFunc});}});realNames[createHybrid(undefined$1,WRAP_BIND_KEY_FLAG).name]=[{'name':'wrapper','func':undefined$1}];// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone=lazyClone;LazyWrapper.prototype.reverse=lazyReverse;LazyWrapper.prototype.value=lazyValue;// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at=wrapperAt;lodash.prototype.chain=wrapperChain;lodash.prototype.commit=wrapperCommit;lodash.prototype.next=wrapperNext;lodash.prototype.plant=wrapperPlant;lodash.prototype.reverse=wrapperReverse;lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue;// Add lazy aliases.
lodash.prototype.first=lodash.prototype.head;if(symIterator){lodash.prototype[symIterator]=wrapperToIterator;}return lodash;};/*--------------------------------------------------------------------------*/ // Export lodash.
var _=runInContext();// Some AMD build optimizers, like r.js, check for condition patterns like:
if(freeModule){// Export for Node.js.
(freeModule.exports=_)._=_;// Export for CommonJS support.
freeExports._=_;}else {// Export to the global object.
root._=_;}}).call(commonjsGlobal);
});
const emptyTransaction = {
type: 'tx',
block: { firstLine: -1, lastLine: -1, block: '' },
blockLine: -1,
value: {
date: '',
payee: '',
expenselines: [],
},
};
/**
* formatTransaction converts a transaction object into the string
* representation which can be stored in the Ledger file.
*/
const formatTransaction = (tx, currencySymbol) => {
const joinedLines = tx.value.expenselines
.map((line, i) => {
if (!('account' in line)) {
return ` ; ${line.comment}`;
}
const currency = line.currency ? line.currency : currencySymbol;
const symb = line.reconcile ? line.reconcile : ' ';
const comment = line.comment ? ` ; ${line.comment}` : '';
return i !== tx.value.expenselines.length - 1
? ` ${symb} ${line.account} ${currency}${line.amount.toFixed(2)}${comment}`
: ` ${symb} ${line.account}${comment}`;
})
.join('\n');
return `\n${tx.value.date} ${tx.value.payee}\n${joinedLines}`;
};
3 years ago
/**
* getTotal returns the total value of the transaction. It assumes that all
* lines use the same currency. In a transaction, any 1 line may be left empty
* and can be inferred from the remainder. If muliple lines are empty, it will
* return a 0 value.
*/
const getTotal = (tx, defaultCurrency) => {
const currency = getCurrency(tx, defaultCurrency);
const total = getTotalAsNum(tx);
return currency + total.toFixed(2);
};
const getTotalAsNum = (tx) => {
// The total of an EnhancedTransaction is -1 * the last line that is not a comment
for (let i = tx.value.expenselines.length - 1; i >= 0; i--) {
const line = tx.value.expenselines[i];
if ('amount' in line) {
// This is the last line which is not a comment-only line
return -1 * line.amount;
3 years ago
}
}
// If we got here then there are no expenselines with an amount, which would not happen because of validation in the parser.
return 0;
3 years ago
};
/**
* getCurrency attempts to return the currency symbol used in this transaction.
* It will return the currency symbol used by the first expense line that has
* one. If no expense lines have a currency symbol, then the provided
* defaultCurrency value will be returned.
*/
const getCurrency = (tx, defaultCurrency) => {
for (let i = 0; i < tx.value.expenselines.length; i++) {
const line = tx.value.expenselines[i];
if ('currency' in line && line.currency) {
3 years ago
return line.currency;
}
}
return defaultCurrency;
};
/**
* firstDate returns the date of the earliest transaction.
*/
const firstDate = (txs) => txs.reduce((prev, tx) => {
const current = window.moment(tx.value.date);
return current.isSameOrBefore(prev) ? current : prev;
}, window.moment());
/**
* filterByAccount accepts an account name and attempts to match to
* transactions. Checks both account name an dealiased acocunt name.
*/
const filterByAccount = (account) => (tx) => lodash.some(tx.value.expenselines, (line) => ('account' in line && line.account.startsWith(account)) ||
('dealiasedAccount' in line &&
line.dealiasedAccount.startsWith(account)));
3 years ago
const filterByStartDate = (start) => (tx) => start.isSameOrBefore(window.moment(tx.value.date));
const filterByEndDate = (end) => (tx) => end.isSameOrAfter(window.moment(tx.value.date));
/**
* filterTransactions filters the provided transactions if _any_ of the provided
* filters match. To _and_ filters, apply this function sequentially.
*/
const filterTransactions = (txs, ...filters) => filters.length > 0 ? txs.filter((tx) => lodash.some(filters, (fn) => fn(tx))) : txs;
const dealiasAccount = (account, aliases) => {
const firstDelimeter = account.indexOf(':');
if (firstDelimeter > 0) {
const prefix = account.substring(0, firstDelimeter);
if (aliases.has(prefix)) {
return aliases.get(prefix) + account.substring(firstDelimeter);
}
}
return aliases.get(account) || account;
3 years ago
};
const makeAccountTree = (nodes, newValue, parent) => {
const parts = newValue.split(':');
const fullName = parent ? `${parent}:${parts[0]}` : parts[0];
let destNode = nodes.find((val) => val.account === parts[0]);
if (!destNode) {
destNode = { account: parts[0], id: fullName };
nodes.push(destNode);
}
if (parts.length > 1) {
if (!destNode.subRows) {
destNode.subRows = [];
}
const newParent = parent ? `${parent}:${parts[0]}` : parts[0];
makeAccountTree(destNode.subRows, parts.slice(1).join(':'), newParent);
}
};
const sortAccountTree = (nodes) => {
nodes.sort((a, b) => a.account.localeCompare(b.account, 'en', { numeric: true }));
nodes.forEach((node) => {
if (node.subRows) {
sortAccountTree(node.subRows);
}
});
};
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */var getOwnPropertySymbols=Object.getOwnPropertySymbols;var hasOwnProperty=Object.prototype.hasOwnProperty;var propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(val===null||val===undefined){throw new TypeError('Object.assign cannot be called with null or undefined');}return Object(val);}function shouldUseNative(){try{if(!Object.assign){return false;}// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1=new String('abc');// eslint-disable-line no-new-wrappers
test1[5]='de';if(Object.getOwnPropertyNames(test1)[0]==='5'){return false;}// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2={};for(var i=0;i<10;i++){test2['_'+String.fromCharCode(i)]=i;}var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n];});if(order2.join('')!=='0123456789'){return false;}// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3={};'abcdefghijklmnopqrst'.split('').forEach(function(letter){test3[letter]=letter;});if(Object.keys(Object.assign({},test3)).join('')!=='abcdefghijklmnopqrst'){return false;}return true;}catch(err){// We don't expect any of the above to throw, but better to be safe.
return false;}}var objectAssign=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty.call(from,key)){to[key]=from[key];}}if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]];}}}}return to;};
3 years ago
/** @license React v17.0.2
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
var react_production_min = createCommonjsModule(function (module, exports) {
var n=60103,p=60106;exports.Fragment=60107;exports.StrictMode=60108;exports.Profiler=60114;var q=60109,r=60110,t=60112;exports.Suspense=60113;var u=60115,v=60116;if("function"===typeof Symbol&&Symbol.for){var w=Symbol.for;n=w("react.element");p=w("react.portal");exports.Fragment=w("react.fragment");exports.StrictMode=w("react.strict_mode");exports.Profiler=w("react.profiler");q=w("react.provider");r=w("react.context");t=w("react.forward_ref");exports.Suspense=w("react.suspense");u=w("react.memo");v=w("react.lazy");}var x="function"===typeof Symbol&&Symbol.iterator;function y(a){if(null===a||"object"!==typeof a)return null;a=x&&a[x]||a["@@iterator"];return "function"===typeof a?a:null;}function z(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return "Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";}var A={isMounted:function(){return !1;},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B={};function C(a,b,c){this.props=a;this.context=b;this.refs=B;this.updater=c||A;}C.prototype.isReactComponent={};C.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error(z(85));this.updater.enqueueSetState(this,a,b,"setState");};C.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function D(){}D.prototype=C.prototype;function E(a,b,c){this.props=a;this.context=b;this.refs=B;this.updater=c||A;}var F=E.prototype=new D();F.constructor=E;objectAssign(F,C.prototype);F.isPureReactComponent=!0;var G={current:null},H=Object.prototype.hasOwnProperty,I={key:!0,ref:!0,__self:!0,__source:!0};function J(a,b,c){var e,d={},k=null,h=null;if(null!=b)for(e in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)H.call(b,e)&&!I.hasOwnProperty(e)&&(d[e]=b[e]);var g=arguments.length-2;if(1===g)d.children=c;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];d.children=f;}if(a&&a.defaultProps)for(e in g=a.defaultProps,g)void 0===d[e]&&(d[e]=g[e]);return {$$typeof:n,type:a,key:k,ref:h,props:d,_owner:G.current};}function K(a,b){return {$$typeof:n,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner};}function L(a){return "object"===typeof a&&null!==a&&a.$$typeof===n;}function escape(a){var b={"=":"=0",":":"=2"};return "$"+a.replace(/[=:]/g,function(a){return b[a];});}var M=/\/+/g;function N(a,b){return "object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36);}function O(a,b,c,e,d){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case"string":case"number":h=!0;break;case"object":switch(a.$$typeof){case n:case p:h=!0;}}if(h)return h=a,d=d(h),a=""===e?"."+N(h,0):e,Array.isArray(d)?(c="",null!=a&&(c=a.replace(M,"$&/")+"/"),O(d,b,c,"",function(a){return a;})):null!=d&&(L(d)&&(d=K(d,c+(!d.key||h&&h.key===d.key?"":(""+d.key).replace(M,"$&/")+"/")+a)),b.push(d)),1;h=0;e=""===e?".":e+":";if(Array.isArray(a))for(var g=0;g<a.length;g++){k=a[g];var f=e+N(k,g);h+=O(k,b,c,f,d);}else if(f=y(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=e+N(k,g++),h+=O(k,b,c,f,d);else if("object"===k)throw b=""+a,Error(z(31,"[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b));return h;}function P(a,b,c){if(null==a)return a;var e=[],d=0;O(a,e,"","",function(a){return b.call(c,a,d++);});return e;}function Q(a){if(-1===a._status){var b=a._result;b=b();a._status=0;a._result=b;b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b);},function(b){0===a._status&&(a._status=2,a._result=b);});}if(1===a._status)return a._result;throw a._result;}var R={current:null};function S(){var a=R.current;if(null===a)throw Error(z(321));return a;}var T={ReactCurrentDispatcher:R,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:G,IsSomeRendererActing:{current:!1},assign:objectAssign};exports.Children={map:P,forEach:function(a,b
3 years ago
});
/** @license React v17.0.2
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
3 years ago
*/
3 years ago
3 years ago
var react_development = createCommonjsModule(function (module, exports) {
{(function(){var _assign=objectAssign;// TODO: this is special because it gets imported during build.
var ReactVersion='17.0.2';// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE=0xeac7;var REACT_PORTAL_TYPE=0xeaca;exports.Fragment=0xeacb;exports.StrictMode=0xeacc;exports.Profiler=0xead2;var REACT_PROVIDER_TYPE=0xeacd;var REACT_CONTEXT_TYPE=0xeace;var REACT_FORWARD_REF_TYPE=0xead0;exports.Suspense=0xead1;var REACT_SUSPENSE_LIST_TYPE=0xead8;var REACT_MEMO_TYPE=0xead3;var REACT_LAZY_TYPE=0xead4;var REACT_BLOCK_TYPE=0xead9;var REACT_SERVER_BLOCK_TYPE=0xeada;var REACT_FUNDAMENTAL_TYPE=0xead5;var REACT_SCOPE_TYPE=0xead7;var REACT_OPAQUE_ID_TYPE=0xeae0;var REACT_DEBUG_TRACING_MODE_TYPE=0xeae1;var REACT_OFFSCREEN_TYPE=0xeae2;var REACT_LEGACY_HIDDEN_TYPE=0xeae3;if(typeof Symbol==='function'&&Symbol.for){var symbolFor=Symbol.for;REACT_ELEMENT_TYPE=symbolFor('react.element');REACT_PORTAL_TYPE=symbolFor('react.portal');exports.Fragment=symbolFor('react.fragment');exports.StrictMode=symbolFor('react.strict_mode');exports.Profiler=symbolFor('react.profiler');REACT_PROVIDER_TYPE=symbolFor('react.provider');REACT_CONTEXT_TYPE=symbolFor('react.context');REACT_FORWARD_REF_TYPE=symbolFor('react.forward_ref');exports.Suspense=symbolFor('react.suspense');REACT_SUSPENSE_LIST_TYPE=symbolFor('react.suspense_list');REACT_MEMO_TYPE=symbolFor('react.memo');REACT_LAZY_TYPE=symbolFor('react.lazy');REACT_BLOCK_TYPE=symbolFor('react.block');REACT_SERVER_BLOCK_TYPE=symbolFor('react.server.block');REACT_FUNDAMENTAL_TYPE=symbolFor('react.fundamental');REACT_SCOPE_TYPE=symbolFor('react.scope');REACT_OPAQUE_ID_TYPE=symbolFor('react.opaque.id');REACT_DEBUG_TRACING_MODE_TYPE=symbolFor('react.debug_trace_mode');REACT_OFFSCREEN_TYPE=symbolFor('react.offscreen');REACT_LEGACY_HIDDEN_TYPE=symbolFor('react.legacy_hidden');}var MAYBE_ITERATOR_SYMBOL=typeof Symbol==='function'&&Symbol.iterator;var FAUX_ITERATOR_SYMBOL='@@iterator';function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=='object'){return null;}var maybeIterator=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL];if(typeof maybeIterator==='function'){return maybeIterator;}return null;}/**
* Keeps track of the current dispatcher.
*/var ReactCurrentDispatcher={/**
* @internal
* @type {ReactComponent}
*/current:null};/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/var ReactCurrentBatchConfig={transition:0};/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/var ReactCurrentOwner={/**
* @internal
* @type {ReactComponent}
*/current:null};var ReactDebugCurrentFrame={};var currentExtraStackFrame=null;function setExtraStackFrame(stack){{currentExtraStackFrame=stack;}}{ReactDebugCurrentFrame.setExtraStackFrame=function(stack){{currentExtraStackFrame=stack;}};// Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack=null;ReactDebugCurrentFrame.getStackAddendum=function(){var stack='';// Add an extra top frame while an element is being validated
if(currentExtraStackFrame){stack+=currentExtraStackFrame;}// Delegate to the injected renderer-specific implementation
var impl=ReactDebugCurrentFrame.getCurrentStack;if(impl){stack+=impl()||'';}return stack;};}/**
* Used by act() to track whether you're inside an act() scope.
*/var IsSomeRendererActing={current:false};var ReactSharedInternals={ReactCurrentDispatcher:ReactCurrentDispatcher,ReactCurrentBatchConfig:ReactCurrentBatchConfig,ReactCurrentOwner:ReactCurrentOwner,IsSomeRendererActing:IsSomeRendererActing,// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign:_assign};{ReactSharedInternals.ReactDebugCurrentFrame=ReactDebugCurrentFrame;}// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format){{for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}printWarning('warn',format,args);}}function error(format){{for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}printWarning('error',format,args);}}function printWarning(level,format,args){// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;var stack=ReactDebugCurrentFrame.getStackAddendum();if(stack!==''){format+='%s';args=args.concat([stack]);}var argsWithFormat=args.map(function(item){return ''+item;});// Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: '+format);// We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level],console,argsWithFormat);}}var didWarnStateUpdateForUnmountedComponent={};function warnNoop(publicInstance,callerName){{var _constructor=publicInstance.constructor;var componentName=_constructor&&(_constructor.displayName||_constructor.name)||'ReactClass';var warningKey=componentName+"."+callerName;if(didWarnStateUpdateForUnmountedComponent[warningKey]){return;}error("Can't call %s on a component that is not yet mounted. "+'This is a no-op, but it might indicate a bug in your application. '+'Instead, assign to `this.state` directly or define a `state = {};` '+'class property with the desired state in the %s component.',callerName,componentName);didWarnStateUpdateForUnmountedComponent[warningKey]=true;}}/**
* This is the abstract API for an update queue.
*/var ReactNoopUpdateQueue={/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/isMounted:function(publicInstance){return false;},/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/enqueueForceUpdate:function(publicInstance,callback,callerName){warnNoop(publicInstance,'forceUpdate');},/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/enqueueReplaceState:function(publicInstance,completeState,callback,callerName){warnNoop(publicInstance,'replaceState');},/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/enqueueSetState:function(publicInstance,partialState,callback,callerName){warnNoop(publicInstance,'setState');}};var emptyObject={};{Object.freeze(emptyObject);}/**
* Base class helpers for the updating state of a component.
*/function Component(props,context,updater){this.props=props;this.context=context;// If a component has string refs, we will assign a different object later.
this.refs=emptyObject;// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater=updater||ReactNoopUpdateQueue;}Component.prototype.isReactComponent={};/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/Component.prototype.setState=function(partialState,callback){if(!(typeof partialState==='object'||typeof partialState==='function'||partialState==null)){{throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");}}this.updater.enqueueSetState(this,partialState,callback,'setState');};/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/Component.prototype.forceUpdate=function(callback){this.updater.enqueueForceUpdate(this,callback,'forceUpdate');};/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/{var deprecatedAPIs={isMounted:['isMounted','Instead, make sure to clean up subscriptions and pending requests in '+'componentWillUnmount to prevent memory leaks.'],replaceState:['replaceState','Refactor your code to use setState instead (see '+'https://github.com/facebook/react/issues/3236).']};var defineDeprecationWarning=function(methodName,info){Object.defineProperty(Component.prototype,methodName,{get:function(){warn('%s(...) is deprecated in plain JavaScript React classes. %s',info[0],info[1]);return undefined;}});};for(var fnName in deprecatedAPIs){if(deprecatedAPIs.hasOwnProperty(fnName)){defineDeprecationWarning(fnName,deprecatedAPIs[fnName]);}}}function ComponentDummy(){}ComponentDummy.prototype=Component.prototype;/**
* Convenience component with default shallow equality check for sCU.
*/function PureComponent(props,context,updater){this.props=props;this.context=context;// If a component has string refs, we will assign a different object later.
this.refs=emptyObject;this.updater=updater||ReactNoopUpdateQueue;}var pureComponentPrototype=PureComponent.prototype=new ComponentDummy();pureComponentPrototype.constructor=PureComponent;// Avoid an extra prototype jump for these methods.
_assign(pureComponentPrototype,Component.prototype);pureComponentPrototype.isPureReactComponent=true;// an immutable object with a single mutable value
function createRef(){var refObject={current:null};{Object.seal(refObject);}return refObject;}function getWrappedName(outerType,innerType,wrapperName){var functionName=innerType.displayName||innerType.name||'';return outerType.displayName||(functionName!==''?wrapperName+"("+functionName+")":wrapperName);}function getContextName(type){return type.displayName||'Context';}function getComponentName(type){if(type==null){// Host root, text node or just invalid type.
return null;}{if(typeof type.tag==='number'){error('Received an unexpected object in getComponentName(). '+'This is likely a bug in React. Please file an issue.');}}if(typeof type==='function'){return type.displayName||type.name||null;}if(typeof type==='string'){return type;}switch(type){case exports.Fragment:return 'Fragment';case REACT_PORTAL_TYPE:return 'Portal';case exports.Profiler:return 'Profiler';case exports.StrictMode:return 'StrictMode';case exports.Suspense:return 'Suspense';case REACT_SUSPENSE_LIST_TYPE:return 'SuspenseList';}if(typeof type==='object'){switch(type.$$typeof){case REACT_CONTEXT_TYPE:var context=type;return getContextName(context)+'.Consumer';case REACT_PROVIDER_TYPE:var provider=type;return getContextName(provider._context)+'.Provider';case REACT_FORWARD_REF_TYPE:return getWrappedName(type,type.render,'ForwardRef');case REACT_MEMO_TYPE:return getComponentName(type.type);case REACT_BLOCK_TYPE:return getComponentName(type._render);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{return getComponentName(init(payload));}catch(x){return null;}}}}return null;}var hasOwnProperty=Object.prototype.hasOwnProperty;var RESERVED_PROPS={key:true,ref:true,__self:true,__source:true};var specialPropKeyWarningShown,specialPropRefWarningShown,didWarnAboutStringRefs;{didWarnAboutStringRefs={};}function hasValidRef(config){{if(hasOwnProperty.call(config,'ref')){var getter=Object.getOwnPropertyDescriptor(config,'ref').get;if(getter&&getter.isReactWarning){return false;}}}return config.ref!==undefined;}function hasValidKey(config){{if(hasOwnProperty.call(config,'key')){var getter=Object.getOwnPropertyDescriptor(config,'key').get;if(getter&&getter.isReactWarning){return false;}}}return config.key!==undefined;}function defineKeyPropWarningGetter(props,displayName){var warnAboutAccessingKey=function(){{if(!specialPropKeyWarningShown){specialPropKeyWarningShown=true;error('%s: `key` is not a prop. Trying to access it will result '+'in `undefined` being returned. If you need to access the same '+'value within the child component, you should pass it as a different '+'prop. (https://reactjs.org/link/special-props)',displayName);}}};warnAboutAccessingKey.isReactWarning=true;Object.defineProperty(props,'key',{get:warnAboutAccessingKey,configurable:true});}function defineRefPropWarningGetter(props,displayName){var warnAboutAccessingRef=function(){{if(!specialPropRefWarningShown){specialPropRefWarningShown=true;error('%s: `ref` is not a prop. Trying to access it will result '+'in `undefined` being returned. If you need to access the same '+'value within the child component, you should pass it as a different '+'prop. (https://reactjs.org/link/special-props)',displayName);}}};warnAboutAccessingRef.isReactWarning=true;Object.defineProperty(props,'ref',{get:warnAboutAccessingRef,configurable:true});}function warnIfStringRefCannotBeAutoConverted(config){{if(typeof config.ref==='string'&&ReactCurrentOwner.current&&config.__self&&ReactCurrentOwner.current.stateNode!==config.__self){var componentName=getComponentName(ReactCurrentOwner.current.type);if(!didWarnAboutStringRefs[componentName]){error('Component "%s" contains the string ref "%s". '+'Support for string refs will be removed in a future major release. '+'This case cannot be automatically converted to an arrow function. '+'We ask you to manually fix this case by using useRef() or createRef() instead. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-string-ref',componentName,config.ref);didWarnAboutStringRefs[componentName]=true;}}}}/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/var ReactElement=function(type,key,ref,self,source,owner,props){var element={// This tag allows us to uniquely identify this as a React Element
$$typeof:REACT_ELEMENT_TYPE,// Built-in properties that belong on the element
type:type,key:key,ref:ref,props:props,// Record the component responsible for creating this element.
_owner:owner};{// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store={};// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store,'validated',{configurable:false,enumerable:false,writable:true,value:false});// self and source are DEV only properties.
Object.defineProperty(element,'_self',{configurable:false,enumerable:false,writable:false,value:self});// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element,'_source',{configurable:false,enumerable:false,writable:false,value:source});if(Object.freeze){Object.freeze(element.props);Object.freeze(element);}}return element;};/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/function createElement(type,config,children){var propName;// Reserved names are extracted
var props={};var key=null;var ref=null;var self=null;var source=null;if(config!=null){if(hasValidRef(config)){ref=config.ref;{warnIfStringRefCannotBeAutoConverted(config);}}if(hasValidKey(config)){key=''+config.key;}self=config.__self===undefined?null:config.__self;source=config.__source===undefined?null:config.__source;// Remaining properties are added to a new props object
for(propName in config){if(hasOwnProperty.call(config,propName)&&!RESERVED_PROPS.hasOwnProperty(propName)){props[propName]=config[propName];}}}// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength=arguments.length-2;if(childrenLength===1){props.children=children;}else if(childrenLength>1){var childArray=Array(childrenLength);for(var i=0;i<childrenLength;i++){childArray[i]=arguments[i+2];}{if(Object.freeze){Object.freeze(childArray);}}props.children=childArray;}// Resolve default props
if(type&&type.defaultProps){var defaultProps=type.defaultProps;for(propName in defaultProps){if(props[propName]===undefined){props[propName]=defaultProps[propName];}}}{if(key||ref){var displayName=typeof type==='function'?type.displayName||type.name||'Unknown':type;if(key){defineKeyPropWarningGetter(props,displayName);}if(ref){defineRefPropWarningGetter(props,displayName);}}}return ReactElement(type,key,ref,self,source,ReactCurrentOwner.current,props);}function cloneAndReplaceKey(oldElement,newKey){var newElement=ReactElement(oldElement.type,newKey,oldElement.ref,oldElement._self,oldElement._source,oldElement._owner,oldElement.props);return newElement;}/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/function cloneElement(element,config,children){if(!!(element===null||element===undefined)){{throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+element+".");}}var propName;// Original props are copied
var props=_assign({},element.props);// Reserved names are extracted
var key=element.key;var ref=element.ref;// Self is preserved since the owner is preserved.
var self=element._self;// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source=element._source;// Owner will be preserved, unless ref is overridden
var owner=element._owner;if(config!=null){if(hasValidRef(config)){// Silently steal the ref from the parent.
ref=config.ref;owner=ReactCurrentOwner.current;}if(hasValidKey(config)){key=''+config.key;}// Remaining properties override existing props
var defaultProps;if(element.type&&element.type.defaultProps){defaultProps=element.type.defaultProps;}for(propName in config){if(hasOwnProperty.call(config,propName)&&!RESERVED_PROPS.hasOwnProperty(propName)){if(config[propName]===undefined&&defaultProps!==undefined){// Resolve default props
props[propName]=defaultProps[propName];}else {props[propName]=config[propName];}}}}// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength=arguments.length-2;if(childrenLength===1){props.children=children;}else if(childrenLength>1){var childArray=Array(childrenLength);for(var i=0;i<childrenLength;i++){childArray[i]=arguments[i+2];}props.children=childArray;}return ReactElement(element.type,key,ref,self,source,owner,props);}/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/function isValidElement(object){return typeof object==='object'&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE;}var SEPARATOR='.';var SUBSEPARATOR=':';/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/function escape(key){var escapeRegex=/[=:]/g;var escaperLookup={'=':'=0',':':'=2'};var escapedString=key.replace(escapeRegex,function(match){return escaperLookup[match];});return '$'+escapedString;}/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/var didWarnAboutMaps=false;var userProvidedKeyEscapeRegex=/\/+/g;function escapeUserProvidedKey(text){return text.replace(userProvidedKeyEscapeRegex,'$&/');}/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/function getElementKey(element,index){// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if(typeof element==='object'&&element!==null&&element.key!=null){// Explicit key
return escape(''+element.key);}// Implicit key determined by the index in the set
return index.toString(36);}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;if(type==='undefined'||type==='boolean'){// All of the above are perceived as null.
children=null;}var invokeCallback=false;if(children===null){invokeCallback=true;}else {switch(type){case'string':case'number':invokeCallback=true;break;case'object':switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=true;}}}if(invokeCallback){var _child=children;var mappedChild=callback(_child);// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows:
var childKey=nameSoFar===''?SEPARATOR+getElementKey(_child,0):nameSoFar;if(Array.isArray(mappedChild)){var escapedChildKey='';if(childKey!=null){escapedChildKey=escapeUserProvidedKey(childKey)+'/';}mapIntoArray(mappedChild,array,escapedChildKey,'',function(c){return c;});}else if(mappedChild!=null){if(isValidElement(mappedChild)){mappedChild=cloneAndReplaceKey(mappedChild,// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix+(// $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key&&(!_child||_child.key!==mappedChild.key)?// $FlowFixMe Flow incorrectly thinks existing element's key can be a number
escapeUserProvidedKey(''+mappedChild.key)+'/':'')+childKey);}array.push(mappedChild);}return 1;}var child;var nextName;var subtreeCount=0;// Count of children found in the current subtree.
var nextNamePrefix=nameSoFar===''?SEPARATOR:nameSoFar+SUBSEPARATOR;if(Array.isArray(children)){for(var i=0;i<children.length;i++){child=children[i];nextName=nextNamePrefix+getElementKey(child,i);subtreeCount+=mapIntoArray(child,array,escapedPrefix,nextName,callback);}}else {var iteratorFn=getIteratorFn(children);if(typeof iteratorFn==='function'){var iterableChildren=children;{// Warn about using Maps as children
if(iteratorFn===iterableChildren.entries){if(!didWarnAboutMaps){warn('Using Maps as children is not supported. '+'Use an array of keyed ReactElements instead.');}didWarnAboutMaps=true;}}var iterator=iteratorFn.call(iterableChildren);var step;var ii=0;while(!(step=iterator.next()).done){child=step.value;nextName=nextNamePrefix+getElementKey(child,ii++);subtreeCount+=mapIntoArray(child,array,escapedPrefix,nextName,callback);}}else if(type==='object'){var childrenString=''+children;{{throw Error("Objects are not valid as a React child (found: "+(childrenString==='[object Object]'?'object with keys {'+Object.keys(children).join(', ')+'}':childrenString)+"). If you meant to render a collection of children, use an array instead.");}}}}return subtreeCount;}/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/function mapChildren(children,func,context){if(children==null){return children;}var result=[];var count=0;mapIntoArray(children,result,'','',function(child){return func.call(context,child,count++);});return result;}/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/function countChildren(children){var n=0;mapChildren(children,function(){n++;// Don't return anything
});return n;}/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/function forEachChildren(children,forEachFunc,forEachContext){mapChildren(children,function(){forEachFunc.apply(this,arguments);// Don't return anything.
},forEachContext);}/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/function toArray(children){return mapChildren(children,function(child){return child;})||[];}/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/function onlyChild(children){if(!isValidElement(children)){{throw Error("React.Children.only expected to receive a single React element child.");}}return children;}function createContext(defaultValue,calculateChangedBits){if(calculateChangedBits===undefined){calculateChangedBits=null;}else {{if(calculateChangedBits!==null&&typeof calculateChangedBits!=='function'){error('createContext: Expected the optional second argument to be a '+'function. Instead received: %s',calculateChangedBits);}}}var context={$$typeof:REACT_CONTEXT_TYPE,_calculateChangedBits:calculateChangedBits,// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue:defaultValue,_currentValue2:defaultValue,// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount:0,// These are circular
Provider:null,Consumer:null};context.Provider={$$typeof:REACT_PROVIDER_TYPE,_context:context};var hasWarnedAboutUsingNestedContextConsumers=false;var hasWarnedAboutUsingConsumerProvider=false;var hasWarnedAboutDisplayNameOnConsumer=false;{// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer={$$typeof:REACT_CONTEXT_TYPE,_context:context,_calculateChangedBits:context._calculateChangedBits};// $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer,{Provider:{get:function(){if(!hasWarnedAboutUsingConsumerProvider){hasWarnedAboutUsingConsumerProvider=true;error('Rendering <Context.Consumer.Provider> is not supported and will be removed in '+'a future major release. Did you mean to render <Context.Provider> instead?');}return context.Provider;},set:function(_Provider){context.Provider=_Provider;}},_currentValue:{get:function(){return context._currentValue;},set:function(_currentValue){context._currentValue=_currentValue;}},_currentValue2:{get:function(){return context._currentValue2;},set:function(_currentValue2){context._currentValue2=_currentValue2;}},_threadCount:{get:function(){return context._threadCount;},set:function(_threadCount){context._threadCount=_threadCount;}},Consumer:{get:function(){if(!hasWarnedAboutUsingNestedContextConsumers){hasWarnedAboutUsingNestedContextConsumers=true;error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in '+'a future major release. Did you mean to render <Context.Consumer> instead?');}return context.Consumer;}},displayName:{get:function(){return context.displayName;},set:function(displayName){if(!hasWarnedAboutDisplayNameOnConsumer){warn('Setting `displayName` on Context.Consumer has no effect. '+"You should set it directly on the context with Context.displayName = '%s'.",displayName);hasWarnedAboutDisplayNameOnConsumer=true;}}}});// $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer=Consumer;}{context._currentRenderer=null;context._currentRenderer2=null;}return context;}var Uninitialized=-1;var Pending=0;var Resolved=1;var Rejected=2;function lazyInitializer(payload){if(payload._status===Uninitialized){var ctor=payload._result;var thenable=ctor();// Transition to the next state.
var pending=payload;pending._status=Pending;pending._result=thenable;thenable.then(function(moduleObject){if(payload._status===Pending){var defaultExport=moduleObject.default;{if(defaultExport===undefined){error('lazy: Expected the result of a dynamic import() call. '+'Instead received: %s\n\nYour code should look like: \n '+// Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp'+"ort('./MyComponent'))",moduleObject);}}// Transition to the next state.
var resolved=payload;resolved._status=Resolved;resolved._result=defaultExport;}},function(error){if(payload._status===Pending){// Transition to the next state.
var rejected=payload;rejected._status=Rejected;rejected._result=error;}});}if(payload._status===Resolved){return payload._result;}else {throw payload._result;}}function lazy(ctor){var payload={// We use these fields to store the result.
_status:-1,_result:ctor};var lazyType={$$typeof:REACT_LAZY_TYPE,_payload:payload,_init:lazyInitializer};{// In production, this would just set it on the object.
var defaultProps;var propTypes;// $FlowFixMe
Object.defineProperties(lazyType,{defaultProps:{configurable:true,get:function(){return defaultProps;},set:function(newDefaultProps){error('React.lazy(...): It is not supported to assign `defaultProps` to '+'a lazy component import. Either specify them where the component '+'is defined, or create a wrapping component around it.');defaultProps=newDefaultProps;// Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType,'defaultProps',{enumerable:true});}},propTypes:{configurable:true,get:function(){return propTypes;},set:function(newPropTypes){error('React.lazy(...): It is not supported to assign `propTypes` to '+'a lazy component import. Either specify them where the component '+'is defined, or create a wrapping component around it.');propTypes=newPropTypes;// Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType,'propTypes',{enumerable:true});}}});}return lazyType;}function forwardRef(render){{if(render!=null&&render.$$typeof===REACT_MEMO_TYPE){error('forwardRef requires a render function but received a `memo` '+'component. Instead of forwardRef(memo(...)), use '+'memo(forwardRef(...)).');}else if(typeof render!=='function'){error('forwardRef requires a render function but was given %s.',render===null?'null':typeof render);}else {if(render.length!==0&&render.length!==2){error('forwardRef render functions accept exactly two parameters: props and ref. %s',render.length===1?'Did you forget to use the ref parameter?':'Any additional parameter will be undefined.');}}if(render!=null){if(render.defaultProps!=null||render.propTypes!=null){error('forwardRef render functions do not support propTypes or defaultProps. '+'Did you accidentally pass a React component?');}}}var elementType={$$typeof:REACT_FORWARD_REF_TYPE,render:render};{var ownName;Object.defineProperty(elementType,'displayName',{enumerable:false,configurable:true,get:function(){return ownName;},set:function(name){ownName=name;if(render.displayName==null){render.displayName=name;}}});}return elementType;}// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableScopeAPI=false;// Experimental Create Event Handle API.
function isValidElementType(type){if(typeof type==='string'||typeof type==='function'){return true;}// Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if(type===exports.Fragment||type===exports.Profiler||type===REACT_DEBUG_TRACING_MODE_TYPE||type===exports.StrictMode||type===exports.Suspense||type===REACT_SUSPENSE_LIST_TYPE||type===REACT_LEGACY_HIDDEN_TYPE||enableScopeAPI){return true;}if(typeof type==='object'&&type!==null){if(type.$$typeof===REACT_LAZY_TYPE||type.$$typeof===REACT_MEMO_TYPE||type.$$typeof===REACT_PROVIDER_TYPE||type.$$typeof===REACT_CONTEXT_TYPE||type.$$typeof===REACT_FORWARD_REF_TYPE||type.$$typeof===REACT_FUNDAMENTAL_TYPE||type.$$typeof===REACT_BLOCK_TYPE||type[0]===REACT_SERVER_BLOCK_TYPE){return true;}}return false;}function memo(type,compare){{if(!isValidElementType(type)){error('memo: The first argument must be a component. Instead '+'received: %s',type===null?'null':typeof type);}}var elementType={$$typeof:REACT_MEMO_TYPE,type:type,compare:compare===undefined?null:compare};{var ownName;Object.defineProperty(elementType,'displayName',{enumerable:false,configurable:true,get:function(){return ownName;},set:function(name){ownName=name;if(type.displayName==null){type.displayName=name;}}});}return elementType;}function resolveDispatcher(){var dispatcher=ReactCurrentDispatcher.current;if(!(dispatcher!==null)){{throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");}}return dispatcher;}function useContext(Context,unstable_observedBits){var dispatcher=resolveDispatcher();{if(unstable_observedBits!==undefined){error('useContext() second argument is reserved for future '+'use in React. Passing it is not supported. '+'You passed: %s.%s',unstable_observedBits,typeof unstable_observedBits==='number'&&Array.isArray(arguments[2])?'\n\nDid you call array.map(useContext)? '+'Calling Hooks inside a loop is not supported. '+'Learn more at https://reactjs.org/link/rules-of-hooks':'');}// TODO: add a more generic warning for invalid values.
if(Context._context!==undefined){var realContext=Context._context;// Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
if(realContext.Consumer===Context){error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be '+'removed in a future major release. Did you mean to call useContext(Context) instead?');}else if(realContext.Provider===Context){error('Calling useContext(Context.Provider) is not supported. '+'Did you mean to call useContext(Context) instead?');}}}return dispatcher.useContext(Context,unstable_observedBits);}function useState(initialState){var dispatcher=resolveDispatcher();return dispatcher.useState(initialState);}function useReducer(reducer,initialArg,init){var dispatcher=resolveDispatcher();return dispatcher.useReducer(reducer,initialArg,init);}function useRef(initialValue){var dispatcher=resolveDispatcher();return dispatcher.useRef(initialValue);}function useEffect(create,deps){var dispatcher=resolveDispatcher();return dispatcher.useEffect(create,deps);}function useLayoutEffect(create,deps){var dispatcher=resolveDispatcher();return dispatcher.useLayoutEffect(create,deps);}function useCallback(callback,deps){var dispatcher=resolveDispatcher();return dispatcher.useCallback(callback,deps);}function useMemo(create,deps){var dispatcher=resolveDispatcher();return dispatcher.useMemo(create,deps);}function useImperativeHandle(ref,create,deps){var dispatcher=resolveDispatcher();return dispatcher.useImperativeHandle(ref,create,deps);}function useDebugValue(value,formatterFn){{var dispatcher=resolveDispatcher();return dispatcher.useDebugValue(value,formatterFn);}}// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth=0;var prevLog;var prevInfo;var prevWarn;var prevError;var prevGroup;var prevGroupCollapsed;var prevGroupEnd;function disabledLog(){}disabledLog.__reactDisabledLog=true;function disableLogs(){{if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */prevLog=console.log;prevInfo=console.info;prevWarn=console.warn;prevError=console.error;prevGroup=console.group;prevGroupCollapsed=console.groupCollapsed;prevGroupEnd=console.groupEnd;// https://github.com/facebook/react/issues/19099
var props={configurable:true,enumerable:true,value:disabledLog,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{info:props,log:props,warn:props,error:props,group:props,groupCollapsed:props,groupEnd:props});/* eslint-enable react-internal/no-production-logging */}disabledDepth++;}}function reenableLogs(){{disabledDepth--;if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */var props={configurable:true,enumerable:true,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{log:_assign({},props,{value:prevLog}),info:_assign({},props,{value:prevInfo}),warn:_assign({},props,{value:prevWarn}),error:_assign({},props,{value:prevError}),group:_assign({},props,{value:prevGroup}),groupCollapsed:_assign({},props,{value:prevGroupCollapsed}),groupEnd:_assign({},props,{value:prevGroupEnd})});/* eslint-enable react-internal/no-production-logging */}if(disabledDepth<0){error('disabledDepth fell below zero. '+'This is a bug in React. Please file an issue.');}}}var ReactCurrentDispatcher$1=ReactSharedInternals.ReactCurrentDispatcher;var prefix;function describeBuiltInComponentFrame(name,source,ownerFn){{if(prefix===undefined){// Extract the VM specific prefix used by each line.
try{throw Error();}catch(x){var match=x.stack.trim().match(/\n( *(at )?)/);prefix=match&&match[1]||'';}}// We use the prefix to ensure our stacks line up with native stack frames.
return '\n'+prefix+name;}}var reentry=false;var componentFrameCache;{var PossiblyWeakMap=typeof WeakMap==='function'?WeakMap:Map;componentFrameCache=new PossiblyWeakMap();}function describeNativeComponentFrame(fn,construct){// If something asked for a stack inside a fake render, it should get ignored.
if(!fn||reentry){return '';}{var frame=componentFrameCache.get(fn);if(frame!==undefined){return frame;}}var control;reentry=true;var previousPrepareStackTrace=Error.prepareStackTrace;// $FlowFixMe It does accept undefined.
Error.prepareStackTrace=undefined;var previousDispatcher;{previousDispatcher=ReactCurrentDispatcher$1.current;// Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher$1.current=null;disableLogs();}try{// This should throw.
if(construct){// Something should be setting the props in the constructor.
var Fake=function(){throw Error();};// $FlowFixMe
Object.defineProperty(Fake.prototype,'props',{set:function(){// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();}});if(typeof Reflect==='object'&&Reflect.construct){// We construct a different control for this case to include any extra
// frames added by the construct call.
try{Reflect.construct(Fake,[]);}catch(x){control=x;}Reflect.construct(fn,[],Fake);}else {try{Fake.call();}catch(x){control=x;}fn.call(Fake.prototype);}}else {try{throw Error();}catch(x){control=x;}fn();}}catch(sample){// This is inlined manually because closure doesn't do it for us.
if(sample&&control&&typeof sample.stack==='string'){// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines=sample.stack.split('\n');var controlLines=control.stack.split('\n');var s=sampleLines.length-1;var c=controlLines.length-1;while(s>=1&&c>=0&&sampleLines[s]!==controlLines[c]){// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;}for(;s>=1&&c>=0;s--,c--){// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if(sampleLines[s]!==controlLines[c]){// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if(s!==1||c!==1){do{s--;c--;// We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if(c<0||sampleLines[s]!==controlLines[c]){// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame='\n'+sampleLines[s].replace(' at new ',' at ');{if(typeof fn==='function'){componentFrameCache.set(fn,_frame);}}// Return the line we found.
return _frame;}}while(s>=1&&c>=0);}break;}}}}finally{reentry=false;{ReactCurrentDispatcher$1.current=previousDispatcher;reenableLogs();}Error.prepareStackTrace=previousPrepareStackTrace;}// Fallback to just using the name if we couldn't make it throw.
var name=fn?fn.displayName||fn.name:'';var syntheticFrame=name?describeBuiltInComponentFrame(name):'';{if(typeof fn==='function'){componentFrameCache.set(fn,syntheticFrame);}}return syntheticFrame;}function describeFunctionComponentFrame(fn,source,ownerFn){{return describeNativeComponentFrame(fn,false);}}function shouldConstruct(Component){var prototype=Component.prototype;return !!(prototype&&prototype.isReactComponent);}function describeUnknownElementTypeFrameInDEV(type,source,ownerFn){if(type==null){return '';}if(typeof type==='function'){{return describeNativeComponentFrame(type,shouldConstruct(type));}}if(typeof type==='string'){return describeBuiltInComponentFrame(type);}switch(type){case exports.Suspense:return describeBuiltInComponentFrame('Suspense');case REACT_SUSPENSE_LIST_TYPE:return describeBuiltInComponentFrame('SuspenseList');}if(typeof type==='object'){switch(type.$$typeof){case REACT_FORWARD_REF_TYPE:return describeFunctionComponentFrame(type.render);case REACT_MEMO_TYPE:// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type,source,ownerFn);case REACT_BLOCK_TYPE:return describeFunctionComponentFrame(type._render);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload),source,ownerFn);}catch(x){}}}}return '';}var loggedTypeFailures={};var ReactDebugCurrentFrame$1=ReactSharedInternals.ReactDebugCurrentFrame;function setCurrentlyValidatingElement(element){{if(element){var owner=element._owner;var stack=describeUnknownElementTypeFrameInDEV(element.type,element._source,owner?owner.type:null);ReactDebugCurrentFrame$1.setExtraStackFrame(stack);}else {ReactDebugCurrentFrame$1.setExtraStackFrame(null);}}}function checkPropTypes(typeSpecs,values,location,componentName,element){{// $FlowFixMe This is okay but Flow doesn't know it.
var has=Function.call.bind(Object.prototype.hasOwnProperty);for(var typeSpecName in typeSpecs){if(has(typeSpecs,typeSpecName)){var error$1=void 0;// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try{// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if(typeof typeSpecs[typeSpecName]!=='function'){var err=Error((componentName||'React class')+': '+location+' type `'+typeSpecName+'` is invalid; '+'it must be a function, usually from the `prop-types` package, but received `'+typeof typeSpecs[typeSpecName]+'`.'+'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');err.name='Invariant Violation';throw err;}error$1=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');}catch(ex){error$1=ex;}if(error$1&&!(error$1 instanceof Error)){setCurrentlyValidatingElement(element);error('%s: type specification of %s'+' `%s` is invalid; the type checker '+'function must return `null` or an `Error` but returned a %s. '+'You may have forgotten to pass an argument to the type checker '+'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and '+'shape all require an argument).',componentName||'React class',location,typeSpecName,typeof error$1);setCurrentlyValidatingElement(null);}if(error$1 instanceof Error&&!(error$1.message in loggedTypeFailures)){// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message]=true;setCurrentlyValidatingElement(element);error('Failed %s type: %s',location,error$1.message);setCurrentlyValidatingElement(null);}}}}}function setCurrentlyValidatingElement$1(element){{if(element){var owner=element._owner;var stack=describeUnknownElementTypeFrameInDEV(element.type,element._source,owner?owner.type:null);setExtraStackFrame(stack);}else {setExtraStackFrame(null);}}}var propTypesMisspellWarningShown;{propTypesMisspellWarningShown=false;}function getDeclarationErrorAddendum(){if(ReactCurrentOwner.current){var name=getComponentName(ReactCurrentOwner.current.type);if(name){return '\n\nCheck the render method of `'+name+'`.';}}return '';}function getSourceInfoErrorAddendum(source){if(source!==undefined){var fileName=source.fileName.replace(/^.*[\\\/]/,'');var lineNumber=source.lineNumber;return '\n\nCheck your code at '+fileName+':'+lineNumber+'.';}return '';}function getSourceInfoErrorAddendumForProps(elementProps){if(elementProps!==null&&elementProps!==undefined){return getSourceInfoErrorAddendum(elementProps.__source);}return '';}/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/var ownerHasKeyUseWarning={};function getCurrentComponentErrorInfo(parentType){var info=getDeclarationErrorAddendum();if(!info){var parentName=typeof parentType==='string'?parentType:parentType.displayName||parentType.name;if(parentName){info="\n\nCheck the top-level render call using <"+parentName+">.";}}return info;}/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/function validateExplicitKey(element,parentType){if(!element._store||element._store.validated||element.key!=null){return;}element._store.validated=true;var currentComponentErrorInfo=getCurrentComponentErrorInfo(parentType);if(ownerHasKeyUseWarning[currentComponentErrorInfo]){return;}ownerHasKeyUseWarning[currentComponentErrorInfo]=true;// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner='';if(element&&element._owner&&element._owner!==ReactCurrentOwner.current){// Give the component that originally created this child.
childOwner=" It was passed a child from "+getComponentName(element._owner.type)+".";}{setCurrentlyValidatingElement$1(element);error('Each child in a list should have a unique "key" prop.'+'%s%s See https://reactjs.org/link/warning-keys for more information.',currentComponentErrorInfo,childOwner);setCurrentlyValidatingElement$1(null);}}/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/function validateChildKeys(node,parentType){if(typeof node!=='object'){return;}if(Array.isArray(node)){for(var i=0;i<node.length;i++){var child=node[i];if(isValidElement(child)){validateExplicitKey(child,parentType);}}}else if(isValidElement(node)){// This element was passed in a valid location.
if(node._store){node._store.validated=true;}}else if(node){var iteratorFn=getIteratorFn(node);if(typeof iteratorFn==='function'){// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if(iteratorFn!==node.entries){var iterator=iteratorFn.call(node);var step;while(!(step=iterator.next()).done){if(isValidElement(step.value)){validateExplicitKey(step.value,parentType);}}}}}}/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/function validatePropTypes(element){{var type=element.type;if(type===null||type===undefined||typeof type==='string'){return;}var propTypes;if(typeof type==='function'){propTypes=type.propTypes;}else if(typeof type==='object'&&(type.$$typeof===REACT_FORWARD_REF_TYPE||// Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof===REACT_MEMO_TYPE)){propTypes=type.propTypes;}else {return;}if(propTypes){// Intentionally inside to avoid triggering lazy initializers:
var name=getComponentName(type);checkPropTypes(propTypes,element.props,'prop',name,element);}else if(type.PropTypes!==undefined&&!propTypesMisspellWarningShown){propTypesMisspellWarningShown=true;// Intentionally inside to avoid triggering lazy initializers:
var _name=getComponentName(type);error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?',_name||'Unknown');}if(typeof type.getDefaultProps==='function'&&!type.getDefaultProps.isReactClassApproved){error('getDefaultProps is only used on classic React.createClass '+'definitions. Use a static property named `defaultProps` instead.');}}}/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/function validateFragmentProps(fragment){{var keys=Object.keys(fragment.props);for(var i=0;i<keys.length;i++){var key=keys[i];if(key!=='children'&&key!=='key'){setCurrentlyValidatingElement$1(fragment);error('Invalid prop `%s` supplied to `React.Fragment`. '+'React.Fragment can only have `key` and `children` props.',key);setCurrentlyValidatingElement$1(null);break;}}if(fragment.ref!==null){setCurrentlyValidatingElement$1(fragment);error('Invalid attribute `ref` supplied to `React.Fragment`.');setCurrentlyValidatingElement$1(null);}}}function createElementWithValidation(type,props,children){var validType=isValidElementType(type);// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if(!validType){var info='';if(type===undefined||typeof type==='object'&&type!==null&&Object.keys(type).length===0){info+=' You likely forgot to export your component from the file '+"it's defined in, or you might have mixed up default and named imports.";}var sourceInfo=getSourceInfoErrorAddendumForProps(props);if(sourceInfo){info+=sourceInfo;}else {info+=getDeclarationErrorAddendum();}var typeString;if(type===null){typeString='null';}else if(Array.isArray(type)){typeString='array';}else if(type!==undefined&&type.$$typeof===REACT_ELEMENT_TYPE){typeString="<"+(getComponentName(type.type)||'Unknown')+" />";info=' Did you accidentally export a JSX literal instead of a component?';}else {typeString=typeof type;}{error('React.createElement: type is invalid -- expected a string (for '+'built-in components) or a class/function (for composite '+'components) but got: %s.%s',typeString,info);}}var element=createElement.apply(this,arguments);// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if(element==null){return element;}// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if(validType){for(var i=2;i<arguments.length;i++){validateChildKeys(arguments[i],type);}}if(type===exports.Fragment){validateFragmentProps(element);}else {validatePropTypes(element);}return element;}var didWarnAboutDeprecatedCreateFactory=false;function createFactoryWithValidation(type){var validatedFactory=createElementWithValidation.bind(null,type);validatedFactory.type=type;{if(!didWarnAboutDeprecatedCreateFactory){didWarnAboutDeprecatedCreateFactory=true;warn('React.createFactory() is deprecated and will be removed in '+'a future major release. Consider using JSX '+'or use React.createElement() directly instead.');}// Legacy hook: remove it
Object.defineProperty(validatedFactory,'type',{enumerable:false,get:function(){warn('Factory.type is deprecated. Access the class directly '+'before passing it to createFactory.');Object.defineProperty(this,'type',{value:type});return type;}});}return validatedFactory;}function cloneElementWithValidation(element,props,children){var newElement=cloneElement.apply(this,arguments);for(var i=2;i<arguments.length;i++){validateChildKeys(arguments[i],newElement.type);}validatePropTypes(newElement);return newElement;}{try{var frozenObject=Object.freeze({});/* eslint-disable no-new */new Map([[frozenObject,null]]);new Set([frozenObject]);/* eslint-enable no-new */}catch(e){}}var createElement$1=createElementWithValidation;var cloneElement$1=cloneElementWithValidation;var createFactory=createFactoryWithValidation;var Children={map:mapChildren,forEach:forEachChildren,count:countChildren,toArray:toArray,only:onlyChild};exports.Children=Children;exports.Component=Component;exports.PureComponent=PureComponent;exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ReactSharedInternals;exports.cloneElement=cloneElement$1;exports.createContext=createContext;exports.createElement=createElement$1;exports.createFactory=createFactory;exports.createRef=createRef;exports.forwardRef=forwardRef;exports.isValidElement=isValidElement;exports.lazy=lazy;exports.memo=memo;exports.useCallback=useCallback;exports.useContext=useContext;exports.useDebugValue=useDebugValue;exports.useEffect=useEffect;exports.useImperativeHandle=useImperativeHandle;exports.useLayoutEffect=useLayoutEffect;exports.useMemo=useMemo;exports.useReducer=useReducer;exports.useRef=useRef;exports.useState=useState;exports.version=ReactVersion;})();}
});
var react = createCommonjsModule(function (module) {
{module.exports=react_development;}
3 years ago
});
3 years ago
/** @license React v16.13.1
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
3 years ago
var reactIs_development = createCommonjsModule(function (module, exports) {
{(function(){// nor polyfill, then a plain number is used for performance.
var hasSymbol=typeof Symbol==='function'&&Symbol.for;var REACT_ELEMENT_TYPE=hasSymbol?Symbol.for('react.element'):0xeac7;var REACT_PORTAL_TYPE=hasSymbol?Symbol.for('react.portal'):0xeaca;var REACT_FRAGMENT_TYPE=hasSymbol?Symbol.for('react.fragment'):0xeacb;var REACT_STRICT_MODE_TYPE=hasSymbol?Symbol.for('react.strict_mode'):0xeacc;var REACT_PROFILER_TYPE=hasSymbol?Symbol.for('react.profiler'):0xead2;var REACT_PROVIDER_TYPE=hasSymbol?Symbol.for('react.provider'):0xeacd;var REACT_CONTEXT_TYPE=hasSymbol?Symbol.for('react.context'):0xeace;// TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
// (unstable) APIs that have been removed. Can we remove the symbols?
var REACT_ASYNC_MODE_TYPE=hasSymbol?Symbol.for('react.async_mode'):0xeacf;var REACT_CONCURRENT_MODE_TYPE=hasSymbol?Symbol.for('react.concurrent_mode'):0xeacf;var REACT_FORWARD_REF_TYPE=hasSymbol?Symbol.for('react.forward_ref'):0xead0;var REACT_SUSPENSE_TYPE=hasSymbol?Symbol.for('react.suspense'):0xead1;var REACT_SUSPENSE_LIST_TYPE=hasSymbol?Symbol.for('react.suspense_list'):0xead8;var REACT_MEMO_TYPE=hasSymbol?Symbol.for('react.memo'):0xead3;var REACT_LAZY_TYPE=hasSymbol?Symbol.for('react.lazy'):0xead4;var REACT_BLOCK_TYPE=hasSymbol?Symbol.for('react.block'):0xead9;var REACT_FUNDAMENTAL_TYPE=hasSymbol?Symbol.for('react.fundamental'):0xead5;var REACT_RESPONDER_TYPE=hasSymbol?Symbol.for('react.responder'):0xead6;var REACT_SCOPE_TYPE=hasSymbol?Symbol.for('react.scope'):0xead7;function isValidElementType(type){return typeof type==='string'||typeof type==='function'||// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type===REACT_FRAGMENT_TYPE||type===REACT_CONCURRENT_MODE_TYPE||type===REACT_PROFILER_TYPE||type===REACT_STRICT_MODE_TYPE||type===REACT_SUSPENSE_TYPE||type===REACT_SUSPENSE_LIST_TYPE||typeof type==='object'&&type!==null&&(type.$$typeof===REACT_LAZY_TYPE||type.$$typeof===REACT_MEMO_TYPE||type.$$typeof===REACT_PROVIDER_TYPE||type.$$typeof===REACT_CONTEXT_TYPE||type.$$typeof===REACT_FORWARD_REF_TYPE||type.$$typeof===REACT_FUNDAMENTAL_TYPE||type.$$typeof===REACT_RESPONDER_TYPE||type.$$typeof===REACT_SCOPE_TYPE||type.$$typeof===REACT_BLOCK_TYPE);}function typeOf(object){if(typeof object==='object'&&object!==null){var $$typeof=object.$$typeof;switch($$typeof){case REACT_ELEMENT_TYPE:var type=object.type;switch(type){case REACT_ASYNC_MODE_TYPE:case REACT_CONCURRENT_MODE_TYPE:case REACT_FRAGMENT_TYPE:case REACT_PROFILER_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_SUSPENSE_TYPE:return type;default:var $$typeofType=type&&type.$$typeof;switch($$typeofType){case REACT_CONTEXT_TYPE:case REACT_FORWARD_REF_TYPE:case REACT_LAZY_TYPE:case REACT_MEMO_TYPE:case REACT_PROVIDER_TYPE:return $$typeofType;default:return $$typeof;}}case REACT_PORTAL_TYPE:return $$typeof;}}return undefined;}// AsyncMode is deprecated along with isAsyncMode
var AsyncMode=REACT_ASYNC_MODE_TYPE;var ConcurrentMode=REACT_CONCURRENT_MODE_TYPE;var ContextConsumer=REACT_CONTEXT_TYPE;var ContextProvider=REACT_PROVIDER_TYPE;var Element=REACT_ELEMENT_TYPE;var ForwardRef=REACT_FORWARD_REF_TYPE;var Fragment=REACT_FRAGMENT_TYPE;var Lazy=REACT_LAZY_TYPE;var Memo=REACT_MEMO_TYPE;var Portal=REACT_PORTAL_TYPE;var Profiler=REACT_PROFILER_TYPE;var StrictMode=REACT_STRICT_MODE_TYPE;var Suspense=REACT_SUSPENSE_TYPE;var hasWarnedAboutDeprecatedIsAsyncMode=false;// AsyncMode should be deprecated
function isAsyncMode(object){{if(!hasWarnedAboutDeprecatedIsAsyncMode){hasWarnedAboutDeprecatedIsAsyncMode=true;// Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, '+'and will be removed in React 17+. Update your code to use '+'ReactIs.isConcurrentMode() instead. It has the exact same API.');}}return isConcurrentMode(object)||typeOf(object)===REACT_ASYNC_MODE_TYPE;}function isConcurrentMode(object){return typeOf(object)===REACT_CONCURRENT_MODE_TYPE;}function isContextConsumer(object){return typeOf(object)===REACT_CONTEXT_TYPE;}function isContextProvider(object){return typeOf(object)===REACT_PROVIDER_TYPE;}function isElement(object){return typeof object==='object'&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE;}function isForwardRef(object){return typeOf(object)===REACT_FORWARD_REF_TYPE;}function isFragment(object){return typeOf(object)===REACT_FRAGMENT_TYPE;}function isLazy(object){return typeOf(object)===REACT_LAZY_TYPE;}function isMemo(object){return typeOf(object)===REACT_MEMO_TYPE;}function isPortal(object){return typeOf(object)===REACT_PORTAL_TYPE;}function isProfiler(object){return typeOf(object)===REACT_PROFILER_TYPE;}function isStrictMode(object){return typeOf(object)===REACT_STRICT_MODE_TYPE;}function isSuspense(object){return typeOf(object)===REACT_SUSPENSE_TYPE;}exports.AsyncMode=AsyncMode;exports.ConcurrentMode=ConcurrentMode;exports.ContextConsumer=ContextConsumer;exports.ContextProvider=ContextProvider;exports.Element=Element;exports.ForwardRef=ForwardRef;exports.Fragment=Fragment;exports.Lazy=Lazy;exports.Memo=Memo;exports.Portal=Portal;exports.Profiler=Profiler;exports.StrictMode=StrictMode;exports.Suspense=Suspense;exports.isAsyncMode=isAsyncMode;exports.isConcurrentMode=isConcurrentMode;exports.isContextConsumer=isContextConsumer;exports.isContextProvider=isContextProvider;exports.isElement=isElement;exports.isForwardRef=isForwardRef;exports.isFragment=isFragment;exports.isLazy=isLazy;exports.isMemo=isMemo;exports.isPortal=isPortal;exports.isProfiler=isProfiler;exports.isStrictMode=isStrictMode;exports.isSuspense=isSuspense;exports.isValidElementType=isValidElementType;exports.typeOf=typeOf;})();}
});
3 years ago
3 years ago
var reactIs = createCommonjsModule(function (module) {
{module.exports=reactIs_development;}
});
3 years ago
3 years ago
function stylis_min(W){function M(d,c,e,h,a){for(var m=0,b=0,v=0,n=0,q,g,x=0,K=0,k,u=k=q=0,l=0,r=0,I=0,t=0,B=e.length,J=B-1,y,f='',p='',F='',G='',C;l<B;){g=e.charCodeAt(l);l===J&&0!==b+n+v+m&&(0!==b&&(g=47===b?10:47),n=v=m=0,B++,J++);if(0===b+n+v+m){if(l===J&&(0<r&&(f=f.replace(N,'')),0<f.trim().length)){switch(g){case 32:case 9:case 59:case 13:case 10:break;default:f+=e.charAt(l);}g=59;}switch(g){case 123:f=f.trim();q=f.charCodeAt(0);k=1;for(t=++l;l<B;){switch(g=e.charCodeAt(l)){case 123:k++;break;case 125:k--;break;case 47:switch(g=e.charCodeAt(l+1)){case 42:case 47:a:{for(u=l+1;u<J;++u){switch(e.charCodeAt(u)){case 47:if(42===g&&42===e.charCodeAt(u-1)&&l+2!==u){l=u+1;break a;}break;case 10:if(47===g){l=u+1;break a;}}}l=u;}}break;case 91:g++;case 40:g++;case 34:case 39:for(;l++<J&&e.charCodeAt(l)!==g;){}}if(0===k)break;l++;}k=e.substring(t,l);0===q&&(q=(f=f.replace(ca,'').trim()).charCodeAt(0));switch(q){case 64:0<r&&(f=f.replace(N,''));g=f.charCodeAt(1);switch(g){case 100:case 109:case 115:case 45:r=c;break;default:r=O;}k=M(c,r,k,g,a+1);t=k.length;0<A&&(r=X(O,f,I),C=H(3,k,r,c,D,z,t,g,a,h),f=r.join(''),void 0!==C&&0===(t=(k=C.trim()).length)&&(g=0,k=''));if(0<t)switch(g){case 115:f=f.replace(da,ea);case 100:case 109:case 45:k=f+'{'+k+'}';break;case 107:f=f.replace(fa,'$1 $2');k=f+'{'+k+'}';k=1===w||2===w&&L('@'+k,3)?'@-webkit-'+k+'@'+k:'@'+k;break;default:k=f+k,112===h&&(k=(p+=k,''));}else k='';break;default:k=M(c,X(c,f,I),k,h,a+1);}F+=k;k=I=r=u=q=0;f='';g=e.charCodeAt(++l);break;case 125:case 59:f=(0<r?f.replace(N,''):f).trim();if(1<(t=f.length))switch(0===u&&(q=f.charCodeAt(0),45===q||96<q&&123>q)&&(t=(f=f.replace(' ',':')).length),0<A&&void 0!==(C=H(1,f,c,d,D,z,p.length,h,a,h))&&0===(t=(f=C.trim()).length)&&(f='\x00\x00'),q=f.charCodeAt(0),g=f.charCodeAt(1),q){case 0:break;case 64:if(105===g||99===g){G+=f+e.charAt(l);break;}default:58!==f.charCodeAt(t-1)&&(p+=P(f,q,g,f.charCodeAt(2)));}I=r=u=q=0;f='';g=e.charCodeAt(++l);}}switch(g){case 13:case 10:47===b?b=0:0===1+q&&107!==h&&0<f.length&&(r=1,f+='\x00');0<A*Y&&H(0,f,c,d,D,z,p.length,h,a,h);z=1;D++;break;case 59:case 125:if(0===b+n+v+m){z++;break;}default:z++;y=e.charAt(l);switch(g){case 9:case 32:if(0===n+m+b)switch(x){case 44:case 58:case 9:case 32:y='';break;default:32!==g&&(y=' ');}break;case 0:y='\\0';break;case 12:y='\\f';break;case 11:y='\\v';break;case 38:0===n+b+m&&(r=I=1,y='\f'+y);break;case 108:if(0===n+b+m+E&&0<u)switch(l-u){case 2:112===x&&58===e.charCodeAt(l-3)&&(E=x);case 8:111===K&&(E=K);}break;case 58:0===n+b+m&&(u=l);break;case 44:0===b+v+n+m&&(r=1,y+='\r');break;case 34:case 39:0===b&&(n=n===g?0:0===n?g:n);break;case 91:0===n+b+v&&m++;break;case 93:0===n+b+v&&m--;break;case 41:0===n+b+m&&v--;break;case 40:if(0===n+b+m){if(0===q)switch(2*x+3*K){case 533:break;default:q=1;}v++;}break;case 64:0===b+v+n+m+u+k&&(k=1);break;case 42:case 47:if(!(0<n+m+v))switch(b){case 0:switch(2*g+3*e.charCodeAt(l+1)){case 235:b=47;break;case 220:t=l,b=42;}break;case 42:47===g&&42===x&&t+2!==l&&(33===e.charCodeAt(t+2)&&(p+=e.substring(t,l+1)),y='',b=0);}}0===b&&(f+=y);}K=x;x=g;l++;}t=p.length;if(0<t){r=c;if(0<A&&(C=H(2,p,r,d,D,z,t,h,a,h),void 0!==C&&0===(p=C).length))return G+p+F;p=r.join(',')+'{'+p+'}';if(0!==w*E){2!==w||L(p,2)||(E=0);switch(E){case 111:p=p.replace(ha,':-moz-$1')+p;break;case 112:p=p.replace(Q,'::-webkit-input-$1')+p.replace(Q,'::-moz-$1')+p.replace(Q,':-ms-input-$1')+p;}E=0;}}return G+p+F;}function X(d,c,e){var h=c.trim().split(ia);c=h;var a=h.length,m=d.length;switch(m){case 0:case 1:var b=0;for(d=0===m?'':d[0]+' ';b<a;++b){c[b]=Z(d,c[b],e).trim();}break;default:var v=b=0;for(c=[];b<a;++b){for(var n=0;n<m;++n){c[v++]=Z(d[n]+' ',h[b],e).trim();}}}return c;}function Z(d,c,e){var h=c.charCodeAt(0);33>h&&(h=(c=c.trim()).charCodeAt(0));switch(h){case 38:return c.replace(F,'$1'+d.trim());case 58:return d.trim()+c.replace(F,'$1'+d.trim());default:if(0<1*e&&0<c.indexOf('\f'))return c.replace(F,(58===d.charCodeAt(0)?'':'$1')+d.trim());}return d+c;}function P(d,c,e,h){var a=d+';',m=2*c+3*e+4*h;if(944===m){d=a.indexOf(':',9)+1;var b=a.substring(d,a.length-1).tr
3 years ago
3 years ago
var unitlessKeys={animationIterationCount:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,// SVG-related properties
fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};var _default=unitlessKeys;
3 years ago
3 years ago
var unitless_cjs_dev = /*#__PURE__*/Object.defineProperty({
default: _default
}, '__esModule', {value: true});
3 years ago
3 years ago
var unitless_cjs = createCommonjsModule(function (module) {
{module.exports=unitless_cjs_dev;}
});
3 years ago
3 years ago
function memoize(fn){var cache={};return function(arg){if(cache[arg]===undefined)cache[arg]=fn(arg);return cache[arg];};}
3 years ago
3 years ago
var reactPropsRegex=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/;// https://esbench.com/bench/5bfee68a4cd7e6009ef61d23
var index=memoize(function(prop){return reactPropsRegex.test(prop)||prop.charCodeAt(0)===111/* o */&&prop.charCodeAt(1)===110/* n */&&prop.charCodeAt(2)<91;}/* Z+1 */);
3 years ago
3 years ago
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/var REACT_STATICS={childContextTypes:true,contextType:true,contextTypes:true,defaultProps:true,displayName:true,getDefaultProps:true,getDerivedStateFromError:true,getDerivedStateFromProps:true,mixins:true,propTypes:true,type:true};var KNOWN_STATICS={name:true,length:true,prototype:true,caller:true,callee:true,arguments:true,arity:true};var FORWARD_REF_STATICS={'$$typeof':true,render:true,defaultProps:true,displayName:true,propTypes:true};var MEMO_STATICS={'$$typeof':true,compare:true,defaultProps:true,displayName:true,propTypes:true,type:true};var TYPE_STATICS={};TYPE_STATICS[reactIs.ForwardRef]=FORWARD_REF_STATICS;TYPE_STATICS[reactIs.Memo]=MEMO_STATICS;function getStatics(component){// React v16.11 and below
if(reactIs.isMemo(component)){return MEMO_STATICS;}// React v16.12 and above
return TYPE_STATICS[component['$$typeof']]||REACT_STATICS;}var defineProperty=Object.defineProperty;var getOwnPropertyNames=Object.getOwnPropertyNames;var getOwnPropertySymbols$1=Object.getOwnPropertySymbols;var getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;var getPrototypeOf=Object.getPrototypeOf;var objectPrototype=Object.prototype;function hoistNonReactStatics(targetComponent,sourceComponent,blacklist){if(typeof sourceComponent!=='string'){// don't hoist over string (html) components
if(objectPrototype){var inheritedComponent=getPrototypeOf(sourceComponent);if(inheritedComponent&&inheritedComponent!==objectPrototype){hoistNonReactStatics(targetComponent,inheritedComponent,blacklist);}}var keys=getOwnPropertyNames(sourceComponent);if(getOwnPropertySymbols$1){keys=keys.concat(getOwnPropertySymbols$1(sourceComponent));}var targetStatics=getStatics(targetComponent);var sourceStatics=getStatics(sourceComponent);for(var i=0;i<keys.length;++i){var key=keys[i];if(!KNOWN_STATICS[key]&&!(blacklist&&blacklist[key])&&!(sourceStatics&&sourceStatics[key])&&!(targetStatics&&targetStatics[key])){var descriptor=getOwnPropertyDescriptor(sourceComponent,key);try{// Avoid failures from read-only properties
defineProperty(targetComponent,key,descriptor);}catch(e){}}}}return targetComponent;}var hoistNonReactStatics_cjs=hoistNonReactStatics;
3 years ago
3 years ago
function v(){return (v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);}return e;}).apply(this,arguments);}var g=function(e,t){for(var n=[e[0]],r=0,o=t.length;r<o;r+=1)n.push(t[r],e[r+1]);return n;},S=function(t){return null!==t&&"object"==typeof t&&"[object Object]"===(t.toString?t.toString():Object.prototype.toString.call(t))&&!reactIs.typeOf(t);},w=Object.freeze([]),E=Object.freeze({});function b(e){return "function"==typeof e;}function _(e){return "string"==typeof e&&e||e.displayName||e.name||"Component";}function N(e){return e&&"string"==typeof e.styledComponentId;}var A="undefined"!=typeof process&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",I="undefined"!=typeof window&&"HTMLElement"in window,P=Boolean("boolean"==typeof SC_DISABLE_SPEEDY?SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&""!==process.env.REACT_APP_SC_DISABLE_SPEEDY?"false"!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&process.env.REACT_APP_SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.SC_DISABLE_SPEEDY&&""!==process.env.SC_DISABLE_SPEEDY?"false"!==process.env.SC_DISABLE_SPEEDY&&process.env.SC_DISABLE_SPEEDY:"production"!==undefined),R={1:"Cannot create styled-component for component: %s.\n\n",2:"Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",3:"Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",4:"The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",5:"The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",6:"Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",7:'ThemeProvider: Please return an object from your "theme" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n',8:'ThemeProvider: Please make your "theme" prop an object.\n\n',9:"Missing document `<head>`\n\n",10:"Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",11:"_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",12:"It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",13:"%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",14:'ThemeProvider: "theme" prop is required.\n\n',15:"A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value
3 years ago
const InputWithIconWrapper = He.div `
position: relative;
3 years ago
`;
const InputWithIcon = He.input `
/* important required to override mobile stylesheet */
padding-left: 25px !important;
width: 100%;
3 years ago
`;
const InputIcon = He.i `
position: absolute;
display: block;
transform: translate(0, -50%);
top: 50%;
pointer-events: none;
width: 25px;
text-align: center;
font-style: normal;
3 years ago
`;
const CurrencyInputFormik = (props) => (react.createElement(CurrencyInput, { placeholder: props.placeholder || 'Amount', currencySymbol: props.currencySymbol, amount: props.field.value, setValue: (newValue) => {
props.form.setFieldValue(props.field.name, newValue);
}, disabled: props.disabled || false }));
const CurrencyInput = ({ placeholder, currencySymbol, amount, setValue, disabled, }) => (react.createElement(InputWithIconWrapper, null,
react.createElement(InputWithIcon, { placeholder: placeholder, disabled: disabled || false, type: "number", value: amount, onChange: (e) => setValue(e.target.value), onBlur: () => {
const val = amount.length > 0 ? parseFloat(amount).toFixed(2) : '';
setValue(val);
} }),
react.createElement(InputIcon, null, currencySymbol)));
3 years ago
3 years ago
/**
* Fuse.js v6.4.6 - Lightweight fuzzy-search (http://fusejs.io)
3 years ago
*
* Copyright (c) 2021 Kiro Risk (http://kiro.me)
* All Rights Reserved. Apache Software License 2.0
3 years ago
*
* http://www.apache.org/licenses/LICENSE-2.0
*/function isArray(value){return !Array.isArray?getTag(value)==='[object Array]':Array.isArray(value);}// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js
const INFINITY=1/0;function baseToString(value){// Exit early for strings to avoid a performance hit in some environments.
if(typeof value=='string'){return value;}let result=value+'';return result=='0'&&1/value==-INFINITY?'-0':result;}function toString(value){return value==null?'':baseToString(value);}function isString(value){return typeof value==='string';}function isNumber(value){return typeof value==='number';}// Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js
function isBoolean(value){return value===true||value===false||isObjectLike(value)&&getTag(value)=='[object Boolean]';}function isObject(value){return typeof value==='object';}// Checks if `value` is object-like.
function isObjectLike(value){return isObject(value)&&value!==null;}function isDefined(value){return value!==undefined&&value!==null;}function isBlank(value){return !value.trim().length;}// Gets the `toStringTag` of `value`.
// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js
function getTag(value){return value==null?value===undefined?'[object Undefined]':'[object Null]':Object.prototype.toString.call(value);}const EXTENDED_SEARCH_UNAVAILABLE='Extended search is not available';const INCORRECT_INDEX_TYPE="Incorrect 'index' type";const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY=key=>`Invalid value for key ${key}`;const PATTERN_LENGTH_TOO_LARGE=max=>`Pattern length exceeds max of ${max}.`;const MISSING_KEY_PROPERTY=name=>`Missing ${name} property in key`;const INVALID_KEY_WEIGHT_VALUE=key=>`Property 'weight' in key '${key}' must be a positive integer`;const hasOwn=Object.prototype.hasOwnProperty;class KeyStore{constructor(keys){this._keys=[];this._keyMap={};let totalWeight=0;keys.forEach(key=>{let obj=createKey(key);totalWeight+=obj.weight;this._keys.push(obj);this._keyMap[obj.id]=obj;totalWeight+=obj.weight;});// Normalize weights so that their sum is equal to 1
this._keys.forEach(key=>{key.weight/=totalWeight;});}get(keyId){return this._keyMap[keyId];}keys(){return this._keys;}toJSON(){return JSON.stringify(this._keys);}}function createKey(key){let path=null;let id=null;let src=null;let weight=1;if(isString(key)||isArray(key)){src=key;path=createKeyPath(key);id=createKeyId(key);}else {if(!hasOwn.call(key,'name')){throw new Error(MISSING_KEY_PROPERTY('name'));}const name=key.name;src=name;if(hasOwn.call(key,'weight')){weight=key.weight;if(weight<=0){throw new Error(INVALID_KEY_WEIGHT_VALUE(name));}}path=createKeyPath(name);id=createKeyId(name);}return {path,id,weight,src};}function createKeyPath(key){return isArray(key)?key:key.split('.');}function createKeyId(key){return isArray(key)?key.join('.'):key;}function get(obj,path){let list=[];let arr=false;const deepGet=(obj,path,index)=>{if(!isDefined(obj)){return;}if(!path[index]){// If there's no path left, we've arrived at the object we care about.
list.push(obj);}else {let key=path[index];const value=obj[key];if(!isDefined(value)){return;}// If we're at the last value in the path, and if it's a string/number/bool,
// add it to the list
if(index===path.length-1&&(isString(value)||isNumber(value)||isBoolean(value))){list.push(toString(value));}else if(isArray(value)){arr=true;// Search each item in the array.
for(let i=0,len=value.length;i<len;i+=1){deepGet(value[i],path,index+1);}}else if(path.length){// An object. Recurse further.
deepGet(value,path,index+1);}}};// Backwards compatibility (since path used to be a string)
deepGet(obj,isString(path)?path.split('.'):path,0);return arr?list:list[0];}const MatchOptions={// Whether the matches should be included in the result set. When `true`, each record in the result
// set will include the indices of the matched characters.
// These can consequently be used for highlighting purposes.
includeMatches:false,// When `true`, the matching function will continue to the end of a search pattern even if
// a perfect match has already been located in the string.
findAllMatches:false,// Minimum number of characters that must be matched before a result is considered a match
minMatchCharLength:1};const BasicOptions={// When `true`, the algorithm continues searching to the end of the input even if a perfect
// match is found before the end of the same input.
isCaseSensitive:false,// When true, the matching function will continue to the end of a search pattern even if
includeScore:false,// List of properties that will be searched. This also supports nested properties.
keys:[],// Whether to sort the result list, by score
shouldSort:true,// Default sort function: sort by ascending score, ascending index
sortFn:(a,b)=>a.score===b.score?a.idx<b.idx?-1:1:a.score<b.score?-1:1};const FuzzyOptions={// Approximately where in the text is the pattern expected to be found?
location:0,// At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
// (of both letters and location), a threshold of '1.0' would match anything.
threshold:0.6,// Determines how close the match must be to the fuzzy location (specified above).
// An exact letter match which is 'distance' characters away from the fuzzy location
// would score as a complete mismatch. A distance of '0' requires the match be at
// the exact location specified, a threshold of '1000' would require a perfect match
// to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
distance:100};const AdvancedOptions={// When `true`, it enables the use of unix-like search commands
useExtendedSearch:false,// The get function to use when fetching an object's properties.
// The default will search nested paths *ie foo.bar.baz*
getFn:get,// When `true`, search will ignore `location` and `distance`, so it won't matter
// where in the string the pattern appears.
// More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
ignoreLocation:false,// When `true`, the calculation for the relevance score (used for sorting) will
// ignore the field-length norm.
// More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
ignoreFieldNorm:false};var Config={...BasicOptions,...MatchOptions,...FuzzyOptions,...AdvancedOptions};const SPACE=/[^ ]+/g;// Field-length norm: the shorter the field, the higher the weight.
// Set to 3 decimals to reduce index size.
function norm(mantissa=3){const cache=new Map();const m=Math.pow(10,mantissa);return {get(value){const numTokens=value.match(SPACE).length;if(cache.has(numTokens)){return cache.get(numTokens);}const norm=1/Math.sqrt(numTokens);// In place of `toFixed(mantissa)`, for faster computation
const n=parseFloat(Math.round(norm*m)/m);cache.set(numTokens,n);return n;},clear(){cache.clear();}};}class FuseIndex{constructor({getFn=Config.getFn}={}){this.norm=norm(3);this.getFn=getFn;this.isCreated=false;this.setIndexRecords();}setSources(docs=[]){this.docs=docs;}setIndexRecords(records=[]){this.records=records;}setKeys(keys=[]){this.keys=keys;this._keysMap={};keys.forEach((key,idx)=>{this._keysMap[key.id]=idx;});}create(){if(this.isCreated||!this.docs.length){return;}this.isCreated=true;// List is Array<String>
if(isString(this.docs[0])){this.docs.forEach((doc,docIndex)=>{this._addString(doc,docIndex);});}else {// List is Array<Object>
this.docs.forEach((doc,docIndex)=>{this._addObject(doc,docIndex);});}this.norm.clear();}// Adds a doc to the end of the index
add(doc){const idx=this.size();if(isString(doc)){this._addString(doc,idx);}else {this._addObject(doc,idx);}}// Removes the doc at the specified index of the index
removeAt(idx){this.records.splice(idx,1);// Change ref index of every subsquent doc
for(let i=idx,len=this.size();i<len;i+=1){this.records[i].i-=1;}}getValueForItemAtKeyId(item,keyId){return item[this._keysMap[keyId]];}size(){return this.records.length;}_addString(doc,docIndex){if(!isDefined(doc)||isBlank(doc)){return;}let record={v:doc,i:docIndex,n:this.norm.get(doc)};this.records.push(record);}_addObject(doc,docIndex){let record={i:docIndex,$:{}};// Iterate over every key (i.e, path), and fetch the value at that key
this.keys.forEach((key,keyIndex)=>{// console.log(key)
let value=this.getFn(doc,key.path);if(!isDefined(value)){return;}if(isArray(value)){let subRecords=[];const stack=[{nestedArrIndex:-1,value}];while(stack.length){const{nestedArrIndex,value}=stack.pop();if(!isDefined(value)){continue;}if(isString(value)&&!isBlank(value)){let subRecord={v:value,i:nestedArrIndex,n:this.norm.get(value)};subRecords.push(subRecord);}else if(isArray(value)){value.forEach((item,k)=>{stack.push({nestedArrIndex:k,value:item});});}}record.$[keyIndex]=subRecords;}else if(!isBlank(value)){let subRecord={v:value,n:this.norm.get(value)};record.$[keyIndex]=subRecord;}});this.records.push(record);}toJSON(){return {keys:this.keys,records:this.records};}}function createIndex(keys,docs,{getFn=Config.getFn}={}){const myIndex=new FuseIndex({getFn});myIndex.setKeys(keys.map(createKey));myIndex.setSources(docs);myIndex.create();return myIndex;}function parseIndex(data,{getFn=Config.getFn}={}){const{keys,records}=data;const myIndex=new FuseIndex({getFn});myIndex.setKeys(keys);myIndex.setIndexRecords(records);return myIndex;}function computeScore(pattern,{errors=0,currentLocation=0,expectedLocation=0,distance=Config.distance,ignoreLocation=Config.ignoreLocation}={}){const accuracy=errors/pattern.length;if(ignoreLocation){return accuracy;}const proximity=Math.abs(expectedLocation-currentLocation);if(!distance){// Dodge divide by zero error.
return proximity?1.0:accuracy;}return accuracy+proximity/distance;}function convertMaskToIndices(matchmask=[],minMatchCharLength=Config.minMatchCharLength){let indices=[];let start=-1;let end=-1;let i=0;for(let len=matchmask.length;i<len;i+=1){let match=matchmask[i];if(match&&start===-1){start=i;}else if(!match&&start!==-1){end=i-1;if(end-start+1>=minMatchCharLength){indices.push([start,end]);}start=-1;}}// (i-1 - start) + 1 => i - start
if(matchmask[i-1]&&i-start>=minMatchCharLength){indices.push([start,i-1]);}return indices;}// Machine word size
const MAX_BITS=32;function search(text,pattern,patternAlphabet,{location=Config.location,distance=Config.distance,threshold=Config.threshold,findAllMatches=Config.findAllMatches,minMatchCharLength=Config.minMatchCharLength,includeMatches=Config.includeMatches,ignoreLocation=Config.ignoreLocation}={}){if(pattern.length>MAX_BITS){throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS));}const patternLen=pattern.length;// Set starting location at beginning text and initialize the alphabet.
const textLen=text.length;// Handle the case when location > text.length
const expectedLocation=Math.max(0,Math.min(location,textLen));// Highest score beyond which we give up.
let currentThreshold=threshold;// Is there a nearby exact match? (speedup)
let bestLocation=expectedLocation;// Performance: only computer matches when the minMatchCharLength > 1
// OR if `includeMatches` is true.
const computeMatches=minMatchCharLength>1||includeMatches;// A mask of the matches, used for building the indices
const matchMask=computeMatches?Array(textLen):[];let index;// Get all exact matches, here for speed up
while((index=text.indexOf(pattern,bestLocation))>-1){let score=computeScore(pattern,{currentLocation:index,expectedLocation,distance,ignoreLocation});currentThreshold=Math.min(score,currentThreshold);bestLocation=index+patternLen;if(computeMatches){let i=0;while(i<patternLen){matchMask[index+i]=1;i+=1;}}}// Reset the best location
bestLocation=-1;let lastBitArr=[];let finalScore=1;let binMax=patternLen+textLen;const mask=1<<patternLen-1;for(let i=0;i<patternLen;i+=1){// Scan for the best match; each iteration allows for one more error.
// Run a binary search to determine how far from the match location we can stray
// at this error level.
let binMin=0;let binMid=binMax;while(binMin<binMid){const score=computeScore(pattern,{errors:i,currentLocation:expectedLocation+binMid,expectedLocation,distance,ignoreLocation});if(score<=currentThreshold){binMin=binMid;}else {binMax=binMid;}binMid=Math.floor((binMax-binMin)/2+binMin);}// Use the result from this iteration as the maximum for the next.
binMax=binMid;let start=Math.max(1,expectedLocation-binMid+1);let finish=findAllMatches?textLen:Math.min(expectedLocation+binMid,textLen)+patternLen;// Initialize the bit array
let bitArr=Array(finish+2);bitArr[finish+1]=(1<<i)-1;for(let j=finish;j>=start;j-=1){let currentLocation=j-1;let charMatch=patternAlphabet[text.charAt(currentLocation)];if(computeMatches){// Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)
matchMask[currentLocation]=+!!charMatch;}// First pass: exact match
bitArr[j]=(bitArr[j+1]<<1|1)&charMatch;// Subsequent passes: fuzzy match
if(i){bitArr[j]|=(lastBitArr[j+1]|lastBitArr[j])<<1|1|lastBitArr[j+1];}if(bitArr[j]&mask){finalScore=computeScore(pattern,{errors:i,currentLocation,expectedLocation,distance,ignoreLocation});// This match will almost certainly be better than any existing match.
// But check anyway.
if(finalScore<=currentThreshold){// Indeed it is
currentThreshold=finalScore;bestLocation=currentLocation;// Already passed `loc`, downhill from here on in.
if(bestLocation<=expectedLocation){break;}// When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.
start=Math.max(1,2*expectedLocation-bestLocation);}}}// No hope for a (better) match at greater error levels.
const score=computeScore(pattern,{errors:i+1,currentLocation:expectedLocation,expectedLocation,distance,ignoreLocation});if(score>currentThreshold){break;}lastBitArr=bitArr;}const result={isMatch:bestLocation>=0,// Count exact matches (those with a score of 0) to be "almost" exact
score:Math.max(0.001,finalScore)};if(computeMatches){const indices=convertMaskToIndices(matchMask,minMatchCharLength);if(!indices.length){result.isMatch=false;}else if(includeMatches){result.indices=indices;}}return result;}function createPatternAlphabet(pattern){let mask={};for(let i=0,len=pattern.length;i<len;i+=1){const char=pattern.charAt(i);mask[char]=(mask[char]||0)|1<<len-i-1;}return mask;}class BitapSearch{constructor(pattern,{location=Config.location,threshold=Config.threshold,distance=Config.distance,includeMatches=Config.includeMatches,findAllMatches=Config.findAllMatches,minMatchCharLength=Config.minMatchCharLength,isCaseSensitive=Config.isCaseSensitive,ignoreLocation=Config.ignoreLocation}={}){this.options={location,threshold,distance,includeMatches,findAllMatches,minMatchCharLength,isCaseSensitive,ignoreLocation};this.pattern=isCaseSensitive?pattern:pattern.toLowerCase();this.chunks=[];if(!this.pattern.length){return;}const addChunk=(pattern,startIndex)=>{this.chunks.push({pattern,alphabet:createPatternAlphabet(pattern),startIndex});};const len=this.pattern.length;if(len>MAX_BITS){let i=0;const remainder=len%MAX_BITS;const end=len-remainder;while(i<end){addChunk(this.pattern.substr(i,MAX_BITS),i);i+=MAX_BITS;}if(remainder){const startIndex=len-MAX_BITS;addChunk(this.pattern.substr(startIndex),startIndex);}}else {addChunk(this.pattern,0);}}searchIn(text){const{isCaseSensitive,includeMatches}=this.options;if(!isCaseSensitive){text=text.toLowerCase();}// Exact match
if(this.pattern===text){let result={isMatch:true,score:0};if(includeMatches){result.indices=[[0,text.length-1]];}return result;}// Otherwise, use Bitap algorithm
const{location,distance,threshold,findAllMatches,minMatchCharLength,ignoreLocation}=this.options;let allIndices=[];let totalScore=0;let hasMatches=false;this.chunks.forEach(({pattern,alphabet,startIndex})=>{const{isMatch,score,indices}=search(text,pattern,alphabet,{location:location+startIndex,distance,threshold,findAllMatches,minMatchCharLength,includeMatches,ignoreLocation});if(isMatch){hasMatches=true;}totalScore+=score;if(isMatch&&indices){allIndices=[...allIndices,...indices];}});let result={isMatch:hasMatches,score:hasMatches?totalScore/this.chunks.length:1};if(hasMatches&&includeMatches){result.indices=allIndices;}return result;}}class BaseMatch{constructor(pattern){this.pattern=pattern;}static isMultiMatch(pattern){return getMatch(pattern,this.multiRegex);}static isSingleMatch(pattern){return getMatch(pattern,this.singleRegex);}search(){}}function getMatch(pattern,exp){const matches=pattern.match(exp);return matches?matches[1]:null;}// Token: 'file
class ExactMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'exact';}static get multiRegex(){return /^="(.*)"$/;}static get singleRegex(){return /^=(.*)$/;}search(text){const isMatch=text===this.pattern;return {isMatch,score:isMatch?0:1,indices:[0,this.pattern.length-1]};}}// Token: !fire
class InverseExactMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'inverse-exact';}static get multiRegex(){return /^!"(.*)"$/;}static get singleRegex(){return /^!(.*)$/;}search(text){const index=text.indexOf(this.pattern);const isMatch=index===-1;return {isMatch,score:isMatch?0:1,indices:[0,text.length-1]};}}// Token: ^file
class PrefixExactMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'prefix-exact';}static get multiRegex(){return /^\^"(.*)"$/;}static get singleRegex(){return /^\^(.*)$/;}search(text){const isMatch=text.startsWith(this.pattern);return {isMatch,score:isMatch?0:1,indices:[0,this.pattern.length-1]};}}// Token: !^fire
class InversePrefixExactMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'inverse-prefix-exact';}static get multiRegex(){return /^!\^"(.*)"$/;}static get singleRegex(){return /^!\^(.*)$/;}search(text){const isMatch=!text.startsWith(this.pattern);return {isMatch,score:isMatch?0:1,indices:[0,text.length-1]};}}// Token: .file$
class SuffixExactMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'suffix-exact';}static get multiRegex(){return /^"(.*)"\$$/;}static get singleRegex(){return /^(.*)\$$/;}search(text){const isMatch=text.endsWith(this.pattern);return {isMatch,score:isMatch?0:1,indices:[text.length-this.pattern.length,text.length-1]};}}// Token: !.file$
class InverseSuffixExactMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'inverse-suffix-exact';}static get multiRegex(){return /^!"(.*)"\$$/;}static get singleRegex(){return /^!(.*)\$$/;}search(text){const isMatch=!text.endsWith(this.pattern);return {isMatch,score:isMatch?0:1,indices:[0,text.length-1]};}}class FuzzyMatch extends BaseMatch{constructor(pattern,{location=Config.location,threshold=Config.threshold,distance=Config.distance,includeMatches=Config.includeMatches,findAllMatches=Config.findAllMatches,minMatchCharLength=Config.minMatchCharLength,isCaseSensitive=Config.isCaseSensitive,ignoreLocation=Config.ignoreLocation}={}){super(pattern);this._bitapSearch=new BitapSearch(pattern,{location,threshold,distance,includeMatches,findAllMatches,minMatchCharLength,isCaseSensitive,ignoreLocation});}static get type(){return 'fuzzy';}static get multiRegex(){return /^"(.*)"$/;}static get singleRegex(){return /^(.*)$/;}search(text){return this._bitapSearch.searchIn(text);}}// Token: 'file
class IncludeMatch extends BaseMatch{constructor(pattern){super(pattern);}static get type(){return 'include';}static get multiRegex(){return /^'"(.*)"$/;}static get singleRegex(){return /^'(.*)$/;}search(text){let location=0;let index;const indices=[];const patternLen=this.pattern.length;// Get all exact matches
while((index=text.indexOf(this.pattern,location))>-1){location=index+patternLen;indices.push([index,location-1]);}const isMatch=!!indices.length;return {isMatch,score:isMatch?0:1,indices};}}// ❗Order is important. DO NOT CHANGE.
const searchers=[ExactMatch,IncludeMatch,PrefixExactMatch,InversePrefixExactMatch,InverseSuffixExactMatch,SuffixExactMatch,InverseExactMatch,FuzzyMatch];const searchersLen=searchers.length;// Regex to split by spaces, but keep anything in quotes together
const SPACE_RE=/ +(?=([^\"]*\"[^\"]*\")*[^\"]*$)/;const OR_TOKEN='|';// Return a 2D array representation of the query, for simpler parsing.
// Example:
// "^core go$ | rb$ | py$ xy$" => [["^core", "go$"], ["rb$"], ["py$", "xy$"]]
function parseQuery(pattern,options={}){return pattern.split(OR_TOKEN).map(item=>{let query=item.trim().split(SPACE_RE).filter(item=>item&&!!item.trim());let results=[];for(let i=0,len=query.length;i<len;i+=1){const queryItem=query[i];// 1. Handle multiple query match (i.e, once that are quoted, like `"hello world"`)
let found=false;let idx=-1;while(!found&&++idx<searchersLen){const searcher=searchers[idx];let token=searcher.isMultiMatch(queryItem);if(token){results.push(new searcher(token,options));found=true;}}if(found){continue;}// 2. Handle single query matches (i.e, once that are *not* quoted)
idx=-1;while(++idx<searchersLen){const searcher=searchers[idx];let token=searcher.isSingleMatch(queryItem);if(token){results.push(new searcher(token,options));break;}}}return results;});}// These extended matchers can return an array of matches, as opposed
// to a singl match
const MultiMatchSet=new Set([FuzzyMatch.type,IncludeMatch.type]);/**
* Command-like searching
* ======================
3 years ago
*
* Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`,
* search in a given text.
3 years ago
*
* Search syntax:
3 years ago
*
* | Token | Match type | Description |
* | ----------- | -------------------------- | -------------------------------------- |
* | `jscript` | fuzzy-match | Items that fuzzy match `jscript` |
* | `=scheme` | exact-match | Items that are `scheme` |
* | `'python` | include-match | Items that include `python` |
* | `!ruby` | inverse-exact-match | Items that do not include `ruby` |
* | `^java` | prefix-exact-match | Items that start with `java` |
* | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` |
* | `.js$` | suffix-exact-match | Items that end with `.js` |
* | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` |
*
* A single pipe character acts as an OR operator. For example, the following
* query matches entries that start with `core` and end with either`go`, `rb`,
* or`py`.
*
* ```
* ^core go$ | rb$ | py$
* ```
*/class ExtendedSearch{constructor(pattern,{isCaseSensitive=Config.isCaseSensitive,includeMatches=Config.includeMatches,minMatchCharLength=Config.minMatchCharLength,ignoreLocation=Config.ignoreLocation,findAllMatches=Config.findAllMatches,location=Config.location,threshold=Config.threshold,distance=Config.distance}={}){this.query=null;this.options={isCaseSensitive,includeMatches,minMatchCharLength,findAllMatches,ignoreLocation,location,threshold,distance};this.pattern=isCaseSensitive?pattern:pattern.toLowerCase();this.query=parseQuery(this.pattern,this.options);}static condition(_,options){return options.useExtendedSearch;}searchIn(text){const query=this.query;if(!query){return {isMatch:false,score:1};}const{includeMatches,isCaseSensitive}=this.options;text=isCaseSensitive?text:text.toLowerCase();let numMatches=0;let allIndices=[];let totalScore=0;// ORs
for(let i=0,qLen=query.length;i<qLen;i+=1){const searchers=query[i];// Reset indices
allIndices.length=0;numMatches=0;// ANDs
for(let j=0,pLen=searchers.length;j<pLen;j+=1){const searcher=searchers[j];const{isMatch,indices,score}=searcher.search(text);if(isMatch){numMatches+=1;totalScore+=score;if(includeMatches){const type=searcher.constructor.type;if(MultiMatchSet.has(type)){allIndices=[...allIndices,...indices];}else {allIndices.push(indices);}}}else {totalScore=0;numMatches=0;allIndices.length=0;break;}}// OR condition, so if TRUE, return
if(numMatches){let result={isMatch:true,score:totalScore/numMatches};if(includeMatches){result.indices=allIndices;}return result;}}// Nothing was matched
return {isMatch:false,score:1};}}const registeredSearchers=[];function register(...args){registeredSearchers.push(...args);}function createSearcher(pattern,options){for(let i=0,len=registeredSearchers.length;i<len;i+=1){let searcherClass=registeredSearchers[i];if(searcherClass.condition(pattern,options)){return new searcherClass(pattern,options);}}return new BitapSearch(pattern,options);}const LogicalOperator={AND:'$and',OR:'$or'};const KeyType={PATH:'$path',PATTERN:'$val'};const isExpression=query=>!!(query[LogicalOperator.AND]||query[LogicalOperator.OR]);const isPath=query=>!!query[KeyType.PATH];const isLeaf=query=>!isArray(query)&&isObject(query)&&!isExpression(query);const convertToExplicit=query=>({[LogicalOperator.AND]:Object.keys(query).map(key=>({[key]:query[key]}))});// When `auto` is `true`, the parse function will infer and initialize and add
// the appropriate `Searcher` instance
function parse(query,options,{auto=true}={}){const next=query=>{let keys=Object.keys(query);const isQueryPath=isPath(query);if(!isQueryPath&&keys.length>1&&!isExpression(query)){return next(convertToExplicit(query));}if(isLeaf(query)){const key=isQueryPath?query[KeyType.PATH]:keys[0];const pattern=isQueryPath?query[KeyType.PATTERN]:query[key];if(!isString(pattern)){throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key));}const obj={keyId:createKeyId(key),pattern};if(auto){obj.searcher=createSearcher(pattern,options);}return obj;}let node={children:[],operator:keys[0]};keys.forEach(key=>{const value=query[key];if(isArray(value)){value.forEach(item=>{node.children.push(next(item));});}});return node;};if(!isExpression(query)){query=convertToExplicit(query);}return next(query);}// Practical scoring function
function computeScore$1(results,{ignoreFieldNorm=Config.ignoreFieldNorm}){results.forEach(result=>{let totalScore=1;result.matches.forEach(({key,norm,score})=>{const weight=key?key.weight:null;totalScore*=Math.pow(score===0&&weight?Number.EPSILON:score,(weight||1)*(ignoreFieldNorm?1:norm));});result.score=totalScore;});}function transformMatches(result,data){const matches=result.matches;data.matches=[];if(!isDefined(matches)){return;}matches.forEach(match=>{if(!isDefined(match.indices)||!match.indices.length){return;}const{indices,value}=match;let obj={indices,value};if(match.key){obj.key=match.key.src;}if(match.idx>-1){obj.refIndex=match.idx;}data.matches.push(obj);});}function transformScore(result,data){data.score=result.score;}function format(results,docs,{includeMatches=Config.includeMatches,includeScore=Config.includeScore}={}){const transformers=[];if(includeMatches)transformers.push(transformMatches);if(includeScore)transformers.push(transformScore);return results.map(result=>{const{idx}=result;const data={item:docs[idx],refIndex:idx};if(transformers.length){transformers.forEach(transformer=>{transformer(result,data);});}return data;});}class Fuse{constructor(docs,options={},index){this.options={...Config,...options};if(this.options.useExtendedSearch&&!true){throw new Error(EXTENDED_SEARCH_UNAVAILABLE);}this._keyStore=new KeyStore(this.options.keys);this.setCollection(docs,index);}setCollection(docs,index){this._docs=docs;if(index&&!(index instanceof FuseIndex)){throw new Error(INCORRECT_INDEX_TYPE);}this._myIndex=index||createIndex(this.options.keys,this._docs,{getFn:this.options.getFn});}add(doc){if(!isDefined(doc)){return;}this._docs.push(doc);this._myIndex.add(doc);}remove(predicate=()=>false){const results=[];for(let i=0,len=this._docs.length;i<len;i+=1){const doc=this._docs[i];if(predicate(doc,i)){this.removeAt(i);i-=1;len-=1;results.push(doc);}}return results;}removeAt(idx){this._docs.splice(idx,1);this._myIndex.removeAt(idx);}getIndex(){return this._myIndex;}search(query,{limit=-1}={}){const{includeMatches,includeScore,shouldSort,sortFn,ignoreFieldNorm}=this.options;let results=isString(query)?isString(this._docs[0])?this._searchStringList(query):this._searchObjectList(query):this._searchLogical(query);computeScore$1(results,{ignoreFieldNorm});if(shouldSort){results.sort(sortFn);}if(isNumber(limit)&&limit>-1){results=results.slice(0,limit);}return format(results,this._docs,{includeMatches,includeScore});}_searchStringList(query){const searcher=createSearcher(query,this.options);const{records}=this._myIndex;const results=[];// Iterate over every string in the index
records.forEach(({v:text,i:idx,n:norm})=>{if(!isDefined(text)){return;}const{isMatch,score,indices}=searcher.searchIn(text);if(isMatch){results.push({item:text,idx,matches:[{score,value:text,norm,indices}]});}});return results;}_searchLogical(query){const expression=parse(query,this.options);const evaluate=(node,item,idx)=>{if(!node.children){const{keyId,searcher}=node;const matches=this._findMatches({key:this._keyStore.get(keyId),value:this._myIndex.getValueForItemAtKeyId(item,keyId),searcher});if(matches&&matches.length){return [{idx,item,matches}];}return [];}/*eslint indent: [2, 2, {"SwitchCase": 1}]*/switch(node.operator){case LogicalOperator.AND:{const res=[];for(let i=0,len=node.children.length;i<len;i+=1){const child=node.children[i];const result=evaluate(child,item,idx);if(result.length){res.push(...result);}else {return [];}}return res;}case LogicalOperator.OR:{const res=[];for(let i=0,len=node.children.length;i<len;i+=1){const child=node.children[i];const result=evaluate(child,item,idx);if(result.length){res.push(...result);break;}}return res;}}};const records=this._myIndex.records;const resultMap={};const results=[];records.forEach(({$:item,i:idx})=>{if(isDefined(item)){let expResults=evaluate(expression,item,idx);if(expResults.length){// Dedupe when adding
if(!resultMap[idx]){resultMap[idx]={idx,item,matches:[]};results.push(resultMap[idx]);}expResults.forEach(({matches})=>{resultMap[idx].matches.push(...matches);});}}});return results;}_searchObjectList(query){const searcher=createSearcher(query,this.options);const{keys,records}=this._myIndex;const results=[];// List is Array<Object>
records.forEach(({$:item,i:idx})=>{if(!isDefined(item)){return;}let matches=[];// Iterate over every key (i.e, path), and fetch the value at that key
keys.forEach((key,keyIndex)=>{matches.push(...this._findMatches({key,value:item[keyIndex],searcher}));});if(matches.length){results.push({idx,item,matches});}});return results;}_findMatches({key,value,searcher}){if(!isDefined(value)){return [];}let matches=[];if(isArray(value)){value.forEach(({v:text,i:idx,n:norm})=>{if(!isDefined(text)){return;}const{isMatch,score,indices}=searcher.searchIn(text);if(isMatch){matches.push({score,key,value:text,idx,norm,indices});}});}else {const{v:text,n:norm}=value;const{isMatch,score,indices}=searcher.searchIn(text);if(isMatch){matches.push({score,key,value:text,norm,indices});}}return matches;}}Fuse.version='6.4.6';Fuse.createIndex=createIndex;Fuse.parseIndex=parseIndex;Fuse.config=Config;{Fuse.parseQuery=parse;}{register(ExtendedSearch);}
3 years ago
/**
* Simple ponyfill for Object.fromEntries
*/var fromEntries=function fromEntries(entries){return entries.reduce(function(acc,_ref){var key=_ref[0],value=_ref[1];acc[key]=value;return acc;},{});};/**
* Small wrapper around `useLayoutEffect` to get rid of the warning on SSR envs
*/var useIsomorphicLayoutEffect=typeof window!=='undefined'&&window.document&&window.document.createElement?react.useLayoutEffect:react.useEffect;
3 years ago
var top='top';var bottom='bottom';var right='right';var left='left';var auto='auto';var basePlacements=[top,bottom,right,left];var start='start';var end='end';var clippingParents='clippingParents';var viewport='viewport';var popper='popper';var reference='reference';var variationPlacements=/*#__PURE__*/basePlacements.reduce(function(acc,placement){return acc.concat([placement+"-"+start,placement+"-"+end]);},[]);var placements=/*#__PURE__*/[].concat(basePlacements,[auto]).reduce(function(acc,placement){return acc.concat([placement,placement+"-"+start,placement+"-"+end]);},[]);// modifiers that need to read the DOM
var beforeRead='beforeRead';var read='read';var afterRead='afterRead';// pure-logic modifiers
var beforeMain='beforeMain';var main='main';var afterMain='afterMain';// modifier with the purpose to write to the DOM (or write into a framework state)
var beforeWrite='beforeWrite';var write='write';var afterWrite='afterWrite';var modifierPhases=[beforeRead,read,afterRead,beforeMain,main,afterMain,beforeWrite,write,afterWrite];
3 years ago
function getNodeName(element){return element?(element.nodeName||'').toLowerCase():null;}
3 years ago
function getWindow(node){if(node==null){return window;}if(node.toString()!=='[object Window]'){var ownerDocument=node.ownerDocument;return ownerDocument?ownerDocument.defaultView||window:window;}return node;}
function isElement(node){var OwnElement=getWindow(node).Element;return node instanceof OwnElement||node instanceof Element;}function isHTMLElement(node){var OwnElement=getWindow(node).HTMLElement;return node instanceof OwnElement||node instanceof HTMLElement;}function isShadowRoot(node){// IE 11 has no ShadowRoot
if(typeof ShadowRoot==='undefined'){return false;}var OwnElement=getWindow(node).ShadowRoot;return node instanceof OwnElement||node instanceof ShadowRoot;}
// and applies them to the HTMLElements such as popper and arrow
function applyStyles(_ref){var state=_ref.state;Object.keys(state.elements).forEach(function(name){var style=state.styles[name]||{};var attributes=state.attributes[name]||{};var element=state.elements[name];// arrow is optional + virtual elements
if(!isHTMLElement(element)||!getNodeName(element)){return;}// Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe[cannot-write]
Object.assign(element.style,style);Object.keys(attributes).forEach(function(name){var value=attributes[name];if(value===false){element.removeAttribute(name);}else {element.setAttribute(name,value===true?'':value);}});});}function effect(_ref2){var state=_ref2.state;var initialStyles={popper:{position:state.options.strategy,left:'0',top:'0',margin:'0'},arrow:{position:'absolute'},reference:{}};Object.assign(state.elements.popper.style,initialStyles.popper);state.styles=initialStyles;if(state.elements.arrow){Object.assign(state.elements.arrow.style,initialStyles.arrow);}return function(){Object.keys(state.elements).forEach(function(name){var element=state.elements[name];var attributes=state.attributes[name]||{};var styleProperties=Object.keys(state.styles.hasOwnProperty(name)?state.styles[name]:initialStyles[name]);// Set all values to an empty string to unset them
var style=styleProperties.reduce(function(style,property){style[property]='';return style;},{});// arrow is optional + virtual elements
if(!isHTMLElement(element)||!getNodeName(element)){return;}Object.assign(element.style,style);Object.keys(attributes).forEach(function(attribute){element.removeAttribute(attribute);});});};}// eslint-disable-next-line import/no-unused-modules
var applyStyles$1 = {name:'applyStyles',enabled:true,phase:'write',fn:applyStyles,effect:effect,requires:['computeStyles']};
function getBasePlacement(placement){return placement.split('-')[0];}
function getBoundingClientRect(element){var rect=element.getBoundingClientRect();return {width:rect.width,height:rect.height,top:rect.top,right:rect.right,bottom:rect.bottom,left:rect.left,x:rect.left,y:rect.top};}
// means it doesn't take into account transforms.
function getLayoutRect(element){var clientRect=getBoundingClientRect(element);// Use the clientRect sizes if it's not been transformed.
// Fixes https://github.com/popperjs/popper-core/issues/1223
var width=element.offsetWidth;var height=element.offsetHeight;if(Math.abs(clientRect.width-width)<=1){width=clientRect.width;}if(Math.abs(clientRect.height-height)<=1){height=clientRect.height;}return {x:element.offsetLeft,y:element.offsetTop,width:width,height:height};}
function contains(parent,child){var rootNode=child.getRootNode&&child.getRootNode();// First, attempt with faster native method
if(parent.contains(child)){return true;}// then fallback to custom implementation with Shadow DOM support
else if(rootNode&&isShadowRoot(rootNode)){var next=child;do{if(next&&parent.isSameNode(next)){return true;}// $FlowFixMe[prop-missing]: need a better way to handle this...
next=next.parentNode||next.host;}while(next);}// Give up, the result is false
return false;}
function getComputedStyle(element){return getWindow(element).getComputedStyle(element);}
function isTableElement(element){return ['table','td','th'].indexOf(getNodeName(element))>=0;}
function getDocumentElement(element){// $FlowFixMe[incompatible-return]: assume body is always available
return ((isElement(element)?element.ownerDocument:// $FlowFixMe[prop-missing]
element.document)||window.document).documentElement;}
function getParentNode(element){if(getNodeName(element)==='html'){return element;}return(// this is a quicker (but less type safe) way to save quite some bytes from the bundle
// $FlowFixMe[incompatible-return]
// $FlowFixMe[prop-missing]
element.assignedSlot||// step into the shadow DOM of the parent of a slotted node
element.parentNode||(// DOM Element detected
isShadowRoot(element)?element.host:null)||// ShadowRoot detected
// $FlowFixMe[incompatible-call]: HTMLElement is a Node
getDocumentElement(element)// fallback
);}
function getTrueOffsetParent(element){if(!isHTMLElement(element)||// https://github.com/popperjs/popper-core/issues/837
getComputedStyle(element).position==='fixed'){return null;}return element.offsetParent;}// `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getContainingBlock(element){var isFirefox=navigator.userAgent.toLowerCase().indexOf('firefox')!==-1;var isIE=navigator.userAgent.indexOf('Trident')!==-1;if(isIE&&isHTMLElement(element)){// In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
var elementCss=getComputedStyle(element);if(elementCss.position==='fixed'){return null;}}var currentNode=getParentNode(element);while(isHTMLElement(currentNode)&&['html','body'].indexOf(getNodeName(currentNode))<0){var css=getComputedStyle(currentNode);// This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
if(css.transform!=='none'||css.perspective!=='none'||css.contain==='paint'||['transform','perspective'].indexOf(css.willChange)!==-1||isFirefox&&css.willChange==='filter'||isFirefox&&css.filter&&css.filter!=='none'){return currentNode;}else {currentNode=currentNode.parentNode;}}return null;}// Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
function getOffsetParent(element){var window=getWindow(element);var offsetParent=getTrueOffsetParent(element);while(offsetParent&&isTableElement(offsetParent)&&getComputedStyle(offsetParent).position==='static'){offsetParent=getTrueOffsetParent(offsetParent);}if(offsetParent&&(getNodeName(offsetParent)==='html'||getNodeName(offsetParent)==='body'&&getComputedStyle(offsetParent).position==='static')){return window;}return offsetParent||getContainingBlock(element)||window;}
function getMainAxisFromPlacement(placement){return ['top','bottom'].indexOf(placement)>=0?'x':'y';}
var max=Math.max;var min=Math.min;var round=Math.round;
function within(min$1,value,max$1){return max(min$1,min(value,max$1));}
function getFreshSideObject(){return {top:0,right:0,bottom:0,left:0};}
function mergePaddingObject(paddingObject){return Object.assign({},getFreshSideObject(),paddingObject);}
function expandToHashMap(value,keys){return keys.reduce(function(hashMap,key){hashMap[key]=value;return hashMap;},{});}
var toPaddingObject=function toPaddingObject(padding,state){padding=typeof padding==='function'?padding(Object.assign({},state.rects,{placement:state.placement})):padding;return mergePaddingObject(typeof padding!=='number'?padding:expandToHashMap(padding,basePlacements));};function arrow(_ref){var _state$modifiersData$;var state=_ref.state,name=_ref.name,options=_ref.options;var arrowElement=state.elements.arrow;var popperOffsets=state.modifiersData.popperOffsets;var basePlacement=getBasePlacement(state.placement);var axis=getMainAxisFromPlacement(basePlacement);var isVertical=[left,right].indexOf(basePlacement)>=0;var len=isVertical?'height':'width';if(!arrowElement||!popperOffsets){return;}var paddingObject=toPaddingObject(options.padding,state);var arrowRect=getLayoutRect(arrowElement);var minProp=axis==='y'?top:left;var maxProp=axis==='y'?bottom:right;var endDiff=state.rects.reference[len]+state.rects.reference[axis]-popperOffsets[axis]-state.rects.popper[len];var startDiff=popperOffsets[axis]-state.rects.reference[axis];var arrowOffsetParent=getOffsetParent(arrowElement);var clientSize=arrowOffsetParent?axis==='y'?arrowOffsetParent.clientHeight||0:arrowOffsetParent.clientWidth||0:0;var centerToReference=endDiff/2-startDiff/2;// Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
var min=paddingObject[minProp];var max=clientSize-arrowRect[len]-paddingObject[maxProp];var center=clientSize/2-arrowRect[len]/2+centerToReference;var offset=within(min,center,max);// Prevents breaking syntax highlighting...
var axisProp=axis;state.modifiersData[name]=(_state$modifiersData$={},_state$modifiersData$[axisProp]=offset,_state$modifiersData$.centerOffset=offset-center,_state$modifiersData$);}function effect$1(_ref2){var state=_ref2.state,options=_ref2.options;var _options$element=options.element,arrowElement=_options$element===void 0?'[data-popper-arrow]':_options$element;if(arrowElement==null){return;}// CSS selector
if(typeof arrowElement==='string'){arrowElement=state.elements.popper.querySelector(arrowElement);if(!arrowElement){return;}}{if(!isHTMLElement(arrowElement)){console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).','To use an SVG arrow, wrap it in an HTMLElement that will be used as','the arrow.'].join(' '));}}if(!contains(state.elements.popper,arrowElement)){{console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper','element.'].join(' '));}return;}state.elements.arrow=arrowElement;}// eslint-disable-next-line import/no-unused-modules
var arrow$1 = {name:'arrow',enabled:true,phase:'main',fn:arrow,effect:effect$1,requires:['popperOffsets'],requiresIfExists:['preventOverflow']};
var unsetSides={top:'auto',right:'auto',bottom:'auto',left:'auto'};// Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsetsByDPR(_ref){var x=_ref.x,y=_ref.y;var win=window;var dpr=win.devicePixelRatio||1;return {x:round(round(x*dpr)/dpr)||0,y:round(round(y*dpr)/dpr)||0};}function mapToStyles(_ref2){var _Object$assign2;var popper=_ref2.popper,popperRect=_ref2.popperRect,placement=_ref2.placement,offsets=_ref2.offsets,position=_ref2.position,gpuAcceleration=_ref2.gpuAcceleration,adaptive=_ref2.adaptive,roundOffsets=_ref2.roundOffsets;var _ref3=roundOffsets===true?roundOffsetsByDPR(offsets):typeof roundOffsets==='function'?roundOffsets(offsets):offsets,_ref3$x=_ref3.x,x=_ref3$x===void 0?0:_ref3$x,_ref3$y=_ref3.y,y=_ref3$y===void 0?0:_ref3$y;var hasX=offsets.hasOwnProperty('x');var hasY=offsets.hasOwnProperty('y');var sideX=left;var sideY=top;var win=window;if(adaptive){var offsetParent=getOffsetParent(popper);var heightProp='clientHeight';var widthProp='clientWidth';if(offsetParent===getWindow(popper)){offsetParent=getDocumentElement(popper);if(getComputedStyle(offsetParent).position!=='static'){heightProp='scrollHeight';widthProp='scrollWidth';}}// $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
offsetParent=offsetParent;if(placement===top){sideY=bottom;// $FlowFixMe[prop-missing]
y-=offsetParent[heightProp]-popperRect.height;y*=gpuAcceleration?1:-1;}if(placement===left){sideX=right;// $FlowFixMe[prop-missing]
x-=offsetParent[widthProp]-popperRect.width;x*=gpuAcceleration?1:-1;}}var commonStyles=Object.assign({position:position},adaptive&&unsetSides);if(gpuAcceleration){var _Object$assign;return Object.assign({},commonStyles,(_Object$assign={},_Object$assign[sideY]=hasY?'0':'',_Object$assign[sideX]=hasX?'0':'',_Object$assign.transform=(win.devicePixelRatio||1)<2?"translate("+x+"px, "+y+"px)":"translate3d("+x+"px, "+y+"px, 0)",_Object$assign));}return Object.assign({},commonStyles,(_Object$assign2={},_Object$assign2[sideY]=hasY?y+"px":'',_Object$assign2[sideX]=hasX?x+"px":'',_Object$assign2.transform='',_Object$assign2));}function computeStyles(_ref4){var state=_ref4.state,options=_ref4.options;var _options$gpuAccelerat=options.gpuAcceleration,gpuAcceleration=_options$gpuAccelerat===void 0?true:_options$gpuAccelerat,_options$adaptive=options.adaptive,adaptive=_options$adaptive===void 0?true:_options$adaptive,_options$roundOffsets=options.roundOffsets,roundOffsets=_options$roundOffsets===void 0?true:_options$roundOffsets;{var transitionProperty=getComputedStyle(state.elements.popper).transitionProperty||'';if(adaptive&&['transform','top','right','bottom','left'].some(function(property){return transitionProperty.indexOf(property)>=0;})){console.warn(['Popper: Detected CSS transitions on at least one of the following','CSS properties: "transform", "top", "right", "bottom", "left".','\n\n','Disable the "computeStyles" modifier\'s `adaptive` option to allow','for smooth transitions, or remove these properties from the CSS','transition declaration on the popper element if only transitioning','opacity or background-color for example.','\n\n','We recommend using the popper element as a wrapper around an inner','element that can have any CSS property transitioned for animations.'].join(' '));}}var commonStyles={placement:getBasePlacement(state.placement),popper:state.elements.popper,popperRect:state.rects.popper,gpuAcceleration:gpuAcceleration};if(state.modifiersData.popperOffsets!=null){state.styles.popper=Object.assign({},state.styles.popper,mapToStyles(Object.assign({},commonStyles,{offsets:state.modifiersData.popperOffsets,position:state.options.strategy,adaptive:adaptive,roundOffsets:roundOffsets})));}if(state.modifiersData.arrow!=null){state.styles.arrow=Object.assign({},state.styles.arrow,mapToStyles(Object.assign({},commonStyles,{offsets:state.modifiersData.arrow,position:'absolute',adaptive:false,roundOffsets:roundOffsets})));}state.attributes.popper=Object.assign({},state.attributes.popper,{'data-popper-placement':state.placement});}// eslint-disable-next-line import/no-unused-modules
var computeStyles$1 = {name:'computeStyles',enabled:true,phase:'beforeWrite',fn:computeStyles,data:{}};
var passive={passive:true};function effect$2(_ref){var state=_ref.state,instance=_ref.instance,options=_ref.options;var _options$scroll=options.scroll,scroll=_options$scroll===void 0?true:_options$scroll,_options$resize=options.resize,resize=_options$resize===void 0?true:_options$resize;var window=getWindow(state.elements.popper);var scrollParents=[].concat(state.scrollParents.reference,state.scrollParents.popper);if(scroll){scrollParents.forEach(function(scrollParent){scrollParent.addEventListener('scroll',instance.update,passive);});}if(resize){window.addEventListener('resize',instance.update,passive);}return function(){if(scroll){scrollParents.forEach(function(scrollParent){scrollParent.removeEventListener('scroll',instance.update,passive);});}if(resize){window.removeEventListener('resize',instance.update,passive);}};}// eslint-disable-next-line import/no-unused-modules
var eventListeners = {name:'eventListeners',enabled:true,phase:'write',fn:function fn(){},effect:effect$2,data:{}};
var hash={left:'right',right:'left',bottom:'top',top:'bottom'};function getOppositePlacement(placement){return placement.replace(/left|right|bottom|top/g,function(matched){return hash[matched];});}
var hash$1={start:'end',end:'start'};function getOppositeVariationPlacement(placement){return placement.replace(/start|end/g,function(matched){return hash$1[matched];});}
function getWindowScroll(node){var win=getWindow(node);var scrollLeft=win.pageXOffset;var scrollTop=win.pageYOffset;return {scrollLeft:scrollLeft,scrollTop:scrollTop};}
function getWindowScrollBarX(element){// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return getBoundingClientRect(getDocumentElement(element)).left+getWindowScroll(element).scrollLeft;}
function getViewportRect(element){var win=getWindow(element);var html=getDocumentElement(element);var visualViewport=win.visualViewport;var width=html.clientWidth;var height=html.clientHeight;var x=0;var y=0;// NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
// can be obscured underneath it.
// Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
// if it isn't open, so if this isn't available, the popper will be detected
// to overflow the bottom of the screen too early.
if(visualViewport){width=visualViewport.width;height=visualViewport.height;// Uses Layout Viewport (like Chrome; Safari does not currently)
// In Chrome, it returns a value very close to 0 (+/-) but contains rounding
// errors due to floating point numbers, so we need to check precision.
// Safari returns a number <= 0, usually < -1 when pinch-zoomed
// Feature detection fails in mobile emulation mode in Chrome.
// Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
// 0.001
// Fallback here: "Not Safari" userAgent
if(!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){x=visualViewport.offsetLeft;y=visualViewport.offsetTop;}}return {width:width,height:height,x:x+getWindowScrollBarX(element),y:y};}
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
function getDocumentRect(element){var _element$ownerDocumen;var html=getDocumentElement(element);var winScroll=getWindowScroll(element);var body=(_element$ownerDocumen=element.ownerDocument)==null?void 0:_element$ownerDocumen.body;var width=max(html.scrollWidth,html.clientWidth,body?body.scrollWidth:0,body?body.clientWidth:0);var height=max(html.scrollHeight,html.clientHeight,body?body.scrollHeight:0,body?body.clientHeight:0);var x=-winScroll.scrollLeft+getWindowScrollBarX(element);var y=-winScroll.scrollTop;if(getComputedStyle(body||html).direction==='rtl'){x+=max(html.clientWidth,body?body.clientWidth:0)-width;}return {width:width,height:height,x:x,y:y};}
function isScrollParent(element){// Firefox wants us to check `-x` and `-y` variations as well
var _getComputedStyle=getComputedStyle(element),overflow=_getComputedStyle.overflow,overflowX=_getComputedStyle.overflowX,overflowY=_getComputedStyle.overflowY;return /auto|scroll|overlay|hidden/.test(overflow+overflowY+overflowX);}
function getScrollParent(node){if(['html','body','#document'].indexOf(getNodeName(node))>=0){// $FlowFixMe[incompatible-return]: assume body is always available
return node.ownerDocument.body;}if(isHTMLElement(node)&&isScrollParent(node)){return node;}return getScrollParent(getParentNode(node));}
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/function listScrollParents(element,list){var _element$ownerDocumen;if(list===void 0){list=[];}var scrollParent=getScrollParent(element);var isBody=scrollParent===((_element$ownerDocumen=element.ownerDocument)==null?void 0:_element$ownerDocumen.body);var win=getWindow(scrollParent);var target=isBody?[win].concat(win.visualViewport||[],isScrollParent(scrollParent)?scrollParent:[]):scrollParent;var updatedList=list.concat(target);return isBody?updatedList:// $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)));}
function rectToClientRect(rect){return Object.assign({},rect,{left:rect.x,top:rect.y,right:rect.x+rect.width,bottom:rect.y+rect.height});}
function getInnerBoundingClientRect(element){var rect=getBoundingClientRect(element);rect.top=rect.top+element.clientTop;rect.left=rect.left+element.clientLeft;rect.bottom=rect.top+element.clientHeight;rect.right=rect.left+element.clientWidth;rect.width=element.clientWidth;rect.height=element.clientHeight;rect.x=rect.left;rect.y=rect.top;return rect;}function getClientRectFromMixedType(element,clippingParent){return clippingParent===viewport?rectToClientRect(getViewportRect(element)):isHTMLElement(clippingParent)?getInnerBoundingClientRect(clippingParent):rectToClientRect(getDocumentRect(getDocumentElement(element)));}// A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element){var clippingParents=listScrollParents(getParentNode(element));var canEscapeClipping=['absolute','fixed'].indexOf(getComputedStyle(element).position)>=0;var clipperElement=canEscapeClipping&&isHTMLElement(element)?getOffsetParent(element):element;if(!isElement(clipperElement)){return [];}// $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(function(clippingParent){return isElement(clippingParent)&&contains(clippingParent,clipperElement)&&getNodeName(clippingParent)!=='body';});}// Gets the maximum area that the element is visible in due to any number of
// clipping parents
function getClippingRect(element,boundary,rootBoundary){var mainClippingParents=boundary==='clippingParents'?getClippingParents(element):[].concat(boundary);var clippingParents=[].concat(mainClippingParents,[rootBoundary]);var firstClippingParent=clippingParents[0];var clippingRect=clippingParents.reduce(function(accRect,clippingParent){var rect=getClientRectFromMixedType(element,clippingParent);accRect.top=max(rect.top,accRect.top);accRect.right=min(rect.right,accRect.right);accRect.bottom=min(rect.bottom,accRect.bottom);accRect.left=max(rect.left,accRect.left);return accRect;},getClientRectFromMixedType(element,firstClippingParent));clippingRect.width=clippingRect.right-clippingRect.left;clippingRect.height=clippingRect.bottom-clippingRect.top;clippingRect.x=clippingRect.left;clippingRect.y=clippingRect.top;return clippingRect;}
function getVariation(placement){return placement.split('-')[1];}
function computeOffsets(_ref){var reference=_ref.reference,element=_ref.element,placement=_ref.placement;var basePlacement=placement?getBasePlacement(placement):null;var variation=placement?getVariation(placement):null;var commonX=reference.x+reference.width/2-element.width/2;var commonY=reference.y+reference.height/2-element.height/2;var offsets;switch(basePlacement){case top:offsets={x:commonX,y:reference.y-element.height};break;case bottom:offsets={x:commonX,y:reference.y+reference.height};break;case right:offsets={x:reference.x+reference.width,y:commonY};break;case left:offsets={x:reference.x-element.width,y:commonY};break;default:offsets={x:reference.x,y:reference.y};}var mainAxis=basePlacement?getMainAxisFromPlacement(basePlacement):null;if(mainAxis!=null){var len=mainAxis==='y'?'height':'width';switch(variation){case start:offsets[mainAxis]=offsets[mainAxis]-(reference[len]/2-element[len]/2);break;case end:offsets[mainAxis]=offsets[mainAxis]+(reference[len]/2-element[len]/2);break;}}return offsets;}
function detectOverflow(state,options){if(options===void 0){options={};}var _options=options,_options$placement=_options.placement,placement=_options$placement===void 0?state.placement:_options$placement,_options$boundary=_options.boundary,boundary=_options$boundary===void 0?clippingParents:_options$boundary,_options$rootBoundary=_options.rootBoundary,rootBoundary=_options$rootBoundary===void 0?viewport:_options$rootBoundary,_options$elementConte=_options.elementContext,elementContext=_options$elementConte===void 0?popper:_options$elementConte,_options$altBoundary=_options.altBoundary,altBoundary=_options$altBoundary===void 0?false:_options$altBoundary,_options$padding=_options.padding,padding=_options$padding===void 0?0:_options$padding;var paddingObject=mergePaddingObject(typeof padding!=='number'?padding:expandToHashMap(padding,basePlacements));var altContext=elementContext===popper?reference:popper;var referenceElement=state.elements.reference;var popperRect=state.rects.popper;var element=state.elements[altBoundary?altContext:elementContext];var clippingClientRect=getClippingRect(isElement(element)?element:element.contextElement||getDocumentElement(state.elements.popper),boundary,rootBoundary);var referenceClientRect=getBoundingClientRect(referenceElement);var popperOffsets=computeOffsets({reference:referenceClientRect,element:popperRect,strategy:'absolute',placement:placement});var popperClientRect=rectToClientRect(Object.assign({},popperRect,popperOffsets));var elementClientRect=elementContext===popper?popperClientRect:referenceClientRect;// positive = overflowing the clipping rect
// 0 or negative = within the clipping rect
var overflowOffsets={top:clippingClientRect.top-elementClientRect.top+paddingObject.top,bottom:elementClientRect.bottom-clippingClientRect.bottom+paddingObject.bottom,left:clippingClientRect.left-elementClientRect.left+paddingObject.left,right:elementClientRect.right-clippingClientRect.right+paddingObject.right};var offsetData=state.modifiersData.offset;// Offsets can be applied only to the popper element
if(elementContext===popper&&offsetData){var offset=offsetData[placement];Object.keys(overflowOffsets).forEach(function(key){var multiply=[right,bottom].indexOf(key)>=0?1:-1;var axis=[top,bottom].indexOf(key)>=0?'y':'x';overflowOffsets[key]+=offset[axis]*multiply;});}return overflowOffsets;}
function computeAutoPlacement(state,options){if(options===void 0){options={};}var _options=options,placement=_options.placement,boundary=_options.boundary,rootBoundary=_options.rootBoundary,padding=_options.padding,flipVariations=_options.flipVariations,_options$allowedAutoP=_options.allowedAutoPlacements,allowedAutoPlacements=_options$allowedAutoP===void 0?placements:_options$allowedAutoP;var variation=getVariation(placement);var placements$1=variation?flipVariations?variationPlacements:variationPlacements.filter(function(placement){return getVariation(placement)===variation;}):basePlacements;var allowedPlacements=placements$1.filter(function(placement){return allowedAutoPlacements.indexOf(placement)>=0;});if(allowedPlacements.length===0){allowedPlacements=placements$1;{console.error(['Popper: The `allowedAutoPlacements` option did not allow any','placements. Ensure the `placement` option matches the variation','of the allowed placements.','For example, "auto" cannot be used to allow "bottom-start".','Use "auto-start" instead.'].join(' '));}}// $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
var overflows=allowedPlacements.reduce(function(acc,placement){acc[placement]=detectOverflow(state,{placement:placement,boundary:boundary,rootBoundary:rootBoundary,padding:padding})[getBasePlacement(placement)];return acc;},{});return Object.keys(overflows).sort(function(a,b){return overflows[a]-overflows[b];});}
function getExpandedFallbackPlacements(placement){if(getBasePlacement(placement)===auto){return [];}var oppositePlacement=getOppositePlacement(placement);return [getOppositeVariationPlacement(placement),oppositePlacement,getOppositeVariationPlacement(oppositePlacement)];}function flip(_ref){var state=_ref.state,options=_ref.options,name=_ref.name;if(state.modifiersData[name]._skip){return;}var _options$mainAxis=options.mainAxis,checkMainAxis=_options$mainAxis===void 0?true:_options$mainAxis,_options$altAxis=options.altAxis,checkAltAxis=_options$altAxis===void 0?true:_options$altAxis,specifiedFallbackPlacements=options.fallbackPlacements,padding=options.padding,boundary=options.boundary,rootBoundary=options.rootBoundary,altBoundary=options.altBoundary,_options$flipVariatio=options.flipVariations,flipVariations=_options$flipVariatio===void 0?true:_options$flipVariatio,allowedAutoPlacements=options.allowedAutoPlacements;var preferredPlacement=state.options.placement;var basePlacement=getBasePlacement(preferredPlacement);var isBasePlacement=basePlacement===preferredPlacement;var fallbackPlacements=specifiedFallbackPlacements||(isBasePlacement||!flipVariations?[getOppositePlacement(preferredPlacement)]:getExpandedFallbackPlacements(preferredPlacement));var placements=[preferredPlacement].concat(fallbackPlacements).reduce(function(acc,placement){return acc.concat(getBasePlacement(placement)===auto?computeAutoPlacement(state,{placement:placement,boundary:boundary,rootBoundary:rootBoundary,padding:padding,flipVariations:flipVariations,allowedAutoPlacements:allowedAutoPlacements}):placement);},[]);var referenceRect=state.rects.reference;var popperRect=state.rects.popper;var checksMap=new Map();var makeFallbackChecks=true;var firstFittingPlacement=placements[0];for(var i=0;i<placements.length;i++){var placement=placements[i];var _basePlacement=getBasePlacement(placement);var isStartVariation=getVariation(placement)===start;var isVertical=[top,bottom].indexOf(_basePlacement)>=0;var len=isVertical?'width':'height';var overflow=detectOverflow(state,{placement:placement,boundary:boundary,rootBoundary:rootBoundary,altBoundary:altBoundary,padding:padding});var mainVariationSide=isVertical?isStartVariation?right:left:isStartVariation?bottom:top;if(referenceRect[len]>popperRect[len]){mainVariationSide=getOppositePlacement(mainVariationSide);}var altVariationSide=getOppositePlacement(mainVariationSide);var checks=[];if(checkMainAxis){checks.push(overflow[_basePlacement]<=0);}if(checkAltAxis){checks.push(overflow[mainVariationSide]<=0,overflow[altVariationSide]<=0);}if(checks.every(function(check){return check;})){firstFittingPlacement=placement;makeFallbackChecks=false;break;}checksMap.set(placement,checks);}if(makeFallbackChecks){// `2` may be desired in some cases research later
var numberOfChecks=flipVariations?3:1;var _loop=function _loop(_i){var fittingPlacement=placements.find(function(placement){var checks=checksMap.get(placement);if(checks){return checks.slice(0,_i).every(function(check){return check;});}});if(fittingPlacement){firstFittingPlacement=fittingPlacement;return "break";}};for(var _i=numberOfChecks;_i>0;_i--){var _ret=_loop(_i);if(_ret==="break")break;}}if(state.placement!==firstFittingPlacement){state.modifiersData[name]._skip=true;state.placement=firstFittingPlacement;state.reset=true;}}// eslint-disable-next-line import/no-unused-modules
var flip$1 = {name:'flip',enabled:true,phase:'main',fn:flip,requiresIfExists:['offset'],data:{_skip:false}};
function getSideOffsets(overflow,rect,preventedOffsets){if(preventedOffsets===void 0){preventedOffsets={x:0,y:0};}return {top:overflow.top-rect.height-preventedOffsets.y,right:overflow.right-rect.width+preventedOffsets.x,bottom:overflow.bottom-rect.height+preventedOffsets.y,left:overflow.left-rect.width-preventedOffsets.x};}function isAnySideFullyClipped(overflow){return [top,right,bottom,left].some(function(side){return overflow[side]>=0;});}function hide(_ref){var state=_ref.state,name=_ref.name;var referenceRect=state.rects.reference;var popperRect=state.rects.popper;var preventedOffsets=state.modifiersData.preventOverflow;var referenceOverflow=detectOverflow(state,{elementContext:'reference'});var popperAltOverflow=detectOverflow(state,{altBoundary:true});var referenceClippingOffsets=getSideOffsets(referenceOverflow,referenceRect);var popperEscapeOffsets=getSideOffsets(popperAltOverflow,popperRect,preventedOffsets);var isReferenceHidden=isAnySideFullyClipped(referenceClippingOffsets);var hasPopperEscaped=isAnySideFullyClipped(popperEscapeOffsets);state.modifiersData[name]={referenceClippingOffsets:referenceClippingOffsets,popperEscapeOffsets:popperEscapeOffsets,isReferenceHidden:isReferenceHidden,hasPopperEscaped:hasPopperEscaped};state.attributes.popper=Object.assign({},state.attributes.popper,{'data-popper-reference-hidden':isReferenceHidden,'data-popper-escaped':hasPopperEscaped});}// eslint-disable-next-line import/no-unused-modules
var hide$1 = {name:'hide',enabled:true,phase:'main',requiresIfExists:['preventOverflow'],fn:hide};
function distanceAndSkiddingToXY(placement,rects,offset){var basePlacement=getBasePlacement(placement);var invertDistance=[left,top].indexOf(basePlacement)>=0?-1:1;var _ref=typeof offset==='function'?offset(Object.assign({},rects,{placement:placement})):offset,skidding=_ref[0],distance=_ref[1];skidding=skidding||0;distance=(distance||0)*invertDistance;return [left,right].indexOf(basePlacement)>=0?{x:distance,y:skidding}:{x:skidding,y:distance};}function offset(_ref2){var state=_ref2.state,options=_ref2.options,name=_ref2.name;var _options$offset=options.offset,offset=_options$offset===void 0?[0,0]:_options$offset;var data=placements.reduce(function(acc,placement){acc[placement]=distanceAndSkiddingToXY(placement,state.rects,offset);return acc;},{});var _data$state$placement=data[state.placement],x=_data$state$placement.x,y=_data$state$placement.y;if(state.modifiersData.popperOffsets!=null){state.modifiersData.popperOffsets.x+=x;state.modifiersData.popperOffsets.y+=y;}state.modifiersData[name]=data;}// eslint-disable-next-line import/no-unused-modules
var offset$1 = {name:'offset',enabled:true,phase:'main',requires:['popperOffsets'],fn:offset};
function popperOffsets(_ref){var state=_ref.state,name=_ref.name;// Offsets are the actual position the popper needs to have to be
// properly positioned near its reference element
// This is the most basic placement, and will be adjusted by
// the modifiers in the next step
state.modifiersData[name]=computeOffsets({reference:state.rects.reference,element:state.rects.popper,strategy:'absolute',placement:state.placement});}// eslint-disable-next-line import/no-unused-modules
var popperOffsets$1 = {name:'popperOffsets',enabled:true,phase:'read',fn:popperOffsets,data:{}};
function getAltAxis(axis){return axis==='x'?'y':'x';}
function preventOverflow(_ref){var state=_ref.state,options=_ref.options,name=_ref.name;var _options$mainAxis=options.mainAxis,checkMainAxis=_options$mainAxis===void 0?true:_options$mainAxis,_options$altAxis=options.altAxis,checkAltAxis=_options$altAxis===void 0?false:_options$altAxis,boundary=options.boundary,rootBoundary=options.rootBoundary,altBoundary=options.altBoundary,padding=options.padding,_options$tether=options.tether,tether=_options$tether===void 0?true:_options$tether,_options$tetherOffset=options.tetherOffset,tetherOffset=_options$tetherOffset===void 0?0:_options$tetherOffset;var overflow=detectOverflow(state,{boundary:boundary,rootBoundary:rootBoundary,padding:padding,altBoundary:altBoundary});var basePlacement=getBasePlacement(state.placement);var variation=getVariation(state.placement);var isBasePlacement=!variation;var mainAxis=getMainAxisFromPlacement(basePlacement);var altAxis=getAltAxis(mainAxis);var popperOffsets=state.modifiersData.popperOffsets;var referenceRect=state.rects.reference;var popperRect=state.rects.popper;var tetherOffsetValue=typeof tetherOffset==='function'?tetherOffset(Object.assign({},state.rects,{placement:state.placement})):tetherOffset;var data={x:0,y:0};if(!popperOffsets){return;}if(checkMainAxis||checkAltAxis){var mainSide=mainAxis==='y'?top:left;var altSide=mainAxis==='y'?bottom:right;var len=mainAxis==='y'?'height':'width';var offset=popperOffsets[mainAxis];var min$1=popperOffsets[mainAxis]+overflow[mainSide];var max$1=popperOffsets[mainAxis]-overflow[altSide];var additive=tether?-popperRect[len]/2:0;var minLen=variation===start?referenceRect[len]:popperRect[len];var maxLen=variation===start?-popperRect[len]:-referenceRect[len];// We need to include the arrow in the calculation so the arrow doesn't go
// outside the reference bounds
var arrowElement=state.elements.arrow;var arrowRect=tether&&arrowElement?getLayoutRect(arrowElement):{width:0,height:0};var arrowPaddingObject=state.modifiersData['arrow#persistent']?state.modifiersData['arrow#persistent'].padding:getFreshSideObject();var arrowPaddingMin=arrowPaddingObject[mainSide];var arrowPaddingMax=arrowPaddingObject[altSide];// If the reference length is smaller than the arrow length, we don't want
// to include its full size in the calculation. If the reference is small
// and near the edge of a boundary, the popper can overflow even if the
// reference is not overflowing as well (e.g. virtual elements with no
// width or height)
var arrowLen=within(0,referenceRect[len],arrowRect[len]);var minOffset=isBasePlacement?referenceRect[len]/2-additive-arrowLen-arrowPaddingMin-tetherOffsetValue:minLen-arrowLen-arrowPaddingMin-tetherOffsetValue;var maxOffset=isBasePlacement?-referenceRect[len]/2+additive+arrowLen+arrowPaddingMax+tetherOffsetValue:maxLen+arrowLen+arrowPaddingMax+tetherOffsetValue;var arrowOffsetParent=state.elements.arrow&&getOffsetParent(state.elements.arrow);var clientOffset=arrowOffsetParent?mainAxis==='y'?arrowOffsetParent.clientTop||0:arrowOffsetParent.clientLeft||0:0;var offsetModifierValue=state.modifiersData.offset?state.modifiersData.offset[state.placement][mainAxis]:0;var tetherMin=popperOffsets[mainAxis]+minOffset-offsetModifierValue-clientOffset;var tetherMax=popperOffsets[mainAxis]+maxOffset-offsetModifierValue;if(checkMainAxis){var preventedOffset=within(tether?min(min$1,tetherMin):min$1,offset,tether?max(max$1,tetherMax):max$1);popperOffsets[mainAxis]=preventedOffset;data[mainAxis]=preventedOffset-offset;}if(checkAltAxis){var _mainSide=mainAxis==='x'?top:left;var _altSide=mainAxis==='x'?bottom:right;var _offset=popperOffsets[altAxis];var _min=_offset+overflow[_mainSide];var _max=_offset-overflow[_altSide];var _preventedOffset=within(tether?min(_min,tetherMin):_min,_offset,tether?max(_max,tetherMax):_max);popperOffsets[altAxis]=_preventedOffset;data[altAxis]=_preventedOffset-_offset;}}state.modifiersData[name]=data;}// eslint-disable-next-line import/no-unused-modules
var preventOverflow$1 = {name:'preventOverflow',enabled:true,phase:'main',fn:preventOverflow,requiresIfExists:['offset']};
function getHTMLElementScroll(element){return {scrollLeft:element.scrollLeft,scrollTop:element.scrollTop};}
function getNodeScroll(node){if(node===getWindow(node)||!isHTMLElement(node)){return getWindowScroll(node);}else {return getHTMLElementScroll(node);}}
// Composite means it takes into account transforms as well as layout.
function getCompositeRect(elementOrVirtualElement,offsetParent,isFixed){if(isFixed===void 0){isFixed=false;}var documentElement=getDocumentElement(offsetParent);var rect=getBoundingClientRect(elementOrVirtualElement);var isOffsetParentAnElement=isHTMLElement(offsetParent);var scroll={scrollLeft:0,scrollTop:0};var offsets={x:0,y:0};if(isOffsetParentAnElement||!isOffsetParentAnElement&&!isFixed){if(getNodeName(offsetParent)!=='body'||// https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)){scroll=getNodeScroll(offsetParent);}if(isHTMLElement(offsetParent)){offsets=getBoundingClientRect(offsetParent);offsets.x+=offsetParent.clientLeft;offsets.y+=offsetParent.clientTop;}else if(documentElement){offsets.x=getWindowScrollBarX(documentElement);}}return {x:rect.left+scroll.scrollLeft-offsets.x,y:rect.top+scroll.scrollTop-offsets.y,width:rect.width,height:rect.height};}
function order(modifiers){var map=new Map();var visited=new Set();var result=[];modifiers.forEach(function(modifier){map.set(modifier.name,modifier);});// On visiting object, check for its dependencies and visit them recursively
function sort(modifier){visited.add(modifier.name);var requires=[].concat(modifier.requires||[],modifier.requiresIfExists||[]);requires.forEach(function(dep){if(!visited.has(dep)){var depModifier=map.get(dep);if(depModifier){sort(depModifier);}}});result.push(modifier);}modifiers.forEach(function(modifier){if(!visited.has(modifier.name)){// check for visited object
sort(modifier);}});return result;}function orderModifiers(modifiers){// order based on dependencies
var orderedModifiers=order(modifiers);// order based on phase
return modifierPhases.reduce(function(acc,phase){return acc.concat(orderedModifiers.filter(function(modifier){return modifier.phase===phase;}));},[]);}
function debounce(fn){var pending;return function(){if(!pending){pending=new Promise(function(resolve){Promise.resolve().then(function(){pending=undefined;resolve(fn());});});}return pending;};}
function format$1(str){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}return [].concat(args).reduce(function(p,c){return p.replace(/%s/,c);},str);}
var INVALID_MODIFIER_ERROR='Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';var MISSING_DEPENDENCY_ERROR='Popper: modifier "%s" requires "%s", but "%s" modifier is not available';var VALID_PROPERTIES=['name','enabled','phase','fn','effect','requires','options'];function validateModifiers(modifiers){modifiers.forEach(function(modifier){Object.keys(modifier).forEach(function(key){switch(key){case'name':if(typeof modifier.name!=='string'){console.error(format$1(INVALID_MODIFIER_ERROR,String(modifier.name),'"name"','"string"',"\""+String(modifier.name)+"\""));}break;case'enabled':if(typeof modifier.enabled!=='boolean'){console.error(format$1(INVALID_MODIFIER_ERROR,modifier.name,'"enabled"','"boolean"',"\""+String(modifier.enabled)+"\""));}case'phase':if(modifierPhases.indexOf(modifier.phase)<0){console.error(format$1(INVALID_MODIFIER_ERROR,modifier.name,'"phase"',"either "+modifierPhases.join(', '),"\""+String(modifier.phase)+"\""));}break;case'fn':if(typeof modifier.fn!=='function'){console.error(format$1(INVALID_MODIFIER_ERROR,modifier.name,'"fn"','"function"',"\""+String(modifier.fn)+"\""));}break;case'effect':if(typeof modifier.effect!=='function'){console.error(format$1(INVALID_MODIFIER_ERROR,modifier.name,'"effect"','"function"',"\""+String(modifier.fn)+"\""));}break;case'requires':if(!Array.isArray(modifier.requires)){console.error(format$1(INVALID_MODIFIER_ERROR,modifier.name,'"requires"','"array"',"\""+String(modifier.requires)+"\""));}break;case'requiresIfExists':if(!Array.isArray(modifier.requiresIfExists)){console.error(format$1(INVALID_MODIFIER_ERROR,modifier.name,'"requiresIfExists"','"array"',"\""+String(modifier.requiresIfExists)+"\""));}break;case'options':case'data':break;default:console.error("PopperJS: an invalid property has been provided to the \""+modifier.name+"\" modifier, valid properties are "+VALID_PROPERTIES.map(function(s){return "\""+s+"\"";}).join(', ')+"; but \""+key+"\" was provided.");}modifier.requires&&modifier.requires.forEach(function(requirement){if(modifiers.find(function(mod){return mod.name===requirement;})==null){console.error(format$1(MISSING_DEPENDENCY_ERROR,String(modifier.name),requirement,requirement));}});});});}
function uniqueBy(arr,fn){var identifiers=new Set();return arr.filter(function(item){var identifier=fn(item);if(!identifiers.has(identifier)){identifiers.add(identifier);return true;}});}
function mergeByName(modifiers){var merged=modifiers.reduce(function(merged,current){var existing=merged[current.name];merged[current.name]=existing?Object.assign({},existing,current,{options:Object.assign({},existing.options,current.options),data:Object.assign({},existing.data,current.data)}):current;return merged;},{});// IE11 does not support Object.values
return Object.keys(merged).map(function(key){return merged[key];});}
var INVALID_ELEMENT_ERROR='Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';var INFINITE_LOOP_ERROR='Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';var DEFAULT_OPTIONS={placement:'bottom',modifiers:[],strategy:'absolute'};function areValidElements(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}return !args.some(function(element){return !(element&&typeof element.getBoundingClientRect==='function');});}function popperGenerator(generatorOptions){if(generatorOptions===void 0){generatorOptions={};}var _generatorOptions=generatorOptions,_generatorOptions$def=_generatorOptions.defaultModifiers,defaultModifiers=_generatorOptions$def===void 0?[]:_generatorOptions$def,_generatorOptions$def2=_generatorOptions.defaultOptions,defaultOptions=_generatorOptions$def2===void 0?DEFAULT_OPTIONS:_generatorOptions$def2;return function createPopper(reference,popper,options){if(options===void 0){options=defaultOptions;}var state={placement:'bottom',orderedModifiers:[],options:Object.assign({},DEFAULT_OPTIONS,defaultOptions),modifiersData:{},elements:{reference:reference,popper:popper},attributes:{},styles:{}};var effectCleanupFns=[];var isDestroyed=false;var instance={state:state,setOptions:function setOptions(options){cleanupModifierEffects();state.options=Object.assign({},defaultOptions,state.options,options);state.scrollParents={reference:isElement(reference)?listScrollParents(reference):reference.contextElement?listScrollParents(reference.contextElement):[],popper:listScrollParents(popper)};// Orders the modifiers based on their dependencies and `phase`
// properties
var orderedModifiers=orderModifiers(mergeByName([].concat(defaultModifiers,state.options.modifiers)));// Strip out disabled modifiers
state.orderedModifiers=orderedModifiers.filter(function(m){return m.enabled;});// Validate the provided modifiers so that the consumer will get warned
// if one of the modifiers is invalid for any reason
{var modifiers=uniqueBy([].concat(orderedModifiers,state.options.modifiers),function(_ref){var name=_ref.name;return name;});validateModifiers(modifiers);if(getBasePlacement(state.options.placement)===auto){var flipModifier=state.orderedModifiers.find(function(_ref2){var name=_ref2.name;return name==='flip';});if(!flipModifier){console.error(['Popper: "auto" placements require the "flip" modifier be','present and enabled to work.'].join(' '));}}var _getComputedStyle=getComputedStyle(popper),marginTop=_getComputedStyle.marginTop,marginRight=_getComputedStyle.marginRight,marginBottom=_getComputedStyle.marginBottom,marginLeft=_getComputedStyle.marginLeft;// We no longer take into account `margins` on the popper, and it can
// cause bugs with positioning, so we'll warn the consumer
if([marginTop,marginRight,marginBottom,marginLeft].some(function(margin){return parseFloat(margin);})){console.warn(['Popper: CSS "margin" styles cannot be used to apply padding','between the popper and its reference element or boundary.','To replicate margin, use the `offset` modifier, as well as','the `padding` option in the `preventOverflow` and `flip`','modifiers.'].join(' '));}}runModifierEffects();return instance.update();},// Sync update it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate:function forceUpdate(){if(isDestroyed){return;}var _state$elements=state.elements,reference=_state$elements.reference,popper=_state$elements.popper;// Don't proceed if `reference` or `popper` are not valid elements
// anymore
if(!areValidElements(reference,popper)){{console.error(INVALID_ELEMENT_ERROR);}return;}// Store the reference and popper rects to be read by modifiers
state.rects={reference:getCompositeRect(reference,getOffsetParent(popper),state.options.strategy==='fixed'),popper:getLayoutRect(popper)};// Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset=false;state.placement=state.options.placement;// On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(function(modifier){return state.modifiersData[modifier.name]=Object.assign({},modifier.data);});var __debug_loops__=0;for(var index=0;index<state.orderedModifiers.length;index++){{__debug_loops__+=1;if(__debug_loops__>100){console.error(INFINITE_LOOP_ERROR);break;}}if(state.reset===true){state.reset=false;index=-1;continue;}var _state$orderedModifie=state.orderedModifiers[index],fn=_state$orderedModifie.fn,_state$orderedModifie2=_state$orderedModifie.options,_options=_state$orderedModifie2===void 0?{}:_state$orderedModifie2,name=_state$orderedModifie.name;if(typeof fn==='function'){state=fn({state:state,options:_options,name:name,instance:instance})||state;}}},// Async and optimistically optimized update it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update:debounce(function(){return new Promise(function(resolve){instance.forceUpdate();resolve(state);});}),destroy:function destroy(){cleanupModifierEffects();isDestroyed=true;}};if(!areValidElements(reference,popper)){{console.error(INVALID_ELEMENT_ERROR);}return instance;}instance.setOptions(options).then(function(state){if(!isDestroyed&&options.onFirstUpdate){options.onFirstUpdate(state);}});// Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects(){state.orderedModifiers.forEach(function(_ref3){var name=_ref3.name,_ref3$options=_ref3.options,options=_ref3$options===void 0?{}:_ref3$options,effect=_ref3.effect;if(typeof effect==='function'){var cleanupFn=effect({state:state,name:name,instance:instance,options:options});var noopFn=function noopFn(){};effectCleanupFns.push(cleanupFn||noopFn);}});}function cleanupModifierEffects(){effectCleanupFns.forEach(function(fn){return fn();});effectCleanupFns=[];}return instance;};}
var defaultModifiers=[eventListeners,popperOffsets$1,computeStyles$1,applyStyles$1,offset$1,flip$1,preventOverflow$1,arrow$1,hide$1];var createPopper=/*#__PURE__*/popperGenerator({defaultModifiers:defaultModifiers});// eslint-disable-next-line import/no-unused-modules
/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */
var hasElementType=typeof Element!=='undefined';var hasMap=typeof Map==='function';var hasSet=typeof Set==='function';var hasArrayBuffer=typeof ArrayBuffer==='function'&&!!ArrayBuffer.isView;// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js
function equal$1(a,b){// START: fast-deep-equal es6/index.js 3.1.1
if(a===b)return true;if(a&&b&&typeof a=='object'&&typeof b=='object'){if(a.constructor!==b.constructor)return false;var length,i,keys;if(Array.isArray(a)){length=a.length;if(length!=b.length)return false;for(i=length;i--!==0;)if(!equal$1(a[i],b[i]))return false;return true;}// START: Modifications:
// 1. Extra `has<Type> &&` helpers in initial condition allow es6 code
// to co-exist with es5.
// 2. Replace `for of` with es5 compliant iteration using `for`.
// Basically, take:
//
// ```js
// for (i of a.entries())
// if (!b.has(i[0])) return false;
// ```
//
// ... and convert to:
//
// ```js
// it = a.entries();
// while (!(i = it.next()).done)
// if (!b.has(i.value[0])) return false;
// ```
//
// **Note**: `i` access switches to `i.value`.
var it;if(hasMap&&a instanceof Map&&b instanceof Map){if(a.size!==b.size)return false;it=a.entries();while(!(i=it.next()).done)if(!b.has(i.value[0]))return false;it=a.entries();while(!(i=it.next()).done)if(!equal$1(i.value[1],b.get(i.value[0])))return false;return true;}if(hasSet&&a instanceof Set&&b instanceof Set){if(a.size!==b.size)return false;it=a.entries();while(!(i=it.next()).done)if(!b.has(i.value[0]))return false;return true;}// END: Modifications
if(hasArrayBuffer&&ArrayBuffer.isView(a)&&ArrayBuffer.isView(b)){length=a.length;if(length!=b.length)return false;for(i=length;i--!==0;)if(a[i]!==b[i])return false;return true;}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();keys=Object.keys(a);length=keys.length;if(length!==Object.keys(b).length)return false;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys[i]))return false;// END: fast-deep-equal
// START: react-fast-compare
// custom handling for DOM elements
if(hasElementType&&a instanceof Element)return false;// custom handling for React/Preact
for(i=length;i--!==0;){if((keys[i]==='_owner'||keys[i]==='__v'||keys[i]==='__o')&&a.$$typeof){// React-specific: avoid traversing React elements' _owner
// Preact-specific: avoid traversing Preact elements' __v and __o
// __v = $_original / $_vnode
// __o = $_owner
// These properties contain circular references and are not needed when
// comparing the actual elements (and not their owners)
// .$$typeof and ._store on just reasonable markers of elements
continue;}// all other properties should be traversed as usual
if(!equal$1(a[keys[i]],b[keys[i]]))return false;}// END: react-fast-compare
// START: fast-deep-equal
return true;}return a!==a&&b!==b;}// end fast-deep-equal
var reactFastCompare=function isEqual(a,b){try{return equal$1(a,b);}catch(error){if((error.message||'').match(/stack|recursion/i)){// warn on circular references, don't crash
// browsers give this different errors name and messages:
// chrome/safari: "RangeError", "Maximum call stack size exceeded"
// firefox: "InternalError", too much recursion"
// edge: "Error", "Out of stack space"
console.warn('react-fast-compare cannot handle circular refs');return false;}// some other error. we should definitely know about these
throw error;}};
var EMPTY_MODIFIERS=[];var usePopper=function usePopper(referenceElement,popperElement,options){if(options===void 0){options={};}var prevOptions=react.useRef(null);var optionsWithDefaults={onFirstUpdate:options.onFirstUpdate,placement:options.placement||'bottom',strategy:options.strategy||'absolute',modifiers:options.modifiers||EMPTY_MODIFIERS};var _React$useState=react.useState({styles:{popper:{position:optionsWithDefaults.strategy,left:'0',top:'0'},arrow:{position:'absolute'}},attributes:{}}),state=_React$useState[0],setState=_React$useState[1];var updateStateModifier=react.useMemo(function(){return {name:'updateState',enabled:true,phase:'write',fn:function fn(_ref){var state=_ref.state;var elements=Object.keys(state.elements);setState({styles:fromEntries(elements.map(function(element){return [element,state.styles[element]||{}];})),attributes:fromEntries(elements.map(function(element){return [element,state.attributes[element]];}))});},requires:['computeStyles']};},[]);var popperOptions=react.useMemo(function(){var newOptions={onFirstUpdate:optionsWithDefaults.onFirstUpdate,placement:optionsWithDefaults.placement,strategy:optionsWithDefaults.strategy,modifiers:[].concat(optionsWithDefaults.modifiers,[updateStateModifier,{name:'applyStyles',enabled:false}])};if(reactFastCompare(prevOptions.current,newOptions)){return prevOptions.current||newOptions;}else {prevOptions.current=newOptions;return newOptions;}},[optionsWithDefaults.onFirstUpdate,optionsWithDefaults.placement,optionsWithDefaults.strategy,optionsWithDefaults.modifiers,updateStateModifier]);var popperInstanceRef=react.useRef();useIsomorphicLayoutEffect(function(){if(popperInstanceRef.current){popperInstanceRef.current.setOptions(popperOptions);}},[popperOptions]);useIsomorphicLayoutEffect(function(){if(referenceElement==null||popperElement==null){return;}var createPopper$1=options.createPopper||createPopper;var popperInstance=createPopper$1(referenceElement,popperElement,popperOptions);popperInstanceRef.current=popperInstance;return function(){popperInstance.destroy();popperInstanceRef.current=null;};},[referenceElement,popperElement,options.createPopper]);return {state:popperInstanceRef.current?popperInstanceRef.current.state:null,styles:state.styles,attributes:state.attributes,update:popperInstanceRef.current?popperInstanceRef.current.update:null,forceUpdate:popperInstanceRef.current?popperInstanceRef.current.forceUpdate:null};};
3 years ago
// TODO: Consider switching from Fuse to Match-Sorter
// https://github.com/kentcdodds/match-sorter
const TextSuggest = (props) => {
const [currentValue, setCurrentValue] = react.useState(props.field.value);
const [currentSuggestions, setCurrentSuggestions] = react.useState(props.suggestions.slice(0, props.displayCount));
const [fuse, setFuse] = react.useState(new Fuse(props.suggestions, { threshold: 0.5 }));
const [selectedIndex, setSelectedIndex] = react.useState(0);
const [visible, setVisibility] = react.useState(false);
const [referenceElement, setReferenceElement] = react.useState(null);
const [popperElement, setPopperElement] = react.useState(null);
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: 'bottom-start',
});
const updateCurrentSuggestions = (newValue) => {
const newSuggestions = newValue === ''
? props.suggestions.slice(0, props.displayCount)
: fuse
.search(newValue)
.map((result) => result.item)
.slice(0, props.displayCount);
setCurrentSuggestions(newSuggestions);
setSelectedIndex(Math.min(selectedIndex, newSuggestions.length - 1));
};
// The Fuse object will not be automatically replaced when the suggestions are
// changed so we need to detect and update manually.
react.useEffect(() => {
setFuse(new Fuse(props.suggestions, { threshold: 0.5 }));
updateCurrentSuggestions(currentValue);
}, [props.suggestions]);
return (react.createElement(react.Fragment, null,
react.createElement("input", { ref: setReferenceElement, type: "text", value: currentValue, placeholder: props.placeholder, onChange: (e) => {
setVisibility(true);
setCurrentValue(e.target.value);
updateCurrentSuggestions(e.target.value);
}, onFocus: () => {
setVisibility(true);
setSelectedIndex(0);
}, onBlur: (e) => {
setVisibility(false);
setCurrentValue(e.target.value);
props.form.setFieldValue(props.field.name, e.target.value);
}, onKeyDown: (e) => {
switch (e.key) {
case 'ArrowUp':
setSelectedIndex(Math.clamp(selectedIndex - 1, 0, currentSuggestions.length - 1));
e.preventDefault();
return;
case 'ArrowDown':
setSelectedIndex(Math.clamp(selectedIndex + 1, 0, currentSuggestions.length - 1));
e.preventDefault();
return;
case 'Enter':
setCurrentValue(currentSuggestions[selectedIndex]);
props.form.setFieldValue(props.field.name, currentSuggestions[selectedIndex]);
setVisibility(false);
e.preventDefault();
return;
}
} }),
visible ? (react.createElement("div", Object.assign({ className: "suggestion-container", ref: setPopperElement, style: styles.popper }, attributes.popper), currentSuggestions.map((s, i) => (react.createElement(Suggestion, { value: s, key: s, selected: i === selectedIndex, onClick: () => {
setCurrentValue(s);
props.form.setFieldValue(props.field.name, s);
setCurrentValue(s);
setVisibility(false);
}, onHover: () => {
setSelectedIndex(i);
} }))))) : null));
};
const Suggestion = ({ value, selected, onClick, onHover }) => (react.createElement("div", { className: 'suggestion-item ' + (selected ? 'is-selected' : ''), onMouseDown: onClick, onMouseOver: onHover }, value));
var isArray$1=Array.isArray;var keyList=Object.keys;var hasProp=Object.prototype.hasOwnProperty;var hasElementType$1=typeof Element!=='undefined';function equal$2(a,b){// fast-deep-equal index.js 2.0.1
if(a===b)return true;if(a&&b&&typeof a=='object'&&typeof b=='object'){var arrA=isArray$1(a),arrB=isArray$1(b),i,length,key;if(arrA&&arrB){length=a.length;if(length!=b.length)return false;for(i=length;i--!==0;)if(!equal$2(a[i],b[i]))return false;return true;}if(arrA!=arrB)return false;var dateA=a instanceof Date,dateB=b instanceof Date;if(dateA!=dateB)return false;if(dateA&&dateB)return a.getTime()==b.getTime();var regexpA=a instanceof RegExp,regexpB=b instanceof RegExp;if(regexpA!=regexpB)return false;if(regexpA&&regexpB)return a.toString()==b.toString();var keys=keyList(a);length=keys.length;if(length!==keyList(b).length)return false;for(i=length;i--!==0;)if(!hasProp.call(b,keys[i]))return false;// end fast-deep-equal
// start react-fast-compare
// custom handling for DOM elements
if(hasElementType$1&&a instanceof Element&&b instanceof Element)return a===b;// custom handling for React
for(i=length;i--!==0;){key=keys[i];if(key==='_owner'&&a.$$typeof){// React-specific: avoid traversing React elements' _owner.
// _owner contains circular references
// and is not needed when comparing the actual elements (and not their owners)
// .$$typeof and ._store on just reasonable markers of a react element
continue;}else {// all other properties should be traversed as usual
if(!equal$2(a[key],b[key]))return false;}}// end react-fast-compare
// fast-deep-equal index.js 2.0.1
return true;}return a!==a&&b!==b;}// end fast-deep-equal
var reactFastCompare$1=function exportedEqual(a,b){try{return equal$2(a,b);}catch(error){if(error.message&&error.message.match(/stack|recursion/i)||error.number===-2146828260){// warn on circular references, don't crash
// browsers give this different errors name and messages:
// chrome/safari: "RangeError", "Maximum call stack size exceeded"
// firefox: "InternalError", too much recursion"
// edge: "Error", "Out of stack space"
console.warn('Warning: react-fast-compare does not handle circular references.',error.name,error.message);return false;}// some other error. we should definitely know about these
throw error;}};
var isMergeableObject=function isMergeableObject(value){return isNonNullObject(value)&&!isSpecial(value);};function isNonNullObject(value){return !!value&&typeof value==='object';}function isSpecial(value){var stringValue=Object.prototype.toString.call(value);return stringValue==='[object RegExp]'||stringValue==='[object Date]'||isReactElement(value);}// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol=typeof Symbol==='function'&&Symbol.for;var REACT_ELEMENT_TYPE=canUseSymbol?Symbol.for('react.element'):0xeac7;function isReactElement(value){return value.$$typeof===REACT_ELEMENT_TYPE;}function emptyTarget(val){return Array.isArray(val)?[]:{};}function cloneUnlessOtherwiseSpecified(value,options){return options.clone!==false&&options.isMergeableObject(value)?deepmerge(emptyTarget(value),value,options):value;}function defaultArrayMerge(target,source,options){return target.concat(source).map(function(element){return cloneUnlessOtherwiseSpecified(element,options);});}function mergeObject(target,source,options){var destination={};if(options.isMergeableObject(target)){Object.keys(target).forEach(function(key){destination[key]=cloneUnlessOtherwiseSpecified(target[key],options);});}Object.keys(source).forEach(function(key){if(!options.isMergeableObject(source[key])||!target[key]){destination[key]=cloneUnlessOtherwiseSpecified(source[key],options);}else {destination[key]=deepmerge(target[key],source[key],options);}});return destination;}function deepmerge(target,source,options){options=options||{};options.arrayMerge=options.arrayMerge||defaultArrayMerge;options.isMergeableObject=options.isMergeableObject||isMergeableObject;var sourceIsArray=Array.isArray(source);var targetIsArray=Array.isArray(target);var sourceAndTargetTypesMatch=sourceIsArray===targetIsArray;if(!sourceAndTargetTypesMatch){return cloneUnlessOtherwiseSpecified(source,options);}else if(sourceIsArray){return options.arrayMerge(target,source,options);}else {return mergeObject(target,source,options);}}deepmerge.all=function deepmergeAll(array,options){if(!Array.isArray(array)){throw new Error('first argument should be an array');}return array.reduce(function(prev,next){return deepmerge(prev,next,options);},{});};var deepmerge_1=deepmerge;
/** Detect free variable `global` from Node.js. */var freeGlobal=typeof global=='object'&&global&&global.Object===Object&&global;
/** 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')();
/** Built-in value references. */var Symbol$1=root.Symbol;
/** Used for built-in method references. */var objectProto=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$1=objectProto.hasOwnProperty;/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/var nativeObjectToString=objectProto.toString;/** Built-in value references. */var symToStringTag=Symbol$1?Symbol$1.toStringTag:undefined;/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/function getRawTag(value){var isOwn=hasOwnProperty$1.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=undefined;var unmasked=true;}catch(e){}var result=nativeObjectToString.call(value);if(unmasked){if(isOwn){value[symToStringTag]=tag;}else {delete value[symToStringTag];}}return result;}
/** Used for built-in method references. */var objectProto$1=Object.prototype;/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/var nativeObjectToString$1=objectProto$1.toString;/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/function objectToString(value){return nativeObjectToString$1.call(value);}
/** `Object#toString` result references. */var nullTag='[object Null]',undefinedTag='[object Undefined]';/** Built-in value references. */var symToStringTag$1=Symbol$1?Symbol$1.toStringTag:undefined;/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/function baseGetTag(value){if(value==null){return value===undefined?undefinedTag:nullTag;}return symToStringTag$1&&symToStringTag$1 in Object(value)?getRawTag(value):objectToString(value);}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/function overArg(func,transform){return function(arg){return func(transform(arg));};}
/** Built-in value references. */var getPrototype=overArg(Object.getPrototypeOf,Object);
/**
* 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$1(value){return value!=null&&typeof value=='object';}
/** `Object#toString` result references. */var objectTag='[object Object]';/** Used for built-in method references. */var funcProto=Function.prototype,objectProto$2=Object.prototype;/** Used to resolve the decompiled source of functions. */var funcToString=funcProto.toString;/** Used to check objects for own properties. */var hasOwnProperty$2=objectProto$2.hasOwnProperty;/** Used to infer the `Object` constructor. */var objectCtorString=funcToString.call(Object);/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/function isPlainObject(value){if(!isObjectLike$1(value)||baseGetTag(value)!=objectTag){return false;}var proto=getPrototype(value);if(proto===null){return true;}var Ctor=hasOwnProperty$2.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/function listCacheClear(){this.__data__=[];this.size=0;}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/function eq(value,other){return value===other||value!==value&&other!==other;}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/function assocIndexOf(array,key){var length=array.length;while(length--){if(eq(array[length][0],key)){return length;}}return -1;}
/** Used for built-in method references. */var arrayProto=Array.prototype;/** Built-in value references. */var splice=arrayProto.splice;/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){return false;}var lastIndex=data.length-1;if(index==lastIndex){data.pop();}else {splice.call(data,index,1);}--this.size;return true;}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?undefined:data[index][1];}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1;}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value]);}else {data[index][1]=value;}return this;}
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/function ListCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}// Add methods to `ListCache`.
ListCache.prototype.clear=listCacheClear;ListCache.prototype['delete']=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/function stackClear(){this.__data__=new ListCache();this.size=0;}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/function stackDelete(key){var data=this.__data__,result=data['delete'](key);this.size=data.size;return result;}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/function stackGet(key){return this.__data__.get(key);}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/function stackHas(key){return this.__data__.has(key);}
/**
* 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$1(value){var type=typeof value;return value!=null&&(type=='object'||type=='function');}
/** `Object#toString` result references. */var asyncTag='[object AsyncFunction]',funcTag='[object Function]',genTag='[object GeneratorFunction]',proxyTag='[object Proxy]';/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/function isFunction(value){if(!isObject$1(value)){return false;}// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}
/** Used to detect overreaching core-js shims. */var coreJsData=root['__core-js_shared__'];
/** Used to detect methods masquerading as native. */var maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||'');return uid?'Symbol(src)_1.'+uid:'';}();/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/function isMasked(func){return !!maskSrcKey&&maskSrcKey in func;}
/** Used for built-in method references. */var funcProto$1=Function.prototype;/** Used to resolve the decompiled source of functions. */var funcToString$1=funcProto$1.toString;/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/function toSource(func){if(func!=null){try{return funcToString$1.call(func);}catch(e){}try{return func+'';}catch(e){}}return '';}
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/var reRegExpChar=/[\\^$.*+?()[\]{}|]/g;/** Used to detect host constructors (Safari). */var reIsHostCtor=/^\[object .+?Constructor\]$/;/** Used for built-in method references. */var funcProto$2=Function.prototype,objectProto$3=Object.prototype;/** Used to resolve the decompiled source of functions. */var funcToString$2=funcProto$2.toString;/** Used to check objects for own properties. */var hasOwnProperty$3=objectProto$3.hasOwnProperty;/** Used to detect if a method is native. */var reIsNative=RegExp('^'+funcToString$2.call(hasOwnProperty$3).replace(reRegExpChar,'\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$');/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/function baseIsNative(value){if(!isObject$1(value)||isMasked(value)){return false;}var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value));}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/function getValue(object,key){return object==null?undefined:object[key];}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:undefined;}
/* Built-in method references that are verified to be native. */var Map$1=getNative(root,'Map');
/* Built-in method references that are verified to be native. */var nativeCreate=getNative(Object,'create');
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{};this.size=0;}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];this.size-=result?1:0;return result;}
/** Used to stand-in for `undefined` hash values. */var HASH_UNDEFINED='__lodash_hash_undefined__';/** Used for built-in method references. */var objectProto$4=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$4=objectProto$4.hasOwnProperty;/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?undefined:result;}return hasOwnProperty$4.call(data,key)?data[key]:undefined;}
/** Used for built-in method references. */var objectProto$5=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$5=objectProto$5.hasOwnProperty;/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/function hashHas(key){var data=this.__data__;return nativeCreate?data[key]!==undefined:hasOwnProperty$5.call(data,key);}
/** Used to stand-in for `undefined` hash values. */var HASH_UNDEFINED$1='__lodash_hash_undefined__';/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/function hashSet(key,value){var data=this.__data__;this.size+=this.has(key)?0:1;data[key]=nativeCreate&&value===undefined?HASH_UNDEFINED$1:value;return this;}
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/function Hash(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}// Add methods to `Hash`.
Hash.prototype.clear=hashClear;Hash.prototype['delete']=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/function mapCacheClear(){this.size=0;this.__data__={'hash':new Hash(),'map':new(Map$1||ListCache)(),'string':new Hash()};}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/function isKeyable(value){var type=typeof value;return type=='string'||type=='number'||type=='symbol'||type=='boolean'?value!=='__proto__':value===null;}
3 years ago
/**
* Gets the data for `map`.
3 years ago
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data[typeof key=='string'?'string':'hash']:data.map;}
/**
* Removes `key` and its value from the map.
3 years ago
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/function mapCacheDelete(key){var result=getMapData(this,key)['delete'](key);this.size-=result?1:0;return result;}
3 years ago
/**
* Gets the map value for `key`.
3 years ago
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/function mapCacheGet(key){return getMapData(this,key).get(key);}
/**
* Checks if a map value for `key` exists.
3 years ago
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/function mapCacheHas(key){return getMapData(this,key).has(key);}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;data.set(key,value);this.size+=data.size==size?0:1;return this;}
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/function MapCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}// Add methods to `MapCache`.
MapCache.prototype.clear=mapCacheClear;MapCache.prototype['delete']=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;
/** Used as the size to enable large array optimizations. */var LARGE_ARRAY_SIZE=200;/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map$1||pairs.length<LARGE_ARRAY_SIZE-1){pairs.push([key,value]);this.size=++data.size;return this;}data=this.__data__=new MapCache(pairs);}data.set(key,value);this.size=data.size;return this;}
3 years ago
/**
* Creates a stack cache object to store key-value pairs.
*
3 years ago
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size;}// Add methods to `Stack`.
Stack.prototype.clear=stackClear;Stack.prototype['delete']=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
3 years ago
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/function arrayEach(array,iteratee){var index=-1,length=array==null?0:array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break;}}return array;}
var defineProperty$1=function(){try{var func=getNative(Object,'defineProperty');func({},'',{});return func;}catch(e){}}();
3 years ago
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
3 years ago
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/function baseAssignValue(object,key,value){if(key=='__proto__'&&defineProperty$1){defineProperty$1(object,key,{'configurable':true,'enumerable':true,'value':value,'writable':true});}else {object[key]=value;}}
/** Used for built-in method references. */var objectProto$6=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$6=objectProto$6.hasOwnProperty;/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
3 years ago
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/function assignValue(object,key,value){var objValue=object[key];if(!(hasOwnProperty$6.call(object,key)&&eq(objValue,value))||value===undefined&&!(key in object)){baseAssignValue(object,key,value);}}
/**
* Copies properties of `source` to `object`.
3 years ago
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/function copyObject(source,props,object,customizer){var isNew=!object;object||(object={});var index=-1,length=props.length;while(++index<length){var key=props[index];var newValue=customizer?customizer(object[key],source[key],key,object,source):undefined;if(newValue===undefined){newValue=source[key];}if(isNew){baseAssignValue(object,key,newValue);}else {assignValue(object,key,newValue);}}return object;}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
3 years ago
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index);}return result;}
/** `Object#toString` result references. */var argsTag='[object Arguments]';/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/function baseIsArguments(value){return isObjectLike$1(value)&&baseGetTag(value)==argsTag;}
/** Used for built-in method references. */var objectProto$7=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$7=objectProto$7.hasOwnProperty;/** Built-in value references. */var propertyIsEnumerable=objectProto$7.propertyIsEnumerable;/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike$1(value)&&hasOwnProperty$7.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/var isArray$2=Array.isArray;
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/function stubFalse(){return false;}
/** Detect free variable `exports`. */var freeExports=typeof exports=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&typeof module=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Built-in value references. */var Buffer=moduleExports?root.Buffer:undefined;/* Built-in method references for those with the same name as other `lodash` methods. */var nativeIsBuffer=Buffer?Buffer.isBuffer:undefined;/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/var isBuffer=nativeIsBuffer||stubFalse;
/** Used as references for various `Number` constants. */var MAX_SAFE_INTEGER=9007199254740991;/** Used to detect unsigned integer values. */var reIsUint=/^(?:0|[1-9]\d*)$/;/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/function isIndex(value,length){var type=typeof value;length=length==null?MAX_SAFE_INTEGER:length;return !!length&&(type=='number'||type!='symbol'&&reIsUint.test(value))&&value>-1&&value%1==0&&value<length;}
/** Used as references for various `Number` constants. */var MAX_SAFE_INTEGER$1=9007199254740991;/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER$1;}
/** `Object#toString` result references. */var argsTag$1='[object Arguments]',arrayTag='[object Array]',boolTag='[object Boolean]',dateTag='[object Date]',errorTag='[object Error]',funcTag$1='[object Function]',mapTag='[object Map]',numberTag='[object Number]',objectTag$1='[object Object]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',weakMapTag='[object WeakMap]';var arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]';/** Used to identify `toStringTag` values of typed arrays. */var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag$1]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/function baseIsTypedArray(value){return isObjectLike$1(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)];}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/function baseUnary(func){return function(value){return func(value);};}
/** Detect free variable `exports`. */var freeExports$1=typeof exports=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule$1=freeExports$1&&typeof module=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1;/** Detect free variable `process` from Node.js. */var freeProcess=moduleExports$1&&freeGlobal.process;/** Used to access faster Node.js helpers. */var nodeUtil=function(){try{// Use `util.types` for Node.js 10+.
var types=freeModule$1&&freeModule$1.require&&freeModule$1.require('util').types;if(types){return types;}// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}();
/* Node.js helper references. */var nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;
/** Used for built-in method references. */var objectProto$8=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$8=objectProto$8.hasOwnProperty;/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/function arrayLikeKeys(value,inherited){var isArr=isArray$2(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value){if((inherited||hasOwnProperty$8.call(value,key))&&!(skipIndexes&&(// Safari 9 has enumerable `arguments.length` in strict mode.
key=='length'||// Node.js 0.10 has enumerable non-index properties on buffers.
isBuff&&(key=='offset'||key=='parent')||// PhantomJS 2 has enumerable non-index properties on typed arrays.
isType&&(key=='buffer'||key=='byteLength'||key=='byteOffset')||// Skip index properties.
isIndex(key,length)))){result.push(key);}}return result;}
/** Used for built-in method references. */var objectProto$9=Object.prototype;/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=='function'&&Ctor.prototype||objectProto$9;return value===proto;}
/* Built-in method references for those with the same name as other `lodash` methods. */var nativeKeys=overArg(Object.keys,Object);
/** Used for built-in method references. */var objectProto$a=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$9=objectProto$a.hasOwnProperty;/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/function baseKeys(object){if(!isPrototype(object)){return nativeKeys(object);}var result=[];for(var key in Object(object)){if(hasOwnProperty$9.call(object,key)&&key!='constructor'){result.push(key);}}return result;}
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/function baseAssign(object,source){return object&&copyObject(source,keys(source),object);}
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/function nativeKeysIn(object){var result=[];if(object!=null){for(var key in Object(object)){result.push(key);}}return result;}
/** Used for built-in method references. */var objectProto$b=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$a=objectProto$b.hasOwnProperty;/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/function baseKeysIn(object){if(!isObject$1(object)){return nativeKeysIn(object);}var isProto=isPrototype(object),result=[];for(var key in object){if(!(key=='constructor'&&(isProto||!hasOwnProperty$a.call(object,key)))){result.push(key);}}return result;}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,true):baseKeysIn(object);}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/function baseAssignIn(object,source){return object&&copyObject(source,keysIn(source),object);}
/** Detect free variable `exports`. */var freeExports$2=typeof exports=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule$2=freeExports$2&&typeof module=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2;/** Built-in value references. */var Buffer$1=moduleExports$2?root.Buffer:undefined,allocUnsafe=Buffer$1?Buffer$1.allocUnsafe:undefined;/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/function cloneBuffer(buffer,isDeep){if(isDeep){return buffer.slice();}var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);buffer.copy(result);return result;}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/function copyArray(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index];}return array;}
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/function arrayFilter(array,predicate){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[resIndex++]=value;}}return result;}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/function stubArray(){return [];}
/** Used for built-in method references. */var objectProto$c=Object.prototype;/** Built-in value references. */var propertyIsEnumerable$1=objectProto$c.propertyIsEnumerable;/* Built-in method references for those with the same name as other `lodash` methods. */var nativeGetSymbols=Object.getOwnPropertySymbols;/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/var getSymbols=!nativeGetSymbols?stubArray:function(object){if(object==null){return [];}object=Object(object);return arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable$1.call(object,symbol);});};
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/function copySymbols(source,object){return copyObject(source,getSymbols(source),object);}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/function arrayPush(array,values){var index=-1,length=values.length,offset=array.length;while(++index<length){array[offset+index]=values[index];}return array;}
/* Built-in method references for those with the same name as other `lodash` methods. */var nativeGetSymbols$1=Object.getOwnPropertySymbols;/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/var getSymbolsIn=!nativeGetSymbols$1?stubArray:function(object){var result=[];while(object){arrayPush(result,getSymbols(object));object=getPrototype(object);}return result;};
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/function copySymbolsIn(source,object){return copyObject(source,getSymbolsIn(source),object);}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
3 years ago
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray$2(object)?result:arrayPush(result,symbolsFunc(object));}
/**
* Creates an array of own enumerable property names and symbols of `object`.
3 years ago
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols);}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
3 years ago
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/function getAllKeysIn(object){return baseGetAllKeys(object,keysIn,getSymbolsIn);}
/* Built-in method references that are verified to be native. */var DataView=getNative(root,'DataView');
/* Built-in method references that are verified to be native. */var Promise$1=getNative(root,'Promise');
/* Built-in method references that are verified to be native. */var Set$1=getNative(root,'Set');
/* Built-in method references that are verified to be native. */var WeakMap$1=getNative(root,'WeakMap');
/** `Object#toString` result references. */var mapTag$1='[object Map]',objectTag$2='[object Object]',promiseTag='[object Promise]',setTag$1='[object Set]',weakMapTag$1='[object WeakMap]';var dataViewTag$1='[object DataView]';/** Used to detect maps, sets, and weakmaps. */var dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map$1),promiseCtorString=toSource(Promise$1),setCtorString=toSource(Set$1),weakMapCtorString=toSource(WeakMap$1);/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/var getTag$1=baseGetTag;// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if(DataView&&getTag$1(new DataView(new ArrayBuffer(1)))!=dataViewTag$1||Map$1&&getTag$1(new Map$1())!=mapTag$1||Promise$1&&getTag$1(Promise$1.resolve())!=promiseTag||Set$1&&getTag$1(new Set$1())!=setTag$1||WeakMap$1&&getTag$1(new WeakMap$1())!=weakMapTag$1){getTag$1=function(value){var result=baseGetTag(value),Ctor=result==objectTag$2?value.constructor:undefined,ctorString=Ctor?toSource(Ctor):'';if(ctorString){switch(ctorString){case dataViewCtorString:return dataViewTag$1;case mapCtorString:return mapTag$1;case promiseCtorString:return promiseTag;case setCtorString:return setTag$1;case weakMapCtorString:return weakMapTag$1;}}return result;};}var getTag$2 = getTag$1;
/** Used for built-in method references. */var objectProto$d=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty$b=objectProto$d.hasOwnProperty;/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/function initCloneArray(array){var length=array.length,result=new array.constructor(length);// Add properties assigned by `RegExp#exec`.
if(length&&typeof array[0]=='string'&&hasOwnProperty$b.call(array,'index')){result.index=array.index;result.input=array.input;}return result;}
/** Built-in value references. */var Uint8Array=root.Uint8Array;
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);new Uint8Array(result).set(new Uint8Array(arrayBuffer));return result;}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength);}
/** Used to match `RegExp` flags from their coerced string values. */var reFlags=/\w*$/;/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result;}
/** Used to convert symbols to primitives and strings. */var symbolProto=Symbol$1?Symbol$1.prototype:undefined,symbolValueOf=symbolProto?symbolProto.valueOf:undefined;/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{};}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length);}
/** `Object#toString` result references. */var boolTag$1='[object Boolean]',dateTag$1='[object Date]',mapTag$2='[object Map]',numberTag$1='[object Number]',regexpTag$1='[object RegExp]',setTag$2='[object Set]',stringTag$1='[object String]',symbolTag='[object Symbol]';var arrayBufferTag$1='[object ArrayBuffer]',dataViewTag$2='[object DataView]',float32Tag$1='[object Float32Array]',float64Tag$1='[object Float64Array]',int8Tag$1='[object Int8Array]',int16Tag$1='[object Int16Array]',int32Tag$1='[object Int32Array]',uint8Tag$1='[object Uint8Array]',uint8ClampedTag$1='[object Uint8ClampedArray]',uint16Tag$1='[object Uint16Array]',uint32Tag$1='[object Uint32Array]';/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag$1:return cloneArrayBuffer(object);case boolTag$1:case dateTag$1:return new Ctor(+object);case dataViewTag$2:return cloneDataView(object,isDeep);case float32Tag$1:case float64Tag$1:case int8Tag$1:case int16Tag$1:case int32Tag$1:case uint8Tag$1:case uint8ClampedTag$1:case uint16Tag$1:case uint32Tag$1:return cloneTypedArray(object,isDeep);case mapTag$2:return new Ctor();case numberTag$1:case stringTag$1:return new Ctor(object);case regexpTag$1:return cloneRegExp(object);case setTag$2:return new Ctor();case symbolTag:return cloneSymbol(object);}}
/** Built-in value references. */var objectCreate=Object.create;/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/var baseCreate=function(){function object(){}return function(proto){if(!isObject$1(proto)){return {};}if(objectCreate){return objectCreate(proto);}object.prototype=proto;var result=new object();object.prototype=undefined;return result;};}();
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/function initCloneObject(object){return typeof object.constructor=='function'&&!isPrototype(object)?baseCreate(getPrototype(object)):{};}
/** `Object#toString` result references. */var mapTag$3='[object Map]';/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/function baseIsMap(value){return isObjectLike$1(value)&&getTag$2(value)==mapTag$3;}
/* Node.js helper references. */var nodeIsMap=nodeUtil&&nodeUtil.isMap;/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/var isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap;
/** `Object#toString` result references. */var setTag$3='[object Set]';/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/function baseIsSet(value){return isObjectLike$1(value)&&getTag$2(value)==setTag$3;}
/* Node.js helper references. */var nodeIsSet=nodeUtil&&nodeUtil.isSet;/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/var isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet;
/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4;/** `Object#toString` result references. */var argsTag$2='[object Arguments]',arrayTag$1='[object Array]',boolTag$2='[object Boolean]',dateTag$2='[object Date]',errorTag$1='[object Error]',funcTag$2='[object Function]',genTag$1='[object GeneratorFunction]',mapTag$4='[object Map]',numberTag$2='[object Number]',objectTag$3='[object Object]',regexpTag$2='[object RegExp]',setTag$4='[object Set]',stringTag$2='[object String]',symbolTag$1='[object Symbol]',weakMapTag$2='[object WeakMap]';var arrayBufferTag$2='[object ArrayBuffer]',dataViewTag$3='[object DataView]',float32Tag$2='[object Float32Array]',float64Tag$2='[object Float64Array]',int8Tag$2='[object Int8Array]',int16Tag$2='[object Int16Array]',int32Tag$2='[object Int32Array]',uint8Tag$2='[object Uint8Array]',uint8ClampedTag$2='[object Uint8ClampedArray]',uint16Tag$2='[object Uint16Array]',uint32Tag$2='[object Uint32Array]';/** Used to identify `toStringTag` values supported by `_.clone`. */var cloneableTags={};cloneableTags[argsTag$2]=cloneableTags[arrayTag$1]=cloneableTags[arrayBufferTag$2]=cloneableTags[dataViewTag$3]=cloneableTags[boolTag$2]=cloneableTags[dateTag$2]=cloneableTags[float32Tag$2]=cloneableTags[float64Tag$2]=cloneableTags[int8Tag$2]=cloneableTags[int16Tag$2]=cloneableTags[int32Tag$2]=cloneableTags[mapTag$4]=cloneableTags[numberTag$2]=cloneableTags[objectTag$3]=cloneableTags[regexpTag$2]=cloneableTags[setTag$4]=cloneableTags[stringTag$2]=cloneableTags[symbolTag$1]=cloneableTags[uint8Tag$2]=cloneableTags[uint8ClampedTag$2]=cloneableTags[uint16Tag$2]=cloneableTags[uint32Tag$2]=true;cloneableTags[errorTag$1]=cloneableTags[funcTag$2]=cloneableTags[weakMapTag$2]=false;/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,isFull=bitmask&CLONE_SYMBOLS_FLAG;if(customizer){result=object?customizer(value,key,object,stack):customizer(value);}if(result!==undefined){return result;}if(!isObject$1(value)){return value;}var isArr=isArray$2(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result);}}else {var tag=getTag$2(value),isFunc=tag==funcTag$2||tag==genTag$1;if(isBuffer(value)){return cloneBuffer(value,isDeep);}if(tag==objectTag$3||tag==argsTag$2||isFunc&&!object){result=isFlat||isFunc?{}:initCloneObject(value);if(!isDeep){return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value));}}else {if(!cloneableTags[tag]){return object?value:{};}result=initCloneByTag(value,tag,isDeep);}}// Check for circular references and return its corresponding clone.
stack||(stack=new Stack());var stacked=stack.get(value);if(stacked){return stacked;}stack.set(value,result);if(isSet(value)){value.forEach(function(subValue){result.add(baseClone(subValue,bitmask,customizer,subValue,value,stack));});}else if(isMap(value)){value.forEach(function(subValue,key){result.set(key,baseClone(subValue,bitmask,customizer,key,value,stack));});}var keysFunc=isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys;var props=isArr?undefined:keysFunc(value);arrayEach(props||value,function(subValue,key){if(props){key=subValue;subValue=value[key];}// Recursively populate clone (susceptible to call stack limits).
assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack));});return result;}
/** Used to compose bitmasks for cloning. */var CLONE_SYMBOLS_FLAG$1=4;/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/function clone(value){return baseClone(value,CLONE_SYMBOLS_FLAG$1);}
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/function arrayMap(array,iteratee){var index=-1,length=array==null?0:array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array);}return result;}
3 years ago
/** `Object#toString` result references. */var symbolTag$2='[object Symbol]';/**
* 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$1(value)&&baseGetTag(value)==symbolTag$2;}
3 years ago
/** Error message constants. */var FUNC_ERROR_TEXT='Expected a function';/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/function memoize$1(func,resolver){if(typeof func!='function'||resolver!=null&&typeof resolver!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize$1.Cache||MapCache)();return memoized;}// Expose `MapCache`.
memoize$1.Cache=MapCache;
3 years ago
/** Used as the maximum memoize cache size. */var MAX_MEMOIZE_SIZE=500;/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/function memoizeCapped(func){var result=memoize$1(func,function(key){if(cache.size===MAX_MEMOIZE_SIZE){cache.clear();}return key;});var cache=result.cache;return result;}
3 years ago
/** Used to match property names within property paths. */var rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;/** Used to match backslashes in property paths. */var reEscapeChar=/\\(\\)?/g;/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/var stringToPath=memoizeCapped(function(string){var result=[];if(string.charCodeAt(0)===46/* . */){result.push('');}string.replace(rePropName,function(match,number,quote,subString){result.push(quote?subString.replace(reEscapeChar,'$1'):number||match);});return result;});
3 years ago
/** Used as references for various `Number` constants. */var INFINITY$1=1/0;/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/function toKey(value){if(typeof value=='string'||isSymbol(value)){return value;}var result=value+'';return result=='0'&&1/value==-INFINITY$1?'-0':result;}
3 years ago
/** Used as references for various `Number` constants. */var INFINITY$2=1/0;/** Used to convert symbols to primitives and strings. */var symbolProto$1=Symbol$1?Symbol$1.prototype:undefined,symbolToString=symbolProto$1?symbolProto$1.toString:undefined;/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/function baseToString$1(value){// Exit early for strings to avoid a performance hit in some environments.
if(typeof value=='string'){return value;}if(isArray$2(value)){// Recursively convert values (susceptible to call stack limits).
return arrayMap(value,baseToString$1)+'';}if(isSymbol(value)){return symbolToString?symbolToString.call(value):'';}var result=value+'';return result=='0'&&1/value==-INFINITY$2?'-0':result;}
3 years ago
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/function toString$1(value){return value==null?'':baseToString$1(value);}
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/function toPath(value){if(isArray$2(value)){return arrayMap(value,toKey);}return isSymbol(value)?[value]:copyArray(stringToPath(toString$1(value)));}
function warning(condition,message){{if(condition){return;}var text="Warning: "+message;if(typeof console!=='undefined'){console.warn(text);}try{throw Error(text);}catch(x){}}}
/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG$1=1,CLONE_SYMBOLS_FLAG$2=4;/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/function cloneDeep(value){return baseClone(value,CLONE_DEEP_FLAG$1|CLONE_SYMBOLS_FLAG$2);}
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return {};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}/** @private is the value an empty array? */var isEmptyArray=function isEmptyArray(value){return Array.isArray(value)&&value.length===0;};/** @private is the given object a Function? */var isFunction$1=function isFunction(obj){return typeof obj==='function';};/** @private is the given object an Object? */var isObject$2=function isObject(obj){return obj!==null&&typeof obj==='object';};/** @private is the given object an integer? */var isInteger=function isInteger(obj){return String(Math.floor(Number(obj)))===obj;};/** @private is the given object a string? */var isString$1=function isString(obj){return Object.prototype.toString.call(obj)==='[object String]';};/** @private is the given object a NaN? */ // eslint-disable-next-line no-self-compare
/** @private Does a React component have exactly 0 children? */var isEmptyChildren=function isEmptyChildren(children){return react.Children.count(children)===0;};/** @private is the given object/value a promise? */var isPromise=function isPromise(value){return isObject$2(value)&&isFunction$1(value.then);};/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*
* @param {?Document} doc Defaults to current document.
* @return {Element | null}
* @see https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/dom/getActiveElement.js
*/function getActiveElement(doc){doc=doc||(typeof document!=='undefined'?document:undefined);if(typeof doc==='undefined'){return null;}try{return doc.activeElement||doc.body;}catch(e){return doc.body;}}/**
* Deeply get a value from an object via its path.
*/function getIn(obj,key,def,p){if(p===void 0){p=0;}var path=toPath(key);while(obj&&p<path.length){obj=obj[path[p++]];}return obj===undefined?def:obj;}/**
* Deeply set a value from in object via it's path. If the value at `path`
* has changed, return a shallow copy of obj with `value` set at `path`.
* If `value` has not changed, return the original `obj`.
*
* Existing objects / arrays along `path` are also shallow copied. Sibling
* objects along path retain the same internal js reference. Since new
* objects / arrays are only created along `path`, we can test if anything
* changed in a nested structure by comparing the object's reference in
* the old and new object, similar to how russian doll cache invalidation
* works.
*
* In earlier versions of this function, which used cloneDeep, there were
* issues whereby settings a nested value would mutate the parent
* instead of creating a new object. `clone` avoids that bug making a
* shallow copy of the objects along the update path
* so no object is mutated in place.
*
* Before changing this function, please read through the following
* discussions.
*
* @see https://github.com/developit/linkstate
* @see https://github.com/jaredpalmer/formik/pull/123
*/function setIn(obj,path,value){var res=clone(obj);// this keeps inheritance when obj is a class
var resVal=res;var i=0;var pathArray=toPath(path);for(;i<pathArray.length-1;i++){var currentPath=pathArray[i];var currentObj=getIn(obj,pathArray.slice(0,i+1));if(currentObj&&(isObject$2(currentObj)||Array.isArray(currentObj))){resVal=resVal[currentPath]=clone(currentObj);}else {var nextPath=pathArray[i+1];resVal=resVal[currentPath]=isInteger(nextPath)&&Number(nextPath)>=0?[]:{};}}// Return original object if new value is the same as current
if((i===0?obj:resVal)[pathArray[i]]===value){return obj;}if(value===undefined){delete resVal[pathArray[i]];}else {resVal[pathArray[i]]=value;}// If the path array has a single element, the loop did not run.
// Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.
if(i===0&&value===undefined){delete res[pathArray[i]];}return res;}/**
* Recursively a set the same value for all keys and arrays nested object, cloning
* @param object
* @param value
* @param visited
* @param response
*/function setNestedObjectValues(object,value,visited,response){if(visited===void 0){visited=new WeakMap();}if(response===void 0){response={};}for(var _i=0,_Object$keys=Object.keys(object);_i<_Object$keys.length;_i++){var k=_Object$keys[_i];var val=object[k];if(isObject$2(val)){if(!visited.get(val)){visited.set(val,true);// In order to keep array values consistent for both dot path and
// bracket syntax, we need to check if this is an array so that
// this will output { friends: [true] } and not { friends: { "0": true } }
response[k]=Array.isArray(val)?[]:{};setNestedObjectValues(val,value,visited,response[k]);}}else {response[k]=value;}}return response;}var FormikContext=/*#__PURE__*/react.createContext(undefined);FormikContext.displayName='FormikContext';var FormikProvider=FormikContext.Provider;var FormikConsumer=FormikContext.Consumer;function useFormikContext(){var formik=react.useContext(FormikContext);!!!formik?warning(false,"Formik context is undefined, please verify you are calling useFormikContext() as child of a <Formik> component."):void 0;return formik;}function formikReducer(state,msg){switch(msg.type){case'SET_VALUES':return _extends({},state,{values:msg.payload});case'SET_TOUCHED':return _extends({},state,{touched:msg.payload});case'SET_ERRORS':if(reactFastCompare$1(state.errors,msg.payload)){return state;}return _extends({},state,{errors:msg.payload});case'SET_STATUS':return _extends({},state,{status:msg.payload});case'SET_ISSUBMITTING':return _extends({},state,{isSubmitting:msg.payload});case'SET_ISVALIDATING':return _extends({},state,{isValidating:msg.payload});case'SET_FIELD_VALUE':return _extends({},state,{values:setIn(state.values,msg.payload.field,msg.payload.value)});case'SET_FIELD_TOUCHED':return _extends({},state,{touched:setIn(state.touched,msg.payload.field,msg.payload.value)});case'SET_FIELD_ERROR':return _extends({},state,{errors:setIn(state.errors,msg.payload.field,msg.payload.value)});case'RESET_FORM':return _extends({},state,msg.payload);case'SET_FORMIK_STATE':return msg.payload(state);case'SUBMIT_ATTEMPT':return _extends({},state,{touched:setNestedObjectValues(state.values,true),isSubmitting:true,submitCount:state.submitCount+1});case'SUBMIT_FAILURE':return _extends({},state,{isSubmitting:false});case'SUBMIT_SUCCESS':return _extends({},state,{isSubmitting:false});default:return state;}}// Initial empty states // objects
var emptyErrors={};var emptyTouched={};function useFormik(_ref){var _ref$validateOnChange=_ref.validateOnChange,validateOnChange=_ref$validateOnChange===void 0?true:_ref$validateOnChange,_ref$validateOnBlur=_ref.validateOnBlur,validateOnBlur=_ref$validateOnBlur===void 0?true:_ref$validateOnBlur,_ref$validateOnMount=_ref.validateOnMount,validateOnMount=_ref$validateOnMount===void 0?false:_ref$validateOnMount,isInitialValid=_ref.isInitialValid,_ref$enableReinitiali=_ref.enableReinitialize,enableReinitialize=_ref$enableReinitiali===void 0?false:_ref$enableReinitiali,onSubmit=_ref.onSubmit,rest=_objectWithoutPropertiesLoose(_ref,["validateOnChange","validateOnBlur","validateOnMount","isInitialValid","enableReinitialize","onSubmit"]);var props=_extends({validateOnChange:validateOnChange,validateOnBlur:validateOnBlur,validateOnMount:validateOnMount,onSubmit:onSubmit},rest);var initialValues=react.useRef(props.initialValues);var initialErrors=react.useRef(props.initialErrors||emptyErrors);var initialTouched=react.useRef(props.initialTouched||emptyTouched);var initialStatus=react.useRef(props.initialStatus);var isMounted=react.useRef(false);var fieldRegistry=react.useRef({});{// eslint-disable-next-line react-hooks/rules-of-hooks
react.useEffect(function(){!(typeof isInitialValid==='undefined')?warning(false,'isInitialValid has been deprecated and will be removed in future versions of Formik. Please use initialErrors or validateOnMount instead.'):void 0;// eslint-disable-next-line
},[]);}react.useEffect(function(){isMounted.current=true;return function(){isMounted.current=false;};},[]);var _React$useReducer=react.useReducer(formikReducer,{values:props.initialValues,errors:props.initialErrors||emptyErrors,touched:props.initialTouched||emptyTouched,status:props.initialStatus,isSubmitting:false,isValidating:false,submitCount:0}),state=_React$useReducer[0],dispatch=_React$useReducer[1];var runValidateHandler=react.useCallback(function(values,field){return new Promise(function(resolve,reject){var maybePromisedErrors=props.validate(values,field);if(maybePromisedErrors==null){// use loose null check here on purpose
resolve(emptyErrors);}else if(isPromise(maybePromisedErrors)){maybePromisedErrors.then(function(errors){resolve(errors||emptyErrors);},function(actualException){{console.warn("Warning: An unhandled error was caught during validation in <Formik validate />",actualException);}reject(actualException);});}else {resolve(maybePromisedErrors);}});},[props.validate]);/**
* Run validation against a Yup schema and optionally run a function if successful
*/var runValidationSchema=react.useCallback(function(values,field){var validationSchema=props.validationSchema;var schema=isFunction$1(validationSchema)?validationSchema(field):validationSchema;var promise=field&&schema.validateAt?schema.validateAt(field,values):validateYupSchema(values,schema);return new Promise(function(resolve,reject){promise.then(function(){resolve(emptyErrors);},function(err){// Yup will throw a validation error if validation fails. We catch those and
// resolve them into Formik errors. We can sniff if something is a Yup error
// by checking error.name.
// @see https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
if(err.name==='ValidationError'){resolve(yupToFormErrors(err));}else {// We throw any other errors
{console.warn("Warning: An unhandled error was caught during validation in <Formik validationSchema />",err);}reject(err);}});});},[props.validationSchema]);var runSingleFieldLevelValidation=react.useCallback(function(field,value){return new Promise(function(resolve){return resolve(fieldRegistry.current[field].validate(value));});},[]);var runFieldLevelValidations=react.useCallback(function(values){var fieldKeysWithValidation=Object.keys(fieldRegistry.current).filter(function(f){return isFunction$1(fieldRegistry.current[f].validate);});// Construct an array with all of the field validation functions
var fieldValidations=fieldKeysWithValidation.length>0?fieldKeysWithValidation.map(function(f){return runSingleFieldLevelValidation(f,getIn(values,f));}):[Promise.resolve('DO_NOT_DELETE_YOU_WILL_BE_FIRED')];// use special case ;)
return Promise.all(fieldValidations).then(function(fieldErrorsList){return fieldErrorsList.reduce(function(prev,curr,index){if(curr==='DO_NOT_DELETE_YOU_WILL_BE_FIRED'){return prev;}if(curr){prev=setIn(prev,fieldKeysWithValidation[index],curr);}return prev;},{});});},[runSingleFieldLevelValidation]);// Run all validations and return the result
var runAllValidations=react.useCallback(function(values){return Promise.all([runFieldLevelValidations(values),props.validationSchema?runValidationSchema(values):{},props.validate?runValidateHandler(values):{}]).then(function(_ref2){var fieldErrors=_ref2[0],schemaErrors=_ref2[1],validateErrors=_ref2[2];var combinedErrors=deepmerge_1.all([fieldErrors,schemaErrors,validateErrors],{arrayMerge:arrayMerge});return combinedErrors;});},[props.validate,props.validationSchema,runFieldLevelValidations,runValidateHandler,runValidationSchema]);// Run all validations methods and update state accordingly
var validateFormWithHighPriority=useEventCallback(function(values){if(values===void 0){values=state.values;}dispatch({type:'SET_ISVALIDATING',payload:true});return runAllValidations(values).then(function(combinedErrors){if(!!isMounted.current){dispatch({type:'SET_ISVALIDATING',payload:false});dispatch({type:'SET_ERRORS',payload:combinedErrors});}return combinedErrors;});});react.useEffect(function(){if(validateOnMount&&isMounted.current===true&&reactFastCompare$1(initialValues.current,props.initialValues)){validateFormWithHighPriority(initialValues.current);}},[validateOnMount,validateFormWithHighPriority]);var resetForm=react.useCallback(function(nextState){var values=nextState&&nextState.values?nextState.values:initialValues.current;var errors=nextState&&nextState.errors?nextState.errors:initialErrors.current?initialErrors.current:props.initialErrors||{};var touched=nextState&&nextState.touched?nextState.touched:initialTouched.current?initialTouched.current:props.initialTouched||{};var status=nextState&&nextState.status?nextState.status:initialStatus.current?initialStatus.current:props.initialStatus;initialValues.current=values;initialErrors.current=errors;initialTouched.current=touched;initialStatus.current=status;var dispatchFn=function dispatchFn(){dispatch({type:'RESET_FORM',payload:{isSubmitting:!!nextState&&!!nextState.isSubmitting,errors:errors,touched:touched,status:status,values:values,isValidating:!!nextState&&!!nextState.isValidating,submitCount:!!nextState&&!!nextState.submitCount&&typeof nextState.submitCount==='number'?nextState.submitCount:0}});};if(props.onReset){var maybePromisedOnReset=props.onReset(state.values,imperativeMethods);if(isPromise(maybePromisedOnReset)){maybePromisedOnReset.then(dispatchFn);}else {dispatchFn();}}else {dispatchFn();}},[props.initialErrors,props.initialStatus,props.initialTouched]);react.useEffect(function(){if(isMounted.current===true&&!reactFastCompare$1(initialValues.current,props.initialValues)){if(enableReinitialize){initialValues.current=props.initialValues;resetForm();}if(validateOnMount){validateFormWithHighPriority(initialValues.current);}}},[enableReinitialize,props.initialValues,resetForm,validateOnMount,validateFormWithHighPriority]);react.useEffect(function(){if(enableReinitialize&&isMounted.current===true&&!reactFastCompare$1(initialErrors.current,props.initialErrors)){initialErrors.current=props.initialErrors||emptyErrors;dispatch({type:'SET_ERRORS',payload:props.initialErrors||emptyErrors});}},[enableReinitialize,props.initialErrors]);react.useEffect(function(){if(enableReinitialize&&isMounted.current===true&&!reactFastCompare$1(initialTouched.current,props.initialTouched)){initialTouched.current=props.initialTouched||emptyTouched;dispatch({type:'SET_TOUCHED',payload:props.initialTouched||emptyTouched});}},[enableReinitialize,props.initialTouched]);react.useEffect(function(){if(enableReinitialize&&isMounted.current===true&&!reactFastCompare$1(initialStatus.current,props.initialStatus)){initialStatus.current=props.initialStatus;dispatch({type:'SET_STATUS',payload:props.initialStatus});}},[enableReinitialize,props.initialStatus,props.initialTouched]);var validateField=useEventCallback(function(name){// This will efficiently validate a single field by avoiding state
// changes if the validation function is synchronous. It's different from
// what is called when using validateForm.
if(fieldRegistry.current[name]&&isFunction$1(fieldRegistry.current[name].validate)){var value=getIn(state.values,name);var maybePromise=fieldRegistry.current[name].validate(value);if(isPromise(maybePromise)){// Only flip isValidating if the function is async.
dispatch({type:'SET_ISVALIDATING',payload:true});return maybePromise.then(function(x){return x;}).then(function(error){dispatch({type:'SET_FIELD_ERROR',payload:{field:name,value:error}});dispatch({type:'SET_ISVALIDATING',payload:false});});}else {dispatch({type:'SET_FIELD_ERROR',payload:{field:name,value:maybePromise}});return Promise.resolve(maybePromise);}}else if(props.validationSchema){dispatch({type:'SET_ISVALIDATING',payload:true});return runValidationSchema(state.values,name).then(function(x){return x;}).then(function(error){dispatch({type:'SET_FIELD_ERROR',payload:{field:name,value:error[name]}});dispatch({type:'SET_ISVALIDATING',payload:false});});}return Promise.resolve();});var registerField=react.useCallback(function(name,_ref3){var validate=_ref3.validate;fieldRegistry.current[name]={validate:validate};},[]);var unregisterField=react.useCallback(function(name){delete fieldRegistry.current[name];},[]);var setTouched=useEventCallback(function(touched,shouldValidate){dispatch({type:'SET_TOUCHED',payload:touched});var willValidate=shouldValidate===undefined?validateOnBlur:shouldValidate;return willValidate?validateFormWithHighPriority(state.values):Promise.resolve();});var setErrors=react.useCallback(function(errors){dispatch({type:'SET_ERRORS',payload:errors});},[]);var setValues=useEventCallback(function(values,shouldValidate){var resolvedValues=isFunction$1(values)?values(state.values):values;dispatch({type:'SET_VALUES',payload:resolvedValues});var willValidate=shouldValidate===undefined?validateOnChange:shouldValidate;return willValidate?validateFormWithHighPriority(resolvedValues):Promise.resolve();});var setFieldError=react.useCallback(function(field,value){dispatch({type:'SET_FIELD_ERROR',payload:{field:field,value:value}});},[]);var setFieldValue=useEventCallback(function(field,value,shouldValidate){dispatch({type:'SET_FIELD_VALUE',payload:{field:field,value:value}});var willValidate=shouldValidate===undefined?validateOnChange:shouldValidate;return willValidate?validateFormWithHighPriority(setIn(state.values,field,value)):Promise.resolve();});var executeChange=react.useCallback(function(eventOrTextValue,maybePath){// By default, assume that the first argument is a string. This allows us to use
// handleChange with React Native and React Native Web's onChangeText prop which
// provides just the value of the input.
var field=maybePath;var val=eventOrTextValue;var parsed;// If the first argument is not a string though, it has to be a synthetic React Event (or a fake one),
// so we handle like we would a normal HTML change event.
if(!isString$1(eventOrTextValue)){// If we can, persist the event
// @see https://reactjs.org/docs/events.html#event-pooling
if(eventOrTextValue.persist){eventOrTextValue.persist();}var target=eventOrTextValue.target?eventOrTextValue.target:eventOrTextValue.currentTarget;var type=target.type,name=target.name,id=target.id,value=target.value,checked=target.checked,outerHTML=target.outerHTML,options=target.options,multiple=target.multiple;field=maybePath?maybePath:name?name:id;if(!field&&undefined!=="production"){warnAboutMissingIdentifier({htmlContent:outerHTML,documentationAnchorLink:'handlechange-e-reactchangeeventany--void',handlerName:'handleChange'});}val=/number|range/.test(type)?(parsed=parseFloat(value),isNaN(parsed)?'':parsed):/checkbox/.test(type)// checkboxes
?getValueForCheckbox(getIn(state.values,field),checked,value):options&&multiple// <select multiple>
?getSelectedValues(options):value;}if(field){// Set form fields by name
setFieldValue(field,val);}},[setFieldValue,state.values]);var handleChange=useEventCallback(function(eventOrPath){if(isString$1(eventOrPath)){return function(event){return executeChange(event,eventOrPath);};}else {executeChange(eventOrPath);}});var setFieldTouched=useEventCallback(function(field,touched,shouldValidate){if(touched===void 0){touched=true;}dispatch({type:'SET_FIELD_TOUCHED',payload:{field:field,value:touched}});var willValidate=shouldValidate===undefined?validateOnBlur:shouldValidate;return willValidate?validateFormWithHighPriority(state.values):Promise.resolve();});var executeBlur=react.useCallback(function(e,path){if(e.persist){e.persist();}var _e$target=e.target,name=_e$target.name,id=_e$target.id,outerHTML=_e$target.outerHTML;var field=path?path:name?name:id;if(!field&&undefined!=="production"){warnAboutMissingIdentifier({htmlContent:outerHTML,documentationAnchorLink:'handleblur-e-any--void',handlerName:'handleBlur'});}setFieldTouched(field,true);},[setFieldTouched]);var handleBlur=useEventCallback(function(eventOrString){if(isString$1(eventOrString)){return function(event){return executeBlur(event,eventOrString);};}else {executeBlur(eventOrString);}});var setFormikState=react.useCallback(function(stateOrCb){if(isFunction$1(stateOrCb)){dispatch({type:'SET_FORMIK_STATE',payload:stateOrCb});}else {dispatch({type:'SET_FORMIK_STATE',payload:function payload(){return stateOrCb;}});}},[]);var setStatus=react.useCallback(function(status){dispatch({type:'SET_STATUS',payload:status});},[]);var setSubmitting=react.useCallback(function(isSubmitting){dispatch({type:'SET_ISSUBMITTING',payload:isSubmitting});},[]);var submitForm=useEventCallback(function(){dispatch({type:'SUBMIT_ATTEMPT'});return validateFormWithHighPriority().then(function(combinedErrors){// In case an error was thrown and passed to the resolved Promise,
// `combinedErrors` can be an instance of an Error. We need to check
// that and abort the submit.
// If we don't do that, calling `Object.keys(new Error())` yields an
// empty array, which causes the validation to pass and the form
// to be submitted.
var isInstanceOfError=combinedErrors instanceof Error;var isActuallyValid=!isInstanceOfError&&Object.keys(combinedErrors).length===0;if(isActuallyValid){// Proceed with submit...
//
// To respect sync submit fns, we can't simply wrap executeSubmit in a promise and
// _always_ dispatch SUBMIT_SUCCESS because isSubmitting would then always be false.
// This would be fine in simple cases, but make it impossible to disable submit
// buttons where people use callbacks or promises as side effects (which is basically
// all of v1 Formik code). Instead, recall that we are inside of a promise chain already,
// so we can try/catch executeSubmit(), if it returns undefined, then just bail.
// If there are errors, throw em. Otherwise, wrap executeSubmit in a promise and handle
// cleanup of isSubmitting on behalf of the consumer.
var promiseOrUndefined;try{promiseOrUndefined=executeSubmit();// Bail if it's sync, consumer is responsible for cleaning up
// via setSubmitting(false)
if(promiseOrUndefined===undefined){return;}}catch(error){throw error;}return Promise.resolve(promiseOrUndefined).then(function(result){if(!!isMounted.current){dispatch({type:'SUBMIT_SUCCESS'});}return result;})["catch"](function(_errors){if(!!isMounted.current){dispatch({type:'SUBMIT_FAILURE'});// This is a legit error rejected by the onSubmit fn
// so we don't want to break the promise chain
throw _errors;}});}else if(!!isMounted.current){// ^^^ Make sure Formik is still mounted before updating state
dispatch({type:'SUBMIT_FAILURE'});// throw combinedErrors;
if(isInstanceOfError){throw combinedErrors;}}return;});});var handleSubmit=useEventCallback(function(e){if(e&&e.preventDefault&&isFunction$1(e.preventDefault)){e.preventDefault();}if(e&&e.stopPropagation&&isFunction$1(e.stopPropagation)){e.stopPropagation();}// Warn if form submission is triggered by a <button> without a
// specified `type` attribute during development. This mitigates
// a common gotcha in forms with both reset and submit buttons,
// where the dev forgets to add type="button" to the reset button.
if(typeof document!=='undefined'){// Safely get the active element (works with IE)
var activeElement=getActiveElement();if(activeElement!==null&&activeElement instanceof HTMLButtonElement){!(activeElement.attributes&&activeElement.attributes.getNamedItem('type'))?warning(false,'You submitted a Formik form using a button with an unspecified `type` attribute. Most browsers default button elements to `type="submit"`. If this is not a submit button, please add `type="button"`.'):void 0;}}submitForm()["catch"](function(reason){console.warn("Warning: An unhandled error was caught from submitForm()",reason);});});var imperativeMethods={resetForm:resetForm,validateForm:validateFormWithHighPriority,validateField:validateField,setErrors:setErrors,setFieldError:setFieldError,setFieldTouched:setFieldTouched,setFieldValue:setFieldValue,setStatus:setStatus,setSubmitting:setSubmitting,setTouched:setTouched,setValues:setValues,setFormikState:setFormikState,submitForm:submitForm};var executeSubmit=useEventCallback(function(){return onSubmit(state.values,imperativeMethods);});var handleReset=useEventCallback(function(e){if(e&&e.preventDefault&&isFunction$1(e.preventDefault)){e.preventDefault();}if(e&&e.stopPropagation&&isFunction$1(e.stopPropagation)){e.stopPropagation();}resetForm();});var getFieldMeta=react.useCallback(function(name){return {value:getIn(state.values,name),error:getIn(state.errors,name),touched:!!getIn(state.touched,name),initialValue:getIn(initialValues.current,name),initialTouched:!!getIn(initialTouched.current,name),initialError:getIn(initialErrors.current,name)};},[state.errors,state.touched,state.values]);var getFieldHelpers=react.useCallback(function(name){return {setValue:function setValue(value,shouldValidate){return setFieldValue(name,value,shouldValidate);},setTouched:function setTouched(value,shouldValidate){return setFieldTouched(name,value,shouldValidate);},setError:function setError(value){return setFieldError(name,value);}};},[setFieldValue,setFieldTouched,setFieldError]);var getFieldProps=react.useCallback(function(nameOrOptions){var isAnObject=isObject$2(nameOrOptions);var name=isAnObject?nameOrOptions.name:nameOrOptions;var valueState=getIn(state.values,name);var field={name:name,value:valueState,onChange:handleChange,onBlur:handleBlur};if(isAnObject){var type=nameOrOptions.type,valueProp=nameOrOptions.value,is=nameOrOptions.as,multiple=nameOrOptions.multiple;if(type==='checkbox'){if(valueProp===undefined){field.checked=!!valueState;}else {field.checked=!!(Array.isArray(valueState)&&~valueState.indexOf(valueProp));field.value=valueProp;}}else if(type==='radio'){field.checked=valueState===valueProp;field.value=valueProp;}else if(is==='select'&&multiple){field.value=field.value||[];field.multiple=true;}}return field;},[handleBlur,handleChange,state.values]);var dirty=react.useMemo(function(){return !reactFastCompare$1(initialValues.current,state.values);},[initialValues.current,state.values]);var isValid=react.useMemo(function(){return typeof isInitialValid!=='undefined'?dirty?state.errors&&Object.keys(state.errors).length===0:isInitialValid!==false&&isFunction$1(isInitialValid)?isInitialValid(props):isInitialValid:state.errors&&Object.keys(state.errors).length===0;},[isInitialValid,dirty,state.errors,props]);var ctx=_extends({},state,{initialValues:initialValues.current,initialErrors:initialErrors.current,initialTouched:initialTouched.current,initialStatus:initialStatus.current,handleBlur:handleBlur,handleChange:handleChange,handleReset:handleReset,handleSubmit:handleSubmit,resetForm:resetForm,setErrors:setErrors,setFormikState:setFormikState,setFieldTouched:setFieldTouched,setFieldValue:setFieldValue,setFieldError:setFieldError,setStatus:setStatus,setSubmitting:setSubmitting,setTouched:setTouched,setValues:setValues,submitForm:submitForm,validateForm:validateFormWithHighPriority,validateField:validateField,isValid:isValid,dirty:dirty,unregisterField:unregisterField,registerField:registerField,getFieldProps:getFieldProps,getFieldMeta:getFieldMeta,getFieldHelpers:getFieldHelpers,validateOnBlur:validateOnBlur,validateOnChange:validateOnChange,validateOnMount:validateOnMount});return ct
react.useImperativeHandle(innerRef,function(){return formikbag;});{// eslint-disable-next-line react-hooks/rules-of-hooks
react.useEffect(function(){!!props.render?warning(false,"<Formik render> has been deprecated and will be removed in future versions of Formik. Please use a child callback function instead. To get rid of this warning, replace <Formik render={(props) => ...} /> with <Formik>{(props) => ...}</Formik>"):void 0;// eslint-disable-next-line
},[]);}return/*#__PURE__*/react.createElement(FormikProvider,{value:formikbag},component?/*#__PURE__*/react.createElement(component,formikbag):render?render(formikbag):children// children come last, always called
?isFunction$1(children)?children(formikbag):!isEmptyChildren(children)?react.Children.only(children):null:null);}function warnAboutMissingIdentifier(_ref4){var htmlContent=_ref4.htmlContent,documentationAnchorLink=_ref4.documentationAnchorLink,handlerName=_ref4.handlerName;console.warn("Warning: Formik called `"+handlerName+"`, but you forgot to pass an `id` or `name` attribute to your input:\n "+htmlContent+"\n Formik cannot determine which value to update. For more info see https://formik.org/docs/api/formik#"+documentationAnchorLink+"\n ");}/**
* Transform Yup ValidationError to a more usable object
*/function yupToFormErrors(yupError){var errors={};if(yupError.inner){if(yupError.inner.length===0){return setIn(errors,yupError.path,yupError.message);}for(var _iterator=yupError.inner,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;){var _ref5;if(_isArray){if(_i>=_iterator.length)break;_ref5=_iterator[_i++];}else {_i=_iterator.next();if(_i.done)break;_ref5=_i.value;}var err=_ref5;if(!getIn(errors,err.path)){errors=setIn(errors,err.path,err.message);}}}return errors;}/**
* Validate a yup schema.
*/function validateYupSchema(values,schema,sync,context){if(sync===void 0){sync=false;}if(context===void 0){context={};}var validateData=prepareDataForValidation(values);return schema[sync?'validateSync':'validate'](validateData,{abortEarly:false,context:context});}/**
* Recursively prepare values.
*/function prepareDataForValidation(values){var data=Array.isArray(values)?[]:{};for(var k in values){if(Object.prototype.hasOwnProperty.call(values,k)){var key=String(k);if(Array.isArray(values[key])===true){data[key]=values[key].map(function(value){if(Array.isArray(value)===true||isPlainObject(value)){return prepareDataForValidation(value);}else {return value!==''?value:undefined;}});}else if(isPlainObject(values[key])){data[key]=prepareDataForValidation(values[key]);}else {data[key]=values[key]!==''?values[key]:undefined;}}}return data;}/**
* deepmerge array merging algorithm
* https://github.com/KyleAMathews/deepmerge#combine-array
*/function arrayMerge(target,source,options){var destination=target.slice();source.forEach(function merge(e,i){if(typeof destination[i]==='undefined'){var cloneRequested=options.clone!==false;var shouldClone=cloneRequested&&options.isMergeableObject(e);destination[i]=shouldClone?deepmerge_1(Array.isArray(e)?[]:{},e,options):e;}else if(options.isMergeableObject(e)){destination[i]=deepmerge_1(target[i],e,options);}else if(target.indexOf(e)===-1){destination.push(e);}});return destination;}/** Return multi select values based on an array of options */function getSelectedValues(options){return Array.from(options).filter(function(el){return el.selected;}).map(function(el){return el.value;});}/** Return the next value for a checkbox */function getValueForCheckbox(currentValue,checked,valueProp){// If the current value was a boolean, return a boolean
if(typeof currentValue==='boolean'){return Boolean(checked);}// If the currentValue was not a boolean we want to return an array
var currentArrayOfValues=[];var isValueInArray=false;var index=-1;if(!Array.isArray(currentValue)){// eslint-disable-next-line eqeqeq
if(!valueProp||valueProp=='true'||valueProp=='false'){return Boolean(checked);}}else {// If the current value is already an array, use it
currentArrayOfValues=currentValue;index=currentValue.indexOf(valueProp);isValueInArray=index>=0;}// If the checkbox was checked and the value is not already present in the aray we want to add the new value to the array of values
if(checked&&valueProp&&!isValueInArray){return currentArrayOfValues.concat(valueProp);}// If the checkbox was unchecked and the value is not in the array, simply return the already existing array of values
if(!isValueInArray){return currentArrayOfValues;}// If the checkbox was unchecked and the value is in the array, remove the value and return the array
return currentArrayOfValues.slice(0,index).concat(currentArrayOfValues.slice(index+1));}// React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser.
// @see https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
var useIsomorphicLayoutEffect$1=typeof window!=='undefined'&&typeof window.document!=='undefined'&&typeof window.document.createElement!=='undefined'?react.useLayoutEffect:react.useEffect;function useEventCallback(fn){var ref=react.useRef(fn);// we copy a ref to the callback scoped to the current state/props on each render
useIsomorphicLayoutEffect$1(function(){ref.current=fn;});return react.useCallback(function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}return ref.current.apply(void 0,args);},[]);}function Field(_ref){var validate=_ref.validate,name=_ref.name,render=_ref.render,children=_ref.children,is=_ref.as,component=_ref.component,props=_objectWithoutPropertiesLoose(_ref,["validate","name","render","children","as","component"]);var _useFormikContext=useFormikContext(),formik=_objectWithoutPropertiesLoose(_useFormikContext,["validate","validationSchema"]);{// eslint-disable-next-line react-hooks/rules-of-hooks
react.useEffect(function(){!!render?warning(false,"<Field render> has been deprecated and will be removed in future versions of Formik. Please use a child callback function instead. To get rid of this warning, replace <Field name=\""+name+"\" render={({field, form}) => ...} /> with <Field name=\""+name+"\">{({field, form, meta}) => ...}</Field>"):void 0;!!(is&&children&&isFunction$1(children))?warning(false,'You should not use <Field as> and <Field children> as a function in the same <Field> component; <Field as> will be ignored.'):void 0;!!(component&&children&&isFunction$1(children))?warning(false,'You should not use <Field component> and <Field children> as a function in the same <Field> component; <Field component> will be ignored.'):void 0;!!(render&&children&&!isEmptyChildren(children))?warning(false,'You should not use <Field render> and <Field children> in the same <Field> component; <Field children> will be ignored'):void 0;// eslint-disable-next-line
},[]);}// Register field and field-level validation with parent <Formik>
var registerField=formik.registerField,unregisterField=formik.unregisterField;react.useEffect(function(){registerField(name,{validate:validate});return function(){unregisterField(name);};},[registerField,unregisterField,name,validate]);var field=formik.getFieldProps(_extends({name:name},props));var meta=formik.getFieldMeta(name);var legacyBag={field:field,form:formik};if(render){return render(_extends({},legacyBag,{meta:meta}));}if(isFunction$1(children)){return children(_extends({},legacyBag,{meta:meta}));}if(component){// This behavior is backwards compat with earlier Formik 0.9 to 1.x
if(typeof component==='string'){var innerRef=props.innerRef,rest=_objectWithoutPropertiesLoose(props,["innerRef"]);return/*#__PURE__*/react.createElement(component,_extends({ref:innerRef},field,rest),children);}// We don't pass `meta` for backwards compat
return/*#__PURE__*/react.createElement(component,_extends({field:field,form:formik},props),children);}// default to input here so we can check for both `as` and `children` above
var asElement=is||'input';if(typeof asElement==='string'){var _innerRef=props.innerRef,_rest=_objectWithoutPropertiesLoose(props,["innerRef"]);return/*#__PURE__*/react.createElement(asElement,_extends({ref:_innerRef},field,_rest),children);}return/*#__PURE__*/react.createElement(asElement,_extends({},field,props),children);}var Form=/*#__PURE__*/react.forwardRef(function(props,ref){// iOS needs an "action" attribute for nice input: https://stackoverflow.com/a/39485162/406725
// We default the action to "#" in case the preventDefault fails (just updates the URL hash)
var action=props.action,rest=_objectWithoutPropertiesLoose(props,["action"]);var _action=action!=null?action:'#';var _useFormikContext=useFormikContext(),handleReset=_useFormikContext.handleReset,handleSubmit=_useFormikContext.handleSubmit;return/*#__PURE__*/react.createElement("form",Object.assign({onSubmit:handleSubmit,ref:ref,onReset:handleReset,action:_action},rest));});Form.displayName='Form';/**
* Connect any component to Formik context, and inject as a prop called `formik`;
* @param Comp React Component
*/function connect(Comp){var C=function C(props){return/*#__PURE__*/react.createElement(FormikConsumer,null,function(formik){!!!formik?warning(false,"Formik context is undefined, please verify you are rendering <Form>, <Field>, <FastField>, <FieldArray>, or your custom context-using component as a child of a <Formik> component. Component name: "+Comp.name):void 0;return/*#__PURE__*/react.createElement(Comp,Object.assign({},props,{formik:formik}));});};var componentDisplayName=Comp.displayName||Comp.name||Comp.constructor&&Comp.constructor.name||'Component';// Assign Comp to C.WrappedComponent so we can access the inner component in tests
// For example, <Field.WrappedComponent /> gets us <FieldInner/>
C.WrappedComponent=Comp;C.displayName="FormikConnect("+componentDisplayName+")";return hoistNonReactStatics_cjs(C,Comp// cast type to ComponentClass (even if SFC)
);}/**
* Some array helpers!
*/var move=function move(array,from,to){var copy=copyArrayLike(array);var value=copy[from];copy.splice(from,1);copy.splice(to,0,value);return copy;};var swap=function swap(arrayLike,indexA,indexB){var copy=copyArrayLike(arrayLike);var a=copy[indexA];copy[indexA]=copy[indexB];copy[indexB]=a;return copy;};var insert=function insert(arrayLike,index,value){var copy=copyArrayLike(arrayLike);copy.splice(index,0,value);return copy;};var replace=function replace(arrayLike,index,value){var copy=copyArrayLike(arrayLike);copy[index]=value;return copy;};var copyArrayLike=function copyArrayLike(arrayLike){if(!arrayLike){return [];}else if(Array.isArray(arrayLike)){return [].concat(arrayLike);}else {var maxIndex=Object.keys(arrayLike).map(function(key){return parseInt(key);}).reduce(function(max,el){return el>max?el:max;},0);return Array.from(_extends({},arrayLike,{length:maxIndex+1}));}};var FieldArrayInner=/*#__PURE__*/function(_React$Component){_inheritsLoose(FieldArrayInner,_React$Component);function FieldArrayInner(props){var _this;_this=_React$Component.call(this,props)||this;_this.updateArrayField=function(fn,alterTouched,alterErrors){var _this$props=_this.props,name=_this$props.name,setFormikState=_this$props.formik.setFormikState;setFormikState(function(prevState){var updateErrors=typeof alterErrors==='function'?alterErrors:fn;var updateTouched=typeof alterTouched==='function'?alterTouched:fn;// values fn should be executed before updateErrors and updateTouched,
// otherwise it causes an error with unshift.
var values=setIn(prevState.values,name,fn(getIn(prevState.values,name)));var fieldError=alterErrors?updateErrors(getIn(prevState.errors,name)):undefined;var fieldTouched=alterTouched?updateTouched(getIn(prevState.touched,name)):undefined;if(isEmptyArray(fieldError)){fieldError=undefined;}if(isEmptyArray(fieldTouched)){fieldTouched=undefined;}return _extends({},prevState,{values:values,errors:alterErrors?setIn(prevState.errors,name,fieldError):prevState.errors,touched:alterTouched?setIn(prevState.touched,name,fieldTouched):prevState.touched});});};_this.push=function(value){return _this.updateArrayField(function(arrayLike){return [].concat(copyArrayLike(arrayLike),[cloneDeep(value)]);},false,false);};_this.handlePush=function(value){return function(){return _this.push(value);};};_this.swap=function(indexA,indexB){return _this.updateArrayField(function(array){return swap(array,indexA,indexB);},true,true);};_this.handleSwap=function(indexA,indexB){return function(){return _this.swap(indexA,indexB);};};_this.move=function(from,to){return _this.updateArrayField(function(array){return move(array,from,to);},true,true);};_this.handleMove=function(from,to){return function(){return _this.move(from,to);};};_this.insert=function(index,value){return _this.updateArrayField(function(array){return insert(array,index,value);},function(array){return insert(array,index,null);},function(array){return insert(array,index,null);});};_this.handleInsert=function(index,value){return function(){return _this.insert(index,value);};};_this.replace=function(index,value){return _this.updateArrayField(function(array){return replace(array,index,value);},false,false);};_this.handleReplace=function(index,value){return function(){return _this.replace(index,value);};};_this.unshift=function(value){var length=-1;_this.updateArrayField(function(array){var arr=array?[value].concat(array):[value];if(length<0){length=arr.length;}return arr;},function(array){var arr=array?[null].concat(array):[null];if(length<0){length=arr.length;}return arr;},function(array){var arr=array?[null].concat(array):[null];if(length<0){length=arr.length;}return arr;});return length;};_this.handleUnshift=function(value){return function(){return _this.unshift(value);};};_this.handleRemove=function(index){return function(){return _this.remove(index);};};_this.handlePop=function(){return function(){return _this.pop();};};// We need TypeScript generics on these, so we'll bind them in the constructor
// @todo Fix TS 3.2.1
_this.remove=_this.remove.bind(_assertThisInitialized(_this));_this.pop=_this.pop.bind(_assertThisInitialized(_this));return _this;}var _proto=FieldArrayInner.prototype;_proto.componentDidUpdate=function componentDidUpdate(prevProps){if(this.props.validateOnChange&&this.props.formik.validateOnChange&&!reactFastCompare$1(getIn(prevProps.formik.values,prevProps.name),getIn(this.props.formik.values,this.props.name))){this.props.formik.validateForm(this.props.formik.values);}};_proto.remove=function remove(index){// We need to make sure we also remove relevant pieces of `touched` and `errors`
var result;this.updateArrayField(// so this gets call 3 times
function(array){var copy=array?copyArrayLike(array):[];if(!result){result=copy[index];}if(isFunction$1(copy.splice)){copy.splice(index,1);}return copy;},true,true);return result;};_proto.pop=function pop(){// Remove relevant pieces of `touched` and `errors` too!
var result;this.updateArrayField(// so this gets call 3 times
function(array){var tmp=array;if(!result){result=tmp&&tmp.pop&&tmp.pop();}return tmp;},true,true);return result;};_proto.render=function render(){var arrayHelpers={push:this.push,pop:this.pop,swap:this.swap,move:this.move,insert:this.insert,replace:this.replace,unshift:this.unshift,remove:this.remove,handlePush:this.handlePush,handlePop:this.handlePop,handleSwap:this.handleSwap,handleMove:this.handleMove,handleInsert:this.handleInsert,handleReplace:this.handleReplace,handleUnshift:this.handleUnshift,handleRemove:this.handleRemove};var _this$props2=this.props,component=_this$props2.component,render=_this$props2.render,children=_this$props2.children,name=_this$props2.name,_this$props2$formik=_this$props2.formik,restOfFormik=_objectWithoutPropertiesLoose(_this$props2$formik,["validate","validationSchema"]);var props=_extends({},arrayHelpers,{form:restOfFormik,name:name});return component?/*#__PURE__*/react.createElement(component,props):render?render(props):children// children come last, always called
?typeof children==='function'?children(props):!isEmptyChildren(children)?react.Children.only(children):null:null;};return FieldArrayInner;}(react.Component);FieldArrayInner.defaultProps={validateOnChange:true};var FieldArray=/*#__PURE__*/connect(FieldArrayInner);var ErrorMessageImpl=/*#__PURE__*/function(_React$Component){_inheritsLoose(ErrorMessageImpl,_React$Component);function ErrorMessageImpl(){return _React$Component.apply(this,arguments)||this;}var _proto=ErrorMessageImpl.prototype;_proto.shouldComponentUpdate=function shouldComponentUpdate(props){if(getIn(this.props.formik.errors,this.props.name)!==getIn(props.formik.errors,this.props.name)||getIn(this.props.formik.touched,this.props.name)!==getIn(props.formik.touched,this.props.name)||Object.keys(this.props).length!==Object.keys(props).length){return true;}else {return false;}};_proto.render=function render(){var _this$props=this.props,component=_this$props.component,formik=_this$props.formik,render=_this$props.render,children=_this$props.children,name=_this$props.name,rest=_objectWithoutPropertiesLoose(_this$props,["component","formik","render","children","name"]);var touch=getIn(formik.touched,name);var error=getIn(formik.errors,name);return !!touch&&!!error?render?isFunction$1(render)?render(error):null:children?isFunction$1(children)?children(error):null:component?/*#__PURE__*/react.createElement(component,rest,error):error:null;};return ErrorMessageImpl;}(react.Component);var ErrorMessage=/*#__PURE__*/connect(ErrorMessageImpl);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
var ok=function(value){return new Ok(value);};// eslint-disable-next-line @typescript-eslint/no-use-before-define
var err=function(err){return new Err(err);};var Ok=/** @class */function(){function Ok(value){var _this=this;this.value=value;// eslint-disable-next-line @typescript-eslint/no-unused-vars
this.match=function(ok,_err){return ok(_this.value);};}Ok.prototype.isOk=function(){return true;};Ok.prototype.isErr=function(){return !this.isOk();};Ok.prototype.map=function(f){return ok(f(this.value));};// eslint-disable-next-line @typescript-eslint/no-unused-vars
Ok.prototype.mapErr=function(_f){return ok(this.value);};// add info on how this is really useful for converting a
// Result<Result<T, E2>, E1>
// into a Result<T, E2>
Ok.prototype.andThen=function(f){return f(this.value);};// need to figure how to overload to prevent nesting of values
// https://github.com/supermacro/neverthrow/issues/183#issuecomment-730554613
Ok.prototype.andThenCollect=function(f){var _this=this;return f(this.value).map(function(newVal){return [newVal,_this.value];});};Ok.prototype.asyncAndThen=function(f){return f(this.value);};Ok.prototype.asyncMap=function(f){return ResultAsync.fromPromise(f(this.value));};// eslint-disable-next-line @typescript-eslint/no-unused-vars
Ok.prototype.unwrapOr=function(_v){return this.value;};Ok.prototype._unsafeUnwrap=function(){return this.value;};Ok.prototype._unsafeUnwrapErr=function(){throw new Error('Called `_unsafeUnwrapErr` on an Ok');};return Ok;}();var Err=/** @class */function(){function Err(error){var _this=this;this.error=error;this.match=function(_ok,err){return err(_this.error);};}Err.prototype.isOk=function(){return false;};Err.prototype.isErr=function(){return !this.isOk();};// eslint-disable-next-line @typescript-eslint/no-unused-vars
Err.prototype.map=function(_f){return err(this.error);};Err.prototype.mapErr=function(f){return err(f(this.error));};// eslint-disable-next-line @typescript-eslint/no-unused-vars
Err.prototype.andThen=function(_f){return err(this.error);};// eslint-disable-next-line @typescript-eslint/no-unused-vars
Err.prototype.asyncAndThen=function(_f){return errAsync(this.error);};// eslint-disable-next-line @typescript-eslint/no-unused-vars
Err.prototype.asyncMap=function(_f){return errAsync(this.error);};Err.prototype.unwrapOr=function(v){return v;};Err.prototype._unsafeUnwrap=function(){throw new Error('Called `_unsafeUnwrap` on an Err');};Err.prototype._unsafeUnwrapErr=function(){return this.error;};return Err;}();/*! *****************************************************************************
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.
***************************************************************************** */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());});}function __generator(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1];},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),"throw":verb(1),"return":verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this;}),g;function verb(n){return function(v){return step([n,v]);};}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return {value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue;}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break;}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break;}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break;}if(t[2])_.ops.pop();_.trys.pop();continue;}op=body.call(thisArg,_);}catch(e){op=[6,e];y=0;}finally{f=t=0;}if(op[0]&5)throw op[1];return {value:op[0]?op[1]:void 0,done:true};}}var logWarning=function(warningMessage){if(typeof process!=='object'||undefined!=='production'){var yellowColor='\x1b[33m%s\x1b[0m';var warning=['[neverthrow]',warningMessage].join(' - ');console.warn(yellowColor,warning);}};var ResultAsync=/** @class */function(){function ResultAsync(res){this._promise=res;}ResultAsync.fromPromise=function(promise,errorFn){var newPromise=promise.then(function(value){return new Ok(value);});if(errorFn){newPromise=newPromise["catch"](function(e){return new Err(errorFn(e));});}else {var warning=['`fromPromise` called without a promise rejection handler','Ensure that you are catching promise rejections yourself, or pass a second argument to `fromPromise` to convert a caught exception into an `Err` instance'].join(' - ');logWarning(warning);}return new ResultAsync(newPromise);};ResultAsync.prototype.map=function(f){var _this=this;return new ResultAsync(this._promise.then(function(res){return __awaiter(_this,void 0,void 0,function(){var _a;return __generator(this,function(_b){switch(_b.label){case 0:if(res.isErr()){return [2/*return*/,new Err(res.error)];}_a=Ok.bind;return [4/*yield*/,f(res.value)];case 1:return [2/*return*/,new(_a.apply(Ok,[void 0,_b.sent()]))()];}});});}));};ResultAsync.prototype.mapErr=function(f){var _this=this;return new ResultAsync(this._promise.then(function(res){return __awaiter(_this,void 0,void 0,function(){var _a;return __generator(this,function(_b){switch(_b.label){case 0:if(res.isOk()){return [2/*return*/,new Ok(res.value)];}_a=Err.bind;return [4/*yield*/,f(res.error)];case 1:return [2/*return*/,new(_a.apply(Err,[void 0,_b.sent()]))()];}});});}));};ResultAsync.prototype.andThen=function(f){return new ResultAsync(this._promise.then(function(res){if(res.isErr()){return new Err(res.error);}var newValue=f(res.value);return newValue instanceof ResultAsync?newValue._promise:newValue;}));};ResultAsync.prototype.match=function(ok,_err){return this._promise.then(function(res){return res.match(ok,_err);});};ResultAsync.prototype.unwrapOr=function(t){return this._promise.then(function(res){return res.unwrapOr(t);});};// Makes ResultAsync implement PromiseLike<Result>
ResultAsync.prototype.then=function(successCallback,failureCallback){return this._promise.then(successCallback,failureCallback);};return ResultAsync;}();var errAsync=function(err){return new ResultAsync(Promise.resolve(new Err(err)));};
const ButtonGroupStyle = He.div `
display: flex;
.button {
background: var(--background-secondary-alt);
color: var(--text-normal);
cursor: pointer;
text-align: center;
margin-left: 0;
margin-right: 0;
flex-grow: 1;
flex-basis: 1;
}
.button:first-child {
border-radius: 4px 0 0 4px;
}
.button:last-child {
border-radius: 0 4px 4px 0;
}
.button:only-child {
border-radius: 4px;
}
.selected {
background: var(--interactive-accent) !important;
color: var(--text-on-accent);
}
`;
const ButtonGroup = (props) => (react.createElement(ButtonGroupStyle, null, props.options.map((option) => (react.createElement("div", { key: option[0], className: (props.field.value === option[0] ? 'selected ' : '') + 'button', onClick: () => {
props.form.setFieldValue(props.field.name, option[0]);
} }, option[1])))));
/**
* calcPlaceholderExpenseLineAmount determines the amount that must be assigned
* to each expense line that does not yet have a value in order for the sum of
* the expense lines to balance.
*/
const calcPlaceholderExpenseLineAmount = (values) => {
const linesExceptLast = values.lines.slice(0, -1);
const numEmptyLines = linesExceptLast.filter((line) => line.amount === '').length;
const unassignedTotal = linesExceptLast.reduce((amount, line) => line.amount === '' ? amount : amount - parseFloat(line.amount), parseFloat(values.total));
if (numEmptyLines === 0 && unassignedTotal !== 0) {
return err('All expense lines assigned, however amounts do not balance to 0');
}
return ok((unassignedTotal / numEmptyLines).toFixed(2));
};
const ExpenseLineStyle = He.div `
.arrow {
width: 0;
height: 0;
position: relative;
top: 4px;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-left: 10px solid var(--text-muted);
margin-right: 8px;
flex-shrink: 1;
cursor: pointer;
}
.arrow.rotateDown {
transform: rotate(90deg);
}
.arrowPlaceholder {
padding-left: 23px;
flex-shrink: 1;
}
.removeLine {
flex-shrink: 1;
margin: 7px 7px 4px 1px;
fill: var(--text-muted);
cursor: pointer;
}
.currencyInput {
flex-basis: 200px;
flex-shrink: 1;
}
.drawer {
display: none;
}
.drawer.expanded {
display: flex;
}
`;
const ExpenseLine = ({ i, formik, ...props }) => {
const lines = formik.values.lines;
const getAccountName = () => {
const lastI = lines.length - 1;
switch (formik.values.txType) {
case 'expense':
return i !== lastI ? 'Expense' : 'Asset';
case 'income':
return i !== lastI ? 'Asset' : 'Expense';
case 'transfer':
return i !== lastI ? 'To' : 'From';
3 years ago
}
return '';
};
const assetsAndLiabilities = lodash.union(props.txCache.assetAccounts, props.txCache.liabilityAccounts);
const getSuggestions = () => {
const lastI = lines.length - 1;
switch (formik.values.txType) {
case 'expense':
return i !== lastI
? props.txCache.expenseAccounts
: assetsAndLiabilities;
case 'income':
return i !== lastI
? assetsAndLiabilities
: props.txCache.expenseAccounts;
case 'transfer':
return assetsAndLiabilities;
3 years ago
}
return props.txCache.accounts;
3 years ago
};
const [expanded, setExpanded] = react.useState(false);
return (react.createElement(ExpenseLineStyle, null,
react.createElement(Margin, { className: "flexRow" },
react.createElement("div", { className: 'arrow' + (expanded ? ' rotateDown' : ''), onClick: () => setExpanded(!expanded) }),
react.createElement(Field, { className: "flexGrow", component: TextSuggest, name: `lines.${i}.account`, placeholder: getAccountName() + ' Account', suggestions: getSuggestions() }),
i + 1 !== lines.length ? (react.createElement(Field, { className: "currencyInput", component: CurrencyInputFormik, placeholder: calcPlaceholderExpenseLineAmount(formik.values).unwrapOr('Error'), currencySymbol: props.currencySymbol, name: `lines.${i}.amount` })) : (react.createElement(Field, { className: "currencyInput", component: CurrencyInputFormik, currencySymbol: props.currencySymbol, name: `lines.${i}.amount`, disabled: i + 1 === lines.length }))),
react.createElement("div", { className: 'drawer' + (expanded ? ' expanded' : '') },
i !== 0 && i !== lines.length - 1 ? (react.createElement("svg", { className: "removeLine", onClick: () => props.remove(i), width: "16", height: "16", version: "1.1", viewBox: "0 0 28 28", xmlns: "http://www.w3.org/2000/svg" },
react.createElement("path", { d: "m6.6465 5.2324-1.4141 1.4141 7.3535 7.3535-7.3535 7.3535 1.4141 1.4141 7.3535-7.3535 7.3535 7.3535 1.4141-1.4141-7.3535-7.3535 7.3535-7.3535-1.4141-1.4141-7.3535 7.3535-7.3535-7.3535z" }))) : (react.createElement("div", { className: "arrowPlaceholder" })),
react.createElement(Field, { className: "flexGrow", type: "text", name: `lines.${i}.comment`, placeholder: "Memo" }))));
};
const Margin = He.div `
margin: 5px;
`;
const Warning = He.div `
background: var(--background-modifier-error);
width: 458px;
padding: 10px 15px;
`;
const FormStyles = He.div `
.flexRow {
display: flex;
}
.flexGrow {
flex-grow: 1;
/* Not sure why this needs to be a percentage */
flex-basis: 40%;
}
.flexShrink {
flex-shrink 1;
}
input {
width: 100%;
}
`;
const lineToEnhancedExpenseLine = (line) => ({
account: line.account,
dealiasedAccount: line.account,
amount: parseFloat(line.amount),
reconcile: line.reconcile,
comment: line.comment || undefined,
currency: line.currency,
});
const EditTransaction = (props) => {
const isNew = props.operation === 'new';
const [page, setPage] = react.useState(1);
const initialValues = {
payee: isNew ? '' : props.initialState.value.payee,
txType: isNew ? 'expense' : 'unknown',
date: isNew
? window.moment().format('YYYY-MM-DD')
: window.moment(props.initialState.value.date).format('YYYY-MM-DD'),
total: isNew ? '' : getTotalAsNum(props.initialState).toString(),
lines: isNew
? [
{
id: 0,
account: '',
amount: '',
comment: '',
reconcile: '',
},
{
id: 1,
account: '',
amount: '',
comment: '',
reconcile: '',
},
]
: props.initialState.value.expenselines
.filter((line) => 'account' in line)
.map((line, i) => ({
id: i,
account: line.account,
amount: line.amount.toFixed(2),
comment: line.comment || '',
reconcile: line.reconcile,
currency: line.currency,
})),
};
return (react.createElement(FormStyles, null,
react.createElement("h2", null, "Add to Ledger"),
props.displayFileWarning ? (react.createElement(Warning, null, "Please rename your ledger file to end with the .ledger extension. Once renamed, please update the configuration option in the Ledger plugin settings.")) : null,
react.createElement(Formik, { initialValues: initialValues, validateOnChange: false, validate: (values) => {
const errors = {};
if (values.date === '') {
errors.date = 'Required';
}
if (values.total === '') {
errors.total = 'Required';
}
else if (Number.isNaN(parseFloat(values.total))) {
errors.total = 'Total must be a number';
}
if (values.txType !== 'transfer' && values.payee === '') {
errors.payee = 'Required';
}
if (values.lines.some((line) => line.account === '')) {
errors.lines = 'All expense lines must specify an account';
}
if (values.lines.filter((line) => line.amount === '').length === 0) {
// Validate that the amounts all add to zero
const sum = values.lines.reduce((acc, line) => parseFloat(line.amount) + acc, 0);
if (sum !== 0) {
errors.lines = `Amounts add up to $${sum.toFixed(2)} but must add up to $0`;
}
}
return errors;
}, onSubmit: (values) => {
if (values.lines.filter((line) => line.amount === '').length > 0) {
// Fill missing values in the expense lines
calcPlaceholderExpenseLineAmount(values).map((amount) => {
values.lines.forEach((line) => {
if (line.amount === '') {
line.amount = amount;
}
});
});
}
let localPayee = values.payee;
if (values.txType === 'transfer') {
const accountNames = values.lines.map((line) => line.account.split(':').last());
const to = accountNames.slice(0, -1).join(' and ');
const from = accountNames.last();
localPayee = `${from} to ${to}`;
}
// This tx is not fully valid because we are not specifying a valid block.
// It's only complete enough that we can format it into a string.
const newTx = {
blockLine: -1,
block: {
firstLine: -1,
lastLine: -1,
block: '',
},
type: 'tx',
value: {
payee: localPayee,
// TODO: This is not a ISO8601. Once reconciliation is added, remove this and reformat file.
date: values.date.replace(/-/g, '/'),
expenselines: values.lines.map((line) => lineToEnhancedExpenseLine(line)),
check: props.initialState.value.check,
comment: props.initialState.value.comment,
},
};
const txStr = formatTransaction(newTx, props.currencySymbol);
switch (props.operation) {
case 'new':
case 'clone':
props.updater.appendLedger(txStr).then(props.close);
break;
case 'modify':
props.updater
.updateTransaction(props.initialState, txStr)
.then(props.close);
break;
}
} }, (formik) => (react.createElement(Form, null,
page === 1 ? (react.createElement(react.Fragment, null,
react.createElement(Margin, null,
react.createElement(Field, { name: "txType", component: ButtonGroup, options: [
['expense', 'Expense'],
['income', 'Income'],
['transfer', 'Transfer'],
] })),
react.createElement("div", { className: "flexRow" },
react.createElement(Margin, { className: "flexGrow" },
react.createElement(Field, { component: CurrencyInputFormik, currencySymbol: props.currencySymbol, name: "total", placeholder: "Total Amount" }),
react.createElement(ErrorMessage, { name: "total", component: "div" })),
react.createElement(Margin, { className: "flexShrink" }, "on"),
react.createElement(Margin, { className: "flexGrow" },
react.createElement(Field, { type: "date", name: "date" }),
react.createElement(ErrorMessage, { name: "date", component: "div" }))),
formik.values.txType !== 'transfer' && (react.createElement(Margin, null,
react.createElement(Field, { component: TextSuggest, name: "payee", placeholder: "Payee (e.g. Obsidian.md)", suggestions: props.txCache.payees }),
react.createElement(ErrorMessage, { name: "payee", component: "div" }))))) : (react.createElement("div", { className: "expenseLines" },
react.createElement(FieldArray, { name: "lines" }, ({ insert, remove }) => (react.createElement(react.Fragment, null,
formik.values.lines.map((line, i) => (react.createElement(ExpenseLine, { key: line.id, line: line, formik: formik, i: i, remove: remove, txCache: props.txCache, currencySymbol: props.currencySymbol }))),
react.createElement("button", { type: "button", onClick: () => {
const prevMaxID = formik.values.lines.reduce((max, line) => Math.max(max, line.id), -1);
const newLine = {
id: prevMaxID + 1,
account: '',
amount: '',
comment: '',
reconcile: '',
};
insert(formik.values.lines.length - 1, newLine);
} }, "Add Split")))),
react.createElement(ErrorMessage, { name: "lines", component: "div" }))),
react.createElement(Margin, null,
page === 1 && (react.createElement("button", { type: "button", onClick: () => {
let hadError = false;
if (formik.values.total === '') {
formik.setFieldTouched('total', true, true);
formik.validateForm();
hadError = true;
}
if (formik.values.txType !== 'transfer' &&
formik.values.payee === '') {
formik.setFieldTouched('payee', true, true);
formik.validateForm();
hadError = true;
}
if (!hadError) {
// The final expense line should be set to the opposite of the total
const lastI = formik.values.lines.length - 1;
const inverse = -1 * parseFloat(formik.values.total);
formik.values.lines[lastI].amount = inverse.toFixed(2);
setPage(page + 1);
}
} }, "Next")),
page === 2 && (react.createElement(react.Fragment, null,
react.createElement("button", { type: "button", onClick: () => {
setPage(page - 1);
} }, "Back"),
react.createElement("button", { type: "submit", disabled: formik.isSubmitting }, "Submit")))))))));
3 years ago
};
3 years ago
3 years ago
/** @license React v0.20.2
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
3 years ago
var scheduler_production_min = createCommonjsModule(function (module, exports) {
var f,g,h,k;if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now();};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q;};}if("undefined"===typeof window||"function"!==typeof MessageChannel){var t=null,u=null,w=function(){if(null!==t)try{var a=exports.unstable_now();t(!0,a);t=null;}catch(b){throw setTimeout(w,0),b;}};f=function(a){null!==t?setTimeout(f,0,a):(t=a,setTimeout(w,0));};g=function(a,b){u=setTimeout(a,b);};h=function(){clearTimeout(u);};exports.unstable_shouldYield=function(){return !1;};k=exports.unstable_forceFrameRate=function(){};}else {var x=window.setTimeout,y=window.clearTimeout;if("undefined"!==typeof console){var z=window.cancelAnimationFrame;"function"!==typeof window.requestAnimationFrame&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");"function"!==typeof z&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");}var A=!1,B=null,C=-1,D=5,E=0;exports.unstable_shouldYield=function(){return exports.unstable_now()>=E;};k=function(){};exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):D=0<a?Math.floor(1E3/a):5;};var F=new MessageChannel(),G=F.port2;F.port1.onmessage=function(){if(null!==B){var a=exports.unstable_now();E=a+D;try{B(!0,a)?G.postMessage(null):(A=!1,B=null);}catch(b){throw G.postMessage(null),b;}}else A=!1;};f=function(a){B=a;A||(A=!0,G.postMessage(null));};g=function(a,b){C=x(function(){a(exports.unstable_now());},b);};h=function(){y(C);C=-1;};}function H(a,b){var c=a.length;a.push(b);a:for(;;){var d=c-1>>>1,e=a[d];if(void 0!==e&&0<I(e,b))a[d]=b,a[c]=e,c=d;else break a;}}function J(a){a=a[0];return void 0===a?null:a;}function K(a){var b=a[0];if(void 0!==b){var c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length;d<e;){var m=2*(d+1)-1,n=a[m],v=m+1,r=a[v];if(void 0!==n&&0>I(n,c))void 0!==r&&0>I(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>I(r,c))a[d]=r,a[v]=c,d=v;else break a;}}return b;}return null;}function I(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id;}var L=[],M=[],N=1,O=null,P=3,Q=!1,R=!1,S=!1;function T(a){for(var b=J(M);null!==b;){if(null===b.callback)K(M);else if(b.startTime<=a)K(M),b.sortIndex=b.expirationTime,H(L,b);else break;b=J(M);}}function U(a){S=!1;T(a);if(!R)if(null!==J(L))R=!0,f(V);else {var b=J(M);null!==b&&g(U,b.startTime-a);}}function V(a,b){R=!1;S&&(S=!1,h());Q=!0;var c=P;try{T(b);for(O=J(L);null!==O&&(!(O.expirationTime>b)||a&&!exports.unstable_shouldYield());){var d=O.callback;if("function"===typeof d){O.callback=null;P=O.priorityLevel;var e=d(O.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?O.callback=e:O===J(L)&&K(L);T(b);}else K(L);O=J(L);}if(null!==O)var m=!0;else {var n=J(M);null!==n&&g(U,n.startTime-b);m=!1;}return m;}finally{O=null,P=c,Q=!1;}}var W=k;exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null;};exports.unstable_continueExecution=function(){R||Q||(R=!0,f(V));};exports.unstable_getCurrentPriorityLevel=function(){return P;};exports.unstable_getFirstCallbackNode=function(){return J(L);};exports.unstable_next=function(a){switch(P){case 1:case 2:case 3:var b=3;break;default:b=P;}var c=P;P=b;try{return a();}finally{P=c;}};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=W;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3;}var c=P;P=a;try{return b();}finally{P=c;}};exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();"object"===typ
});
3 years ago
3 years ago
/** @license React v0.20.2
* scheduler.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
3 years ago
var scheduler_development = createCommonjsModule(function (module, exports) {
{(function(){var enableSchedulerDebugging=false;var enableProfiling=false;var requestHostCallback;var requestHostTimeout;var cancelHostTimeout;var requestPaint;var hasPerformanceNow=typeof performance==='object'&&typeof performance.now==='function';if(hasPerformanceNow){var localPerformance=performance;exports.unstable_now=function(){return localPerformance.now();};}else {var localDate=Date;var initialTime=localDate.now();exports.unstable_now=function(){return localDate.now()-initialTime;};}if(// If Scheduler runs in a non-DOM environment, it falls back to a naive
// implementation using setTimeout.
typeof window==='undefined'||// Check if MessageChannel is supported, too.
typeof MessageChannel!=='function'){// If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,
// fallback to a naive implementation.
var _callback=null;var _timeoutID=null;var _flushCallback=function(){if(_callback!==null){try{var currentTime=exports.unstable_now();var hasRemainingTime=true;_callback(hasRemainingTime,currentTime);_callback=null;}catch(e){setTimeout(_flushCallback,0);throw e;}}};requestHostCallback=function(cb){if(_callback!==null){// Protect against re-entrancy.
setTimeout(requestHostCallback,0,cb);}else {_callback=cb;setTimeout(_flushCallback,0);}};requestHostTimeout=function(cb,ms){_timeoutID=setTimeout(cb,ms);};cancelHostTimeout=function(){clearTimeout(_timeoutID);};exports.unstable_shouldYield=function(){return false;};requestPaint=exports.unstable_forceFrameRate=function(){};}else {// Capture local references to native APIs, in case a polyfill overrides them.
var _setTimeout=window.setTimeout;var _clearTimeout=window.clearTimeout;if(typeof console!=='undefined'){// TODO: Scheduler no longer requires these methods to be polyfilled. But
// maybe we want to continue warning if they don't exist, to preserve the
// option to rely on it in the future?
var requestAnimationFrame=window.requestAnimationFrame;var cancelAnimationFrame=window.cancelAnimationFrame;if(typeof requestAnimationFrame!=='function'){// Using console['error'] to evade Babel and ESLint
console['error']("This browser doesn't support requestAnimationFrame. "+'Make sure that you load a '+'polyfill in older browsers. https://reactjs.org/link/react-polyfills');}if(typeof cancelAnimationFrame!=='function'){// Using console['error'] to evade Babel and ESLint
console['error']("This browser doesn't support cancelAnimationFrame. "+'Make sure that you load a '+'polyfill in older browsers. https://reactjs.org/link/react-polyfills');}}var isMessageLoopRunning=false;var scheduledHostCallback=null;var taskTimeoutID=-1;// Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.
var yieldInterval=5;var deadline=0;// TODO: Make this configurable
{// `isInputPending` is not available. Since we have no way of knowing if
// there's pending input, always yield at the end of the frame.
exports.unstable_shouldYield=function(){return exports.unstable_now()>=deadline;};// Since we yield every frame regardless, `requestPaint` has no effect.
requestPaint=function(){};}exports.unstable_forceFrameRate=function(fps){if(fps<0||fps>125){// Using console['error'] to evade Babel and ESLint
console['error']('forceFrameRate takes a positive int between 0 and 125, '+'forcing frame rates higher than 125 fps is not supported');return;}if(fps>0){yieldInterval=Math.floor(1000/fps);}else {// reset the framerate
yieldInterval=5;}};var performWorkUntilDeadline=function(){if(scheduledHostCallback!==null){var currentTime=exports.unstable_now();// Yield after `yieldInterval` ms, regardless of where we are in the vsync
// cycle. This means there's always time remaining at the beginning of
// the message event.
deadline=currentTime+yieldInterval;var hasTimeRemaining=true;try{var hasMoreWork=scheduledHostCallback(hasTimeRemaining,currentTime);if(!hasMoreWork){isMessageLoopRunning=false;scheduledHostCallback=null;}else {// If there's more work, schedule the next message event at the end
// of the preceding one.
port.postMessage(null);}}catch(error){// If a scheduler task throws, exit the current browser task so the
// error can be observed.
port.postMessage(null);throw error;}}else {isMessageLoopRunning=false;}// Yielding to the browser will give it a chance to paint, so we can
};var channel=new MessageChannel();var port=channel.port2;channel.port1.onmessage=performWorkUntilDeadline;requestHostCallback=function(callback){scheduledHostCallback=callback;if(!isMessageLoopRunning){isMessageLoopRunning=true;port.postMessage(null);}};requestHostTimeout=function(callback,ms){taskTimeoutID=_setTimeout(function(){callback(exports.unstable_now());},ms);};cancelHostTimeout=function(){_clearTimeout(taskTimeoutID);taskTimeoutID=-1;};}function push(heap,node){var index=heap.length;heap.push(node);siftUp(heap,node,index);}function peek(heap){var first=heap[0];return first===undefined?null:first;}function pop(heap){var first=heap[0];if(first!==undefined){var last=heap.pop();if(last!==first){heap[0]=last;siftDown(heap,last,0);}return first;}else {return null;}}function siftUp(heap,node,i){var index=i;while(true){var parentIndex=index-1>>>1;var parent=heap[parentIndex];if(parent!==undefined&&compare(parent,node)>0){// The parent is larger. Swap positions.
heap[parentIndex]=node;heap[index]=parent;index=parentIndex;}else {// The parent is smaller. Exit.
return;}}}function siftDown(heap,node,i){var index=i;var length=heap.length;while(index<length){var leftIndex=(index+1)*2-1;var left=heap[leftIndex];var rightIndex=leftIndex+1;var right=heap[rightIndex];// If the left or right node is smaller, swap with the smaller of those.
if(left!==undefined&&compare(left,node)<0){if(right!==undefined&&compare(right,left)<0){heap[index]=right;heap[rightIndex]=node;index=rightIndex;}else {heap[index]=left;heap[leftIndex]=node;index=leftIndex;}}else if(right!==undefined&&compare(right,node)<0){heap[index]=right;heap[rightIndex]=node;index=rightIndex;}else {// Neither child is smaller. Exit.
return;}}}function compare(a,b){// Compare sort index first, then task id.
var diff=a.sortIndex-b.sortIndex;return diff!==0?diff:a.id-b.id;}// TODO: Use symbols?
var ImmediatePriority=1;var UserBlockingPriority=2;var NormalPriority=3;var LowPriority=4;var IdlePriority=5;function markTaskErrored(task,ms){}/* eslint-disable no-var */ // Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var maxSigned31BitInt=1073741823;// Times out immediately
var IMMEDIATE_PRIORITY_TIMEOUT=-1;// Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT=250;var NORMAL_PRIORITY_TIMEOUT=5000;var LOW_PRIORITY_TIMEOUT=10000;// Never times out
var IDLE_PRIORITY_TIMEOUT=maxSigned31BitInt;// Tasks are stored on a min heap
var taskQueue=[];var timerQueue=[];// Incrementing id counter. Used to maintain insertion order.
var taskIdCounter=1;// Pausing the scheduler is useful for debugging.
var currentTask=null;var currentPriorityLevel=NormalPriority;// This is set while performing work, to prevent re-entrancy.
var isPerformingWork=false;var isHostCallbackScheduled=false;var isHostTimeoutScheduled=false;function advanceTimers(currentTime){// Check for tasks that are no longer delayed and add them to the queue.
var timer=peek(timerQueue);while(timer!==null){if(timer.callback===null){// Timer was cancelled.
pop(timerQueue);}else if(timer.startTime<=currentTime){// Timer fired. Transfer to the task queue.
pop(timerQueue);timer.sortIndex=timer.expirationTime;push(taskQueue,timer);}else {// Remaining timers are pending.
return;}timer=peek(timerQueue);}}function handleTimeout(currentTime){isHostTimeoutScheduled=false;advanceTimers(currentTime);if(!isHostCallbackScheduled){if(peek(taskQueue)!==null){isHostCallbackScheduled=true;requestHostCallback(flushWork);}else {var firstTimer=peek(timerQueue);if(firstTimer!==null){requestHostTimeout(handleTimeout,firstTimer.startTime-currentTime);}}}}function flushWork(hasTimeRemaining,initialTime){isHostCallbackScheduled=false;if(isHostTimeoutScheduled){// We scheduled a timeout but it's no longer needed. Cancel it.
isHostTimeoutScheduled=false;cancelHostTimeout();}isPerformingWork=true;var previousPriorityLevel=currentPriorityLevel;try{var currentTime; if(enableProfiling);else {// No catch in prod code path.
return workLoop(hasTimeRemaining,initialTime);}}finally{currentTask=null;currentPriorityLevel=previousPriorityLevel;isPerformingWork=false;}}function workLoop(hasTimeRemaining,initialTime){var currentTime=initialTime;advanceTimers(currentTime);currentTask=peek(taskQueue);while(currentTask!==null&&!enableSchedulerDebugging){if(currentTask.expirationTime>currentTime&&(!hasTimeRemaining||exports.unstable_shouldYield())){// This currentTask hasn't expired, and we've reached the deadline.
break;}var callback=currentTask.callback;if(typeof callback==='function'){currentTask.callback=null;currentPriorityLevel=currentTask.priorityLevel;var didUserCallbackTimeout=currentTask.expirationTime<=currentTime;var continuationCallback=callback(didUserCallbackTimeout);currentTime=exports.unstable_now();if(typeof continuationCallback==='function'){currentTask.callback=continuationCallback;}else {if(currentTask===peek(taskQueue)){pop(taskQueue);}}advanceTimers(currentTime);}else {pop(taskQueue);}currentTask=peek(taskQueue);}// Return whether there's additional work
if(currentTask!==null){return true;}else {var firstTimer=peek(timerQueue);if(firstTimer!==null){requestHostTimeout(handleTimeout,firstTimer.startTime-currentTime);}return false;}}function unstable_runWithPriority(priorityLevel,eventHandler){switch(priorityLevel){case ImmediatePriority:case UserBlockingPriority:case NormalPriority:case LowPriority:case IdlePriority:break;default:priorityLevel=NormalPriority;}var previousPriorityLevel=currentPriorityLevel;currentPriorityLevel=priorityLevel;try{return eventHandler();}finally{currentPriorityLevel=previousPriorityLevel;}}function unstable_next(eventHandler){var priorityLevel;switch(currentPriorityLevel){case ImmediatePriority:case UserBlockingPriority:case NormalPriority:// Shift down to normal priority
priorityLevel=NormalPriority;break;default:// Anything lower than normal priority should remain at the current level.
priorityLevel=currentPriorityLevel;break;}var previousPriorityLevel=currentPriorityLevel;currentPriorityLevel=priorityLevel;try{return eventHandler();}finally{currentPriorityLevel=previousPriorityLevel;}}function unstable_wrapCallback(callback){var parentPriorityLevel=currentPriorityLevel;return function(){// This is a fork of runWithPriority, inlined for performance.
var previousPriorityLevel=currentPriorityLevel;currentPriorityLevel=parentPriorityLevel;try{return callback.apply(this,arguments);}finally{currentPriorityLevel=previousPriorityLevel;}};}function unstable_scheduleCallback(priorityLevel,callback,options){var currentTime=exports.unstable_now();var startTime;if(typeof options==='object'&&options!==null){var delay=options.delay;if(typeof delay==='number'&&delay>0){startTime=currentTime+delay;}else {startTime=currentTime;}}else {startTime=currentTime;}var timeout;switch(priorityLevel){case ImmediatePriority:timeout=IMMEDIATE_PRIORITY_TIMEOUT;break;case UserBlockingPriority:timeout=USER_BLOCKING_PRIORITY_TIMEOUT;break;case IdlePriority:timeout=IDLE_PRIORITY_TIMEOUT;break;case LowPriority:timeout=LOW_PRIORITY_TIMEOUT;break;case NormalPriority:default:timeout=NORMAL_PRIORITY_TIMEOUT;break;}var expirationTime=startTime+timeout;var newTask={id:taskIdCounter++,callback:callback,priorityLevel:priorityLevel,startTime:startTime,expirationTime:expirationTime,sortIndex:-1};if(startTime>currentTime){// This is a delayed task.
newTask.sortIndex=startTime;push(timerQueue,newTask);if(peek(taskQueue)===null&&newTask===peek(timerQueue)){// All tasks are delayed, and this is the task with the earliest delay.
if(isHostTimeoutScheduled){// Cancel an existing timeout.
cancelHostTimeout();}else {isHostTimeoutScheduled=true;}// Schedule a timeout.
requestHostTimeout(handleTimeout,startTime-currentTime);}}else {newTask.sortIndex=expirationTime;push(taskQueue,newTask);// wait until the next time we yield.
if(!isHostCallbackScheduled&&!isPerformingWork){isHostCallbackScheduled=true;requestHostCallback(flushWork);}}return newTask;}function unstable_pauseExecution(){}function unstable_continueExecution(){if(!isHostCallbackScheduled&&!isPerformingWork){isHostCallbackScheduled=true;requestHostCallback(flushWork);}}function unstable_getFirstCallbackNode(){return peek(taskQueue);}function unstable_cancelCallback(task){// remove from the queue because you can't remove arbitrary nodes from an
// array based heap, only the first one.)
task.callback=null;}function unstable_getCurrentPriorityLevel(){return currentPriorityLevel;}var unstable_requestPaint=requestPaint;var unstable_Profiling=null;exports.unstable_IdlePriority=IdlePriority;exports.unstable_ImmediatePriority=ImmediatePriority;exports.unstable_LowPriority=LowPriority;exports.unstable_NormalPriority=NormalPriority;exports.unstable_Profiling=unstable_Profiling;exports.unstable_UserBlockingPriority=UserBlockingPriority;exports.unstable_cancelCallback=unstable_cancelCallback;exports.unstable_continueExecution=unstable_continueExecution;exports.unstable_getCurrentPriorityLevel=unstable_getCurrentPriorityLevel;exports.unstable_getFirstCallbackNode=unstable_getFirstCallbackNode;exports.unstable_next=unstable_next;exports.unstable_pauseExecution=unstable_pauseExecution;exports.unstable_requestPaint=unstable_requestPaint;exports.unstable_runWithPriority=unstable_runWithPriority;exports.unstable_scheduleCallback=unstable_scheduleCallback;exports.unstable_wrapCallback=unstable_wrapCallback;})();}
});
3 years ago
3 years ago
var scheduler = createCommonjsModule(function (module) {
{module.exports=scheduler_development;}
});
3 years ago
3 years ago
/** @license React v17.0.2
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function y(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return "Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";}if(!react)throw Error(y(227));var ba=new Set();function da(a,b){ea(a,b);ea(a+"Capture",b);}function ea(a,b){for(a=0;a<b.length;a++)ba.add(b[a]);}var fa=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement);function B$1(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var D$1={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){D$1[a]=new B$1(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];D$1[b]=new B$1(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){D$1[a]=new B$1(a,2,!1,a.toLowerCase(),null,!1,!1);});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){D$1[a]=new B$1(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){D$1[a]=new B$1(a,3,!1,a.toLowerCase(),null,!1,!1);});["checked","multiple","muted","selected"].forEach(function(a){D$1[a]=new B$1(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){D$1[a]=new B$1(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){D$1[a]=new B$1(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){D$1[a]=new B$1(a,5,!1,a.toLowerCase(),null,!1,!1);});var oa=/[\-:]([a-z])/g;function pa(a){return a[1].toUpperCase();}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(oa,pa);D$1[b]=new B$1(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(oa,pa);D$1[b]=new B$1(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(oa,pa);D$1[b]=new B$1(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){D$1[a]=new B$1(a,1,!1,a.toLowerCase(),null,!1,!1);});D$1.xlinkHref=new B$1("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){D$1[a]=new B$1(a,1,!1,a.toLowerCase(),null,!0,!0);});var ra=react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,s
3 years ago
/** @license React v0.20.2
* scheduler-tracing.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
3 years ago
var schedulerTracing_development = createCommonjsModule(function (module, exports) {
{(function(){var DEFAULT_THREAD_ID=0;// Counters used to generate unique IDs.
var interactionIDCounter=0;var threadIDCounter=0;// Set of currently traced interactions.
// Interactions "stack"
// Meaning that newly traced interactions are appended to the previously active set.
// When an interaction goes out of scope, the previous set (if any) is restored.
exports.__interactionsRef=null;// Listener(s) to notify when interactions begin and end.
exports.__subscriberRef=null;{exports.__interactionsRef={current:new Set()};exports.__subscriberRef={current:null};}function unstable_clear(callback){var prevInteractions=exports.__interactionsRef.current;exports.__interactionsRef.current=new Set();try{return callback();}finally{exports.__interactionsRef.current=prevInteractions;}}function unstable_getCurrent(){{return exports.__interactionsRef.current;}}function unstable_getThreadID(){return ++threadIDCounter;}function unstable_trace(name,timestamp,callback){var threadID=arguments.length>3&&arguments[3]!==undefined?arguments[3]:DEFAULT_THREAD_ID;var interaction={__count:1,id:interactionIDCounter++,name:name,timestamp:timestamp};var prevInteractions=exports.__interactionsRef.current;// Traced interactions should stack/accumulate.
// To do that, clone the current interactions.
// The previous set will be restored upon completion.
var interactions=new Set(prevInteractions);interactions.add(interaction);exports.__interactionsRef.current=interactions;var subscriber=exports.__subscriberRef.current;var returnValue;try{if(subscriber!==null){subscriber.onInteractionTraced(interaction);}}finally{try{if(subscriber!==null){subscriber.onWorkStarted(interactions,threadID);}}finally{try{returnValue=callback();}finally{exports.__interactionsRef.current=prevInteractions;try{if(subscriber!==null){subscriber.onWorkStopped(interactions,threadID);}}finally{interaction.__count--;// If no async work was scheduled for this interaction,
// Notify subscribers that it's completed.
if(subscriber!==null&&interaction.__count===0){subscriber.onInteractionScheduledWorkCompleted(interaction);}}}}}return returnValue;}function unstable_wrap(callback){var threadID=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_THREAD_ID;var wrappedInteractions=exports.__interactionsRef.current;var subscriber=exports.__subscriberRef.current;if(subscriber!==null){subscriber.onWorkScheduled(wrappedInteractions,threadID);}// Update the pending async work count for the current interactions.
// Update after calling subscribers in case of error.
wrappedInteractions.forEach(function(interaction){interaction.__count++;});var hasRun=false;function wrapped(){var prevInteractions=exports.__interactionsRef.current;exports.__interactionsRef.current=wrappedInteractions;subscriber=exports.__subscriberRef.current;try{var returnValue;try{if(subscriber!==null){subscriber.onWorkStarted(wrappedInteractions,threadID);}}finally{try{returnValue=callback.apply(undefined,arguments);}finally{exports.__interactionsRef.current=prevInteractions;if(subscriber!==null){subscriber.onWorkStopped(wrappedInteractions,threadID);}}}return returnValue;}finally{if(!hasRun){// We only expect a wrapped function to be executed once,
// But in the event that it's executed more than once
// Only decrement the outstanding interaction counts once.
hasRun=true;// Update pending async counts for all wrapped interactions.
// If this was the last scheduled async work for any of them,
// Mark them as completed.
wrappedInteractions.forEach(function(interaction){interaction.__count--;if(subscriber!==null&&interaction.__count===0){subscriber.onInteractionScheduledWorkCompleted(interaction);}});}}}wrapped.cancel=function cancel(){subscriber=exports.__subscriberRef.current;try{if(subscriber!==null){subscriber.onWorkCanceled(wrappedInteractions,threadID);}}finally{// Update pending async counts for all wrapped interactions.
// If this was the last scheduled async work for any of them,
// Mark them as completed.
wrappedInteractions.forEach(function(interaction){interaction.__count--;if(subscriber&&interaction.__count===0){subscriber.onInteractionScheduledWorkCompleted(interaction);}});}};return wrapped;}var subscribers=null;{subscribers=new Set();}function unstable_subscribe(subscriber){{subscribers.add(subscriber);if(subscribers.size===1){exports.__subscriberRef.current={onInteractionScheduledWorkCompleted:onInteractionScheduledWorkCompleted,onInteractionTraced:onInteractionTraced,onWorkCanceled:onWorkCanceled,onWorkScheduled:onWorkScheduled,onWorkStarted:onWorkStarted,onWorkStopped:onWorkStopped};}}}function unstable_unsubscribe(subscriber){{subscribers.delete(subscriber);if(subscribers.size===0){exports.__subscriberRef.current=null;}}}function onInteractionTraced(interaction){var didCatchError=false;var caughtError=null;subscribers.forEach(function(subscriber){try{subscriber.onInteractionTraced(interaction);}catch(error){if(!didCatchError){didCatchError=true;caughtError=error;}}});if(didCatchError){throw caughtError;}}function onInteractionScheduledWorkCompleted(interaction){var didCatchError=false;var caughtError=null;subscribers.forEach(function(subscriber){try{subscriber.onInteractionScheduledWorkCompleted(interaction);}catch(error){if(!didCatchError){didCatchError=true;caughtError=error;}}});if(didCatchError){throw caughtError;}}function onWorkScheduled(interactions,threadID){var didCatchError=false;var caughtError=null;subscribers.forEach(function(subscriber){try{subscriber.onWorkScheduled(interactions,threadID);}catch(error){if(!didCatchError){didCatchError=true;caughtError=error;}}});if(didCatchError){throw caughtError;}}function onWorkStarted(interactions,threadID){var didCatchError=false;var caughtError=null;subscribers.forEach(function(subscriber){try{subscriber.onWorkStarted(interactions,threadID);}catch(error){if(!didCatchError){didCatchError=true;caughtError=error;}}});if(didCatchError){throw caughtError;}}function onWorkStopped(interactions,threadID){var didCatchError=false;var caughtError=null;subscribers.forEach(function(subscriber){try{subscriber.onWorkStopped(interactions,threadID);}catch(error){if(!didCatchError){didCatchError=true;caughtError=error;}}});if(didCatchError){throw caughtError;}}function onWorkCanceled(interactions,threadID){var didCatchError=false;var caughtError=null;subscribers.forEach(function(subscriber){try{subscriber.onWorkCanceled(interactions,threadID);}catch(error){if(!didCatchError){didCatchError=true;caughtError=error;}}});if(didCatchError){throw caughtError;}}exports.unstable_clear=unstable_clear;exports.unstable_getCurrent=unstable_getCurrent;exports.unstable_getThreadID=unstable_getThreadID;exports.unstable_subscribe=unstable_subscribe;exports.unstable_trace=unstable_trace;exports.unstable_unsubscribe=unstable_unsubscribe;exports.unstable_wrap=unstable_wrap;})();}
});
3 years ago
3 years ago
var tracing = createCommonjsModule(function (module) {
{module.exports=schedulerTracing_development;}
});
3 years ago
3 years ago
/** @license React v17.0.2
* react-dom.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
3 years ago
var reactDom_development = createCommonjsModule(function (module, exports) {
{(function(){var React=react;var _assign=objectAssign;var Scheduler=scheduler;var tracing$1=tracing;var ReactSharedInternals=React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format){{for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}printWarning('warn',format,args);}}function error(format){{for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}printWarning('error',format,args);}}function printWarning(level,format,args){// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;var stack=ReactDebugCurrentFrame.getStackAddendum();if(stack!==''){format+='%s';args=args.concat([stack]);}var argsWithFormat=args.map(function(item){return ''+item;});// Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: '+format);// We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level],console,argsWithFormat);}}if(!React){{throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.");}}var FunctionComponent=0;var ClassComponent=1;var IndeterminateComponent=2;// Before we know whether it is function or class
var HostRoot=3;// Root of a host tree. Could be nested inside another node.
var HostPortal=4;// A subtree. Could be an entry point to a different renderer.
var HostComponent=5;var HostText=6;var Fragment=7;var Mode=8;var ContextConsumer=9;var ContextProvider=10;var ForwardRef=11;var Profiler=12;var SuspenseComponent=13;var MemoComponent=14;var SimpleMemoComponent=15;var LazyComponent=16;var IncompleteClassComponent=17;var DehydratedFragment=18;var SuspenseListComponent=19;var FundamentalComponent=20;var ScopeComponent=21;var Block=22;var OffscreenComponent=23;var LegacyHiddenComponent=24;// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableProfilerTimer=true;// Record durations for commit and passive effects phases.
var enableFundamentalAPI=false;// Experimental Scope support.
var enableNewReconciler=false;// Errors that are thrown while unmounting (or after in the case of passive effects)
var warnAboutStringRefs=false;var allNativeEvents=new Set();/**
* Mapping from registration name to event name
*/var registrationNameDependencies={};/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in true.
* @type {Object}
*/var possibleRegistrationNames={};// Trust the developer to only use possibleRegistrationNames in true
function registerTwoPhaseEvent(registrationName,dependencies){registerDirectEvent(registrationName,dependencies);registerDirectEvent(registrationName+'Capture',dependencies);}function registerDirectEvent(registrationName,dependencies){{if(registrationNameDependencies[registrationName]){error('EventRegistry: More than one plugin attempted to publish the same '+'registration name, `%s`.',registrationName);}}registrationNameDependencies[registrationName]=dependencies;{var lowerCasedName=registrationName.toLowerCase();possibleRegistrationNames[lowerCasedName]=registrationName;if(registrationName==='onDoubleClick'){possibleRegistrationNames.ondblclick=registrationName;}}for(var i=0;i<dependencies.length;i++){allNativeEvents.add(dependencies[i]);}}var canUseDOM=!!(typeof window!=='undefined'&&typeof window.document!=='undefined'&&typeof window.document.createElement!=='undefined');// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED=0;// A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.
var STRING=1;// A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.
var BOOLEANISH_STRING=2;// A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
var BOOLEAN=3;// An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.
var OVERLOADED_BOOLEAN=4;// An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.
var NUMERIC=5;// An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.
var POSITIVE_NUMERIC=6;/* eslint-disable max-len */var ATTRIBUTE_NAME_START_CHAR=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";/* eslint-enable max-len */var ATTRIBUTE_NAME_CHAR=ATTRIBUTE_NAME_START_CHAR+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";var ROOT_ATTRIBUTE_NAME='data-reactroot';var VALID_ATTRIBUTE_NAME_REGEX=new RegExp('^['+ATTRIBUTE_NAME_START_CHAR+']['+ATTRIBUTE_NAME_CHAR+']*$');var hasOwnProperty=Object.prototype.hasOwnProperty;var illegalAttributeNameCache={};var validatedAttributeNameCache={};function isAttributeNameSafe(attributeName){if(hasOwnProperty.call(validatedAttributeNameCache,attributeName)){return true;}if(hasOwnProperty.call(illegalAttributeNameCache,attributeName)){return false;}if(VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)){validatedAttributeNameCache[attributeName]=true;return true;}illegalAttributeNameCache[attributeName]=true;{error('Invalid attribute name: `%s`',attributeName);}return false;}function shouldIgnoreAttribute(name,propertyInfo,isCustomComponentTag){if(propertyInfo!==null){return propertyInfo.type===RESERVED;}if(isCustomComponentTag){return false;}if(name.length>2&&(name[0]==='o'||name[0]==='O')&&(name[1]==='n'||name[1]==='N')){return true;}return false;}function shouldRemoveAttributeWithWarning(name,value,propertyInfo,isCustomComponentTag){if(propertyInfo!==null&&propertyInfo.type===RESERVED){return false;}switch(typeof value){case'function':// $FlowIssue symbol is perfectly valid here
case'symbol':// eslint-disable-line
return true;case'boolean':{if(isCustomComponentTag){return false;}if(propertyInfo!==null){return !propertyInfo.acceptsBooleans;}else {var prefix=name.toLowerCase().slice(0,5);return prefix!=='data-'&&prefix!=='aria-';}}default:return false;}}function shouldRemoveAttribute(name,value,propertyInfo,isCustomComponentTag){if(value===null||typeof value==='undefined'){return true;}if(shouldRemoveAttributeWithWarning(name,value,propertyInfo,isCustomComponentTag)){return true;}if(isCustomComponentTag){return false;}if(propertyInfo!==null){switch(propertyInfo.type){case BOOLEAN:return !value;case OVERLOADED_BOOLEAN:return value===false;case NUMERIC:return isNaN(value);case POSITIVE_NUMERIC:return isNaN(value)||value<1;}}return false;}function getPropertyInfo(name){return properties.hasOwnProperty(name)?properties[name]:null;}function PropertyInfoRecord(name,type,mustUseProperty,attributeName,attributeNamespace,sanitizeURL,removeEmptyString){this.acceptsBooleans=type===BOOLEANISH_STRING||type===BOOLEAN||type===OVERLOADED_BOOLEAN;this.attributeName=attributeName;this.attributeNamespace=attributeNamespace;this.mustUseProperty=mustUseProperty;this.propertyName=name;this.type=type;this.sanitizeURL=sanitizeURL;this.removeEmptyString=removeEmptyString;}// When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.
var properties={};// These props are reserved by React. They shouldn't be written to the DOM.
var reservedProps=['children','dangerouslySetInnerHTML',// TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue','defaultChecked','innerHTML','suppressContentEditableWarning','suppressHydrationWarning','style'];reservedProps.forEach(function(name){properties[name]=new PropertyInfoRecord(name,RESERVED,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.
[['acceptCharset','accept-charset'],['className','class'],['htmlFor','for'],['httpEquiv','http-equiv']].forEach(function(_ref){var name=_ref[0],attributeName=_ref[1];properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
['contentEditable','draggable','spellCheck','value'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEANISH_STRING,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.
['autoReverse','externalResourcesRequired','focusable','preserveAlpha'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEANISH_STRING,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML boolean attributes.
['allowFullScreen','async',// Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus','autoPlay','controls','default','defer','disabled','disablePictureInPicture','disableRemotePlayback','formNoValidate','hidden','loop','noModule','noValidate','open','playsInline','readOnly','required','reversed','scoped','seamless',// Microdata
'itemScope'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEAN,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.
['checked',// Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple','muted','selected'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEAN,true,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.
['capture','download'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,OVERLOADED_BOOLEAN,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that must be positive numbers.
['cols','rows','size','span'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,POSITIVE_NUMERIC,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that must be numbers.
['rowSpan','start'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,NUMERIC,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});var CAMELIZE=/[\-\:]([a-z])/g;var capitalize=function(token){return token[1].toUpperCase();};// This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.
['accent-height','alignment-baseline','arabic-form','baseline-shift','cap-height','clip-path','clip-rule','color-interpolation','color-interpolation-filters','color-profile','color-rendering','dominant-baseline','enable-background','fill-opacity','fill-rule','flood-color','flood-opacity','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','glyph-name','glyph-orientation-horizontal','glyph-orientation-vertical','horiz-adv-x','horiz-origin-x','image-rendering','letter-spacing','lighting-color','marker-end','marker-mid','marker-start','overline-position','overline-thickness','paint-order','panose-1','pointer-events','rendering-intent','shape-rendering','stop-color','stop-opacity','strikethrough-position','strikethrough-thickness','stroke-dasharray','stroke-dashoffset','stroke-linecap','stroke-linejoin','stroke-miterlimit','stroke-opacity','stroke-width','text-anchor','text-decoration','text-rendering','underline-position','underline-thickness','unicode-bidi','unicode-range','units-per-em','v-alphabetic','v-hanging','v-ideographic','v-mathematical','vector-effect','vert-adv-y','vert-origin-x','vert-origin-y','word-spacing','writing-mode','xmlns:xlink','x-height'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,null,// attributeNamespace
false,// sanitizeURL
false);});// String SVG attributes with the xlink namespace.
['xlink:actuate','xlink:arcrole','xlink:role','xlink:show','xlink:title','xlink:type'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,'http://www.w3.org/1999/xlink',false,// sanitizeURL
false);});// String SVG attributes with the xml namespace.
['xml:base','xml:lang','xml:space'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,'http://www.w3.org/XML/1998/namespace',false,// sanitizeURL
false);});// These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.
['tabIndex','crossOrigin'].forEach(function(attributeName){properties[attributeName]=new PropertyInfoRecord(attributeName,STRING,false,// mustUseProperty
attributeName.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.
var xlinkHref='xlinkHref';properties[xlinkHref]=new PropertyInfoRecord('xlinkHref',STRING,false,// mustUseProperty
'xlink:href','http://www.w3.org/1999/xlink',true,// sanitizeURL
false);['src','href','action','formAction'].forEach(function(attributeName){properties[attributeName]=new PropertyInfoRecord(attributeName,STRING,false,// mustUseProperty
attributeName.toLowerCase(),// attributeName
null,// attributeNamespace
true,// sanitizeURL
true);});// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space
/* eslint-disable max-len */var isJavaScriptProtocol=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;var didWarn=false;function sanitizeURL(url){{if(!didWarn&&isJavaScriptProtocol.test(url)){didWarn=true;error('A future version of React will block javascript: URLs as a security precaution. '+'Use event handlers instead if you can. If you need to generate unsafe HTML try '+'using dangerouslySetInnerHTML instead. React was passed %s.',JSON.stringify(url));}}}/**
* Get the value for a property on a node. Only used in DEV for SSR validation.
* The "expected" argument is used as a hint of what the expected value is.
* Some properties have multiple equivalent values.
*/function getValueForProperty(node,name,expected,propertyInfo){{if(propertyInfo.mustUseProperty){var propertyName=propertyInfo.propertyName;return node[propertyName];}else {if(propertyInfo.sanitizeURL){// If we haven't fully disabled javascript: URLs, and if
// the hydration is successful of a javascript: URL, we
// still want to warn on the client.
sanitizeURL(''+expected);}var attributeName=propertyInfo.attributeName;var stringValue=null;if(propertyInfo.type===OVERLOADED_BOOLEAN){if(node.hasAttribute(attributeName)){var value=node.getAttribute(attributeName);if(value===''){return true;}if(shouldRemoveAttribute(name,expected,propertyInfo,false)){return value;}if(value===''+expected){return expected;}return value;}}else if(node.hasAttribute(attributeName)){if(shouldRemoveAttribute(name,expected,propertyInfo,false)){// We had an attribute but shouldn't have had one, so read it
// for the error message.
return node.getAttribute(attributeName);}if(propertyInfo.type===BOOLEAN){// If this was a boolean, it doesn't matter what the value is
// the fact that we have it is the same as the expected.
return expected;}// Even if this property uses a namespace we use getAttribute
// because we assume its namespaced name is the same as our config.
// To use getAttributeNS we need the local name which we don't have
// in our config atm.
stringValue=node.getAttribute(attributeName);}if(shouldRemoveAttribute(name,expected,propertyInfo,false)){return stringValue===null?expected:stringValue;}else if(stringValue===''+expected){return expected;}else {return stringValue;}}}}/**
* Get the value for a attribute on a node. Only used in DEV for SSR validation.
* The third argument is used as a hint of what the expected value is. Some
* attributes have multiple equivalent values.
*/function getValueForAttribute(node,name,expected){{if(!isAttributeNameSafe(name)){return;}// If the object is an opaque reference ID, it's expected that
// the next prop is different than the server value, so just return
// expected
if(isOpaqueHydratingObject(expected)){return expected;}if(!node.hasAttribute(name)){return expected===undefined?undefined:null;}var value=node.getAttribute(name);if(value===''+expected){return expected;}return value;}}/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/function setValueForProperty(node,name,value,isCustomComponentTag){var propertyInfo=getPropertyInfo(name);if(shouldIgnoreAttribute(name,propertyInfo,isCustomComponentTag)){return;}if(shouldRemoveAttribute(name,value,propertyInfo,isCustomComponentTag)){value=null;}// If the prop isn't in the special list, treat it as a simple attribute.
if(isCustomComponentTag||propertyInfo===null){if(isAttributeNameSafe(name)){var _attributeName=name;if(value===null){node.removeAttribute(_attributeName);}else {node.setAttribute(_attributeName,''+value);}}return;}var mustUseProperty=propertyInfo.mustUseProperty;if(mustUseProperty){var propertyName=propertyInfo.propertyName;if(value===null){var type=propertyInfo.type;node[propertyName]=type===BOOLEAN?false:'';}else {// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyName]=value;}return;}// The rest are treated as attributes with special cases.
var attributeName=propertyInfo.attributeName,attributeNamespace=propertyInfo.attributeNamespace;if(value===null){node.removeAttribute(attributeName);}else {var _type=propertyInfo.type;var attributeValue;if(_type===BOOLEAN||_type===OVERLOADED_BOOLEAN&&value===true){// If attribute type is boolean, we know for sure it won't be an execution sink
// and we won't require Trusted Type here.
attributeValue='';}else {// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
{attributeValue=''+value;}if(propertyInfo.sanitizeURL){sanitizeURL(attributeValue.toString());}}if(attributeNamespace){node.setAttributeNS(attributeNamespace,attributeName,attributeValue);}else {node.setAttribute(attributeName,attributeValue);}}}// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE=0xeac7;var REACT_PORTAL_TYPE=0xeaca;var REACT_FRAGMENT_TYPE=0xeacb;var REACT_STRICT_MODE_TYPE=0xeacc;var REACT_PROFILER_TYPE=0xead2;var REACT_PROVIDER_TYPE=0xeacd;var REACT_CONTEXT_TYPE=0xeace;var REACT_FORWARD_REF_TYPE=0xead0;var REACT_SUSPENSE_TYPE=0xead1;var REACT_SUSPENSE_LIST_TYPE=0xead8;var REACT_MEMO_TYPE=0xead3;var REACT_LAZY_TYPE=0xead4;var REACT_BLOCK_TYPE=0xead9;var REACT_SERVER_BLOCK_TYPE=0xeada;var REACT_FUNDAMENTAL_TYPE=0xead5;var REACT_SCOPE_TYPE=0xead7;var REACT_OPAQUE_ID_TYPE=0xeae0;var REACT_DEBUG_TRACING_MODE_TYPE=0xeae1;var REACT_OFFSCREEN_TYPE=0xeae2;var REACT_LEGACY_HIDDEN_TYPE=0xeae3;if(typeof Symbol==='function'&&Symbol.for){var symbolFor=Symbol.for;REACT_ELEMENT_TYPE=symbolFor('react.element');REACT_PORTAL_TYPE=symbolFor('react.portal');REACT_FRAGMENT_TYPE=symbolFor('react.fragment');REACT_STRICT_MODE_TYPE=symbolFor('react.strict_mode');REACT_PROFILER_TYPE=symbolFor('react.profiler');REACT_PROVIDER_TYPE=symbolFor('react.provider');REACT_CONTEXT_TYPE=symbolFor('react.context');REACT_FORWARD_REF_TYPE=symbolFor('react.forward_ref');REACT_SUSPENSE_TYPE=symbolFor('react.suspense');REACT_SUSPENSE_LIST_TYPE=symbolFor('react.suspense_list');REACT_MEMO_TYPE=symbolFor('react.memo');REACT_LAZY_TYPE=symbolFor('react.lazy');REACT_BLOCK_TYPE=symbolFor('react.block');REACT_SERVER_BLOCK_TYPE=symbolFor('react.server.block');REACT_FUNDAMENTAL_TYPE=symbolFor('react.fundamental');REACT_SCOPE_TYPE=symbolFor('react.scope');REACT_OPAQUE_ID_TYPE=symbolFor('react.opaque.id');REACT_DEBUG_TRACING_MODE_TYPE=symbolFor('react.debug_trace_mode');REACT_OFFSCREEN_TYPE=symbolFor('react.offscreen');REACT_LEGACY_HIDDEN_TYPE=symbolFor('react.legacy_hidden');}var MAYBE_ITERATOR_SYMBOL=typeof Symbol==='function'&&Symbol.iterator;var FAUX_ITERATOR_SYMBOL='@@iterator';function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=='object'){return null;}var maybeIterator=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL];if(typeof maybeIterator==='function'){return maybeIterator;}return null;}// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth=0;var prevLog;var prevInfo;var prevWarn;var prevError;var prevGroup;var prevGroupCollapsed;var prevGroupEnd;function disabledLog(){}disabledLog.__reactDisabledLog=true;function disableLogs(){{if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */prevLog=console.log;prevInfo=console.info;prevWarn=console.warn;prevError=console.error;prevGroup=console.group;prevGroupCollapsed=console.groupCollapsed;prevGroupEnd=console.groupEnd;// https://github.com/facebook/react/issues/19099
var props={configurable:true,enumerable:true,value:disabledLog,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{info:props,log:props,warn:props,error:props,group:props,groupCollapsed:props,groupEnd:props});/* eslint-enable react-internal/no-production-logging */}disabledDepth++;}}function reenableLogs(){{disabledDepth--;if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */var props={configurable:true,enumerable:true,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{log:_assign({},props,{value:prevLog}),info:_assign({},props,{value:prevInfo}),warn:_assign({},props,{value:prevWarn}),error:_assign({},props,{value:prevError}),group:_assign({},props,{value:prevGroup}),groupCollapsed:_assign({},props,{value:prevGroupCollapsed}),groupEnd:_assign({},props,{value:prevGroupEnd})});/* eslint-enable react-internal/no-production-logging */}if(disabledDepth<0){error('disabledDepth fell below zero. '+'This is a bug in React. Please file an issue.');}}}var ReactCurrentDispatcher=ReactSharedInternals.ReactCurrentDispatcher;var prefix;function describeBuiltInComponentFrame(name,source,ownerFn){{if(prefix===undefined){// Extract the VM specific prefix used by each line.
try{throw Error();}catch(x){var match=x.stack.trim().match(/\n( *(at )?)/);prefix=match&&match[1]||'';}}// We use the prefix to ensure our stacks line up with native stack frames.
return '\n'+prefix+name;}}var reentry=false;var componentFrameCache;{var PossiblyWeakMap=typeof WeakMap==='function'?WeakMap:Map;componentFrameCache=new PossiblyWeakMap();}function describeNativeComponentFrame(fn,construct){// If something asked for a stack inside a fake render, it should get ignored.
if(!fn||reentry){return '';}{var frame=componentFrameCache.get(fn);if(frame!==undefined){return frame;}}var control;reentry=true;var previousPrepareStackTrace=Error.prepareStackTrace;// $FlowFixMe It does accept undefined.
Error.prepareStackTrace=undefined;var previousDispatcher;{previousDispatcher=ReactCurrentDispatcher.current;// Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher.current=null;disableLogs();}try{// This should throw.
if(construct){// Something should be setting the props in the constructor.
var Fake=function(){throw Error();};// $FlowFixMe
Object.defineProperty(Fake.prototype,'props',{set:function(){// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();}});if(typeof Reflect==='object'&&Reflect.construct){// We construct a different control for this case to include any extra
// frames added by the construct call.
try{Reflect.construct(Fake,[]);}catch(x){control=x;}Reflect.construct(fn,[],Fake);}else {try{Fake.call();}catch(x){control=x;}fn.call(Fake.prototype);}}else {try{throw Error();}catch(x){control=x;}fn();}}catch(sample){// This is inlined manually because closure doesn't do it for us.
if(sample&&control&&typeof sample.stack==='string'){// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines=sample.stack.split('\n');var controlLines=control.stack.split('\n');var s=sampleLines.length-1;var c=controlLines.length-1;while(s>=1&&c>=0&&sampleLines[s]!==controlLines[c]){// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;}for(;s>=1&&c>=0;s--,c--){// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if(sampleLines[s]!==controlLines[c]){// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if(s!==1||c!==1){do{s--;c--;// We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if(c<0||sampleLines[s]!==controlLines[c]){// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame='\n'+sampleLines[s].replace(' at new ',' at ');{if(typeof fn==='function'){componentFrameCache.set(fn,_frame);}}// Return the line we found.
return _frame;}}while(s>=1&&c>=0);}break;}}}}finally{reentry=false;{ReactCurrentDispatcher.current=previousDispatcher;reenableLogs();}Error.prepareStackTrace=previousPrepareStackTrace;}// Fallback to just using the name if we couldn't make it throw.
var name=fn?fn.displayName||fn.name:'';var syntheticFrame=name?describeBuiltInComponentFrame(name):'';{if(typeof fn==='function'){componentFrameCache.set(fn,syntheticFrame);}}return syntheticFrame;}function describeClassComponentFrame(ctor,source,ownerFn){{return describeNativeComponentFrame(ctor,true);}}function describeFunctionComponentFrame(fn,source,ownerFn){{return describeNativeComponentFrame(fn,false);}}function shouldConstruct(Component){var prototype=Component.prototype;return !!(prototype&&prototype.isReactComponent);}function describeUnknownElementTypeFrameInDEV(type,source,ownerFn){if(type==null){return '';}if(typeof type==='function'){{return describeNativeComponentFrame(type,shouldConstruct(type));}}if(typeof type==='string'){return describeBuiltInComponentFrame(type);}switch(type){case REACT_SUSPENSE_TYPE:return describeBuiltInComponentFrame('Suspense');case REACT_SUSPENSE_LIST_TYPE:return describeBuiltInComponentFrame('SuspenseList');}if(typeof type==='object'){switch(type.$$typeof){case REACT_FORWARD_REF_TYPE:return describeFunctionComponentFrame(type.render);case REACT_MEMO_TYPE:// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type,source,ownerFn);case REACT_BLOCK_TYPE:return describeFunctionComponentFrame(type._render);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload),source,ownerFn);}catch(x){}}}}return '';}function describeFiber(fiber){var owner=fiber._debugOwner?fiber._debugOwner.type:null;var source=fiber._debugSource;switch(fiber.tag){case HostComponent:return describeBuiltInComponentFrame(fiber.type);case LazyComponent:return describeBuiltInComponentFrame('Lazy');case SuspenseComponent:return describeBuiltInComponentFrame('Suspense');case SuspenseListComponent:return describeBuiltInComponentFrame('SuspenseList');case FunctionComponent:case IndeterminateComponent:case SimpleMemoComponent:return describeFunctionComponentFrame(fiber.type);case ForwardRef:return describeFunctionComponentFrame(fiber.type.render);case Block:return describeFunctionComponentFrame(fiber.type._render);case ClassComponent:return describeClassComponentFrame(fiber.type);default:return '';}}function getStackByFiberInDevAndProd(workInProgress){try{var info='';var node=workInProgress;do{info+=describeFiber(node);node=node.return;}while(node);return info;}catch(x){return '\nError generating stack: '+x.message+'\n'+x.stack;}}function getWrappedName(outerType,innerType,wrapperName){var functionName=innerType.displayName||innerType.name||'';return outerType.displayName||(functionName!==''?wrapperName+"("+functionName+")":wrapperName);}function getContextName(type){return type.displayName||'Context';}function getComponentName(type){if(type==null){// Host root, text node or just invalid type.
return null;}{if(typeof type.tag==='number'){error('Received an unexpected object in getComponentName(). '+'This is likely a bug in React. Please file an issue.');}}if(typeof type==='function'){return type.displayName||type.name||null;}if(typeof type==='string'){return type;}switch(type){case REACT_FRAGMENT_TYPE:return 'Fragment';case REACT_PORTAL_TYPE:return 'Portal';case REACT_PROFILER_TYPE:return 'Profiler';case REACT_STRICT_MODE_TYPE:return 'StrictMode';case REACT_SUSPENSE_TYPE:return 'Suspense';case REACT_SUSPENSE_LIST_TYPE:return 'SuspenseList';}if(typeof type==='object'){switch(type.$$typeof){case REACT_CONTEXT_TYPE:var context=type;return getContextName(context)+'.Consumer';case REACT_PROVIDER_TYPE:var provider=type;return getContextName(provider._context)+'.Provider';case REACT_FORWARD_REF_TYPE:return getWrappedName(type,type.render,'ForwardRef');case REACT_MEMO_TYPE:return getComponentName(type.type);case REACT_BLOCK_TYPE:return getComponentName(type._render);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{return getComponentName(init(payload));}catch(x){return null;}}}}return null;}var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;var current=null;var isRendering=false;function getCurrentFiberOwnerNameInDevOrNull(){{if(current===null){return null;}var owner=current._debugOwner;if(owner!==null&&typeof owner!=='undefined'){return getComponentName(owner.type);}}return null;}function getCurrentFiberStackInDev(){{if(current===null){return '';}// Safe because if current fiber exists, we are reconciling,
// and it is guaranteed to be the work-in-progress version.
return getStackByFiberInDevAndProd(current);}}function resetCurrentFiber(){{ReactDebugCurrentFrame.getCurrentStack=null;current=null;isRendering=false;}}function setCurrentFiber(fiber){{ReactDebugCurrentFrame.getCurrentStack=getCurrentFiberStackInDev;current=fiber;isRendering=false;}}function setIsRendering(rendering){{isRendering=rendering;}}function getIsRendering(){{return isRendering;}}// Flow does not allow string concatenation of most non-string types. To work
// around this limitation, we use an opaque type that can only be obtained by
// passing the value through getToStringValue first.
function toString(value){return ''+value;}function getToStringValue(value){switch(typeof value){case'boolean':case'number':case'object':case'string':case'undefined':return value;default:// function, symbol are assigned as empty strings
return '';}}var hasReadOnlyValue={button:true,checkbox:true,image:true,hidden:true,radio:true,reset:true,submit:true};function checkControlledValueProps(tagName,props){{if(!(hasReadOnlyValue[props.type]||props.onChange||props.onInput||props.readOnly||props.disabled||props.value==null)){error('You provided a `value` prop to a form field without an '+'`onChange` handler. This will render a read-only field. If '+'the field should be mutable use `defaultValue`. Otherwise, '+'set either `onChange` or `readOnly`.');}if(!(props.onChange||props.readOnly||props.disabled||props.checked==null)){error('You provided a `checked` prop to a form field without an '+'`onChange` handler. This will render a read-only field. If '+'the field should be mutable use `defaultChecked`. Otherwise, '+'set either `onChange` or `readOnly`.');}}}function isCheckable(elem){var type=elem.type;var nodeName=elem.nodeName;return nodeName&&nodeName.toLowerCase()==='input'&&(type==='checkbox'||type==='radio');}function getTracker(node){return node._valueTracker;}function detachTracker(node){node._valueTracker=null;}function getValueFromNode(node){var value='';if(!node){return value;}if(isCheckable(node)){value=node.checked?'true':'false';}else {value=node.value;}return value;}function trackValueOnNode(node){var valueField=isCheckable(node)?'checked':'value';var descriptor=Object.getOwnPropertyDescriptor(node.constructor.prototype,valueField);var currentValue=''+node[valueField];// if someone has already defined a value or Safari, then bail
// and don't track value will cause over reporting of changes,
// but it's better then a hard failure
// (needed for certain tests that spyOn input values and Safari)
if(node.hasOwnProperty(valueField)||typeof descriptor==='undefined'||typeof descriptor.get!=='function'||typeof descriptor.set!=='function'){return;}var get=descriptor.get,set=descriptor.set;Object.defineProperty(node,valueField,{configurable:true,get:function(){return get.call(this);},set:function(value){currentValue=''+value;set.call(this,value);}});// We could've passed this the first time
// but it triggers a bug in IE11 and Edge 14/15.
// Calling defineProperty() again should be equivalent.
// https://github.com/facebook/react/issues/11768
Object.defineProperty(node,valueField,{enumerable:descriptor.enumerable});var tracker={getValue:function(){return currentValue;},setValue:function(value){currentValue=''+value;},stopTracking:function(){detachTracker(node);delete node[valueField];}};return tracker;}function track(node){if(getTracker(node)){return;}// TODO: Once it's just Fiber we can move this to node._wrapperState
node._valueTracker=trackValueOnNode(node);}function updateValueIfChanged(node){if(!node){return false;}var tracker=getTracker(node);// if there is no tracker at this point it's unlikely
// that trying again will succeed
if(!tracker){return true;}var lastValue=tracker.getValue();var nextValue=getValueFromNode(node);if(nextValue!==lastValue){tracker.setValue(nextValue);return true;}return false;}function getActiveElement(doc){doc=doc||(typeof document!=='undefined'?document:undefined);if(typeof doc==='undefined'){return null;}try{return doc.activeElement||doc.body;}catch(e){return doc.body;}}var didWarnValueDefaultValue=false;var didWarnCheckedDefaultChecked=false;var didWarnControlledToUncontrolled=false;var didWarnUncontrolledToControlled=false;function isControlled(props){var usesChecked=props.type==='checkbox'||props.type==='radio';return usesChecked?props.checked!=null:props.value!=null;}/**
* Implements an <input> host component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/function getHostProps(element,props){var node=element;var checked=props.checked;var hostProps=_assign({},props,{defaultChecked:undefined,defaultValue:undefined,value:undefined,checked:checked!=null?checked:node._wrapperState.initialChecked});return hostProps;}function initWrapperState(element,props){{checkControlledValueProps('input',props);if(props.checked!==undefined&&props.defaultChecked!==undefined&&!didWarnCheckedDefaultChecked){error('%s contains an input of type %s with both checked and defaultChecked props. '+'Input elements must be either controlled or uncontrolled '+'(specify either the checked prop, or the defaultChecked prop, but not '+'both). Decide between using a controlled or uncontrolled input '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components',getCurrentFiberOwnerNameInDevOrNull()||'A component',props.type);didWarnCheckedDefaultChecked=true;}if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnValueDefaultValue){error('%s contains an input of type %s with both value and defaultValue props. '+'Input elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled input '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components',getCurrentFiberOwnerNameInDevOrNull()||'A component',props.type);didWarnValueDefaultValue=true;}}var node=element;var defaultValue=props.defaultValue==null?'':props.defaultValue;node._wrapperState={initialChecked:props.checked!=null?props.checked:props.defaultChecked,initialValue:getToStringValue(props.value!=null?props.value:defaultValue),controlled:isControlled(props)};}function updateChecked(element,props){var node=element;var checked=props.checked;if(checked!=null){setValueForProperty(node,'checked',checked,false);}}function updateWrapper(element,props){var node=element;{var controlled=isControlled(props);if(!node._wrapperState.controlled&&controlled&&!didWarnUncontrolledToControlled){error('A component is changing an uncontrolled input to be controlled. '+'This is likely caused by the value changing from undefined to '+'a defined value, which should not happen. '+'Decide between using a controlled or uncontrolled input '+'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');didWarnUncontrolledToControlled=true;}if(node._wrapperState.controlled&&!controlled&&!didWarnControlledToUncontrolled){error('A component is changing a controlled input to be uncontrolled. '+'This is likely caused by the value changing from a defined to '+'undefined, which should not happen. '+'Decide between using a controlled or uncontrolled input '+'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');didWarnControlledToUncontrolled=true;}}updateChecked(element,props);var value=getToStringValue(props.value);var type=props.type;if(value!=null){if(type==='number'){if(value===0&&node.value===''||// We explicitly want to coerce to number here if possible.
// eslint-disable-next-line
node.value!=value){node.value=toString(value);}}else if(node.value!==toString(value)){node.value=toString(value);}}else if(type==='submit'||type==='reset'){// Submit/reset inputs need the attribute removed completely to avoid
// blank-text buttons.
node.removeAttribute('value');return;}{// When syncing the value attribute, the value comes from a cascade of
// properties:
// 1. The value React property
// 2. The defaultValue React property
// 3. Otherwise there should be no change
if(props.hasOwnProperty('value')){setDefaultValue(node,props.type,value);}else if(props.hasOwnProperty('defaultValue')){setDefaultValue(node,props.type,getToStringValue(props.defaultValue));}}{// When syncing the checked attribute, it only changes when it needs
// to be removed, such as transitioning from a checkbox into a text input
if(props.checked==null&&props.defaultChecked!=null){node.defaultChecked=!!props.defaultChecked;}}}function postMountWrapper(element,props,isHydrating){var node=element;// Do not assign value if it is already set. This prevents user text input
// from being lost during SSR hydration.
if(props.hasOwnProperty('value')||props.hasOwnProperty('defaultValue')){var type=props.type;var isButton=type==='submit'||type==='reset';// Avoid setting value attribute on submit/reset inputs as it overrides the
// default value provided by the browser. See: #12872
if(isButton&&(props.value===undefined||props.value===null)){return;}var initialValue=toString(node._wrapperState.initialValue);// Do not assign value if it is already set. This prevents user text input
// from being lost during SSR hydration.
if(!isHydrating){{// When syncing the value attribute, the value property should use
// the wrapperState._initialValue property. This uses:
//
// 1. The value React property when present
// 2. The defaultValue React property when present
// 3. An empty string
if(initialValue!==node.value){node.value=initialValue;}}}{// Otherwise, the value attribute is synchronized to the property,
// so we assign defaultValue to the same thing as the value property
// assignment step above.
node.defaultValue=initialValue;}}// Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
// this is needed to work around a chrome bug where setting defaultChecked
// will sometimes influence the value of checked (even after detachment).
// Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
// We need to temporarily unset name to avoid disrupting radio button groups.
var name=node.name;if(name!==''){node.name='';}{// When syncing the checked attribute, both the checked property and
// attribute are assigned at the same time using defaultChecked. This uses:
//
// 1. The checked React property when present
// 2. The defaultChecked React property when present
// 3. Otherwise, false
node.defaultChecked=!node.defaultChecked;node.defaultChecked=!!node._wrapperState.initialChecked;}if(name!==''){node.name=name;}}function restoreControlledState(element,props){var node=element;updateWrapper(node,props);updateNamedCousins(node,props);}function updateNamedCousins(rootNode,props){var name=props.name;if(props.type==='radio'&&name!=null){var queryRoot=rootNode;while(queryRoot.parentNode){queryRoot=queryRoot.parentNode;}// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form. It might not even be in the
// document. Let's just use the local `querySelectorAll` to ensure we don't
// miss anything.
var group=queryRoot.querySelectorAll('input[name='+JSON.stringify(''+name)+'][type="radio"]');for(var i=0;i<group.length;i++){var otherNode=group[i];if(otherNode===rootNode||otherNode.form!==rootNode.form){continue;}// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherProps=getFiberCurrentPropsFromNode(otherNode);if(!otherProps){{throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");}}// We need update the tracked value on the named cousin since the value
// was changed but the input saw no event or value set
updateValueIfChanged(otherNode);// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
updateWrapper(otherNode,otherProps);}}}// In Chrome, assigning defaultValue to certain input types triggers input validation.
// For number inputs, the display value loses trailing decimal points. For email inputs,
// Chrome raises "The specified value <x> is not a valid email address".
//
// Here we check to see if the defaultValue has actually changed, avoiding these problems
// when the user is inputting text
//
// https://github.com/facebook/react/issues/7253
function setDefaultValue(node,type,value){if(// Focused number inputs synchronize on blur. See ChangeEventPlugin.js
type!=='number'||getActiveElement(node.ownerDocument)!==node){if(value==null){node.defaultValue=toString(node._wrapperState.initialValue);}else if(node.defaultValue!==toString(value)){node.defaultValue=toString(value);}}}var didWarnSelectedSetOnOption=false;var didWarnInvalidChild=false;function flattenChildren(children){var content='';// Flatten children. We'll warn if they are invalid
// during validateProps() which runs for hydration too.
// Note that this would throw on non-element objects.
// Elements are stringified (which is normally irrelevant
// but matters for <fbt>).
React.Children.forEach(children,function(child){if(child==null){return;}content+=child;// Note: we don't warn about invalid children here.
// Instead, this is done separately below so that
// it happens during the hydration code path too.
});return content;}/**
* Implements an <option> host component that warns when `selected` is set.
*/function validateProps(element,props){{// This mirrors the code path above, but runs for hydration too.
// Warn about invalid children here so that client and hydration are consistent.
// TODO: this seems like it could cause a DEV-only throw for hydration
// if children contains a non-element object. We should try to avoid that.
if(typeof props.children==='object'&&props.children!==null){React.Children.forEach(props.children,function(child){if(child==null){return;}if(typeof child==='string'||typeof child==='number'){return;}if(typeof child.type!=='string'){return;}if(!didWarnInvalidChild){didWarnInvalidChild=true;error('Only strings and numbers are supported as <option> children.');}});}// TODO: Remove support for `selected` in <option>.
if(props.selected!=null&&!didWarnSelectedSetOnOption){error('Use the `defaultValue` or `value` props on <select> instead of '+'setting `selected` on <option>.');didWarnSelectedSetOnOption=true;}}}function postMountWrapper$1(element,props){// value="" should make a value attribute (#6219)
if(props.value!=null){element.setAttribute('value',toString(getToStringValue(props.value)));}}function getHostProps$1(element,props){var hostProps=_assign({children:undefined},props);var content=flattenChildren(props.children);if(content){hostProps.children=content;}return hostProps;}var didWarnValueDefaultValue$1;{didWarnValueDefaultValue$1=false;}function getDeclarationErrorAddendum(){var ownerName=getCurrentFiberOwnerNameInDevOrNull();if(ownerName){return '\n\nCheck the render method of `'+ownerName+'`.';}return '';}var valuePropNames=['value','defaultValue'];/**
* Validation function for `value` and `defaultValue`.
*/function checkSelectPropTypes(props){{checkControlledValueProps('select',props);for(var i=0;i<valuePropNames.length;i++){var propName=valuePropNames[i];if(props[propName]==null){continue;}var isArray=Array.isArray(props[propName]);if(props.multiple&&!isArray){error('The `%s` prop supplied to <select> must be an array if '+'`multiple` is true.%s',propName,getDeclarationErrorAddendum());}else if(!props.multiple&&isArray){error('The `%s` prop supplied to <select> must be a scalar '+'value if `multiple` is false.%s',propName,getDeclarationErrorAddendum());}}}}function updateOptions(node,multiple,propValue,setDefaultSelected){var options=node.options;if(multiple){var selectedValues=propValue;var selectedValue={};for(var i=0;i<selectedValues.length;i++){// Prefix to avoid chaos with special keys.
selectedValue['$'+selectedValues[i]]=true;}for(var _i=0;_i<options.length;_i++){var selected=selectedValue.hasOwnProperty('$'+options[_i].value);if(options[_i].selected!==selected){options[_i].selected=selected;}if(selected&&setDefaultSelected){options[_i].defaultSelected=true;}}}else {// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
var _selectedValue=toString(getToStringValue(propValue));var defaultSelected=null;for(var _i2=0;_i2<options.length;_i2++){if(options[_i2].value===_selectedValue){options[_i2].selected=true;if(setDefaultSelected){options[_i2].defaultSelected=true;}return;}if(defaultSelected===null&&!options[_i2].disabled){defaultSelected=options[_i2];}}if(defaultSelected!==null){defaultSelected.selected=true;}}}/**
* Implements a <select> host component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/function getHostProps$2(element,props){return _assign({},props,{value:undefined});}function initWrapperState$1(element,props){var node=element;{checkSelectPropTypes(props);}node._wrapperState={wasMultiple:!!props.multiple};{if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnValueDefaultValue$1){error('Select elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled select '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components');didWarnValueDefaultValue$1=true;}}}function postMountWrapper$2(element,props){var node=element;node.multiple=!!props.multiple;var value=props.value;if(value!=null){updateOptions(node,!!props.multiple,value,false);}else if(props.defaultValue!=null){updateOptions(node,!!props.multiple,props.defaultValue,true);}}function postUpdateWrapper(element,props){var node=element;var wasMultiple=node._wrapperState.wasMultiple;node._wrapperState.wasMultiple=!!props.multiple;var value=props.value;if(value!=null){updateOptions(node,!!props.multiple,value,false);}else if(wasMultiple!==!!props.multiple){// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if(props.defaultValue!=null){updateOptions(node,!!props.multiple,props.defaultValue,true);}else {// Revert the select back to its default unselected state.
updateOptions(node,!!props.multiple,props.multiple?[]:'',false);}}}function restoreControlledState$1(element,props){var node=element;var value=props.value;if(value!=null){updateOptions(node,!!props.multiple,value,false);}}var didWarnValDefaultVal=false;/**
* Implements a <textarea> host component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/function getHostProps$3(element,props){var node=element;if(!(props.dangerouslySetInnerHTML==null)){{throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");}}// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated. We could add a check in setTextContent
// to only set the value if/when the value differs from the node value (which would
// completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
// solution. The value can be a boolean or object so that's why it's forced
// to be a string.
var hostProps=_assign({},props,{value:undefined,defaultValue:undefined,children:toString(node._wrapperState.initialValue)});return hostProps;}function initWrapperState$2(element,props){var node=element;{checkControlledValueProps('textarea',props);if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnValDefaultVal){error('%s contains a textarea with both value and defaultValue props. '+'Textarea elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled textarea '+'and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components',getCurrentFiberOwnerNameInDevOrNull()||'A component');didWarnValDefaultVal=true;}}var initialValue=props.value;// Only bother fetching default value if we're going to use it
if(initialValue==null){var children=props.children,defaultValue=props.defaultValue;if(children!=null){{error('Use the `defaultValue` or `value` props instead of setting '+'children on <textarea>.');}{if(!(defaultValue==null)){{throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");}}if(Array.isArray(children)){if(!(children.length<=1)){{throw Error("<textarea> can only have at most one child.");}}children=children[0];}defaultValue=children;}}if(defaultValue==null){defaultValue='';}initialValue=defaultValue;}node._wrapperState={initialValue:getToStringValue(initialValue)};}function updateWrapper$1(element,props){var node=element;var value=getToStringValue(props.value);var defaultValue=getToStringValue(props.defaultValue);if(value!=null){// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
var newValue=toString(value);// To avoid side effects (such as losing text selection), only set value if changed
if(newValue!==node.value){node.value=newValue;}if(props.defaultValue==null&&node.defaultValue!==newValue){node.defaultValue=newValue;}}if(defaultValue!=null){node.defaultValue=toString(defaultValue);}}function postMountWrapper$3(element,props){var node=element;// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var textContent=node.textContent;// Only set node.value if textContent is equal to the expected
// initial value. In IE10/IE11 there is a bug where the placeholder attribute
// will populate textContent as well.
// https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
if(textContent===node._wrapperState.initialValue){if(textContent!==''&&textContent!==null){node.value=textContent;}}}function restoreControlledState$2(element,props){// DOM component is still mounted; update
updateWrapper$1(element,props);}var HTML_NAMESPACE='http://www.w3.org/1999/xhtml';var MATH_NAMESPACE='http://www.w3.org/1998/Math/MathML';var SVG_NAMESPACE='http://www.w3.org/2000/svg';var Namespaces={html:HTML_NAMESPACE,mathml:MATH_NAMESPACE,svg:SVG_NAMESPACE};// Assumes there is no parent namespace.
function getIntrinsicNamespace(type){switch(type){case'svg':return SVG_NAMESPACE;case'math':return MATH_NAMESPACE;default:return HTML_NAMESPACE;}}function getChildNamespace(parentNamespace,type){if(parentNamespace==null||parentNamespace===HTML_NAMESPACE){// No (or default) parent namespace: potential entry point.
return getIntrinsicNamespace(type);}if(parentNamespace===SVG_NAMESPACE&&type==='foreignObject'){// We're leaving SVG.
return HTML_NAMESPACE;}// By default, pass namespace below.
return parentNamespace;}/* globals MSApp */ /**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/var createMicrosoftUnsafeLocalFunction=function(func){if(typeof MSApp!=='undefined'&&MSApp.execUnsafeLocalFunction){return function(arg0,arg1,arg2,arg3){MSApp.execUnsafeLocalFunction(function(){return func(arg0,arg1,arg2,arg3);});};}else {return func;}};var reusableSVGContainer;/**
* Set the innerHTML property of a node
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/var setInnerHTML=createMicrosoftUnsafeLocalFunction(function(node,html){if(node.namespaceURI===Namespaces.svg){if(!('innerHTML'in node)){// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
reusableSVGContainer=reusableSVGContainer||document.createElement('div');reusableSVGContainer.innerHTML='<svg>'+html.valueOf().toString()+'</svg>';var svgNode=reusableSVGContainer.firstChild;while(node.firstChild){node.removeChild(node.firstChild);}while(svgNode.firstChild){node.appendChild(svgNode.firstChild);}return;}}node.innerHTML=html;});/**
* HTML nodeType values that represent the type of the node
*/var ELEMENT_NODE=1;var TEXT_NODE=3;var COMMENT_NODE=8;var DOCUMENT_NODE=9;var DOCUMENT_FRAGMENT_NODE=11;/**
* Set the textContent property of a node. For text updates, it's faster
* to set the `nodeValue` of the Text node directly instead of using
* `.textContent` which will remove the existing node and create a new one.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/var setTextContent=function(node,text){if(text){var firstChild=node.firstChild;if(firstChild&&firstChild===node.lastChild&&firstChild.nodeType===TEXT_NODE){firstChild.nodeValue=text;return;}}node.textContent=text;};// List derived from Gecko source code:
// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
var shorthandToLonghand={animation:['animationDelay','animationDirection','animationDuration','animationFillMode','animationIterationCount','animationName','animationPlayState','animationTimingFunction'],background:['backgroundAttachment','backgroundClip','backgroundColor','backgroundImage','backgroundOrigin','backgroundPositionX','backgroundPositionY','backgroundRepeat','backgroundSize'],backgroundPosition:['backgroundPositionX','backgroundPositionY'],border:['borderBottomColor','borderBottomStyle','borderBottomWidth','borderImageOutset','borderImageRepeat','borderImageSlice','borderImageSource','borderImageWidth','borderLeftColor','borderLeftStyle','borderLeftWidth','borderRightColor','borderRightStyle','borderRightWidth','borderTopColor','borderTopStyle','borderTopWidth'],borderBlockEnd:['borderBlockEndColor','borderBlockEndStyle','borderBlockEndWidth'],borderBlockStart:['borderBlockStartColor','borderBlockStartStyle','borderBlockStartWidth'],borderBottom:['borderBottomColor','borderBottomStyle','borderBottomWidth'],borderColor:['borderBottomColor','borderLeftColor','borderRightColor','borderTopColor'],borderImage:['borderImageOutset','borderImageRepeat','borderImageSlice','borderImageSource','borderImageWidth'],borderInlineEnd:['borderInlineEndColor','borderInlineEndStyle','borderInlineEndWidth'],borderInlineStart:['borderInlineStartColor','borderInlineStartStyle','borderInlineStartWidth'],borderLeft:['borderLeftColor','borderLeftStyle','borderLeftWidth'],borderRadius:['borderBottomLeftRadius','borderBottomRightRadius','borderTopLeftRadius','borderTopRightRadius'],borderRight:['borderRightColor','borderRightStyle','borderRightWidth'],borderStyle:['borderBottomStyle','borderLeftStyle','borderRightStyle','borderTopStyle'],borderTop:['borderTopColor','borderTopStyle','borderTopWidth'],borderWidth:['borderBottomWidth','borderLeftWidth','borderRightWidth','borderTopWidth'],columnRule:['columnRuleColor','columnRuleStyle','columnRuleWidth'],columns:['columnCount','columnWidth'],flex:['flexBasis','flexGrow','flexShrink'],flexFlow:['flexDirection','flexWrap'],font:['fontFamily','fontFeatureSettings','fontKerning','fontLanguageOverride','fontSize','fontSizeAdjust','fontStretch','fontStyle','fontVariant','fontVariantAlternates','fontVariantCaps','fontVariantEastAsian','fontVariantLigatures','fontVariantNumeric','fontVariantPosition','fontWeight','lineHeight'],fontVariant:['fontVariantAlternates','fontVariantCaps','fontVariantEastAsian','fontVariantLigatures','fontVariantNumeric','fontVariantPosition'],gap:['columnGap','rowGap'],grid:['gridAutoColumns','gridAutoFlow','gridAutoRows','gridTemplateAreas','gridTemplateColumns','gridTemplateRows'],gridArea:['gridColumnEnd','gridColumnStart','gridRowEnd','gridRowStart'],gridColumn:['gridColumnEnd','gridColumnStart'],gridColumnGap:['columnGap'],gridGap:['columnGap','rowGap'],gridRow:['gridRowEnd','gridRowStart'],gridRowGap:['rowGap'],gridTemplate:['gridTemplateAreas','gridTemplateColumns','gridTemplateRows'],listStyle:['listStyleImage','listStylePosition','listStyleType'],margin:['marginBottom','marginLeft','marginRight','marginTop'],marker:['markerEnd','markerMid','markerStart'],mask:['maskClip','maskComposite','maskImage','maskMode','maskOrigin','maskPositionX','maskPositionY','maskRepeat','maskSize'],maskPosition:['maskPositionX','maskPositionY'],outline:['outlineColor','outlineStyle','outlineWidth'],overflow:['overflowX','overflowY'],padding:['paddingBottom','paddingLeft','paddingRight','paddingTop'],placeContent:['alignContent','justifyContent'],placeItems:['alignItems','justifyItems'],placeSelf:['alignSelf','justifySelf'],textDecoration:['textDecorationColor','textDecorationLine','textDecorationStyle'],textEmphasis:['textEmphasisColor','textEmphasisStyle'],transition:['transitionDelay','transitionDuration','transitionProperty','transitionTimingFunction'],wordWrap:['overflowWrap']};/**
* CSS properties which accept numbers but are not in units of "px".
*/var isUnitlessNumber={animationIterationCount:true,borderImageOutset:true,borderImageSlice:true,borderImageWidth:true,boxFlex:true,boxFlexGroup:true,boxOrdinalGroup:true,columnCount:true,columns:true,flex:true,flexGrow:true,flexPositive:true,flexShrink:true,flexNegative:true,flexOrder:true,gridArea:true,gridRow:true,gridRowEnd:true,gridRowSpan:true,gridRowStart:true,gridColumn:true,gridColumnEnd:true,gridColumnSpan:true,gridColumnStart:true,fontWeight:true,lineClamp:true,lineHeight:true,opacity:true,order:true,orphans:true,tabSize:true,widows:true,zIndex:true,zoom:true,// SVG-related properties
fillOpacity:true,floodOpacity:true,stopOpacity:true,strokeDasharray:true,strokeDashoffset:true,strokeMiterlimit:true,strokeOpacity:true,strokeWidth:true};/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/function prefixKey(prefix,key){return prefix+key.charAt(0).toUpperCase()+key.substring(1);}/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/var prefixes=['Webkit','ms','Moz','O'];// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function(prop){prefixes.forEach(function(prefix){isUnitlessNumber[prefixKey(prefix,prop)]=isUnitlessNumber[prop];});});/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/function dangerousStyleValue(name,value,isCustomProperty){// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty=value==null||typeof value==='boolean'||value==='';if(isEmpty){return '';}if(!isCustomProperty&&typeof value==='number'&&value!==0&&!(isUnitlessNumber.hasOwnProperty(name)&&isUnitlessNumber[name])){return value+'px';// Presumes implicit 'px' suffix for unitless numbers
}return (''+value).trim();}var uppercasePattern=/([A-Z])/g;var msPattern=/^ms-/;/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*/function hyphenateStyleName(name){return name.replace(uppercasePattern,'-$1').toLowerCase().replace(msPattern,'-ms-');}var warnValidStyle=function(){};{// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern=/^(?:webkit|moz|o)[A-Z]/;var msPattern$1=/^-ms-/;var hyphenPattern=/-(.)/g;// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern=/;\s*$/;var warnedStyleNames={};var warnedStyleValues={};var warnedForNaNValue=false;var warnedForInfinityValue=false;var camelize=function(string){return string.replace(hyphenPattern,function(_,character){return character.toUpperCase();});};var warnHyphenatedStyleName=function(name){if(warnedStyleNames.hasOwnProperty(name)&&warnedStyleNames[name]){return;}warnedStyleNames[name]=true;error('Unsupported style property %s. Did you mean %s?',name,// As Andi Smith suggests
// (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
// is converted to lowercase `ms`.
camelize(name.replace(msPattern$1,'ms-')));};var warnBadVendoredStyleName=function(name){if(warnedStyleNames.hasOwnProperty(name)&&warnedStyleNames[name]){return;}warnedStyleNames[name]=true;error('Unsupported vendor-prefixed style property %s. Did you mean %s?',name,name.charAt(0).toUpperCase()+name.slice(1));};var warnStyleValueWithSemicolon=function(name,value){if(warnedStyleValues.hasOwnProperty(value)&&warnedStyleValues[value]){return;}warnedStyleValues[value]=true;error("Style property values shouldn't contain a semicolon. "+'Try "%s: %s" instead.',name,value.replace(badStyleValueWithSemicolonPattern,''));};var warnStyleValueIsNaN=function(name,value){if(warnedForNaNValue){return;}warnedForNaNValue=true;error('`NaN` is an invalid value for the `%s` css style property.',name);};var warnStyleValueIsInfinity=function(name,value){if(warnedForInfinityValue){return;}warnedForInfinityValue=true;error('`Infinity` is an invalid value for the `%s` css style property.',name);};warnValidStyle=function(name,value){if(name.indexOf('-')>-1){warnHyphenatedStyleName(name);}else if(badVendoredStyleNamePattern.test(name)){warnBadVendoredStyleName(name);}else if(badStyleValueWithSemicolonPattern.test(value)){warnStyleValueWithSemicolon(name,value);}if(typeof value==='number'){if(isNaN(value)){warnStyleValueIsNaN(name,value);}else if(!isFinite(value)){warnStyleValueIsInfinity(name,value);}}};}var warnValidStyle$1=warnValidStyle;/**
* Operations for dealing with CSS properties.
*/ /**
* This creates a string that is expected to be equivalent to the style
* attribute generated by server-side rendering. It by-passes warnings and
* security checks so it's not safe to use this value for anything other than
* comparison. It is only used in DEV for SSR validation.
*/function createDangerousStringForStyles(styles){{var serialized='';var delimiter='';for(var styleName in styles){if(!styles.hasOwnProperty(styleName)){continue;}var styleValue=styles[styleName];if(styleValue!=null){var isCustomProperty=styleName.indexOf('--')===0;serialized+=delimiter+(isCustomProperty?styleName:hyphenateStyleName(styleName))+':';serialized+=dangerousStyleValue(styleName,styleValue,isCustomProperty);delimiter=';';}}return serialized||null;}}/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/function setValueForStyles(node,styles){var style=node.style;for(var styleName in styles){if(!styles.hasOwnProperty(styleName)){continue;}var isCustomProperty=styleName.indexOf('--')===0;{if(!isCustomProperty){warnValidStyle$1(styleName,styles[styleName]);}}var styleValue=dangerousStyleValue(styleName,styles[styleName],isCustomProperty);if(styleName==='float'){styleName='cssFloat';}if(isCustomProperty){style.setProperty(styleName,styleValue);}else {style[styleName]=styleValue;}}}function isValueEmpty(value){return value==null||typeof value==='boolean'||value==='';}/**
* Given {color: 'red', overflow: 'hidden'} returns {
* color: 'color',
* overflowX: 'overflow',
* overflowY: 'overflow',
* }. This can be read as "the overflowY property was set by the overflow
* shorthand". That is, the values are the property that each was derived from.
*/function expandShorthandMap(styles){var expanded={};for(var key in styles){var longhands=shorthandToLonghand[key]||[key];for(var i=0;i<longhands.length;i++){expanded[longhands[i]]=key;}}return expanded;}/**
* When mixing shorthand and longhand property names, we warn during updates if
* we expect an incorrect result to occur. In particular, we warn for:
*
* Updating a shorthand property (longhand gets overwritten):
* {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
* becomes .style.font = 'baz'
* Removing a shorthand property (longhand gets lost too):
* {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
* becomes .style.font = ''
* Removing a longhand property (should revert to shorthand; doesn't):
* {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
* becomes .style.fontVariant = ''
*/function validateShorthandPropertyCollisionInDev(styleUpdates,nextStyles){{if(!nextStyles){return;}var expandedUpdates=expandShorthandMap(styleUpdates);var expandedStyles=expandShorthandMap(nextStyles);var warnedAbout={};for(var key in expandedUpdates){var originalKey=expandedUpdates[key];var correctOriginalKey=expandedStyles[key];if(correctOriginalKey&&originalKey!==correctOriginalKey){var warningKey=originalKey+','+correctOriginalKey;if(warnedAbout[warningKey]){continue;}warnedAbout[warningKey]=true;error('%s a style property during rerender (%s) when a '+'conflicting property is set (%s) can lead to styling bugs. To '+"avoid this, don't mix shorthand and non-shorthand properties "+'for the same value; instead, replace the shorthand with '+'separate values.',isValueEmpty(styleUpdates[originalKey])?'Removing':'Updating',originalKey,correctOriginalKey);}}}}// For HTML, certain tags should omit their close tag. We keep a list for
// those special-case tags.
var omittedCloseTags={area:true,base:true,br:true,col:true,embed:true,hr:true,img:true,input:true,keygen:true,link:true,meta:true,param:true,source:true,track:true,wbr:true// NOTE: menuitem's close tag should be omitted, but that causes problems.
};// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags=_assign({menuitem:true},omittedCloseTags);var HTML='__html';function assertValidProps(tag,props){if(!props){return;}// Note the use of `==` which checks for null or undefined.
if(voidElementTags[tag]){if(!(props.children==null&&props.dangerouslySetInnerHTML==null)){{throw Error(tag+" is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");}}}if(props.dangerouslySetInnerHTML!=null){if(!(props.children==null)){{throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");}}if(!(typeof props.dangerouslySetInnerHTML==='object'&&HTML in props.dangerouslySetInnerHTML)){{throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");}}}{if(!props.suppressContentEditableWarning&&props.contentEditable&&props.children!=null){error('A component is `contentEditable` and contains `children` managed by '+'React. It is now your responsibility to guarantee that none of '+'those nodes are unexpectedly modified or duplicated. This is '+'probably not intentional.');}}if(!(props.style==null||typeof props.style==='object')){{throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");}}}function isCustomComponent(tagName,props){if(tagName.indexOf('-')===-1){return typeof props.is==='string';}switch(tagName){// These are reserved SVG and MathML elements.
// We don't mind this list too much because we expect it to never grow.
// The alternative is to track the namespace in a few places which is convoluted.
// https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
case'annotation-xml':case'color-profile':case'font-face':case'font-face-src':case'font-face-uri':case'font-face-format':case'font-face-name':case'missing-glyph':return false;default:return true;}}// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames={// HTML
accept:'accept',acceptcharset:'acceptCharset','accept-charset':'acceptCharset',accesskey:'accessKey',action:'action',allowfullscreen:'allowFullScreen',alt:'alt',as:'as',async:'async',autocapitalize:'autoCapitalize',autocomplete:'autoComplete',autocorrect:'autoCorrect',autofocus:'autoFocus',autoplay:'autoPlay',autosave:'autoSave',capture:'capture',cellpadding:'cellPadding',cellspacing:'cellSpacing',challenge:'challenge',charset:'charSet',checked:'checked',children:'children',cite:'cite',class:'className',classid:'classID',classname:'className',cols:'cols',colspan:'colSpan',content:'content',contenteditable:'contentEditable',contextmenu:'contextMenu',controls:'controls',controlslist:'controlsList',coords:'coords',crossorigin:'crossOrigin',dangerouslysetinnerhtml:'dangerouslySetInnerHTML',data:'data',datetime:'dateTime',default:'default',defaultchecked:'defaultChecked',defaultvalue:'defaultValue',defer:'defer',dir:'dir',disabled:'disabled',disablepictureinpicture:'disablePictureInPicture',disableremoteplayback:'disableRemotePlayback',download:'download',draggable:'draggable',enctype:'encType',enterkeyhint:'enterKeyHint',for:'htmlFor',form:'form',formmethod:'formMethod',formaction:'formAction',formenctype:'formEncType',formnovalidate:'formNoValidate',formtarget:'formTarget',frameborder:'frameBorder',headers:'headers',height:'height',hidden:'hidden',high:'high',href:'href',hreflang:'hrefLang',htmlfor:'htmlFor',httpequiv:'httpEquiv','http-equiv':'httpEquiv',icon:'icon',id:'id',innerhtml:'innerHTML',inputmode:'inputMode',integrity:'integrity',is:'is',itemid:'itemID',itemprop:'itemProp',itemref:'itemRef',itemscope:'itemScope',itemtype:'itemType',keyparams:'keyParams',keytype:'keyType',kind:'kind',label:'label',lang:'lang',list:'list',loop:'loop',low:'low',manifest:'manifest',marginwidth:'marginWidth',marginheight:'marginHeight',max:'max',maxlength:'maxLength',media:'media',mediagroup:'mediaGroup',method:'method',min:'min',minlength:'minLength',multiple:'multiple',muted:'muted',name:'name',nomodule:'noModule',nonce:'nonce',novalidate:'noValidate',open:'open',optimum:'optimum',pattern:'pattern',placeholder:'placeholder',playsinline:'playsInline',poster:'poster',preload:'preload',profile:'profile',radiogroup:'radioGroup',readonly:'readOnly',referrerpolicy:'referrerPolicy',rel:'rel',required:'required',reversed:'reversed',role:'role',rows:'rows',rowspan:'rowSpan',sandbox:'sandbox',scope:'scope',scoped:'scoped',scrolling:'scrolling',seamless:'seamless',selected:'selected',shape:'shape',size:'size',sizes:'sizes',span:'span',spellcheck:'spellCheck',src:'src',srcdoc:'srcDoc',srclang:'srcLang',srcset:'srcSet',start:'start',step:'step',style:'style',summary:'summary',tabindex:'tabIndex',target:'target',title:'title',type:'type',usemap:'useMap',value:'value',width:'width',wmode:'wmode',wrap:'wrap',// SVG
about:'about',accentheight:'accentHeight','accent-height':'accentHeight',accumulate:'accumulate',additive:'additive',alignmentbaseline:'alignmentBaseline','alignment-baseline':'alignmentBaseline',allowreorder:'allowReorder',alphabetic:'alphabetic',amplitude:'amplitude',arabicform:'arabicForm','arabic-form':'arabicForm',ascent:'ascent',attributename:'attributeName',attributetype:'attributeType',autoreverse:'autoReverse',azimuth:'azimuth',basefrequency:'baseFrequency',baselineshift:'baselineShift','baseline-shift':'baselineShift',baseprofile:'baseProfile',bbox:'bbox',begin:'begin',bias:'bias',by:'by',calcmode:'calcMode',capheight:'capHeight','cap-height':'capHeight',clip:'clip',clippath:'clipPath','clip-path':'clipPath',clippathunits:'clipPathUnits',cliprule:'clipRule','clip-rule':'clipRule',color:'color',colorinterpolation:'colorInterpolation','color-interpolation':'colorInterpolation',colorinterpolationfilters:'colorInterpolationFilters','color-interpolation-filters':'colorInterpolationFilters',colorprofile:'colorProfile','color-profile':'colorProfile',colorrendering:'colorRendering','color-rendering':'colorRendering',contentscripttype:'contentScriptType',contentstyletype:'contentStyleType',cursor:'cursor',cx:'cx',cy:'cy',d:'d',datatype:'datatype',decelerate:'decelerate',descent:'descent',diffuseconstant:'diffuseConstant',direction:'direction',display:'display',divisor:'divisor',dominantbaseline:'dominantBaseline','dominant-baseline':'dominantBaseline',dur:'dur',dx:'dx',dy:'dy',edgemode:'edgeMode',elevation:'elevation',enablebackground:'enableBackground','enable-background':'enableBackground',end:'end',exponent:'exponent',externalresourcesrequired:'externalResourcesRequired',fill:'fill',fillopacity:'fillOpacity','fill-opacity':'fillOpacity',fillrule:'fillRule','fill-rule':'fillRule',filter:'filter',filterres:'filterRes',filterunits:'filterUnits',floodopacity:'floodOpacity','flood-opacity':'floodOpacity',floodcolor:'floodColor','flood-color':'floodColor',focusable:'focusable',fontfamily:'fontFamily','font-family':'fontFamily',fontsize:'fontSize','font-size':'fontSize',fontsizeadjust:'fontSizeAdjust','font-size-adjust':'fontSizeAdjust',fontstretch:'fontStretch','font-stretch':'fontStretch',fontstyle:'fontStyle','font-style':'fontStyle',fontvariant:'fontVariant','font-variant':'fontVariant',fontweight:'fontWeight','font-weight':'fontWeight',format:'format',from:'from',fx:'fx',fy:'fy',g1:'g1',g2:'g2',glyphname:'glyphName','glyph-name':'glyphName',glyphorientationhorizontal:'glyphOrientationHorizontal','glyph-orientation-horizontal':'glyphOrientationHorizontal',glyphorientationvertical:'glyphOrientationVertical','glyph-orientation-vertical':'glyphOrientationVertical',glyphref:'glyphRef',gradienttransform:'gradientTransform',gradientunits:'gradientUnits',hanging:'hanging',horizadvx:'horizAdvX','horiz-adv-x':'horizAdvX',horizoriginx:'horizOriginX','horiz-origin-x':'horizOriginX',ideographic:'ideographic',imagerendering:'imageRendering','image-rendering':'imageRendering',in2:'in2',in:'in',inlist:'inlist',intercept:'intercept',k1:'k1',k2:'k2',k3:'k3',k4:'k4',k:'k',kernelmatrix:'kernelMatrix',kernelunitlength:'kernelUnitLength',kerning:'kerning',keypoints:'keyPoints',keysplines:'keySplines',keytimes:'keyTimes',lengthadjust:'lengthAdjust',letterspacing:'letterSpacing','letter-spacing':'letterSpacing',lightingcolor:'lightingColor','lighting-color':'lightingColor',limitingconeangle:'limitingConeAngle',local:'local',markerend:'markerEnd','marker-end':'markerEnd',markerheight:'markerHeight',markermid:'markerMid','marker-mid':'markerMid',markerstart:'markerStart','marker-start':'markerStart',markerunits:'markerUnits',markerwidth:'markerWidth',mask:'mask',maskcontentunits:'maskContentUnits',maskunits:'maskUnits',mathematical:'mathematical',mode:'mode',numoctaves:'numOctaves',offset:'offset',opacity:'opacity',operator:'operator',order:'order',orient:'orient',orientation:'orientation',origin:'origin',overflow:'overflow',overlineposition:'overlinePosition','overline-position':'overlinePosition',overlinethickness:'overlineThickness','overli
'aria-details':0,'aria-disabled':0,// state
'aria-hidden':0,// state
'aria-invalid':0,// state
'aria-keyshortcuts':0,'aria-label':0,'aria-roledescription':0,// Widget Attributes
'aria-autocomplete':0,'aria-checked':0,'aria-expanded':0,'aria-haspopup':0,'aria-level':0,'aria-modal':0,'aria-multiline':0,'aria-multiselectable':0,'aria-orientation':0,'aria-placeholder':0,'aria-pressed':0,'aria-readonly':0,'aria-required':0,'aria-selected':0,'aria-sort':0,'aria-valuemax':0,'aria-valuemin':0,'aria-valuenow':0,'aria-valuetext':0,// Live Region Attributes
'aria-atomic':0,'aria-busy':0,'aria-live':0,'aria-relevant':0,// Drag-and-Drop Attributes
'aria-dropeffect':0,'aria-grabbed':0,// Relationship Attributes
'aria-activedescendant':0,'aria-colcount':0,'aria-colindex':0,'aria-colspan':0,'aria-controls':0,'aria-describedby':0,'aria-errormessage':0,'aria-flowto':0,'aria-labelledby':0,'aria-owns':0,'aria-posinset':0,'aria-rowcount':0,'aria-rowindex':0,'aria-rowspan':0,'aria-setsize':0};var warnedProperties={};var rARIA=new RegExp('^(aria)-['+ATTRIBUTE_NAME_CHAR+']*$');var rARIACamel=new RegExp('^(aria)[A-Z]['+ATTRIBUTE_NAME_CHAR+']*$');var hasOwnProperty$1=Object.prototype.hasOwnProperty;function validateProperty(tagName,name){{if(hasOwnProperty$1.call(warnedProperties,name)&&warnedProperties[name]){return true;}if(rARIACamel.test(name)){var ariaName='aria-'+name.slice(4).toLowerCase();var correctName=ariaProperties.hasOwnProperty(ariaName)?ariaName:null;// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if(correctName==null){error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.',name);warnedProperties[name]=true;return true;}// aria-* attributes should be lowercase; suggest the lowercase version.
if(name!==correctName){error('Invalid ARIA attribute `%s`. Did you mean `%s`?',name,correctName);warnedProperties[name]=true;return true;}}if(rARIA.test(name)){var lowerCasedName=name.toLowerCase();var standardName=ariaProperties.hasOwnProperty(lowerCasedName)?lowerCasedName:null;// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if(standardName==null){warnedProperties[name]=true;return false;}// aria-* attributes should be lowercase; suggest the lowercase version.
if(name!==standardName){error('Unknown ARIA attribute `%s`. Did you mean `%s`?',name,standardName);warnedProperties[name]=true;return true;}}}return true;}function warnInvalidARIAProps(type,props){{var invalidProps=[];for(var key in props){var isValid=validateProperty(type,key);if(!isValid){invalidProps.push(key);}}var unknownPropString=invalidProps.map(function(prop){return '`'+prop+'`';}).join(', ');if(invalidProps.length===1){error('Invalid aria prop %s on <%s> tag. '+'For details, see https://reactjs.org/link/invalid-aria-props',unknownPropString,type);}else if(invalidProps.length>1){error('Invalid aria props %s on <%s> tag. '+'For details, see https://reactjs.org/link/invalid-aria-props',unknownPropString,type);}}}function validateProperties(type,props){if(isCustomComponent(type,props)){return;}warnInvalidARIAProps(type,props);}var didWarnValueNull=false;function validateProperties$1(type,props){{if(type!=='input'&&type!=='textarea'&&type!=='select'){return;}if(props!=null&&props.value===null&&!didWarnValueNull){didWarnValueNull=true;if(type==='select'&&props.multiple){error('`value` prop on `%s` should not be null. '+'Consider using an empty array when `multiple` is set to `true` '+'to clear the component or `undefined` for uncontrolled components.',type);}else {error('`value` prop on `%s` should not be null. '+'Consider using an empty string to clear the component or `undefined` '+'for uncontrolled components.',type);}}}}var validateProperty$1=function(){};{var warnedProperties$1={};var _hasOwnProperty=Object.prototype.hasOwnProperty;var EVENT_NAME_REGEX=/^on./;var INVALID_EVENT_NAME_REGEX=/^on[^A-Z]/;var rARIA$1=new RegExp('^(aria)-['+ATTRIBUTE_NAME_CHAR+']*$');var rARIACamel$1=new RegExp('^(aria)[A-Z]['+ATTRIBUTE_NAME_CHAR+']*$');validateProperty$1=function(tagName,name,value,eventRegistry){if(_hasOwnProperty.call(warnedProperties$1,name)&&warnedProperties$1[name]){return true;}var lowerCasedName=name.toLowerCase();if(lowerCasedName==='onfocusin'||lowerCasedName==='onfocusout'){error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. '+'All React events are normalized to bubble, so onFocusIn and onFocusOut '+'are not needed/supported by React.');warnedProperties$1[name]=true;return true;}// We can't rely on the event system being injected on the server.
if(eventRegistry!=null){var registrationNameDependencies=eventRegistry.registrationNameDependencies,possibleRegistrationNames=eventRegistry.possibleRegistrationNames;if(registrationNameDependencies.hasOwnProperty(name)){return true;}var registrationName=possibleRegistrationNames.hasOwnProperty(lowerCasedName)?possibleRegistrationNames[lowerCasedName]:null;if(registrationName!=null){error('Invalid event handler property `%s`. Did you mean `%s`?',name,registrationName);warnedProperties$1[name]=true;return true;}if(EVENT_NAME_REGEX.test(name)){error('Unknown event handler property `%s`. It will be ignored.',name);warnedProperties$1[name]=true;return true;}}else if(EVENT_NAME_REGEX.test(name)){// If no event plugins have been injected, we are in a server environment.
// So we can't tell if the event name is correct for sure, but we can filter
// out known bad ones like `onclick`. We can't suggest a specific replacement though.
if(INVALID_EVENT_NAME_REGEX.test(name)){error('Invalid event handler property `%s`. '+'React events use the camelCase naming convention, for example `onClick`.',name);}warnedProperties$1[name]=true;return true;}// Let the ARIA attribute hook validate ARIA attributes
if(rARIA$1.test(name)||rARIACamel$1.test(name)){return true;}if(lowerCasedName==='innerhtml'){error('Directly setting property `innerHTML` is not permitted. '+'For more information, lookup documentation on `dangerouslySetInnerHTML`.');warnedProperties$1[name]=true;return true;}if(lowerCasedName==='aria'){error('The `aria` attribute is reserved for future use in React. '+'Pass individual `aria-` attributes instead.');warnedProperties$1[name]=true;return true;}if(lowerCasedName==='is'&&value!==null&&value!==undefined&&typeof value!=='string'){error('Received a `%s` for a string attribute `is`. If this is expected, cast '+'the value to a string.',typeof value);warnedProperties$1[name]=true;return true;}if(typeof value==='number'&&isNaN(value)){error('Received NaN for the `%s` attribute. If this is expected, cast '+'the value to a string.',name);warnedProperties$1[name]=true;return true;}var propertyInfo=getPropertyInfo(name);var isReserved=propertyInfo!==null&&propertyInfo.type===RESERVED;// Known attributes should match the casing specified in the property config.
if(possibleStandardNames.hasOwnProperty(lowerCasedName)){var standardName=possibleStandardNames[lowerCasedName];if(standardName!==name){error('Invalid DOM property `%s`. Did you mean `%s`?',name,standardName);warnedProperties$1[name]=true;return true;}}else if(!isReserved&&name!==lowerCasedName){// Unknown attributes should have lowercase casing since that's how they
// will be cased anyway with server rendering.
error('React does not recognize the `%s` prop on a DOM element. If you '+'intentionally want it to appear in the DOM as a custom '+'attribute, spell it as lowercase `%s` instead. '+'If you accidentally passed it from a parent component, remove '+'it from the DOM element.',name,lowerCasedName);warnedProperties$1[name]=true;return true;}if(typeof value==='boolean'&&shouldRemoveAttributeWithWarning(name,value,propertyInfo,false)){if(value){error('Received `%s` for a non-boolean attribute `%s`.\n\n'+'If you want to write it to the DOM, pass a string instead: '+'%s="%s" or %s={value.toString()}.',value,name,name,value,name);}else {error('Received `%s` for a non-boolean attribute `%s`.\n\n'+'If you want to write it to the DOM, pass a string instead: '+'%s="%s" or %s={value.toString()}.\n\n'+'If you used to conditionally omit it with %s={condition && value}, '+'pass %s={condition ? value : undefined} instead.',value,name,name,value,name,name,name);}warnedProperties$1[name]=true;return true;}// Now that we've validated casing, do not validate
// data types for reserved props
if(isReserved){return true;}// Warn when a known attribute is a bad type
if(shouldRemoveAttributeWithWarning(name,value,propertyInfo,false)){warnedProperties$1[name]=true;return false;}// Warn when passing the strings 'false' or 'true' into a boolean prop
if((value==='false'||value==='true')&&propertyInfo!==null&&propertyInfo.type===BOOLEAN){error('Received the string `%s` for the boolean attribute `%s`. '+'%s '+'Did you mean %s={%s}?',value,name,value==='false'?'The browser will interpret it as a truthy value.':'Although this works, it will not work as expected if you pass the string "false".',name,value);warnedProperties$1[name]=true;return true;}return true;};}var warnUnknownProperties=function(type,props,eventRegistry){{var unknownProps=[];for(var key in props){var isValid=validateProperty$1(type,key,props[key],eventRegistry);if(!isValid){unknownProps.push(key);}}var unknownPropString=unknownProps.map(function(prop){return '`'+prop+'`';}).join(', ');if(unknownProps.length===1){error('Invalid value for prop %s on <%s> tag. Either remove it from the element, '+'or pass a string or number value to keep it in the DOM. '+'For details, see https://reactjs.org/link/attribute-behavior ',unknownPropString,type);}else if(unknownProps.length>1){error('Invalid values for props %s on <%s> tag. Either remove them from the element, '+'or pass a string or number value to keep them in the DOM. '+'For details, see https://reactjs.org/link/attribute-behavior ',unknownPropString,type);}}};function validateProperties$2(type,props,eventRegistry){if(isCustomComponent(type,props)){return;}warnUnknownProperties(type,props,eventRegistry);}var IS_EVENT_HANDLE_NON_MANAGED_NODE=1;var IS_NON_DELEGATED=1<<1;var IS_CAPTURE_PHASE=1<<2;var IS_REPLAYED=1<<4;// set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
// we call willDeferLaterForLegacyFBSupport, thus not bailing out
// will result in endless cycles like an infinite loop.
// We also don't want to defer during event replaying.
var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS=IS_EVENT_HANDLE_NON_MANAGED_NODE|IS_NON_DELEGATED|IS_CAPTURE_PHASE;/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/function getEventTarget(nativeEvent){// Fallback to nativeEvent.srcElement for IE9
// https://github.com/facebook/react/issues/12506
var target=nativeEvent.target||nativeEvent.srcElement||window;// Normalize SVG <use> element events #4963
if(target.correspondingUseElement){target=target.correspondingUseElement;}// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType===TEXT_NODE?target.parentNode:target;}var restoreImpl=null;var restoreTarget=null;var restoreQueue=null;function restoreStateOfTarget(target){// We perform this translation at the end of the event loop so that we
// always receive the correct fiber here
var internalInstance=getInstanceFromNode(target);if(!internalInstance){// Unmounted
return;}if(!(typeof restoreImpl==='function')){{throw Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.");}}var stateNode=internalInstance.stateNode;// Guard against Fiber being unmounted.
if(stateNode){var _props=getFiberCurrentPropsFromNode(stateNode);restoreImpl(internalInstance.stateNode,internalInstance.type,_props);}}function setRestoreImplementation(impl){restoreImpl=impl;}function enqueueStateRestore(target){if(restoreTarget){if(restoreQueue){restoreQueue.push(target);}else {restoreQueue=[target];}}else {restoreTarget=target;}}function needsStateRestore(){return restoreTarget!==null||restoreQueue!==null;}function restoreStateIfNeeded(){if(!restoreTarget){return;}var target=restoreTarget;var queuedTargets=restoreQueue;restoreTarget=null;restoreQueue=null;restoreStateOfTarget(target);if(queuedTargets){for(var i=0;i<queuedTargets.length;i++){restoreStateOfTarget(queuedTargets[i]);}}}// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.
// Defaults
var batchedUpdatesImpl=function(fn,bookkeeping){return fn(bookkeeping);};var discreteUpdatesImpl=function(fn,a,b,c,d){return fn(a,b,c,d);};var flushDiscreteUpdatesImpl=function(){};var batchedEventUpdatesImpl=batchedUpdatesImpl;var isInsideEventHandler=false;var isBatchingEventUpdates=false;function finishEventHandler(){// Here we wait until all updates have propagated, which is important
// when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
// Then we restore state of any controlled component.
var controlledComponentsHavePendingUpdates=needsStateRestore();if(controlledComponentsHavePendingUpdates){// If a controlled event was fired, we may need to restore the state of
// the DOM node back to the controlled value. This is necessary when React
// bails out of the update without touching the DOM.
flushDiscreteUpdatesImpl();restoreStateIfNeeded();}}function batchedUpdates(fn,bookkeeping){if(isInsideEventHandler){// If we are currently inside another batch, we need to wait until it
// fully completes before restoring state.
return fn(bookkeeping);}isInsideEventHandler=true;try{return batchedUpdatesImpl(fn,bookkeeping);}finally{isInsideEventHandler=false;finishEventHandler();}}function batchedEventUpdates(fn,a,b){if(isBatchingEventUpdates){// If we are currently inside another batch, we need to wait until it
// fully completes before restoring state.
return fn(a,b);}isBatchingEventUpdates=true;try{return batchedEventUpdatesImpl(fn,a,b);}finally{isBatchingEventUpdates=false;finishEventHandler();}}function discreteUpdates(fn,a,b,c,d){var prevIsInsideEventHandler=isInsideEventHandler;isInsideEventHandler=true;try{return discreteUpdatesImpl(fn,a,b,c,d);}finally{isInsideEventHandler=prevIsInsideEventHandler;if(!isInsideEventHandler){finishEventHandler();}}}function flushDiscreteUpdatesIfNeeded(timeStamp){{if(!isInsideEventHandler){flushDiscreteUpdatesImpl();}}}function setBatchingImplementation(_batchedUpdatesImpl,_discreteUpdatesImpl,_flushDiscreteUpdatesImpl,_batchedEventUpdatesImpl){batchedUpdatesImpl=_batchedUpdatesImpl;discreteUpdatesImpl=_discreteUpdatesImpl;flushDiscreteUpdatesImpl=_flushDiscreteUpdatesImpl;batchedEventUpdatesImpl=_batchedEventUpdatesImpl;}function isInteractive(tag){return tag==='button'||tag==='input'||tag==='select'||tag==='textarea';}function shouldPreventMouseEvent(name,type,props){switch(name){case'onClick':case'onClickCapture':case'onDoubleClick':case'onDoubleClickCapture':case'onMouseDown':case'onMouseDownCapture':case'onMouseMove':case'onMouseMoveCapture':case'onMouseUp':case'onMouseUpCapture':case'onMouseEnter':return !!(props.disabled&&isInteractive(type));default:return false;}}/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/function getListener(inst,registrationName){var stateNode=inst.stateNode;if(stateNode===null){// Work in progress (ex: onload events in incremental mode).
return null;}var props=getFiberCurrentPropsFromNode(stateNode);if(props===null){// Work in progress.
return null;}var listener=props[registrationName];if(shouldPreventMouseEvent(registrationName,inst.type,props)){return null;}if(!(!listener||typeof listener==='function')){{throw Error("Expected `"+registrationName+"` listener to be a function, instead got a value of `"+typeof listener+"` type.");}}return listener;}var passiveBrowserEventsSupported=false;// Check if browser support events with passive listeners
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
if(canUseDOM){try{var options={};// $FlowFixMe: Ignore Flow complaining about needing a value
Object.defineProperty(options,'passive',{get:function(){passiveBrowserEventsSupported=true;}});window.addEventListener('test',options,options);window.removeEventListener('test',options,options);}catch(e){passiveBrowserEventsSupported=false;}}function invokeGuardedCallbackProd(name,func,context,a,b,c,d,e,f){var funcArgs=Array.prototype.slice.call(arguments,3);try{func.apply(context,funcArgs);}catch(error){this.onError(error);}}var invokeGuardedCallbackImpl=invokeGuardedCallbackProd;{// In DEV mode, we swap out invokeGuardedCallback for a special version
// that plays more nicely with the browser's DevTools. The idea is to preserve
// "Pause on exceptions" behavior. Because React wraps all user-provided
// functions in invokeGuardedCallback, and the production version of
// invokeGuardedCallback uses a try-catch, all user exceptions are treated
// like caught exceptions, and the DevTools won't pause unless the developer
// takes the extra step of enabling pause on caught exceptions. This is
// unintuitive, though, because even though React has caught the error, from
// the developer's perspective, the error is uncaught.
//
// To preserve the expected "Pause on exceptions" behavior, we don't use a
// try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
// DOM node, and call the user-provided callback from inside an event handler
// for that fake event. If the callback throws, the error is "captured" using
// a global event handler. But because the error happens in a different
// event loop context, it does not interrupt the normal program flow.
// Effectively, this gives us try-catch behavior without actually using
// try-catch. Neat!
// Check that the browser supports the APIs we need to implement our special
// DEV version of invokeGuardedCallback
if(typeof window!=='undefined'&&typeof window.dispatchEvent==='function'&&typeof document!=='undefined'&&typeof document.createEvent==='function'){var fakeNode=document.createElement('react');invokeGuardedCallbackImpl=function invokeGuardedCallbackDev(name,func,context,a,b,c,d,e,f){// If document doesn't exist we know for sure we will crash in this method
// when we call document.createEvent(). However this can cause confusing
// errors: https://github.com/facebookincubator/create-react-app/issues/3482
// So we preemptively throw with a better message instead.
if(!(typeof document!=='undefined')){{throw Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");}}var evt=document.createEvent('Event');var didCall=false;// Keeps track of whether the user-provided callback threw an error. We
// set this to true at the beginning, then set it to false right after
// calling the function. If the function errors, `didError` will never be
// set to false. This strategy works even if the browser is flaky and
// fails to call our global error handler, because it doesn't rely on
// the error event at all.
var didError=true;// Keeps track of the value of window.event so that we can reset it
// during the callback to let user code access window.event in the
// browsers that support it.
var windowEvent=window.event;// Keeps track of the descriptor of window.event to restore it after event
// dispatching: https://github.com/facebook/react/issues/13688
var windowEventDescriptor=Object.getOwnPropertyDescriptor(window,'event');function restoreAfterDispatch(){// We immediately remove the callback from event listeners so that
// nested `invokeGuardedCallback` calls do not clash. Otherwise, a
// nested call would trigger the fake event handlers of any call higher
// in the stack.
fakeNode.removeEventListener(evtType,callCallback,false);// We check for window.hasOwnProperty('event') to prevent the
// window.event assignment in both IE <= 10 as they throw an error
// "Member not found" in strict mode, and in Firefox which does not
// support window.event.
if(typeof window.event!=='undefined'&&window.hasOwnProperty('event')){window.event=windowEvent;}}// Create an event handler for our fake event. We will synchronously
// dispatch our fake event using `dispatchEvent`. Inside the handler, we
// call the user-provided callback.
var funcArgs=Array.prototype.slice.call(arguments,3);function callCallback(){didCall=true;restoreAfterDispatch();func.apply(context,funcArgs);didError=false;}// Create a global error event handler. We use this to capture the value
// that was thrown. It's possible that this error handler will fire more
// than once; for example, if non-React code also calls `dispatchEvent`
// and a handler for that event throws. We should be resilient to most of
// those cases. Even if our error event handler fires more than once, the
// last error event is always used. If the callback actually does error,
// we know that the last error event is the correct one, because it's not
// possible for anything else to have happened in between our callback
// erroring and the code that follows the `dispatchEvent` call below. If
// the callback doesn't error, but the error event was fired, we know to
// ignore it because `didError` will be false, as described above.
var error;// Use this to track whether the error event is ever called.
var didSetError=false;var isCrossOriginError=false;function handleWindowError(event){error=event.error;didSetError=true;if(error===null&&event.colno===0&&event.lineno===0){isCrossOriginError=true;}if(event.defaultPrevented){// Some other error handler has prevented default.
// Browsers silence the error report if this happens.
// We'll remember this to later decide whether to log it or not.
if(error!=null&&typeof error==='object'){try{error._suppressLogging=true;}catch(inner){// Ignore.
}}}}// Create a fake event type.
var evtType="react-"+(name?name:'invokeguardedcallback');// Attach our event handlers
window.addEventListener('error',handleWindowError);fakeNode.addEventListener(evtType,callCallback,false);// Synchronously dispatch our fake event. If the user-provided function
// errors, it will trigger our global error handler.
evt.initEvent(evtType,false,false);fakeNode.dispatchEvent(evt);if(windowEventDescriptor){Object.defineProperty(window,'event',windowEventDescriptor);}if(didCall&&didError){if(!didSetError){// The callback errored, but the error event never fired.
error=new Error('An error was thrown inside one of your components, but React '+"doesn't know what it was. This is likely due to browser "+'flakiness. React does its best to preserve the "Pause on '+'exceptions" behavior of the DevTools, which requires some '+"DEV-mode only tricks. It's possible that these don't work in "+'your browser. Try triggering the error in production mode, '+'or switching to a modern browser. If you suspect that this is '+'actually an issue with React, please file an issue.');}else if(isCrossOriginError){error=new Error("A cross-origin error was thrown. React doesn't have access to "+'the actual error object in development. '+'See https://reactjs.org/link/crossorigin-error for more information.');}this.onError(error);}// Remove our event listeners
window.removeEventListener('error',handleWindowError);if(!didCall){// Something went really wrong, and our event was not dispatched.
// https://github.com/facebook/react/issues/16734
// https://github.com/facebook/react/issues/16585
// Fall back to the production implementation.
restoreAfterDispatch();return invokeGuardedCallbackProd.apply(this,arguments);}};}}var invokeGuardedCallbackImpl$1=invokeGuardedCallbackImpl;var hasError=false;var caughtError=null;// Used by event system to capture/rethrow the first error.
var hasRethrowError=false;var rethrowError=null;var reporter={onError:function(error){hasError=true;caughtError=error;}};/**
* Call a function while guarding against errors that happens within it.
* Returns an error if it throws, otherwise null.
*
* In production, this is implemented using a try-catch. The reason we don't
* use a try-catch directly is so that we can swap out a different
* implementation in DEV mode.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} context The context to use when calling the function
* @param {...*} args Arguments for function
*/function invokeGuardedCallback(name,func,context,a,b,c,d,e,f){hasError=false;caughtError=null;invokeGuardedCallbackImpl$1.apply(reporter,arguments);}/**
* Same as invokeGuardedCallback, but instead of returning an error, it stores
* it in a global so it can be rethrown by `rethrowCaughtError` later.
* TODO: See if caughtError and rethrowError can be unified.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} context The context to use when calling the function
* @param {...*} args Arguments for function
*/function invokeGuardedCallbackAndCatchFirstError(name,func,context,a,b,c,d,e,f){invokeGuardedCallback.apply(this,arguments);if(hasError){var error=clearCaughtError();if(!hasRethrowError){hasRethrowError=true;rethrowError=error;}}}/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/function rethrowCaughtError(){if(hasRethrowError){var error=rethrowError;hasRethrowError=false;rethrowError=null;throw error;}}function hasCaughtError(){return hasError;}function clearCaughtError(){if(hasError){var error=caughtError;hasError=false;caughtError=null;return error;}else {{{throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");}}}}/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*
* Note that this module is currently shared and assumed to be stateless.
* If this becomes an actual Map, that will break.
*/function get(key){return key._reactInternals;}function has(key){return key._reactInternals!==undefined;}function set(key,value){key._reactInternals=value;}// Don't change these two values. They're used by React Dev Tools.
var NoFlags=/* */0;var PerformedWork=/* */1;// You can change the rest (and add more).
var Placement=/* */2;var Update=/* */4;var PlacementAndUpdate=/* */6;var Deletion=/* */8;var ContentReset=/* */16;var Callback=/* */32;var DidCapture=/* */64;var Ref=/* */128;var Snapshot=/* */256;var Passive=/* */512;// TODO (effects) Remove this bit once the new reconciler is synced to the old.
var PassiveUnmountPendingDev=/* */8192;var Hydrating=/* */1024;var HydratingAndUpdate=/* */1028;// Passive & Update & Callback & Ref & Snapshot
var LifecycleEffectMask=/* */932;// Union of all host effects
var HostEffectMask=/* */2047;// These are not really side effects, but we still reuse this field.
var Incomplete=/* */2048;var ShouldCapture=/* */4096;var ForceUpdateForLegacySuspense=/* */16384;// Static tags describe aspects of a fiber that are not specific to a render,
var ReactCurrentOwner=ReactSharedInternals.ReactCurrentOwner;function getNearestMountedFiber(fiber){var node=fiber;var nearestMounted=fiber;if(!fiber.alternate){// If there is no alternate, this might be a new tree that isn't inserted
// yet. If it is, then it will have a pending insertion effect on it.
var nextNode=node;do{node=nextNode;if((node.flags&(Placement|Hydrating))!==NoFlags){// This is an insertion or in-progress hydration. The nearest possible
// mounted fiber is the parent but we need to continue to figure out
// if that one is still mounted.
nearestMounted=node.return;}nextNode=node.return;}while(nextNode);}else {while(node.return){node=node.return;}}if(node.tag===HostRoot){// TODO: Check if this was a nested HostRoot when used with
// renderContainerIntoSubtree.
return nearestMounted;}// If we didn't hit the root, that means that we're in an disconnected tree
// that has been unmounted.
return null;}function getSuspenseInstanceFromFiber(fiber){if(fiber.tag===SuspenseComponent){var suspenseState=fiber.memoizedState;if(suspenseState===null){var current=fiber.alternate;if(current!==null){suspenseState=current.memoizedState;}}if(suspenseState!==null){return suspenseState.dehydrated;}}return null;}function getContainerFromFiber(fiber){return fiber.tag===HostRoot?fiber.stateNode.containerInfo:null;}function isFiberMounted(fiber){return getNearestMountedFiber(fiber)===fiber;}function isMounted(component){{var owner=ReactCurrentOwner.current;if(owner!==null&&owner.tag===ClassComponent){var ownerFiber=owner;var instance=ownerFiber.stateNode;if(!instance._warnedAboutRefsInRender){error('%s is accessing isMounted inside its render() function. '+'render() should be a pure function of props and state. It should '+'never access something that requires stale data from the previous '+'render, such as refs. Move this logic to componentDidMount and '+'componentDidUpdate instead.',getComponentName(ownerFiber.type)||'A component');}instance._warnedAboutRefsInRender=true;}}var fiber=get(component);if(!fiber){return false;}return getNearestMountedFiber(fiber)===fiber;}function assertIsMounted(fiber){if(!(getNearestMountedFiber(fiber)===fiber)){{throw Error("Unable to find node on an unmounted component.");}}}function findCurrentFiberUsingSlowPath(fiber){var alternate=fiber.alternate;if(!alternate){// If there is no alternate, then we only need to check if it is mounted.
var nearestMounted=getNearestMountedFiber(fiber);if(!(nearestMounted!==null)){{throw Error("Unable to find node on an unmounted component.");}}if(nearestMounted!==fiber){return null;}return fiber;}// If we have two possible branches, we'll walk backwards up to the root
// to see what path the root points to. On the way we may hit one of the
// special cases and we'll deal with them.
var a=fiber;var b=alternate;while(true){var parentA=a.return;if(parentA===null){// We're at the root.
break;}var parentB=parentA.alternate;if(parentB===null){// There is no alternate. This is an unusual case. Currently, it only
// happens when a Suspense component is hidden. An extra fragment fiber
// is inserted in between the Suspense fiber and its children. Skip
// over this extra fragment fiber and proceed to the next parent.
var nextParent=parentA.return;if(nextParent!==null){a=b=nextParent;continue;}// If there's no parent, we're at the root.
break;}// If both copies of the parent fiber point to the same child, we can
// assume that the child is current. This happens when we bailout on low
// priority: the bailed out fiber's child reuses the current child.
if(parentA.child===parentB.child){var child=parentA.child;while(child){if(child===a){// We've determined that A is the current branch.
assertIsMounted(parentA);return fiber;}if(child===b){// We've determined that B is the current branch.
assertIsMounted(parentA);return alternate;}child=child.sibling;}// We should never have an alternate for any mounting node. So the only
// way this could possibly happen is if this was unmounted, if at all.
{{throw Error("Unable to find node on an unmounted component.");}}}if(a.return!==b.return){// The return pointer of A and the return pointer of B point to different
// fibers. We assume that return pointers never criss-cross, so A must
// belong to the child set of A.return, and B must belong to the child
// set of B.return.
a=parentA;b=parentB;}else {// The return pointers point to the same fiber. We'll have to use the
// default, slow path: scan the child sets of each parent alternate to see
// which child belongs to which set.
//
// Search parent A's child set
var didFindChild=false;var _child=parentA.child;while(_child){if(_child===a){didFindChild=true;a=parentA;b=parentB;break;}if(_child===b){didFindChild=true;b=parentA;a=parentB;break;}_child=_child.sibling;}if(!didFindChild){// Search parent B's child set
_child=parentB.child;while(_child){if(_child===a){didFindChild=true;a=parentB;b=parentA;break;}if(_child===b){didFindChild=true;b=parentB;a=parentA;break;}_child=_child.sibling;}if(!didFindChild){{throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");}}}}if(!(a.alternate===b)){{throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");}}}// If the root is not a host container, we're in a disconnected tree. I.e.
// unmounted.
if(!(a.tag===HostRoot)){{throw Error("Unable to find node on an unmounted component.");}}if(a.stateNode.current===a){// We've determined that A is the current branch.
return fiber;}// Otherwise B has to be current branch.
return alternate;}function findCurrentHostFiber(parent){var currentParent=findCurrentFiberUsingSlowPath(parent);if(!currentParent){return null;}// Next we'll drill down this component to find the first HostComponent/Text.
var node=currentParent;while(true){if(node.tag===HostComponent||node.tag===HostText){return node;}else if(node.child){node.child.return=node;node=node.child;continue;}if(node===currentParent){return null;}while(!node.sibling){if(!node.return||node.return===currentParent){return null;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}// Flow needs the return null here, but ESLint complains about it.
// eslint-disable-next-line no-unreachable
return null;}function findCurrentHostFiberWithNoPortals(parent){var currentParent=findCurrentFiberUsingSlowPath(parent);if(!currentParent){return null;}// Next we'll drill down this component to find the first HostComponent/Text.
var node=currentParent;while(true){if(node.tag===HostComponent||node.tag===HostText||enableFundamentalAPI){return node;}else if(node.child&&node.tag!==HostPortal){node.child.return=node;node=node.child;continue;}if(node===currentParent){return null;}while(!node.sibling){if(!node.return||node.return===currentParent){return null;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}// Flow needs the return null here, but ESLint complains about it.
// eslint-disable-next-line no-unreachable
return null;}function doesFiberContain(parentFiber,childFiber){var node=childFiber;var parentFiberAlternate=parentFiber.alternate;while(node!==null){if(node===parentFiber||node===parentFiberAlternate){return true;}node=node.return;}return false;}var attemptUserBlockingHydration;function setAttemptUserBlockingHydration(fn){attemptUserBlockingHydration=fn;}var attemptContinuousHydration;function setAttemptContinuousHydration(fn){attemptContinuousHydration=fn;}var attemptHydrationAtCurrentPriority;function setAttemptHydrationAtCurrentPriority(fn){attemptHydrationAtCurrentPriority=fn;}var attemptHydrationAtPriority;function setAttemptHydrationAtPriority(fn){attemptHydrationAtPriority=fn;}// TODO: Upgrade this definition once we're on a newer version of Flow that
var hasScheduledReplayAttempt=false;// The queue of discrete events to be replayed.
var queuedDiscreteEvents=[];// Indicates if any continuous event targets are non-null for early bailout.
// if the last target was dehydrated.
var queuedFocus=null;var queuedDrag=null;var queuedMouse=null;// For pointer events there can be one latest event per pointerId.
var queuedPointers=new Map();var queuedPointerCaptures=new Map();// We could consider replaying selectionchange and touchmoves too.
var queuedExplicitHydrationTargets=[];function hasQueuedDiscreteEvents(){return queuedDiscreteEvents.length>0;}var discreteReplayableEvents=['mousedown','mouseup','touchcancel','touchend','touchstart','auxclick','dblclick','pointercancel','pointerdown','pointerup','dragend','dragstart','drop','compositionend','compositionstart','keydown','keypress','keyup','input','textInput',// Intentionally camelCase
'copy','cut','paste','click','change','contextmenu','reset','submit'];function isReplayableDiscreteEvent(eventType){return discreteReplayableEvents.indexOf(eventType)>-1;}function createQueuedReplayableEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){return {blockedOn:blockedOn,domEventName:domEventName,eventSystemFlags:eventSystemFlags|IS_REPLAYED,nativeEvent:nativeEvent,targetContainers:[targetContainer]};}function queueDiscreteEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){var queuedEvent=createQueuedReplayableEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent);queuedDiscreteEvents.push(queuedEvent);}// Resets the replaying for this type of continuous event to no event.
function clearIfContinuousEvent(domEventName,nativeEvent){switch(domEventName){case'focusin':case'focusout':queuedFocus=null;break;case'dragenter':case'dragleave':queuedDrag=null;break;case'mouseover':case'mouseout':queuedMouse=null;break;case'pointerover':case'pointerout':{var pointerId=nativeEvent.pointerId;queuedPointers.delete(pointerId);break;}case'gotpointercapture':case'lostpointercapture':{var _pointerId=nativeEvent.pointerId;queuedPointerCaptures.delete(_pointerId);break;}}}function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent,blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){if(existingQueuedEvent===null||existingQueuedEvent.nativeEvent!==nativeEvent){var queuedEvent=createQueuedReplayableEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent);if(blockedOn!==null){var _fiber2=getInstanceFromNode(blockedOn);if(_fiber2!==null){// Attempt to increase the priority of this target.
attemptContinuousHydration(_fiber2);}}return queuedEvent;}// If we have already queued this exact event, then it's because
// the different event systems have different DOM event listeners.
// We can accumulate the flags, and the targetContainers, and
// store a single event to be replayed.
existingQueuedEvent.eventSystemFlags|=eventSystemFlags;var targetContainers=existingQueuedEvent.targetContainers;if(targetContainer!==null&&targetContainers.indexOf(targetContainer)===-1){targetContainers.push(targetContainer);}return existingQueuedEvent;}function queueIfContinuousEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){// These set relatedTarget to null because the replayed event will be treated as if we
// moved from outside the window (no target) onto the target once it hydrates.
// Instead of mutating we could clone the event.
switch(domEventName){case'focusin':{var focusEvent=nativeEvent;queuedFocus=accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus,blockedOn,domEventName,eventSystemFlags,targetContainer,focusEvent);return true;}case'dragenter':{var dragEvent=nativeEvent;queuedDrag=accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag,blockedOn,domEventName,eventSystemFlags,targetContainer,dragEvent);return true;}case'mouseover':{var mouseEvent=nativeEvent;queuedMouse=accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse,blockedOn,domEventName,eventSystemFlags,targetContainer,mouseEvent);return true;}case'pointerover':{var pointerEvent=nativeEvent;var pointerId=pointerEvent.pointerId;queuedPointers.set(pointerId,accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId)||null,blockedOn,domEventName,eventSystemFlags,targetContainer,pointerEvent));return true;}case'gotpointercapture':{var _pointerEvent=nativeEvent;var _pointerId2=_pointerEvent.pointerId;queuedPointerCaptures.set(_pointerId2,accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2)||null,blockedOn,domEventName,eventSystemFlags,targetContainer,_pointerEvent));return true;}}return false;}// Check if this target is unblocked. Returns true if it's unblocked.
function attemptExplicitHydrationTarget(queuedTarget){// TODO: This function shares a lot of logic with attemptToDispatchEvent.
// Try to unify them. It's a bit tricky since it would require two return
// values.
var targetInst=getClosestInstanceFromNode(queuedTarget.target);if(targetInst!==null){var nearestMounted=getNearestMountedFiber(targetInst);if(nearestMounted!==null){var tag=nearestMounted.tag;if(tag===SuspenseComponent){var instance=getSuspenseInstanceFromFiber(nearestMounted);if(instance!==null){// We're blocked on hydrating this boundary.
// Increase its priority.
queuedTarget.blockedOn=instance;attemptHydrationAtPriority(queuedTarget.lanePriority,function(){Scheduler.unstable_runWithPriority(queuedTarget.priority,function(){attemptHydrationAtCurrentPriority(nearestMounted);});});return;}}else if(tag===HostRoot){var root=nearestMounted.stateNode;if(root.hydrate){queuedTarget.blockedOn=getContainerFromFiber(nearestMounted);// We don't currently have a way to increase the priority of
// a root other than sync.
return;}}}}queuedTarget.blockedOn=null;}function attemptReplayContinuousQueuedEvent(queuedEvent){if(queuedEvent.blockedOn!==null){return false;}var targetContainers=queuedEvent.targetContainers;while(targetContainers.length>0){var targetContainer=targetContainers[0];var nextBlockedOn=attemptToDispatchEvent(queuedEvent.domEventName,queuedEvent.eventSystemFlags,targetContainer,queuedEvent.nativeEvent);if(nextBlockedOn!==null){// We're still blocked. Try again later.
var _fiber3=getInstanceFromNode(nextBlockedOn);if(_fiber3!==null){attemptContinuousHydration(_fiber3);}queuedEvent.blockedOn=nextBlockedOn;return false;}// This target container was successfully dispatched. Try the next.
targetContainers.shift();}return true;}function attemptReplayContinuousQueuedEventInMap(queuedEvent,key,map){if(attemptReplayContinuousQueuedEvent(queuedEvent)){map.delete(key);}}function replayUnblockedEvents(){hasScheduledReplayAttempt=false;// First replay discrete events.
while(queuedDiscreteEvents.length>0){var nextDiscreteEvent=queuedDiscreteEvents[0];if(nextDiscreteEvent.blockedOn!==null){// We're still blocked.
// Increase the priority of this boundary to unblock
// the next discrete event.
var _fiber4=getInstanceFromNode(nextDiscreteEvent.blockedOn);if(_fiber4!==null){attemptUserBlockingHydration(_fiber4);}break;}var targetContainers=nextDiscreteEvent.targetContainers;while(targetContainers.length>0){var targetContainer=targetContainers[0];var nextBlockedOn=attemptToDispatchEvent(nextDiscreteEvent.domEventName,nextDiscreteEvent.eventSystemFlags,targetContainer,nextDiscreteEvent.nativeEvent);if(nextBlockedOn!==null){// We're still blocked. Try again later.
nextDiscreteEvent.blockedOn=nextBlockedOn;break;}// This target container was successfully dispatched. Try the next.
targetContainers.shift();}if(nextDiscreteEvent.blockedOn===null){// We've successfully replayed the first event. Let's try the next one.
queuedDiscreteEvents.shift();}}// Next replay any continuous events.
if(queuedFocus!==null&&attemptReplayContinuousQueuedEvent(queuedFocus)){queuedFocus=null;}if(queuedDrag!==null&&attemptReplayContinuousQueuedEvent(queuedDrag)){queuedDrag=null;}if(queuedMouse!==null&&attemptReplayContinuousQueuedEvent(queuedMouse)){queuedMouse=null;}queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);}function scheduleCallbackIfUnblocked(queuedEvent,unblocked){if(queuedEvent.blockedOn===unblocked){queuedEvent.blockedOn=null;if(!hasScheduledReplayAttempt){hasScheduledReplayAttempt=true;// Schedule a callback to attempt replaying as many events as are
// now unblocked. This first might not actually be unblocked yet.
// We could check it early to avoid scheduling an unnecessary callback.
Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority,replayUnblockedEvents);}}}function retryIfBlockedOn(unblocked){// Mark anything that was blocked on this as no longer blocked
// and eligible for a replay.
if(queuedDiscreteEvents.length>0){scheduleCallbackIfUnblocked(queuedDiscreteEvents[0],unblocked);// This is a exponential search for each boundary that commits. I think it's
// worth it because we expect very few discrete events to queue up and once
// we are actually fully unblocked it will be fast to replay them.
for(var i=1;i<queuedDiscreteEvents.length;i++){var queuedEvent=queuedDiscreteEvents[i];if(queuedEvent.blockedOn===unblocked){queuedEvent.blockedOn=null;}}}if(queuedFocus!==null){scheduleCallbackIfUnblocked(queuedFocus,unblocked);}if(queuedDrag!==null){scheduleCallbackIfUnblocked(queuedDrag,unblocked);}if(queuedMouse!==null){scheduleCallbackIfUnblocked(queuedMouse,unblocked);}var unblock=function(queuedEvent){return scheduleCallbackIfUnblocked(queuedEvent,unblocked);};queuedPointers.forEach(unblock);queuedPointerCaptures.forEach(unblock);for(var _i=0;_i<queuedExplicitHydrationTargets.length;_i++){var queuedTarget=queuedExplicitHydrationTargets[_i];if(queuedTarget.blockedOn===unblocked){queuedTarget.blockedOn=null;}}while(queuedExplicitHydrationTargets.length>0){var nextExplicitTarget=queuedExplicitHydrationTargets[0];if(nextExplicitTarget.blockedOn!==null){// We're still blocked.
break;}else {attemptExplicitHydrationTarget(nextExplicitTarget);if(nextExplicitTarget.blockedOn===null){// We're unblocked.
queuedExplicitHydrationTargets.shift();}}}}var DiscreteEvent=0;var UserBlockingEvent=1;var ContinuousEvent=2;/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/function makePrefixMap(styleProp,eventName){var prefixes={};prefixes[styleProp.toLowerCase()]=eventName.toLowerCase();prefixes['Webkit'+styleProp]='webkit'+eventName;prefixes['Moz'+styleProp]='moz'+eventName;return prefixes;}/**
* A list of event names to a configurable list of vendor prefixes.
*/var vendorPrefixes={animationend:makePrefixMap('Animation','AnimationEnd'),animationiteration:makePrefixMap('Animation','AnimationIteration'),animationstart:makePrefixMap('Animation','AnimationStart'),transitionend:makePrefixMap('Transition','TransitionEnd')};/**
* Event names that have already been detected and prefixed (if applicable).
*/var prefixedEventNames={};/**
* Element to check for prefixes on.
*/var style={};/**
* Bootstrap if a DOM exists.
*/if(canUseDOM){style=document.createElement('div').style;// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if(!('AnimationEvent'in window)){delete vendorPrefixes.animationend.animation;delete vendorPrefixes.animationiteration.animation;delete vendorPrefixes.animationstart.animation;}// Same as above
if(!('TransitionEvent'in window)){delete vendorPrefixes.transitionend.transition;}}/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/function getVendorPrefixedEventName(eventName){if(prefixedEventNames[eventName]){return prefixedEventNames[eventName];}else if(!vendorPrefixes[eventName]){return eventName;}var prefixMap=vendorPrefixes[eventName];for(var styleProp in prefixMap){if(prefixMap.hasOwnProperty(styleProp)&&styleProp in style){return prefixedEventNames[eventName]=prefixMap[styleProp];}}return eventName;}var ANIMATION_END=getVendorPrefixedEventName('animationend');var ANIMATION_ITERATION=getVendorPrefixedEventName('animationiteration');var ANIMATION_START=getVendorPrefixedEventName('animationstart');var TRANSITION_END=getVendorPrefixedEventName('transitionend');var topLevelEventsToReactNames=new Map();var eventPriorities=new Map();// We store most of the events in this module in pairs of two strings so we can re-use
// the code required to apply the same logic for event prioritization and that of the
// SimpleEventPlugin. This complicates things slightly, but the aim is to reduce code
// duplication (for which there would be quite a bit). For the events that are not needed
// for the SimpleEventPlugin (otherDiscreteEvents) we process them separately as an
// array of top level events.
// Lastly, we ignore prettier so we can keep the formatting sane.
// prettier-ignore
var discreteEventPairsForSimpleEventPlugin=['cancel','cancel','click','click','close','close','contextmenu','contextMenu','copy','copy','cut','cut','auxclick','auxClick','dblclick','doubleClick',// Careful!
'dragend','dragEnd','dragstart','dragStart','drop','drop','focusin','focus',// Careful!
'focusout','blur',// Careful!
'input','input','invalid','invalid','keydown','keyDown','keypress','keyPress','keyup','keyUp','mousedown','mouseDown','mouseup','mouseUp','paste','paste','pause','pause','play','play','pointercancel','pointerCancel','pointerdown','pointerDown','pointerup','pointerUp','ratechange','rateChange','reset','reset','seeked','seeked','submit','submit','touchcancel','touchCancel','touchend','touchEnd','touchstart','touchStart','volumechange','volumeChange'];var otherDiscreteEvents=['change','selectionchange','textInput','compositionstart','compositionend','compositionupdate'];var userBlockingPairsForSimpleEventPlugin=['drag','drag','dragenter','dragEnter','dragexit','dragExit','dragleave','dragLeave','dragover','dragOver','mousemove','mouseMove','mouseout','mouseOut','mouseover','mouseOver','pointermove','pointerMove','pointerout','pointerOut','pointerover','pointerOver','scroll','scroll','toggle','toggle','touchmove','touchMove','wheel','wheel'];// prettier-ignore
var continuousPairsForSimpleEventPlugin=['abort','abort',ANIMATION_END,'animationEnd',ANIMATION_ITERATION,'animationIteration',ANIMATION_START,'animationStart','canplay','canPlay','canplaythrough','canPlayThrough','durationchange','durationChange','emptied','emptied','encrypted','encrypted','ended','ended','error','error','gotpointercapture','gotPointerCapture','load','load','loadeddata','loadedData','loadedmetadata','loadedMetadata','loadstart','loadStart','lostpointercapture','lostPointerCapture','playing','playing','progress','progress','seeking','seeking','stalled','stalled','suspend','suspend','timeupdate','timeUpdate',TRANSITION_END,'transitionEnd','waiting','waiting'];/**
* Turns
* ['abort', ...]
*
* into
*
* topLevelEventsToReactNames = new Map([
* ['abort', 'onAbort'],
* ]);
*
* and registers them.
*/function registerSimplePluginEventsAndSetTheirPriorities(eventTypes,priority){// As the event types are in pairs of two, we need to iterate
// through in twos. The events are in pairs of two to save code
// and improve init perf of processing this array, as it will
// result in far fewer object allocations and property accesses
// if we only use three arrays to process all the categories of
// instead of tuples.
for(var i=0;i<eventTypes.length;i+=2){var topEvent=eventTypes[i];var event=eventTypes[i+1];var capitalizedEvent=event[0].toUpperCase()+event.slice(1);var reactName='on'+capitalizedEvent;eventPriorities.set(topEvent,priority);topLevelEventsToReactNames.set(topEvent,reactName);registerTwoPhaseEvent(reactName,[topEvent]);}}function setEventPriorities(eventTypes,priority){for(var i=0;i<eventTypes.length;i++){eventPriorities.set(eventTypes[i],priority);}}function getEventPriorityForPluginSystem(domEventName){var priority=eventPriorities.get(domEventName);// Default to a ContinuousEvent. Note: we might
// want to warn if we can't detect the priority
// for the event.
return priority===undefined?ContinuousEvent:priority;}function registerSimpleEvents(){registerSimplePluginEventsAndSetTheirPriorities(discreteEventPairsForSimpleEventPlugin,DiscreteEvent);registerSimplePluginEventsAndSetTheirPriorities(userBlockingPairsForSimpleEventPlugin,UserBlockingEvent);registerSimplePluginEventsAndSetTheirPriorities(continuousPairsForSimpleEventPlugin,ContinuousEvent);setEventPriorities(otherDiscreteEvents,DiscreteEvent);}var Scheduler_now=Scheduler.unstable_now;{// Provide explicit error message when production+profiling bundle of e.g.
// react-dom is used with production (non-profiling) bundle of
// scheduler/tracing
if(!(tracing$1.__interactionsRef!=null&&tracing$1.__interactionsRef.current!=null)){{throw Error("It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at https://reactjs.org/link/profiling");}}}// ascending numbers so we can compare them like numbers. They start at 90 to
// avoid clashing with Scheduler's priorities.
var ImmediatePriority=99;var UserBlockingPriority=98;var NormalPriority=97;var LowPriority=96;var IdlePriority=95;// NoPriority is the absence of priority. Also React-only.
var NoPriority=90;var initialTimeMs=Scheduler_now();// If the initial timestamp is reasonably small, use Scheduler's `now` directly.
var SyncLanePriority=15;var SyncBatchedLanePriority=14;var InputDiscreteHydrationLanePriority=13;var InputDiscreteLanePriority=12;var InputContinuousHydrationLanePriority=11;var InputContinuousLanePriority=10;var DefaultHydrationLanePriority=9;var DefaultLanePriority=8;var TransitionHydrationPriority=7;var TransitionPriority=6;var RetryLanePriority=5;var SelectiveHydrationLanePriority=4;var IdleHydrationLanePriority=3;var IdleLanePriority=2;var OffscreenLanePriority=1;var NoLanePriority=0;var TotalLanes=31;var NoLanes=/* */0;var NoLane=/* */0;var SyncLane=/* */1;var SyncBatchedLane=/* */2;var InputDiscreteHydrationLane=/* */4;var InputDiscreteLanes=/* */24;var InputContinuousHydrationLane=/* */32;var InputContinuousLanes=/* */192;var DefaultHydrationLane=/* */256;var DefaultLanes=/* */3584;var TransitionHydrationLane=/* */4096;var TransitionLanes=/* */4186112;var RetryLanes=/* */62914560;var SomeRetryLane=/* */33554432;var SelectiveHydrationLane=/* */67108864;var NonIdleLanes=/* */134217727;var IdleHydrationLane=/* */134217728;var IdleLanes=/* */805306368;var OffscreenLane=/* */1073741824;var NoTimestamp=-1;function setCurrentUpdateLanePriority(newLanePriority){}// "Registers" used to "return" multiple values
// Used by getHighestPriorityLanes and getNextLanes:
var return_highestLanePriority=DefaultLanePriority;function getHighestPriorityLanes(lanes){if((SyncLane&lanes)!==NoLanes){return_highestLanePriority=SyncLanePriority;return SyncLane;}if((SyncBatchedLane&lanes)!==NoLanes){return_highestLanePriority=SyncBatchedLanePriority;return SyncBatchedLane;}if((InputDiscreteHydrationLane&lanes)!==NoLanes){return_highestLanePriority=InputDiscreteHydrationLanePriority;return InputDiscreteHydrationLane;}var inputDiscreteLanes=InputDiscreteLanes&lanes;if(inputDiscreteLanes!==NoLanes){return_highestLanePriority=InputDiscreteLanePriority;return inputDiscreteLanes;}if((lanes&InputContinuousHydrationLane)!==NoLanes){return_highestLanePriority=InputContinuousHydrationLanePriority;return InputContinuousHydrationLane;}var inputContinuousLanes=InputContinuousLanes&lanes;if(inputContinuousLanes!==NoLanes){return_highestLanePriority=InputContinuousLanePriority;return inputContinuousLanes;}if((lanes&DefaultHydrationLane)!==NoLanes){return_highestLanePriority=DefaultHydrationLanePriority;return DefaultHydrationLane;}var defaultLanes=DefaultLanes&lanes;if(defaultLanes!==NoLanes){return_highestLanePriority=DefaultLanePriority;return defaultLanes;}if((lanes&TransitionHydrationLane)!==NoLanes){return_highestLanePriority=TransitionHydrationPriority;return TransitionHydrationLane;}var transitionLanes=TransitionLanes&lanes;if(transitionLanes!==NoLanes){return_highestLanePriority=TransitionPriority;return transitionLanes;}var retryLanes=RetryLanes&lanes;if(retryLanes!==NoLanes){return_highestLanePriority=RetryLanePriority;return retryLanes;}if(lanes&SelectiveHydrationLane){return_highestLanePriority=SelectiveHydrationLanePriority;return SelectiveHydrationLane;}if((lanes&IdleHydrationLane)!==NoLanes){return_highestLanePriority=IdleHydrationLanePriority;return IdleHydrationLane;}var idleLanes=IdleLanes&lanes;if(idleLanes!==NoLanes){return_highestLanePriority=IdleLanePriority;return idleLanes;}if((OffscreenLane&lanes)!==NoLanes){return_highestLanePriority=OffscreenLanePriority;return OffscreenLane;}{error('Should have found matching lanes. This is a bug in React.');}// This shouldn't be reachable, but as a fallback, return the entire bitmask.
return_highestLanePriority=DefaultLanePriority;return lanes;}function schedulerPriorityToLanePriority(schedulerPriorityLevel){switch(schedulerPriorityLevel){case ImmediatePriority:return SyncLanePriority;case UserBlockingPriority:return InputContinuousLanePriority;case NormalPriority:case LowPriority:// TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
return DefaultLanePriority;case IdlePriority:return IdleLanePriority;default:return NoLanePriority;}}function lanePriorityToSchedulerPriority(lanePriority){switch(lanePriority){case SyncLanePriority:case SyncBatchedLanePriority:return ImmediatePriority;case InputDiscreteHydrationLanePriority:case InputDiscreteLanePriority:case InputContinuousHydrationLanePriority:case InputContinuousLanePriority:return UserBlockingPriority;case DefaultHydrationLanePriority:case DefaultLanePriority:case TransitionHydrationPriority:case TransitionPriority:case SelectiveHydrationLanePriority:case RetryLanePriority:return NormalPriority;case IdleHydrationLanePriority:case IdleLanePriority:case OffscreenLanePriority:return IdlePriority;case NoLanePriority:return NoPriority;default:{{throw Error("Invalid update priority: "+lanePriority+". This is a bug in React.");}}}}function getNextLanes(root,wipLanes){// Early bailout if there's no pending work left.
var pendingLanes=root.pendingLanes;if(pendingLanes===NoLanes){return_highestLanePriority=NoLanePriority;return NoLanes;}var nextLanes=NoLanes;var nextLanePriority=NoLanePriority;var expiredLanes=root.expiredLanes;var suspendedLanes=root.suspendedLanes;var pingedLanes=root.pingedLanes;// Check if any work has expired.
if(expiredLanes!==NoLanes){nextLanes=expiredLanes;nextLanePriority=return_highestLanePriority=SyncLanePriority;}else {// Do not work on any idle work until all the non-idle work has finished,
// even if the work is suspended.
var nonIdlePendingLanes=pendingLanes&NonIdleLanes;if(nonIdlePendingLanes!==NoLanes){var nonIdleUnblockedLanes=nonIdlePendingLanes&~suspendedLanes;if(nonIdleUnblockedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(nonIdleUnblockedLanes);nextLanePriority=return_highestLanePriority;}else {var nonIdlePingedLanes=nonIdlePendingLanes&pingedLanes;if(nonIdlePingedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(nonIdlePingedLanes);nextLanePriority=return_highestLanePriority;}}}else {// The only remaining work is Idle.
var unblockedLanes=pendingLanes&~suspendedLanes;if(unblockedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(unblockedLanes);nextLanePriority=return_highestLanePriority;}else {if(pingedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(pingedLanes);nextLanePriority=return_highestLanePriority;}}}}if(nextLanes===NoLanes){// This should only be reachable if we're suspended
// TODO: Consider warning in this path if a fallback timer is not scheduled.
return NoLanes;}// If there are higher priority lanes, we'll include them even if they
// are suspended.
nextLanes=pendingLanes&getEqualOrHigherPriorityLanes(nextLanes);// If we're already in the middle of a render, switching lanes will interrupt
// it and we'll lose our progress. We should only do this if the new lanes are
// higher priority.
if(wipLanes!==NoLanes&&wipLanes!==nextLanes&&// If we already suspended with a delay, then interrupting is fine. Don't
// bother waiting until the root is complete.
(wipLanes&suspendedLanes)===NoLanes){getHighestPriorityLanes(wipLanes);var wipLanePriority=return_highestLanePriority;if(nextLanePriority<=wipLanePriority){return wipLanes;}else {return_highestLanePriority=nextLanePriority;}}// Check for entangled lanes and add them to the batch.
//
// A lane is said to be entangled with another when it's not allowed to render
// in a batch that does not also include the other lane. Typically we do this
// when multiple updates have the same source, and we only want to respond to
// the most recent event from that source.
//
// Note that we apply entanglements *after* checking for partial work above.
// This means that if a lane is entangled during an interleaved event while
// it's already rendering, we won't interrupt it. This is intentional, since
// entanglement is usually "best effort": we'll try our best to render the
// lanes in the same batch, but it's not worth throwing out partially
// completed work in order to do it.
//
// For those exceptions where entanglement is semantically important, like
// useMutableSource, we should ensure that there is no partial work at the
// time we apply the entanglement.
var entangledLanes=root.entangledLanes;if(entangledLanes!==NoLanes){var entanglements=root.entanglements;var lanes=nextLanes&entangledLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;nextLanes|=entanglements[index];lanes&=~lane;}}return nextLanes;}function getMostRecentEventTime(root,lanes){var eventTimes=root.eventTimes;var mostRecentEventTime=NoTimestamp;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;var eventTime=eventTimes[index];if(eventTime>mostRecentEventTime){mostRecentEventTime=eventTime;}lanes&=~lane;}return mostRecentEventTime;}function computeExpirationTime(lane,currentTime){// TODO: Expiration heuristic is constant per lane, so could use a map.
getHighestPriorityLanes(lane);var priority=return_highestLanePriority;if(priority>=InputContinuousLanePriority){// User interactions should expire slightly more quickly.
//
// NOTE: This is set to the corresponding constant as in Scheduler.js. When
// we made it larger, a product metric in www regressed, suggesting there's
// a user interaction that's being starved by a series of synchronous
// updates. If that theory is correct, the proper solution is to fix the
// starvation. However, this scenario supports the idea that expiration
// times are an important safeguard when starvation does happen.
//
// Also note that, in the case of user input specifically, this will soon no
// longer be an issue because we plan to make user input synchronous by
// default (until you enter `startTransition`, of course.)
//
// If weren't planning to make these updates synchronous soon anyway, I
// would probably make this number a configurable parameter.
return currentTime+250;}else if(priority>=TransitionPriority){return currentTime+5000;}else {// Anything idle priority or lower should never expire.
return NoTimestamp;}}function markStarvedLanesAsExpired(root,currentTime){// TODO: This gets called every time we yield. We can optimize by storing
// the earliest expiration time on the root. Then use that to quickly bail out
// of this function.
var pendingLanes=root.pendingLanes;var suspendedLanes=root.suspendedLanes;var pingedLanes=root.pingedLanes;var expirationTimes=root.expirationTimes;// Iterate through the pending lanes and check if we've reached their
// expiration time. If so, we'll assume the update is being starved and mark
// it as expired to force it to finish.
var lanes=pendingLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;var expirationTime=expirationTimes[index];if(expirationTime===NoTimestamp){// Found a pending lane with no expiration time. If it's not suspended, or
// if it's pinged, assume it's CPU-bound. Compute a new expiration time
// using the current time.
if((lane&suspendedLanes)===NoLanes||(lane&pingedLanes)!==NoLanes){// Assumes timestamps are monotonically increasing.
expirationTimes[index]=computeExpirationTime(lane,currentTime);}}else if(expirationTime<=currentTime){// This lane expired
root.expiredLanes|=lane;}lanes&=~lane;}}// This returns the highest priority pending lanes regardless of whether they
function getLanesToRetrySynchronouslyOnError(root){var everythingButOffscreen=root.pendingLanes&~OffscreenLane;if(everythingButOffscreen!==NoLanes){return everythingButOffscreen;}if(everythingButOffscreen&OffscreenLane){return OffscreenLane;}return NoLanes;}function returnNextLanesPriority(){return return_highestLanePriority;}function includesNonIdleWork(lanes){return (lanes&NonIdleLanes)!==NoLanes;}function includesOnlyRetries(lanes){return (lanes&RetryLanes)===lanes;}function includesOnlyTransitions(lanes){return (lanes&TransitionLanes)===lanes;}// To ensure consistency across multiple updates in the same event, this should
// be a pure function, so that it always returns the same lane for given inputs.
function findUpdateLane(lanePriority,wipLanes){switch(lanePriority){case NoLanePriority:break;case SyncLanePriority:return SyncLane;case SyncBatchedLanePriority:return SyncBatchedLane;case InputDiscreteLanePriority:{var _lane=pickArbitraryLane(InputDiscreteLanes&~wipLanes);if(_lane===NoLane){// Shift to the next priority level
return findUpdateLane(InputContinuousLanePriority,wipLanes);}return _lane;}case InputContinuousLanePriority:{var _lane2=pickArbitraryLane(InputContinuousLanes&~wipLanes);if(_lane2===NoLane){// Shift to the next priority level
return findUpdateLane(DefaultLanePriority,wipLanes);}return _lane2;}case DefaultLanePriority:{var _lane3=pickArbitraryLane(DefaultLanes&~wipLanes);if(_lane3===NoLane){// If all the default lanes are already being worked on, look for a
// lane in the transition range.
_lane3=pickArbitraryLane(TransitionLanes&~wipLanes);if(_lane3===NoLane){// All the transition lanes are taken, too. This should be very
// rare, but as a last resort, pick a default lane. This will have
// the effect of interrupting the current work-in-progress render.
_lane3=pickArbitraryLane(DefaultLanes);}}return _lane3;}case TransitionPriority:// Should be handled by findTransitionLane instead
case RetryLanePriority:// Should be handled by findRetryLane instead
break;case IdleLanePriority:var lane=pickArbitraryLane(IdleLanes&~wipLanes);if(lane===NoLane){lane=pickArbitraryLane(IdleLanes);}return lane;}{{throw Error("Invalid update priority: "+lanePriority+". This is a bug in React.");}}}// To ensure consistency across multiple updates in the same event, this should
// be pure function, so that it always returns the same lane for given inputs.
function findTransitionLane(wipLanes,pendingLanes){// First look for lanes that are completely unclaimed, i.e. have no
// pending work.
var lane=pickArbitraryLane(TransitionLanes&~pendingLanes);if(lane===NoLane){// If all lanes have pending work, look for a lane that isn't currently
// being worked on.
lane=pickArbitraryLane(TransitionLanes&~wipLanes);if(lane===NoLane){// If everything is being worked on, pick any lane. This has the
// effect of interrupting the current work-in-progress.
lane=pickArbitraryLane(TransitionLanes);}}return lane;}// To ensure consistency across multiple updates in the same event, this should
// be pure function, so that it always returns the same lane for given inputs.
function findRetryLane(wipLanes){// This is a fork of `findUpdateLane` designed specifically for Suspense
// "retries" — a special update that attempts to flip a Suspense boundary
// from its placeholder state to its primary/resolved state.
var lane=pickArbitraryLane(RetryLanes&~wipLanes);if(lane===NoLane){lane=pickArbitraryLane(RetryLanes);}return lane;}function getHighestPriorityLane(lanes){return lanes&-lanes;}function getLowestPriorityLane(lanes){// This finds the most significant non-zero bit.
var index=31-clz32(lanes);return index<0?NoLanes:1<<index;}function getEqualOrHigherPriorityLanes(lanes){return (getLowestPriorityLane(lanes)<<1)-1;}function pickArbitraryLane(lanes){// This wrapper function gets inlined. Only exists so to communicate that it
// doesn't matter which bit is selected; you can pick any bit without
// affecting the algorithms where its used. Here I'm using
// getHighestPriorityLane because it requires the fewest operations.
return getHighestPriorityLane(lanes);}function pickArbitraryLaneIndex(lanes){return 31-clz32(lanes);}function laneToIndex(lane){return pickArbitraryLaneIndex(lane);}function includesSomeLane(a,b){return (a&b)!==NoLanes;}function isSubsetOfLanes(set,subset){return (set&subset)===subset;}function mergeLanes(a,b){return a|b;}function removeLanes(set,subset){return set&~subset;}// Seems redundant, but it changes the type from a single lane (used for
// updates) to a group of lanes (used for flushing work).
function laneToLanes(lane){return lane;}function higherPriorityLane(a,b){// This works because the bit ranges decrease in priority as you go left.
return a!==NoLane&&a<b?a:b;}function createLaneMap(initial){// Intentionally pushing one by one.
// https://v8.dev/blog/elements-kinds#avoid-creating-holes
var laneMap=[];for(var i=0;i<TotalLanes;i++){laneMap.push(initial);}return laneMap;}function markRootUpdated(root,updateLane,eventTime){root.pendingLanes|=updateLane;// TODO: Theoretically, any update to any lane can unblock any other lane. But
// it's not practical to try every single possible combination. We need a
// heuristic to decide which lanes to attempt to render, and in which batches.
// For now, we use the same heuristic as in the old ExpirationTimes model:
// retry any lane at equal or lower priority, but don't try updates at higher
// priority without also including the lower priority updates. This works well
// when considering updates across different priority levels, but isn't
// sufficient for updates within the same priority, since we want to treat
// those updates as parallel.
// Unsuspend any update at equal or lower priority.
var higherPriorityLanes=updateLane-1;// Turns 0b1000 into 0b0111
root.suspendedLanes&=higherPriorityLanes;root.pingedLanes&=higherPriorityLanes;var eventTimes=root.eventTimes;var index=laneToIndex(updateLane);// We can always overwrite an existing timestamp because we prefer the most
// recent event, and we assume time is monotonically increasing.
eventTimes[index]=eventTime;}function markRootSuspended(root,suspendedLanes){root.suspendedLanes|=suspendedLanes;root.pingedLanes&=~suspendedLanes;// The suspended lanes are no longer CPU-bound. Clear their expiration times.
var expirationTimes=root.expirationTimes;var lanes=suspendedLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;expirationTimes[index]=NoTimestamp;lanes&=~lane;}}function markRootPinged(root,pingedLanes,eventTime){root.pingedLanes|=root.suspendedLanes&pingedLanes;}function markDiscreteUpdatesExpired(root){root.expiredLanes|=InputDiscreteLanes&root.pendingLanes;}function hasDiscreteLanes(lanes){return (lanes&InputDiscreteLanes)!==NoLanes;}function markRootMutableRead(root,updateLane){root.mutableReadLanes|=updateLane&root.pendingLanes;}function markRootFinished(root,remainingLanes){var noLongerPendingLanes=root.pendingLanes&~remainingLanes;root.pendingLanes=remainingLanes;// Let's try everything again
root.suspendedLanes=0;root.pingedLanes=0;root.expiredLanes&=remainingLanes;root.mutableReadLanes&=remainingLanes;root.entangledLanes&=remainingLanes;var entanglements=root.entanglements;var eventTimes=root.eventTimes;var expirationTimes=root.expirationTimes;// Clear the lanes that no longer have pending work
var lanes=noLongerPendingLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;entanglements[index]=NoLanes;eventTimes[index]=NoTimestamp;expirationTimes[index]=NoTimestamp;lanes&=~lane;}}function markRootEntangled(root,entangledLanes){root.entangledLanes|=entangledLanes;var entanglements=root.entanglements;var lanes=entangledLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;entanglements[index]|=entangledLanes;lanes&=~lane;}}var clz32=Math.clz32?Math.clz32:clz32Fallback;// Count leading zeros. Only used on lanes, so assume input is an integer.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
var log=Math.log;var LN2=Math.LN2;function clz32Fallback(lanes){if(lanes===0){return 32;}return 31-(log(lanes)/LN2|0)|0;}// Intentionally not named imports because Rollup would use dynamic dispatch for
var UserBlockingPriority$1=Scheduler.unstable_UserBlockingPriority,runWithPriority=Scheduler.unstable_runWithPriority;// TODO: can we stop exporting these?
var _enabled=true;// This is exported in FB builds for use by legacy FB layer infra.
// We'd like to remove this but it's not clear if this is safe.
function setEnabled(enabled){_enabled=!!enabled;}function isEnabled(){return _enabled;}function createEventListenerWrapperWithPriority(targetContainer,domEventName,eventSystemFlags){var eventPriority=getEventPriorityForPluginSystem(domEventName);var listenerWrapper;switch(eventPriority){case DiscreteEvent:listenerWrapper=dispatchDiscreteEvent;break;case UserBlockingEvent:listenerWrapper=dispatchUserBlockingUpdate;break;case ContinuousEvent:default:listenerWrapper=dispatchEvent;break;}return listenerWrapper.bind(null,domEventName,eventSystemFlags,targetContainer);}function dispatchDiscreteEvent(domEventName,eventSystemFlags,container,nativeEvent){{flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);}discreteUpdates(dispatchEvent,domEventName,eventSystemFlags,container,nativeEvent);}function dispatchUserBlockingUpdate(domEventName,eventSystemFlags,container,nativeEvent){{runWithPriority(UserBlockingPriority$1,dispatchEvent.bind(null,domEventName,eventSystemFlags,container,nativeEvent));}}function dispatchEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent){if(!_enabled){return;}var allowReplay=true;{// TODO: replaying capture phase events is currently broken
// because we used to do it during top-level native bubble handlers
// but now we use different bubble and capture handlers.
// In eager mode, we attach capture listeners early, so we need
// to filter them out until we fix the logic to handle them correctly.
// This could've been outside the flag but I put it inside to reduce risk.
allowReplay=(eventSystemFlags&IS_CAPTURE_PHASE)===0;}if(allowReplay&&hasQueuedDiscreteEvents()&&isReplayableDiscreteEvent(domEventName)){// If we already have a queue of discrete events, and this is another discrete
// event, then we can't dispatch it regardless of its target, since they
// need to dispatch in order.
queueDiscreteEvent(null,// Flags that we're not actually blocked on anything as far as we know.
domEventName,eventSystemFlags,targetContainer,nativeEvent);return;}var blockedOn=attemptToDispatchEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent);if(blockedOn===null){// We successfully dispatched this event.
if(allowReplay){clearIfContinuousEvent(domEventName,nativeEvent);}return;}if(allowReplay){if(isReplayableDiscreteEvent(domEventName)){// This this to be replayed later once the target is available.
queueDiscreteEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent);return;}if(queueIfContinuousEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent)){return;}// We need to clear only if we didn't queue because
// queueing is accummulative.
clearIfContinuousEvent(domEventName,nativeEvent);}// This is not replayable so we'll invoke it but without a target,
// in case the event system needs to trace it.
dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,null,targetContainer);}// Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.
function attemptToDispatchEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent){// TODO: Warn if _enabled is false.
var nativeEventTarget=getEventTarget(nativeEvent);var targetInst=getClosestInstanceFromNode(nativeEventTarget);if(targetInst!==null){var nearestMounted=getNearestMountedFiber(targetInst);if(nearestMounted===null){// This tree has been unmounted already. Dispatch without a target.
targetInst=null;}else {var tag=nearestMounted.tag;if(tag===SuspenseComponent){var instance=getSuspenseInstanceFromFiber(nearestMounted);if(instance!==null){// Queue the event to be replayed later. Abort dispatching since we
// don't want this event dispatched twice through the event system.
// TODO: If this is the first discrete event in the queue. Schedule an increased
// priority for this boundary.
return instance;}// This shouldn't happen, something went wrong but to avoid blocking
// the whole system, dispatch the event without a target.
// TODO: Warn.
targetInst=null;}else if(tag===HostRoot){var root=nearestMounted.stateNode;if(root.hydrate){// If this happens during a replay something went wrong and it might block
// the whole system.
return getContainerFromFiber(nearestMounted);}targetInst=null;}else if(nearestMounted!==targetInst){// If we get an event (ex: img onload) before committing that
// component's mount, ignore it for now (that is, treat it as if it was an
// event on a non-React tree). We might also consider queueing events and
// dispatching them after the mount.
targetInst=null;}}}dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,targetInst,targetContainer);// We're not blocked on anything.
return null;}function addEventBubbleListener(target,eventType,listener){target.addEventListener(eventType,listener,false);return listener;}function addEventCaptureListener(target,eventType,listener){target.addEventListener(eventType,listener,true);return listener;}function addEventCaptureListenerWithPassiveFlag(target,eventType,listener,passive){target.addEventListener(eventType,listener,{capture:true,passive:passive});return listener;}function addEventBubbleListenerWithPassiveFlag(target,eventType,listener,passive){target.addEventListener(eventType,listener,{passive:passive});return listener;}/**
* These variables store information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
*
*/var root=null;var startText=null;var fallbackText=null;function initialize(nativeEventTarget){root=nativeEventTarget;startText=getText();return true;}function reset(){root=null;startText=null;fallbackText=null;}function getData(){if(fallbackText){return fallbackText;}var start;var startValue=startText;var startLength=startValue.length;var end;var endValue=getText();var endLength=endValue.length;for(start=0;start<startLength;start++){if(startValue[start]!==endValue[start]){break;}}var minEnd=startLength-start;for(end=1;end<=minEnd;end++){if(startValue[startLength-end]!==endValue[endLength-end]){break;}}var sliceTail=end>1?1-end:undefined;fallbackText=endValue.slice(start,sliceTail);return fallbackText;}function getText(){if('value'in root){return root.value;}return root.textContent;}/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/function getEventCharCode(nativeEvent){var charCode;var keyCode=nativeEvent.keyCode;if('charCode'in nativeEvent){charCode=nativeEvent.charCode;// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if(charCode===0&&keyCode===13){charCode=13;}}else {// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode=keyCode;}// IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
// report Enter as charCode 10 when ctrl is pressed.
if(charCode===10){charCode=13;}// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if(charCode>=32||charCode===13){return charCode;}return 0;}function functionThatReturnsTrue(){return true;}function functionThatReturnsFalse(){return false;}// This is intentionally a factory so that we have different returned constructors.
// If we had a single constructor, it would be megamorphic and engines would deopt.
function createSyntheticEvent(Interface){/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*/function SyntheticBaseEvent(reactName,reactEventType,targetInst,nativeEvent,nativeEventTarget){this._reactName=reactName;this._targetInst=targetInst;this.type=reactEventType;this.nativeEvent=nativeEvent;this.target=nativeEventTarget;this.currentTarget=null;for(var _propName in Interface){if(!Interface.hasOwnProperty(_propName)){continue;}var normalize=Interface[_propName];if(normalize){this[_propName]=normalize(nativeEvent);}else {this[_propName]=nativeEvent[_propName];}}var defaultPrevented=nativeEvent.defaultPrevented!=null?nativeEvent.defaultPrevented:nativeEvent.returnValue===false;if(defaultPrevented){this.isDefaultPrevented=functionThatReturnsTrue;}else {this.isDefaultPrevented=functionThatReturnsFalse;}this.isPropagationStopped=functionThatReturnsFalse;return this;}_assign(SyntheticBaseEvent.prototype,{preventDefault:function(){this.defaultPrevented=true;var event=this.nativeEvent;if(!event){return;}if(event.preventDefault){event.preventDefault();// $FlowFixMe - flow is not aware of `unknown` in IE
}else if(typeof event.returnValue!=='unknown'){event.returnValue=false;}this.isDefaultPrevented=functionThatReturnsTrue;},stopPropagation:function(){var event=this.nativeEvent;if(!event){return;}if(event.stopPropagation){event.stopPropagation();// $FlowFixMe - flow is not aware of `unknown` in IE
}else if(typeof event.cancelBubble!=='unknown'){// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble=true;}this.isPropagationStopped=functionThatReturnsTrue;},/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/persist:function(){// Modern event system doesn't use pooling.
},/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/isPersistent:functionThatReturnsTrue});return SyntheticBaseEvent;}/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/var EventInterface={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(event){return event.timeStamp||Date.now();},defaultPrevented:0,isTrusted:0};var SyntheticEvent=createSyntheticEvent(EventInterface);var UIEventInterface=_assign({},EventInterface,{view:0,detail:0});var SyntheticUIEvent=createSyntheticEvent(UIEventInterface);var lastMovementX;var lastMovementY;var lastMouseEvent;function updateMouseMovementPolyfillState(event){if(event!==lastMouseEvent){if(lastMouseEvent&&event.type==='mousemove'){lastMovementX=event.screenX-lastMouseEvent.screenX;lastMovementY=event.screenY-lastMouseEvent.screenY;}else {lastMovementX=0;lastMovementY=0;}lastMouseEvent=event;}}/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/var MouseEventInterface=_assign({},UIEventInterface,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:getEventModifierState,button:0,buttons:0,relatedTarget:function(event){if(event.relatedTarget===undefined)return event.fromElement===event.srcElement?event.toElement:event.fromElement;return event.relatedTarget;},movementX:function(event){if('movementX'in event){return event.movementX;}updateMouseMovementPolyfillState(event);return lastMovementX;},movementY:function(event){if('movementY'in event){return event.movementY;}// Don't need to call updateMouseMovementPolyfillState() here
// because it's guaranteed to have already run when movementX
// was copied.
return lastMovementY;}});var SyntheticMouseEvent=createSyntheticEvent(MouseEventInterface);/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/var DragEventInterface=_assign({},MouseEventInterface,{dataTransfer:0});var SyntheticDragEvent=createSyntheticEvent(DragEventInterface);/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/var FocusEventInterface=_assign({},UIEventInterface,{relatedTarget:0});var SyntheticFocusEvent=createSyntheticEvent(FocusEventInterface);/**
* @interface Event
* @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
* @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
*/var AnimationEventInterface=_assign({},EventInterface,{animationName:0,elapsedTime:0,pseudoElement:0});var SyntheticAnimationEvent=createSyntheticEvent(AnimationEventInterface);/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/var ClipboardEventInterface=_assign({},EventInterface,{clipboardData:function(event){return 'clipboardData'in event?event.clipboardData:window.clipboardData;}});var SyntheticClipboardEvent=createSyntheticEvent(ClipboardEventInterface);/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/var CompositionEventInterface=_assign({},EventInterface,{data:0});var SyntheticCompositionEvent=createSyntheticEvent(CompositionEventInterface);/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/ // Happens to share the same list for now.
var SyntheticInputEvent=SyntheticCompositionEvent;/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/var normalizeKey={Esc:'Escape',Spacebar:' ',Left:'ArrowLeft',Up:'ArrowUp',Right:'ArrowRight',Down:'ArrowDown',Del:'Delete',Win:'OS',Menu:'ContextMenu',Apps:'ContextMenu',Scroll:'ScrollLock',MozPrintableKey:'Unidentified'};/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/var translateToKey={'8':'Backspace','9':'Tab','12':'Clear','13':'Enter','16':'Shift','17':'Control','18':'Alt','19':'Pause','20':'CapsLock','27':'Escape','32':' ','33':'PageUp','34':'PageDown','35':'End','36':'Home','37':'ArrowLeft','38':'ArrowUp','39':'ArrowRight','40':'ArrowDown','45':'Insert','46':'Delete','112':'F1','113':'F2','114':'F3','115':'F4','116':'F5','117':'F6','118':'F7','119':'F8','120':'F9','121':'F10','122':'F11','123':'F12','144':'NumLock','145':'ScrollLock','224':'Meta'};/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/function getEventKey(nativeEvent){if(nativeEvent.key){// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key=normalizeKey[nativeEvent.key]||nativeEvent.key;if(key!=='Unidentified'){return key;}}// Browser does not implement `key`, polyfill as much of it as we can.
if(nativeEvent.type==='keypress'){var charCode=getEventCharCode(nativeEvent);// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode===13?'Enter':String.fromCharCode(charCode);}if(nativeEvent.type==='keydown'||nativeEvent.type==='keyup'){// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode]||'Unidentified';}return '';}/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/var modifierKeyToProp={Alt:'altKey',Control:'ctrlKey',Meta:'metaKey',Shift:'shiftKey'};// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
// getModifierState. If getModifierState is not supported, we map it to a set of
// modifier keys exposed by the event. In this case, Lock-keys are not supported.
function modifierStateGetter(keyArg){var syntheticEvent=this;var nativeEvent=syntheticEvent.nativeEvent;if(nativeEvent.getModifierState){return nativeEvent.getModifierState(keyArg);}var keyProp=modifierKeyToProp[keyArg];return keyProp?!!nativeEvent[keyProp]:false;}function getEventModifierState(nativeEvent){return modifierStateGetter;}/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/var KeyboardEventInterface=_assign({},UIEventInterface,{key:getEventKey,code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:getEventModifierState,// Legacy Interface
charCode:function(event){// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if(event.type==='keypress'){return getEventCharCode(event);}return 0;},keyCode:function(event){// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if(event.type==='keydown'||event.type==='keyup'){return event.keyCode;}return 0;},which:function(event){// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if(event.type==='keypress'){return getEventCharCode(event);}if(event.type==='keydown'||event.type==='keyup'){return event.keyCode;}return 0;}});var SyntheticKeyboardEvent=createSyntheticEvent(KeyboardEventInterface);/**
* @interface PointerEvent
* @see http://www.w3.org/TR/pointerevents/
*/var PointerEventInterface=_assign({},MouseEventInterface,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0});var SyntheticPointerEvent=createSyntheticEvent(PointerEventInterface);/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/var TouchEventInterface=_assign({},UIEventInterface,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:getEventModifierState});var SyntheticTouchEvent=createSyntheticEvent(TouchEventInterface);/**
* @interface Event
* @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
* @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
*/var TransitionEventInterface=_assign({},EventInterface,{propertyName:0,elapsedTime:0,pseudoElement:0});var SyntheticTransitionEvent=createSyntheticEvent(TransitionEventInterface);/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/var WheelEventInterface=_assign({},MouseEventInterface,{deltaX:function(event){return 'deltaX'in event?event.deltaX:// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX'in event?-event.wheelDeltaX:0;},deltaY:function(event){return 'deltaY'in event?event.deltaY:// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY'in event?-event.wheelDeltaY:// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta'in event?-event.wheelDelta:0;},deltaZ:0,// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode:0});var SyntheticWheelEvent=createSyntheticEvent(WheelEventInterface);var END_KEYCODES=[9,13,27,32];// Tab, Return, Esc, Space
var START_KEYCODE=229;var canUseCompositionEvent=canUseDOM&&'CompositionEvent'in window;var documentMode=null;if(canUseDOM&&'documentMode'in document){documentMode=document.documentMode;}// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent=canUseDOM&&'TextEvent'in window&&!documentMode;// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData=canUseDOM&&(!canUseCompositionEvent||documentMode&&documentMode>8&&documentMode<=11);var SPACEBAR_CODE=32;var SPACEBAR_CHAR=String.fromCharCode(SPACEBAR_CODE);function registerEvents(){registerTwoPhaseEvent('onBeforeInput',['compositionend','keypress','textInput','paste']);registerTwoPhaseEvent('onCompositionEnd',['compositionend','focusout','keydown','keypress','keyup','mousedown']);registerTwoPhaseEvent('onCompositionStart',['compositionstart','focusout','keydown','keypress','keyup','mousedown']);registerTwoPhaseEvent('onCompositionUpdate',['compositionupdate','focusout','keydown','keypress','keyup','mousedown']);}// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress=false;/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/function isKeypressCommand(nativeEvent){return (nativeEvent.ctrlKey||nativeEvent.altKey||nativeEvent.metaKey)&&// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey&&nativeEvent.altKey);}/**
* Translate native top level events into event types.
*/function getCompositionEventType(domEventName){switch(domEventName){case'compositionstart':return 'onCompositionStart';case'compositionend':return 'onCompositionEnd';case'compositionupdate':return 'onCompositionUpdate';}}/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*/function isFallbackCompositionStart(domEventName,nativeEvent){return domEventName==='keydown'&&nativeEvent.keyCode===START_KEYCODE;}/**
* Does our fallback mode think that this event is the end of composition?
*/function isFallbackCompositionEnd(domEventName,nativeEvent){switch(domEventName){case'keyup':// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode)!==-1;case'keydown':// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode!==START_KEYCODE;case'keypress':case'mousedown':case'focusout':// Events are not possible without cancelling IME.
return true;default:return false;}}/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/function getDataFromCustomEvent(nativeEvent){var detail=nativeEvent.detail;if(typeof detail==='object'&&'data'in detail){return detail.data;}return null;}/**
* Check if a composition event was triggered by Korean IME.
* Our fallback mode does not work well with IE's Korean IME,
* so just use native composition events when Korean IME is used.
* Although CompositionEvent.locale property is deprecated,
* it is available in IE, where our fallback mode is enabled.
*
* @param {object} nativeEvent
* @return {boolean}
*/function isUsingKoreanIME(nativeEvent){return nativeEvent.locale==='ko';}// Track the current IME composition status, if any.
var isComposing=false;/**
* @return {?object} A SyntheticCompositionEvent.
*/function extractCompositionEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget){var eventType;var fallbackData;if(canUseCompositionEvent){eventType=getCompositionEventType(domEventName);}else if(!isComposing){if(isFallbackCompositionStart(domEventName,nativeEvent)){eventType='onCompositionStart';}}else if(isFallbackCompositionEnd(domEventName,nativeEvent)){eventType='onCompositionEnd';}if(!eventType){return null;}if(useFallbackCompositionData&&!isUsingKoreanIME(nativeEvent)){// The current composition is stored statically and must not be
// overwritten while composition continues.
if(!isComposing&&eventType==='onCompositionStart'){isComposing=initialize(nativeEventTarget);}else if(eventType==='onCompositionEnd'){if(isComposing){fallbackData=getData();}}}var listeners=accumulateTwoPhaseListeners(targetInst,eventType);if(listeners.length>0){var event=new SyntheticCompositionEvent(eventType,domEventName,null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:event,listeners:listeners});if(fallbackData){// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data=fallbackData;}else {var customData=getDataFromCustomEvent(nativeEvent);if(customData!==null){event.data=customData;}}}}function getNativeBeforeInputChars(domEventName,nativeEvent){switch(domEventName){case'compositionend':return getDataFromCustomEvent(nativeEvent);case'keypress':/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/var which=nativeEvent.which;if(which!==SPACEBAR_CODE){return null;}hasSpaceKeypress=true;return SPACEBAR_CHAR;case'textInput':// Record the characters to be added to the DOM.
var chars=nativeEvent.data;// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to ignore it.
if(chars===SPACEBAR_CHAR&&hasSpaceKeypress){return null;}return chars;default:// For other native event types, do nothing.
return null;}}/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*/function getFallbackBeforeInputChars(domEventName,nativeEvent){// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if(isComposing){if(domEventName==='compositionend'||!canUseCompositionEvent&&isFallbackCompositionEnd(domEventName,nativeEvent)){var chars=getData();reset();isComposing=false;return chars;}return null;}switch(domEventName){case'paste':// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;case'keypress':/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/if(!isKeypressCommand(nativeEvent)){// IE fires the `keypress` event when a user types an emoji via
// Touch keyboard of Windows. In such a case, the `char` property
// holds an emoji character like `\uD83D\uDE0A`. Because its length
// is 2, the property `which` does not represent an emoji correctly.
// In such a case, we directly return the `char` property instead of
// using `which`.
if(nativeEvent.char&&nativeEvent.char.length>1){return nativeEvent.char;}else if(nativeEvent.which){return String.fromCharCode(nativeEvent.which);}}return null;case'compositionend':return useFallbackCompositionData&&!isUsingKoreanIME(nativeEvent)?null:nativeEvent.data;default:return null;}}/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @return {?object} A SyntheticInputEvent.
*/function extractBeforeInputEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget){var chars;if(canUseTextInputEvent){chars=getNativeBeforeInputChars(domEventName,nativeEvent);}else {chars=getFallbackBeforeInputChars(domEventName,nativeEvent);}// If no characters are being inserted, no BeforeInput event should
// be fired.
if(!chars){return null;}var listeners=accumulateTwoPhaseListeners(targetInst,'onBeforeInput');if(listeners.length>0){var event=new SyntheticInputEvent('onBeforeInput','beforeinput',null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:event,listeners:listeners});event.data=chars;}}/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/function extractEvents(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){extractCompositionEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractBeforeInputEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);}/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/var supportedInputTypes={color:true,date:true,datetime:true,'datetime-local':true,email:true,month:true,number:true,password:true,range:true,search:true,tel:true,text:true,time:true,url:true,week:true};function isTextInputElement(elem){var nodeName=elem&&elem.nodeName&&elem.nodeName.toLowerCase();if(nodeName==='input'){return !!supportedInputTypes[elem.type];}if(nodeName==='textarea'){return true;}return false;}/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/function isEventSupported(eventNameSuffix){if(!canUseDOM){return false;}var eventName='on'+eventNameSuffix;var isSupported=(eventName in document);if(!isSupported){var element=document.createElement('div');element.setAttribute(eventName,'return;');isSupported=typeof element[eventName]==='function';}return isSupported;}function registerEvents$1(){registerTwoPhaseEvent('onChange',['change','click','focusin','focusout','input','keydown','keyup','selectionchange']);}function createAndAccumulateChangeEvent(dispatchQueue,inst,nativeEvent,target){// Flag this event loop as needing state restore.
enqueueStateRestore(target);var listeners=accumulateTwoPhaseListeners(inst,'onChange');if(listeners.length>0){var event=new SyntheticEvent('onChange','change',null,nativeEvent,target);dispatchQueue.push({event:event,listeners:listeners});}}/**
* For IE shims
*/var activeElement=null;var activeElementInst=null;/**
* SECTION: handle `change` event
*/function shouldUseChangeEvent(elem){var nodeName=elem.nodeName&&elem.nodeName.toLowerCase();return nodeName==='select'||nodeName==='input'&&elem.type==='file';}function manualDispatchChangeEvent(nativeEvent){var dispatchQueue=[];createAndAccumulateChangeEvent(dispatchQueue,activeElementInst,nativeEvent,getEventTarget(nativeEvent));// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
batchedUpdates(runEventInBatch,dispatchQueue);}function runEventInBatch(dispatchQueue){processDispatchQueue(dispatchQueue,0);}function getInstIfValueChanged(targetInst){var targetNode=getNodeFromInstance(targetInst);if(updateValueIfChanged(targetNode)){return targetInst;}}function getTargetInstForChangeEvent(domEventName,targetInst){if(domEventName==='change'){return targetInst;}}/**
* SECTION: handle `input` event
*/var isInputEventSupported=false;if(canUseDOM){// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
isInputEventSupported=isEventSupported('input')&&(!document.documentMode||document.documentMode>9);}/**
* (For IE <=9) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/function startWatchingForValueChange(target,targetInst){activeElement=target;activeElementInst=targetInst;activeElement.attachEvent('onpropertychange',handlePropertyChange);}/**
* (For IE <=9) Removes the event listeners from the currently-tracked element,
* if any exists.
*/function stopWatchingForValueChange(){if(!activeElement){return;}activeElement.detachEvent('onpropertychange',handlePropertyChange);activeElement=null;activeElementInst=null;}/**
* (For IE <=9) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/function handlePropertyChange(nativeEvent){if(nativeEvent.propertyName!=='value'){return;}if(getInstIfValueChanged(activeElementInst)){manualDispatchChangeEvent(nativeEvent);}}function handleEventsForInputEventPolyfill(domEventName,target,targetInst){if(domEventName==='focusin'){// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();startWatchingForValueChange(target,targetInst);}else if(domEventName==='focusout'){stopWatchingForValueChange();}}// For IE8 and IE9.
function getTargetInstForInputEventPolyfill(domEventName,targetInst){if(domEventName==='selectionchange'||domEventName==='keyup'||domEventName==='keydown'){// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
return getInstIfValueChanged(activeElementInst);}}/**
* SECTION: handle `click` event
*/function shouldUseClickEvent(elem){// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
var nodeName=elem.nodeName;return nodeName&&nodeName.toLowerCase()==='input'&&(elem.type==='checkbox'||elem.type==='radio');}function getTargetInstForClickEvent(domEventName,targetInst){if(domEventName==='click'){return getInstIfValueChanged(targetInst);}}function getTargetInstForInputOrChangeEvent(domEventName,targetInst){if(domEventName==='input'||domEventName==='change'){return getInstIfValueChanged(targetInst);}}function handleControlledInputBlur(node){var state=node._wrapperState;if(!state||!state.controlled||node.type!=='number'){return;}{// If controlled, assign the value attribute to the current value on blur
setDefaultValue(node,'number',node.value);}}/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/function extractEvents$1(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var targetNode=targetInst?getNodeFromInstance(targetInst):window;var getTargetInstFunc,handleEventFunc;if(shouldUseChangeEvent(targetNode)){getTargetInstFunc=getTargetInstForChangeEvent;}else if(isTextInputElement(targetNode)){if(isInputEventSupported){getTargetInstFunc=getTargetInstForInputOrChangeEvent;}else {getTargetInstFunc=getTargetInstForInputEventPolyfill;handleEventFunc=handleEventsForInputEventPolyfill;}}else if(shouldUseClickEvent(targetNode)){getTargetInstFunc=getTargetInstForClickEvent;}if(getTargetInstFunc){var inst=getTargetInstFunc(domEventName,targetInst);if(inst){createAndAccumulateChangeEvent(dispatchQueue,inst,nativeEvent,nativeEventTarget);return;}}if(handleEventFunc){handleEventFunc(domEventName,targetNode,targetInst);}// When blurring, set the value attribute for number inputs
if(domEventName==='focusout'){handleControlledInputBlur(targetNode);}}function registerEvents$2(){registerDirectEvent('onMouseEnter',['mouseout','mouseover']);registerDirectEvent('onMouseLeave',['mouseout','mouseover']);registerDirectEvent('onPointerEnter',['pointerout','pointerover']);registerDirectEvent('onPointerLeave',['pointerout','pointerover']);}/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/function extractEvents$2(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var isOverEvent=domEventName==='mouseover'||domEventName==='pointerover';var isOutEvent=domEventName==='mouseout'||domEventName==='pointerout';if(isOverEvent&&(eventSystemFlags&IS_REPLAYED)===0){// If this is an over event with a target, we might have already dispatched
// the event in the out event of the other target. If this is replayed,
// then it's because we couldn't dispatch against this target previously
// so we have to do it now instead.
var related=nativeEvent.relatedTarget||nativeEvent.fromElement;if(related){// If the related node is managed by React, we can assume that we have
// already dispatched the corresponding events during its mouseout.
if(getClosestInstanceFromNode(related)||isContainerMarkedAsRoot(related)){return;}}}if(!isOutEvent&&!isOverEvent){// Must not be a mouse or pointer in or out - ignoring.
return;}var win;// TODO: why is this nullable in the types but we read from it?
if(nativeEventTarget.window===nativeEventTarget){// `nativeEventTarget` is probably a window object.
win=nativeEventTarget;}else {// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc=nativeEventTarget.ownerDocument;if(doc){win=doc.defaultView||doc.parentWindow;}else {win=window;}}var from;var to;if(isOutEvent){var _related=nativeEvent.relatedTarget||nativeEvent.toElement;from=targetInst;to=_related?getClosestInstanceFromNode(_related):null;if(to!==null){var nearestMounted=getNearestMountedFiber(to);if(to!==nearestMounted||to.tag!==HostComponent&&to.tag!==HostText){to=null;}}}else {// Moving to a node from outside the window.
from=null;to=targetInst;}if(from===to){// Nothing pertains to our managed components.
return;}var SyntheticEventCtor=SyntheticMouseEvent;var leaveEventType='onMouseLeave';var enterEventType='onMouseEnter';var eventTypePrefix='mouse';if(domEventName==='pointerout'||domEventName==='pointerover'){SyntheticEventCtor=SyntheticPointerEvent;leaveEventType='onPointerLeave';enterEventType='onPointerEnter';eventTypePrefix='pointer';}var fromNode=from==null?win:getNodeFromInstance(from);var toNode=to==null?win:getNodeFromInstance(to);var leave=new SyntheticEventCtor(leaveEventType,eventTypePrefix+'leave',from,nativeEvent,nativeEventTarget);leave.target=fromNode;leave.relatedTarget=toNode;var enter=null;// We should only process this nativeEvent if we are processing
// the first ancestor. Next time, we will ignore the event.
var nativeTargetInst=getClosestInstanceFromNode(nativeEventTarget);if(nativeTargetInst===targetInst){var enterEvent=new SyntheticEventCtor(enterEventType,eventTypePrefix+'enter',to,nativeEvent,nativeEventTarget);enterEvent.target=toNode;enterEvent.relatedTarget=fromNode;enter=enterEvent;}accumulateEnterLeaveTwoPhaseListeners(dispatchQueue,leave,enter,from,to);}/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y// eslint-disable-line no-self-compare
;}var objectIs=typeof Object.is==='function'?Object.is:is;var hasOwnProperty$2=Object.prototype.hasOwnProperty;/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/function shallowEqual(objA,objB){if(objectIs(objA,objB)){return true;}if(typeof objA!=='object'||objA===null||typeof objB!=='object'||objB===null){return false;}var keysA=Object.keys(objA);var keysB=Object.keys(objB);if(keysA.length!==keysB.length){return false;}// Test for A's keys different from B.
for(var i=0;i<keysA.length;i++){if(!hasOwnProperty$2.call(objB,keysA[i])||!objectIs(objA[keysA[i]],objB[keysA[i]])){return false;}}return true;}/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/function getLeafNode(node){while(node&&node.firstChild){node=node.firstChild;}return node;}/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/function getSiblingNode(node){while(node){if(node.nextSibling){return node.nextSibling;}node=node.parentNode;}}/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/function getNodeForCharacterOffset(root,offset){var node=getLeafNode(root);var nodeStart=0;var nodeEnd=0;while(node){if(node.nodeType===TEXT_NODE){nodeEnd=nodeStart+node.textContent.length;if(nodeStart<=offset&&nodeEnd>=offset){return {node:node,offset:offset-nodeStart};}nodeStart=nodeEnd;}node=getLeafNode(getSiblingNode(node));}}/**
* @param {DOMElement} outerNode
* @return {?object}
*/function getOffsets(outerNode){var ownerDocument=outerNode.ownerDocument;var win=ownerDocument&&ownerDocument.defaultView||window;var selection=win.getSelection&&win.getSelection();if(!selection||selection.rangeCount===0){return null;}var anchorNode=selection.anchorNode,anchorOffset=selection.anchorOffset,focusNode=selection.focusNode,focusOffset=selection.focusOffset;// In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
// up/down buttons on an <input type="number">. Anonymous divs do not seem to
// expose properties, triggering a "Permission denied error" if any of its
// properties are accessed. The only seemingly possible way to avoid erroring
// is to access a property that typically works for non-anonymous divs and
// catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try{/* eslint-disable no-unused-expressions */anchorNode.nodeType;focusNode.nodeType;/* eslint-enable no-unused-expressions */}catch(e){return null;}return getModernOffsetsFromPoints(outerNode,anchorNode,anchorOffset,focusNode,focusOffset);}/**
* Returns {start, end} where `start` is the character/codepoint index of
* (anchorNode, anchorOffset) within the textContent of `outerNode`, and
* `end` is the index of (focusNode, focusOffset).
*
* Returns null if you pass in garbage input but we should probably just crash.
*
* Exported only for testing.
*/function getModernOffsetsFromPoints(outerNode,anchorNode,anchorOffset,focusNode,focusOffset){var length=0;var start=-1;var end=-1;var indexWithinAnchor=0;var indexWithinFocus=0;var node=outerNode;var parentNode=null;outer:while(true){var next=null;while(true){if(node===anchorNode&&(anchorOffset===0||node.nodeType===TEXT_NODE)){start=length+anchorOffset;}if(node===focusNode&&(focusOffset===0||node.nodeType===TEXT_NODE)){end=length+focusOffset;}if(node.nodeType===TEXT_NODE){length+=node.nodeValue.length;}if((next=node.firstChild)===null){break;}// Moving from `node` to its first child `next`.
parentNode=node;node=next;}while(true){if(node===outerNode){// If `outerNode` has children, this is always the second time visiting
// it. If it has no children, this is still the first loop, and the only
// valid selection is anchorNode and focusNode both equal to this node
// and both offsets 0, in which case we will have handled above.
break outer;}if(parentNode===anchorNode&&++indexWithinAnchor===anchorOffset){start=length;}if(parentNode===focusNode&&++indexWithinFocus===focusOffset){end=length;}if((next=node.nextSibling)!==null){break;}node=parentNode;parentNode=node.parentNode;}// Moving from `node` to its next sibling `next`.
node=next;}if(start===-1||end===-1){// This should never happen. (Would happen if the anchor/focus nodes aren't
// actually inside the passed-in node.)
return null;}return {start:start,end:end};}/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programmatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/function setOffsets(node,offsets){var doc=node.ownerDocument||document;var win=doc&&doc.defaultView||window;// Edge fails with "Object expected" in some scenarios.
// (For instance: TinyMCE editor used in a list component that supports pasting to add more,
// fails when pasting 100+ items)
if(!win.getSelection){return;}var selection=win.getSelection();var length=node.textContent.length;var start=Math.min(offsets.start,length);var end=offsets.end===undefined?start:Math.min(offsets.end,length);// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if(!selection.extend&&start>end){var temp=end;end=start;start=temp;}var startMarker=getNodeForCharacterOffset(node,start);var endMarker=getNodeForCharacterOffset(node,end);if(startMarker&&endMarker){if(selection.rangeCount===1&&selection.anchorNode===startMarker.node&&selection.anchorOffset===startMarker.offset&&selection.focusNode===endMarker.node&&selection.focusOffset===endMarker.offset){return;}var range=doc.createRange();range.setStart(startMarker.node,startMarker.offset);selection.removeAllRanges();if(start>end){selection.addRange(range);selection.extend(endMarker.node,endMarker.offset);}else {range.setEnd(endMarker.node,endMarker.offset);selection.addRange(range);}}}function isTextNode(node){return node&&node.nodeType===TEXT_NODE;}function containsNode(outerNode,innerNode){if(!outerNode||!innerNode){return false;}else if(outerNode===innerNode){return true;}else if(isTextNode(outerNode)){return false;}else if(isTextNode(innerNode)){return containsNode(outerNode,innerNode.parentNode);}else if('contains'in outerNode){return outerNode.contains(innerNode);}else if(outerNode.compareDocumentPosition){return !!(outerNode.compareDocumentPosition(innerNode)&16);}else {return false;}}function isInDocument(node){return node&&node.ownerDocument&&containsNode(node.ownerDocument.documentElement,node);}function isSameOriginFrame(iframe){try{// Accessing the contentDocument of a HTMLIframeElement can cause the browser
// to throw, e.g. if it has a cross-origin src attribute.
// Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
// iframe.contentDocument.defaultView;
// A safety way is to access one of the cross origin properties: Window or Location
// Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
// https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
return typeof iframe.contentWindow.location.href==='string';}catch(err){return false;}}function getActiveElementDeep(){var win=window;var element=getActiveElement();while(element instanceof win.HTMLIFrameElement){if(isSameOriginFrame(element)){win=element.contentWindow;}else {return element;}element=getActiveElement(win.document);}return element;}/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/ /**
* @hasSelectionCapabilities: we get the element types that support selection
* from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
* and `selectionEnd` rows.
*/function hasSelectionCapabilities(elem){var nodeName=elem&&elem.nodeName&&elem.nodeName.toLowerCase();return nodeName&&(nodeName==='input'&&(elem.type==='text'||elem.type==='search'||elem.type==='tel'||elem.type==='url'||elem.type==='password')||nodeName==='textarea'||elem.contentEditable==='true');}function getSelectionInformation(){var focusedElem=getActiveElementDeep();return {focusedElem:focusedElem,selectionRange:hasSelectionCapabilities(focusedElem)?getSelection(focusedElem):null};}/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/function restoreSelection(priorSelectionInformation){var curFocusedElem=getActiveElementDeep();var priorFocusedElem=priorSelectionInformation.focusedElem;var priorSelectionRange=priorSelectionInformation.selectionRange;if(curFocusedElem!==priorFocusedElem&&isInDocument(priorFocusedElem)){if(priorSelectionRange!==null&&hasSelectionCapabilities(priorFocusedElem)){setSelection(priorFocusedElem,priorSelectionRange);}// Focusing a node can change the scroll position, which is undesirable
var ancestors=[];var ancestor=priorFocusedElem;while(ancestor=ancestor.parentNode){if(ancestor.nodeType===ELEMENT_NODE){ancestors.push({element:ancestor,left:ancestor.scrollLeft,top:ancestor.scrollTop});}}if(typeof priorFocusedElem.focus==='function'){priorFocusedElem.focus();}for(var i=0;i<ancestors.length;i++){var info=ancestors[i];info.element.scrollLeft=info.left;info.element.scrollTop=info.top;}}}/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/function getSelection(input){var selection;if('selectionStart'in input){// Modern browser with input or textarea.
selection={start:input.selectionStart,end:input.selectionEnd};}else {// Content editable or old IE textarea.
selection=getOffsets(input);}return selection||{start:0,end:0};}/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/function setSelection(input,offsets){var start=offsets.start;var end=offsets.end;if(end===undefined){end=start;}if('selectionStart'in input){input.selectionStart=start;input.selectionEnd=Math.min(end,input.value.length);}else {setOffsets(input,offsets);}}var skipSelectionChangeEvent=canUseDOM&&'documentMode'in document&&document.documentMode<=11;function registerEvents$3(){registerTwoPhaseEvent('onSelect',['focusout','contextmenu','dragend','focusin','keydown','keyup','mousedown','mouseup','selectionchange']);}var activeElement$1=null;var activeElementInst$1=null;var lastSelection=null;var mouseDown=false;/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*/function getSelection$1(node){if('selectionStart'in node&&hasSelectionCapabilities(node)){return {start:node.selectionStart,end:node.selectionEnd};}else {var win=node.ownerDocument&&node.ownerDocument.defaultView||window;var selection=win.getSelection();return {anchorNode:selection.anchorNode,anchorOffset:selection.anchorOffset,focusNode:selection.focusNode,focusOffset:selection.focusOffset};}}/**
* Get document associated with the event target.
*/function getEventTargetDocument(eventTarget){return eventTarget.window===eventTarget?eventTarget.document:eventTarget.nodeType===DOCUMENT_NODE?eventTarget:eventTarget.ownerDocument;}/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @param {object} nativeEventTarget
* @return {?SyntheticEvent}
*/function constructSelectEvent(dispatchQueue,nativeEvent,nativeEventTarget){// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
var doc=getEventTargetDocument(nativeEventTarget);if(mouseDown||activeElement$1==null||activeElement$1!==getActiveElement(doc)){return;}// Only fire when selection has actually changed.
var currentSelection=getSelection$1(activeElement$1);if(!lastSelection||!shallowEqual(lastSelection,currentSelection)){lastSelection=currentSelection;var listeners=accumulateTwoPhaseListeners(activeElementInst$1,'onSelect');if(listeners.length>0){var event=new SyntheticEvent('onSelect','select',null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:event,listeners:listeners});event.target=activeElement$1;}}}/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/function extractEvents$3(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var targetNode=targetInst?getNodeFromInstance(targetInst):window;switch(domEventName){// Track the input node that has focus.
case'focusin':if(isTextInputElement(targetNode)||targetNode.contentEditable==='true'){activeElement$1=targetNode;activeElementInst$1=targetInst;lastSelection=null;}break;case'focusout':activeElement$1=null;activeElementInst$1=null;lastSelection=null;break;// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case'mousedown':mouseDown=true;break;case'contextmenu':case'mouseup':case'dragend':mouseDown=false;constructSelectEvent(dispatchQueue,nativeEvent,nativeEventTarget);break;// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case'selectionchange':if(skipSelectionChangeEvent){break;}// falls through
case'keydown':case'keyup':constructSelectEvent(dispatchQueue,nativeEvent,nativeEventTarget);}}function extractEvents$4(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var reactName=topLevelEventsToReactNames.get(domEventName);if(reactName===undefined){return;}var SyntheticEventCtor=SyntheticEvent;var reactEventType=domEventName;switch(domEventName){case'keypress':// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if(getEventCharCode(nativeEvent)===0){return;}/* falls through */case'keydown':case'keyup':SyntheticEventCtor=SyntheticKeyboardEvent;break;case'focusin':reactEventType='focus';SyntheticEventCtor=SyntheticFocusEvent;break;case'focusout':reactEventType='blur';SyntheticEventCtor=SyntheticFocusEvent;break;case'beforeblur':case'afterblur':SyntheticEventCtor=SyntheticFocusEvent;break;case'click':// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if(nativeEvent.button===2){return;}/* falls through */case'auxclick':case'dblclick':case'mousedown':case'mousemove':case'mouseup':// TODO: Disabled elements should not respond to mouse events
/* falls through */case'mouseout':case'mouseover':case'contextmenu':SyntheticEventCtor=SyntheticMouseEvent;break;case'drag':case'dragend':case'dragenter':case'dragexit':case'dragleave':case'dragover':case'dragstart':case'drop':SyntheticEventCtor=SyntheticDragEvent;break;case'touchcancel':case'touchend':case'touchmove':case'touchstart':SyntheticEventCtor=SyntheticTouchEvent;break;case ANIMATION_END:case ANIMATION_ITERATION:case ANIMATION_START:SyntheticEventCtor=SyntheticAnimationEvent;break;case TRANSITION_END:SyntheticEventCtor=SyntheticTransitionEvent;break;case'scroll':SyntheticEventCtor=SyntheticUIEvent;break;case'wheel':SyntheticEventCtor=SyntheticWheelEvent;break;case'copy':case'cut':case'paste':SyntheticEventCtor=SyntheticClipboardEvent;break;case'gotpointercapture':case'lostpointercapture':case'pointercancel':case'pointerdown':case'pointermove':case'pointerout':case'pointerover':case'pointerup':SyntheticEventCtor=SyntheticPointerEvent;break;}var inCapturePhase=(eventSystemFlags&IS_CAPTURE_PHASE)!==0;{// Some events don't bubble in the browser.
// In the past, React has always bubbled them, but this can be surprising.
// We're going to try aligning closer to the browser behavior by not bubbling
// them in React either. We'll start by not bubbling onScroll, and then expand.
var accumulateTargetOnly=!inCapturePhase&&// TODO: ideally, we'd eventually add all events from
// nonDelegatedEvents list in DOMPluginEventSystem.
// Then we can remove this special list.
// This is a breaking change that can wait until React 18.
domEventName==='scroll';var _listeners=accumulateSinglePhaseListeners(targetInst,reactName,nativeEvent.type,inCapturePhase,accumulateTargetOnly);if(_listeners.length>0){// Intentionally create event lazily.
var _event=new SyntheticEventCtor(reactName,reactEventType,null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:_event,listeners:_listeners});}}}// TODO: remove top-level side effect.
registerSimpleEvents();registerEvents$2();registerEvents$1();registerEvents$3();registerEvents();function extractEvents$5(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){// TODO: we should remove the concept of a "SimpleEventPlugin".
// This is the basic functionality of the event system. All
// the other plugins are essentially polyfills. So the plugin
// should probably be inlined somewhere and have its logic
// be core the to event system. This would potentially allow
// us to ship builds of React without the polyfilled plugins below.
extractEvents$4(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags);var shouldProcessPolyfillPlugins=(eventSystemFlags&SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS)===0;// We don't process these events unless we are in the
// event's native "bubble" phase, which means that we're
// not in the capture phase. That's because we emulate
// the capture phase here still. This is a trade-off,
// because in an ideal world we would not emulate and use
// the phases properly, like we do with the SimpleEvent
// plugin. However, the plugins below either expect
// emulation (EnterLeave) or use state localized to that
// plugin (BeforeInput, Change, Select). The state in
// these modules complicates things, as you'll essentially
// get the case where the capture phase event might change
// state, only for the following bubble event to come in
// later and not trigger anything as the state now
// invalidates the heuristics of the event plugin. We
// could alter all these plugins to work in such ways, but
// that might cause other unknown side-effects that we
// can't forsee right now.
if(shouldProcessPolyfillPlugins){extractEvents$2(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags);extractEvents$1(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractEvents$3(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractEvents(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);}}// List of events that need to be individually attached to media elements.
var mediaEventTypes=['abort','canplay','canplaythrough','durationchange','emptied','encrypted','ended','error','loadeddata','loadedmetadata','loadstart','pause','play','playing','progress','ratechange','seeked','seeking','stalled','suspend','timeupdate','volumechange','waiting'];// We should not delegate these events to the container, but rather
// set them on the actual target element itself. This is primarily
// because these events do not consistently bubble in the DOM.
var nonDelegatedEvents=new Set(['cancel','close','invalid','load','scroll','toggle'].concat(mediaEventTypes));function executeDispatch(event,listener,currentTarget){var type=event.type||'unknown-event';event.currentTarget=currentTarget;invokeGuardedCallbackAndCatchFirstError(type,listener,undefined,event);event.currentTarget=null;}function processDispatchQueueItemsInOrder(event,dispatchListeners,inCapturePhase){var previousInstance;if(inCapturePhase){for(var i=dispatchListeners.length-1;i>=0;i--){var _dispatchListeners$i=dispatchListeners[i],instance=_dispatchListeners$i.instance,currentTarget=_dispatchListeners$i.currentTarget,listener=_dispatchListeners$i.listener;if(instance!==previousInstance&&event.isPropagationStopped()){return;}executeDispatch(event,listener,currentTarget);previousInstance=instance;}}else {for(var _i=0;_i<dispatchListeners.length;_i++){var _dispatchListeners$_i=dispatchListeners[_i],_instance=_dispatchListeners$_i.instance,_currentTarget=_dispatchListeners$_i.currentTarget,_listener=_dispatchListeners$_i.listener;if(_instance!==previousInstance&&event.isPropagationStopped()){return;}executeDispatch(event,_listener,_currentTarget);previousInstance=_instance;}}}function processDispatchQueue(dispatchQueue,eventSystemFlags){var inCapturePhase=(eventSystemFlags&IS_CAPTURE_PHASE)!==0;for(var i=0;i<dispatchQueue.length;i++){var _dispatchQueue$i=dispatchQueue[i],event=_dispatchQueue$i.event,listeners=_dispatchQueue$i.listeners;processDispatchQueueItemsInOrder(event,listeners,inCapturePhase);// event system doesn't use pooling.
}// This would be a good time to rethrow if any of the event handlers threw.
rethrowCaughtError();}function dispatchEventsForPlugins(domEventName,eventSystemFlags,nativeEvent,targetInst,targetContainer){var nativeEventTarget=getEventTarget(nativeEvent);var dispatchQueue=[];extractEvents$5(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags);processDispatchQueue(dispatchQueue,eventSystemFlags);}function listenToNonDelegatedEvent(domEventName,targetElement){var isCapturePhaseListener=false;var listenerSet=getEventListenerSet(targetElement);var listenerSetKey=getListenerSetKey(domEventName,isCapturePhaseListener);if(!listenerSet.has(listenerSetKey)){addTrappedEventListener(targetElement,domEventName,IS_NON_DELEGATED,isCapturePhaseListener);listenerSet.add(listenerSetKey);}}var listeningMarker='_reactListening'+Math.random().toString(36).slice(2);function listenToAllSupportedEvents(rootContainerElement){{if(rootContainerElement[listeningMarker]){// Performance optimization: don't iterate through events
// for the same portal container or root node more than once.
// TODO: once we remove the flag, we may be able to also
// remove some of the bookkeeping maps used for laziness.
return;}rootContainerElement[listeningMarker]=true;allNativeEvents.forEach(function(domEventName){if(!nonDelegatedEvents.has(domEventName)){listenToNativeEvent(domEventName,false,rootContainerElement,null);}listenToNativeEvent(domEventName,true,rootContainerElement,null);});}}function listenToNativeEvent(domEventName,isCapturePhaseListener,rootContainerElement,targetElement){var eventSystemFlags=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var target=rootContainerElement;// selectionchange needs to be attached to the document
// otherwise it won't capture incoming events that are only
// triggered on the document directly.
if(domEventName==='selectionchange'&&rootContainerElement.nodeType!==DOCUMENT_NODE){target=rootContainerElement.ownerDocument;}// If the event can be delegated (or is capture phase), we can
// register it to the root container. Otherwise, we should
// register the event to the target element and mark it as
// a non-delegated event.
if(targetElement!==null&&!isCapturePhaseListener&&nonDelegatedEvents.has(domEventName)){// For all non-delegated events, apart from scroll, we attach
// their event listeners to the respective elements that their
// events fire on. That means we can skip this step, as event
// listener has already been added previously. However, we
// special case the scroll event because the reality is that any
// element can scroll.
// TODO: ideally, we'd eventually apply the same logic to all
// events from the nonDelegatedEvents list. Then we can remove
// this special case and use the same logic for all events.
if(domEventName!=='scroll'){return;}eventSystemFlags|=IS_NON_DELEGATED;target=targetElement;}var listenerSet=getEventListenerSet(target);var listenerSetKey=getListenerSetKey(domEventName,isCapturePhaseListener);// If the listener entry is empty or we should upgrade, then
// we need to trap an event listener onto the target.
if(!listenerSet.has(listenerSetKey)){if(isCapturePhaseListener){eventSystemFlags|=IS_CAPTURE_PHASE;}addTrappedEventListener(target,domEventName,eventSystemFlags,isCapturePhaseListener);listenerSet.add(listenerSetKey);}}function addTrappedEventListener(targetContainer,domEventName,eventSystemFlags,isCapturePhaseListener,isDeferredListenerForLegacyFBSupport){var listener=createEventListenerWrapperWithPriority(targetContainer,domEventName,eventSystemFlags);// If passive option is not supported, then the event will be
// active and not passive.
var isPassiveListener=undefined;if(passiveBrowserEventsSupported){// Browsers introduced an intervention, making these events
// passive by default on document. React doesn't bind them
// to document anymore, but changing this now would undo
// the performance wins from the change. So we emulate
// the existing behavior manually on the roots now.
// https://github.com/facebook/react/issues/19651
if(domEventName==='touchstart'||domEventName==='touchmove'||domEventName==='wheel'){isPassiveListener=true;}}targetContainer=targetContainer;var unsubscribeListener;// When legacyFBSupport is enabled, it's for when we
if(isCapturePhaseListener){if(isPassiveListener!==undefined){unsubscribeListener=addEventCaptureListenerWithPassiveFlag(targetContainer,domEventName,listener,isPassiveListener);}else {unsubscribeListener=addEventCaptureListener(targetContainer,domEventName,listener);}}else {if(isPassiveListener!==undefined){unsubscribeListener=addEventBubbleListenerWithPassiveFlag(targetContainer,domEventName,listener,isPassiveListener);}else {unsubscribeListener=addEventBubbleListener(targetContainer,domEventName,listener);}}}function isMatchingRootContainer(grandContainer,targetContainer){return grandContainer===targetContainer||grandContainer.nodeType===COMMENT_NODE&&grandContainer.parentNode===targetContainer;}function dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,targetInst,targetContainer){var ancestorInst=targetInst;if((eventSystemFlags&IS_EVENT_HANDLE_NON_MANAGED_NODE)===0&&(eventSystemFlags&IS_NON_DELEGATED)===0){var targetContainerNode=targetContainer;// If we are using the legacy FB support flag, we
if(targetInst!==null){// The below logic attempts to work out if we need to change
// the target fiber to a different ancestor. We had similar logic
// in the legacy event system, except the big difference between
// systems is that the modern event system now has an event listener
// attached to each React Root and React Portal Root. Together,
// the DOM nodes representing these roots are the "rootContainer".
// To figure out which ancestor instance we should use, we traverse
// up the fiber tree from the target instance and attempt to find
// root boundaries that match that of our current "rootContainer".
// If we find that "rootContainer", we find the parent fiber
// sub-tree for that root and make that our ancestor instance.
var node=targetInst;mainLoop:while(true){if(node===null){return;}var nodeTag=node.tag;if(nodeTag===HostRoot||nodeTag===HostPortal){var container=node.stateNode.containerInfo;if(isMatchingRootContainer(container,targetContainerNode)){break;}if(nodeTag===HostPortal){// The target is a portal, but it's not the rootContainer we're looking for.
// Normally portals handle their own events all the way down to the root.
// So we should be able to stop now. However, we don't know if this portal
// was part of *our* root.
var grandNode=node.return;while(grandNode!==null){var grandTag=grandNode.tag;if(grandTag===HostRoot||grandTag===HostPortal){var grandContainer=grandNode.stateNode.containerInfo;if(isMatchingRootContainer(grandContainer,targetContainerNode)){// This is the rootContainer we're looking for and we found it as
// a parent of the Portal. That means we can ignore it because the
// Portal will bubble through to us.
return;}}grandNode=grandNode.return;}}// Now we need to find it's corresponding host fiber in the other
// tree. To do this we can use getClosestInstanceFromNode, but we
// need to validate that the fiber is a host instance, otherwise
// we need to traverse up through the DOM till we find the correct
// node that is from the other tree.
while(container!==null){var parentNode=getClosestInstanceFromNode(container);if(parentNode===null){return;}var parentTag=parentNode.tag;if(parentTag===HostComponent||parentTag===HostText){node=ancestorInst=parentNode;continue mainLoop;}container=container.parentNode;}}node=node.return;}}}batchedEventUpdates(function(){return dispatchEventsForPlugins(domEventName,eventSystemFlags,nativeEvent,ancestorInst);});}function createDispatchListener(instance,listener,currentTarget){return {instance:instance,listener:listener,currentTarget:currentTarget};}function accumulateSinglePhaseListeners(targetFiber,reactName,nativeEventType,inCapturePhase,accumulateTargetOnly){var captureName=reactName!==null?reactName+'Capture':null;var reactEventName=inCapturePhase?captureName:reactName;var listeners=[];var instance=targetFiber;var lastHostComponent=null;// Accumulate all instances and listeners via the target -> root path.
while(instance!==null){var _instance2=instance,stateNode=_instance2.stateNode,tag=_instance2.tag;// Handle listeners that are on HostComponents (i.e. <div>)
if(tag===HostComponent&&stateNode!==null){lastHostComponent=stateNode;// createEventHandle listeners
if(reactEventName!==null){var listener=getListener(instance,reactEventName);if(listener!=null){listeners.push(createDispatchListener(instance,listener,lastHostComponent));}}}// If we are only accumulating events for the target, then we don't
// continue to propagate through the React fiber tree to find other
// listeners.
if(accumulateTargetOnly){break;}instance=instance.return;}return listeners;}// We should only use this function for:
// - BeforeInputEventPlugin
// - ChangeEventPlugin
// - SelectEventPlugin
// This is because we only process these plugins
// in the bubble phase, so we need to accumulate two
// phase event listeners (via emulation).
function accumulateTwoPhaseListeners(targetFiber,reactName){var captureName=reactName+'Capture';var listeners=[];var instance=targetFiber;// Accumulate all instances and listeners via the target -> root path.
while(instance!==null){var _instance3=instance,stateNode=_instance3.stateNode,tag=_instance3.tag;// Handle listeners that are on HostComponents (i.e. <div>)
if(tag===HostComponent&&stateNode!==null){var currentTarget=stateNode;var captureListener=getListener(instance,captureName);if(captureListener!=null){listeners.unshift(createDispatchListener(instance,captureListener,currentTarget));}var bubbleListener=getListener(instance,reactName);if(bubbleListener!=null){listeners.push(createDispatchListener(instance,bubbleListener,currentTarget));}}instance=instance.return;}return listeners;}function getParent(inst){if(inst===null){return null;}do{inst=inst.return;// TODO: If this is a HostRoot we might want to bail out.
// That is depending on if we want nested subtrees (layers) to bubble
// events to their parent. We could also go through parentNode on the
// host node but that wouldn't work for React Native and doesn't let us
// do the portal feature.
}while(inst&&inst.tag!==HostComponent);if(inst){return inst;}return null;}/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/function getLowestCommonAncestor(instA,instB){var nodeA=instA;var nodeB=instB;var depthA=0;for(var tempA=nodeA;tempA;tempA=getParent(tempA)){depthA++;}var depthB=0;for(var tempB=nodeB;tempB;tempB=getParent(tempB)){depthB++;}// If A is deeper, crawl up.
while(depthA-depthB>0){nodeA=getParent(nodeA);depthA--;}// If B is deeper, crawl up.
while(depthB-depthA>0){nodeB=getParent(nodeB);depthB--;}// Walk in lockstep until we find a match.
var depth=depthA;while(depth--){if(nodeA===nodeB||nodeB!==null&&nodeA===nodeB.alternate){return nodeA;}nodeA=getParent(nodeA);nodeB=getParent(nodeB);}return null;}function accumulateEnterLeaveListenersForEvent(dispatchQueue,event,target,common,inCapturePhase){var registrationName=event._reactName;var listeners=[];var instance=target;while(instance!==null){if(instance===common){break;}var _instance4=instance,alternate=_instance4.alternate,stateNode=_instance4.stateNode,tag=_instance4.tag;if(alternate!==null&&alternate===common){break;}if(tag===HostComponent&&stateNode!==null){var currentTarget=stateNode;if(inCapturePhase){var captureListener=getListener(instance,registrationName);if(captureListener!=null){listeners.unshift(createDispatchListener(instance,captureListener,currentTarget));}}else if(!inCapturePhase){var bubbleListener=getListener(instance,registrationName);if(bubbleListener!=null){listeners.push(createDispatchListener(instance,bubbleListener,currentTarget));}}}instance=instance.return;}if(listeners.length!==0){dispatchQueue.push({event:event,listeners:listeners});}}// We should only use this function for:
// - EnterLeaveEventPlugin
// This is because we only process this plugin
// in the bubble phase, so we need to accumulate two
// phase event listeners.
function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue,leaveEvent,enterEvent,from,to){var common=from&&to?getLowestCommonAncestor(from,to):null;if(from!==null){accumulateEnterLeaveListenersForEvent(dispatchQueue,leaveEvent,from,common,false);}if(to!==null&&enterEvent!==null){accumulateEnterLeaveListenersForEvent(dispatchQueue,enterEvent,to,common,true);}}function getListenerSetKey(domEventName,capture){return domEventName+"__"+(capture?'capture':'bubble');}var didWarnInvalidHydration=false;var DANGEROUSLY_SET_INNER_HTML='dangerouslySetInnerHTML';var SUPPRESS_CONTENT_EDITABLE_WARNING='suppressContentEditableWarning';var SUPPRESS_HYDRATION_WARNING='suppressHydrationWarning';var AUTOFOCUS='autoFocus';var CHILDREN='children';var STYLE='style';var HTML$1='__html';var HTML_NAMESPACE$1=Namespaces.html;var warnedUnknownTags;var suppressHydrationWarning;var validatePropertiesInDevelopment;var warnForTextDifference;var warnForPropDifference;var warnForExtraAttributes;var warnForInvalidEventListener;var canDiffStyleForHydrationWarning;var normalizeMarkupForTextOrAttribute;var normalizeHTML;{warnedUnknownTags={// There are working polyfills for <dialog>. Let people use it.
dialog:true,// Electron ships a custom <webview> tag to display external web content in
// an isolated frame and process.
// This tag is not present in non Electron environments such as JSDom which
// is often used for testing purposes.
// @see https://electronjs.org/docs/api/webview-tag
webview:true};validatePropertiesInDevelopment=function(type,props){validateProperties(type,props);validateProperties$1(type,props);validateProperties$2(type,props,{registrationNameDependencies:registrationNameDependencies,possibleRegistrationNames:possibleRegistrationNames});};// IE 11 parses & normalizes the style attribute as opposed to other
// browsers. It adds spaces and sorts the properties in some
// non-alphabetical order. Handling that would require sorting CSS
// properties in the client & server versions or applying
// `expectedStyle` to a temporary DOM node to read its `style` attribute
// normalized. Since it only affects IE, we're skipping style warnings
// in that browser completely in favor of doing all that work.
// See https://github.com/facebook/react/issues/11807
canDiffStyleForHydrationWarning=canUseDOM&&!document.documentMode;// HTML parsing normalizes CR and CRLF to LF.
// It also can turn \u0000 into \uFFFD inside attributes.
// https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
// If we have a mismatch, it might be caused by that.
// We will still patch up in this case but not fire the warning.
var NORMALIZE_NEWLINES_REGEX=/\r\n?/g;var NORMALIZE_NULL_AND_REPLACEMENT_REGEX=/\u0000|\uFFFD/g;normalizeMarkupForTextOrAttribute=function(markup){var markupString=typeof markup==='string'?markup:''+markup;return markupString.replace(NORMALIZE_NEWLINES_REGEX,'\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX,'');};warnForTextDifference=function(serverText,clientText){if(didWarnInvalidHydration){return;}var normalizedClientText=normalizeMarkupForTextOrAttribute(clientText);var normalizedServerText=normalizeMarkupForTextOrAttribute(serverText);if(normalizedServerText===normalizedClientText){return;}didWarnInvalidHydration=true;error('Text content did not match. Server: "%s" Client: "%s"',normalizedServerText,normalizedClientText);};warnForPropDifference=function(propName,serverValue,clientValue){if(didWarnInvalidHydration){return;}var normalizedClientValue=normalizeMarkupForTextOrAttribute(clientValue);var normalizedServerValue=normalizeMarkupForTextOrAttribute(serverValue);if(normalizedServerValue===normalizedClientValue){return;}didWarnInvalidHydration=true;error('Prop `%s` did not match. Server: %s Client: %s',propName,JSON.stringify(normalizedServerValue),JSON.stringify(normalizedClientValue));};warnForExtraAttributes=function(attributeNames){if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;var names=[];attributeNames.forEach(function(name){names.push(name);});error('Extra attributes from the server: %s',names);};warnForInvalidEventListener=function(registrationName,listener){if(listener===false){error('Expected `%s` listener to be a function, instead got `false`.\n\n'+'If you used to conditionally omit it with %s={condition && value}, '+'pass %s={condition ? value : undefined} instead.',registrationName,registrationName,registrationName);}else {error('Expected `%s` listener to be a function, instead got a value of `%s` type.',registrationName,typeof listener);}};// Parse the HTML and read it back to normalize the HTML string so that it
// can be used for comparison.
normalizeHTML=function(parent,html){// We could have created a separate document here to avoid
// re-initializing custom elements if they exist. But this breaks
// how <noscript> is being handled. So we use the same document.
// See the discussion in https://github.com/facebook/react/pull/11157.
var testElement=parent.namespaceURI===HTML_NAMESPACE$1?parent.ownerDocument.createElement(parent.tagName):parent.ownerDocument.createElementNS(parent.namespaceURI,parent.tagName);testElement.innerHTML=html;return testElement.innerHTML;};}function getOwnerDocumentFromRootContainer(rootContainerElement){return rootContainerElement.nodeType===DOCUMENT_NODE?rootContainerElement:rootContainerElement.ownerDocument;}function noop(){}function trapClickOnNonInteractiveElement(node){// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
// https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
// Just set it using the onclick property so that we don't have to manage any
// bookkeeping for it. Not sure if we need to clear it when the listener is
// removed.
// TODO: Only do this for the relevant Safaris maybe?
node.onclick=noop;}function setInitialDOMProperties(tag,domElement,rootContainerElement,nextProps,isCustomComponentTag){for(var propKey in nextProps){if(!nextProps.hasOwnProperty(propKey)){continue;}var nextProp=nextProps[propKey];if(propKey===STYLE){{if(nextProp){// Freeze the next style object so that we can assume it won't be
// mutated. We have already warned for this in the past.
Object.freeze(nextProp);}}// Relies on `updateStylesByID` not mutating `styleUpdates`.
setValueForStyles(domElement,nextProp);}else if(propKey===DANGEROUSLY_SET_INNER_HTML){var nextHtml=nextProp?nextProp[HTML$1]:undefined;if(nextHtml!=null){setInnerHTML(domElement,nextHtml);}}else if(propKey===CHILDREN){if(typeof nextProp==='string'){// Avoid setting initial textContent when the text is empty. In IE11 setting
// textContent on a <textarea> will cause the placeholder to not
// show within the <textarea> until it has been focused and blurred again.
// https://github.com/facebook/react/issues/6731#issuecomment-254874553
var canSetTextContent=tag!=='textarea'||nextProp!=='';if(canSetTextContent){setTextContent(domElement,nextProp);}}else if(typeof nextProp==='number'){setTextContent(domElement,''+nextProp);}}else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING);else if(propKey===AUTOFOCUS);else if(registrationNameDependencies.hasOwnProperty(propKey)){if(nextProp!=null){if(typeof nextProp!=='function'){warnForInvalidEventListener(propKey,nextProp);}if(propKey==='onScroll'){listenToNonDelegatedEvent('scroll',domElement);}}}else if(nextProp!=null){setValueForProperty(domElement,propKey,nextProp,isCustomComponentTag);}}}function updateDOMProperties(domElement,updatePayload,wasCustomComponentTag,isCustomComponentTag){// TODO: Handle wasCustomComponentTag
for(var i=0;i<updatePayload.length;i+=2){var propKey=updatePayload[i];var propValue=updatePayload[i+1];if(propKey===STYLE){setValueForStyles(domElement,propValue);}else if(propKey===DANGEROUSLY_SET_INNER_HTML){setInnerHTML(domElement,propValue);}else if(propKey===CHILDREN){setTextContent(domElement,propValue);}else {setValueForProperty(domElement,propKey,propValue,isCustomComponentTag);}}}function createElement(type,props,rootContainerElement,parentNamespace){var isCustomComponentTag;// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var ownerDocument=getOwnerDocumentFromRootContainer(rootContainerElement);var domElement;var namespaceURI=parentNamespace;if(namespaceURI===HTML_NAMESPACE$1){namespaceURI=getIntrinsicNamespace(type);}if(namespaceURI===HTML_NAMESPACE$1){{isCustomComponentTag=isCustomComponent(type,props);// Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
if(!isCustomComponentTag&&type!==type.toLowerCase()){error('<%s /> is using incorrect casing. '+'Use PascalCase for React components, '+'or lowercase for HTML elements.',type);}}if(type==='script'){// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div=ownerDocument.createElement('div');div.innerHTML='<script><'+'/script>';// eslint-disable-line
// This is guaranteed to yield a script element.
var firstChild=div.firstChild;domElement=div.removeChild(firstChild);}else if(typeof props.is==='string'){// $FlowIssue `createElement` should be updated for Web Components
domElement=ownerDocument.createElement(type,{is:props.is});}else {// Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
domElement=ownerDocument.createElement(type);// Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
// attributes on `select`s needs to be added before `option`s are inserted.
// This prevents:
// - a bug where the `select` does not scroll to the correct option because singular
// `select` elements automatically pick the first item #13222
// - a bug where the `select` set the first item as selected despite the `size` attribute #14239
// See https://github.com/facebook/react/issues/13222
// and https://github.com/facebook/react/issues/14239
if(type==='select'){var node=domElement;if(props.multiple){node.multiple=true;}else if(props.size){// Setting a size greater than 1 causes a select to behave like `multiple=true`, where
// it is possible that no option is selected.
//
// This is only necessary when a select in "single selection mode".
node.size=props.size;}}}}else {domElement=ownerDocument.createElementNS(namespaceURI,type);}{if(namespaceURI===HTML_NAMESPACE$1){if(!isCustomComponentTag&&Object.prototype.toString.call(domElement)==='[object HTMLUnknownElement]'&&!Object.prototype.hasOwnProperty.call(warnedUnknownTags,type)){warnedUnknownTags[type]=true;error('The tag <%s> is unrecognized in this browser. '+'If you meant to render a React component, start its name with '+'an uppercase letter.',type);}}}return domElement;}function createTextNode(text,rootContainerElement){return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);}function setInitialProperties(domElement,tag,rawProps,rootContainerElement){var isCustomComponentTag=isCustomComponent(tag,rawProps);{validatePropertiesInDevelopment(tag,rawProps);}// TODO: Make sure that we check isMounted before firing any of these events.
var props;switch(tag){case'dialog':listenToNonDelegatedEvent('cancel',domElement);listenToNonDelegatedEvent('close',domElement);props=rawProps;break;case'iframe':case'object':case'embed':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load',domElement);props=rawProps;break;case'video':case'audio':// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for(var i=0;i<mediaEventTypes.length;i++){listenToNonDelegatedEvent(mediaEventTypes[i],domElement);}props=rawProps;break;case'source':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error',domElement);props=rawProps;break;case'img':case'image':case'link':// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error',domElement);listenToNonDelegatedEvent('load',domElement);props=rawProps;break;case'details':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle',domElement);props=rawProps;break;case'input':initWrapperState(domElement,rawProps);props=getHostProps(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'option':validateProps(domElement,rawProps);props=getHostProps$1(domElement,rawProps);break;case'select':initWrapperState$1(domElement,rawProps);props=getHostProps$2(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'textarea':initWrapperState$2(domElement,rawProps);props=getHostProps$3(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;default:props=rawProps;}assertValidProps(tag,props);setInitialDOMProperties(tag,domElement,rootContainerElement,props,isCustomComponentTag);switch(tag){case'input':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper(domElement,rawProps,false);break;case'textarea':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper$3(domElement);break;case'option':postMountWrapper$1(domElement,rawProps);break;case'select':postMountWrapper$2(domElement,rawProps);break;default:if(typeof props.onClick==='function'){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);}break;}}// Calculate the diff between the two objects.
function diffProperties(domElement,tag,lastRawProps,nextRawProps,rootContainerElement){{validatePropertiesInDevelopment(tag,nextRawProps);}var updatePayload=null;var lastProps;var nextProps;switch(tag){case'input':lastProps=getHostProps(domElement,lastRawProps);nextProps=getHostProps(domElement,nextRawProps);updatePayload=[];break;case'option':lastProps=getHostProps$1(domElement,lastRawProps);nextProps=getHostProps$1(domElement,nextRawProps);updatePayload=[];break;case'select':lastProps=getHostProps$2(domElement,lastRawProps);nextProps=getHostProps$2(domElement,nextRawProps);updatePayload=[];break;case'textarea':lastProps=getHostProps$3(domElement,lastRawProps);nextProps=getHostProps$3(domElement,nextRawProps);updatePayload=[];break;default:lastProps=lastRawProps;nextProps=nextRawProps;if(typeof lastProps.onClick!=='function'&&typeof nextProps.onClick==='function'){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);}break;}assertValidProps(tag,nextProps);var propKey;var styleName;var styleUpdates=null;for(propKey in lastProps){if(nextProps.hasOwnProperty(propKey)||!lastProps.hasOwnProperty(propKey)||lastProps[propKey]==null){continue;}if(propKey===STYLE){var lastStyle=lastProps[propKey];for(styleName in lastStyle){if(lastStyle.hasOwnProperty(styleName)){if(!styleUpdates){styleUpdates={};}styleUpdates[styleName]='';}}}else if(propKey===DANGEROUSLY_SET_INNER_HTML||propKey===CHILDREN);else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING);else if(propKey===AUTOFOCUS);else if(registrationNameDependencies.hasOwnProperty(propKey)){// This is a special case. If any listener updates we need to ensure
// that the "current" fiber pointer gets updated so we need a commit
// to update this element.
if(!updatePayload){updatePayload=[];}}else {// For all other deleted properties we add it to the queue. We use
// the allowed property list in the commit phase instead.
(updatePayload=updatePayload||[]).push(propKey,null);}}for(propKey in nextProps){var nextProp=nextProps[propKey];var lastProp=lastProps!=null?lastProps[propKey]:undefined;if(!nextProps.hasOwnProperty(propKey)||nextProp===lastProp||nextProp==null&&lastProp==null){continue;}if(propKey===STYLE){{if(nextProp){// Freeze the next style object so that we can assume it won't be
// mutated. We have already warned for this in the past.
Object.freeze(nextProp);}}if(lastProp){// Unset styles on `lastProp` but not on `nextProp`.
for(styleName in lastProp){if(lastProp.hasOwnProperty(styleName)&&(!nextProp||!nextProp.hasOwnProperty(styleName))){if(!styleUpdates){styleUpdates={};}styleUpdates[styleName]='';}}// Update styles that changed since `lastProp`.
for(styleName in nextProp){if(nextProp.hasOwnProperty(styleName)&&lastProp[styleName]!==nextProp[styleName]){if(!styleUpdates){styleUpdates={};}styleUpdates[styleName]=nextProp[styleName];}}}else {// Relies on `updateStylesByID` not mutating `styleUpdates`.
if(!styleUpdates){if(!updatePayload){updatePayload=[];}updatePayload.push(propKey,styleUpdates);}styleUpdates=nextProp;}}else if(propKey===DANGEROUSLY_SET_INNER_HTML){var nextHtml=nextProp?nextProp[HTML$1]:undefined;var lastHtml=lastProp?lastProp[HTML$1]:undefined;if(nextHtml!=null){if(lastHtml!==nextHtml){(updatePayload=updatePayload||[]).push(propKey,nextHtml);}}}else if(propKey===CHILDREN){if(typeof nextProp==='string'||typeof nextProp==='number'){(updatePayload=updatePayload||[]).push(propKey,''+nextProp);}}else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING);else if(registrationNameDependencies.hasOwnProperty(propKey)){if(nextProp!=null){// We eagerly listen to this even though we haven't committed yet.
if(typeof nextProp!=='function'){warnForInvalidEventListener(propKey,nextProp);}if(propKey==='onScroll'){listenToNonDelegatedEvent('scroll',domElement);}}if(!updatePayload&&lastProp!==nextProp){// This is a special case. If any listener updates we need to ensure
// that the "current" props pointer gets updated so we need a commit
// to update this element.
updatePayload=[];}}else if(typeof nextProp==='object'&&nextProp!==null&&nextProp.$$typeof===REACT_OPAQUE_ID_TYPE){// If we encounter useOpaqueReference's opaque object, this means we are hydrating.
// In this case, call the opaque object's toString function which generates a new client
// ID so client and server IDs match and throws to rerender.
nextProp.toString();}else {// For any other property we always add it to the queue and then we
// filter it out using the allowed property list during the commit.
(updatePayload=updatePayload||[]).push(propKey,nextProp);}}if(styleUpdates){{validateShorthandPropertyCollisionInDev(styleUpdates,nextProps[STYLE]);}(updatePayload=updatePayload||[]).push(STYLE,styleUpdates);}return updatePayload;}// Apply the diff.
function updateProperties(domElement,updatePayload,tag,lastRawProps,nextRawProps){// Update checked *before* name.
// In the middle of an update, it is possible to have multiple checked.
// When a checked radio tries to change name, browser makes another radio's checked false.
if(tag==='input'&&nextRawProps.type==='radio'&&nextRawProps.name!=null){updateChecked(domElement,nextRawProps);}var wasCustomComponentTag=isCustomComponent(tag,lastRawProps);var isCustomComponentTag=isCustomComponent(tag,nextRawProps);// Apply the diff.
updateDOMProperties(domElement,updatePayload,wasCustomComponentTag,isCustomComponentTag);// TODO: Ensure that an update gets scheduled if any of the special props
// changed.
switch(tag){case'input':// Update the wrapper around inputs *after* updating props. This has to
// happen after `updateDOMProperties`. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
updateWrapper(domElement,nextRawProps);break;case'textarea':updateWrapper$1(domElement,nextRawProps);break;case'select':// <select> value update needs to occur after <option> children
// reconciliation
postUpdateWrapper(domElement,nextRawProps);break;}}function getPossibleStandardName(propName){{var lowerCasedName=propName.toLowerCase();if(!possibleStandardNames.hasOwnProperty(lowerCasedName)){return null;}return possibleStandardNames[lowerCasedName]||null;}}function diffHydratedProperties(domElement,tag,rawProps,parentNamespace,rootContainerElement){var isCustomComponentTag;var extraAttributeNames;{suppressHydrationWarning=rawProps[SUPPRESS_HYDRATION_WARNING]===true;isCustomComponentTag=isCustomComponent(tag,rawProps);validatePropertiesInDevelopment(tag,rawProps);}// TODO: Make sure that we check isMounted before firing any of these events.
switch(tag){case'dialog':listenToNonDelegatedEvent('cancel',domElement);listenToNonDelegatedEvent('close',domElement);break;case'iframe':case'object':case'embed':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load',domElement);break;case'video':case'audio':// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for(var i=0;i<mediaEventTypes.length;i++){listenToNonDelegatedEvent(mediaEventTypes[i],domElement);}break;case'source':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error',domElement);break;case'img':case'image':case'link':// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error',domElement);listenToNonDelegatedEvent('load',domElement);break;case'details':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle',domElement);break;case'input':initWrapperState(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'option':validateProps(domElement,rawProps);break;case'select':initWrapperState$1(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'textarea':initWrapperState$2(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;}assertValidProps(tag,rawProps);{extraAttributeNames=new Set();var attributes=domElement.attributes;for(var _i=0;_i<attributes.length;_i++){var name=attributes[_i].name.toLowerCase();switch(name){// Built-in SSR attribute is allowed
case'data-reactroot':break;// Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
case'value':break;case'checked':break;case'selected':break;default:// Intentionally use the original name.
// See discussion in https://github.com/facebook/react/pull/10676.
extraAttributeNames.add(attributes[_i].name);}}}var updatePayload=null;for(var propKey in rawProps){if(!rawProps.hasOwnProperty(propKey)){continue;}var nextProp=rawProps[propKey];if(propKey===CHILDREN){// For text content children we compare against textContent. This
// might match additional HTML that is hidden when we read it using
// textContent. E.g. "foo" will match "f<span>oo</span>" but that still
// satisfies our requirement. Our requirement is not to produce perfect
// HTML and attributes. Ideally we should preserve structure but it's
// ok not to if the visible content is still enough to indicate what
// even listeners these nodes might be wired up to.
// TODO: Warn if there is more than a single textNode as a child.
// TODO: Should we use domElement.firstChild.nodeValue to compare?
if(typeof nextProp==='string'){if(domElement.textContent!==nextProp){if(!suppressHydrationWarning){warnForTextDifference(domElement.textContent,nextProp);}updatePayload=[CHILDREN,nextProp];}}else if(typeof nextProp==='number'){if(domElement.textContent!==''+nextProp){if(!suppressHydrationWarning){warnForTextDifference(domElement.textContent,nextProp);}updatePayload=[CHILDREN,''+nextProp];}}}else if(registrationNameDependencies.hasOwnProperty(propKey)){if(nextProp!=null){if(typeof nextProp!=='function'){warnForInvalidEventListener(propKey,nextProp);}if(propKey==='onScroll'){listenToNonDelegatedEvent('scroll',domElement);}}}else if(// Convince Flow we've calculated it (it's DEV-only in this method.)
typeof isCustomComponentTag==='boolean'){// Validate that the properties correspond to their expected values.
var serverValue=void 0;var propertyInfo=getPropertyInfo(propKey);if(suppressHydrationWarning);else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING||// Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
propKey==='value'||propKey==='checked'||propKey==='selected');else if(propKey===DANGEROUSLY_SET_INNER_HTML){var serverHTML=domElement.innerHTML;var nextHtml=nextProp?nextProp[HTML$1]:undefined;if(nextHtml!=null){var expectedHTML=normalizeHTML(domElement,nextHtml);if(expectedHTML!==serverHTML){warnForPropDifference(propKey,serverHTML,expectedHTML);}}}else if(propKey===STYLE){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey);if(canDiffStyleForHydrationWarning){var expectedStyle=createDangerousStringForStyles(nextProp);serverValue=domElement.getAttribute('style');if(expectedStyle!==serverValue){warnForPropDifference(propKey,serverValue,expectedStyle);}}}else if(isCustomComponentTag){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey.toLowerCase());serverValue=getValueForAttribute(domElement,propKey,nextProp);if(nextProp!==serverValue){warnForPropDifference(propKey,serverValue,nextProp);}}else if(!shouldIgnoreAttribute(propKey,propertyInfo,isCustomComponentTag)&&!shouldRemoveAttribute(propKey,nextProp,propertyInfo,isCustomComponentTag)){var isMismatchDueToBadCasing=false;if(propertyInfo!==null){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propertyInfo.attributeName);serverValue=getValueForProperty(domElement,propKey,nextProp,propertyInfo);}else {var ownNamespace=parentNamespace;if(ownNamespace===HTML_NAMESPACE$1){ownNamespace=getIntrinsicNamespace(tag);}if(ownNamespace===HTML_NAMESPACE$1){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey.toLowerCase());}else {var standardName=getPossibleStandardName(propKey);if(standardName!==null&&standardName!==propKey){// If an SVG prop is supplied with bad casing, it will
// be successfully parsed from HTML, but will produce a mismatch
// (and would be incorrectly rendered on the client).
// However, we already warn about bad casing elsewhere.
// So we'll skip the misleading extra mismatch warning in this case.
isMismatchDueToBadCasing=true;// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(standardName);}// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey);}serverValue=getValueForAttribute(domElement,propKey,nextProp);}if(nextProp!==serverValue&&!isMismatchDueToBadCasing){warnForPropDifference(propKey,serverValue,nextProp);}}}}{// $FlowFixMe - Should be inferred as not undefined.
if(extraAttributeNames.size>0&&!suppressHydrationWarning){// $FlowFixMe - Should be inferred as not undefined.
warnForExtraAttributes(extraAttributeNames);}}switch(tag){case'input':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper(domElement,rawProps,true);break;case'textarea':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper$3(domElement);break;case'select':case'option':// For input and textarea we current always set the value property at
// post mount to force it to diverge from attributes. However, for
// option and select we don't quite do the same thing and select
// is not resilient to the DOM state changing so we don't do that here.
// TODO: Consider not doing this for input and textarea.
break;default:if(typeof rawProps.onClick==='function'){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);}break;}return updatePayload;}function diffHydratedText(textNode,text){var isDifferent=textNode.nodeValue!==text;return isDifferent;}function warnForUnmatchedText(textNode,text){{warnForTextDifference(textNode.nodeValue,text);}}function warnForDeletedHydratableElement(parentNode,child){{if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Did not expect server HTML to contain a <%s> in <%s>.',child.nodeName.toLowerCase(),parentNode.nodeName.toLowerCase());}}function warnForDeletedHydratableText(parentNode,child){{if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Did not expect server HTML to contain the text node "%s" in <%s>.',child.nodeValue,parentNode.nodeName.toLowerCase());}}function warnForInsertedHydratedElement(parentNode,tag,props){{if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Expected server HTML to contain a matching <%s> in <%s>.',tag,parentNode.nodeName.toLowerCase());}}function warnForInsertedHydratedText(parentNode,text){{if(text===''){// We expect to insert empty text nodes since they're not represented in
// the HTML.
// TODO: Remove this special case if we can just avoid inserting empty
// text nodes.
return;}if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Expected server HTML to contain a matching text node for "%s" in <%s>.',text,parentNode.nodeName.toLowerCase());}}function restoreControlledState$3(domElement,tag,props){switch(tag){case'input':restoreControlledState(domElement,props);return;case'textarea':restoreControlledState$2(domElement,props);return;case'select':restoreControlledState$1(domElement,props);return;}}var validateDOMNesting=function(){};var updatedAncestorInfo=function(){};{// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags=['address','applet','area','article','aside','base','basefont','bgsound','blockquote','body','br','button','caption','center','col','colgroup','dd','details','dir','div','dl','dt','embed','fieldset','figcaption','figure','footer','form','frame','frameset','h1','h2','h3','h4','h5','h6','head','header','hgroup','hr','html','iframe','img','input','isindex','li','link','listing','main','marquee','menu','menuitem','meta','nav','noembed','noframes','noscript','object','ol','p','param','plaintext','pre','script','section','select','source','style','summary','table','tbody','td','template','textarea','tfoot','th','thead','title','tr','track','ul','wbr','xmp'];// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags=['applet','caption','html','table','td','th','marquee','object','template',// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject','desc','title'];// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags=inScopeTags.concat(['button']);// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags=['dd','dt','li','option','optgroup','p','rp','rt'];var emptyAncestorInfo={current:null,formTag:null,aTagInScope:null,buttonTagInScope:null,nobrTagInScope:null,pTagInButtonScope:null,listItemTagAutoclosing:null,dlItemTagAutoclosing:null};updatedAncestorInfo=function(oldInfo,tag){var ancestorInfo=_assign({},oldInfo||emptyAncestorInfo);var info={tag:tag};if(inScopeTags.indexOf(tag)!==-1){ancestorInfo.aTagInScope=null;ancestorInfo.buttonTagInScope=null;ancestorInfo.nobrTagInScope=null;}if(buttonScopeTags.indexOf(tag)!==-1){ancestorInfo.pTagInButtonScope=null;}// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if(specialTags.indexOf(tag)!==-1&&tag!=='address'&&tag!=='div'&&tag!=='p'){ancestorInfo.listItemTagAutoclosing=null;ancestorInfo.dlItemTagAutoclosing=null;}ancestorInfo.current=info;if(tag==='form'){ancestorInfo.formTag=info;}if(tag==='a'){ancestorInfo.aTagInScope=info;}if(tag==='button'){ancestorInfo.buttonTagInScope=info;}if(tag==='nobr'){ancestorInfo.nobrTagInScope=info;}if(tag==='p'){ancestorInfo.pTagInButtonScope=info;}if(tag==='li'){ancestorInfo.listItemTagAutoclosing=info;}if(tag==='dd'||tag==='dt'){ancestorInfo.dlItemTagAutoclosing=info;}return ancestorInfo;};/**
* Returns whether
*/var isTagValidWithParent=function(tag,parentTag){// First, let's check if we're in an unusual parsing mode...
switch(parentTag){// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case'select':return tag==='option'||tag==='optgroup'||tag==='#text';case'optgroup':return tag==='option'||tag==='#text';// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case'option':return tag==='#text';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case'tr':return tag==='th'||tag==='td'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case'tbody':case'thead':case'tfoot':return tag==='tr'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case'colgroup':return tag==='col'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case'table':return tag==='caption'||tag==='colgroup'||tag==='tbody'||tag==='tfoot'||tag==='thead'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case'head':return tag==='base'||tag==='basefont'||tag==='bgsound'||tag==='link'||tag==='meta'||tag==='title'||tag==='noscript'||tag==='noframes'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case'html':return tag==='head'||tag==='body'||tag==='frameset';case'frameset':return tag==='frame';case'#document':return tag==='html';}// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch(tag){case'h1':case'h2':case'h3':case'h4':case'h5':case'h6':return parentTag!=='h1'&&parentTag!=='h2'&&parentTag!=='h3'&&parentTag!=='h4'&&parentTag!=='h5'&&parentTag!=='h6';case'rp':case'rt':return impliedEndTags.indexOf(parentTag)===-1;case'body':case'caption':case'col':case'colgroup':case'frameset':case'frame':case'head':case'html':case'tbody':case'td':case'tfoot':case'th':case'thead':case'tr':// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag==null;}return true;};/**
* Returns whether
*/var findInvalidAncestorForTag=function(tag,ancestorInfo){switch(tag){case'address':case'article':case'aside':case'blockquote':case'center':case'details':case'dialog':case'dir':case'div':case'dl':case'fieldset':case'figcaption':case'figure':case'footer':case'header':case'hgroup':case'main':case'menu':case'nav':case'ol':case'p':case'section':case'summary':case'ul':case'pre':case'listing':case'table':case'hr':case'xmp':case'h1':case'h2':case'h3':case'h4':case'h5':case'h6':return ancestorInfo.pTagInButtonScope;case'form':return ancestorInfo.formTag||ancestorInfo.pTagInButtonScope;case'li':return ancestorInfo.listItemTagAutoclosing;case'dd':case'dt':return ancestorInfo.dlItemTagAutoclosing;case'button':return ancestorInfo.buttonTagInScope;case'a':// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;case'nobr':return ancestorInfo.nobrTagInScope;}return null;};var didWarn$1={};validateDOMNesting=function(childTag,childText,ancestorInfo){ancestorInfo=ancestorInfo||emptyAncestorInfo;var parentInfo=ancestorInfo.current;var parentTag=parentInfo&&parentInfo.tag;if(childText!=null){if(childTag!=null){error('validateDOMNesting: when childText is passed, childTag should be null');}childTag='#text';}var invalidParent=isTagValidWithParent(childTag,parentTag)?null:parentInfo;var invalidAncestor=invalidParent?null:findInvalidAncestorForTag(childTag,ancestorInfo);var invalidParentOrAncestor=invalidParent||invalidAncestor;if(!invalidParentOrAncestor){return;}var ancestorTag=invalidParentOrAncestor.tag;var warnKey=!!invalidParent+'|'+childTag+'|'+ancestorTag;if(didWarn$1[warnKey]){return;}didWarn$1[warnKey]=true;var tagDisplayName=childTag;var whitespaceInfo='';if(childTag==='#text'){if(/\S/.test(childText)){tagDisplayName='Text nodes';}else {tagDisplayName='Whitespace text nodes';whitespaceInfo=" Make sure you don't have any extra whitespace between tags on "+'each line of your source code.';}}else {tagDisplayName='<'+childTag+'>';}if(invalidParent){var info='';if(ancestorTag==='table'&&childTag==='tr'){info+=' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by '+'the browser.';}error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s',tagDisplayName,ancestorTag,whitespaceInfo,info);}else {error('validateDOMNesting(...): %s cannot appear as a descendant of '+'<%s>.',tagDisplayName,ancestorTag);}};}var SUPPRESS_HYDRATION_WARNING$1;{SUPPRESS_HYDRATION_WARNING$1='suppressHydrationWarning';}var SUSPENSE_START_DATA='$';var SUSPENSE_END_DATA='/$';var SUSPENSE_PENDING_START_DATA='$?';var SUSPENSE_FALLBACK_START_DATA='$!';var STYLE$1='style';var eventsEnabled=null;var selectionInformation=null;function shouldAutoFocusHostComponent(type,props){switch(type){case'button':case'input':case'select':case'textarea':return !!props.autoFocus;}return false;}function getRootHostContext(rootContainerInstance){var type;var namespace;var nodeType=rootContainerInstance.nodeType;switch(nodeType){case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:{type=nodeType===DOCUMENT_NODE?'#document':'#fragment';var root=rootContainerInstance.documentElement;namespace=root?root.namespaceURI:getChildNamespace(null,'');break;}default:{var container=nodeType===COMMENT_NODE?rootContainerInstance.parentNode:rootContainerInstance;var ownNamespace=container.namespaceURI||null;type=container.tagName;namespace=getChildNamespace(ownNamespace,type);break;}}{var validatedTag=type.toLowerCase();var ancestorInfo=updatedAncestorInfo(null,validatedTag);return {namespace:namespace,ancestorInfo:ancestorInfo};}}function getChildHostContext(parentHostContext,type,rootContainerInstance){{var parentHostContextDev=parentHostContext;var namespace=getChildNamespace(parentHostContextDev.namespace,type);var ancestorInfo=updatedAncestorInfo(parentHostContextDev.ancestorInfo,type);return {namespace:namespace,ancestorInfo:ancestorInfo};}}function getPublicInstance(instance){return instance;}function prepareForCommit(containerInfo){eventsEnabled=isEnabled();selectionInformation=getSelectionInformation();var activeInstance=null;setEnabled(false);return activeInstance;}function resetAfterCommit(containerInfo){restoreSelection(selectionInformation);setEnabled(eventsEnabled);eventsEnabled=null;selectionInformation=null;}function createInstance(type,props,rootContainerInstance,hostContext,internalInstanceHandle){var parentNamespace;{// TODO: take namespace into account when validating.
var hostContextDev=hostContext;validateDOMNesting(type,null,hostContextDev.ancestorInfo);if(typeof props.children==='string'||typeof props.children==='number'){var string=''+props.children;var ownAncestorInfo=updatedAncestorInfo(hostContextDev.ancestorInfo,type);validateDOMNesting(null,string,ownAncestorInfo);}parentNamespace=hostContextDev.namespace;}var domElement=createElement(type,props,rootContainerInstance,parentNamespace);precacheFiberNode(internalInstanceHandle,domElement);updateFiberProps(domElement,props);return domElement;}function appendInitialChild(parentInstance,child){parentInstance.appendChild(child);}function finalizeInitialChildren(domElement,type,props,rootContainerInstance,hostContext){setInitialProperties(domElement,type,props,rootContainerInstance);return shouldAutoFocusHostComponent(type,props);}function prepareUpdate(domElement,type,oldProps,newProps,rootContainerInstance,hostContext){{var hostContextDev=hostContext;if(typeof newProps.children!==typeof oldProps.children&&(typeof newProps.children==='string'||typeof newProps.children==='number')){var string=''+newProps.children;var ownAncestorInfo=updatedAncestorInfo(hostContextDev.ancestorInfo,type);validateDOMNesting(null,string,ownAncestorInfo);}}return diffProperties(domElement,type,oldProps,newProps);}function shouldSetTextContent(type,props){return type==='textarea'||type==='option'||type==='noscript'||typeof props.children==='string'||typeof props.children==='number'||typeof props.dangerouslySetInnerHTML==='object'&&props.dangerouslySetInnerHTML!==null&&props.dangerouslySetInnerHTML.__html!=null;}function createTextInstance(text,rootContainerInstance,hostContext,internalInstanceHandle){{var hostContextDev=hostContext;validateDOMNesting(null,text,hostContextDev.ancestorInfo);}var textNode=createTextNode(text,rootContainerInstance);precacheFiberNode(internalInstanceHandle,textNode);return textNode;}// if a component just imports ReactDOM (e.g. for findDOMNode).
// Some environments might not have setTimeout or clearTimeout.
var scheduleTimeout=typeof setTimeout==='function'?setTimeout:undefined;var cancelTimeout=typeof clearTimeout==='function'?clearTimeout:undefined;var noTimeout=-1;// -------------------
function commitMount(domElement,type,newProps,internalInstanceHandle){// Despite the naming that might imply otherwise, this method only
// fires if there is an `Update` effect scheduled during mounting.
// This happens if `finalizeInitialChildren` returns `true` (which it
// does to implement the `autoFocus` attribute on the client). But
// there are also other cases when this might happen (such as patching
// up text content during hydration mismatch). So we'll check this again.
if(shouldAutoFocusHostComponent(type,newProps)){domElement.focus();}}function commitUpdate(domElement,updatePayload,type,oldProps,newProps,internalInstanceHandle){// Update the props handle so that we know which props are the ones with
// with current event handlers.
updateFiberProps(domElement,newProps);// Apply the diff to the DOM node.
updateProperties(domElement,updatePayload,type,oldProps,newProps);}function resetTextContent(domElement){setTextContent(domElement,'');}function commitTextUpdate(textInstance,oldText,newText){textInstance.nodeValue=newText;}function appendChild(parentInstance,child){parentInstance.appendChild(child);}function appendChildToContainer(container,child){var parentNode;if(container.nodeType===COMMENT_NODE){parentNode=container.parentNode;parentNode.insertBefore(child,container);}else {parentNode=container;parentNode.appendChild(child);}// This container might be used for a portal.
// If something inside a portal is clicked, that click should bubble
// through the React tree. However, on Mobile Safari the click would
// never bubble through the *DOM* tree unless an ancestor with onclick
// event exists. So we wouldn't see it and dispatch it.
// This is why we ensure that non React root containers have inline onclick
// defined.
// https://github.com/facebook/react/issues/11918
var reactRootContainer=container._reactRootContainer;if((reactRootContainer===null||reactRootContainer===undefined)&&parentNode.onclick===null){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(parentNode);}}function insertBefore(parentInstance,child,beforeChild){parentInstance.insertBefore(child,beforeChild);}function insertInContainerBefore(container,child,beforeChild){if(container.nodeType===COMMENT_NODE){container.parentNode.insertBefore(child,beforeChild);}else {container.insertBefore(child,beforeChild);}}function removeChild(parentInstance,child){parentInstance.removeChild(child);}function removeChildFromContainer(container,child){if(container.nodeType===COMMENT_NODE){container.parentNode.removeChild(child);}else {container.removeChild(child);}}function hideInstance(instance){// TODO: Does this work for all element types? What about MathML? Should we
// pass host context to this method?
instance=instance;var style=instance.style;if(typeof style.setProperty==='function'){style.setProperty('display','none','important');}else {style.display='none';}}function hideTextInstance(textInstance){textInstance.nodeValue='';}function unhideInstance(instance,props){instance=instance;var styleProp=props[STYLE$1];var display=styleProp!==undefined&&styleProp!==null&&styleProp.hasOwnProperty('display')?styleProp.display:null;instance.style.display=dangerousStyleValue('display',display);}function unhideTextInstance(textInstance,text){textInstance.nodeValue=text;}function clearContainer(container){if(container.nodeType===ELEMENT_NODE){container.textContent='';}else if(container.nodeType===DOCUMENT_NODE){var body=container.body;if(body!=null){body.textContent='';}}}// -------------------
function canHydrateInstance(instance,type,props){if(instance.nodeType!==ELEMENT_NODE||type.toLowerCase()!==instance.nodeName.toLowerCase()){return null;}// This has now been refined to an element node.
return instance;}function canHydrateTextInstance(instance,text){if(text===''||instance.nodeType!==TEXT_NODE){// Empty strings are not parsed by HTML so there won't be a correct match here.
return null;}// This has now been refined to a text node.
return instance;}function isSuspenseInstancePending(instance){return instance.data===SUSPENSE_PENDING_START_DATA;}function isSuspenseInstanceFallback(instance){return instance.data===SUSPENSE_FALLBACK_START_DATA;}function getNextHydratable(node){// Skip non-hydratable nodes.
for(;node!=null;node=node.nextSibling){var nodeType=node.nodeType;if(nodeType===ELEMENT_NODE||nodeType===TEXT_NODE){break;}}return node;}function getNextHydratableSibling(instance){return getNextHydratable(instance.nextSibling);}function getFirstHydratableChild(parentInstance){return getNextHydratable(parentInstance.firstChild);}function hydrateInstance(instance,type,props,rootContainerInstance,hostContext,internalInstanceHandle){precacheFiberNode(internalInstanceHandle,instance);// TODO: Possibly defer this until the commit phase where all the events
// get attached.
updateFiberProps(instance,props);var parentNamespace;{var hostContextDev=hostContext;parentNamespace=hostContextDev.namespace;}return diffHydratedProperties(instance,type,props,parentNamespace);}function hydrateTextInstance(textInstance,text,internalInstanceHandle){precacheFiberNode(internalInstanceHandle,textInstance);return diffHydratedText(textInstance,text);}function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance){var node=suspenseInstance.nextSibling;// Skip past all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth=0;while(node){if(node.nodeType===COMMENT_NODE){var data=node.data;if(data===SUSPENSE_END_DATA){if(depth===0){return getNextHydratableSibling(node);}else {depth--;}}else if(data===SUSPENSE_START_DATA||data===SUSPENSE_FALLBACK_START_DATA||data===SUSPENSE_PENDING_START_DATA){depth++;}}node=node.nextSibling;}// TODO: Warn, we didn't find the end comment boundary.
return null;}// Returns the SuspenseInstance if this node is a direct child of a
// SuspenseInstance. I.e. if its previous sibling is a Comment with
// SUSPENSE_x_START_DATA. Otherwise, null.
function getParentSuspenseInstance(targetInstance){var node=targetInstance.previousSibling;// Skip past all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth=0;while(node){if(node.nodeType===COMMENT_NODE){var data=node.data;if(data===SUSPENSE_START_DATA||data===SUSPENSE_FALLBACK_START_DATA||data===SUSPENSE_PENDING_START_DATA){if(depth===0){return node;}else {depth--;}}else if(data===SUSPENSE_END_DATA){depth++;}}node=node.previousSibling;}return null;}function commitHydratedContainer(container){// Retry if any event replaying was blocked on this.
retryIfBlockedOn(container);}function commitHydratedSuspenseInstance(suspenseInstance){// Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);}function didNotMatchHydratedContainerTextInstance(parentContainer,textInstance,text){{warnForUnmatchedText(textInstance,text);}}function didNotMatchHydratedTextInstance(parentType,parentProps,parentInstance,textInstance,text){if(parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){warnForUnmatchedText(textInstance,text);}}function didNotHydrateContainerInstance(parentContainer,instance){{if(instance.nodeType===ELEMENT_NODE){warnForDeletedHydratableElement(parentContainer,instance);}else if(instance.nodeType===COMMENT_NODE);else {warnForDeletedHydratableText(parentContainer,instance);}}}function didNotHydrateInstance(parentType,parentProps,parentInstance,instance){if(parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){if(instance.nodeType===ELEMENT_NODE){warnForDeletedHydratableElement(parentInstance,instance);}else if(instance.nodeType===COMMENT_NODE);else {warnForDeletedHydratableText(parentInstance,instance);}}}function didNotFindHydratableContainerInstance(parentContainer,type,props){{warnForInsertedHydratedElement(parentContainer,type);}}function didNotFindHydratableContainerTextInstance(parentContainer,text){{warnForInsertedHydratedText(parentContainer,text);}}function didNotFindHydratableInstance(parentType,parentProps,parentInstance,type,props){if(parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){warnForInsertedHydratedElement(parentInstance,type);}}function didNotFindHydratableTextInstance(parentType,parentProps,parentInstance,text){if(parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){warnForInsertedHydratedText(parentInstance,text);}}function didNotFindHydratableSuspenseInstance(parentType,parentProps,parentInstance){if(parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true);}var clientId=0;function makeClientIdInDEV(warnOnAccessInDEV){var id='r:'+(clientId++).toString(36);return {toString:function(){warnOnAccessInDEV();return id;},valueOf:function(){warnOnAccessInDEV();return id;}};}function isOpaqueHydratingObject(value){return value!==null&&typeof value==='object'&&value.$$typeof===REACT_OPAQUE_ID_TYPE;}function makeOpaqueHydratingObject(attemptToReadValue){return {$$typeof:REACT_OPAQUE_ID_TYPE,toString:attemptToReadValue,valueOf:attemptToReadValue};}function preparePortalMount(portalInstance){{listenToAllSupportedEvents(portalInstance);}}var randomKey=Math.random().toString(36).slice(2);var internalInstanceKey='__reactFiber$'+randomKey;var internalPropsKey='__reactProps$'+randomKey;var internalContainerInstanceKey='__reactContainer$'+randomKey;var internalEventHandlersKey='__reactEvents$'+randomKey;function precacheFiberNode(hostInst,node){node[internalInstanceKey]=hostInst;}function markContainerAsRoot(hostRoot,node){node[internalContainerInstanceKey]=hostRoot;}function unmarkContainerAsRoot(node){node[internalContainerInstanceKey]=null;}function isContainerMarkedAsRoot(node){return !!node[internalContainerInstanceKey];}// Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
// If the target node is part of a hydrated or not yet rendered subtree, then
// this may also return a SuspenseComponent or HostRoot to indicate that.
// Conceptually the HostRoot fiber is a child of the Container node. So if you
// pass the Container node as the targetNode, you will not actually get the
// HostRoot back. To get to the HostRoot, you need to pass a child of it.
// The same thing applies to Suspense boundaries.
function getClosestInstanceFromNode(targetNode){var targetInst=targetNode[internalInstanceKey];if(targetInst){// Don't return HostRoot or SuspenseComponent here.
return targetInst;}// If the direct event target isn't a React owned DOM node, we need to look
// to see if one of its parents is a React owned DOM node.
var parentNode=targetNode.parentNode;while(parentNode){// We'll check if this is a container root that could include
// React nodes in the future. We need to check this first because
// if we're a child of a dehydrated container, we need to first
// find that inner container before moving on to finding the parent
// instance. Note that we don't check this field on the targetNode
// itself because the fibers are conceptually between the container
// node and the first child. It isn't surrounding the container node.
// If it's not a container, we check if it's an instance.
targetInst=parentNode[internalContainerInstanceKey]||parentNode[internalInstanceKey];if(targetInst){// Since this wasn't the direct target of the event, we might have
// stepped past dehydrated DOM nodes to get here. However they could
// also have been non-React nodes. We need to answer which one.
// If we the instance doesn't have any children, then there can't be
// a nested suspense boundary within it. So we can use this as a fast
// bailout. Most of the time, when people add non-React children to
// the tree, it is using a ref to a child-less DOM node.
// Normally we'd only need to check one of the fibers because if it
// has ever gone from having children to deleting them or vice versa
// it would have deleted the dehydrated boundary nested inside already.
// However, since the HostRoot starts out with an alternate it might
// have one on the alternate so we need to check in case this was a
// root.
var alternate=targetInst.alternate;if(targetInst.child!==null||alternate!==null&&alternate.child!==null){// Next we need to figure out if the node that skipped past is
// nested within a dehydrated boundary and if so, which one.
var suspenseInstance=getParentSuspenseInstance(targetNode);while(suspenseInstance!==null){// We found a suspense instance. That means that we haven't
// hydrated it yet. Even though we leave the comments in the
// DOM after hydrating, and there are boundaries in the DOM
// that could already be hydrated, we wouldn't have found them
// through this pass since if the target is hydrated it would
// have had an internalInstanceKey on it.
// Let's get the fiber associated with the SuspenseComponent
// as the deepest instance.
var targetSuspenseInst=suspenseInstance[internalInstanceKey];if(targetSuspenseInst){return targetSuspenseInst;}// If we don't find a Fiber on the comment, it might be because
// we haven't gotten to hydrate it yet. There might still be a
// parent boundary that hasn't above this one so we need to find
// the outer most that is known.
suspenseInstance=getParentSuspenseInstance(suspenseInstance);// If we don't find one, then that should mean that the parent
// host component also hasn't hydrated yet. We can return it
// below since it will bail out on the isMounted check later.
}}return targetInst;}targetNode=parentNode;parentNode=targetNode.parentNode;}return null;}/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/function getInstanceFromNode(node){var inst=node[internalInstanceKey]||node[internalContainerInstanceKey];if(inst){if(inst.tag===HostComponent||inst.tag===HostText||inst.tag===SuspenseComponent||inst.tag===HostRoot){return inst;}else {return null;}}return null;}/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/function getNodeFromInstance(inst){if(inst.tag===HostComponent||inst.tag===HostText){// In Fiber this, is just the state node right now. We assume it will be
// a host component or host text.
return inst.stateNode;}// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
{{throw Error("getNodeFromInstance: Invalid argument.");}}}function getFiberCurrentPropsFromNode(node){return node[internalPropsKey]||null;}function updateFiberProps(node,props){node[internalPropsKey]=props;}function getEventListenerSet(node){var elementListenerSet=node[internalEventHandlersKey];if(elementListenerSet===undefined){elementListenerSet=node[internalEventHandlersKey]=new Set();}return elementListenerSet;}var loggedTypeFailures={};var ReactDebugCurrentFrame$1=ReactSharedInternals.ReactDebugCurrentFrame;function setCurrentlyValidatingElement(element){{if(element){var owner=element._owner;var stack=describeUnknownElementTypeFrameInDEV(element.type,element._source,owner?owner.type:null);ReactDebugCurrentFrame$1.setExtraStackFrame(stack);}else {ReactDebugCurrentFrame$1.setExtraStackFrame(null);}}}function checkPropTypes(typeSpecs,values,location,componentName,element){{// $FlowFixMe This is okay but Flow doesn't know it.
var has=Function.call.bind(Object.prototype.hasOwnProperty);for(var typeSpecName in typeSpecs){if(has(typeSpecs,typeSpecName)){var error$1=void 0;// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try{// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if(typeof typeSpecs[typeSpecName]!=='function'){var err=Error((componentName||'React class')+': '+location+' type `'+typeSpecName+'` is invalid; '+'it must be a function, usually from the `prop-types` package, but received `'+typeof typeSpecs[typeSpecName]+'`.'+'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');err.name='Invariant Violation';throw err;}error$1=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');}catch(ex){error$1=ex;}if(error$1&&!(error$1 instanceof Error)){setCurrentlyValidatingElement(element);error('%s: type specification of %s'+' `%s` is invalid; the type checker '+'function must return `null` or an `Error` but returned a %s. '+'You may have forgotten to pass an argument to the type checker '+'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and '+'shape all require an argument).',componentName||'React class',location,typeSpecName,typeof error$1);setCurrentlyValidatingElement(null);}if(error$1 instanceof Error&&!(error$1.message in loggedTypeFailures)){// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message]=true;setCurrentlyValidatingElement(element);error('Failed %s type: %s',location,error$1.message);setCurrentlyValidatingElement(null);}}}}}var valueStack=[];var fiberStack;{fiberStack=[];}var index=-1;function createCursor(defaultValue){return {current:defaultValue};}function pop(cursor,fiber){if(index<0){{error('Unexpected pop.');}return;}{if(fiber!==fiberStack[index]){error('Unexpected Fiber popped.');}}cursor.current=valueStack[index];valueStack[index]=null;{fiberStack[index]=null;}index--;}function push(cursor,value,fiber){index++;valueStack[index]=cursor.current;{fiberStack[index]=fiber;}cursor.current=value;}var warnedAboutMissingGetChildContext;{warnedAboutMissingGetChildContext={};}var emptyContextObject={};{Object.freeze(emptyContextObject);}// A cursor to the current merged context object on the stack.
var contextStackCursor=createCursor(emptyContextObject);// A cursor to a boolean indicating whether the context has changed.
var didPerformWorkStackCursor=createCursor(false);// Keep track of the previous context object that was on the stack.
// We use this to get access to the parent context after we have already
// pushed the next context provider, and now need to merge their contexts.
var previousContext=emptyContextObject;function getUnmaskedContext(workInProgress,Component,didPushOwnContextIfProvider){{if(didPushOwnContextIfProvider&&isContextProvider(Component)){// If the fiber is a context provider itself, when we read its context
// we may have already pushed its own child context on the stack. A context
// provider should not "see" its own child context. Therefore we read the
// previous (parent) context instead for a context provider.
return previousContext;}return contextStackCursor.current;}}function cacheContext(workInProgress,unmaskedContext,maskedContext){{var instance=workInProgress.stateNode;instance.__reactInternalMemoizedUnmaskedChildContext=unmaskedContext;instance.__reactInternalMemoizedMaskedChildContext=maskedContext;}}function getMaskedContext(workInProgress,unmaskedContext){{var type=workInProgress.type;var contextTypes=type.contextTypes;if(!contextTypes){return emptyContextObject;}// Avoid recreating masked context unless unmasked context has changed.
// Failing to do this will result in unnecessary calls to componentWillReceiveProps.
// This may trigger infinite loops if componentWillReceiveProps calls setState.
var instance=workInProgress.stateNode;if(instance&&instance.__reactInternalMemoizedUnmaskedChildContext===unmaskedContext){return instance.__reactInternalMemoizedMaskedChildContext;}var context={};for(var key in contextTypes){context[key]=unmaskedContext[key];}{var name=getComponentName(type)||'Unknown';checkPropTypes(contextTypes,context,'context',name);}// Cache unmasked context so we can avoid recreating masked context unless necessary.
// Context is created before the class component is instantiated so check for instance.
if(instance){cacheContext(workInProgress,unmaskedContext,context);}return context;}}function hasContextChanged(){{return didPerformWorkStackCursor.current;}}function isContextProvider(type){{var childContextTypes=type.childContextTypes;return childContextTypes!==null&&childContextTypes!==undefined;}}function popContext(fiber){{pop(didPerformWorkStackCursor,fiber);pop(contextStackCursor,fiber);}}function popTopLevelContextObject(fiber){{pop(didPerformWorkStackCursor,fiber);pop(contextStackCursor,fiber);}}function pushTopLevelContextObject(fiber,context,didChange){{if(!(contextStackCursor.current===emptyContextObject)){{throw Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");}}push(contextStackCursor,context,fiber);push(didPerformWorkStackCursor,didChange,fiber);}}function processChildContext(fiber,type,parentContext){{var instance=fiber.stateNode;var childContextTypes=type.childContextTypes;// TODO (bvaughn) Replace this behavior with an invariant() in the future.
// It has only been added in Fiber to match the (unintentional) behavior in Stack.
if(typeof instance.getChildContext!=='function'){{var componentName=getComponentName(type)||'Unknown';if(!warnedAboutMissingGetChildContext[componentName]){warnedAboutMissingGetChildContext[componentName]=true;error('%s.childContextTypes is specified but there is no getChildContext() method '+'on the instance. You can either define getChildContext() on %s or remove '+'childContextTypes from it.',componentName,componentName);}}return parentContext;}var childContext=instance.getChildContext();for(var contextKey in childContext){if(!(contextKey in childContextTypes)){{throw Error((getComponentName(type)||'Unknown')+".getChildContext(): key \""+contextKey+"\" is not defined in childContextTypes.");}}}{var name=getComponentName(type)||'Unknown';checkPropTypes(childContextTypes,childContext,'child context',name);}return _assign({},parentContext,childContext);}}function pushContextProvider(workInProgress){{var instance=workInProgress.stateNode;// We push the context as early as possible to ensure stack integrity.
// If the instance does not exist yet, we will push null at first,
// and replace it on the stack later when invalidating the context.
var memoizedMergedChildContext=instance&&instance.__reactInternalMemoizedMergedChildContext||emptyContextObject;// Remember the parent context so we can merge with it later.
// Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
previousContext=contextStackCursor.current;push(contextStackCursor,memoizedMergedChildContext,workInProgress);push(didPerformWorkStackCursor,didPerformWorkStackCursor.current,workInProgress);return true;}}function invalidateContextProvider(workInProgress,type,didChange){{var instance=workInProgress.stateNode;if(!instance){{throw Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");}}if(didChange){// Merge parent and own context.
// Skip this if we're not updating due to sCU.
// This avoids unnecessarily recomputing memoized values.
var mergedContext=processChildContext(workInProgress,type,previousContext);instance.__reactInternalMemoizedMergedChildContext=mergedContext;// Replace the old (or empty) context with the new one.
// It is important to unwind the context in the reverse order.
pop(didPerformWorkStackCursor,workInProgress);pop(contextStackCursor,workInProgress);// Now push the new context and mark that it has changed.
push(contextStackCursor,mergedContext,workInProgress);push(didPerformWorkStackCursor,didChange,workInProgress);}else {pop(didPerformWorkStackCursor,workInProgress);push(didPerformWorkStackCursor,didChange,workInProgress);}}}function findCurrentUnmaskedContext(fiber){{// Currently this is only used with renderSubtreeIntoContainer; not sure if it
// makes sense elsewhere
if(!(isFiberMounted(fiber)&&fiber.tag===ClassComponent)){{throw Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");}}var node=fiber;do{switch(node.tag){case HostRoot:return node.stateNode.context;case ClassComponent:{var Component=node.type;if(isContextProvider(Component)){return node.stateNode.__reactInternalMemoizedMergedChildContext;}break;}}node=node.return;}while(node!==null);{{throw Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");}}}}var LegacyRoot=0;var BlockingRoot=1;var ConcurrentRoot=2;var rendererID=null;var injectedHook=null;var hasLoggedError=false;var isDevToolsPresent=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!=='undefined';function injectInternals(internals){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__==='undefined'){// No DevTools
return false;}var hook=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(hook.isDisabled){// This isn't a real property on the hook, but it can be set to opt out
// of DevTools integration and associated warnings and logs.
// https://github.com/facebook/react/issues/3877
return true;}if(!hook.supportsFiber){{error('The installed version of React DevTools is too old and will not work '+'with the current version of React. Please update React DevTools. '+'https://reactjs.org/link/react-devtools');}// DevTools exists, even though it doesn't support Fiber.
return true;}try{rendererID=hook.inject(internals);// We have successfully injected, so now it is safe to set up hooks.
injectedHook=hook;}catch(err){// Catch all errors because it is unsafe to throw during initialization.
{error('React instrumentation encountered an error: %s.',err);}}// DevTools exists
return true;}function onScheduleRoot(root,children){{if(injectedHook&&typeof injectedHook.onScheduleFiberRoot==='function'){try{injectedHook.onScheduleFiberRoot(rendererID,root,children);}catch(err){if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}function onCommitRoot(root,priorityLevel){if(injectedHook&&typeof injectedHook.onCommitFiberRoot==='function'){try{var didError=(root.current.flags&DidCapture)===DidCapture;if(enableProfilerTimer){injectedHook.onCommitFiberRoot(rendererID,root,priorityLevel,didError);}}catch(err){{if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}function onCommitUnmount(fiber){if(injectedHook&&typeof injectedHook.onCommitFiberUnmount==='function'){try{injectedHook.onCommitFiberUnmount(rendererID,fiber);}catch(err){{if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}var Scheduler_runWithPriority=Scheduler.unstable_runWithPriority,Scheduler_scheduleCallback=Scheduler.unstable_scheduleCallback,Scheduler_cancelCallback=Scheduler.unstable_cancelCallback,Scheduler_shouldYield=Scheduler.unstable_shouldYield,Scheduler_requestPaint=Scheduler.unstable_requestPaint,Scheduler_now$1=Scheduler.unstable_now,Scheduler_getCurrentPriorityLevel=Scheduler.unstable_getCurrentPriorityLevel,Scheduler_ImmediatePriority=Scheduler.unstable_ImmediatePriority,Scheduler_UserBlockingPriority=Scheduler.unstable_UserBlockingPriority,Scheduler_NormalPriority=Scheduler.unstable_NormalPriority,Scheduler_LowPriority=Scheduler.unstable_LowPriority,Scheduler_IdlePriority=Scheduler.unstable_IdlePriority;{// Provide explicit error message when production+profiling bundle of e.g.
// react-dom is used with production (non-profiling) bundle of
// scheduler/tracing
if(!(tracing$1.__interactionsRef!=null&&tracing$1.__interactionsRef.current!=null)){{throw Error("It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at https://reactjs.org/link/profiling");}}}var fakeCallbackNode={};// Except for NoPriority, these correspond to Scheduler priorities. We use
// ascending numbers so we can compare them like numbers. They start at 90 to
// avoid clashing with Scheduler's priorities.
var ImmediatePriority$1=99;var UserBlockingPriority$2=98;var NormalPriority$1=97;var LowPriority$1=96;var IdlePriority$1=95;// NoPriority is the absence of priority. Also React-only.
var NoPriority$1=90;var shouldYield=Scheduler_shouldYield;var requestPaint=// Fall back gracefully if we're running an older version of Scheduler.
Scheduler_requestPaint!==undefined?Scheduler_requestPaint:function(){};var syncQueue=null;var immediateQueueCallbackNode=null;var isFlushingSyncQueue=false;var initialTimeMs$1=Scheduler_now$1();// If the initial timestamp is reasonably small, use Scheduler's `now` directly.
// This will be the case for modern browsers that support `performance.now`. In
// older browsers, Scheduler falls back to `Date.now`, which returns a Unix
// timestamp. In that case, subtract the module initialization time to simulate
// the behavior of performance.now and keep our times small enough to fit
// within 32 bits.
// TODO: Consider lifting this into Scheduler.
var now=initialTimeMs$1<10000?Scheduler_now$1:function(){return Scheduler_now$1()-initialTimeMs$1;};function getCurrentPriorityLevel(){switch(Scheduler_getCurrentPriorityLevel()){case Scheduler_ImmediatePriority:return ImmediatePriority$1;case Scheduler_UserBlockingPriority:return UserBlockingPriority$2;case Scheduler_NormalPriority:return NormalPriority$1;case Scheduler_LowPriority:return LowPriority$1;case Scheduler_IdlePriority:return IdlePriority$1;default:{{throw Error("Unknown priority level.");}}}}function reactPriorityToSchedulerPriority(reactPriorityLevel){switch(reactPriorityLevel){case ImmediatePriority$1:return Scheduler_ImmediatePriority;case UserBlockingPriority$2:return Scheduler_UserBlockingPriority;case NormalPriority$1:return Scheduler_NormalPriority;case LowPriority$1:return Scheduler_LowPriority;case IdlePriority$1:return Scheduler_IdlePriority;default:{{throw Error("Unknown priority level.");}}}}function runWithPriority$1(reactPriorityLevel,fn){var priorityLevel=reactPriorityToSchedulerPriority(reactPriorityLevel);return Scheduler_runWithPriority(priorityLevel,fn);}function scheduleCallback(reactPriorityLevel,callback,options){var priorityLevel=reactPriorityToSchedulerPriority(reactPriorityLevel);return Scheduler_scheduleCallback(priorityLevel,callback,options);}function scheduleSyncCallback(callback){// Push this callback into an internal queue. We'll flush these either in
// the next tick, or earlier if something calls `flushSyncCallbackQueue`.
if(syncQueue===null){syncQueue=[callback];// Flush the queue in the next tick, at the earliest.
immediateQueueCallbackNode=Scheduler_scheduleCallback(Scheduler_ImmediatePriority,flushSyncCallbackQueueImpl);}else {// Push onto existing queue. Don't need to schedule a callback because
// we already scheduled one when we created the queue.
syncQueue.push(callback);}return fakeCallbackNode;}function cancelCallback(callbackNode){if(callbackNode!==fakeCallbackNode){Scheduler_cancelCallback(callbackNode);}}function flushSyncCallbackQueue(){if(immediateQueueCallbackNode!==null){var node=immediateQueueCallbackNode;immediateQueueCallbackNode=null;Scheduler_cancelCallback(node);}flushSyncCallbackQueueImpl();}function flushSyncCallbackQueueImpl(){if(!isFlushingSyncQueue&&syncQueue!==null){// Prevent re-entrancy.
isFlushingSyncQueue=true;var i=0;{try{var _isSync2=true;var _queue=syncQueue;runWithPriority$1(ImmediatePriority$1,function(){for(;i<_queue.length;i++){var callback=_queue[i];do{callback=callback(_isSync2);}while(callback!==null);}});syncQueue=null;}catch(error){// If something throws, leave the remaining callbacks on the queue.
if(syncQueue!==null){syncQueue=syncQueue.slice(i+1);}// Resume flushing in the next tick
Scheduler_scheduleCallback(Scheduler_ImmediatePriority,flushSyncCallbackQueue);throw error;}finally{isFlushingSyncQueue=false;}}}}// TODO: this is special because it gets imported during build.
var ReactVersion='17.0.2';var NoMode=0;var StrictMode=1;// TODO: Remove BlockingMode and ConcurrentMode by reading from the root
// tag instead
var BlockingMode=2;var ConcurrentMode=4;var ProfileMode=8;var DebugTracingMode=16;var ReactCurrentBatchConfig=ReactSharedInternals.ReactCurrentBatchConfig;var NoTransition=0;function requestCurrentTransition(){return ReactCurrentBatchConfig.transition;}var ReactStrictModeWarnings={recordUnsafeLifecycleWarnings:function(fiber,instance){},flushPendingUnsafeLifecycleWarnings:function(){},recordLegacyContextWarning:function(fiber,instance){},flushLegacyContextWarning:function(){},discardPendingWarnings:function(){}};{var findStrictRoot=function(fiber){var maybeStrictRoot=null;var node=fiber;while(node!==null){if(node.mode&StrictMode){maybeStrictRoot=node;}node=node.return;}return maybeStrictRoot;};var setToSortedString=function(set){var array=[];set.forEach(function(value){array.push(value);});return array.sort().join(', ');};var pendingComponentWillMountWarnings=[];var pendingUNSAFE_ComponentWillMountWarnings=[];var pendingComponentWillReceivePropsWarnings=[];var pendingUNSAFE_ComponentWillReceivePropsWarnings=[];var pendingComponentWillUpdateWarnings=[];var pendingUNSAFE_ComponentWillUpdateWarnings=[];// Tracks components we have already warned about.
var didWarnAboutUnsafeLifecycles=new Set();ReactStrictModeWarnings.recordUnsafeLifecycleWarnings=function(fiber,instance){// Dedup strategy: Warn once per component.
if(didWarnAboutUnsafeLifecycles.has(fiber.type)){return;}if(typeof instance.componentWillMount==='function'&&// Don't warn about react-lifecycles-compat polyfilled components.
instance.componentWillMount.__suppressDeprecationWarning!==true){pendingComponentWillMountWarnings.push(fiber);}if(fiber.mode&StrictMode&&typeof instance.UNSAFE_componentWillMount==='function'){pendingUNSAFE_ComponentWillMountWarnings.push(fiber);}if(typeof instance.componentWillReceiveProps==='function'&&instance.componentWillReceiveProps.__suppressDeprecationWarning!==true){pendingComponentWillReceivePropsWarnings.push(fiber);}if(fiber.mode&StrictMode&&typeof instance.UNSAFE_componentWillReceiveProps==='function'){pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);}if(typeof instance.componentWillUpdate==='function'&&instance.componentWillUpdate.__suppressDeprecationWarning!==true){pendingComponentWillUpdateWarnings.push(fiber);}if(fiber.mode&StrictMode&&typeof instance.UNSAFE_componentWillUpdate==='function'){pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);}};ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings=function(){// We do an initial pass to gather component names
var componentWillMountUniqueNames=new Set();if(pendingComponentWillMountWarnings.length>0){pendingComponentWillMountWarnings.forEach(function(fiber){componentWillMountUniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingComponentWillMountWarnings=[];}var UNSAFE_componentWillMountUniqueNames=new Set();if(pendingUNSAFE_ComponentWillMountWarnings.length>0){pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber){UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingUNSAFE_ComponentWillMountWarnings=[];}var componentWillReceivePropsUniqueNames=new Set();if(pendingComponentWillReceivePropsWarnings.length>0){pendingComponentWillReceivePropsWarnings.forEach(function(fiber){componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingComponentWillReceivePropsWarnings=[];}var UNSAFE_componentWillReceivePropsUniqueNames=new Set();if(pendingUNSAFE_ComponentWillReceivePropsWarnings.length>0){pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber){UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingUNSAFE_ComponentWillReceivePropsWarnings=[];}var componentWillUpdateUniqueNames=new Set();if(pendingComponentWillUpdateWarnings.length>0){pendingComponentWillUpdateWarnings.forEach(function(fiber){componentWillUpdateUniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingComponentWillUpdateWarnings=[];}var UNSAFE_componentWillUpdateUniqueNames=new Set();if(pendingUNSAFE_ComponentWillUpdateWarnings.length>0){pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber){UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingUNSAFE_ComponentWillUpdateWarnings=[];}// Finally, we flush all the warnings
// UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
if(UNSAFE_componentWillMountUniqueNames.size>0){var sortedNames=setToSortedString(UNSAFE_componentWillMountUniqueNames);error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move code with side effects to componentDidMount, and set initial state in the constructor.\n'+'\nPlease update the following components: %s',sortedNames);}if(UNSAFE_componentWillReceivePropsUniqueNames.size>0){var _sortedNames=setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended '+'and may indicate bugs in your code. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+"* If you're updating state whenever props change, "+'refactor your code to use memoization techniques or move it to '+'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n'+'\nPlease update the following components: %s',_sortedNames);}if(UNSAFE_componentWillUpdateUniqueNames.size>0){var _sortedNames2=setToSortedString(UNSAFE_componentWillUpdateUniqueNames);error('Using UNSAFE_componentWillUpdate in strict mode is not recommended '+'and may indicate bugs in your code. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+'\nPlease update the following components: %s',_sortedNames2);}if(componentWillMountUniqueNames.size>0){var _sortedNames3=setToSortedString(componentWillMountUniqueNames);warn('componentWillMount has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move code with side effects to componentDidMount, and set initial state in the constructor.\n'+'* Rename componentWillMount to UNSAFE_componentWillMount to suppress '+'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. '+'To rename all deprecated lifecycles to their new names, you can run '+'`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n'+'\nPlease update the following components: %s',_sortedNames3);}if(componentWillReceivePropsUniqueNames.size>0){var _sortedNames4=setToSortedString(componentWillReceivePropsUniqueNames);warn('componentWillReceiveProps has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+"* If you're updating state whenever props change, refactor your "+'code to use memoization techniques or move it to '+'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n'+'* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress '+'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. '+'To rename all deprecated lifecycles to their new names, you can run '+'`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n'+'\nPlease update the following components: %s',_sortedNames4);}if(componentWillUpdateUniqueNames.size>0){var _sortedNames5=setToSortedString(componentWillUpdateUniqueNames);warn('componentWillUpdate has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+'* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress '+'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. '+'To rename all deprecated lifecycles to their new names, you can run '+'`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n'+'\nPlease update the following components: %s',_sortedNames5);}};var pendingLegacyContextWarning=new Map();// Tracks components we have already warned about.
var didWarnAboutLegacyContext=new Set();ReactStrictModeWarnings.recordLegacyContextWarning=function(fiber,instance){var strictRoot=findStrictRoot(fiber);if(strictRoot===null){error('Expected to find a StrictMode component in a strict mode tree. '+'This error is likely caused by a bug in React. Please file an issue.');return;}// Dedup strategy: Warn once per component.
if(didWarnAboutLegacyContext.has(fiber.type)){return;}var warningsForRoot=pendingLegacyContextWarning.get(strictRoot);if(fiber.type.contextTypes!=null||fiber.type.childContextTypes!=null||instance!==null&&typeof instance.getChildContext==='function'){if(warningsForRoot===undefined){warningsForRoot=[];pendingLegacyContextWarning.set(strictRoot,warningsForRoot);}warningsForRoot.push(fiber);}};ReactStrictModeWarnings.flushLegacyContextWarning=function(){pendingLegacyContextWarning.forEach(function(fiberArray,strictRoot){if(fiberArray.length===0){return;}var firstFiber=fiberArray[0];var uniqueNames=new Set();fiberArray.forEach(function(fiber){uniqueNames.add(getComponentName(fiber.type)||'Component');didWarnAboutLegacyContext.add(fiber.type);});var sortedNames=setToSortedString(uniqueNames);try{setCurrentFiber(firstFiber);error('Legacy context API has been detected within a strict-mode tree.'+'\n\nThe old API will be supported in all 16.x releases, but applications '+'using it should migrate to the new version.'+'\n\nPlease update the following components: %s'+'\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context',sortedNames);}finally{resetCurrentFiber();}});};ReactStrictModeWarnings.discardPendingWarnings=function(){pendingComponentWillMountWarnings=[];pendingUNSAFE_ComponentWillMountWarnings=[];pendingComponentWillReceivePropsWarnings=[];pendingUNSAFE_ComponentWillReceivePropsWarnings=[];pendingComponentWillUpdateWarnings=[];pendingUNSAFE_ComponentWillUpdateWarnings=[];pendingLegacyContextWarning=new Map();};}function resolveDefaultProps(Component,baseProps){if(Component&&Component.defaultProps){// Resolve default props. Taken from ReactElement
var props=_assign({},baseProps);var defaultProps=Component.defaultProps;for(var propName in defaultProps){if(props[propName]===undefined){props[propName]=defaultProps[propName];}}return props;}return baseProps;}// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var MAX_SIGNED_31_BIT_INT=1073741823;var valueCursor=createCursor(null);var rendererSigil;{// Use this to detect multiple renderers using the same context
rendererSigil={};}var currentlyRenderingFiber=null;var lastContextDependency=null;var lastContextWithAllBitsObserved=null;var isDisallowedContextReadInDEV=false;function resetContextDependencies(){// This is called right before React yields execution, to ensure `readContext`
// cannot be called outside the render phase.
currentlyRenderingFiber=null;lastContextDependency=null;lastContextWithAllBitsObserved=null;{isDisallowedContextReadInDEV=false;}}function enterDisallowedContextReadInDEV(){{isDisallowedContextReadInDEV=true;}}function exitDisallowedContextReadInDEV(){{isDisallowedContextReadInDEV=false;}}function pushProvider(providerFiber,nextValue){var context=providerFiber.type._context;{push(valueCursor,context._currentValue,providerFiber);context._currentValue=nextValue;{if(context._currentRenderer!==undefined&&context._currentRenderer!==null&&context._currentRenderer!==rendererSigil){error('Detected multiple renderers concurrently rendering the '+'same context provider. This is currently unsupported.');}context._currentRenderer=rendererSigil;}}}function popProvider(providerFiber){var currentValue=valueCursor.current;pop(valueCursor,providerFiber);var context=providerFiber.type._context;{context._currentValue=currentValue;}}function calculateChangedBits(context,newValue,oldValue){if(objectIs(oldValue,newValue)){// No change
return 0;}else {var changedBits=typeof context._calculateChangedBits==='function'?context._calculateChangedBits(oldValue,newValue):MAX_SIGNED_31_BIT_INT;{if((changedBits&MAX_SIGNED_31_BIT_INT)!==changedBits){error('calculateChangedBits: Expected the return value to be a '+'31-bit integer. Instead received: %s',changedBits);}}return changedBits|0;}}function scheduleWorkOnParentPath(parent,renderLanes){// Update the child lanes of all the ancestors, including the alternates.
var node=parent;while(node!==null){var alternate=node.alternate;if(!isSubsetOfLanes(node.childLanes,renderLanes)){node.childLanes=mergeLanes(node.childLanes,renderLanes);if(alternate!==null){alternate.childLanes=mergeLanes(alternate.childLanes,renderLanes);}}else if(alternate!==null&&!isSubsetOfLanes(alternate.childLanes,renderLanes)){alternate.childLanes=mergeLanes(alternate.childLanes,renderLanes);}else {// Neither alternate was updated, which means the rest of the
// ancestor path already has sufficient priority.
break;}node=node.return;}}function propagateContextChange(workInProgress,context,changedBits,renderLanes){var fiber=workInProgress.child;if(fiber!==null){// Set the return pointer of the child to the work-in-progress fiber.
fiber.return=workInProgress;}while(fiber!==null){var nextFiber=void 0;// Visit this fiber.
var list=fiber.dependencies;if(list!==null){nextFiber=fiber.child;var dependency=list.firstContext;while(dependency!==null){// Check if the context matches.
if(dependency.context===context&&(dependency.observedBits&changedBits)!==0){// Match! Schedule an update on this fiber.
if(fiber.tag===ClassComponent){// Schedule a force update on the work-in-progress.
var update=createUpdate(NoTimestamp,pickArbitraryLane(renderLanes));update.tag=ForceUpdate;// TODO: Because we don't have a work-in-progress, this will add the
// update to the current fiber, too, which means it will persist even if
// this render is thrown away. Since it's a race condition, not sure it's
// worth fixing.
enqueueUpdate(fiber,update);}fiber.lanes=mergeLanes(fiber.lanes,renderLanes);var alternate=fiber.alternate;if(alternate!==null){alternate.lanes=mergeLanes(alternate.lanes,renderLanes);}scheduleWorkOnParentPath(fiber.return,renderLanes);// Mark the updated lanes on the list, too.
list.lanes=mergeLanes(list.lanes,renderLanes);// Since we already found a match, we can stop traversing the
// dependency list.
break;}dependency=dependency.next;}}else if(fiber.tag===ContextProvider){// Don't scan deeper if this is a matching provider
nextFiber=fiber.type===workInProgress.type?null:fiber.child;}else {// Traverse down.
nextFiber=fiber.child;}if(nextFiber!==null){// Set the return pointer of the child to the work-in-progress fiber.
nextFiber.return=fiber;}else {// No child. Traverse to next sibling.
nextFiber=fiber;while(nextFiber!==null){if(nextFiber===workInProgress){// We're back to the root of this subtree. Exit.
nextFiber=null;break;}var sibling=nextFiber.sibling;if(sibling!==null){// Set the return pointer of the sibling to the work-in-progress fiber.
sibling.return=nextFiber.return;nextFiber=sibling;break;}// No more siblings. Traverse up.
nextFiber=nextFiber.return;}}fiber=nextFiber;}}function prepareToReadContext(workInProgress,renderLanes){currentlyRenderingFiber=workInProgress;lastContextDependency=null;lastContextWithAllBitsObserved=null;var dependencies=workInProgress.dependencies;if(dependencies!==null){var firstContext=dependencies.firstContext;if(firstContext!==null){if(includesSomeLane(dependencies.lanes,renderLanes)){// Context list has a pending update. Mark that this fiber performed work.
markWorkInProgressReceivedUpdate();}// Reset the work-in-progress list
dependencies.firstContext=null;}}}function readContext(context,observedBits){{// This warning would fire if you read context inside a Hook like useMemo.
// Unlike the class check below, it's not enforced in production for perf.
if(isDisallowedContextReadInDEV){error('Context can only be read while React is rendering. '+'In classes, you can read it in the render method or getDerivedStateFromProps. '+'In function components, you can read it directly in the function body, but not '+'inside Hooks like useReducer() or useMemo().');}}if(lastContextWithAllBitsObserved===context);else if(observedBits===false||observedBits===0);else {var resolvedObservedBits;// Avoid deopting on observable arguments or heterogeneous types.
if(typeof observedBits!=='number'||observedBits===MAX_SIGNED_31_BIT_INT){// Observe all updates.
lastContextWithAllBitsObserved=context;resolvedObservedBits=MAX_SIGNED_31_BIT_INT;}else {resolvedObservedBits=observedBits;}var contextItem={context:context,observedBits:resolvedObservedBits,next:null};if(lastContextDependency===null){if(!(currentlyRenderingFiber!==null)){{throw Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");}}// This is the first dependency for this component. Create a new list.
lastContextDependency=contextItem;currentlyRenderingFiber.dependencies={lanes:NoLanes,firstContext:contextItem,responders:null};}else {// Append a new context item.
lastContextDependency=lastContextDependency.next=contextItem;}}return context._currentValue;}var UpdateState=0;var ReplaceState=1;var ForceUpdate=2;var CaptureUpdate=3;// Global state that is reset at the beginning of calling `processUpdateQueue`.
// It should only be read right after calling `processUpdateQueue`, via
// `checkHasForceUpdateAfterProcessing`.
var hasForceUpdate=false;var didWarnUpdateInsideUpdate;var currentlyProcessingQueue;{didWarnUpdateInsideUpdate=false;currentlyProcessingQueue=null;}function initializeUpdateQueue(fiber){var queue={baseState:fiber.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null},effects:null};fiber.updateQueue=queue;}function cloneUpdateQueue(current,workInProgress){// Clone the update queue from current. Unless it's already a clone.
var queue=workInProgress.updateQueue;var currentQueue=current.updateQueue;if(queue===currentQueue){var clone={baseState:currentQueue.baseState,firstBaseUpdate:currentQueue.firstBaseUpdate,lastBaseUpdate:currentQueue.lastBaseUpdate,shared:currentQueue.shared,effects:currentQueue.effects};workInProgress.updateQueue=clone;}}function createUpdate(eventTime,lane){var update={eventTime:eventTime,lane:lane,tag:UpdateState,payload:null,callback:null,next:null};return update;}function enqueueUpdate(fiber,update){var updateQueue=fiber.updateQueue;if(updateQueue===null){// Only occurs if the fiber has been unmounted.
return;}var sharedQueue=updateQueue.shared;var pending=sharedQueue.pending;if(pending===null){// This is the first update. Create a circular list.
update.next=update;}else {update.next=pending.next;pending.next=update;}sharedQueue.pending=update;{if(currentlyProcessingQueue===sharedQueue&&!didWarnUpdateInsideUpdate){error('An update (setState, replaceState, or forceUpdate) was scheduled '+'from inside an update function. Update functions should be pure, '+'with zero side-effects. Consider using componentDidUpdate or a '+'callback.');didWarnUpdateInsideUpdate=true;}}}function enqueueCapturedUpdate(workInProgress,capturedUpdate){// Captured updates are updates that are thrown by a child during the render
// phase. They should be discarded if the render is aborted. Therefore,
// we should only put them on the work-in-progress queue, not the current one.
var queue=workInProgress.updateQueue;// Check if the work-in-progress queue is a clone.
var current=workInProgress.alternate;if(current!==null){var currentQueue=current.updateQueue;if(queue===currentQueue){// The work-in-progress queue is the same as current. This happens when
// we bail out on a parent fiber that then captures an error thrown by
// a child. Since we want to append the update only to the work-in
// -progress queue, we need to clone the updates. We usually clone during
// processUpdateQueue, but that didn't happen in this case because we
// skipped over the parent when we bailed out.
var newFirst=null;var newLast=null;var firstBaseUpdate=queue.firstBaseUpdate;if(firstBaseUpdate!==null){// Loop through the updates and clone them.
var update=firstBaseUpdate;do{var clone={eventTime:update.eventTime,lane:update.lane,tag:update.tag,payload:update.payload,callback:update.callback,next:null};if(newLast===null){newFirst=newLast=clone;}else {newLast.next=clone;newLast=clone;}update=update.next;}while(update!==null);// Append the captured update the end of the cloned list.
if(newLast===null){newFirst=newLast=capturedUpdate;}else {newLast.next=capturedUpdate;newLast=capturedUpdate;}}else {// There are no base updates.
newFirst=newLast=capturedUpdate;}queue={baseState:currentQueue.baseState,firstBaseUpdate:newFirst,lastBaseUpdate:newLast,shared:currentQueue.shared,effects:currentQueue.effects};workInProgress.updateQueue=queue;return;}}// Append the update to the end of the list.
var lastBaseUpdate=queue.lastBaseUpdate;if(lastBaseUpdate===null){queue.firstBaseUpdate=capturedUpdate;}else {lastBaseUpdate.next=capturedUpdate;}queue.lastBaseUpdate=capturedUpdate;}function getStateFromUpdate(workInProgress,queue,update,prevState,nextProps,instance){switch(update.tag){case ReplaceState:{var payload=update.payload;if(typeof payload==='function'){// Updater function
{enterDisallowedContextReadInDEV();}var nextState=payload.call(instance,prevState,nextProps);{if(workInProgress.mode&StrictMode){disableLogs();try{payload.call(instance,prevState,nextProps);}finally{reenableLogs();}}exitDisallowedContextReadInDEV();}return nextState;}// State object
return payload;}case CaptureUpdate:{workInProgress.flags=workInProgress.flags&~ShouldCapture|DidCapture;}// Intentional fallthrough
case UpdateState:{var _payload=update.payload;var partialState;if(typeof _payload==='function'){// Updater function
{enterDisallowedContextReadInDEV();}partialState=_payload.call(instance,prevState,nextProps);{if(workInProgress.mode&StrictMode){disableLogs();try{_payload.call(instance,prevState,nextProps);}finally{reenableLogs();}}exitDisallowedContextReadInDEV();}}else {// Partial state object
partialState=_payload;}if(partialState===null||partialState===undefined){// Null and undefined are treated as no-ops.
return prevState;}// Merge the partial state and the previous state.
return _assign({},prevState,partialState);}case ForceUpdate:{hasForceUpdate=true;return prevState;}}return prevState;}function processUpdateQueue(workInProgress,props,instance,renderLanes){// This is always non-null on a ClassComponent or HostRoot
var queue=workInProgress.updateQueue;hasForceUpdate=false;{currentlyProcessingQueue=queue.shared;}var firstBaseUpdate=queue.firstBaseUpdate;var lastBaseUpdate=queue.lastBaseUpdate;// Check if there are pending updates. If so, transfer them to the base queue.
var pendingQueue=queue.shared.pending;if(pendingQueue!==null){queue.shared.pending=null;// The pending queue is circular. Disconnect the pointer between first
// and last so that it's non-circular.
var lastPendingUpdate=pendingQueue;var firstPendingUpdate=lastPendingUpdate.next;lastPendingUpdate.next=null;// Append pending updates to base queue
if(lastBaseUpdate===null){firstBaseUpdate=firstPendingUpdate;}else {lastBaseUpdate.next=firstPendingUpdate;}lastBaseUpdate=lastPendingUpdate;// If there's a current queue, and it's different from the base queue, then
// we need to transfer the updates to that queue, too. Because the base
// queue is a singly-linked list with no cycles, we can append to both
// lists and take advantage of structural sharing.
// TODO: Pass `current` as argument
var current=workInProgress.alternate;if(current!==null){// This is always non-null on a ClassComponent or HostRoot
var currentQueue=current.updateQueue;var currentLastBaseUpdate=currentQueue.lastBaseUpdate;if(currentLastBaseUpdate!==lastBaseUpdate){if(currentLastBaseUpdate===null){currentQueue.firstBaseUpdate=firstPendingUpdate;}else {currentLastBaseUpdate.next=firstPendingUpdate;}currentQueue.lastBaseUpdate=lastPendingUpdate;}}}// These values may change as we process the queue.
if(firstBaseUpdate!==null){// Iterate through the list of updates to compute the result.
var newState=queue.baseState;// TODO: Don't need to accumulate this. Instead, we can remove renderLanes
// from the original lanes.
var newLanes=NoLanes;var newBaseState=null;var newFirstBaseUpdate=null;var newLastBaseUpdate=null;var update=firstBaseUpdate;do{var updateLane=update.lane;var updateEventTime=update.eventTime;if(!isSubsetOfLanes(renderLanes,updateLane)){// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
var clone={eventTime:updateEventTime,lane:updateLane,tag:update.tag,payload:update.payload,callback:update.callback,next:null};if(newLastBaseUpdate===null){newFirstBaseUpdate=newLastBaseUpdate=clone;newBaseState=newState;}else {newLastBaseUpdate=newLastBaseUpdate.next=clone;}// Update the remaining priority in the queue.
newLanes=mergeLanes(newLanes,updateLane);}else {// This update does have sufficient priority.
if(newLastBaseUpdate!==null){var _clone={eventTime:updateEventTime,// This update is going to be committed so we never want uncommit
// it. Using NoLane works because 0 is a subset of all bitmasks, so
// this will never be skipped by the check above.
lane:NoLane,tag:update.tag,payload:update.payload,callback:update.callback,next:null};newLastBaseUpdate=newLastBaseUpdate.next=_clone;}// Process this update.
newState=getStateFromUpdate(workInProgress,queue,update,newState,props,instance);var callback=update.callback;if(callback!==null){workInProgress.flags|=Callback;var effects=queue.effects;if(effects===null){queue.effects=[update];}else {effects.push(update);}}}update=update.next;if(update===null){pendingQueue=queue.shared.pending;if(pendingQueue===null){break;}else {// An update was scheduled from inside a reducer. Add the new
// pending updates to the end of the list and keep processing.
var _lastPendingUpdate=pendingQueue;// Intentionally unsound. Pending updates form a circular list, but we
// unravel them when transferring them to the base queue.
var _firstPendingUpdate=_lastPendingUpdate.next;_lastPendingUpdate.next=null;update=_firstPendingUpdate;queue.lastBaseUpdate=_lastPendingUpdate;queue.shared.pending=null;}}}while(true);if(newLastBaseUpdate===null){newBaseState=newState;}queue.baseState=newBaseState;queue.firstBaseUpdate=newFirstBaseUpdate;queue.lastBaseUpdate=newLastBaseUpdate;// Set the remaining expiration time to be whatever is remaining in the queue.
// This should be fine because the only two other things that contribute to
// expiration time are props and context. We're already in the middle of the
// begin phase by the time we start processing the queue, so we've already
// dealt with the props. Context in components that specify
// shouldComponentUpdate is tricky; but we'll have to account for
// that regardless.
markSkippedUpdateLanes(newLanes);workInProgress.lanes=newLanes;workInProgress.memoizedState=newState;}{currentlyProcessingQueue=null;}}function callCallback(callback,context){if(!(typeof callback==='function')){{throw Error("Invalid argument passed as callback. Expected a function. Instead received: "+callback);}}callback.call(context);}function resetHasForceUpdateBeforeProcessing(){hasForceUpdate=false;}function checkHasForceUpdateAfterProcessing(){return hasForceUpdate;}function commitUpdateQueue(finishedWork,finishedQueue,instance){// Commit the effects
var effects=finishedQueue.effects;finishedQueue.effects=null;if(effects!==null){for(var i=0;i<effects.length;i++){var effect=effects[i];var callback=effect.callback;if(callback!==null){effect.callback=null;callCallback(callback,instance);}}}}var fakeInternalInstance={};var isArray=Array.isArray;// React.Component uses a shared frozen object by default.
// We'll use it to determine whether we need to initialize legacy refs.
var emptyRefsObject=new React.Component().refs;var didWarnAboutStateAssignmentForComponent;var didWarnAboutUninitializedState;var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;var didWarnAboutLegacyLifecyclesAndDerivedState;var didWarnAboutUndefinedDerivedState;var warnOnUndefinedDerivedState;var warnOnInvalidCallback;var didWarnAboutDirectlyAssigningPropsToState;var didWarnAboutContextTypeAndContextTypes;var didWarnAboutInvalidateContextType;{didWarnAboutStateAssignmentForComponent=new Set();didWarnAboutUninitializedState=new Set();didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate=new Set();didWarnAboutLegacyLifecyclesAndDerivedState=new Set();didWarnAboutDirectlyAssigningPropsToState=new Set();didWarnAboutUndefinedDerivedState=new Set();didWarnAboutContextTypeAndContextTypes=new Set();didWarnAboutInvalidateContextType=new Set();var didWarnOnInvalidCallback=new Set();warnOnInvalidCallback=function(callback,callerName){if(callback===null||typeof callback==='function'){return;}var key=callerName+'_'+callback;if(!didWarnOnInvalidCallback.has(key)){didWarnOnInvalidCallback.add(key);error('%s(...): Expected the last optional `callback` argument to be a '+'function. Instead received: %s.',callerName,callback);}};warnOnUndefinedDerivedState=function(type,partialState){if(partialState===undefined){var componentName=getComponentName(type)||'Component';if(!didWarnAboutUndefinedDerivedState.has(componentName)){didWarnAboutUndefinedDerivedState.add(componentName);error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. '+'You have returned undefined.',componentName);}}};// This is so gross but it's at least non-critical and can be removed if
// it causes problems. This is meant to give a nicer error message for
// ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
// ...)) which otherwise throws a "_processChildContext is not a function"
// exception.
Object.defineProperty(fakeInternalInstance,'_processChildContext',{enumerable:false,value:function(){{{throw Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).");}}}});Object.freeze(fakeInternalInstance);}function applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,nextProps){var prevState=workInProgress.memoizedState;{if(workInProgress.mode&StrictMode){disableLogs();try{// Invoke the function an extra time to help detect side-effects.
getDerivedStateFromProps(nextProps,prevState);}finally{reenableLogs();}}}var partialState=getDerivedStateFromProps(nextProps,prevState);{warnOnUndefinedDerivedState(ctor,partialState);}// Merge the partial state and the previous state.
var memoizedState=partialState===null||partialState===undefined?prevState:_assign({},prevState,partialState);workInProgress.memoizedState=memoizedState;// Once the update queue is empty, persist the derived state onto the
// base state.
if(workInProgress.lanes===NoLanes){// Queue is always non-null for classes
var updateQueue=workInProgress.updateQueue;updateQueue.baseState=memoizedState;}}var classComponentUpdater={isMounted:isMounted,enqueueSetState:function(inst,payload,callback){var fiber=get(inst);var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update=createUpdate(eventTime,lane);update.payload=payload;if(callback!==undefined&&callback!==null){{warnOnInvalidCallback(callback,'setState');}update.callback=callback;}enqueueUpdate(fiber,update);scheduleUpdateOnFiber(fiber,lane,eventTime);},enqueueReplaceState:function(inst,payload,callback){var fiber=get(inst);var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update=createUpdate(eventTime,lane);update.tag=ReplaceState;update.payload=payload;if(callback!==undefined&&callback!==null){{warnOnInvalidCallback(callback,'replaceState');}update.callback=callback;}enqueueUpdate(fiber,update);scheduleUpdateOnFiber(fiber,lane,eventTime);},enqueueForceUpdate:function(inst,callback){var fiber=get(inst);var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update=createUpdate(eventTime,lane);update.tag=ForceUpdate;if(callback!==undefined&&callback!==null){{warnOnInvalidCallback(callback,'forceUpdate');}update.callback=callback;}enqueueUpdate(fiber,update);scheduleUpdateOnFiber(fiber,lane,eventTime);}};function checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext){var instance=workInProgress.stateNode;if(typeof instance.shouldComponentUpdate==='function'){{if(workInProgress.mode&StrictMode){disableLogs();try{// Invoke the function an extra time to help detect side-effects.
instance.shouldComponentUpdate(newProps,newState,nextContext);}finally{reenableLogs();}}}var shouldUpdate=instance.shouldComponentUpdate(newProps,newState,nextContext);{if(shouldUpdate===undefined){error('%s.shouldComponentUpdate(): Returned undefined instead of a '+'boolean value. Make sure to return true or false.',getComponentName(ctor)||'Component');}}return shouldUpdate;}if(ctor.prototype&&ctor.prototype.isPureReactComponent){return !shallowEqual(oldProps,newProps)||!shallowEqual(oldState,newState);}return true;}function checkClassInstance(workInProgress,ctor,newProps){var instance=workInProgress.stateNode;{var name=getComponentName(ctor)||'Component';var renderPresent=instance.render;if(!renderPresent){if(ctor.prototype&&typeof ctor.prototype.render==='function'){error('%s(...): No `render` method found on the returned component '+'instance: did you accidentally return an object from the constructor?',name);}else {error('%s(...): No `render` method found on the returned component '+'instance: you may have forgotten to define `render`.',name);}}if(instance.getInitialState&&!instance.getInitialState.isReactClassApproved&&!instance.state){error('getInitialState was defined on %s, a plain JavaScript class. '+'This is only supported for classes created using React.createClass. '+'Did you mean to define a state property instead?',name);}if(instance.getDefaultProps&&!instance.getDefaultProps.isReactClassApproved){error('getDefaultProps was defined on %s, a plain JavaScript class. '+'This is only supported for classes created using React.createClass. '+'Use a static property to define defaultProps instead.',name);}if(instance.propTypes){error('propTypes was defined as an instance property on %s. Use a static '+'property to define propTypes instead.',name);}if(instance.contextType){error('contextType was defined as an instance property on %s. Use a static '+'property to define contextType instead.',name);}{if(instance.contextTypes){error('contextTypes was defined as an instance property on %s. Use a static '+'property to define contextTypes instead.',name);}if(ctor.contextType&&ctor.contextTypes&&!didWarnAboutContextTypeAndContextTypes.has(ctor)){didWarnAboutContextTypeAndContextTypes.add(ctor);error('%s declares both contextTypes and contextType static properties. '+'The legacy contextTypes property will be ignored.',name);}}if(typeof instance.componentShouldUpdate==='function'){error('%s has a method called '+'componentShouldUpdate(). Did you mean shouldComponentUpdate()? '+'The name is phrased as a question because the function is '+'expected to return a value.',name);}if(ctor.prototype&&ctor.prototype.isPureReactComponent&&typeof instance.shouldComponentUpdate!=='undefined'){error('%s has a method called shouldComponentUpdate(). '+'shouldComponentUpdate should not be used when extending React.PureComponent. '+'Please extend React.Component if shouldComponentUpdate is used.',getComponentName(ctor)||'A pure component');}if(typeof instance.componentDidUnmount==='function'){error('%s has a method called '+'componentDidUnmount(). But there is no such lifecycle method. '+'Did you mean componentWillUnmount()?',name);}if(typeof instance.componentDidReceiveProps==='function'){error('%s has a method called '+'componentDidReceiveProps(). But there is no such lifecycle method. '+'If you meant to update the state in response to changing props, '+'use componentWillReceiveProps(). If you meant to fetch data or '+'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',name);}if(typeof instance.componentWillRecieveProps==='function'){error('%s has a method called '+'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',name);}if(typeof instance.UNSAFE_componentWillRecieveProps==='function'){error('%s has a method called '+'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?',name);}var hasMutatedProps=instance.props!==newProps;if(instance.props!==undefined&&hasMutatedProps){error('%s(...): When calling super() in `%s`, make sure to pass '+"up the same
set(instance,workInProgress);{instance._reactInternalInstance=fakeInternalInstance;}}function constructClassInstance(workInProgress,ctor,props){var isLegacyContextConsumer=false;var unmaskedContext=emptyContextObject;var context=emptyContextObject;var contextType=ctor.contextType;{if('contextType'in ctor){var isValid=// Allow null for conditional declaration
contextType===null||contextType!==undefined&&contextType.$$typeof===REACT_CONTEXT_TYPE&&contextType._context===undefined;// Not a <Context.Consumer>
if(!isValid&&!didWarnAboutInvalidateContextType.has(ctor)){didWarnAboutInvalidateContextType.add(ctor);var addendum='';if(contextType===undefined){addendum=' However, it is set to undefined. '+'This can be caused by a typo or by mixing up named and default imports. '+'This can also happen due to a circular dependency, so '+'try moving the createContext() call to a separate file.';}else if(typeof contextType!=='object'){addendum=' However, it is set to a '+typeof contextType+'.';}else if(contextType.$$typeof===REACT_PROVIDER_TYPE){addendum=' Did you accidentally pass the Context.Provider instead?';}else if(contextType._context!==undefined){// <Context.Consumer>
addendum=' Did you accidentally pass the Context.Consumer instead?';}else {addendum=' However, it is set to an object with keys {'+Object.keys(contextType).join(', ')+'}.';}error('%s defines an invalid contextType. '+'contextType should point to the Context object returned by React.createContext().%s',getComponentName(ctor)||'Component',addendum);}}}if(typeof contextType==='object'&&contextType!==null){context=readContext(contextType);}else {unmaskedContext=getUnmaskedContext(workInProgress,ctor,true);var contextTypes=ctor.contextTypes;isLegacyContextConsumer=contextTypes!==null&&contextTypes!==undefined;context=isLegacyContextConsumer?getMaskedContext(workInProgress,unmaskedContext):emptyContextObject;}// Instantiate twice to help detect side-effects.
{if(workInProgress.mode&StrictMode){disableLogs();try{new ctor(props,context);// eslint-disable-line no-new
}finally{reenableLogs();}}}var instance=new ctor(props,context);var state=workInProgress.memoizedState=instance.state!==null&&instance.state!==undefined?instance.state:null;adoptClassInstance(workInProgress,instance);{if(typeof ctor.getDerivedStateFromProps==='function'&&state===null){var componentName=getComponentName(ctor)||'Component';if(!didWarnAboutUninitializedState.has(componentName)){didWarnAboutUninitializedState.add(componentName);error('`%s` uses `getDerivedStateFromProps` but its initial state is '+'%s. This is not recommended. Instead, define the initial state by '+'assigning an object to `this.state` in the constructor of `%s`. '+'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.',componentName,instance.state===null?'null':'undefined',componentName);}}// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Warn about these lifecycles if they are present.
// Don't warn about react-lifecycles-compat polyfilled methods though.
if(typeof ctor.getDerivedStateFromProps==='function'||typeof instance.getSnapshotBeforeUpdate==='function'){var foundWillMountName=null;var foundWillReceivePropsName=null;var foundWillUpdateName=null;if(typeof instance.componentWillMount==='function'&&instance.componentWillMount.__suppressDeprecationWarning!==true){foundWillMountName='componentWillMount';}else if(typeof instance.UNSAFE_componentWillMount==='function'){foundWillMountName='UNSAFE_componentWillMount';}if(typeof instance.componentWillReceiveProps==='function'&&instance.componentWillReceiveProps.__suppressDeprecationWarning!==true){foundWillReceivePropsName='componentWillReceiveProps';}else if(typeof instance.UNSAFE_componentWillReceiveProps==='function'){foundWillReceivePropsName='UNSAFE_componentWillReceiveProps';}if(typeof instance.componentWillUpdate==='function'&&instance.componentWillUpdate.__suppressDeprecationWarning!==true){foundWillUpdateName='componentWillUpdate';}else if(typeof instance.UNSAFE_componentWillUpdate==='function'){foundWillUpdateName='UNSAFE_componentWillUpdate';}if(foundWillMountName!==null||foundWillReceivePropsName!==null||foundWillUpdateName!==null){var _componentName=getComponentName(ctor)||'Component';var newApiName=typeof ctor.getDerivedStateFromProps==='function'?'getDerivedStateFromProps()':'getSnapshotBeforeUpdate()';if(!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)){didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n'+'%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n'+'The above lifecycles should be removed. Learn more about this warning here:\n'+'https://reactjs.org/link/unsafe-component-lifecycles',_componentName,newApiName,foundWillMountName!==null?"\n "+foundWillMountName:'',foundWillReceivePropsName!==null?"\n "+foundWillReceivePropsName:'',foundWillUpdateName!==null?"\n "+foundWillUpdateName:'');}}}}// Cache unmasked context so we can avoid recreating masked context unless necessary.
// ReactFiberContext usually updates this cache but can't for newly-created instances.
if(isLegacyContextConsumer){cacheContext(workInProgress,unmaskedContext,context);}return instance;}function callComponentWillMount(workInProgress,instance){var oldState=instance.state;if(typeof instance.componentWillMount==='function'){instance.componentWillMount();}if(typeof instance.UNSAFE_componentWillMount==='function'){instance.UNSAFE_componentWillMount();}if(oldState!==instance.state){{error('%s.componentWillMount(): Assigning directly to this.state is '+"deprecated (except inside a component's "+'constructor). Use setState instead.',getComponentName(workInProgress.type)||'Component');}classComponentUpdater.enqueueReplaceState(instance,instance.state,null);}}function callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext){var oldState=instance.state;if(typeof instance.componentWillReceiveProps==='function'){instance.componentWillReceiveProps(newProps,nextContext);}if(typeof instance.UNSAFE_componentWillReceiveProps==='function'){instance.UNSAFE_componentWillReceiveProps(newProps,nextContext);}if(instance.state!==oldState){{var componentName=getComponentName(workInProgress.type)||'Component';if(!didWarnAboutStateAssignmentForComponent.has(componentName)){didWarnAboutStateAssignmentForComponent.add(componentName);error('%s.componentWillReceiveProps(): Assigning directly to '+"this.state is deprecated (except inside a component's "+'constructor). Use setState instead.',componentName);}}classComponentUpdater.enqueueReplaceState(instance,instance.state,null);}}// Invokes the mount life-cycles on a previously never rendered instance.
function mountClassInstance(workInProgress,ctor,newProps,renderLanes){{checkClassInstance(workInProgress,ctor,newProps);}var instance=workInProgress.stateNode;instance.props=newProps;instance.state=workInProgress.memoizedState;instance.refs=emptyRefsObject;initializeUpdateQueue(workInProgress);var contextType=ctor.contextType;if(typeof contextType==='object'&&contextType!==null){instance.context=readContext(contextType);}else {var unmaskedContext=getUnmaskedContext(workInProgress,ctor,true);instance.context=getMaskedContext(workInProgress,unmaskedContext);}{if(instance.state===newProps){var componentName=getComponentName(ctor)||'Component';if(!didWarnAboutDirectlyAssigningPropsToState.has(componentName)){didWarnAboutDirectlyAssigningPropsToState.add(componentName);error('%s: It is not recommended to assign props directly to state '+"because updates to props won't be reflected in state. "+'In most cases, it is better to use props directly.',componentName);}}if(workInProgress.mode&StrictMode){ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress,instance);}{ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress,instance);}}processUpdateQueue(workInProgress,newProps,instance,renderLanes);instance.state=workInProgress.memoizedState;var getDerivedStateFromProps=ctor.getDerivedStateFromProps;if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,newProps);instance.state=workInProgress.memoizedState;}// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(typeof ctor.getDerivedStateFromProps!=='function'&&typeof instance.getSnapshotBeforeUpdate!=='function'&&(typeof instance.UNSAFE_componentWillMount==='function'||typeof instance.componentWillMount==='function')){callComponentWillMount(workInProgress,instance);// If we had additional state updates during this life-cycle, let's
// process them now.
processUpdateQueue(workInProgress,newProps,instance,renderLanes);instance.state=workInProgress.memoizedState;}if(typeof instance.componentDidMount==='function'){workInProgress.flags|=Update;}}function resumeMountClassInstance(workInProgress,ctor,newProps,renderLanes){var instance=workInProgress.stateNode;var oldProps=workInProgress.memoizedProps;instance.props=oldProps;var oldContext=instance.context;var contextType=ctor.contextType;var nextContext=emptyContextObject;if(typeof contextType==='object'&&contextType!==null){nextContext=readContext(contextType);}else {var nextLegacyUnmaskedContext=getUnmaskedContext(workInProgress,ctor,true);nextContext=getMaskedContext(workInProgress,nextLegacyUnmaskedContext);}var getDerivedStateFromProps=ctor.getDerivedStateFromProps;var hasNewLifecycles=typeof getDerivedStateFromProps==='function'||typeof instance.getSnapshotBeforeUpdate==='function';// Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillReceiveProps==='function'||typeof instance.componentWillReceiveProps==='function')){if(oldProps!==newProps||oldContext!==nextContext){callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext);}}resetHasForceUpdateBeforeProcessing();var oldState=workInProgress.memoizedState;var newState=instance.state=oldState;processUpdateQueue(workInProgress,newProps,instance,renderLanes);newState=workInProgress.memoizedState;if(oldProps===newProps&&oldState===newState&&!hasContextChanged()&&!checkHasForceUpdateAfterProcessing()){// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidMount==='function'){workInProgress.flags|=Update;}return false;}if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,newProps);newState=workInProgress.memoizedState;}var shouldUpdate=checkHasForceUpdateAfterProcessing()||checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext);if(shouldUpdate){// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillMount==='function'||typeof instance.componentWillMount==='function')){if(typeof instance.componentWillMount==='function'){instance.componentWillMount();}if(typeof instance.UNSAFE_componentWillMount==='function'){instance.UNSAFE_componentWillMount();}}if(typeof instance.componentDidMount==='function'){workInProgress.flags|=Update;}}else {// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidMount==='function'){workInProgress.flags|=Update;}// If shouldComponentUpdate returned false, we should still update the
// memoized state to indicate that this work can be reused.
workInProgress.memoizedProps=newProps;workInProgress.memoizedState=newState;}// Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props=newProps;instance.state=newState;instance.context=nextContext;return shouldUpdate;}// Invokes the update life-cycles and returns false if it shouldn't rerender.
function updateClassInstance(current,workInProgress,ctor,newProps,renderLanes){var instance=workInProgress.stateNode;cloneUpdateQueue(current,workInProgress);var unresolvedOldProps=workInProgress.memoizedProps;var oldProps=workInProgress.type===workInProgress.elementType?unresolvedOldProps:resolveDefaultProps(workInProgress.type,unresolvedOldProps);instance.props=oldProps;var unresolvedNewProps=workInProgress.pendingProps;var oldContext=instance.context;var contextType=ctor.contextType;var nextContext=emptyContextObject;if(typeof contextType==='object'&&contextType!==null){nextContext=readContext(contextType);}else {var nextUnmaskedContext=getUnmaskedContext(workInProgress,ctor,true);nextContext=getMaskedContext(workInProgress,nextUnmaskedContext);}var getDerivedStateFromProps=ctor.getDerivedStateFromProps;var hasNewLifecycles=typeof getDerivedStateFromProps==='function'||typeof instance.getSnapshotBeforeUpdate==='function';// Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillReceiveProps==='function'||typeof instance.componentWillReceiveProps==='function')){if(unresolvedOldProps!==unresolvedNewProps||oldContext!==nextContext){callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext);}}resetHasForceUpdateBeforeProcessing();var oldState=workInProgress.memoizedState;var newState=instance.state=oldState;processUpdateQueue(workInProgress,newProps,instance,renderLanes);newState=workInProgress.memoizedState;if(unresolvedOldProps===unresolvedNewProps&&oldState===newState&&!hasContextChanged()&&!checkHasForceUpdateAfterProcessing()){// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Update;}}if(typeof instance.getSnapshotBeforeUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Snapshot;}}return false;}if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,newProps);newState=workInProgress.memoizedState;}var shouldUpdate=checkHasForceUpdateAfterProcessing()||checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext);if(shouldUpdate){// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillUpdate==='function'||typeof instance.componentWillUpdate==='function')){if(typeof instance.componentWillUpdate==='function'){instance.componentWillUpdate(newProps,newState,nextContext);}if(typeof instance.UNSAFE_componentWillUpdate==='function'){instance.UNSAFE_componentWillUpdate(newProps,newState,nextContext);}}if(typeof instance.componentDidUpdate==='function'){workInProgress.flags|=Update;}if(typeof instance.getSnapshotBeforeUpdate==='function'){workInProgress.flags|=Snapshot;}}else {// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Update;}}if(typeof instance.getSnapshotBeforeUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Snapshot;}}// If shouldComponentUpdate returned false, we should still update the
// memoized props/state to indicate that this work can be reused.
workInProgress.memoizedProps=newProps;workInProgress.memoizedState=newState;}// Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props=newProps;instance.state=newState;instance.context=nextContext;return shouldUpdate;}var didWarnAboutMaps;var didWarnAboutGenerators;var didWarnAboutStringRefs;var ownerHasKeyUseWarning;var ownerHasFunctionTypeWarning;var warnForMissingKey=function(child,returnFiber){};{didWarnAboutMaps=false;didWarnAboutGenerators=false;didWarnAboutStringRefs={};/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/ownerHasKeyUseWarning={};ownerHasFunctionTypeWarning={};warnForMissingKey=function(child,returnFiber){if(child===null||typeof child!=='object'){return;}if(!child._store||child._store.validated||child.key!=null){return;}if(!(typeof child._store==='object')){{throw Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");}}child._store.validated=true;var componentName=getComponentName(returnFiber.type)||'Component';if(ownerHasKeyUseWarning[componentName]){return;}ownerHasKeyUseWarning[componentName]=true;error('Each child in a list should have a unique '+'"key" prop. See https://reactjs.org/link/warning-keys for '+'more information.');};}var isArray$1=Array.isArray;function coerceRef(returnFiber,current,element){var mixedRef=element.ref;if(mixedRef!==null&&typeof mixedRef!=='function'&&typeof mixedRef!=='object'){{// TODO: Clean this up once we turn on the string ref warning for
// everyone, because the strict mode case will no longer be relevant
if((returnFiber.mode&StrictMode||warnAboutStringRefs)&&// We warn in ReactElement.js if owner and self are equal for string refs
// because these cannot be automatically converted to an arrow function
// using a codemod. Therefore, we don't have to warn about string refs again.
!(element._owner&&element._self&&element._owner.stateNode!==element._self)){var componentName=getComponentName(returnFiber.type)||'Component';if(!didWarnAboutStringRefs[componentName]){{error('A string ref, "%s", has been found within a strict mode tree. '+'String refs are a source of potential bugs and should be avoided. '+'We recommend using useRef() or createRef() instead. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-string-ref',mixedRef);}didWarnAboutStringRefs[componentName]=true;}}}if(element._owner){var owner=element._owner;var inst;if(owner){var ownerFiber=owner;if(!(ownerFiber.tag===ClassComponent)){{throw Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref");}}inst=ownerFiber.stateNode;}if(!inst){{throw Error("Missing owner for string ref "+mixedRef+". This error is likely caused by a bug in React. Please file an issue.");}}var stringRef=''+mixedRef;// Check if previous string ref matches new string ref
if(current!==null&&current.ref!==null&&typeof current.ref==='function'&&current.ref._stringRef===stringRef){return current.ref;}var ref=function(value){var refs=inst.refs;if(refs===emptyRefsObject){// This is a lazy pooled frozen object, so we need to initialize.
refs=inst.refs={};}if(value===null){delete refs[stringRef];}else {refs[stringRef]=value;}};ref._stringRef=stringRef;return ref;}else {if(!(typeof mixedRef==='string')){{throw Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");}}if(!element._owner){{throw Error("Element ref was specified as a string ("+mixedRef+") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information.");}}}}return mixedRef;}function throwOnInvalidObjectType(returnFiber,newChild){if(returnFiber.type!=='textarea'){{{throw Error("Objects are not valid as a React child (found: "+(Object.prototype.toString.call(newChild)==='[object Object]'?'object with keys {'+Object.keys(newChild).join(', ')+'}':newChild)+"). If you meant to render a collection of children, use an array instead.");}}}}function warnOnFunctionType(returnFiber){{var componentName=getComponentName(returnFiber.type)||'Component';if(ownerHasFunctionTypeWarning[componentName]){return;}ownerHasFunctionTypeWarning[componentName]=true;error('Functions are not valid as a React child. This may happen if '+'you return a Component instead of <Component /> from render. '+'Or maybe you meant to call this function rather than return it.');}}// We avoid inlining this to avoid potential deopts from using try/catch.
// to be able to optimize each path individually by branching early. This needs
// a compiler or we can do it manually. Helpers that don't need this branching
// live outside of this function.
function ChildReconciler(shouldTrackSideEffects){function deleteChild(returnFiber,childToDelete){if(!shouldTrackSideEffects){// Noop.
return;}// Deletions are added in reversed order so we add it to the front.
// At this point, the return fiber's effect list is empty except for
// deletions, so we can just append the deletion to the list. The remaining
// effects aren't added until the complete phase. Once we implement
// resuming, this may not be true.
var last=returnFiber.lastEffect;if(last!==null){last.nextEffect=childToDelete;returnFiber.lastEffect=childToDelete;}else {returnFiber.firstEffect=returnFiber.lastEffect=childToDelete;}childToDelete.nextEffect=null;childToDelete.flags=Deletion;}function deleteRemainingChildren(returnFiber,currentFirstChild){if(!shouldTrackSideEffects){// Noop.
return null;}// TODO: For the shouldClone case, this could be micro-optimized a bit by
// assuming that after the first child we've already added everything.
var childToDelete=currentFirstChild;while(childToDelete!==null){deleteChild(returnFiber,childToDelete);childToDelete=childToDelete.sibling;}return null;}function mapRemainingChildren(returnFiber,currentFirstChild){// Add the remaining children to a temporary map so that we can find them by
// keys quickly. Implicit (null) keys get added to this set with their index
// instead.
var existingChildren=new Map();var existingChild=currentFirstChild;while(existingChild!==null){if(existingChild.key!==null){existingChildren.set(existingChild.key,existingChild);}else {existingChildren.set(existingChild.index,existingChild);}existingChild=existingChild.sibling;}return existingChildren;}function useFiber(fiber,pendingProps){// We currently set sibling to null and index to 0 here because it is easy
// to forget to do before returning it. E.g. for the single child case.
var clone=createWorkInProgress(fiber,pendingProps);clone.index=0;clone.sibling=null;return clone;}function placeChild(newFiber,lastPlacedIndex,newIndex){newFiber.index=newIndex;if(!shouldTrackSideEffects){// Noop.
return lastPlacedIndex;}var current=newFiber.alternate;if(current!==null){var oldIndex=current.index;if(oldIndex<lastPlacedIndex){// This is a move.
newFiber.flags=Placement;return lastPlacedIndex;}else {// This item can stay in place.
return oldIndex;}}else {// This is an insertion.
newFiber.flags=Placement;return lastPlacedIndex;}}function placeSingleChild(newFiber){// This is simpler for the single child case. We only need to do a
// placement for inserting new children.
if(shouldTrackSideEffects&&newFiber.alternate===null){newFiber.flags=Placement;}return newFiber;}function updateTextNode(returnFiber,current,textContent,lanes){if(current===null||current.tag!==HostText){// Insert
var created=createFiberFromText(textContent,returnFiber.mode,lanes);created.return=returnFiber;return created;}else {// Update
var existing=useFiber(current,textContent);existing.return=returnFiber;return existing;}}function updateElement(returnFiber,current,element,lanes){if(current!==null){if(current.elementType===element.type||// Keep this check inline so it only runs on the false path:
isCompatibleFamilyForHotReloading(current,element)){// Move based on index
var existing=useFiber(current,element.props);existing.ref=coerceRef(returnFiber,current,element);existing.return=returnFiber;{existing._debugSource=element._source;existing._debugOwner=element._owner;}return existing;}}// Insert
var created=createFiberFromElement(element,returnFiber.mode,lanes);created.ref=coerceRef(returnFiber,current,element);created.return=returnFiber;return created;}function updatePortal(returnFiber,current,portal,lanes){if(current===null||current.tag!==HostPortal||current.stateNode.containerInfo!==portal.containerInfo||current.stateNode.implementation!==portal.implementation){// Insert
var created=createFiberFromPortal(portal,returnFiber.mode,lanes);created.return=returnFiber;return created;}else {// Update
var existing=useFiber(current,portal.children||[]);existing.return=returnFiber;return existing;}}function updateFragment(returnFiber,current,fragment,lanes,key){if(current===null||current.tag!==Fragment){// Insert
var created=createFiberFromFragment(fragment,returnFiber.mode,lanes,key);created.return=returnFiber;return created;}else {// Update
var existing=useFiber(current,fragment);existing.return=returnFiber;return existing;}}function createChild(returnFiber,newChild,lanes){if(typeof newChild==='string'||typeof newChild==='number'){// Text nodes don't have keys. If the previous node is implicitly keyed
// we can continue to replace it without aborting even if it is not a text
// node.
var created=createFiberFromText(''+newChild,returnFiber.mode,lanes);created.return=returnFiber;return created;}if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:{var _created=createFiberFromElement(newChild,returnFiber.mode,lanes);_created.ref=coerceRef(returnFiber,null,newChild);_created.return=returnFiber;return _created;}case REACT_PORTAL_TYPE:{var _created2=createFiberFromPortal(newChild,returnFiber.mode,lanes);_created2.return=returnFiber;return _created2;}}if(isArray$1(newChild)||getIteratorFn(newChild)){var _created3=createFiberFromFragment(newChild,returnFiber.mode,lanes,null);_created3.return=returnFiber;return _created3;}throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}return null;}function updateSlot(returnFiber,oldFiber,newChild,lanes){// Update the fiber if the keys match, otherwise return null.
var key=oldFiber!==null?oldFiber.key:null;if(typeof newChild==='string'||typeof newChild==='number'){// Text nodes don't have keys. If the previous node is implicitly keyed
// we can continue to replace it without aborting even if it is not a text
// node.
if(key!==null){return null;}return updateTextNode(returnFiber,oldFiber,''+newChild,lanes);}if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:{if(newChild.key===key){if(newChild.type===REACT_FRAGMENT_TYPE){return updateFragment(returnFiber,oldFiber,newChild.props.children,lanes,key);}return updateElement(returnFiber,oldFiber,newChild,lanes);}else {return null;}}case REACT_PORTAL_TYPE:{if(newChild.key===key){return updatePortal(returnFiber,oldFiber,newChild,lanes);}else {return null;}}}if(isArray$1(newChild)||getIteratorFn(newChild)){if(key!==null){return null;}return updateFragment(returnFiber,oldFiber,newChild,lanes,null);}throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}return null;}function updateFromMap(existingChildren,returnFiber,newIdx,newChild,lanes){if(typeof newChild==='string'||typeof newChild==='number'){// Text nodes don't have keys, so we neither have to check the old nor
// new node for the key. If both are text nodes, they match.
var matchedFiber=existingChildren.get(newIdx)||null;return updateTextNode(returnFiber,matchedFiber,''+newChild,lanes);}if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:{var _matchedFiber=existingChildren.get(newChild.key===null?newIdx:newChild.key)||null;if(newChild.type===REACT_FRAGMENT_TYPE){return updateFragment(returnFiber,_matchedFiber,newChild.props.children,lanes,newChild.key);}return updateElement(returnFiber,_matchedFiber,newChild,lanes);}case REACT_PORTAL_TYPE:{var _matchedFiber2=existingChildren.get(newChild.key===null?newIdx:newChild.key)||null;return updatePortal(returnFiber,_matchedFiber2,newChild,lanes);}}if(isArray$1(newChild)||getIteratorFn(newChild)){var _matchedFiber3=existingChildren.get(newIdx)||null;return updateFragment(returnFiber,_matchedFiber3,newChild,lanes,null);}throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}return null;}/**
* Warns if there is a duplicate or missing key
*/function warnOnInvalidKey(child,knownKeys,returnFiber){{if(typeof child!=='object'||child===null){return knownKeys;}switch(child.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:warnForMissingKey(child,returnFiber);var key=child.key;if(typeof key!=='string'){break;}if(knownKeys===null){knownKeys=new Set();knownKeys.add(key);break;}if(!knownKeys.has(key)){knownKeys.add(key);break;}error('Encountered two children with the same key, `%s`. '+'Keys should be unique so that components maintain their identity '+'across updates. Non-unique keys may cause children to be '+'duplicated and/or omitted the behavior is unsupported and '+'could change in a future version.',key);break;}}return knownKeys;}function reconcileChildrenArray(returnFiber,currentFirstChild,newChildren,lanes){// This algorithm can't optimize by searching from both ends since we
// don't have backpointers on fibers. I'm trying to see how far we can get
// with that model. If it ends up not being worth the tradeoffs, we can
// add it later.
// Even with a two ended optimization, we'd want to optimize for the case
// where there are few changes and brute force the comparison instead of
// going for the Map. It'd like to explore hitting that path first in
// forward-only mode and only go for the Map once we notice that we need
// lots of look ahead. This doesn't handle reversal as well as two ended
// search but that's unusual. Besides, for the two ended optimization to
// work on Iterables, we'd need to copy the whole set.
// In this first iteration, we'll just live with hitting the bad case
// (adding everything to a Map) in for every insert/move.
// If you change this code, also update reconcileChildrenIterator() which
// uses the same algorithm.
{// First, validate keys.
var knownKeys=null;for(var i=0;i<newChildren.length;i++){var child=newChildren[i];knownKeys=warnOnInvalidKey(child,knownKeys,returnFiber);}}var resultingFirstChild=null;var previousNewFiber=null;var oldFiber=currentFirstChild;var lastPlacedIndex=0;var newIdx=0;var nextOldFiber=null;for(;oldFiber!==null&&newIdx<newChildren.length;newIdx++){if(oldFiber.index>newIdx){nextOldFiber=oldFiber;oldFiber=null;}else {nextOldFiber=oldFiber.sibling;}var newFiber=updateSlot(returnFiber,oldFiber,newChildren[newIdx],lanes);if(newFiber===null){// TODO: This breaks on empty slots like null children. That's
// unfortunate because it triggers the slow path all the time. We need
// a better way to communicate whether this was a miss or null,
// boolean, undefined, etc.
if(oldFiber===null){oldFiber=nextOldFiber;}break;}if(shouldTrackSideEffects){if(oldFiber&&newFiber.alternate===null){// We matched the slot, but we didn't reuse the existing fiber, so we
// need to delete the existing child.
deleteChild(returnFiber,oldFiber);}}lastPlacedIndex=placeChild(newFiber,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=newFiber;}else {// TODO: Defer siblings if we're not at the right index for this slot.
// I.e. if we had null values before, then we want to defer this
// for each null value. However, we also don't want to call updateSlot
// with the previous one.
previousNewFiber.sibling=newFiber;}previousNewFiber=newFiber;oldFiber=nextOldFiber;}if(newIdx===newChildren.length){// We've reached the end of the new children. We can delete the rest.
deleteRemainingChildren(returnFiber,oldFiber);return resultingFirstChild;}if(oldFiber===null){// If we don't have any more existing children we can choose a fast path
// since the rest will all be insertions.
for(;newIdx<newChildren.length;newIdx++){var _newFiber=createChild(returnFiber,newChildren[newIdx],lanes);if(_newFiber===null){continue;}lastPlacedIndex=placeChild(_newFiber,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=_newFiber;}else {previousNewFiber.sibling=_newFiber;}previousNewFiber=_newFiber;}return resultingFirstChild;}// Add all children to a key map for quick lookups.
var existingChildren=mapRemainingChildren(returnFiber,oldFiber);// Keep scanning and use the map to restore deleted items as moves.
for(;newIdx<newChildren.length;newIdx++){var _newFiber2=updateFromMap(existingChildren,returnFiber,newIdx,newChildren[newIdx],lanes);if(_newFiber2!==null){if(shouldTrackSideEffects){if(_newFiber2.alternate!==null){// The new fiber is a work in progress, but if there exists a
// current, that means that we reused the fiber. We need to delete
// it from the child list so that we don't add it to the deletion
// list.
existingChildren.delete(_newFiber2.key===null?newIdx:_newFiber2.key);}}lastPlacedIndex=placeChild(_newFiber2,lastPlacedIndex,newIdx);if(previousNewFiber===null){resultingFirstChild=_newFiber2;}else {previousNewFiber.sibling=_newFiber2;}previousNewFiber=_newFiber2;}}if(shouldTrackSideEffects){// Any existing children that weren't consumed above were deleted. We need
// to add them to the deletion list.
existingChildren.forEach(function(child){return deleteChild(returnFiber,child);});}return resultingFirstChild;}function reconcileChildrenIterator(returnFiber,currentFirstChild,newChildrenIterable,lanes){// This is the same implementation as reconcileChildrenArray(),
// but using the iterator instead.
var iteratorFn=getIteratorFn(newChildrenIterable);if(!(typeof iteratorFn==='function')){{throw Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");}}{// We don't support rendering Generators because it's a mutation.
// See https://github.com/facebook/react/issues/12995
if(typeof Symbol==='function'&&// $FlowFixMe Flow doesn't know about toStringTag
newChildrenIterable[Symbol.toStringTag]==='Generator'){if(!didWarnAboutGenerators){error('Using Generators as children is unsupported and will likely yield '+'unexpected results because enumerating a generator mutates it. '+'You may convert it to an array with `Array.from()` or the '+'`[...spread]` operator before rendering. Keep in mind '+'you might need to polyfill these features for older browsers.');}didWarnAboutGenerators=true;}// Warn about using Maps as children
if(newChildrenIterable.entries===iteratorFn){if(!didWarnAboutMaps){error('Using Maps as children is not supported. '+'Use an array of keyed ReactElements instead.');}didWarnAboutMaps=true;}// First, validate keys.
// We'll get a different iterator later for the main pass.
var _newChildren=iteratorFn.call(newChildrenIterable);if(_newChildren){var knownKeys=null;var _step=_newChildren.next();for(;!_step.done;_step=_newChildren.next()){var child=_step.value;knownKeys=warnOnInvalidKey(child,knownKeys,returnFiber);}}}var newChildren=iteratorFn.call(newChildrenIterable);if(!(newChildren!=null)){{throw Error("An iterable object provided no iterator.");}}var resultingFirstChild=null;var previousNewFiber=null;var oldFiber=currentFirstChild;var lastPlacedIndex=0;var newIdx=0;var nextOldFiber=null;var step=newChildren.next();for(;oldFiber!==null&&!step.done;newIdx++,step=newChildren.next()){if(oldFiber.index>newIdx){nextOldFiber=oldFiber;oldFiber=null;}else {nextOldFiber=oldFiber.sibling;}var newFiber=updateSlot(returnFiber,oldFiber,step.value,lanes);if(newFiber===null){// TODO: This breaks on empty slots like null children. That's
// unfortunate because it triggers the slow path all the time. We need
// a better way to communicate whether this was a miss or null,
// boolean, undefined, etc.
if(oldFiber===null){oldFiber=nextOldFiber;}break;}if(shouldTrackSideEffects){if(oldFiber&&newFiber.alternate===null){// We matched the slot, but we didn't reuse the existing fiber, so we
// need to delete the existing child.
deleteChild(returnFiber,oldFiber);}}lastPlacedIndex=placeChild(newFiber,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=newFiber;}else {// TODO: Defer siblings if we're not at the right index for this slot.
// I.e. if we had null values before, then we want to defer this
// for each null value. However, we also don't want to call updateSlot
// with the previous one.
previousNewFiber.sibling=newFiber;}previousNewFiber=newFiber;oldFiber=nextOldFiber;}if(step.done){// We've reached the end of the new children. We can delete the rest.
deleteRemainingChildren(returnFiber,oldFiber);return resultingFirstChild;}if(oldFiber===null){// If we don't have any more existing children we can choose a fast path
// since the rest will all be insertions.
for(;!step.done;newIdx++,step=newChildren.next()){var _newFiber3=createChild(returnFiber,step.value,lanes);if(_newFiber3===null){continue;}lastPlacedIndex=placeChild(_newFiber3,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=_newFiber3;}else {previousNewFiber.sibling=_newFiber3;}previousNewFiber=_newFiber3;}return resultingFirstChild;}// Add all children to a key map for quick lookups.
var existingChildren=mapRemainingChildren(returnFiber,oldFiber);// Keep scanning and use the map to restore deleted items as moves.
for(;!step.done;newIdx++,step=newChildren.next()){var _newFiber4=updateFromMap(existingChildren,returnFiber,newIdx,step.value,lanes);if(_newFiber4!==null){if(shouldTrackSideEffects){if(_newFiber4.alternate!==null){// The new fiber is a work in progress, but if there exists a
// current, that means that we reused the fiber. We need to delete
// it from the child list so that we don't add it to the deletion
// list.
existingChildren.delete(_newFiber4.key===null?newIdx:_newFiber4.key);}}lastPlacedIndex=placeChild(_newFiber4,lastPlacedIndex,newIdx);if(previousNewFiber===null){resultingFirstChild=_newFiber4;}else {previousNewFiber.sibling=_newFiber4;}previousNewFiber=_newFiber4;}}if(shouldTrackSideEffects){// Any existing children that weren't consumed above were deleted. We need
// to add them to the deletion list.
existingChildren.forEach(function(child){return deleteChild(returnFiber,child);});}return resultingFirstChild;}function reconcileSingleTextNode(returnFiber,currentFirstChild,textContent,lanes){// There's no need to check for keys on text nodes since we don't have a
// way to define them.
if(currentFirstChild!==null&&currentFirstChild.tag===HostText){// We already have an existing node so let's just update it and delete
// the rest.
deleteRemainingChildren(returnFiber,currentFirstChild.sibling);var existing=useFiber(currentFirstChild,textContent);existing.return=returnFiber;return existing;}// The existing first child is not a text node so we need to create one
// and delete the existing ones.
deleteRemainingChildren(returnFiber,currentFirstChild);var created=createFiberFromText(textContent,returnFiber.mode,lanes);created.return=returnFiber;return created;}function reconcileSingleElement(returnFiber,currentFirstChild,element,lanes){var key=element.key;var child=currentFirstChild;while(child!==null){// TODO: If key === null and child.key === null, then this only applies to
// the first item in the list.
if(child.key===key){switch(child.tag){case Fragment:{if(element.type===REACT_FRAGMENT_TYPE){deleteRemainingChildren(returnFiber,child.sibling);var existing=useFiber(child,element.props.children);existing.return=returnFiber;{existing._debugSource=element._source;existing._debugOwner=element._owner;}return existing;}break;}case Block:// We intentionally fallthrough here if enableBlocksAPI is not on.
// eslint-disable-next-lined no-fallthrough
default:{if(child.elementType===element.type||// Keep this check inline so it only runs on the false path:
isCompatibleFamilyForHotReloading(child,element)){deleteRemainingChildren(returnFiber,child.sibling);var _existing3=useFiber(child,element.props);_existing3.ref=coerceRef(returnFiber,child,element);_existing3.return=returnFiber;{_existing3._debugSource=element._source;_existing3._debugOwner=element._owner;}return _existing3;}break;}}// Didn't match.
deleteRemainingChildren(returnFiber,child);break;}else {deleteChild(returnFiber,child);}child=child.sibling;}if(element.type===REACT_FRAGMENT_TYPE){var created=createFiberFromFragment(element.props.children,returnFiber.mode,lanes,element.key);created.return=returnFiber;return created;}else {var _created4=createFiberFromElement(element,returnFiber.mode,lanes);_created4.ref=coerceRef(returnFiber,currentFirstChild,element);_created4.return=returnFiber;return _created4;}}function reconcileSinglePortal(returnFiber,currentFirstChild,portal,lanes){var key=portal.key;var child=currentFirstChild;while(child!==null){// TODO: If key === null and child.key === null, then this only applies to
// the first item in the list.
if(child.key===key){if(child.tag===HostPortal&&child.stateNode.containerInfo===portal.containerInfo&&child.stateNode.implementation===portal.implementation){deleteRemainingChildren(returnFiber,child.sibling);var existing=useFiber(child,portal.children||[]);existing.return=returnFiber;return existing;}else {deleteRemainingChildren(returnFiber,child);break;}}else {deleteChild(returnFiber,child);}child=child.sibling;}var created=createFiberFromPortal(portal,returnFiber.mode,lanes);created.return=returnFiber;return created;}// This API will tag the children with the side-effect of the reconciliation
// itself. They will be added to the side-effect list as we pass through the
// children and the parent.
function reconcileChildFibers(returnFiber,currentFirstChild,newChild,lanes){// This function is not recursive.
// If the top level item is an array, we treat it as a set of children,
// not as a fragment. Nested arrays on the other hand will be treated as
// fragment nodes. Recursion happens at the normal flow.
// Handle top level unkeyed fragments as if they were arrays.
// This leads to an ambiguity between <>{[...]}</> and <>...</>.
// We treat the ambiguous cases above the same.
var isUnkeyedTopLevelFragment=typeof newChild==='object'&&newChild!==null&&newChild.type===REACT_FRAGMENT_TYPE&&newChild.key===null;if(isUnkeyedTopLevelFragment){newChild=newChild.props.children;}// Handle object types
var isObject=typeof newChild==='object'&&newChild!==null;if(isObject){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:return placeSingleChild(reconcileSingleElement(returnFiber,currentFirstChild,newChild,lanes));case REACT_PORTAL_TYPE:return placeSingleChild(reconcileSinglePortal(returnFiber,currentFirstChild,newChild,lanes));}}if(typeof newChild==='string'||typeof newChild==='number'){return placeSingleChild(reconcileSingleTextNode(returnFiber,currentFirstChild,''+newChild,lanes));}if(isArray$1(newChild)){return reconcileChildrenArray(returnFiber,currentFirstChild,newChild,lanes);}if(getIteratorFn(newChild)){return reconcileChildrenIterator(returnFiber,currentFirstChild,newChild,lanes);}if(isObject){throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}if(typeof newChild==='undefined'&&!isUnkeyedTopLevelFragment){// If the new child is undefined, and the return fiber is a composite
// component, throw an error. If Fiber return types are disabled,
// we already threw above.
switch(returnFiber.tag){case ClassComponent:{{var instance=returnFiber.stateNode;if(instance.render._isMockFunction){// We allow auto-mocks to proceed as if they're returning null.
break;}}}// Intentionally fall through to the next case, which handles both
// functions and classes
// eslint-disable-next-lined no-fallthrough
case Block:case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{{{throw Error((getComponentName(returnFiber.type)||'Component')+"(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.");}}}}}// Remaining cases are all treated as empty.
return deleteRemainingChildren(returnFiber,currentFirstChild);}return reconcileChildFibers;}var reconcileChildFibers=ChildReconciler(true);var mountChildFibers=ChildReconciler(false);function cloneChildFibers(current,workInProgress){if(!(current===null||workInProgress.child===current.child)){{throw Error("Resuming work not yet implemented.");}}if(workInProgress.child===null){return;}var currentChild=workInProgress.child;var newChild=createWorkInProgress(currentChild,currentChild.pendingProps);workInProgress.child=newChild;newChild.return=workInProgress;while(currentChild.sibling!==null){currentChild=currentChild.sibling;newChild=newChild.sibling=createWorkInProgress(currentChild,currentChild.pendingProps);newChild.return=workInProgress;}newChild.sibling=null;}// Reset a workInProgress child set to prepare it for a second pass.
function resetChildFibers(workInProgress,lanes){var child=workInProgress.child;while(child!==null){resetWorkInProgress(child,lanes);child=child.sibling;}}var NO_CONTEXT={};var contextStackCursor$1=createCursor(NO_CONTEXT);var contextFiberStackCursor=createCursor(NO_CONTEXT);var rootInstanceStackCursor=createCursor(NO_CONTEXT);function requiredContext(c){if(!(c!==NO_CONTEXT)){{throw Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");}}return c;}function getRootHostContainer(){var rootInstance=requiredContext(rootInstanceStackCursor.current);return rootInstance;}function pushHostContainer(fiber,nextRootInstance){// Push current root instance onto the stack;
// This allows us to reset root when portals are popped.
push(rootInstanceStackCursor,nextRootInstance,fiber);// Track the context and the Fiber that provided it.
// This enables us to pop only Fibers that provide unique contexts.
push(contextFiberStackCursor,fiber,fiber);// Finally, we need to push the host context to the stack.
// However, we can't just call getRootHostContext() and push it because
// we'd have a different number of entries on the stack depending on
// whether getRootHostContext() throws somewhere in renderer code or not.
// So we push an empty value first. This lets us safely unwind on errors.
push(contextStackCursor$1,NO_CONTEXT,fiber);var nextRootContext=getRootHostContext(nextRootInstance);// Now that we know this function doesn't throw, replace it.
pop(contextStackCursor$1,fiber);push(contextStackCursor$1,nextRootContext,fiber);}function popHostContainer(fiber){pop(contextStackCursor$1,fiber);pop(contextFiberStackCursor,fiber);pop(rootInstanceStackCursor,fiber);}function getHostContext(){var context=requiredContext(contextStackCursor$1.current);return context;}function pushHostContext(fiber){var rootInstance=requiredContext(rootInstanceStackCursor.current);var context=requiredContext(contextStackCursor$1.current);var nextContext=getChildHostContext(context,fiber.type);// Don't push this Fiber's context unless it's unique.
if(context===nextContext){return;}// Track the context and the Fiber that provided it.
// This enables us to pop only Fibers that provide unique contexts.
push(contextFiberStackCursor,fiber,fiber);push(contextStackCursor$1,nextContext,fiber);}function popHostContext(fiber){// Do not pop unless this Fiber provided the current context.
// pushHostContext() only pushes Fibers that provide unique contexts.
if(contextFiberStackCursor.current!==fiber){return;}pop(contextStackCursor$1,fiber);pop(contextFiberStackCursor,fiber);}var DefaultSuspenseContext=0;// The Suspense Context is split into two parts. The lower bits is
// inherited deeply down the subtree. The upper bits only affect
// this immediate suspense boundary and gets reset each new
// boundary or suspense list.
var SubtreeSuspenseContextMask=1;// Subtree Flags:
// InvisibleParentSuspenseContext indicates that one of our parent Suspense
// boundaries is not currently showing visible main content.
// Either because it is already showing a fallback or is not mounted at all.
// We can use this to determine if it is desirable to trigger a fallback at
// the parent. If not, then we might need to trigger undesirable boundaries
// and/or suspend the commit to avoid hiding the parent content.
var InvisibleParentSuspenseContext=1;// Shallow Flags:
// ForceSuspenseFallback can be used by SuspenseList to force newly added
// items into their fallback state during one of the render passes.
var ForceSuspenseFallback=2;var suspenseStackCursor=createCursor(DefaultSuspenseContext);function hasSuspenseContext(parentContext,flag){return (parentContext&flag)!==0;}function setDefaultShallowSuspenseContext(parentContext){return parentContext&SubtreeSuspenseContextMask;}function setShallowSuspenseContext(parentContext,shallowContext){return parentContext&SubtreeSuspenseContextMask|shallowContext;}function addSubtreeSuspenseContext(parentContext,subtreeContext){return parentContext|subtreeContext;}function pushSuspenseContext(fiber,newContext){push(suspenseStackCursor,newContext,fiber);}function popSuspenseContext(fiber){pop(suspenseStackCursor,fiber);}function shouldCaptureSuspense(workInProgress,hasInvisibleParent){// If it was the primary children that just suspended, capture and render the
// fallback. Otherwise, don't capture and bubble to the next boundary.
var nextState=workInProgress.memoizedState;if(nextState!==null){if(nextState.dehydrated!==null){// A dehydrated boundary always captures.
return true;}return false;}var props=workInProgress.memoizedProps;// In order to capture, the Suspense component must have a fallback prop.
if(props.fallback===undefined){return false;}// Regular boundaries always capture.
if(props.unstable_avoidThisFallback!==true){return true;}// If it's a boundary we should avoid, then we prefer to bubble up to the
// parent boundary if it is currently invisible.
if(hasInvisibleParent){return false;}// If the parent is not able to handle it, we must handle it.
return true;}function findFirstSuspended(row){var node=row;while(node!==null){if(node.tag===SuspenseComponent){var state=node.memoizedState;if(state!==null){var dehydrated=state.dehydrated;if(dehydrated===null||isSuspenseInstancePending(dehydrated)||isSuspenseInstanceFallback(dehydrated)){return node;}}}else if(node.tag===SuspenseListComponent&&// revealOrder undefined can't be trusted because it don't
// keep track of whether it suspended or not.
node.memoizedProps.revealOrder!==undefined){var didSuspend=(node.flags&DidCapture)!==NoFlags;if(didSuspend){return node;}}else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===row){return null;}while(node.sibling===null){if(node.return===null||node.return===row){return null;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}return null;}var NoFlags$1=/* */0;// Represents whether effect should fire.
var HasEffect=/* */1;// Represents the phase in which the effect (not the clean-up) fires.
var Layout=/* */2;var Passive$1=/* */4;// This may have been an insertion or a hydration.
var hydrationParentFiber=null;var nextHydratableInstance=null;var isHydrating=false;function enterHydrationState(fiber){var parentInstance=fiber.stateNode.containerInfo;nextHydratableInstance=getFirstHydratableChild(parentInstance);hydrationParentFiber=fiber;isHydrating=true;return true;}function deleteHydratableInstance(returnFiber,instance){{switch(returnFiber.tag){case HostRoot:didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo,instance);break;case HostComponent:didNotHydrateInstance(returnFiber.type,returnFiber.memoizedProps,returnFiber.stateNode,instance);break;}}var childToDelete=createFiberFromHostInstanceForDeletion();childToDelete.stateNode=instance;childToDelete.return=returnFiber;childToDelete.flags=Deletion;// This might seem like it belongs on progressedFirstDeletion. However,
// these children are not part of the reconciliation list of children.
// Even if we abort and rereconcile the children, that will try to hydrate
// again and the nodes are still in the host tree so these will be
// recreated.
if(returnFiber.lastEffect!==null){returnFiber.lastEffect.nextEffect=childToDelete;returnFiber.lastEffect=childToDelete;}else {returnFiber.firstEffect=returnFiber.lastEffect=childToDelete;}}function insertNonHydratedInstance(returnFiber,fiber){fiber.flags=fiber.flags&~Hydrating|Placement;{switch(returnFiber.tag){case HostRoot:{var parentContainer=returnFiber.stateNode.containerInfo;switch(fiber.tag){case HostComponent:var type=fiber.type;var props=fiber.pendingProps;didNotFindHydratableContainerInstance(parentContainer,type);break;case HostText:var text=fiber.pendingProps;didNotFindHydratableContainerTextInstance(parentContainer,text);break;}break;}case HostComponent:{var parentType=returnFiber.type;var parentProps=returnFiber.memoizedProps;var parentInstance=returnFiber.stateNode;switch(fiber.tag){case HostComponent:var _type=fiber.type;var _props=fiber.pendingProps;didNotFindHydratableInstance(parentType,parentProps,parentInstance,_type);break;case HostText:var _text=fiber.pendingProps;didNotFindHydratableTextInstance(parentType,parentProps,parentInstance,_text);break;case SuspenseComponent:didNotFindHydratableSuspenseInstance(parentType,parentProps);break;}break;}default:return;}}}function tryHydrate(fiber,nextInstance){switch(fiber.tag){case HostComponent:{var type=fiber.type;var props=fiber.pendingProps;var instance=canHydrateInstance(nextInstance,type);if(instance!==null){fiber.stateNode=instance;return true;}return false;}case HostText:{var text=fiber.pendingProps;var textInstance=canHydrateTextInstance(nextInstance,text);if(textInstance!==null){fiber.stateNode=textInstance;return true;}return false;}case SuspenseComponent:{return false;}default:return false;}}function tryToClaimNextHydratableInstance(fiber){if(!isHydrating){return;}var nextInstance=nextHydratableInstance;if(!nextInstance){// Nothing to hydrate. Make it an insertion.
insertNonHydratedInstance(hydrationParentFiber,fiber);isHydrating=false;hydrationParentFiber=fiber;return;}var firstAttemptedInstance=nextInstance;if(!tryHydrate(fiber,nextInstance)){// If we can't hydrate this instance let's try the next one.
// We use this as a heuristic. It's based on intuition and not data so it
// might be flawed or unnecessary.
nextInstance=getNextHydratableSibling(firstAttemptedInstance);if(!nextInstance||!tryHydrate(fiber,nextInstance)){// Nothing to hydrate. Make it an insertion.
insertNonHydratedInstance(hydrationParentFiber,fiber);isHydrating=false;hydrationParentFiber=fiber;return;}// We matched the next one, we'll now assume that the first one was
// superfluous and we'll delete it. Since we can't eagerly delete it
// we'll have to schedule a deletion. To do that, this node needs a dummy
// fiber associated with it.
deleteHydratableInstance(hydrationParentFiber,firstAttemptedInstance);}hydrationParentFiber=fiber;nextHydratableInstance=getFirstHydratableChild(nextInstance);}function prepareToHydrateHostInstance(fiber,rootContainerInstance,hostContext){var instance=fiber.stateNode;var updatePayload=hydrateInstance(instance,fiber.type,fiber.memoizedProps,rootContainerInstance,hostContext,fiber);// TODO: Type this specific to this type of component.
fiber.updateQueue=updatePayload;// If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update.
if(updatePayload!==null){return true;}return false;}function prepareToHydrateHostTextInstance(fiber){var textInstance=fiber.stateNode;var textContent=fiber.memoizedProps;var shouldUpdate=hydrateTextInstance(textInstance,textContent,fiber);{if(shouldUpdate){// We assume that prepareToHydrateHostTextInstance is called in a context where the
// hydration parent is the parent host component of this host text.
var returnFiber=hydrationParentFiber;if(returnFiber!==null){switch(returnFiber.tag){case HostRoot:{var parentContainer=returnFiber.stateNode.containerInfo;didNotMatchHydratedContainerTextInstance(parentContainer,textInstance,textContent);break;}case HostComponent:{var parentType=returnFiber.type;var parentProps=returnFiber.memoizedProps;var parentInstance=returnFiber.stateNode;didNotMatchHydratedTextInstance(parentType,parentProps,parentInstance,textInstance,textContent);break;}}}}}return shouldUpdate;}function skipPastDehydratedSuspenseInstance(fiber){var suspenseState=fiber.memoizedState;var suspenseInstance=suspenseState!==null?suspenseState.dehydrated:null;if(!suspenseInstance){{throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");}}return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);}function popToNextHostParent(fiber){var parent=fiber.return;while(parent!==null&&parent.tag!==HostComponent&&parent.tag!==HostRoot&&parent.tag!==SuspenseComponent){parent=parent.return;}hydrationParentFiber=parent;}function popHydrationState(fiber){if(fiber!==hydrationParentFiber){// We're deeper than the current hydration context, inside an inserted
// tree.
return false;}if(!isHydrating){// If we're not currently hydrating but we're in a hydration context, then
// we were an insertion and now need to pop up reenter hydration of our
// siblings.
popToNextHostParent(fiber);isHydrating=true;return false;}var type=fiber.type;// If we have any remaining hydratable nodes, we need to delete them now.
// We only do this deeper than head and body since they tend to have random
// other nodes in them. We also ignore components with pure text content in
// side of them.
// TODO: Better heuristic.
if(fiber.tag!==HostComponent||type!=='head'&&type!=='body'&&!shouldSetTextContent(type,fiber.memoizedProps)){var nextInstance=nextHydratableInstance;while(nextInstance){deleteHydratableInstance(fiber,nextInstance);nextInstance=getNextHydratableSibling(nextInstance);}}popToNextHostParent(fiber);if(fiber.tag===SuspenseComponent){nextHydratableInstance=skipPastDehydratedSuspenseInstance(fiber);}else {nextHydratableInstance=hydrationParentFiber?getNextHydratableSibling(fiber.stateNode):null;}return true;}function resetHydrationState(){hydrationParentFiber=null;nextHydratableInstance=null;isHydrating=false;}function getIsHydrating(){return isHydrating;}// and should be reset before starting a new render.
// This tracks which mutable sources need to be reset after a render.
var workInProgressSources=[];var rendererSigil$1;{// Used to detect multiple renderers using the same mutable source.
rendererSigil$1={};}function markSourceAsDirty(mutableSource){workInProgressSources.push(mutableSource);}function resetWorkInProgressVersions(){for(var i=0;i<workInProgressSources.length;i++){var mutableSource=workInProgressSources[i];{mutableSource._workInProgressVersionPrimary=null;}}workInProgressSources.length=0;}function getWorkInProgressVersion(mutableSource){{return mutableSource._workInProgressVersionPrimary;}}function setWorkInProgressVersion(mutableSource,version){{mutableSource._workInProgressVersionPrimary=version;}workInProgressSources.push(mutableSource);}function warnAboutMultipleRenderersDEV(mutableSource){{{if(mutableSource._currentPrimaryRenderer==null){mutableSource._currentPrimaryRenderer=rendererSigil$1;}else if(mutableSource._currentPrimaryRenderer!==rendererSigil$1){error('Detected multiple renderers concurrently rendering the '+'same mutable source. This is currently unsupported.');}}}}// Eager reads the version of a mutable source and stores it on the root.
var ReactCurrentDispatcher$1=ReactSharedInternals.ReactCurrentDispatcher,ReactCurrentBatchConfig$1=ReactSharedInternals.ReactCurrentBatchConfig;var didWarnAboutMismatchedHooksForComponent;var didWarnAboutUseOpaqueIdentifier;{didWarnAboutUseOpaqueIdentifier={};didWarnAboutMismatchedHooksForComponent=new Set();}// These are set right before calling the component.
var renderLanes=NoLanes;// The work-in-progress fiber. I've named it differently to distinguish it from
// the work-in-progress hook.
var currentlyRenderingFiber$1=null;// Hooks are stored as a linked list on the fiber's memoizedState field. The
// current hook list is the list that belongs to the current fiber. The
// work-in-progress hook list is a new list that will be added to the
// work-in-progress fiber.
var currentHook=null;var workInProgressHook=null;// Whether an update was scheduled at any point during the render phase. This
// does not get reset if we do another render pass; only when we're completely
// finished evaluating this component. This is an optimization so we know
// whether we need to clear render phase updates after a throw.
var didScheduleRenderPhaseUpdate=false;// Where an update was scheduled only during the current render pass. This
// gets reset after each attempt.
// TODO: Maybe there's some way to consolidate this with
// `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
var didScheduleRenderPhaseUpdateDuringThisPass=false;var RE_RENDER_LIMIT=25;// In DEV, this is the name of the currently executing primitive hook
var currentHookNameInDev=null;// In DEV, this list ensures that hooks are called in the same order between renders.
// The list stores the order of hooks used during the initial render (mount).
// Subsequent renders (updates) reference this list.
var hookTypesDev=null;var hookTypesUpdateIndexDev=-1;// In DEV, this tracks whether currently rendering component needs to ignore
// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
// When true, such Hooks will always be "remounted". Only used during hot reload.
var ignorePreviousDependencies=false;function mountHookTypesDev(){{var hookName=currentHookNameInDev;if(hookTypesDev===null){hookTypesDev=[hookName];}else {hookTypesDev.push(hookName);}}}function updateHookTypesDev(){{var hookName=currentHookNameInDev;if(hookTypesDev!==null){hookTypesUpdateIndexDev++;if(hookTypesDev[hookTypesUpdateIndexDev]!==hookName){warnOnHookMismatchInDev(hookName);}}}}function checkDepsAreArrayDev(deps){{if(deps!==undefined&&deps!==null&&!Array.isArray(deps)){// Verify deps, but only on mount to avoid extra checks.
// It's unlikely their type would change as usually you define them inline.
error('%s received a final argument that is not an array (instead, received `%s`). When '+'specified, the final argument must be an array.',currentHookNameInDev,typeof deps);}}}function warnOnHookMismatchInDev(currentHookName){{var componentName=getComponentName(currentlyRenderingFiber$1.type);if(!didWarnAboutMismatchedHooksForComponent.has(componentName)){didWarnAboutMismatchedHooksForComponent.add(componentName);if(hookTypesDev!==null){var table='';var secondColumnStart=30;for(var i=0;i<=hookTypesUpdateIndexDev;i++){var oldHookName=hookTypesDev[i];var newHookName=i===hookTypesUpdateIndexDev?currentHookName:oldHookName;var row=i+1+". "+oldHookName;// Extra space so second column lines up
// lol @ IE not supporting String#repeat
while(row.length<secondColumnStart){row+=' ';}row+=newHookName+'\n';table+=row;}error('React has detected a change in the order of Hooks called by %s. '+'This will lead to bugs and errors if not fixed. '+'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n'+' Previous render Next render\n'+' ------------------------------------------------------\n'+'%s'+' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',componentName,table);}}}}function throwInvalidHookError(){{{throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");}}}function areHookInputsEqual(nextDeps,prevDeps){{if(ignorePreviousDependencies){// Only true when this component is being hot reloaded.
return false;}}if(prevDeps===null){{error('%s received a final argument during this render, but not during '+'the previous render. Even though the final argument is optional, '+'its type cannot change between renders.',currentHookNameInDev);}return false;}{// Don't bother comparing lengths in prod because these arrays should be
// passed inline.
if(nextDeps.length!==prevDeps.length){error('The final argument passed to %s changed size between renders. The '+'order and size of this array must remain constant.\n\n'+'Previous: %s\n'+'Incoming: %s',currentHookNameInDev,"["+prevDeps.join(', ')+"]","["+nextDeps.join(', ')+"]");}}for(var i=0;i<prevDeps.length&&i<nextDeps.length;i++){if(objectIs(nextDeps[i],prevDeps[i])){continue;}return false;}return true;}function renderWithHooks(current,workInProgress,Component,props,secondArg,nextRenderLanes){renderLanes=nextRenderLanes;currentlyRenderingFiber$1=workInProgress;{hookTypesDev=current!==null?current._debugHookTypes:null;hookTypesUpdateIndexDev=-1;// Used for hot reloading:
ignorePreviousDependencies=current!==null&&current.type!==workInProgress.type;}workInProgress.memoizedState=null;workInProgress.updateQueue=null;workInProgress.lanes=NoLanes;// The following should have already been reset
// currentHook = null;
// workInProgressHook = null;
// didScheduleRenderPhaseUpdate = false;
// TODO Warn if no hooks are used at all during mount, then some are used during update.
// Currently we will identify the update render as a mount because memoizedState === null.
// This is tricky because it's valid for certain types of components (e.g. React.lazy)
// Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
// Non-stateful hooks (e.g. context) don't get added to memoizedState,
// so memoizedState would be null during updates and mounts.
{if(current!==null&&current.memoizedState!==null){ReactCurrentDispatcher$1.current=HooksDispatcherOnUpdateInDEV;}else if(hookTypesDev!==null){// This dispatcher handles an edge case where a component is updating,
// but no stateful hooks have been used.
// We want to match the production code behavior (which will use HooksDispatcherOnMount),
// but with the extra DEV validation to ensure hooks ordering hasn't changed.
// This dispatcher does that.
ReactCurrentDispatcher$1.current=HooksDispatcherOnMountWithHookTypesInDEV;}else {ReactCurrentDispatcher$1.current=HooksDispatcherOnMountInDEV;}}var children=Component(props,secondArg);// Check if there was a render phase update
if(didScheduleRenderPhaseUpdateDuringThisPass){// Keep rendering in a loop for as long as render phase updates continue to
// be scheduled. Use a counter to prevent infinite loops.
var numberOfReRenders=0;do{didScheduleRenderPhaseUpdateDuringThisPass=false;if(!(numberOfReRenders<RE_RENDER_LIMIT)){{throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");}}numberOfReRenders+=1;{// Even when hot reloading, allow dependencies to stabilize
// after first render to prevent infinite render phase updates.
ignorePreviousDependencies=false;}// Start over from the beginning of the list
currentHook=null;workInProgressHook=null;workInProgress.updateQueue=null;{// Also validate hook order for cascading updates.
hookTypesUpdateIndexDev=-1;}ReactCurrentDispatcher$1.current=HooksDispatcherOnRerenderInDEV;children=Component(props,secondArg);}while(didScheduleRenderPhaseUpdateDuringThisPass);}// We can assume the previous dispatcher is always this one, since we set it
// at the beginning of the render phase and there's no re-entrancy.
ReactCurrentDispatcher$1.current=ContextOnlyDispatcher;{workInProgress._debugHookTypes=hookTypesDev;}// This check uses currentHook so that it works the same in DEV and prod bundles.
// hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
var didRenderTooFewHooks=currentHook!==null&&currentHook.next!==null;renderLanes=NoLanes;currentlyRenderingFiber$1=null;currentHook=null;workInProgressHook=null;{currentHookNameInDev=null;hookTypesDev=null;hookTypesUpdateIndexDev=-1;}didScheduleRenderPhaseUpdate=false;if(!!didRenderTooFewHooks){{throw Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");}}return children;}function bailoutHooks(current,workInProgress,lanes){workInProgress.updateQueue=current.updateQueue;workInProgress.flags&=~(Passive|Update);current.lanes=removeLanes(current.lanes,lanes);}function resetHooksAfterThrow(){// We can assume the previous dispatcher is always this one, since we set it
// at the beginning of the render phase and there's no re-entrancy.
ReactCurrentDispatcher$1.current=ContextOnlyDispatcher;if(didScheduleRenderPhaseUpdate){// There were render phase updates. These are only valid for this render
// phase, which we are now aborting. Remove the updates from the queues so
// they do not persist to the next render. Do not remove updates from hooks
// that weren't processed.
//
// Only reset the updates from the queue if it has a clone. If it does
// not have a clone, that means it wasn't processed, and the updates were
// scheduled before we entered the render phase.
var hook=currentlyRenderingFiber$1.memoizedState;while(hook!==null){var queue=hook.queue;if(queue!==null){queue.pending=null;}hook=hook.next;}didScheduleRenderPhaseUpdate=false;}renderLanes=NoLanes;currentlyRenderingFiber$1=null;currentHook=null;workInProgressHook=null;{hookTypesDev=null;hookTypesUpdateIndexDev=-1;currentHookNameInDev=null;isUpdatingOpaqueValueInRenderPhase=false;}didScheduleRenderPhaseUpdateDuringThisPass=false;}function mountWorkInProgressHook(){var hook={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};if(workInProgressHook===null){// This is the first hook in the list
currentlyRenderingFiber$1.memoizedState=workInProgressHook=hook;}else {// Append to the end of the list
workInProgressHook=workInProgressHook.next=hook;}return workInProgressHook;}function updateWorkInProgressHook(){// This function is used both for updates and for re-renders triggered by a
// render phase update. It assumes there is either a current hook we can
// clone, or a work-in-progress hook from a previous render pass that we can
// use as a base. When we reach the end of the base list, we must switch to
// the dispatcher used for mounts.
var nextCurrentHook;if(currentHook===null){var current=currentlyRenderingFiber$1.alternate;if(current!==null){nextCurrentHook=current.memoizedState;}else {nextCurrentHook=null;}}else {nextCurrentHook=currentHook.next;}var nextWorkInProgressHook;if(workInProgressHook===null){nextWorkInProgressHook=currentlyRenderingFiber$1.memoizedState;}else {nextWorkInProgressHook=workInProgressHook.next;}if(nextWorkInProgressHook!==null){// There's already a work-in-progress. Reuse it.
workInProgressHook=nextWorkInProgressHook;nextWorkInProgressHook=workInProgressHook.next;currentHook=nextCurrentHook;}else {// Clone from the current hook.
if(!(nextCurrentHook!==null)){{throw Error("Rendered more hooks than during the previous render.");}}currentHook=nextCurrentHook;var newHook={memoizedState:currentHook.memoizedState,baseState:currentHook.baseState,baseQueue:currentHook.baseQueue,queue:currentHook.queue,next:null};if(workInProgressHook===null){// This is the first hook in the list.
currentlyRenderingFiber$1.memoizedState=workInProgressHook=newHook;}else {// Append to the end of the list.
workInProgressHook=workInProgressHook.next=newHook;}}return workInProgressHook;}function createFunctionComponentUpdateQueue(){return {lastEffect:null};}function basicStateReducer(state,action){// $FlowFixMe: Flow doesn't like mixed types
return typeof action==='function'?action(state):action;}function mountReducer(reducer,initialArg,init){var hook=mountWorkInProgressHook();var initialState;if(init!==undefined){initialState=init(initialArg);}else {initialState=initialArg;}hook.memoizedState=hook.baseState=initialState;var queue=hook.queue={pending:null,dispatch:null,lastRenderedReducer:reducer,lastRenderedState:initialState};var dispatch=queue.dispatch=dispatchAction.bind(null,currentlyRenderingFiber$1,queue);return [hook.memoizedState,dispatch];}function updateReducer(reducer,initialArg,init){var hook=updateWorkInProgressHook();var queue=hook.queue;if(!(queue!==null)){{throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");}}queue.lastRenderedReducer=reducer;var current=currentHook;// The last rebase update that is NOT part of the base state.
var baseQueue=current.baseQueue;// The last pending update that hasn't been processed yet.
var pendingQueue=queue.pending;if(pendingQueue!==null){// We have new updates that haven't been processed yet.
// We'll add them to the base queue.
if(baseQueue!==null){// Merge the pending queue and the base queue.
var baseFirst=baseQueue.next;var pendingFirst=pendingQueue.next;baseQueue.next=pendingFirst;pendingQueue.next=baseFirst;}{if(current.baseQueue!==baseQueue){// Internal invariant that should never happen, but feasibly could in
// the future if we implement resuming, or some form of that.
error('Internal error: Expected work-in-progress queue to be a clone. '+'This is a bug in React.');}}current.baseQueue=baseQueue=pendingQueue;queue.pending=null;}if(baseQueue!==null){// We have a queue to process.
var first=baseQueue.next;var newState=current.baseState;var newBaseState=null;var newBaseQueueFirst=null;var newBaseQueueLast=null;var update=first;do{var updateLane=update.lane;if(!isSubsetOfLanes(renderLanes,updateLane)){// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
var clone={lane:updateLane,action:update.action,eagerReducer:update.eagerReducer,eagerState:update.eagerState,next:null};if(newBaseQueueLast===null){newBaseQueueFirst=newBaseQueueLast=clone;newBaseState=newState;}else {newBaseQueueLast=newBaseQueueLast.next=clone;}// Update the remaining priority in the queue.
// TODO: Don't need to accumulate this. Instead, we can remove
// renderLanes from the original lanes.
currentlyRenderingFiber$1.lanes=mergeLanes(currentlyRenderingFiber$1.lanes,updateLane);markSkippedUpdateLanes(updateLane);}else {// This update does have sufficient priority.
if(newBaseQueueLast!==null){var _clone={// This update is going to be committed so we never want uncommit
// it. Using NoLane works because 0 is a subset of all bitmasks, so
// this will never be skipped by the check above.
lane:NoLane,action:update.action,eagerReducer:update.eagerReducer,eagerState:update.eagerState,next:null};newBaseQueueLast=newBaseQueueLast.next=_clone;}// Process this update.
if(update.eagerReducer===reducer){// If this update was processed eagerly, and its reducer matches the
// current reducer, we can use the eagerly computed state.
newState=update.eagerState;}else {var action=update.action;newState=reducer(newState,action);}}update=update.next;}while(update!==null&&update!==first);if(newBaseQueueLast===null){newBaseState=newState;}else {newBaseQueueLast.next=newBaseQueueFirst;}// Mark that the fiber performed work, but only if the new state is
// different from the current state.
if(!objectIs(newState,hook.memoizedState)){markWorkInProgressReceivedUpdate();}hook.memoizedState=newState;hook.baseState=newBaseState;hook.baseQueue=newBaseQueueLast;queue.lastRenderedState=newState;}var dispatch=queue.dispatch;return [hook.memoizedState,dispatch];}function rerenderReducer(reducer,initialArg,init){var hook=updateWorkInProgressHook();var queue=hook.queue;if(!(queue!==null)){{throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");}}queue.lastRenderedReducer=reducer;// This is a re-render. Apply the new render phase updates to the previous
// work-in-progress hook.
var dispatch=queue.dispatch;var lastRenderPhaseUpdate=queue.pending;var newState=hook.memoizedState;if(lastRenderPhaseUpdate!==null){// The queue doesn't persist past this render pass.
queue.pending=null;var firstRenderPhaseUpdate=lastRenderPhaseUpdate.next;var update=firstRenderPhaseUpdate;do{// Process this render phase update. We don't have to check the
// priority because it will always be the same as the current
// render's.
var action=update.action;newState=reducer(newState,action);update=update.next;}while(update!==firstRenderPhaseUpdate);// Mark that the fiber performed work, but only if the new state is
// different from the current state.
if(!objectIs(newState,hook.memoizedState)){markWorkInProgressReceivedUpdate();}hook.memoizedState=newState;// Don't persist the state accumulated from the render phase updates to
// the base state unless the queue is empty.
// TODO: Not sure if this is the desired semantics, but it's what we
// do for gDSFP. I can't remember why.
if(hook.baseQueue===null){hook.baseState=newState;}queue.lastRenderedState=newState;}return [newState,dispatch];}function readFromUnsubcribedMutableSource(root,source,getSnapshot){{warnAboutMultipleRenderersDEV(source);}var getVersion=source._getVersion;var version=getVersion(source._source);// Is it safe for this component to read from this source during the current render?
var isSafeToReadFromSource=false;// Check the version first.
// If this render has already been started with a specific version,
// we can use it alone to determine if we can safely read from the source.
var currentRenderVersion=getWorkInProgressVersion(source);if(currentRenderVersion!==null){// It's safe to read if the store hasn't been mutated since the last time
// we read something.
isSafeToReadFromSource=currentRenderVersion===version;}else {// If there's no version, then this is the first time we've read from the
// source during the current render pass, so we need to do a bit more work.
// What we need to determine is if there are any hooks that already
// subscribed to the source, and if so, whether there are any pending
// mutations that haven't been synchronized yet.
//
// If there are no pending mutations, then `root.mutableReadLanes` will be
// empty, and we know we can safely read.
//
// If there *are* pending mutations, we may still be able to safely read
// if the currently rendering lanes are inclusive of the pending mutation
// lanes, since that guarantees that the value we're about to read from
// the source is consistent with the values that we read during the most
// recent mutation.
isSafeToReadFromSource=isSubsetOfLanes(renderLanes,root.mutableReadLanes);if(isSafeToReadFromSource){// If it's safe to read from this source during the current render,
// store the version in case other components read from it.
// A changed version number will let those components know to throw and restart the render.
setWorkInProgressVersion(source,version);}}if(isSafeToReadFromSource){var snapshot=getSnapshot(source._source);{if(typeof snapshot==='function'){error('Mutable source should not return a function as the snapshot value. '+'Functions may close over mutable values and cause tearing.');}}return snapshot;}else {// This handles the special case of a mutable source being shared between renderers.
// In that case, if the source is mutated between the first and second renderer,
// The second renderer don't know that it needs to reset the WIP version during unwind,
// (because the hook only marks sources as dirty if it's written to their WIP version).
// That would cause this tear check to throw again and eventually be visible to the user.
// We can avoid this infinite loop by explicitly marking the source as dirty.
//
// This can lead to tearing in the first renderer when it resumes,
// but there's nothing we can do about that (short of throwing here and refusing to continue the render).
markSourceAsDirty(source);{{throw Error("Cannot read from mutable source during the current render without tearing. This is a bug in React. Please file an issue.");}}}}function useMutableSource(hook,source,getSnapshot,subscribe){var root=getWorkInProgressRoot();if(!(root!==null)){{throw Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");}}var getVersion=source._getVersion;var version=getVersion(source._source);var dispatcher=ReactCurrentDispatcher$1.current;// eslint-disable-next-line prefer-const
var _dispatcher$useState=dispatcher.useState(function(){return readFromUnsubcribedMutableSource(root,source,getSnapshot);}),currentSnapshot=_dispatcher$useState[0],setSnapshot=_dispatcher$useState[1];var snapshot=currentSnapshot;// Grab a handle to the state hook as well.
// We use it to clear the pending update queue if we have a new source.
var stateHook=workInProgressHook;var memoizedState=hook.memoizedState;var refs=memoizedState.refs;var prevGetSnapshot=refs.getSnapshot;var prevSource=memoizedState.source;var prevSubscribe=memoizedState.subscribe;var fiber=currentlyRenderingFiber$1;hook.memoizedState={refs:refs,source:source,subscribe:subscribe};// Sync the values needed by our subscription handler after each commit.
dispatcher.useEffect(function(){refs.getSnapshot=getSnapshot;// Normally the dispatch function for a state hook never changes,
// but this hook recreates the queue in certain cases to avoid updates from stale sources.
// handleChange() below needs to reference the dispatch function without re-subscribing,
// so we use a ref to ensure that it always has the latest version.
refs.setSnapshot=setSnapshot;// Check for a possible change between when we last rendered now.
var maybeNewVersion=getVersion(source._source);if(!objectIs(version,maybeNewVersion)){var maybeNewSnapshot=getSnapshot(source._source);{if(typeof maybeNewSnapshot==='function'){error('Mutable source should not return a function as the snapshot value. '+'Functions may close over mutable values and cause tearing.');}}if(!objectIs(snapshot,maybeNewSnapshot)){setSnapshot(maybeNewSnapshot);var lane=requestUpdateLane(fiber);markRootMutableRead(root,lane);}// If the source mutated between render and now,
// there may be state updates already scheduled from the old source.
// Entangle the updates so that they render in the same batch.
markRootEntangled(root,root.mutableReadLanes);}},[getSnapshot,source,subscribe]);// If we got a new source or subscribe function, re-subscribe in a passive effect.
dispatcher.useEffect(function(){var handleChange=function(){var latestGetSnapshot=refs.getSnapshot;var latestSetSnapshot=refs.setSnapshot;try{latestSetSnapshot(latestGetSnapshot(source._source));// Record a pending mutable source update with the same expiration time.
var lane=requestUpdateLane(fiber);markRootMutableRead(root,lane);}catch(error){// A selector might throw after a source mutation.
// e.g. it might try to read from a part of the store that no longer exists.
// In this case we should still schedule an update with React.
// Worst case the selector will throw again and then an error boundary will handle it.
latestSetSnapshot(function(){throw error;});}};var unsubscribe=subscribe(source._source,handleChange);{if(typeof unsubscribe!=='function'){error('Mutable source subscribe function must return an unsubscribe function.');}}return unsubscribe;},[source,subscribe]);// If any of the inputs to useMutableSource change, reading is potentially unsafe.
//
// If either the source or the subscription have changed we can't can't trust the update queue.
// Maybe the source changed in a way that the old subscription ignored but the new one depends on.
//
// If the getSnapshot function changed, we also shouldn't rely on the update queue.
// It's possible that the underlying source was mutated between the when the last "change" event fired,
// and when the current render (with the new getSnapshot function) is processed.
//
// In both cases, we need to throw away pending updates (since they are no longer relevant)
// and treat reading from the source as we do in the mount case.
if(!objectIs(prevGetSnapshot,getSnapshot)||!objectIs(prevSource,source)||!objectIs(prevSubscribe,subscribe)){// Create a new queue and setState method,
// So if there are interleaved updates, they get pushed to the older queue.
// When this becomes current, the previous queue and dispatch method will be discarded,
// including any interleaving updates that occur.
var newQueue={pending:null,dispatch:null,lastRenderedReducer:basicStateReducer,lastRenderedState:snapshot};newQueue.dispatch=setSnapshot=dispatchAction.bind(null,currentlyRenderingFiber$1,newQueue);stateHook.queue=newQueue;stateHook.baseQueue=null;snapshot=readFromUnsubcribedMutableSource(root,source,getSnapshot);stateHook.memoizedState=stateHook.baseState=snapshot;}return snapshot;}function mountMutableSource(source,getSnapshot,subscribe){var hook=mountWorkInProgressHook();hook.memoizedState={refs:{getSnapshot:getSnapshot,setSnapshot:null},source:source,subscribe:subscribe};return useMutableSource(hook,source,getSnapshot,subscribe);}function updateMutableSource(source,getSnapshot,subscribe){var hook=updateWorkInProgressHook();return useMutableSource(hook,source,getSnapshot,subscribe);}function mountState(initialState){var hook=mountWorkInProgressHook();if(typeof initialState==='function'){// $FlowFixMe: Flow doesn't like mixed types
initialState=initialState();}hook.memoizedState=hook.baseState=initialState;var queue=hook.queue={pending:null,dispatch:null,lastRenderedReducer:basicStateReducer,lastRenderedState:initialState};var dispatch=queue.dispatch=dispatchAction.bind(null,currentlyRenderingFiber$1,queue);return [hook.memoizedState,dispatch];}function updateState(initialState){return updateReducer(basicStateReducer);}function rerenderState(initialState){return rerenderReducer(basicStateReducer);}function pushEffect(tag,create,destroy,deps){var effect={tag:tag,create:create,destroy:destroy,deps:deps,// Circular
next:null};var componentUpdateQueue=currentlyRenderingFiber$1.updateQueue;if(componentUpdateQueue===null){componentUpdateQueue=createFunctionComponentUpdateQueue();currentlyRenderingFiber$1.updateQueue=componentUpdateQueue;componentUpdateQueue.lastEffect=effect.next=effect;}else {var lastEffect=componentUpdateQueue.lastEffect;if(lastEffect===null){componentUpdateQueue.lastEffect=effect.next=effect;}else {var firstEffect=lastEffect.next;lastEffect.next=effect;effect.next=firstEffect;componentUpdateQueue.lastEffect=effect;}}return effect;}function mountRef(initialValue){var hook=mountWorkInProgressHook();var ref={current:initialValue};{Object.seal(ref);}hook.memoizedState=ref;return ref;}function updateRef(initialValue){var hook=updateWorkInProgressHook();return hook.memoizedState;}function mountEffectImpl(fiberFlags,hookFlags,create,deps){var hook=mountWorkInProgressHook();var nextDeps=deps===undefined?null:deps;currentlyRenderingFiber$1.flags|=fiberFlags;hook.memoizedState=pushEffect(HasEffect|hookFlags,create,undefined,nextDeps);}function updateEffectImpl(fiberFlags,hookFlags,create,deps){var hook=updateWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var destroy=undefined;if(currentHook!==null){var prevEffect=currentHook.memoizedState;destroy=prevEffect.destroy;if(nextDeps!==null){var prevDeps=prevEffect.deps;if(areHookInputsEqual(nextDeps,prevDeps)){pushEffect(hookFlags,create,destroy,nextDeps);return;}}}currentlyRenderingFiber$1.flags|=fiberFlags;hook.memoizedState=pushEffect(HasEffect|hookFlags,create,destroy,nextDeps);}function mountEffect(create,deps){{// $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
if('undefined'!==typeof jest){warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);}}return mountEffectImpl(Update|Passive,Passive$1,create,deps);}function updateEffect(create,deps){{// $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
if('undefined'!==typeof jest){warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);}}return updateEffectImpl(Update|Passive,Passive$1,create,deps);}function mountLayoutEffect(create,deps){return mountEffectImpl(Update,Layout,create,deps);}function updateLayoutEffect(create,deps){return updateEffectImpl(Update,Layout,create,deps);}function imperativeHandleEffect(create,ref){if(typeof ref==='function'){var refCallback=ref;var _inst=create();refCallback(_inst);return function(){refCallback(null);};}else if(ref!==null&&ref!==undefined){var refObject=ref;{if(!refObject.hasOwnProperty('current')){error('Expected useImperativeHandle() first argument to either be a '+'ref callback or React.createRef() object. Instead received: %s.','an object with keys {'+Object.keys(refObject).join(', ')+'}');}}var _inst2=create();refObject.current=_inst2;return function(){refObject.current=null;};}}function mountImperativeHandle(ref,create,deps){{if(typeof create!=='function'){error('Expected useImperativeHandle() second argument to be a function '+'that creates a handle. Instead received: %s.',create!==null?typeof create:'null');}}// TODO: If deps are provided, should we skip comparing the ref itself?
var effectDeps=deps!==null&&deps!==undefined?deps.concat([ref]):null;return mountEffectImpl(Update,Layout,imperativeHandleEffect.bind(null,create,ref),effectDeps);}function updateImperativeHandle(ref,create,deps){{if(typeof create!=='function'){error('Expected useImperativeHandle() second argument to be a function '+'that creates a handle. Instead received: %s.',create!==null?typeof create:'null');}}// TODO: If deps are provided, should we skip comparing the ref itself?
var effectDeps=deps!==null&&deps!==undefined?deps.concat([ref]):null;return updateEffectImpl(Update,Layout,imperativeHandleEffect.bind(null,create,ref),effectDeps);}function mountDebugValue(value,formatterFn){// This hook is normally a no-op.
// The react-debug-hooks package injects its own implementation
// so that e.g. DevTools can display custom hook values.
}var updateDebugValue=mountDebugValue;function mountCallback(callback,deps){var hook=mountWorkInProgressHook();var nextDeps=deps===undefined?null:deps;hook.memoizedState=[callback,nextDeps];return callback;}function updateCallback(callback,deps){var hook=updateWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var prevState=hook.memoizedState;if(prevState!==null){if(nextDeps!==null){var prevDeps=prevState[1];if(areHookInputsEqual(nextDeps,prevDeps)){return prevState[0];}}}hook.memoizedState=[callback,nextDeps];return callback;}function mountMemo(nextCreate,deps){var hook=mountWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var nextValue=nextCreate();hook.memoizedState=[nextValue,nextDeps];return nextValue;}function updateMemo(nextCreate,deps){var hook=updateWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var prevState=hook.memoizedState;if(prevState!==null){// Assume these are defined. If they're not, areHookInputsEqual will warn.
if(nextDeps!==null){var prevDeps=prevState[1];if(areHookInputsEqual(nextDeps,prevDeps)){return prevState[0];}}}var nextValue=nextCreate();hook.memoizedState=[nextValue,nextDeps];return nextValue;}function mountDeferredValue(value){var _mountState=mountState(value),prevValue=_mountState[0],setValue=_mountState[1];mountEffect(function(){var prevTransition=ReactCurrentBatchConfig$1.transition;ReactCurrentBatchConfig$1.transition=1;try{setValue(value);}finally{ReactCurrentBatchConfig$1.transition=prevTransition;}},[value]);return prevValue;}function updateDeferredValue(value){var _updateState=updateState(),prevValue=_updateState[0],setValue=_updateState[1];updateEffect(function(){var prevTransition=ReactCurrentBatchConfig$1.transition;ReactCurrentBatchConfig$1.transition=1;try{setValue(value);}finally{ReactCurrentBatchConfig$1.transition=prevTransition;}},[value]);return prevValue;}function rerenderDeferredValue(value){var _rerenderState=rerenderState(),prevValue=_rerenderState[0],setValue=_rerenderState[1];updateEffect(function(){var prevTransition=ReactCurrentBatchConfig$1.transition;ReactCurrentBatchConfig$1.transition=1;try{setValue(value);}finally{ReactCurrentBatchConfig$1.transition=prevTransition;}},[value]);return prevValue;}function startTransition(setPending,callback){var priorityLevel=getCurrentPriorityLevel();{runWithPriority$1(priorityLevel<UserBlockingPriority$2?UserBlockingPriority$2:priorityLevel,function(){setPending(true);});runWithPriority$1(priorityLevel>NormalPriority$1?NormalPriority$1:priorityLevel,function(){var prevTransition=ReactCurrentBatchConfig$1.transition;ReactCurrentBatchConfig$1.transition=1;try{setPending(false);callback();}finally{ReactCurrentBatchConfig$1.transition=prevTransition;}});}}function mountTransition(){var _mountState2=mountState(false),isPending=_mountState2[0],setPending=_mountState2[1];// The `start` method can be stored on a ref, since `setPending`
// never changes.
var start=startTransition.bind(null,setPending);mountRef(start);return [start,isPending];}function updateTransition(){var _updateState2=updateState(),isPending=_updateState2[0];var startRef=updateRef();var start=startRef.current;return [start,isPending];}function rerenderTransition(){var _rerenderState2=rerenderState(),isPending=_rerenderState2[0];var startRef=updateRef();var start=startRef.current;return [start,isPending];}var isUpdatingOpaqueValueInRenderPhase=false;function getIsUpdatingOpaqueValueInRenderPhaseInDEV(){{return isUpdatingOpaqueValueInRenderPhase;}}function warnOnOpaqueIdentifierAccessInDEV(fiber){{// TODO: Should warn in effects and callbacks, too
var name=getComponentName(fiber.type)||'Unknown';if(getIsRendering()&&!didWarnAboutUseOpaqueIdentifier[name]){error('The object passed back from useOpaqueIdentifier is meant to be '+'passed through to attributes only. Do not read the '+'value directly.');didWarnAboutUseOpaqueIdentifier[name]=true;}}}function mountOpaqueIdentifier(){var makeId=makeClientIdInDEV.bind(null,warnOnOpaqueIdentifierAccessInDEV.bind(null,currentlyRenderingFiber$1));if(getIsHydrating()){var didUpgrade=false;var fiber=currentlyRenderingFiber$1;var readValue=function(){if(!didUpgrade){// Only upgrade once. This works even inside the render phase because
// the update is added to a shared queue, which outlasts the
// in-progress render.
didUpgrade=true;{isUpdatingOpaqueValueInRenderPhase=true;setId(makeId());isUpdatingOpaqueValueInRenderPhase=false;warnOnOpaqueIdentifierAccessInDEV(fiber);}}{{throw Error("The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.");}}};var id=makeOpaqueHydratingObject(readValue);var setId=mountState(id)[1];if((currentlyRenderingFiber$1.mode&BlockingMode)===NoMode){currentlyRenderingFiber$1.flags|=Update|Passive;pushEffect(HasEffect|Passive$1,function(){setId(makeId());},undefined,null);}return id;}else {var _id=makeId();mountState(_id);return _id;}}function updateOpaqueIdentifier(){var id=updateState()[0];return id;}function rerenderOpaqueIdentifier(){var id=rerenderState()[0];return id;}function dispatchAction(fiber,queue,action){{if(typeof arguments[3]==='function'){error("State updates from the useState() and useReducer() Hooks don't support the "+'second callback argument. To execute a side effect after '+'rendering, declare it in the component body with useEffect().');}}var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update={lane:lane,action:action,eagerReducer:null,eagerState:null,next:null};// Append the update to the end of the list.
var pending=queue.pending;if(pending===null){// This is the first update. Create a circular list.
update.next=update;}else {update.next=pending.next;pending.next=update;}queue.pending=update;var alternate=fiber.alternate;if(fiber===currentlyRenderingFiber$1||alternate!==null&&alternate===currentlyRenderingFiber$1){// This is a render phase update. Stash it in a lazily-created map of
// queue -> linked list of updates. After this render pass, we'll restart
// and apply the stashed updates on top of the work-in-progress hook.
didScheduleRenderPhaseUpdateDuringThisPass=didScheduleRenderPhaseUpdate=true;}else {if(fiber.lanes===NoLanes&&(alternate===null||alternate.lanes===NoLanes)){// The queue is currently empty, which means we can eagerly compute the
// next state before entering the render phase. If the new state is the
// same as the current state, we may be able to bail out entirely.
var lastRenderedReducer=queue.lastRenderedReducer;if(lastRenderedReducer!==null){var prevDispatcher;{prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;}try{var currentState=queue.lastRenderedState;var eagerState=lastRenderedReducer(currentState,action);// Stash the eagerly computed state, and the reducer used to compute
// it, on the update object. If the reducer hasn't changed by the
// time we enter the render phase, then the eager state can be used
// without calling the reducer again.
update.eagerReducer=lastRenderedReducer;update.eagerState=eagerState;if(objectIs(eagerState,currentState)){// Fast path. We can bail out without scheduling React to re-render.
// It's still possible that we'll need to rebase this update later,
// if the component re-renders for a different reason and by that
// time the reducer has changed.
return;}}catch(error){// Suppress the error. It will throw again in the render phase.
}finally{{ReactCurrentDispatcher$1.current=prevDispatcher;}}}}{// $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
if('undefined'!==typeof jest){warnIfNotScopedWithMatchingAct(fiber);warnIfNotCurrentlyActingUpdatesInDev(fiber);}}scheduleUpdateOnFiber(fiber,lane,eventTime);}}var ContextOnlyDispatcher={readContext:readContext,useCallback:throwInvalidHookError,useContext:throwInvalidHookError,useEffect:throwInvalidHookError,useImperativeHandle:throwInvalidHookError,useLayoutEffect:throwInvalidHookError,useMemo:throwInvalidHookError,useReducer:throwInvalidHookError,useRef:throwInvalidHookError,useState:throwInvalidHookError,useDebugValue:throwInvalidHookError,useDeferredValue:throwInvalidHookError,useTransition:throwInvalidHookError,useMutableSource:throwInvalidHookError,useOpaqueIdentifier:throwInvalidHookError,unstable_isNewReconciler:enableNewReconciler};var HooksDispatcherOnMountInDEV=null;var HooksDispatcherOnMountWithHookTypesInDEV=null;var HooksDispatcherOnUpdateInDEV=null;var HooksDispatcherOnRerenderInDEV=null;var InvalidNestedHooksDispatcherOnMountInDEV=null;var InvalidNestedHooksDispatcherOnUpdateInDEV=null;var InvalidNestedHooksDispatcherOnRerenderInDEV=null;{var warnInvalidContextAccess=function(){error('Context can only be read while React is rendering. '+'In classes, you can read it in the render method or getDerivedStateFromProps. '+'In function components, you can read it directly in the function body, but not '+'inside Hooks like useReducer() or useMemo().');};var warnInvalidHookAccess=function(){error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. '+'You can only call Hooks at the top level of your React function. '+'For more information, see '+'https://reactjs.org/link/rules-of-hooks');};HooksDispatcherOnMountInDEV={readContext:function(context,observedBits){return readContext(context,observedBits);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountCallback(callback,deps);},useContext:function(context,observedBits){currentHookNameInDev='useContext';mountHookTypesDev();return readContext(context,observedBits);},useEffect:function(create,deps){currentHookNameInDev='useEffect';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountImperativeHandle(ref,create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';mountHookTypesDev();checkDepsAreArrayDev(deps);var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';mountHookTypesDev();return mountRef(initialValue);},useState:function(initialState){currentHookNameInDev='useState';mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';mountHookTypesDev();return mountDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';mountHookTypesDev();return mountDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';mountHookTypesDev();return mountTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';
// after we rerender. This is used as a helper in special cases
// where we should count the work of multiple passes.
var child=fiber.child;while(child){fiber.actualDuration+=child.actualDuration;child=child.sibling;}}var ReactCurrentOwner$1=ReactSharedInternals.ReactCurrentOwner;var didReceiveUpdate=false;var didWarnAboutBadClass;var didWarnAboutModulePatternComponent;var didWarnAboutContextTypeOnFunctionComponent;var didWarnAboutGetDerivedStateOnFunctionComponent;var didWarnAboutFunctionRefs;var didWarnAboutReassigningProps;var didWarnAboutRevealOrder;var didWarnAboutTailOptions;{didWarnAboutBadClass={};didWarnAboutModulePatternComponent={};didWarnAboutContextTypeOnFunctionComponent={};didWarnAboutGetDerivedStateOnFunctionComponent={};didWarnAboutFunctionRefs={};didWarnAboutReassigningProps=false;didWarnAboutRevealOrder={};didWarnAboutTailOptions={};}function reconcileChildren(current,workInProgress,nextChildren,renderLanes){if(current===null){// If this is a fresh new component that hasn't been rendered yet, we
// won't update its child set by applying minimal side-effects. Instead,
// we will add them all to the child before it gets rendered. That means
// we can optimize this reconciliation pass by not tracking side-effects.
workInProgress.child=mountChildFibers(workInProgress,null,nextChildren,renderLanes);}else {// If the current child is the same as the work in progress, it means that
// we haven't yet started any work on these children. Therefore, we use
// the clone algorithm to create a copy of all the current children.
// If we had any progressed work already, that is invalid at this point so
// let's throw it out.
workInProgress.child=reconcileChildFibers(workInProgress,current.child,nextChildren,renderLanes);}}function forceUnmountCurrentAndReconcile(current,workInProgress,nextChildren,renderLanes){// This function is fork of reconcileChildren. It's used in cases where we
// want to reconcile without matching against the existing set. This has the
// effect of all current children being unmounted; even if the type and key
// are the same, the old child is unmounted and a new child is created.
//
// To do this, we're going to go through the reconcile algorithm twice. In
// the first pass, we schedule a deletion for all the current children by
// passing null.
workInProgress.child=reconcileChildFibers(workInProgress,current.child,null,renderLanes);// In the second pass, we mount the new children. The trick here is that we
// pass null in place of where we usually pass the current child set. This has
// the effect of remounting all children regardless of whether their
// identities match.
workInProgress.child=reconcileChildFibers(workInProgress,null,nextChildren,renderLanes);}function updateForwardRef(current,workInProgress,Component,nextProps,renderLanes){// TODO: current can be non-null here even if the component
// hasn't yet mounted. This happens after the first render suspends.
// We'll need to figure out if this is fine or can cause issues.
{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes=Component.propTypes;if(innerPropTypes){checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentName(Component));}}}var render=Component.render;var ref=workInProgress.ref;// The rest is a fork of updateFunctionComponent
var nextChildren;prepareToReadContext(workInProgress,renderLanes);{ReactCurrentOwner$1.current=workInProgress;setIsRendering(true);nextChildren=renderWithHooks(current,workInProgress,render,nextProps,ref,renderLanes);if(workInProgress.mode&StrictMode){disableLogs();try{nextChildren=renderWithHooks(current,workInProgress,render,nextProps,ref,renderLanes);}finally{reenableLogs();}}setIsRendering(false);}if(current!==null&&!didReceiveUpdate){bailoutHooks(current,workInProgress,renderLanes);return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateMemoComponent(current,workInProgress,Component,nextProps,updateLanes,renderLanes){if(current===null){var type=Component.type;if(isSimpleFunctionComponent(type)&&Component.compare===null&&// SimpleMemoComponent codepath doesn't resolve outer props either.
Component.defaultProps===undefined){var resolvedType=type;{resolvedType=resolveFunctionForHotReloading(type);}// If this is a plain function component without default props,
// and with only the default shallow comparison, we upgrade it
// to a SimpleMemoComponent to allow fast path updates.
workInProgress.tag=SimpleMemoComponent;workInProgress.type=resolvedType;{validateFunctionComponentInDev(workInProgress,type);}return updateSimpleMemoComponent(current,workInProgress,resolvedType,nextProps,updateLanes,renderLanes);}{var innerPropTypes=type.propTypes;if(innerPropTypes){// Inner memo component props aren't currently validated in createElement.
// We could move it there, but we'd still need this for lazy code path.
checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentName(type));}}var child=createFiberFromTypeAndProps(Component.type,null,nextProps,workInProgress,workInProgress.mode,renderLanes);child.ref=workInProgress.ref;child.return=workInProgress;workInProgress.child=child;return child;}{var _type=Component.type;var _innerPropTypes=_type.propTypes;if(_innerPropTypes){// Inner memo component props aren't currently validated in createElement.
// We could move it there, but we'd still need this for lazy code path.
checkPropTypes(_innerPropTypes,nextProps,// Resolved props
'prop',getComponentName(_type));}}var currentChild=current.child;// This is always exactly one child
if(!includesSomeLane(updateLanes,renderLanes)){// This will be the props with resolved defaultProps,
// unlike current.memoizedProps which will be the unresolved ones.
var prevProps=currentChild.memoizedProps;// Default to shallow comparison
var compare=Component.compare;compare=compare!==null?compare:shallowEqual;if(compare(prevProps,nextProps)&&current.ref===workInProgress.ref){return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;var newChild=createWorkInProgress(currentChild,nextProps);newChild.ref=workInProgress.ref;newChild.return=workInProgress;workInProgress.child=newChild;return newChild;}function updateSimpleMemoComponent(current,workInProgress,Component,nextProps,updateLanes,renderLanes){// TODO: current can be non-null here even if the component
// hasn't yet mounted. This happens when the inner render suspends.
// We'll need to figure out if this is fine or can cause issues.
{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var outerMemoType=workInProgress.elementType;if(outerMemoType.$$typeof===REACT_LAZY_TYPE){// We warn when you define propTypes on lazy()
// so let's just skip over it to find memo() outer wrapper.
// Inner props for memo are validated later.
var lazyComponent=outerMemoType;var payload=lazyComponent._payload;var init=lazyComponent._init;try{outerMemoType=init(payload);}catch(x){outerMemoType=null;}// Inner propTypes will be validated in the function component path.
var outerPropTypes=outerMemoType&&outerMemoType.propTypes;if(outerPropTypes){checkPropTypes(outerPropTypes,nextProps,// Resolved (SimpleMemoComponent has no defaultProps)
'prop',getComponentName(outerMemoType));}}}}if(current!==null){var prevProps=current.memoizedProps;if(shallowEqual(prevProps,nextProps)&&current.ref===workInProgress.ref&&// Prevent bailout if the implementation changed due to hot reload.
workInProgress.type===current.type){didReceiveUpdate=false;if(!includesSomeLane(renderLanes,updateLanes)){// The pending lanes were cleared at the beginning of beginWork. We're
// about to bail out, but there might be other lanes that weren't
// included in the current render. Usually, the priority level of the
// remaining updates is accumlated during the evaluation of the
// component (i.e. when processing the update queue). But since since
// we're bailing out early *without* evaluating the component, we need
// to account for it here, too. Reset to the value of the current fiber.
// NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
// because a MemoComponent fiber does not have hooks or an update queue;
// rather, it wraps around an inner component, which may or may not
// contains hooks.
// TODO: Move the reset at in beginWork out of the common path so that
// this is no longer necessary.
workInProgress.lanes=current.lanes;return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}else if((current.flags&ForceUpdateForLegacySuspense)!==NoFlags){// This is a special case that only exists for legacy mode.
// See https://github.com/facebook/react/pull/19216.
didReceiveUpdate=true;}}}return updateFunctionComponent(current,workInProgress,Component,nextProps,renderLanes);}function updateOffscreenComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps;var nextChildren=nextProps.children;var prevState=current!==null?current.memoizedState:null;if(nextProps.mode==='hidden'||nextProps.mode==='unstable-defer-without-hiding'){if((workInProgress.mode&ConcurrentMode)===NoMode){// In legacy sync mode, don't defer the subtree. Render it now.
// TODO: Figure out what we should do in Blocking mode.
var nextState={baseLanes:NoLanes};workInProgress.memoizedState=nextState;pushRenderLanes(workInProgress,renderLanes);}else if(!includesSomeLane(renderLanes,OffscreenLane)){var nextBaseLanes;if(prevState!==null){var prevBaseLanes=prevState.baseLanes;nextBaseLanes=mergeLanes(prevBaseLanes,renderLanes);}else {nextBaseLanes=renderLanes;}// Schedule this fiber to re-render at offscreen priority. Then bailout.
{markSpawnedWork(OffscreenLane);}workInProgress.lanes=workInProgress.childLanes=laneToLanes(OffscreenLane);var _nextState={baseLanes:nextBaseLanes};workInProgress.memoizedState=_nextState;// We're about to bail out, but we need to push this to the stack anyway
// to avoid a push/pop misalignment.
pushRenderLanes(workInProgress,nextBaseLanes);return null;}else {// Rendering at offscreen, so we can clear the base lanes.
var _nextState2={baseLanes:NoLanes};workInProgress.memoizedState=_nextState2;// Push the lanes that were skipped when we bailed out.
var subtreeRenderLanes=prevState!==null?prevState.baseLanes:renderLanes;pushRenderLanes(workInProgress,subtreeRenderLanes);}}else {var _subtreeRenderLanes;if(prevState!==null){_subtreeRenderLanes=mergeLanes(prevState.baseLanes,renderLanes);// Since we're not hidden anymore, reset the state
workInProgress.memoizedState=null;}else {// We weren't previously hidden, and we still aren't, so there's nothing
// special to do. Need to push to the stack regardless, though, to avoid
// a push/pop misalignment.
_subtreeRenderLanes=renderLanes;}pushRenderLanes(workInProgress,_subtreeRenderLanes);}reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}// Note: These happen to have identical begin phases, for now. We shouldn't hold
// ourselves to this constraint, though. If the behavior diverges, we should
// fork the function.
var updateLegacyHiddenComponent=updateOffscreenComponent;function updateFragment(current,workInProgress,renderLanes){var nextChildren=workInProgress.pendingProps;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateMode(current,workInProgress,renderLanes){var nextChildren=workInProgress.pendingProps.children;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateProfiler(current,workInProgress,renderLanes){{workInProgress.flags|=Update;// Reset effect durations for the next eventual effect phase.
// These are reset during render to allow the DevTools commit hook a chance to read them,
var stateNode=workInProgress.stateNode;stateNode.effectDuration=0;stateNode.passiveEffectDuration=0;}var nextProps=workInProgress.pendingProps;var nextChildren=nextProps.children;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function markRef(current,workInProgress){var ref=workInProgress.ref;if(current===null&&ref!==null||current!==null&&current.ref!==ref){// Schedule a Ref effect
workInProgress.flags|=Ref;}}function updateFunctionComponent(current,workInProgress,Component,nextProps,renderLanes){{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes=Component.propTypes;if(innerPropTypes){checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentName(Component));}}}var context;{var unmaskedContext=getUnmaskedContext(workInProgress,Component,true);context=getMaskedContext(workInProgress,unmaskedContext);}var nextChildren;prepareToReadContext(workInProgress,renderLanes);{ReactCurrentOwner$1.current=workInProgress;setIsRendering(true);nextChildren=renderWithHooks(current,workInProgress,Component,nextProps,context,renderLanes);if(workInProgress.mode&StrictMode){disableLogs();try{nextChildren=renderWithHooks(current,workInProgress,Component,nextProps,context,renderLanes);}finally{reenableLogs();}}setIsRendering(false);}if(current!==null&&!didReceiveUpdate){bailoutHooks(current,workInProgress,renderLanes);return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateClassComponent(current,workInProgress,Component,nextProps,renderLanes){{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes=Component.propTypes;if(innerPropTypes){checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentName(Component));}}}// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext;if(isContextProvider(Component)){hasContext=true;pushContextProvider(workInProgress);}else {hasContext=false;}prepareToReadContext(workInProgress,renderLanes);var instance=workInProgress.stateNode;var shouldUpdate;if(instance===null){if(current!==null){// A class component without an instance only mounts if it suspended
// inside a non-concurrent tree, in an inconsistent state. We want to
// treat it like a new mount, even though an empty version of it already
// committed. Disconnect the alternate pointers.
current.alternate=null;workInProgress.alternate=null;// Since this is conceptually a new fiber, schedule a Placement effect
workInProgress.flags|=Placement;}// In the initial pass we might need to construct the instance.
constructClassInstance(workInProgress,Component,nextProps);mountClassInstance(workInProgress,Component,nextProps,renderLanes);shouldUpdate=true;}else if(current===null){// In a resume, we'll already have an instance we can reuse.
shouldUpdate=resumeMountClassInstance(workInProgress,Component,nextProps,renderLanes);}else {shouldUpdate=updateClassInstance(current,workInProgress,Component,nextProps,renderLanes);}var nextUnitOfWork=finishClassComponent(current,workInProgress,Component,shouldUpdate,hasContext,renderLanes);{var inst=workInProgress.stateNode;if(shouldUpdate&&inst.props!==nextProps){if(!didWarnAboutReassigningProps){error('It looks like %s is reassigning its own `this.props` while rendering. '+'This is not supported and can lead to confusing bugs.',getComponentName(workInProgress.type)||'a component');}didWarnAboutReassigningProps=true;}}return nextUnitOfWork;}function finishClassComponent(current,workInProgress,Component,shouldUpdate,hasContext,renderLanes){// Refs should update even if shouldComponentUpdate returns false
markRef(current,workInProgress);var didCaptureError=(workInProgress.flags&DidCapture)!==NoFlags;if(!shouldUpdate&&!didCaptureError){// Context providers should defer to sCU for rendering
if(hasContext){invalidateContextProvider(workInProgress,Component,false);}return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}var instance=workInProgress.stateNode;// Rerender
ReactCurrentOwner$1.current=workInProgress;var nextChildren;if(didCaptureError&&typeof Component.getDerivedStateFromError!=='function'){// If we captured an error, but getDerivedStateFromError is not defined,
// unmount all the children. componentDidCatch will schedule an update to
// re-render a fallback. This is temporary until we migrate everyone to
// the new API.
// TODO: Warn in a future release.
nextChildren=null;{stopProfilerTimerIfRunning();}}else {{setIsRendering(true);nextChildren=instance.render();if(workInProgress.mode&StrictMode){disableLogs();try{instance.render();}finally{reenableLogs();}}setIsRendering(false);}}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;if(current!==null&&didCaptureError){// If we're recovering from an error, reconcile without reusing any of
// the existing children. Conceptually, the normal children and the children
// that are shown on error are two different sets, so we shouldn't reuse
// normal children even if their identities match.
forceUnmountCurrentAndReconcile(current,workInProgress,nextChildren,renderLanes);}else {reconcileChildren(current,workInProgress,nextChildren,renderLanes);}// Memoize state using the values we just used to render.
// TODO: Restructure so we never read values from the instance.
workInProgress.memoizedState=instance.state;// The context might have changed so we need to recalculate it.
if(hasContext){invalidateContextProvider(workInProgress,Component,true);}return workInProgress.child;}function pushHostRootContext(workInProgress){var root=workInProgress.stateNode;if(root.pendingContext){pushTopLevelContextObject(workInProgress,root.pendingContext,root.pendingContext!==root.context);}else if(root.context){// Should always be set
pushTopLevelContextObject(workInProgress,root.context,false);}pushHostContainer(workInProgress,root.containerInfo);}function updateHostRoot(current,workInProgress,renderLanes){pushHostRootContext(workInProgress);var updateQueue=workInProgress.updateQueue;if(!(current!==null&&updateQueue!==null)){{throw Error("If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.");}}var nextProps=workInProgress.pendingProps;var prevState=workInProgress.memoizedState;var prevChildren=prevState!==null?prevState.element:null;cloneUpdateQueue(current,workInProgress);processUpdateQueue(workInProgress,nextProps,null,renderLanes);var nextState=workInProgress.memoizedState;// Caution: React DevTools currently depends on this property
// being called "element".
var nextChildren=nextState.element;if(nextChildren===prevChildren){resetHydrationState();return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}var root=workInProgress.stateNode;if(root.hydrate&&enterHydrationState(workInProgress)){// If we don't have any current children this might be the first pass.
// We always try to hydrate. If this isn't a hydration pass there won't
// be any children to hydrate which is effectively the same thing as
// not hydrating.
{var mutableSourceEagerHydrationData=root.mutableSourceEagerHydrationData;if(mutableSourceEagerHydrationData!=null){for(var i=0;i<mutableSourceEagerHydrationData.length;i+=2){var mutableSource=mutableSourceEagerHydrationData[i];var version=mutableSourceEagerHydrationData[i+1];setWorkInProgressVersion(mutableSource,version);}}}var child=mountChildFibers(workInProgress,null,nextChildren,renderLanes);workInProgress.child=child;var node=child;while(node){// Mark each child as hydrating. This is a fast path to know whether this
// tree is part of a hydrating tree. This is used to determine if a child
// node has fully mounted yet, and for scheduling event replaying.
// Conceptually this is similar to Placement in that a new subtree is
// inserted into the React tree here. It just happens to not need DOM
// mutations because it already exists.
node.flags=node.flags&~Placement|Hydrating;node=node.sibling;}}else {// Otherwise reset hydration state in case we aborted and resumed another
// root.
reconcileChildren(current,workInProgress,nextChildren,renderLanes);resetHydrationState();}return workInProgress.child;}function updateHostComponent(current,workInProgress,renderLanes){pushHostContext(workInProgress);if(current===null){tryToClaimNextHydratableInstance(workInProgress);}var type=workInProgress.type;var nextProps=workInProgress.pendingProps;var prevProps=current!==null?current.memoizedProps:null;var nextChildren=nextProps.children;var isDirectTextChild=shouldSetTextContent(type,nextProps);if(isDirectTextChild){// We special case a direct text child of a host node. This is a common
// case. We won't handle it as a reified child. We will instead handle
// this in the host environment that also has access to this prop. That
// avoids allocating another HostText fiber and traversing it.
nextChildren=null;}else if(prevProps!==null&&shouldSetTextContent(type,prevProps)){// If we're switching from a direct text child to a normal child, or to
// empty, we need to schedule the text content to be reset.
workInProgress.flags|=ContentReset;}markRef(current,workInProgress);reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateHostText(current,workInProgress){if(current===null){tryToClaimNextHydratableInstance(workInProgress);}// Nothing to do here. This is terminal. We'll do the completion step
// immediately after.
return null;}function mountLazyComponent(_current,workInProgress,elementType,updateLanes,renderLanes){if(_current!==null){// A lazy component only mounts if it suspended inside a non-
// concurrent tree, in an inconsistent state. We want to treat it like
// a new mount, even though an empty version of it already committed.
// Disconnect the alternate pointers.
_current.alternate=null;workInProgress.alternate=null;// Since this is conceptually a new fiber, schedule a Placement effect
workInProgress.flags|=Placement;}var props=workInProgress.pendingProps;var lazyComponent=elementType;var payload=lazyComponent._payload;var init=lazyComponent._init;var Component=init(payload);// Store the unwrapped component in the type.
workInProgress.type=Component;var resolvedTag=workInProgress.tag=resolveLazyComponentTag(Component);var resolvedProps=resolveDefaultProps(Component,props);var child;switch(resolvedTag){case FunctionComponent:{{validateFunctionComponentInDev(workInProgress,Component);workInProgress.type=Component=resolveFunctionForHotReloading(Component);}child=updateFunctionComponent(null,workInProgress,Component,resolvedProps,renderLanes);return child;}case ClassComponent:{{workInProgress.type=Component=resolveClassForHotReloading(Component);}child=updateClassComponent(null,workInProgress,Component,resolvedProps,renderLanes);return child;}case ForwardRef:{{workInProgress.type=Component=resolveForwardRefForHotReloading(Component);}child=updateForwardRef(null,workInProgress,Component,resolvedProps,renderLanes);return child;}case MemoComponent:{{if(workInProgress.type!==workInProgress.elementType){var outerPropTypes=Component.propTypes;if(outerPropTypes){checkPropTypes(outerPropTypes,resolvedProps,// Resolved for outer only
'prop',getComponentName(Component));}}}child=updateMemoComponent(null,workInProgress,Component,resolveDefaultProps(Component.type,resolvedProps),// The inner type can have defaults too
updateLanes,renderLanes);return child;}}var hint='';{if(Component!==null&&typeof Component==='object'&&Component.$$typeof===REACT_LAZY_TYPE){hint=' Did you wrap a component in React.lazy() more than once?';}}// This message intentionally doesn't mention ForwardRef or MemoComponent
// because the fact that it's a separate type of work is an
// implementation detail.
{{throw Error("Element type is invalid. Received a promise that resolves to: "+Component+". Lazy element type must resolve to a class or function."+hint);}}}function mountIncompleteClassComponent(_current,workInProgress,Component,nextProps,renderLanes){if(_current!==null){// An incomplete component only mounts if it suspended inside a non-
// concurrent tree, in an inconsistent state. We want to treat it like
// a new mount, even though an empty version of it already committed.
// Disconnect the alternate pointers.
_current.alternate=null;workInProgress.alternate=null;// Since this is conceptually a new fiber, schedule a Placement effect
workInProgress.flags|=Placement;}// Promote the fiber to a class and try rendering again.
workInProgress.tag=ClassComponent;// The rest of this function is a fork of `updateClassComponent`
// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext;if(isContextProvider(Component)){hasContext=true;pushContextProvider(workInProgress);}else {hasContext=false;}prepareToReadContext(workInProgress,renderLanes);constructClassInstance(workInProgress,Component,nextProps);mountClassInstance(workInProgress,Component,nextProps,renderLanes);return finishClassComponent(null,workInProgress,Component,true,hasContext,renderLanes);}function mountIndeterminateComponent(_current,workInProgress,Component,renderLanes){if(_current!==null){// An indeterminate component only mounts if it suspended inside a non-
// concurrent tree, in an inconsistent state. We want to treat it like
// a new mount, even though an empty version of it already committed.
// Disconnect the alternate pointers.
_current.alternate=null;workInProgress.alternate=null;// Since this is conceptually a new fiber, schedule a Placement effect
workInProgress.flags|=Placement;}var props=workInProgress.pendingProps;var context;{var unmaskedContext=getUnmaskedContext(workInProgress,Component,false);context=getMaskedContext(workInProgress,unmaskedContext);}prepareToReadContext(workInProgress,renderLanes);var value;{if(Component.prototype&&typeof Component.prototype.render==='function'){var componentName=getComponentName(Component)||'Unknown';if(!didWarnAboutBadClass[componentName]){error("The <%s /> component appears to have a render method, but doesn't extend React.Component. "+'This is likely to cause errors. Change %s to extend React.Component instead.',componentName,componentName);didWarnAboutBadClass[componentName]=true;}}if(workInProgress.mode&StrictMode){ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress,null);}setIsRendering(true);ReactCurrentOwner$1.current=workInProgress;value=renderWithHooks(null,workInProgress,Component,props,context,renderLanes);setIsRendering(false);}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;{// Support for module components is deprecated and is removed behind a flag.
// Whether or not it would crash later, we want to show a good message in DEV first.
if(typeof value==='object'&&value!==null&&typeof value.render==='function'&&value.$$typeof===undefined){var _componentName=getComponentName(Component)||'Unknown';if(!didWarnAboutModulePatternComponent[_componentName]){error('The <%s /> component appears to be a function component that returns a class instance. '+'Change %s to a class that extends React.Component instead. '+"If you can't use a class try assigning the prototype on the function as a workaround. "+"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it "+'cannot be called with `new` by React.',_componentName,_componentName,_componentName);didWarnAboutModulePatternComponent[_componentName]=true;}}}if(// Run these checks in production only if the flag is off.
// Eventually we'll delete this branch altogether.
typeof value==='object'&&value!==null&&typeof value.render==='function'&&value.$$typeof===undefined){{var _componentName2=getComponentName(Component)||'Unknown';if(!didWarnAboutModulePatternComponent[_componentName2]){error('The <%s /> component appears to be a function component that returns a class instance. '+'Change %s to a class that extends React.Component instead. '+"If you can't use a class try assigning the prototype on the function as a workaround. "+"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it "+'cannot be called with `new` by React.',_componentName2,_componentName2,_componentName2);didWarnAboutModulePatternComponent[_componentName2]=true;}}// Proceed under the assumption that this is a class instance
workInProgress.tag=ClassComponent;// Throw out any hooks that were used.
workInProgress.memoizedState=null;workInProgress.updateQueue=null;// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext=false;if(isContextProvider(Component)){hasContext=true;pushContextProvider(workInProgress);}else {hasContext=false;}workInProgress.memoizedState=value.state!==null&&value.state!==undefined?value.state:null;initializeUpdateQueue(workInProgress);var getDerivedStateFromProps=Component.getDerivedStateFromProps;if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,Component,getDerivedStateFromProps,props);}adoptClassInstance(workInProgress,value);mountClassInstance(workInProgress,Component,props,renderLanes);return finishClassComponent(null,workInProgress,Component,true,hasContext,renderLanes);}else {// Proceed under the assumption that this is a function component
workInProgress.tag=FunctionComponent;{if(workInProgress.mode&StrictMode){disableLogs();try{value=renderWithHooks(null,workInProgress,Component,props,context,renderLanes);}finally{reenableLogs();}}}reconcileChildren(null,workInProgress,value,renderLanes);{validateFunctionComponentInDev(workInProgress,Component);}return workInProgress.child;}}function validateFunctionComponentInDev(workInProgress,Component){{if(Component){if(Component.childContextTypes){error('%s(...): childContextTypes cannot be defined on a function component.',Component.displayName||Component.name||'Component');}}if(workInProgress.ref!==null){var info='';var ownerName=getCurrentFiberOwnerNameInDevOrNull();if(ownerName){info+='\n\nCheck the render method of `'+ownerName+'`.';}var warningKey=ownerName||workInProgress._debugID||'';var debugSource=workInProgress._debugSource;if(debugSource){warningKey=debugSource.fileName+':'+debugSource.lineNumber;}if(!didWarnAboutFunctionRefs[warningKey]){didWarnAboutFunctionRefs[warningKey]=true;error('Function components cannot be given refs. '+'Attempts to access this ref will fail. '+'Did you mean to use React.forwardRef()?%s',info);}}if(typeof Component.getDerivedStateFromProps==='function'){var _componentName3=getComponentName(Component)||'Unknown';if(!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]){error('%s: Function components do not support getDerivedStateFromProps.',_componentName3);didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]=true;}}if(typeof Component.contextType==='object'&&Component.contextType!==null){var _componentName4=getComponentName(Component)||'Unknown';if(!didWarnAboutContextTypeOnFunctionComponent[_componentName4]){error('%s: Function components do not support contextType.',_componentName4);didWarnAboutContextTypeOnFunctionComponent[_componentName4]=true;}}}}var SUSPENDED_MARKER={dehydrated:null,retryLane:NoLane};function mountSuspenseOffscreenState(renderLanes){return {baseLanes:renderLanes};}function updateSuspenseOffscreenState(prevOffscreenState,renderLanes){return {baseLanes:mergeLanes(prevOffscreenState.baseLanes,renderLanes)};}// TODO: Probably should inline this back
function shouldRemainOnFallback(suspenseContext,current,workInProgress,renderLanes){// If we're already showing a fallback, there are cases where we need to
// remain on that fallback regardless of whether the content has resolved.
// For example, SuspenseList coordinates when nested content appears.
if(current!==null){var suspenseState=current.memoizedState;if(suspenseState===null){// Currently showing content. Don't hide it, even if ForceSuspenseFallack
// is true. More precise name might be "ForceRemainSuspenseFallback".
// Note: This is a factoring smell. Can't remain on a fallback if there's
// no fallback to remain on.
return false;}}// Not currently showing content. Consult the Suspense context.
return hasSuspenseContext(suspenseContext,ForceSuspenseFallback);}function getRemainingWorkInPrimaryTree(current,renderLanes){// TODO: Should not remove render lanes that were pinged during this render
return removeLanes(current.childLanes,renderLanes);}function updateSuspenseComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps;// This is used by DevTools to force a boundary to suspend.
{if(shouldSuspend(workInProgress)){workInProgress.flags|=DidCapture;}}var suspenseContext=suspenseStackCursor.current;var showFallback=false;var didSuspend=(workInProgress.flags&DidCapture)!==NoFlags;if(didSuspend||shouldRemainOnFallback(suspenseContext,current)){// Something in this boundary's subtree already suspended. Switch to
// rendering the fallback children.
showFallback=true;workInProgress.flags&=~DidCapture;}else {// Attempting the main content
if(current===null||current.memoizedState!==null){// This is a new mount or this boundary is already showing a fallback state.
// Mark this subtree context as having at least one invisible parent that could
// handle the fallback state.
// Boundaries without fallbacks or should be avoided are not considered since
// they cannot handle preferred fallback states.
if(nextProps.fallback!==undefined&&nextProps.unstable_avoidThisFallback!==true){suspenseContext=addSubtreeSuspenseContext(suspenseContext,InvisibleParentSuspenseContext);}}}suspenseContext=setDefaultShallowSuspenseContext(suspenseContext);pushSuspenseContext(workInProgress,suspenseContext);// OK, the next part is confusing. We're about to reconcile the Suspense
// boundary's children. This involves some custom reconcilation logic. Two
// main reasons this is so complicated.
//
// First, Legacy Mode has different semantics for backwards compatibility. The
// primary tree will commit in an inconsistent state, so when we do the
// second pass to render the fallback, we do some exceedingly, uh, clever
// hacks to make that not totally break. Like transferring effects and
// deletions from hidden tree. In Concurrent Mode, it's much simpler,
// because we bailout on the primary tree completely and leave it in its old
// state, no effects. Same as what we do for Offscreen (except that
// Offscreen doesn't have the first render pass).
//
// Second is hydration. During hydration, the Suspense fiber has a slightly
// different layout, where the child points to a dehydrated fragment, which
// contains the DOM rendered by the server.
//
// Third, even if you set all that aside, Suspense is like error boundaries in
// that we first we try to render one tree, and if that fails, we render again
// and switch to a different tree. Like a try/catch block. So we have to track
// which branch we're currently rendering. Ideally we would model this using
// a stack.
if(current===null){// Initial mount
// If we're currently hydrating, try to hydrate this boundary.
// But only if this has a fallback.
if(nextProps.fallback!==undefined){tryToClaimNextHydratableInstance(workInProgress);// This could've been a dehydrated suspense component.
}var nextPrimaryChildren=nextProps.children;var nextFallbackChildren=nextProps.fallback;if(showFallback){var fallbackFragment=mountSuspenseFallbackChildren(workInProgress,nextPrimaryChildren,nextFallbackChildren,renderLanes);var primaryChildFragment=workInProgress.child;primaryChildFragment.memoizedState=mountSuspenseOffscreenState(renderLanes);workInProgress.memoizedState=SUSPENDED_MARKER;return fallbackFragment;}else if(typeof nextProps.unstable_expectedLoadTime==='number'){// This is a CPU-bound tree. Skip this tree and show a placeholder to
// unblock the surrounding content. Then immediately retry after the
// initial commit.
var _fallbackFragment=mountSuspenseFallbackChildren(workInProgress,nextPrimaryChildren,nextFallbackChildren,renderLanes);var _primaryChildFragment=workInProgress.child;_primaryChildFragment.memoizedState=mountSuspenseOffscreenState(renderLanes);workInProgress.memoizedState=SUSPENDED_MARKER;// Since nothing actually suspended, there will nothing to ping this to
// get it started back up to attempt the next item. While in terms of
// priority this work has the same priority as this current render, it's
// not part of the same transition once the transition has committed. If
// it's sync, we still want to yield so that it can be painted.
// Conceptually, this is really the same as pinging. We can use any
// RetryLane even if it's the one currently rendering since we're leaving
// it behind on this node.
workInProgress.lanes=SomeRetryLane;{markSpawnedWork(SomeRetryLane);}return _fallbackFragment;}else {return mountSuspensePrimaryChildren(workInProgress,nextPrimaryChildren,renderLanes);}}else {// This is an update.
// If the current fiber has a SuspenseState, that means it's already showing
// a fallback.
var prevState=current.memoizedState;if(prevState!==null){if(showFallback){var _nextFallbackChildren2=nextProps.fallback;var _nextPrimaryChildren2=nextProps.children;var _fallbackChildFragment=updateSuspenseFallbackChildren(current,workInProgress,_nextPrimaryChildren2,_nextFallbackChildren2,renderLanes);var _primaryChildFragment3=workInProgress.child;var prevOffscreenState=current.child.memoizedState;_primaryChildFragment3.memoizedState=prevOffscreenState===null?mountSuspenseOffscreenState(renderLanes):updateSuspenseOffscreenState(prevOffscreenState,renderLanes);_primaryChildFragment3.childLanes=getRemainingWorkInPrimaryTree(current,renderLanes);workInProgress.memoizedState=SUSPENDED_MARKER;return _fallbackChildFragment;}else {var _nextPrimaryChildren3=nextProps.children;var _primaryChildFragment4=updateSuspensePrimaryChildren(current,workInProgress,_nextPrimaryChildren3,renderLanes);workInProgress.memoizedState=null;return _primaryChildFragment4;}}else {// The current tree is not already showing a fallback.
if(showFallback){// Timed out.
var _nextFallbackChildren3=nextProps.fallback;var _nextPrimaryChildren4=nextProps.children;var _fallbackChildFragment2=updateSuspenseFallbackChildren(current,workInProgress,_nextPrimaryChildren4,_nextFallbackChildren3,renderLanes);var _primaryChildFragment5=workInProgress.child;var _prevOffscreenState=current.child.memoizedState;_primaryChildFragment5.memoizedState=_prevOffscreenState===null?mountSuspenseOffscreenState(renderLanes):updateSuspenseOffscreenState(_prevOffscreenState,renderLanes);_primaryChildFragment5.childLanes=getRemainingWorkInPrimaryTree(current,renderLanes);// Skip the primary children, and continue working on the
// fallback children.
workInProgress.memoizedState=SUSPENDED_MARKER;return _fallbackChildFragment2;}else {// Still haven't timed out. Continue rendering the children, like we
// normally do.
var _nextPrimaryChildren5=nextProps.children;var _primaryChildFragment6=updateSuspensePrimaryChildren(current,workInProgress,_nextPrimaryChildren5,renderLanes);workInProgress.memoizedState=null;return _primaryChildFragment6;}}}}function mountSuspensePrimaryChildren(workInProgress,primaryChildren,renderLanes){var mode=workInProgress.mode;var primaryChildProps={mode:'visible',children:primaryChildren};var primaryChildFragment=createFiberFromOffscreen(primaryChildProps,mode,renderLanes,null);primaryChildFragment.return=workInProgress;workInProgress.child=primaryChildFragment;return primaryChildFragment;}function mountSuspenseFallbackChildren(workInProgress,primaryChildren,fallbackChildren,renderLanes){var mode=workInProgress.mode;var progressedPrimaryFragment=workInProgress.child;var primaryChildProps={mode:'hidden',children:primaryChildren};var primaryChildFragment;var fallbackChildFragment;if((mode&BlockingMode)===NoMode&&progressedPrimaryFragment!==null){// In legacy mode, we commit the primary tree as if it successfully
// completed, even though it's in an inconsistent state.
primaryChildFragment=progressedPrimaryFragment;primaryChildFragment.childLanes=NoLanes;primaryChildFragment.pendingProps=primaryChildProps;if(workInProgress.mode&ProfileMode){// Reset the durations from the first pass so they aren't included in the
// final amounts. This seems counterintuitive, since we're intentionally
// not measuring part of the render phase, but this makes it match what we
// do in Concurrent Mode.
primaryChildFragment.actualDuration=0;primaryChildFragment.actualStartTime=-1;primaryChildFragment.selfBaseDuration=0;primaryChildFragment.treeBaseDuration=0;}fallbackChildFragment=createFiberFromFragment(fallbackChildren,mode,renderLanes,null);}else {primaryChildFragment=createFiberFromOffscreen(primaryChildProps,mode,NoLanes,null);fallbackChildFragment=createFiberFromFragment(fallbackChildren,mode,renderLanes,null);}primaryChildFragment.return=workInProgress;fallbackChildFragment.return=workInProgress;primaryChildFragment.sibling=fallbackChildFragment;workInProgress.child=primaryChildFragment;return fallbackChildFragment;}function createWorkInProgressOffscreenFiber(current,offscreenProps){// The props argument to `createWorkInProgress` is `any` typed, so we use this
// wrapper function to constrain it.
return createWorkInProgress(current,offscreenProps);}function updateSuspensePrimaryChildren(current,workInProgress,primaryChildren,renderLanes){var currentPrimaryChildFragment=current.child;var currentFallbackChildFragment=currentPrimaryChildFragment.sibling;var primaryChildFragment=createWorkInProgressOffscreenFiber(currentPrimaryChildFragment,{mode:'visible',children:primaryChildren});if((workInProgress.mode&BlockingMode)===NoMode){primaryChildFragment.lanes=renderLanes;}primaryChildFragment.return=workInProgress;primaryChildFragment.sibling=null;if(currentFallbackChildFragment!==null){// Delete the fallback child fragment
currentFallbackChildFragment.nextEffect=null;currentFallbackChildFragment.flags=Deletion;workInProgress.firstEffect=workInProgress.lastEffect=currentFallbackChildFragment;}workInProgress.child=primaryChildFragment;return primaryChildFragment;}function updateSuspenseFallbackChildren(current,workInProgress,primaryChildren,fallbackChildren,renderLanes){var mode=workInProgress.mode;var currentPrimaryChildFragment=current.child;var currentFallbackChildFragment=currentPrimaryChildFragment.sibling;var primaryChildProps={mode:'hidden',children:primaryChildren};var primaryChildFragment;if(// In legacy mode, we commit the primary tree as if it successfully
// completed, even though it's in an inconsistent state.
(mode&BlockingMode)===NoMode&&// Make sure we're on the second pass, i.e. the primary child fragment was
// already cloned. In legacy mode, the only case where this isn't true is
// when DevTools forces us to display a fallback; we skip the first render
// pass entirely and go straight to rendering the fallback. (In Concurrent
// Mode, SuspenseList can also trigger this scenario, but this is a legacy-
// only codepath.)
workInProgress.child!==currentPrimaryChildFragment){var progressedPrimaryFragment=workInProgress.child;primaryChildFragment=progressedPrimaryFragment;primaryChildFragment.childLanes=NoLanes;primaryChildFragment.pendingProps=primaryChildProps;if(workInProgress.mode&ProfileMode){// Reset the durations from the first pass so they aren't included in the
// final amounts. This seems counterintuitive, since we're intentionally
// not measuring part of the render phase, but this makes it match what we
// do in Concurrent Mode.
primaryChildFragment.actualDuration=0;primaryChildFragment.actualStartTime=-1;primaryChildFragment.selfBaseDuration=currentPrimaryChildFragment.selfBaseDuration;primaryChildFragment.treeBaseDuration=currentPrimaryChildFragment.treeBaseDuration;}// The fallback fiber was added as a deletion effect during the first pass.
// However, since we're going to remain on the fallback, we no longer want
// to delete it. So we need to remove it from the list. Deletions are stored
// on the same list as effects. We want to keep the effects from the primary
// tree. So we copy the primary child fragment's effect list, which does not
// include the fallback deletion effect.
var progressedLastEffect=primaryChildFragment.lastEffect;if(progressedLastEffect!==null){workInProgress.firstEffect=primaryChildFragment.firstEffect;workInProgress.lastEffect=progressedLastEffect;progressedLastEffect.nextEffect=null;}else {// TODO: Reset this somewhere else? Lol legacy mode is so weird.
workInProgress.firstEffect=workInProgress.lastEffect=null;}}else {primaryChildFragment=createWorkInProgressOffscreenFiber(currentPrimaryChildFragment,primaryChildProps);}var fallbackChildFragment;if(currentFallbackChildFragment!==null){fallbackChildFragment=createWorkInProgress(currentFallbackChildFragment,fallbackChildren);}else {fallbackChildFragment=createFiberFromFragment(fallbackChildren,mode,renderLanes,null);// Needs a placement effect because the parent (the Suspense boundary) already
// mounted but this is a new fiber.
fallbackChildFragment.flags|=Placement;}fallbackChildFragment.return=workInProgress;primaryChildFragment.return=workInProgress;primaryChildFragment.sibling=fallbackChildFragment;workInProgress.child=primaryChildFragment;return fallbackChildFragment;}function scheduleWorkOnFiber(fiber,renderLanes){fiber.lanes=mergeLanes(fiber.lanes,renderLanes);var alternate=fiber.alternate;if(alternate!==null){alternate.lanes=mergeLanes(alternate.lanes,renderLanes);}scheduleWorkOnParentPath(fiber.return,renderLanes);}function propagateSuspenseContextChange(workInProgress,firstChild,renderLanes){// Mark any Suspense boundaries with fallbacks as having work to do.
// If they were previously forced into fallbacks, they may now be able
// to unblock.
var node=firstChild;while(node!==null){if(node.tag===SuspenseComponent){var state=node.memoizedState;if(state!==null){scheduleWorkOnFiber(node,renderLanes);}}else if(node.tag===SuspenseListComponent){// If the tail is hidden there might not be an Suspense boundaries
// to schedule work on. In this case we have to schedule it on the
// list itself.
// We don't have to traverse to the children of the list since
// the list will propagate the change when it rerenders.
scheduleWorkOnFiber(node,renderLanes);}else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===workInProgress){return;}while(node.sibling===null){if(node.return===null||node.return===workInProgress){return;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}}function findLastContentRow(firstChild){// This is going to find the last row among these children that is already
// showing content on the screen, as opposed to being in fallback state or
// new. If a row has multiple Suspense boundaries, any of them being in the
// fallback state, counts as the whole row being in a fallback state.
// Note that the "rows" will be workInProgress, but any nested children
// will still be current since we haven't rendered them yet. The mounted
// order may not be the same as the new order. We use the new order.
var row=firstChild;var lastContentRow=null;while(row!==null){var currentRow=row.alternate;// New rows can't be content rows.
if(currentRow!==null&&findFirstSuspended(currentRow)===null){lastContentRow=row;}row=row.sibling;}return lastContentRow;}function validateRevealOrder(revealOrder){{if(revealOrder!==undefined&&revealOrder!=='forwards'&&revealOrder!=='backwards'&&revealOrder!=='together'&&!didWarnAboutRevealOrder[revealOrder]){didWarnAboutRevealOrder[revealOrder]=true;if(typeof revealOrder==='string'){switch(revealOrder.toLowerCase()){case'together':case'forwards':case'backwards':{error('"%s" is not a valid value for revealOrder on <SuspenseList />. '+'Use lowercase "%s" instead.',revealOrder,revealOrder.toLowerCase());break;}case'forward':case'backward':{error('"%s" is not a valid value for revealOrder on <SuspenseList />. '+'React uses the -s suffix in the spelling. Use "%ss" instead.',revealOrder,revealOrder.toLowerCase());break;}default:error('"%s" is not a supported revealOrder on <SuspenseList />. '+'Did you mean "together", "forwards" or "backwards"?',revealOrder);break;}}else {error('%s is not a supported value for revealOrder on <SuspenseList />. '+'Did you mean "together", "forwards" or "backwards"?',revealOrder);}}}}function validateTailOptions(tailMode,revealOrder){{if(tailMode!==undefined&&!didWarnAboutTailOptions[tailMode]){if(tailMode!=='collapsed'&&tailMode!=='hidden'){didWarnAboutTailOptions[tailMode]=true;error('"%s" is not a supported value for tail on <SuspenseList />. '+'Did you mean "collapsed" or "hidden"?',tailMode);}else if(revealOrder!=='forwards'&&revealOrder!=='backwards'){didWarnAboutTailOptions[tailMode]=true;error('<SuspenseList tail="%s" /> is only valid if revealOrder is '+'"forwards" or "backwards". '+'Did you mean to specify revealOrder="forwards"?',tailMode);}}}}function validateSuspenseListNestedChild(childSlot,index){{var isArray=Array.isArray(childSlot);var isIterable=!isArray&&typeof getIteratorFn(childSlot)==='function';if(isArray||isIterable){var type=isArray?'array':'iterable';error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in '+'an additional SuspenseList to configure its revealOrder: '+'<SuspenseList revealOrder=...> ... '+'<SuspenseList revealOrder=...>{%s}</SuspenseList> ... '+'</SuspenseList>',type,index,type);return false;}}return true;}function validateSuspenseListChildren(children,revealOrder){{if((revealOrder==='forwards'||revealOrder==='backwards')&&children!==undefined&&children!==null&&children!==false){if(Array.isArray(children)){for(var i=0;i<children.length;i++){if(!validateSuspenseListNestedChild(children[i],i)){return;}}}else {var iteratorFn=getIteratorFn(children);if(typeof iteratorFn==='function'){var childrenIterator=iteratorFn.call(children);if(childrenIterator){var step=childrenIterator.next();var _i=0;for(;!step.done;step=childrenIterator.next()){if(!validateSuspenseListNestedChild(step.value,_i)){return;}_i++;}}}else {error('A single row was passed to a <SuspenseList revealOrder="%s" />. '+'This is not useful since it needs multiple rows. '+'Did you mean to pass multiple children or an array?',revealOrder);}}}}}function initSuspenseListRenderState(workInProgress,isBackwards,tail,lastContentRow,tailMode,lastEffectBeforeRendering){var renderState=workInProgress.memoizedState;if(renderState===null){workInProgress.memoizedState={isBackwards:isBackwards,rendering:null,renderingStartTime:0,last:lastContentRow,tail:tail,tailMode:tailMode,lastEffect:lastEffectBeforeRendering};}else {// We can reuse the existing object from previous renders.
renderState.isBackwards=isBackwards;renderState.rendering=null;renderState.renderingStartTime=0;renderState.last=lastContentRow;renderState.tail=tail;renderState.tailMode=tailMode;renderState.lastEffect=lastEffectBeforeRendering;}}// This can end up rendering this component multiple passes.
// The first pass splits the children fibers into two sets. A head and tail.
// We first render the head. If anything is in fallback state, we do another
// pass through beginWork to rerender all children (including the tail) with
// the force suspend context. If the first render didn't have anything in
// in fallback state. Then we render each row in the tail one-by-one.
// That happens in the completeWork phase without going back to beginWork.
function updateSuspenseListComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps;var revealOrder=nextProps.revealOrder;var tailMode=nextProps.tail;var newChildren=nextProps.children;validateRevealOrder(revealOrder);validateTailOptions(tailMode,revealOrder);validateSuspenseListChildren(newChildren,revealOrder);reconcileChildren(current,workInProgress,newChildren,renderLanes);var suspenseContext=suspenseStackCursor.current;var shouldForceFallback=hasSuspenseContext(suspenseContext,ForceSuspenseFallback);if(shouldForceFallback){suspenseContext=setShallowSuspenseContext(suspenseContext,ForceSuspenseFallback);workInProgress.flags|=DidCapture;}else {var didSuspendBefore=current!==null&&(current.flags&DidCapture)!==NoFlags;if(didSuspendBefore){// If we previously forced a fallback, we need to schedule work
// on any nested boundaries to let them know to try to render
// again. This is the same as context updating.
propagateSuspenseContextChange(workInProgress,workInProgress.child,renderLanes);}suspenseContext=setDefaultShallowSuspenseContext(suspenseContext);}pushSuspenseContext(workInProgress,suspenseContext);if((workInProgress.mode&BlockingMode)===NoMode){// In legacy mode, SuspenseList doesn't work so we just
// use make it a noop by treating it as the default revealOrder.
workInProgress.memoizedState=null;}else {switch(revealOrder){case'forwards':{var lastContentRow=findLastContentRow(workInProgress.child);var tail;if(lastContentRow===null){// The whole list is part of the tail.
// TODO: We could fast path by just rendering the tail now.
tail=workInProgress.child;workInProgress.child=null;}else {// Disconnect the tail rows after the content row.
// We're going to render them separately later.
tail=lastContentRow.sibling;lastContentRow.sibling=null;}initSuspenseListRenderState(workInProgress,false,// isBackwards
tail,lastContentRow,tailMode,workInProgress.lastEffect);break;}case'backwards':{// We're going to find the first row that has existing content.
// At the same time we're going to reverse the list of everything
// we pass in the meantime. That's going to be our tail in reverse
// order.
var _tail=null;var row=workInProgress.child;workInProgress.child=null;while(row!==null){var currentRow=row.alternate;// New rows can't be content rows.
if(currentRow!==null&&findFirstSuspended(currentRow)===null){// This is the beginning of the main content.
workInProgress.child=row;break;}var nextRow=row.sibling;row.sibling=_tail;_tail=row;row=nextRow;}// TODO: If workInProgress.child is null, we can continue on the tail immediately.
initSuspenseListRenderState(workInProgress,true,// isBackwards
_tail,null,// last
tailMode,workInProgress.lastEffect);break;}case'together':{initSuspenseListRenderState(workInProgress,false,// isBackwards
null,// tail
null,// last
undefined,workInProgress.lastEffect);break;}default:{// The default reveal order is the same as not having
// a boundary.
workInProgress.memoizedState=null;}}}return workInProgress.child;}function updatePortalComponent(current,workInProgress,renderLanes){pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo);var nextChildren=workInProgress.pendingProps;if(current===null){// Portals are special because we don't append the children during mount
// but at commit. Therefore we need to track insertions which the normal
// flow doesn't do during mount. This doesn't happen at the root because
// the root always starts with a "current" with a null child.
// TODO: Consider unifying this with how the root works.
workInProgress.child=reconcileChildFibers(workInProgress,null,nextChildren,renderLanes);}else {reconcileChildren(current,workInProgress,nextChildren,renderLanes);}return workInProgress.child;}var hasWarnedAboutUsingNoValuePropOnContextProvider=false;function updateContextProvider(current,workInProgress,renderLanes){var providerType=workInProgress.type;var context=providerType._context;var newProps=workInProgress.pendingProps;var oldProps=workInProgress.memoizedProps;var newValue=newProps.value;{if(!('value'in newProps)){if(!hasWarnedAboutUsingNoValuePropOnContextProvider){hasWarnedAboutUsingNoValuePropOnContextProvider=true;error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');}}var providerPropTypes=workInProgress.type.propTypes;if(providerPropTypes){checkPropTypes(providerPropTypes,newProps,'prop','Context.Provider');}}pushProvider(workInProgress,newValue);if(oldProps!==null){var oldValue=oldProps.value;var changedBits=calculateChangedBits(context,newValue,oldValue);if(changedBits===0){// No change. Bailout early if children are the same.
if(oldProps.children===newProps.children&&!hasContextChanged()){return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}}else {// The context value changed. Search for matching consumers and schedule
// them to update.
propagateContextChange(workInProgress,context,changedBits,renderLanes);}}var newChildren=newProps.children;reconcileChildren(current,workInProgress,newChildren,renderLanes);return workInProgress.child;}var hasWarnedAboutUsingContextAsConsumer=false;function updateContextConsumer(current,workInProgress,renderLanes){var context=workInProgress.type;// The logic below for Context differs depending on PROD or DEV mode. In
// DEV mode, we create a separate object for Context.Consumer that acts
// like a proxy to Context. This proxy object adds unnecessary code in PROD
// so we use the old behaviour (Context.Consumer references Context) to
// reduce size and overhead. The separate object references context via
// a property called "_context", which also gives us the ability to check
// in DEV mode if this property exists or not and warn if it does not.
{if(context._context===undefined){// This may be because it's a Context (rather than a Consumer).
// Or it may be because it's older React where they're the same thing.
// We only want to warn if we're sure it's a new React.
if(context!==context.Consumer){if(!hasWarnedAboutUsingContextAsConsumer){hasWarnedAboutUsingContextAsConsumer=true;error('Rendering <Context> directly is not supported and will be removed in '+'a future major release. Did you mean to render <Context.Consumer> instead?');}}}else {context=context._context;}}var newProps=workInProgress.pendingProps;var render=newProps.children;{if(typeof render!=='function'){error('A context consumer was rendered with multiple children, or a child '+"that isn't a function. A context consumer expects a single child "+'that is a function. If you did pass a function, make sure there '+'is no trailing or leading whitespace around it.');}}prepareToReadContext(workInProgress,renderLanes);var newValue=readContext(context,newProps.unstable_observedBits);var newChildren;{ReactCurrentOwner$1.current=workInProgress;setIsRendering(true);newChildren=render(newValue);setIsRendering(false);}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;reconcileChildren(current,workInProgress,newChildren,renderLanes);return workInProgress.child;}function markWorkInProgressReceivedUpdate(){didReceiveUpdate=true;}function bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes){if(current!==null){// Reuse previous dependencies
workInProgress.dependencies=current.dependencies;}{// Don't update "base" render times for bailouts.
stopProfilerTimerIfRunning();}markSkippedUpdateLanes(workInProgress.lanes);// Check if the children have any pending work.
if(!includesSomeLane(renderLanes,workInProgress.childLanes)){// The children don't have any work either. We can skip them.
// TODO: Once we add back resuming, we should check if the children are
// a work-in-progress set. If so, we need to transfer their effects.
return null;}else {// This fiber doesn't have work, but its subtree does. Clone the child
// fibers and continue.
cloneChildFibers(current,workInProgress);return workInProgress.child;}}function remountFiber(current,oldWorkInProgress,newWorkInProgress){{var returnFiber=oldWorkInProgress.return;if(returnFiber===null){throw new Error('Cannot swap the root fiber.');}// Disconnect from the old current.
// It will get deleted.
current.alternate=null;oldWorkInProgress.alternate=null;// Connect to the new tree.
newWorkInProgress.index=oldWorkInProgress.index;newWorkInProgress.sibling=oldWorkInProgress.sibling;newWorkInProgress.return=oldWorkInProgress.return;newWorkInProgress.ref=oldWorkInProgress.ref;// Replace the child/sibling pointers above it.
if(oldWorkInProgress===returnFiber.child){returnFiber.child=newWorkInProgress;}else {var prevSibling=returnFiber.child;if(prevSibling===null){throw new Error('Expected parent to have a child.');}while(prevSibling.sibling!==oldWorkInProgress){prevSibling=prevSibling.sibling;if(prevSibling===null){throw new Error('Expected to find the previous sibling.');}}prevSibling.sibling=newWorkInProgress;}// Delete the old fiber and place the new one.
// Since the old fiber is disconnected, we have to schedule it manually.
var last=returnFiber.lastEffect;if(last!==null){last.nextEffect=current;returnFiber.lastEffect=current;}else {returnFiber.firstEffect=returnFiber.lastEffect=current;}current.nextEffect=null;current.flags=Deletion;newWorkInProgress.flags|=Placement;// Restart work from the new fiber.
return newWorkInProgress;}}function beginWork(current,workInProgress,renderLanes){var updateLanes=workInProgress.lanes;{if(workInProgress._debugNeedsRemount&&current!==null){// This will restart the begin phase with a new fiber.
return remountFiber(current,workInProgress,createFiberFromTypeAndProps(workInProgress.type,workInProgress.key,workInProgress.pendingProps,workInProgress._debugOwner||null,workInProgress.mode,workInProgress.lanes));}}if(current!==null){var oldProps=current.memoizedProps;var newProps=workInProgress.pendingProps;if(oldProps!==newProps||hasContextChanged()||// Force a re-render if the implementation changed due to hot reload:
workInProgress.type!==current.type){// If props or context changed, mark the fiber as having performed work.
// This may be unset if the props are determined to be equal later (memo).
didReceiveUpdate=true;}else if(!includesSomeLane(renderLanes,updateLanes)){didReceiveUpdate=false;// This fiber does not have any pending work. Bailout without entering
// the begin phase. There's still some bookkeeping we that needs to be done
// in this optimized path, mostly pushing stuff onto the stack.
switch(workInProgress.tag){case HostRoot:pushHostRootContext(workInProgress);resetHydrationState();break;case HostComponent:pushHostContext(workInProgress);break;case ClassComponent:{var Component=workInProgress.type;if(isContextProvider(Component)){pushContextProvider(workInProgress);}break;}case HostPortal:pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo);break;case ContextProvider:{var newValue=workInProgress.memoizedProps.value;pushProvider(workInProgress,newValue);break;}case Profiler:{// Profiler should only call onRender when one of its descendants actually rendered.
var hasChildWork=includesSomeLane(renderLanes,workInProgress.childLanes);if(hasChildWork){workInProgress.flags|=Update;}// Reset effect durations for the next eventual effect phase.
// These are reset during render to allow the DevTools commit hook a chance to read them,
var stateNode=workInProgress.stateNode;stateNode.effectDuration=0;stateNode.passiveEffectDuration=0;}break;case SuspenseComponent:{var state=workInProgress.memoizedState;if(state!==null){// whether to retry the primary children, or to skip over it and
// go straight to the fallback. Check the priority of the primary
// child fragment.
var primaryChildFragment=workInProgress.child;var primaryChildLanes=primaryChildFragment.childLanes;if(includesSomeLane(renderLanes,primaryChildLanes)){// The primary children have pending work. Use the normal path
// to attempt to render the primary children again.
return updateSuspenseComponent(current,workInProgress,renderLanes);}else {// The primary child fragment does not have pending work marked
// on it
pushSuspenseContext(workInProgress,setDefaultShallowSuspenseContext(suspenseStackCursor.current));// The primary children do not have pending work with sufficient
// priority. Bailout.
var child=bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);if(child!==null){// The fallback children have pending work. Skip over the
// primary children and work on the fallback.
return child.sibling;}else {return null;}}}else {pushSuspenseContext(workInProgress,setDefaultShallowSuspenseContext(suspenseStackCursor.current));}break;}case SuspenseListComponent:{var didSuspendBefore=(current.flags&DidCapture)!==NoFlags;var _hasChildWork=includesSomeLane(renderLanes,workInProgress.childLanes);if(didSuspendBefore){if(_hasChildWork){// If something was in fallback state last time, and we have all the
// same children then we're still in progressive loading state.
// Something might get unblocked by state updates or retries in the
// tree which will affect the tail. So we need to use the normal
// path to compute the correct tail.
return updateSuspenseListComponent(current,workInProgress,renderLanes);}// If none of the children had any work, that means that none of
// them got retried so they'll still be blocked in the same way
// as before. We can fast bail out.
workInProgress.flags|=DidCapture;}// If nothing suspended before and we're rendering the same children,
// then the tail doesn't matter. Anything new that suspends will work
// in the "together" mode, so we can continue from the state we had.
var renderState=workInProgress.memoizedState;if(renderState!==null){// Reset to the "together" mode in case we've started a different
// update in the past but didn't complete it.
renderState.rendering=null;renderState.tail=null;renderState.lastEffect=null;}pushSuspenseContext(workInProgress,suspenseStackCursor.current);if(_hasChildWork){break;}else {// If none of the children had any work, that means that none of
// them got retried so they'll still be blocked in the same way
// as before. We can fast bail out.
return null;}}case OffscreenComponent:case LegacyHiddenComponent:{// Need to check if the tree still needs to be deferred. This is
// almost identical to the logic used in the normal update path,
// so we'll just enter that. The only difference is we'll bail out
// at the next level instead of this one, because the child props
// have not changed. Which is fine.
// TODO: Probably should refactor `beginWork` to split the bailout
// path from the normal path. I'm tempted to do a labeled break here
// but I won't :)
workInProgress.lanes=NoLanes;return updateOffscreenComponent(current,workInProgress,renderLanes);}}return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}else {if((current.flags&ForceUpdateForLegacySuspense)!==NoFlags){// This is a special case that only exists for legacy mode.
// See https://github.com/facebook/react/pull/19216.
didReceiveUpdate=true;}else {// An update was scheduled on this fiber, but there are no new props
// nor legacy context. Set this to false. If an update queue or context
// consumer produces a changed value, it will set this to true. Otherwise,
// the component will assume the children have not changed and bail out.
didReceiveUpdate=false;}}}else {didReceiveUpdate=false;}// Before entering the begin phase, clear pending update priority.
// TODO: This assumes that we're about to evaluate the component and process
// the update queue. However, there's an exception: SimpleMemoComponent
// sometimes bails out later in the begin phase. This indicates that we should
// move this assignment out of the common path and into each branch.
workInProgress.lanes=NoLanes;switch(workInProgress.tag){case IndeterminateComponent:{return mountIndeterminateComponent(current,workInProgress,workInProgress.type,renderLanes);}case LazyComponent:{var elementType=workInProgress.elementType;return mountLazyComponent(current,workInProgress,elementType,updateLanes,renderLanes);}case FunctionComponent:{var _Component=workInProgress.type;var unresolvedProps=workInProgress.pendingProps;var resolvedProps=workInProgress.elementType===_Component?unresolvedProps:resolveDefaultProps(_Component,unresolvedProps);return updateFunctionComponent(current,workInProgress,_Component,resolvedProps,renderLanes);}case ClassComponent:{var _Component2=workInProgress.type;var _unresolvedProps=workInProgress.pendingProps;var _resolvedProps=workInProgress.elementType===_Component2?_unresolvedProps:resolveDefaultProps(_Component2,_unresolvedProps);return updateClassComponent(current,workInProgress,_Component2,_resolvedProps,renderLanes);}case HostRoot:return updateHostRoot(current,workInProgress,renderLanes);case HostComponent:return updateHostComponent(current,workInProgress,renderLanes);case HostText:return updateHostText(current,workInProgress);case SuspenseComponent:return updateSuspenseComponent(current,workInProgress,renderLanes);case HostPortal:return updatePortalComponent(current,workInProgress,renderLanes);case ForwardRef:{var type=workInProgress.type;var _unresolvedProps2=workInProgress.pendingProps;var _resolvedProps2=workInProgress.elementType===type?_unresolvedProps2:resolveDefaultProps(type,_unresolvedProps2);return updateForwardRef(current,workInProgress,type,_resolvedProps2,renderLanes);}case Fragment:return updateFragment(current,workInProgress,renderLanes);case Mode:return updateMode(current,workInProgress,renderLanes);case Profiler:return updateProfiler(current,workInProgress,renderLanes);case ContextProvider:return updateContextProvider(current,workInProgress,renderLanes);case ContextConsumer:return updateContextConsumer(current,workInProgress,renderLanes);case MemoComponent:{var _type2=workInProgress.type;var _unresolvedProps3=workInProgress.pendingProps;// Resolve outer props first, then resolve inner props.
var _resolvedProps3=resolveDefaultProps(_type2,_unresolvedProps3);{if(workInProgress.type!==workInProgress.elementType){var outerPropTypes=_type2.propTypes;if(outerPropTypes){checkPropTypes(outerPropTypes,_resolvedProps3,// Resolved for outer only
'prop',getComponentName(_type2));}}}_resolvedProps3=resolveDefaultProps(_type2.type,_resolvedProps3);return updateMemoComponent(current,workInProgress,_type2,_resolvedProps3,updateLanes,renderLanes);}case SimpleMemoComponent:{return updateSimpleMemoComponent(current,workInProgress,workInProgress.type,workInProgress.pendingProps,updateLanes,renderLanes);}case IncompleteClassComponent:{var _Component3=workInProgress.type;var _unresolvedProps4=workInProgress.pendingProps;var _resolvedProps4=workInProgress.elementType===_Component3?_unresolvedProps4:resolveDefaultProps(_Component3,_unresolvedProps4);return mountIncompleteClassComponent(current,workInProgress,_Component3,_resolvedProps4,renderLanes);}case SuspenseListComponent:{return updateSuspenseListComponent(current,workInProgress,renderLanes);}case FundamentalComponent:{break;}case ScopeComponent:{break;}case Block:{break;}case OffscreenComponent:{return updateOffscreenComponent(current,workInProgress,renderLanes);}case LegacyHiddenComponent:{return updateLegacyHiddenComponent(current,workInProgress,renderLanes);}}{{throw Error("Unknown unit of work tag ("+workInProgress.tag+"). This error is likely caused by a bug in React. Please file an issue.");}}}function markUpdate(workInProgress){// Tag the fiber with an update effect. This turns a Placement into
// a PlacementAndUpdate.
workInProgress.flags|=Update;}function markRef$1(workInProgress){workInProgress.flags|=Ref;}var appendAllChildren;var updateHostContainer;var updateHostComponent$1;var updateHostText$1;{// Mutation mode
appendAllChildren=function(parent,workInProgress,needsVisibilityToggle,isHidden){// We only have the top Fiber that was created but we need recurse down its
// children to find all the terminal nodes.
var node=workInProgress.child;while(node!==null){if(node.tag===HostComponent||node.tag===HostText){appendInitialChild(parent,node.stateNode);}else if(node.tag===HostPortal);else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===workInProgress){return;}while(node.sibling===null){if(node.return===null||node.return===workInProgress){return;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}};updateHostContainer=function(workInProgress){// Noop
};updateHostComponent$1=function(current,workInProgress,type,newProps,rootContainerInstance){// If we have an alternate, that means this is an update and we need to
// schedule a side-effect to do the updates.
var oldProps=current.memoizedProps;if(oldProps===newProps){// In mutation mode, this is sufficient for a bailout because
// we won't touch this node even if children changed.
return;}// If we get updated because one of our children updated, we don't
// have newProps so we'll have to reuse them.
// TODO: Split the update API as separate for the props vs. children.
// Even better would be if children weren't special cased at all tho.
var instance=workInProgress.stateNode;var currentHostContext=getHostContext();// TODO: Experiencing an error where oldProps is null. Suggests a host
// component is hitting the resume path. Figure out why. Possibly
// related to `hidden`.
var updatePayload=prepareUpdate(instance,type,oldProps,newProps,rootContainerInstance,currentHostContext);// TODO: Type this specific to this type of component.
workInProgress.updateQueue=updatePayload;// If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update. All the work is done in commitWork.
if(updatePayload){markUpdate(workInProgress);}};updateHostText$1=function(current,workInProgress,oldText,newText){// If the text differs, mark it as an update. All the work in done in commitWork.
if(oldText!==newText){markUpdate(workInProgress);}};}function cutOffTailIfNeeded(renderState,hasRenderedATailFallback){if(getIsHydrating()){// If we're hydrating, we should consume as many items as we can
// so we don't leave any behind.
return;}switch(renderState.tailMode){case'hidden':{// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
var tailNode=renderState.tail;var lastTailNode=null;while(tailNode!==null){if(tailNode.alternate!==null){lastTailNode=tailNode;}tailNode=tailNode.sibling;}// Next we're simply going to delete all insertions after the
// last rendered item.
if(lastTailNode===null){// All remaining items in the tail are insertions.
renderState.tail=null;}else {// Detach the insertion after the last node that was already
// inserted.
lastTailNode.sibling=null;}break;}case'collapsed':{// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
var _tailNode=renderState.tail;var _lastTailNode=null;while(_tailNode!==null){if(_tailNode.alternate!==null){_lastTailNode=_tailNode;}_tailNode=_tailNode.sibling;}// Next we're simply going to delete all insertions after the
// last rendered item.
if(_lastTailNode===null){// All remaining items in the tail are insertions.
if(!hasRenderedATailFallback&&renderState.tail!==null){// We suspended during the head. We want to show at least one
// row at the tail. So we'll keep on and cut off the rest.
renderState.tail.sibling=null;}else {renderState.tail=null;}}else {// Detach the insertion after the last node that was already
// inserted.
_lastTailNode.sibling=null;}break;}}}function completeWork(current,workInProgress,renderLanes){var newProps=workInProgress.pendingProps;switch(workInProgress.tag){case IndeterminateComponent:case LazyComponent:case SimpleMemoComponent:case FunctionComponent:case ForwardRef:case Fragment:case Mode:case Profiler:case ContextConsumer:case MemoComponent:return null;case ClassComponent:{var Component=workInProgress.type;if(isContextProvider(Component)){popContext(workInProgress);}return null;}case HostRoot:{popHostContainer(workInProgress);popTopLevelContextObject(workInProgress);resetWorkInProgressVersions();var fiberRoot=workInProgress.stateNode;if(fiberRoot.pendingContext){fiberRoot.context=fiberRoot.pendingContext;fiberRoot.pendingContext=null;}if(current===null||current.child===null){// If we hydrated, pop so that we can delete any remaining children
// that weren't hydrated.
var wasHydrated=popHydrationState(workInProgress);if(wasHydrated){// If we hydrated, then we'll need to schedule an update for
// the commit side-effects on the root.
markUpdate(workInProgress);}else if(!fiberRoot.hydrate){// Schedule an effect to clear this container at the start of the next commit.
// This handles the case of React rendering into a container with previous children.
// It's also safe to do for updates too, because current.child would only be null
// if the previous render was null (so the the container would already be empty).
workInProgress.flags|=Snapshot;}}updateHostContainer(workInProgress);return null;}case HostComponent:{popHostContext(workInProgress);var rootContainerInstance=getRootHostContainer();var type=workInProgress.type;if(current!==null&&workInProgress.stateNode!=null){updateHostComponent$1(current,workInProgress,type,newProps,rootContainerInstance);if(current.ref!==workInProgress.ref){markRef$1(workInProgress);}}else {if(!newProps){if(!(workInProgress.stateNode!==null)){{throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");}}// This can happen when we abort work.
return null;}var currentHostContext=getHostContext();// TODO: Move createInstance to beginWork and keep it on a context
// "stack" as the parent. Then append children as we go in beginWork
// or completeWork depending on whether we want to add them top->down or
// bottom->up. Top->down is faster in IE11.
var _wasHydrated=popHydrationState(workInProgress);if(_wasHydrated){// TODO: Move this and createInstance step into the beginPhase
// to consolidate.
if(prepareToHydrateHostInstance(workInProgress,rootContainerInstance,currentHostContext)){// If changes to the hydrated node need to be applied at the
// commit-phase we mark this as such.
markUpdate(workInProgress);}}else {var instance=createInstance(type,newProps,rootContainerInstance,currentHostContext,workInProgress);appendAllChildren(instance,workInProgress,false,false);workInProgress.stateNode=instance;// Certain renderers require commit-time effects for initial mount.
// (eg DOM renderer supports auto-focus for certain elements).
// Make sure such renderers get scheduled for later work.
if(finalizeInitialChildren(instance,type,newProps,rootContainerInstance)){markUpdate(workInProgress);}}if(workInProgress.ref!==null){// If there is a ref on a host node we need to schedule a callback
markRef$1(workInProgress);}}return null;}case HostText:{var newText=newProps;if(current&&workInProgress.stateNode!=null){var oldText=current.memoizedProps;// If we have an alternate, that means this is an update and we need
// to schedule a side-effect to do the updates.
updateHostText$1(current,workInProgress,oldText,newText);}else {if(typeof newText!=='string'){if(!(workInProgress.stateNode!==null)){{throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");}}// This can happen when we abort work.
}var _rootContainerInstance=getRootHostContainer();var _currentHostContext=getHostContext();var _wasHydrated2=popHydrationState(workInProgress);if(_wasHydrated2){if(prepareToHydrateHostTextInstance(workInProgress)){markUpdate(workInProgress);}}else {workInProgress.stateNode=createTextInstance(newText,_rootContainerInstance,_currentHostContext,workInProgress);}}return null;}case SuspenseComponent:{popSuspenseContext(workInProgress);var nextState=workInProgress.memoizedState;if((workInProgress.flags&DidCapture)!==NoFlags){// Something suspended. Re-render with the fallback children.
workInProgress.lanes=renderLanes;// Do not reset the effect list.
if((workInProgress.mode&ProfileMode)!==NoMode){transferActualDuration(workInProgress);}return workInProgress;}var nextDidTimeout=nextState!==null;var prevDidTimeout=false;if(current===null){if(workInProgress.memoizedProps.fallback!==undefined){popHydrationState(workInProgress);}}else {var prevState=current.memoizedState;prevDidTimeout=prevState!==null;}if(nextDidTimeout&&!prevDidTimeout){// If this subtreee is running in blocking mode we can suspend,
// otherwise we won't suspend.
// TODO: This will still suspend a synchronous tree if anything
// in the concurrent tree already suspended during this render.
// This is a known bug.
if((workInProgress.mode&BlockingMode)!==NoMode){// TODO: Move this back to throwException because this is too late
// if this is a large tree which is common for initial loads. We
// don't know if we should restart a render or not until we get
// this marker, and this is too late.
// If this render already had a ping or lower pri updates,
// and this is the first time we know we're going to suspend we
// should be able to immediately restart from within throwException.
var hasInvisibleChildContext=current===null&&workInProgress.memoizedProps.unstable_avoidThisFallback!==true;if(hasInvisibleChildContext||hasSuspenseContext(suspenseStackCursor.current,InvisibleParentSuspenseContext)){// If this was in an invisible tree or a new render, then showing
// this boundary is ok.
renderDidSuspend();}else {// Otherwise, we're going to have to hide content so we should
// suspend for longer if possible.
renderDidSuspendDelayIfPossible();}}}{// TODO: Only schedule updates if these values are non equal, i.e. it changed.
if(nextDidTimeout||prevDidTimeout){// If this boundary just timed out, schedule an effect to attach a
// retry listener to the promise. This flag is also used to hide the
// primary children. In mutation mode, we also need the flag to
// *unhide* children that were previously hidden, so check if this
// is currently timed out, too.
workInProgress.flags|=Update;}}return null;}case HostPortal:popHostContainer(workInProgress);updateHostContainer(workInProgress);if(current===null){preparePortalMount(workInProgress.stateNode.containerInfo);}return null;case ContextProvider:// Pop provider fiber
popProvider(workInProgress);return null;case IncompleteClassComponent:{// Same as class component case. I put it down here so that the tags are
// sequential to ensure this switch is compiled to a jump table.
var _Component=workInProgress.type;if(isContextProvider(_Component)){popContext(workInProgress);}return null;}case SuspenseListComponent:{popSuspenseContext(workInProgress);var renderState=workInProgress.memoizedState;if(renderState===null){// We're running in the default, "independent" mode.
// We don't do anything in this mode.
return null;}var didSuspendAlready=(workInProgress.flags&DidCapture)!==NoFlags;var renderedTail=renderState.rendering;if(renderedTail===null){// We just rendered the head.
if(!didSuspendAlready){// This is the first pass. We need to figure out if anything is still
// suspended in the rendered set.
// If new content unsuspended, but there's still some content that
// didn't. Then we need to do a second pass that forces everything
// to keep showing their fallbacks.
// We might be suspended if something in this render pass suspended, or
// something in the previous committed pass suspended. Otherwise,
// there's no chance so we can skip the expensive call to
// findFirstSuspended.
var cannotBeSuspended=renderHasNotSuspendedYet()&&(current===null||(current.flags&DidCapture)===NoFlags);if(!cannotBeSuspended){var row=workInProgress.child;while(row!==null){var suspended=findFirstSuspended(row);if(suspended!==null){didSuspendAlready=true;workInProgress.flags|=DidCapture;cutOffTailIfNeeded(renderState,false);// If this is a newly suspended tree, it might not get committed as
// part of the second pass. In that case nothing will subscribe to
// its thennables. Instead, we'll transfer its thennables to the
// SuspenseList so that it can retry if they resolve.
// There might be multiple of these in the list but since we're
// going to wait for all of them anyway, it doesn't really matter
// which ones gets to ping. In theory we could get clever and keep
// track of how many dependencies remain but it gets tricky because
// in the meantime, we can add/remove/change items and dependencies.
// We might bail out of the loop before finding any but that
// doesn't matter since that means that the other boundaries that
// we did find already has their listeners attached.
var newThennables=suspended.updateQueue;if(newThennables!==null){workInProgress.updateQueue=newThennables;workInProgress.flags|=Update;}// Rerender the whole list, but this time, we'll force fallbacks
// to stay in place.
// Reset the effect list before doing the second pass since that's now invalid.
if(renderState.lastEffect===null){workInProgress.firstEffect=null;}workInProgress.lastEffect=renderState.lastEffect;// Reset the child fibers to their original state.
resetChildFibers(workInProgress,renderLanes);// Set up the Suspense Context to force suspense and immediately
// rerender the children.
pushSuspenseContext(workInProgress,setShallowSuspenseContext(suspenseStackCursor.current,ForceSuspenseFallback));return workInProgress.child;}row=row.sibling;}}if(renderState.tail!==null&&now()>getRenderTargetTime()){// We have already passed our CPU deadline but we still have rows
// left in the tail. We'll just give up further attempts to render
// the main content and only render fallbacks.
workInProgress.flags|=DidCapture;didSuspendAlready=true;cutOffTailIfNeeded(renderState,false);// Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. While in terms
// of priority this work has the same priority as this current render,
// it's not part of the same transition once the transition has
// committed. If it's sync, we still want to yield so that it can be
// painted. Conceptually, this is really the same as pinging.
// We can use any RetryLane even if it's the one currently rendering
// since we're leaving it behind on this node.
workInProgress.lanes=SomeRetryLane;{markSpawnedWork(SomeRetryLane);}}}else {cutOffTailIfNeeded(renderState,false);}// Next we're going to render the tail.
}else {// Append the rendered row to the child list.
if(!didSuspendAlready){var _suspended=findFirstSuspended(renderedTail);if(_suspended!==null){workInProgress.flags|=DidCapture;didSuspendAlready=true;// Ensure we transfer the update queue to the parent so that it doesn't
// get lost if this row ends up dropped during a second pass.
var _newThennables=_suspended.updateQueue;if(_newThennables!==null){workInProgress.updateQueue=_newThennables;workInProgress.flags|=Update;}cutOffTailIfNeeded(renderState,true);// This might have been modified.
if(renderState.tail===null&&renderState.tailMode==='hidden'&&!renderedTail.alternate&&!getIsHydrating()// We don't cut it if we're hydrating.
){// We need to delete the row we just rendered.
// Reset the effect list to what it was before we rendered this
// child. The nested children have already appended themselves.
var lastEffect=workInProgress.lastEffect=renderState.lastEffect;// Remove any effects that were appended after this point.
if(lastEffect!==null){lastEffect.nextEffect=null;}// We're done.
return null;}}else if(// The time it took to render last row is greater than the remaining
// time we have to render. So rendering one more row would likely
// exceed it.
now()*2-renderState.renderingStartTime>getRenderTargetTime()&&renderLanes!==OffscreenLane){// We have now passed our CPU deadline and we'll just give up further
// attempts to render the main content and only render fallbacks.
// The assumption is that this is usually faster.
workInProgress.flags|=DidCapture;didSuspendAlready=true;cutOffTailIfNeeded(renderState,false);// Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. While in terms
// of priority this work has the same priority as this current render,
// it's not part of the same transition once the transition has
// committed. If it's sync, we still want to yield so that it can be
// painted. Conceptually, this is really the same as pinging.
// We can use any RetryLane even if it's the one currently rendering
// since we're leaving it behind on this node.
workInProgress.lanes=SomeRetryLane;{markSpawnedWork(SomeRetryLane);}}}if(renderState.isBackwards){// The effect list of the backwards tail will have been added
// to the end. This breaks the guarantee that life-cycles fire in
// sibling order but that isn't a strong guarantee promised by React.
// Especially since these might also just pop in during future commits.
// Append to the beginning of the list.
renderedTail.sibling=workInProgress.child;workInProgress.child=renderedTail;}else {var previousSibling=renderState.last;if(previousSibling!==null){previousSibling.sibling=renderedTail;}else {workInProgress.child=renderedTail;}renderState.last=renderedTail;}}if(renderState.tail!==null){// We still have tail rows to render.
// Pop a row.
var next=renderState.tail;renderState.rendering=next;renderState.tail=next.sibling;renderState.lastEffect=workInProgress.lastEffect;renderState.renderingStartTime=now();next.sibling=null;// Restore the context.
// TODO: We can probably just avoid popping it instead and only
// setting it the first time we go from not suspended to suspended.
var suspenseContext=suspenseStackCursor.current;if(didSuspendAlready){suspenseContext=setShallowSuspenseContext(suspenseContext,ForceSuspenseFallback);}else {suspenseContext=setDefaultShallowSuspenseContext(suspenseContext);}pushSuspenseContext(workInProgress,suspenseContext);// Do a pass over the next row.
return next;}return null;}case FundamentalComponent:{break;}case ScopeComponent:{break;}case Block:break;case OffscreenComponent:case LegacyHiddenComponent:{popRenderLanes(workInProgress);if(current!==null){var _nextState=workInProgress.memoizedState;var _prevState=current.memoizedState;var prevIsHidden=_prevState!==null;var nextIsHidden=_nextState!==null;if(prevIsHidden!==nextIsHidden&&newProps.mode!=='unstable-defer-without-hiding'){workInProgress.flags|=Update;}}return null;}}{{throw Error("Unknown unit of work tag ("+workInProgress.tag+"). This error is likely caused by a bug in React. Please file an issue.");}}}function unwindWork(workInProgress,renderLanes){switch(workInProgress.tag){case ClassComponent:{var Component=workInProgress.type;if(isContextProvider(Component)){popContext(workInProgress);}var flags=workInProgress.flags;if(flags&ShouldCapture){workInProgress.flags=flags&~ShouldCapture|DidCapture;if((workInProgress.mode&ProfileMode)!==NoMode){transferActualDuration(workInProgress);}return workInProgress;}return null;}case HostRoot:{popHostContainer(workInProgress);popTopLevelContextObject(workInProgress);resetWorkInProgressVersions();var _flags=workInProgress.flags;if(!((_flags&DidCapture)===NoFlags)){{throw Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue.");}}workInProgress.flags=_flags&~ShouldCapture|DidCapture;return workInProgress;}case HostComponent:{// TODO: popHydrationState
popHostContext(workInProgress);return null;}case SuspenseComponent:{popSuspenseContext(workInProgress);var _flags2=workInProgress.flags;if(_flags2&ShouldCapture){workInProgress.flags=_flags2&~ShouldCapture|DidCapture;// Captured a suspense effect. Re-render the boundary.
if((workInProgress.mode&ProfileMode)!==NoMode){transferActualDuration(workInProgress);}return workInProgress;}return null;}case SuspenseListComponent:{popSuspenseContext(workInProgress);// SuspenseList doesn't actually catch anything. It should've been
// caught by a nested boundary. If not, it should bubble through.
return null;}case HostPortal:popHostContainer(workInProgress);return null;case ContextProvider:popProvider(workInProgress);return null;case OffscreenComponent:case LegacyHiddenComponent:popRenderLanes(workInProgress);return null;default:return null;}}function unwindInterruptedWork(interruptedWork){switch(interruptedWork.tag){case ClassComponent:{var childContextTypes=interruptedWork.type.childContextTypes;if(childContextTypes!==null&&childContextTypes!==undefined){popContext(interruptedWork);}break;}case HostRoot:{popHostContainer(interruptedWork);popTopLevelContextObject(interruptedWork);resetWorkInProgressVersions();break;}case HostComponent:{popHostContext(interruptedWork);break;}case HostPortal:popHostContainer(interruptedWork);break;case SuspenseComponent:popSuspenseContext(interruptedWork);break;case SuspenseListComponent:popSuspenseContext(interruptedWork);break;case ContextProvider:popProvider(interruptedWork);break;case OffscreenComponent:case LegacyHiddenComponent:popRenderLanes(interruptedWork);break;}}function createCapturedValue(value,source){// If the value is an error, call this function immediately after it is thrown
// so the stack is accurate.
return {value:value,source:source,stack:getStackByFiberInDevAndProd(source)};}// This module is forked in different environments.
// By default, return `true` to log errors to the console.
// Forks can return `false` if this isn't desirable.
function showErrorDialog(boundary,errorInfo){return true;}function logCapturedError(boundary,errorInfo){try{var logError=showErrorDialog(boundary,errorInfo);// Allow injected showErrorDialog() to prevent default console.error logging.
// This enables renderers like ReactNative to better manage redbox behavior.
if(logError===false){return;}var error=errorInfo.value;if(true){var source=errorInfo.source;var stack=errorInfo.stack;var componentStack=stack!==null?stack:'';// Browsers support silencing uncaught errors by calling
// `preventDefault()` in window `error` handler.
// We record this information as an expando on the error.
if(error!=null&&error._suppressLogging){if(boundary.tag===ClassComponent){// The error is recoverable and was silenced.
// Ignore it and don't print the stack addendum.
// This is handy for testing error boundaries without noise.
return;}// The error is fatal. Since the silencing might have
// been accidental, we'll surface it anyway.
// However, the browser would have silenced the original error
// so we'll print it first, and then print the stack addendum.
console['error'](error);// Don't transform to our wrapper
// For a more detailed description of this block, see:
// https://github.com/facebook/react/pull/13384
}var componentName=source?getComponentName(source.type):null;var componentNameMessage=componentName?"The above error occurred in the <"+componentName+"> component:":'The above error occurred in one of your React components:';var errorBoundaryMessage;var errorBoundaryName=getComponentName(boundary.type);if(errorBoundaryName){errorBoundaryMessage="React will try to recreate this component tree from scratch "+("using the error boundary you provided, "+errorBoundaryName+".");}else {errorBoundaryMessage='Consider adding an error boundary to your tree to customize error handling behavior.\n'+'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';}var combinedMessage=componentNameMessage+"\n"+componentStack+"\n\n"+(""+errorBoundaryMessage);// In development, we provide our own message with just the component stack.
// We don't include the original error message and JS stack because the browser
// has already printed it. Even if the application swallows the error, it is still
// displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
console['error'](combinedMessage);// Don't transform to our wrapper
}}catch(e){// This method must not throw, or React internal state will get messed up.
// If console.error is overridden, or logCapturedError() shows a dialog that throws,
// we want to report this error outside of the normal stack as a last resort.
// https://github.com/facebook/react/issues/13188
setTimeout(function(){throw e;});}}var PossiblyWeakMap$1=typeof WeakMap==='function'?WeakMap:Map;function createRootErrorUpdate(fiber,errorInfo,lane){var update=createUpdate(NoTimestamp,lane);// Unmount the root by rendering null.
update.tag=CaptureUpdate;// Caution: React DevTools currently depends on this property
// being called "element".
update.payload={element:null};var error=errorInfo.value;update.callback=function(){onUncaughtError(error);logCapturedError(fiber,errorInfo);};return update;}function createClassErrorUpdate(fiber,errorInfo,lane){var update=createUpdate(NoTimestamp,lane);update.tag=CaptureUpdate;var getDerivedStateFromError=fiber.type.getDerivedStateFromError;if(typeof getDerivedStateFromError==='function'){var error$1=errorInfo.value;update.payload=function(){logCapturedError(fiber,errorInfo);return getDerivedStateFromError(error$1);};}var inst=fiber.stateNode;if(inst!==null&&typeof inst.componentDidCatch==='function'){update.callback=function callback(){{markFailedErrorBoundaryForHotReloading(fiber);}if(typeof getDerivedStateFromError!=='function'){// To preserve the preexisting retry behavior of error boundaries,
// we keep track of which ones already failed during this batch.
// This gets reset before we yield back to the browser.
// TODO: Warn in strict mode if getDerivedStateFromError is
// not defined.
markLegacyErrorBoundaryAsFailed(this);// Only log here if componentDidCatch is the only error boundary method defined
logCapturedError(fiber,errorInfo);}var error$1=errorInfo.value;var stack=errorInfo.stack;this.componentDidCatch(error$1,{componentStack:stack!==null?stack:''});{if(typeof getDerivedStateFromError!=='function'){// If componentDidCatch is the only error boundary method defined,
// then it needs to call setState to recover from errors.
// If no state update is scheduled then the boundary will swallow the error.
if(!includesSomeLane(fiber.lanes,SyncLane)){error('%s: Error boundaries should implement getDerivedStateFromError(). '+'In that method, return a state update to display an error message or fallback UI.',getComponentName(fiber.type)||'Unknown');}}}};}else {update.callback=function(){markFailedErrorBoundaryForHotReloading(fiber);};}return update;}function attachPingListener(root,wakeable,lanes){// Attach a listener to the promise to "ping" the root and retry. But only if
// one does not already exist for the lanes we're currently rendering (which
// acts like a "thread ID" here).
var pingCache=root.pingCache;var threadIDs;if(pingCache===null){pingCache=root.pingCache=new PossiblyWeakMap$1();threadIDs=new Set();pingCache.set(wakeable,threadIDs);}else {threadIDs=pingCache.get(wakeable);if(threadIDs===undefined){threadIDs=new Set();pingCache.set(wakeable,threadIDs);}}if(!threadIDs.has(lanes)){// Memoize using the thread ID to prevent redundant listeners.
threadIDs.add(lanes);var ping=pingSuspendedRoot.bind(null,root,wakeable,lanes);wakeable.then(ping,ping);}}function throwException(root,returnFiber,sourceFiber,value,rootRenderLanes){// The source fiber did not complete.
sourceFiber.flags|=Incomplete;// Its effect list is no longer valid.
sourceFiber.firstEffect=sourceFiber.lastEffect=null;if(value!==null&&typeof value==='object'&&typeof value.then==='function'){// This is a wakeable.
var wakeable=value;if((sourceFiber.mode&BlockingMode)===NoMode){// Reset the memoizedState to what it was before we attempted
// to render it.
var currentSource=sourceFiber.alternate;if(currentSource){sourceFiber.updateQueue=currentSource.updateQueue;sourceFiber.memoizedState=currentSource.memoizedState;sourceFiber.lanes=currentSource.lanes;}else {sourceFiber.updateQueue=null;sourceFiber.memoizedState=null;}}var hasInvisibleParentBoundary=hasSuspenseContext(suspenseStackCursor.current,InvisibleParentSuspenseContext);// Schedule the nearest Suspense to re-render the timed out view.
var _workInProgress=returnFiber;do{if(_workInProgress.tag===SuspenseComponent&&shouldCaptureSuspense(_workInProgress,hasInvisibleParentBoundary)){// Found the nearest boundary.
// Stash the promise on the boundary fiber. If the boundary times out, we'll
// attach another listener to flip the boundary back to its normal state.
var wakeables=_workInProgress.updateQueue;if(wakeables===null){var updateQueue=new Set();updateQueue.add(wakeable);_workInProgress.updateQueue=updateQueue;}else {wakeables.add(wakeable);}// If the boundary is outside of blocking mode, we should *not*
// suspend the commit. Pretend as if the suspended component rendered
// null and keep rendering. In the commit phase, we'll schedule a
// subsequent synchronous update to re-render the Suspense.
//
// Note: It doesn't matter whether the component that suspended was
// inside a blocking mode tree. If the Suspense is outside of it, we
// should *not* suspend the commit.
if((_workInProgress.mode&BlockingMode)===NoMode){_workInProgress.flags|=DidCapture;sourceFiber.flags|=ForceUpdateForLegacySuspense;// We're going to commit this fiber even though it didn't complete.
// But we shouldn't call any lifecycle methods or callbacks. Remove
// all lifecycle effect tags.
sourceFiber.flags&=~(LifecycleEffectMask|Incomplete);if(sourceFiber.tag===ClassComponent){var currentSourceFiber=sourceFiber.alternate;if(currentSourceFiber===null){// This is a new mount. Change the tag so it's not mistaken for a
// completed class component. For example, we should not call
// componentWillUnmount if it is deleted.
sourceFiber.tag=IncompleteClassComponent;}else {// When we try rendering again, we should not reuse the current fiber,
// since it's known to be in an inconsistent state. Use a force update to
// prevent a bail out.
var update=createUpdate(NoTimestamp,SyncLane);update.tag=ForceUpdate;enqueueUpdate(sourceFiber,update);}}// The source fiber did not complete. Mark it with Sync priority to
// indicate that it still has pending work.
sourceFiber.lanes=mergeLanes(sourceFiber.lanes,SyncLane);// Exit without suspending.
return;}// Confirmed that the boundary is in a concurrent mode tree. Continue
// with the normal suspend path.
//
// After this we'll use a set of heuristics to determine whether this
// render pass will run to completion or restart or "suspend" the commit.
// The actual logic for this is spread out in different places.
//
// This first principle is that if we're going to suspend when we complete
// a root, then we should also restart if we get an update or ping that
// might unsuspend it, and vice versa. The only reason to suspend is
// because you think you might want to restart before committing. However,
// it doesn't make sense to restart only while in the period we're suspended.
//
// Restarting too aggressively is also not good because it starves out any
// intermediate loading state. So we use heuristics to determine when.
// Suspense Heuristics
//
// If nothing threw a Promise or all the same fallbacks are already showing,
// then don't suspend/restart.
//
// If this is an initial render of a new tree of Suspense boundaries and
// those trigger a fallback, then don't suspend/restart. We want to ensure
// that we can show the initial loading state as quickly as possible.
//
// If we hit a "Delayed" case, such as when we'd switch from content back into
// a fallback, then we should always suspend/restart. Transitions apply
// to this case. If none is defined, JND is used instead.
//
// If we're already showing a fallback and it gets "retried", allowing us to show
// another level, but there's still an inner boundary that would show a fallback,
// then we suspend/restart for 500ms since the last time we showed a fallback
// anywhere in the tree. This effectively throttles progressive loading into a
// consistent train of commits. This also gives us an opportunity to restart to
// get to the completed state slightly earlier.
//
// If there's ambiguity due to batching it's resolved in preference of:
// 1) "delayed", 2) "initial render", 3) "retry".
//
// We want to ensure that a "busy" state doesn't get force committed. We want to
// ensure that new initial loading states can commit as soon as possible.
attachPingListener(root,wakeable,rootRenderLanes);_workInProgress.flags|=ShouldCapture;_workInProgress.lanes=rootRenderLanes;return;}// This boundary already captured during this render. Continue to the next
// boundary.
_workInProgress=_workInProgress.return;}while(_workInProgress!==null);// No boundary was found. Fallthrough to error mode.
// TODO: Use invariant so the message is stripped in prod?
value=new Error((getComponentName(sourceFiber.type)||'A React component')+' suspended while rendering, but no fallback UI was specified.\n'+'\n'+'Add a <Suspense fallback=...> component higher in the tree to '+'provide a loading indicator or placeholder to display.');}// We didn't find a boundary that could handle this type of exception. Start
// over and traverse parent path again, this time treating the exception
// as an error.
renderDidError();value=createCapturedValue(value,sourceFiber);var workInProgress=returnFiber;do{switch(workInProgress.tag){case HostRoot:{var _errorInfo=value;workInProgress.flags|=ShouldCapture;var lane=pickArbitraryLane(rootRenderLanes);workInProgress.lanes=mergeLanes(workInProgress.lanes,lane);var _update=createRootErrorUpdate(workInProgress,_errorInfo,lane);enqueueCapturedUpdate(workInProgress,_update);return;}case ClassComponent:// Capture and retry
var errorInfo=value;var ctor=workInProgress.type;var instance=workInProgress.stateNode;if((workInProgress.flags&DidCapture)===NoFlags&&(typeof ctor.getDerivedStateFromError==='function'||instance!==null&&typeof instance.componentDidCatch==='function'&&!isAlreadyFailedLegacyErrorBoundary(instance))){workInProgress.flags|=ShouldCapture;var _lane=pickArbitraryLane(rootRenderLanes);workInProgress.lanes=mergeLanes(workInProgress.lanes,_lane);// Schedule the error boundary to re-render using updated state
var _update2=createClassErrorUpdate(workInProgress,errorInfo,_lane);enqueueCapturedUpdate(workInProgress,_update2);return;}break;}workInProgress=workInProgress.return;}while(workInProgress!==null);}var didWarnAboutUndefinedSnapshotBeforeUpdate=null;{didWarnAboutUndefinedSnapshotBeforeUpdate=new Set();}var PossiblyWeakSet=typeof WeakSet==='function'?WeakSet:Set;var callComponentWillUnmountWithTimer=function(current,instance){instance.props=current.memoizedProps;instance.state=current.memoizedState;{instance.componentWillUnmount();}};// Capture errors so they don't interrupt unmounting.
function safelyCallComponentWillUnmount(current,instance){{invokeGuardedCallback(null,callComponentWillUnmountWithTimer,null,current,instance);if(hasCaughtError()){var unmountError=clearCaughtError();captureCommitPhaseError(current,unmountError);}}}function safelyDetachRef(current){var ref=current.ref;if(ref!==null){if(typeof ref==='function'){{invokeGuardedCallback(null,ref,null,null);if(hasCaughtError()){var refError=clearCaughtError();captureCommitPhaseError(current,refError);}}}else {ref.current=null;}}}function safelyCallDestroy(current,destroy){{invokeGuardedCallback(null,destroy,null);if(hasCaughtError()){var error=clearCaughtError();captureCommitPhaseError(current,error);}}}function commitBeforeMutationLifeCycles(current,finishedWork){switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:case Block:{return;}case ClassComponent:{if(finishedWork.flags&Snapshot){if(current!==null){var prevProps=current.memoizedProps;var prevState=current.memoizedState;var instance=finishedWork.stateNode;// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'getSnapshotBeforeUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'getSnapshotBeforeUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}}}var snapshot=instance.getSnapshotBeforeUpdate(finishedWork.elementType===finishedWork.type?prevProps:resolveDefaultProps(finishedWork.type,prevProps),prevState);{var didWarnSet=didWarnAboutUndefinedSnapshotBeforeUpdate;if(snapshot===undefined&&!didWarnSet.has(finishedWork.type)){didWarnSet.add(finishedWork.type);error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) '+'must be returned. You have returned undefined.',getComponentName(finishedWork.type));}}instance.__reactInternalSnapshotBeforeUpdate=snapshot;}}return;}case HostRoot:{{if(finishedWork.flags&Snapshot){var root=finishedWork.stateNode;clearContainer(root.containerInfo);}}return;}case HostComponent:case HostText:case HostPortal:case IncompleteClassComponent:// Nothing to do for these component types
return;}{{throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");}}}function commitHookEffectListUnmount(tag,finishedWork){var updateQueue=finishedWork.updateQueue;var lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{if((effect.tag&tag)===tag){// Unmount
var destroy=effect.destroy;effect.destroy=undefined;if(destroy!==undefined){destroy();}}effect=effect.next;}while(effect!==firstEffect);}}function commitHookEffectListMount(tag,finishedWork){var updateQueue=finishedWork.updateQueue;var lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{if((effect.tag&tag)===tag){// Mount
var create=effect.create;effect.destroy=create();{var destroy=effect.destroy;if(destroy!==undefined&&typeof destroy!=='function'){var addendum=void 0;if(destroy===null){addendum=' You returned null. If your effect does not require clean '+'up, return undefined (or nothing).';}else if(typeof destroy.then==='function'){addendum='\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. '+'Instead, write the async function inside your effect '+'and call it immediately:\n\n'+'useEffect(() => {\n'+' async function fetchData() {\n'+' // You can await here\n'+' const response = await MyAPI.getData(someId);\n'+' // ...\n'+' }\n'+' fetchData();\n'+"}, [someId]); // Or [] if effect doesn't need props or state\n\n"+'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';}else {addendum=' You returned: '+destroy;}error('An effect function must not return anything besides a function, '+'which is used for clean-up.%s',addendum);}}}effect=effect.next;}while(effect!==firstEffect);}}function schedulePassiveEffects(finishedWork){var updateQueue=finishedWork.updateQueue;var lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{var _effect=effect,next=_effect.next,tag=_effect.tag;if((tag&Passive$1)!==NoFlags$1&&(tag&HasEffect)!==NoFlags$1){enqueuePendingPassiveHookEffectUnmount(finishedWork,effect);enqueuePendingPassiveHookEffectMount(finishedWork,effect);}effect=next;}while(effect!==firstEffect);}}function commitLifeCycles(finishedRoot,current,finishedWork,committedLanes){switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:case Block:{// At this point layout effects have already been destroyed (during mutation phase).
// This is done to prevent sibling component effects from interfering with each other,
// e.g. a destroy function in one component should never override a ref set
// by a create function in another component during the same commit.
{commitHookEffectListMount(Layout|HasEffect,finishedWork);}schedulePassiveEffects(finishedWork);return;}case ClassComponent:{var instance=finishedWork.stateNode;if(finishedWork.flags&Update){if(current===null){// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'componentDidMount. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'componentDidMount. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}}}{instance.componentDidMount();}}else {var prevProps=finishedWork.elementType===finishedWork.type?current.memoizedProps:resolveDefaultProps(finishedWork.type,current.memoizedProps);var prevState=current.memoizedState;// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'componentDidUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'componentDidUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}}}{instance.componentDidUpdate(prevProps,prevState,instance.__reactInternalSnapshotBeforeUpdate);}}}// TODO: I think this is now always non-null by the time it reaches the
// commit phase. Consider removing the type check.
var updateQueue=finishedWork.updateQueue;if(updateQueue!==null){{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'processing the update queue. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'processing the update queue. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentName(finishedWork.type)||'instance');}}}// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
commitUpdateQueue(finishedWork,updateQueue,instance);}return;}case HostRoot:{// TODO: I think this is now always non-null by the time it reaches the
// commit phase. Consider removing the type check.
var _updateQueue=finishedWork.updateQueue;if(_updateQueue!==null){var _instance=null;if(finishedWork.child!==null){switch(finishedWork.child.tag){case HostComponent:_instance=getPublicInstance(finishedWork.child.stateNode);break;case ClassComponent:_instance=finishedWork.child.stateNode;break;}}commitUpdateQueue(finishedWork,_updateQueue,_instance);}return;}case HostComponent:{var _instance2=finishedWork.stateNode;// Renderers may schedule work to be done after host components are mounted
// (eg DOM renderer may schedule auto-focus for inputs and form controls).
// These effects should only be committed when components are first mounted,
// aka when there is no current/alternate.
if(current===null&&finishedWork.flags&Update){var type=finishedWork.type;var props=finishedWork.memoizedProps;commitMount(_instance2,type,props);}return;}case HostText:{// We have no life-cycles associated with text.
return;}case HostPortal:{// We have no life-cycles associated with portals.
return;}case Profiler:{{var _finishedWork$memoize2=finishedWork.memoizedProps,onCommit=_finishedWork$memoize2.onCommit,onRender=_finishedWork$memoize2.onRender;var effectDuration=finishedWork.stateNode.effectDuration;var commitTime=getCommitTime();if(typeof onRender==='function'){{onRender(finishedWork.memoizedProps.id,current===null?'mount':'update',finishedWork.actualDuration,finishedWork.treeBaseDuration,finishedWork.actualStartTime,commitTime,finishedRoot.memoizedInteractions);}}}return;}case SuspenseComponent:{commitSuspenseHydrationCallbacks(finishedRoot,finishedWork);return;}case SuspenseListComponent:case IncompleteClassComponent:case FundamentalComponent:case ScopeComponent:case OffscreenComponent:case LegacyHiddenComponent:return;}{{throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");}}}function hideOrUnhideAllChildren(finishedWork,isHidden){{// We only have the top Fiber that was inserted but we need to recurse down its
// children to find all the terminal nodes.
var node=finishedWork;while(true){if(node.tag===HostComponent){var instance=node.stateNode;if(isHidden){hideInstance(instance);}else {unhideInstance(node.stateNode,node.memoizedProps);}}else if(node.tag===HostText){var _instance3=node.stateNode;if(isHidden){hideTextInstance(_instance3);}else {unhideTextInstance(_instance3,node.memoizedProps);}}else if((node.tag===OffscreenComponent||node.tag===LegacyHiddenComponent)&&node.memoizedState!==null&&node!==finishedWork);else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===finishedWork){return;}while(node.sibling===null){if(node.return===null||node.return===finishedWork){return;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}}}function commitAttachRef(finishedWork){var ref=finishedWork.ref;if(ref!==null){var instance=finishedWork.stateNode;var instanceToUse;switch(finishedWork.tag){case HostComponent:instanceToUse=getPublicInstance(instance);break;default:instanceToUse=instance;}// Moved outside to ensure DCE works with this flag
if(typeof ref==='function'){ref(instanceToUse);}else {{if(!ref.hasOwnProperty('current')){error('Unexpected ref object provided for %s. '+'Use either a ref-setter function or React.createRef().',getComponentName(finishedWork.type));}}ref.current=instanceToUse;}}}function commitDetachRef(current){var currentRef=current.ref;if(currentRef!==null){if(typeof currentRef==='function'){currentRef(null);}else {currentRef.current=null;}}}// User-originating errors (lifecycles and refs) should not interrupt
// deletion, so don't let them throw. Host-originating errors should
// interrupt deletion, so it's okay
function commitUnmount(finishedRoot,current,renderPriorityLevel){onCommitUnmount(current);switch(current.tag){case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:case Block:{var updateQueue=current.updateQueue;if(updateQueue!==null){var lastEffect=updateQueue.lastEffect;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{var _effect2=effect,destroy=_effect2.destroy,tag=_effect2.tag;if(destroy!==undefined){if((tag&Passive$1)!==NoFlags$1){enqueuePendingPassiveHookEffectUnmount(current,effect);}else {{safelyCallDestroy(current,destroy);}}}effect=effect.next;}while(effect!==firstEffect);}}return;}case ClassComponent:{safelyDetachRef(current);var instance=current.stateNode;if(typeof instance.componentWillUnmount==='function'){safelyCallComponentWillUnmount(current,instance);}return;}case HostComponent:{safelyDetachRef(current);return;}case HostPortal:{// TODO: this is recursive.
// We are also not using this parent because
// the portal will get pushed immediately.
{unmountHostComponents(finishedRoot,current);}return;}case FundamentalComponent:{return;}case DehydratedFragment:{return;}case ScopeComponent:{return;}}}function commitNestedUnmounts(finishedRoot,root,renderPriorityLevel){// While we're inside a removed host node we don't want to call
// removeChild on the inner nodes because they're removed by the top
// call anyway. We also want to call componentWillUnmount on all
// composites before this host node is removed from the tree. Therefore
// we do an inner loop while we're still inside the host node.
var node=root;while(true){commitUnmount(finishedRoot,node);// Visit children because they may contain more composite or host nodes.
// Skip portals because commitUnmount() currently visits them recursively.
if(node.child!==null&&// If we use mutation we drill down into portals using commitUnmount above.
// If we don't use mutation we drill down into portals here instead.
node.tag!==HostPortal){node.child.return=node;node=node.child;continue;}if(node===root){return;}while(node.sibling===null){if(node.return===null||node.return===root){return;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}}function detachFiberMutation(fiber){// Cut off the return pointers to disconnect it from the tree. Ideally, we
// should clear the child pointer of the parent alternate to let this
// get GC:ed but we don't know which for sure which parent is the current
// one so we'll settle for GC:ing the subtree of this child. This child
// itself will be GC:ed when the parent updates the next time.
// Note: we cannot null out sibling here, otherwise it can cause issues
// with findDOMNode and how it requires the sibling field to carry out
// traversal in a later effect. See PR #16820. We now clear the sibling
// field after effects, see: detachFiberAfterEffects.
//
// Don't disconnect stateNode now; it will be detached in detachFiberAfterEffects.
// It may be required if the current component is an error boundary,
// and one of its descendants throws while unmounting a passive effect.
fiber.alternate=null;fiber.child=null;fiber.dependencies=null;fiber.firstEffect=null;fiber.lastEffect=null;fiber.memoizedProps=null;fiber.memoizedState=null;fiber.pendingProps=null;fiber.return=null;fiber.updateQueue=null;{fiber._debugOwner=null;}}function getHostParentFiber(fiber){var parent=fiber.return;while(parent!==null){if(isHostParent(parent)){return parent;}parent=parent.return;}{{throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");}}}function isHostParent(fiber){return fiber.tag===HostComponent||fiber.tag===HostRoot||fiber.tag===HostPortal;}function getHostSibling(fiber){// We're going to search forward into the tree until we find a sibling host
// node. Unfortunately, if multiple insertions are done in a row we have to
// search past them. This leads to exponential search for the next sibling.
// TODO: Find a more efficient way to do this.
var node=fiber;siblings:while(true){// If we didn't find anything, let's try the next sibling.
while(node.sibling===null){if(node.return===null||isHostParent(node.return)){// If we pop out of the root or hit the parent the fiber we are the
// last sibling.
return null;}node=node.return;}node.sibling.return=node.return;node=node.sibling;while(node.tag!==HostComponent&&node.tag!==HostText&&node.tag!==DehydratedFragment){// If it is not host node and, we might have a host node inside it.
// Try to search down until we find one.
if(node.flags&Placement){// If we don't have a child, try the siblings instead.
continue siblings;}// If we don't have a child, try the siblings instead.
// We also skip portals because they are not part of this host tree.
if(node.child===null||node.tag===HostPortal){continue siblings;}else {node.child.return=node;node=node.child;}}// Check if this host node is stable or about to be placed.
if(!(node.flags&Placement)){// Found it!
return node.stateNode;}}}function commitPlacement(finishedWork){var parentFiber=getHostParentFiber(finishedWork);// Note: these two variables *must* always be updated together.
var parent;var isContainer;var parentStateNode=parentFiber.stateNode;switch(parentFiber.tag){case HostComponent:parent=parentStateNode;isContainer=false;break;case HostRoot:parent=parentStateNode.containerInfo;isContainer=true;break;case HostPortal:parent=parentStateNode.containerInfo;isContainer=true;break;case FundamentalComponent:// eslint-disable-next-line-no-fallthrough
default:{{throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");}}}if(parentFiber.flags&ContentReset){// Reset the text content of the parent before doing any insertions
resetTextContent(parent);// Clear ContentReset from the effect tag
parentFiber.flags&=~ContentReset;}var before=getHostSibling(finishedWork);// We only have the top Fiber that was inserted but we need to recurse down its
// children to find all the terminal nodes.
if(isContainer){insertOrAppendPlacementNodeIntoContainer(finishedWork,before,parent);}else {insertOrAppendPlacementNode(finishedWork,before,parent);}}function insertOrAppendPlacementNodeIntoContainer(node,before,parent){var tag=node.tag;var isHost=tag===HostComponent||tag===HostText;if(isHost||enableFundamentalAPI){var stateNode=isHost?node.stateNode:node.stateNode.instance;if(before){insertInContainerBefore(parent,stateNode,before);}else {appendChildToContainer(parent,stateNode);}}else if(tag===HostPortal);else {var child=node.child;if(child!==null){insertOrAppendPlacementNodeIntoContainer(child,before,parent);var sibling=child.sibling;while(sibling!==null){insertOrAppendPlacementNodeIntoContainer(sibling,before,parent);sibling=sibling.sibling;}}}}function insertOrAppendPlacementNode(node,before,parent){var tag=node.tag;var isHost=tag===HostComponent||tag===HostText;if(isHost||enableFundamentalAPI){var stateNode=isHost?node.stateNode:node.stateNode.instance;if(before){insertBefore(parent,stateNode,before);}else {appendChild(parent,stateNode);}}else if(tag===HostPortal);else {var child=node.child;if(child!==null){insertOrAppendPlacementNode(child,before,parent);var sibling=child.sibling;while(sibling!==null){insertOrAppendPlacementNode(sibling,before,parent);sibling=sibling.sibling;}}}}function unmountHostComponents(finishedRoot,current,renderPriorityLevel){// We only have the top Fiber that was deleted but we need to recurse down its
// children to find all the terminal nodes.
var node=current;// Each iteration, currentParent is populated with node's host parent if not
// currentParentIsValid.
var currentParentIsValid=false;// Note: these two variables *must* always be updated together.
var currentParent;var currentParentIsContainer;while(true){if(!currentParentIsValid){var parent=node.return;findParent:while(true){if(!(parent!==null)){{throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");}}var parentStateNode=parent.stateNode;switch(parent.tag){case HostComponent:currentParent=parentStateNode;currentParentIsContainer=false;break findParent;case HostRoot:currentParent=parentStateNode.containerInfo;currentParentIsContainer=true;break findParent;case HostPortal:currentParent=parentStateNode.containerInfo;currentParentIsContainer=true;break findParent;}parent=parent.return;}currentParentIsValid=true;}if(node.tag===HostComponent||node.tag===HostText){commitNestedUnmounts(finishedRoot,node);// After all the children have unmounted, it is now safe to remove the
// node from the tree.
if(currentParentIsContainer){removeChildFromContainer(currentParent,node.stateNode);}else {removeChild(currentParent,node.stateNode);}// Don't visit children because we already visited them.
}else if(node.tag===HostPortal){if(node.child!==null){// When we go into a portal, it becomes the parent to remove from.
// We will reassign it back when we pop the portal on the way up.
currentParent=node.stateNode.containerInfo;currentParentIsContainer=true;// Visit children because portals might contain host components.
node.child.return=node;node=node.child;continue;}}else {commitUnmount(finishedRoot,node);// Visit children because we may find more host components below.
if(node.child!==null){node.child.return=node;node=node.child;continue;}}if(node===current){return;}while(node.sibling===null){if(node.return===null||node.return===current){return;}node=node.return;if(node.tag===HostPortal){// When we go out of the portal, we need to restore the parent.
// Since we don't keep a stack of them, we will search for it.
currentParentIsValid=false;}}node.sibling.return=node.return;node=node.sibling;}}function commitDeletion(finishedRoot,current,renderPriorityLevel){{// Recursively delete all host nodes from the parent.
// Detach refs and call componentWillUnmount() on the whole subtree.
unmountHostComponents(finishedRoot,current);}var alternate=current.alternate;detachFiberMutation(current);if(alternate!==null){detachFiberMutation(alternate);}}function commitWork(current,finishedWork){switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:case Block:{// Layout effects are destroyed during the mutation phase so that all
// destroy functions for all fibers are called before any create functions.
// This prevents sibling component effects from interfering with each other,
// e.g. a destroy function in one component should never override a ref set
// by a create function in another component during the same commit.
{commitHookEffectListUnmount(Layout|HasEffect,finishedWork);}return;}case ClassComponent:{return;}case HostComponent:{var instance=finishedWork.stateNode;if(instance!=null){// Commit the work prepared earlier.
var newProps=finishedWork.memoizedProps;// For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
var oldProps=current!==null?current.memoizedProps:newProps;var type=finishedWork.type;// TODO: Type the updateQueue to be specific to host components.
var updatePayload=finishedWork.updateQueue;finishedWork.updateQueue=null;if(updatePayload!==null){commitUpdate(instance,updatePayload,type,oldProps,newProps);}}return;}case HostText:{if(!(finishedWork.stateNode!==null)){{throw Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");}}var textInstance=finishedWork.stateNode;var newText=finishedWork.memoizedProps;// For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
var oldText=current!==null?current.memoizedProps:newText;commitTextUpdate(textInstance,oldText,newText);return;}case HostRoot:{{var _root=finishedWork.stateNode;if(_root.hydrate){// We've just hydrated. No need to hydrate again.
_root.hydrate=false;commitHydratedContainer(_root.containerInfo);}}return;}case Profiler:{return;}case SuspenseComponent:{commitSuspenseComponent(finishedWork);attachSuspenseRetryListeners(finishedWork);return;}case SuspenseListComponent:{attachSuspenseRetryListeners(finishedWork);return;}case IncompleteClassComponent:{return;}case FundamentalComponent:{break;}case ScopeComponent:{break;}case OffscreenComponent:case LegacyHiddenComponent:{var newState=finishedWork.memoizedState;var isHidden=newState!==null;hideOrUnhideAllChildren(finishedWork,isHidden);return;}}{{throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");}}}function commitSuspenseComponent(finishedWork){var newState=finishedWork.memoizedState;if(newState!==null){markCommitTimeOfFallback();{// Hide the Offscreen component that contains the primary children. TODO:
// Ideally, this effect would have been scheduled on the Offscreen fiber
// itself. That's how unhiding works: the Offscreen component schedules an
// effect on itself. However, in this case, the component didn't complete,
// so the fiber was never added to the effect list in the normal path. We
// could have appended it to the effect list in the Suspense component's
// second pass, but doing it this way is less complicated. This would be
// simpler if we got rid of the effect list and traversed the tree, like
// we're planning to do.
var primaryChildParent=finishedWork.child;hideOrUnhideAllChildren(primaryChildParent,true);}}}function commitSuspenseHydrationCallbacks(finishedRoot,finishedWork){var newState=finishedWork.memoizedState;if(newState===null){var current=finishedWork.alternate;if(current!==null){var prevState=current.memoizedState;if(prevState!==null){var suspenseInstance=prevState.dehydrated;if(suspenseInstance!==null){commitHydratedSuspenseInstance(suspenseInstance);}}}}}function attachSuspenseRetryListeners(finishedWork){// If this boundary just timed out, then it will have a set of wakeables.
// For each wakeable, attach a listener so that when it resolves, React
// attempts to re-render the boundary in the primary (pre-timeout) state.
var wakeables=finishedWork.updateQueue;if(wakeables!==null){finishedWork.updateQueue=null;var retryCache=finishedWork.stateNode;if(retryCache===null){retryCache=finishedWork.stateNode=new PossiblyWeakSet();}wakeables.forEach(function(wakeable){// Memoize using the boundary fiber to prevent redundant listeners.
var retry=resolveRetryWakeable.bind(null,finishedWork,wakeable);if(!retryCache.has(wakeable)){{if(wakeable.__reactDoNotTraceInteractions!==true){retry=tracing$1.unstable_wrap(retry);}}retryCache.add(wakeable);wakeable.then(retry,retry);}});}}// This function detects when a Suspense boundary goes from visible to hidden.
// It returns false if the boundary is already hidden.
// TODO: Use an effect tag.
function isSuspenseBoundaryBeingHidden(current,finishedWork){if(current!==null){var oldState=current.memoizedState;if(oldState===null||oldState.dehydrated!==null){var newState=finishedWork.memoizedState;return newState!==null&&newState.dehydrated===null;}}return false;}function commitResetTextContent(current){resetTextContent(current.stateNode);}var COMPONENT_TYPE=0;var HAS_PSEUDO_CLASS_TYPE=1;var ROLE_TYPE=2;var TEST_NAME_TYPE=3;var TEXT_TYPE=4;if(typeof Symbol==='function'&&Symbol.for){var symbolFor$1=Symbol.for;COMPONENT_TYPE=symbolFor$1('selector.component');HAS_PSEUDO_CLASS_TYPE=symbolFor$1('selector.has_pseudo_class');ROLE_TYPE=symbolFor$1('selector.role');TEST_NAME_TYPE=symbolFor$1('selector.test_id');TEXT_TYPE=symbolFor$1('selector.text');}var commitHooks=[];function onCommitRoot$1(){{commitHooks.forEach(function(commitHook){return commitHook();});}}var ceil=Math.ceil;var ReactCurrentDispatcher$2=ReactSharedInternals.ReactCurrentDispatcher,ReactCurrentOwner$2=ReactSharedInternals.ReactCurrentOwner,IsSomeRendererActing=ReactSharedInternals.IsSomeRendererActing;var NoContext=/* */0;var BatchedContext=/* */1;var EventContext=/* */2;var DiscreteEventContext=/* */4;var LegacyUnbatchedContext=/* */8;var RenderContext=/* */16;var CommitContext=/* */32;var RetryAfterError=/* */64;var RootIncomplete=0;var RootFatalErrored=1;var RootErrored=2;var RootSuspended=3;var RootSuspendedWithDelay=4;var RootCompleted=5;// Describes where we are in the React execution stack
var executionContext=NoContext;// The root we're working on
var workInProgressRoot=null;// The fiber we're working on
var workInProgress=null;// The lanes we're rendering
var workInProgressRootRenderLanes=NoLanes;// Stack that allows components to change the render lanes for its subtree
// This is a superset of the lanes we started working on at the root. The only
// case where it's different from `workInProgressRootRenderLanes` is when we
// enter a subtree that is hidden and needs to be unhidden: Suspense and
// Offscreen component.
//
// Most things in the work loop should deal with workInProgressRootRenderLanes.
// Most things in begin/complete phases should deal with subtreeRenderLanes.
var subtreeRenderLanes=NoLanes;var subtreeRenderLanesCursor=createCursor(NoLanes);// Whether to root completed, errored, suspended, etc.
var workInProgressRootExitStatus=RootIncomplete;// A fatal error, if one is thrown
var workInProgressRootFatalError=null;// "Included" lanes refer to lanes that were worked on during this render. It's
// slightly different than `renderLanes` because `renderLanes` can change as you
// enter and exit an Offscreen tree. This value is the combination of all render
// lanes for the entire render phase.
var workInProgressRootIncludedLanes=NoLanes;// The work left over by components that were visited during this render. Only
// includes unprocessed updates, not work in bailed out children.
var workInProgressRootSkippedLanes=NoLanes;// Lanes that were updated (in an interleaved event) during this render.
var workInProgressRootUpdatedLanes=NoLanes;// Lanes that were pinged (in an interleaved event) during this render.
var workInProgressRootPingedLanes=NoLanes;var mostRecentlyUpdatedRoot=null;// The most recent time we committed a fallback. This lets us ensure a train
// model where we don't commit new loading states in too quick succession.
var globalMostRecentFallbackTime=0;var FALLBACK_THROTTLE_MS=500;// The absolute time for when we should start giving up on rendering
// more and prefer CPU suspense heuristics instead.
var workInProgressRootRenderTargetTime=Infinity;// How long a render is supposed to take before we start following CPU
// suspense heuristics and opt out of rendering more content.
var RENDER_TIMEOUT_MS=500;function resetRenderTimer(){workInProgressRootRenderTargetTime=now()+RENDER_TIMEOUT_MS;}function getRenderTargetTime(){return workInProgressRootRenderTargetTime;}var nextEffect=null;var hasUncaughtError=false;var firstUncaughtError=null;var legacyErrorBoundariesThatAlreadyFailed=null;var rootDoesHavePassiveEffects=false;var rootWithPendingPassiveEffects=null;var pendingPassiveEffectsRenderPriority=NoPriority$1;var pendingPassiveEffectsLanes=NoLanes;var pendingPassiveHookEffectsMount=[];var pendingPassiveHookEffectsUnmount=[];var rootsWithPendingDiscreteUpdates=null;// Use these to prevent an infinite loop of nested updates
var NESTED_UPDATE_LIMIT=50;var nestedUpdateCount=0;var rootWithNestedUpdates=null;var NESTED_PASSIVE_UPDATE_LIMIT=50;var nestedPassiveUpdateCount=0;// Marks the need to reschedule pending interactions at these lanes
// during the commit phase. This enables them to be traced across components
// that spawn new work during render. E.g. hidden boundaries, suspended SSR
// hydration or SuspenseList.
// TODO: Can use a bitmask instead of an array
var spawnedWorkDuringRender=null;// If two updates are scheduled within the same event, we should treat their
// event times as simultaneous, even if the actual clock time has advanced
// between the first and second call.
var currentEventTime=NoTimestamp;var currentEventWipLanes=NoLanes;var currentEventPendingLanes=NoLanes;// Dev only flag that tracks if passive effects are currently being flushed.
// We warn about state updates for unmounted components differently in this case.
var isFlushingPassiveEffects=false;var focusedInstanceHandle=null;var shouldFireAfterActiveInstanceBlur=false;function getWorkInProgressRoot(){return workInProgressRoot;}function requestEventTime(){if((executionContext&(RenderContext|CommitContext))!==NoContext){// We're inside React, so it's fine to read the actual time.
return now();}// We're not inside React, so we may be in the middle of a browser event.
if(currentEventTime!==NoTimestamp){// Use the same start time for all updates until we enter React again.
return currentEventTime;}// This is the first update since React yielded. Compute a new start time.
currentEventTime=now();return currentEventTime;}function requestUpdateLane(fiber){// Special cases
var mode=fiber.mode;if((mode&BlockingMode)===NoMode){return SyncLane;}else if((mode&ConcurrentMode)===NoMode){return getCurrentPriorityLevel()===ImmediatePriority$1?SyncLane:SyncBatchedLane;}// The algorithm for assigning an update to a lane should be stable for all
// updates at the same priority within the same event. To do this, the inputs
// to the algorithm must be the same. For example, we use the `renderLanes`
// to avoid choosing a lane that is already in the middle of rendering.
//
// However, the "included" lanes could be mutated in between updates in the
// same event, like if you perform an update inside `flushSync`. Or any other
// code path that might call `prepareFreshStack`.
//
// The trick we use is to cache the first of each of these inputs within an
// event. Then reset the cached values once we can be sure the event is over.
// Our heuristic for that is whenever we enter a concurrent work loop.
//
// We'll do the same for `currentEventPendingLanes` below.
if(currentEventWipLanes===NoLanes){currentEventWipLanes=workInProgressRootIncludedLanes;}var isTransition=requestCurrentTransition()!==NoTransition;if(isTransition){if(currentEventPendingLanes!==NoLanes){currentEventPendingLanes=mostRecentlyUpdatedRoot!==null?mostRecentlyUpdatedRoot.pendingLanes:NoLanes;}return findTransitionLane(currentEventWipLanes,currentEventPendingLanes);}// TODO: Remove this dependency on the Scheduler priority.
// To do that, we're replacing it with an update lane priority.
var schedulerPriority=getCurrentPriorityLevel();// The old behavior was using the priority level of the Scheduler.
// This couples React to the Scheduler internals, so we're replacing it
// with the currentUpdateLanePriority above. As an example of how this
// could be problematic, if we're not inside `Scheduler.runWithPriority`,
// then we'll get the priority of the current running Scheduler task,
// which is probably not what we want.
var lane;if(// TODO: Temporary. We're removing the concept of discrete updates.
(executionContext&DiscreteEventContext)!==NoContext&&schedulerPriority===UserBlockingPriority$2){lane=findUpdateLane(InputDiscreteLanePriority,currentEventWipLanes);}else {var schedulerLanePriority=schedulerPriorityToLanePriority(schedulerPriority);lane=findUpdateLane(schedulerLanePriority,currentEventWipLanes);}return lane;}function requestRetryLane(fiber){// This is a fork of `requestUpdateLane` designed specifically for Suspense
// "retries" — a special update that attempts to flip a Suspense boundary
// from its placeholder state to its primary/resolved state.
// Special cases
var mode=fiber.mode;if((mode&BlockingMode)===NoMode){return SyncLane;}else if((mode&ConcurrentMode)===NoMode){return getCurrentPriorityLevel()===ImmediatePriority$1?SyncLane:SyncBatchedLane;}// See `requestUpdateLane` for explanation of `currentEventWipLanes`
if(currentEventWipLanes===NoLanes){currentEventWipLanes=workInProgressRootIncludedLanes;}return findRetryLane(currentEventWipLanes);}function scheduleUpdateOnFiber(fiber,lane,eventTime){checkForNestedUpdates();warnAboutRenderPhaseUpdatesInDEV(fiber);var root=markUpdateLaneFromFiberToRoot(fiber,lane);if(root===null){warnAboutUpdateOnUnmountedFiberInDEV(fiber);return null;}// Mark that the root has a pending update.
markRootUpdated(root,lane,eventTime);if(root===workInProgressRoot){// Received an update to a tree that's in the middle of rendering. Mark
// that there was an interleaved update work on this root. Unless the
// `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
// phase update. In that case, we don't treat render phase updates as if
// they were interleaved, for backwards compat reasons.
{workInProgressRootUpdatedLanes=mergeLanes(workInProgressRootUpdatedLanes,lane);}if(workInProgressRootExitStatus===RootSuspendedWithDelay){// The root already suspended with a delay, which means this render
// definitely won't finish. Since we have a new update, let's mark it as
// suspended now, right before marking the incoming update. This has the
// effect of interrupting the current render and switching to the update.
// TODO: Make sure this doesn't override pings that happen while we've
// already started rendering.
markRootSuspended$1(root,workInProgressRootRenderLanes);}}// TODO: requestUpdateLanePriority also reads the priority. Pass the
// priority as an argument to that function and this one.
var priorityLevel=getCurrentPriorityLevel();if(lane===SyncLane){if(// Check if we're inside unbatchedUpdates
(executionContext&LegacyUnbatchedContext)!==NoContext&&// Check if we're not already rendering
(executionContext&(RenderContext|CommitContext))===NoContext){// Register pending interactions on the root to avoid losing traced interaction data.
schedulePendingInteractions(root,lane);// This is a legacy edge case. The initial mount of a ReactDOM.render-ed
// root inside of batchedUpdates should be synchronous, but layout updates
// should be deferred until the end of the batch.
performSyncWorkOnRoot(root);}else {ensureRootIsScheduled(root,eventTime);schedulePendingInteractions(root,lane);if(executionContext===NoContext){// Flush the synchronous work now, unless we're already working or inside
// a batch. This is intentionally inside scheduleUpdateOnFiber instead of
// scheduleCallbackForFiber to preserve the ability to schedule a callback
// without immediately flushing it. We only do this for user-initiated
// updates, to preserve historical behavior of legacy mode.
resetRenderTimer();flushSyncCallbackQueue();}}}else {// Schedule a discrete update but only if it's not Sync.
if((executionContext&DiscreteEventContext)!==NoContext&&(// Only updates at user-blocking priority or greater are considered
// discrete, even inside a discrete event.
priorityLevel===UserBlockingPriority$2||priorityLevel===ImmediatePriority$1)){// This is the result of a discrete event. Track the lowest priority
// discrete update per root so we can flush them early, if needed.
if(rootsWithPendingDiscreteUpdates===null){rootsWithPendingDiscreteUpdates=new Set([root]);}else {rootsWithPendingDiscreteUpdates.add(root);}}// Schedule other updates after in case the callback is sync.
ensureRootIsScheduled(root,eventTime);schedulePendingInteractions(root,lane);}// We use this when assigning a lane for a transition inside
// `requestUpdateLane`. We assume it's the same as the root being updated,
// since in the common case of a single root app it probably is. If it's not
// the same root, then it's not a huge deal, we just might batch more stuff
// together more than necessary.
mostRecentlyUpdatedRoot=root;}// This is split into a separate function so we can mark a fiber with pending
// work without treating it as a typical update that originates from an event;
// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
// on a fiber.
function markUpdateLaneFromFiberToRoot(sourceFiber,lane){// Update the source fiber's lanes
sourceFiber.lanes=mergeLanes(sourceFiber.lanes,lane);var alternate=sourceFiber.alternate;if(alternate!==null){alternate.lanes=mergeLanes(alternate.lanes,lane);}{if(alternate===null&&(sourceFiber.flags&(Placement|Hydrating))!==NoFlags){warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);}}// Walk the parent path to the root and update the child expiration time.
var node=sourceFiber;var parent=sourceFiber.return;while(parent!==null){parent.childLanes=mergeLanes(parent.childLanes,lane);alternate=parent.alternate;if(alternate!==null){alternate.childLanes=mergeLanes(alternate.childLanes,lane);}else {{if((parent.flags&(Placement|Hydrating))!==NoFlags){warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);}}}node=parent;parent=parent.return;}if(node.tag===HostRoot){var root=node.stateNode;return root;}else {return null;}}// Use this function to schedule a task for a root. There's only one task per
// root; if a task was already scheduled, we'll check to make sure the priority
// of the existing task is the same as the priority of the next level that the
// root has work on. This function is called on every update, and right before
// exiting a task.
function ensureRootIsScheduled(root,currentTime){var existingCallbackNode=root.callbackNode;// Check if any lanes are being starved by other work. If so, mark them as
// expired so we know to work on those next.
markStarvedLanesAsExpired(root,currentTime);// Determine the next lanes to work on, and their priority.
var nextLanes=getNextLanes(root,root===workInProgressRoot?workInProgressRootRenderLanes:NoLanes);// This returns the priority level computed during the `getNextLanes` call.
var newCallbackPriority=returnNextLanesPriority();if(nextLanes===NoLanes){// Special case: There's nothing to work on.
if(existingCallbackNode!==null){cancelCallback(existingCallbackNode);root.callbackNode=null;root.callbackPriority=NoLanePriority;}return;}// Check if there's an existing task. We may be able to reuse it.
if(existingCallbackNode!==null){var existingCallbackPriority=root.callbackPriority;if(existingCallbackPriority===newCallbackPriority){// The priority hasn't changed. We can reuse the existing task. Exit.
return;}// The priority changed. Cancel the existing callback. We'll schedule a new
// one below.
cancelCallback(existingCallbackNode);}// Schedule a new callback.
var newCallbackNode;if(newCallbackPriority===SyncLanePriority){// Special case: Sync React callbacks are scheduled on a special
// internal queue
newCallbackNode=scheduleSyncCallback(performSyncWorkOnRoot.bind(null,root));}else if(newCallbackPriority===SyncBatchedLanePriority){newCallbackNode=scheduleCallback(ImmediatePriority$1,performSyncWorkOnRoot.bind(null,root));}else {var schedulerPriorityLevel=lanePriorityToSchedulerPriority(newCallbackPriority);newCallbackNode=scheduleCallback(schedulerPriorityLevel,performConcurrentWorkOnRoot.bind(null,root));}root.callbackPriority=newCallbackPriority;root.callbackNode=newCallbackNode;}// This is the entry point for every concurrent task, i.e. anything that
// goes through Scheduler.
function performConcurrentWorkOnRoot(root){// Since we know we're in a React event, we can clear the current
// event time. The next update will compute a new event time.
currentEventTime=NoTimestamp;currentEventWipLanes=NoLanes;currentEventPendingLanes=NoLanes;if(!((executionContext&(RenderContext|CommitContext))===NoContext)){{throw Error("Should not already be working.");}}// Flush any pending passive effects before deciding which lanes to work on,
// in case they schedule additional work.
var originalCallbackNode=root.callbackNode;var didFlushPassiveEffects=flushPassiveEffects();if(didFlushPassiveEffects){// Something in the passive effect phase may have canceled the current task.
// Check if the task node for this root was changed.
if(root.callbackNode!==originalCallbackNode){// The current task was canceled. Exit. We don't need to call
// `ensureRootIsScheduled` because the check above implies either that
// there's a new task, or that there's no remaining work on this root.
return null;}}// Determine the next expiration time to work on, using the fields stored
// on the root.
var lanes=getNextLanes(root,root===workInProgressRoot?workInProgressRootRenderLanes:NoLanes);if(lanes===NoLanes){// Defensive coding. This is never expected to happen.
return null;}var exitStatus=renderRootConcurrent(root,lanes);if(includesSomeLane(workInProgressRootIncludedLanes,workInProgressRootUpdatedLanes)){// The render included lanes that were updated during the render phase.
// For example, when unhiding a hidden tree, we include all the lanes
// that were previously skipped when the tree was hidden. That set of
// lanes is a superset of the lanes we started rendering with.
//
// So we'll throw out the current work and restart.
prepareFreshStack(root,NoLanes);}else if(exitStatus!==RootIncomplete){if(exitStatus===RootErrored){executionContext|=RetryAfterError;// If an error occurred during hydration,
// discard server response and fall back to client side render.
if(root.hydrate){root.hydrate=false;clearContainer(root.containerInfo);}// If something threw an error, try rendering one more time. We'll render
// synchronously to block concurrent data mutations, and we'll includes
// all pending updates are included. If it still fails after the second
// attempt, we'll give up and commit the resulting tree.
lanes=getLanesToRetrySynchronouslyOnError(root);if(lanes!==NoLanes){exitStatus=renderRootSync(root,lanes);}}if(exitStatus===RootFatalErrored){var fatalError=workInProgressRootFatalError;prepareFreshStack(root,NoLanes);markRootSuspended$1(root,lanes);ensureRootIsScheduled(root,now());throw fatalError;}// We now have a consistent tree. The next step is either to commit it,
// or, if something suspended, wait to commit it after a timeout.
var finishedWork=root.current.alternate;root.finishedWork=finishedWork;root.finishedLanes=lanes;finishConcurrentRender(root,exitStatus,lanes);}ensureRootIsScheduled(root,now());if(root.callbackNode===originalCallbackNode){// The task node scheduled for this root is the same one that's
// currently executed. Need to return a continuation.
return performConcurrentWorkOnRoot.bind(null,root);}return null;}function finishConcurrentRender(root,exitStatus,lanes){switch(exitStatus){case RootIncomplete:case RootFatalErrored:{{{throw Error("Root did not complete. This is a bug in React.");}}}// Flow knows about invariant, so it complains if I add a break
// statement, but eslint doesn't know about invariant, so it complains
// if I do. eslint-disable-next-line no-fallthrough
case RootErrored:{// We should have already attempted to retry this tree. If we reached
// this point, it errored again. Commit it.
commitRoot(root);break;}case RootSuspended:{markRootSuspended$1(root,lanes);// We have an acceptable loading state. We need to figure out if we
// should immediately commit it or wait a bit.
if(includesOnlyRetries(lanes)&&// do not delay if we're inside an act() scope
!shouldForceFlushFallbacksInDEV()){// This render only included retries, no updates. Throttle committing
// retries so that we don't show too many loading states too quickly.
var msUntilTimeout=globalMostRecentFallbackTime+FALLBACK_THROTTLE_MS-now();// Don't bother with a very short suspense time.
if(msUntilTimeout>10){var nextLanes=getNextLanes(root,NoLanes);if(nextLanes!==NoLanes){// There's additional work on this root.
break;}var suspendedLanes=root.suspendedLanes;if(!isSubsetOfLanes(suspendedLanes,lanes)){// We should prefer to render the fallback of at the last
// suspended level. Ping the last suspended level to try
// rendering it again.
// FIXME: What if the suspended lanes are Idle? Should not restart.
var eventTime=requestEventTime();markRootPinged(root,suspendedLanes);break;}// The render is suspended, it hasn't timed out, and there's no
// lower priority work to do. Instead of committing the fallback
// immediately, wait for more data to arrive.
root.timeoutHandle=scheduleTimeout(commitRoot.bind(null,root),msUntilTimeout);break;}}// The work expired. Commit immediately.
commitRoot(root);break;}case RootSuspendedWithDelay:{markRootSuspended$1(root,lanes);if(includesOnlyTransitions(lanes)){// This is a transition, so we should exit without committing a
// placeholder and without scheduling a timeout. Delay indefinitely
// until we receive more data.
break;}{// This is not a transition, but we did trigger an avoided state.
// Schedule a placeholder to display after a short delay, using the Just
// Noticeable Difference.
// TODO: Is the JND optimization worth the added complexity? If this is
// the only reason we track the event time, then probably not.
// Consider removing.
var mostRecentEventTime=getMostRecentEventTime(root,lanes);var eventTimeMs=mostRecentEventTime;var timeElapsedMs=now()-eventTimeMs;var _msUntilTimeout=jnd(timeElapsedMs)-timeElapsedMs;// Don't bother with a very short suspense time.
if(_msUntilTimeout>10){// Instead of committing the fallback immediately, wait for more data
// to arrive.
root.timeoutHandle=scheduleTimeout(commitRoot.bind(null,root),_msUntilTimeout);break;}}// Commit the placeholder.
commitRoot(root);break;}case RootCompleted:{// The work completed. Ready to commit.
commitRoot(root);break;}default:{{{throw Error("Unknown root exit status.");}}}}}function markRootSuspended$1(root,suspendedLanes){// When suspending, we should always exclude lanes that were pinged or (more
// rarely, since we try to avoid it) updated during the render phase.
// TODO: Lol maybe there's a better way to factor this besides this
// obnoxiously named function :)
suspendedLanes=removeLanes(suspendedLanes,workInProgressRootPingedLanes);suspendedLanes=removeLanes(suspendedLanes,workInProgressRootUpdatedLanes);markRootSuspended(root,suspendedLanes);}// This is the entry point for synchronous tasks that don't go
// through Scheduler
function performSyncWorkOnRoot(root){if(!((executionContext&(RenderContext|CommitContext))===NoContext)){{throw Error("Should not already be working.");}}flushPassiveEffects();var lanes;var exitStatus;if(root===workInProgressRoot&&includesSomeLane(root.expiredLanes,workInProgressRootRenderLanes)){// There's a partial tree, and at least one of its lanes has expired. Finish
// rendering it before rendering the rest of the expired work.
lanes=workInProgressRootRenderLanes;exitStatus=renderRootSync(root,lanes);if(includesSomeLane(workInProgressRootIncludedLanes,workInProgressRootUpdatedLanes)){// The render included lanes that were updated during the render phase.
// For example, when unhiding a hidden tree, we include all the lanes
// that were previously skipped when the tree was hidden. That set of
// lanes is a superset of the lanes we started rendering with.
//
// Note that this only happens when part of the tree is rendered
// concurrently. If the whole tree is rendered synchronously, then there
// are no interleaved events.
lanes=getNextLanes(root,lanes);exitStatus=renderRootSync(root,lanes);}}else {lanes=getNextLanes(root,NoLanes);exitStatus=renderRootSync(root,lanes);}if(root.tag!==LegacyRoot&&exitStatus===RootErrored){executionContext|=RetryAfterError;// If an error occurred during hydration,
// discard server response and fall back to client side render.
if(root.hydrate){root.hydrate=false;clearContainer(root.containerInfo);}// If something threw an error, try rendering one more time. We'll render
// synchronously to block concurrent data mutations, and we'll includes
// all pending updates are included. If it still fails after the second
// attempt, we'll give up and commit the resulting tree.
lanes=getLanesToRetrySynchronouslyOnError(root);if(lanes!==NoLanes){exitStatus=renderRootSync(root,lanes);}}if(exitStatus===RootFatalErrored){var fatalError=workInProgressRootFatalError;prepareFreshStack(root,NoLanes);markRootSuspended$1(root,lanes);ensureRootIsScheduled(root,now());throw fatalError;}// We now have a consistent tree. Because this is a sync render, we
// will commit it even if something suspended.
var finishedWork=root.current.alternate;root.finishedWork=finishedWork;root.finishedLanes=lanes;commitRoot(root);// Before exiting, make sure there's a callback scheduled for the next
// pending level.
ensureRootIsScheduled(root,now());return null;}function flushDiscreteUpdates(){// TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
// However, `act` uses `batchedUpdates`, so there's no way to distinguish
// those two cases. Need to fix this before exposing flushDiscreteUpdates
// as a public API.
if((executionContext&(BatchedContext|RenderContext|CommitContext))!==NoContext){{if((executionContext&RenderContext)!==NoContext){error('unstable_flushDiscreteUpdates: Cannot flush updates when React is '+'already rendering.');}}// We're already rendering, so we can't synchronously flush pending work.
// This is probably a nested event dispatch triggered by a lifecycle/effect,
// like `el.focus()`. Exit.
return;}flushPendingDiscreteUpdates();// If the discrete updates scheduled passive effects, flush them now so that
// they fire before the next serial event.
flushPassiveEffects();}function flushPendingDiscreteUpdates(){if(rootsWithPendingDiscreteUpdates!==null){// For each root with pending discrete updates, schedule a callback to
// immediately flush them.
var roots=rootsWithPendingDiscreteUpdates;rootsWithPendingDiscreteUpdates=null;roots.forEach(function(root){markDiscreteUpdatesExpired(root);ensureRootIsScheduled(root,now());});}// Now flush the immediate queue.
flushSyncCallbackQueue();}function batchedUpdates$1(fn,a){var prevExecutionContext=executionContext;executionContext|=BatchedContext;try{return fn(a);}finally{executionContext=prevExecutionContext;if(executionContext===NoContext){// Flush the immediate callbacks that were scheduled during this batch
resetRenderTimer();flushSyncCallbackQueue();}}}function batchedEventUpdates$1(fn,a){var prevExecutionContext=executionContext;executionContext|=EventContext;try{return fn(a);}finally{executionContext=prevExecutionContext;if(executionContext===NoContext){// Flush the immediate callbacks that were scheduled during this batch
resetRenderTimer();flushSyncCallbackQueue();}}}function discreteUpdates$1(fn,a,b,c,d){var prevExecutionContext=executionContext;executionContext|=DiscreteEventContext;{try{return runWithPriority$1(UserBlockingPriority$2,fn.bind(null,a,b,c,d));}finally{executionContext=prevExecutionContext;if(executionContext===NoContext){// Flush the immediate callbacks that were scheduled during this batch
resetRenderTimer();flushSyncCallbackQueue();}}}}function unbatchedUpdates(fn,a){var prevExecutionContext=executionContext;executionContext&=~BatchedContext;executionContext|=LegacyUnbatchedContext;try{return fn(a);}finally{executionContext=prevExecutionContext;if(executionContext===NoContext){// Flush the immediate callbacks that were scheduled during this batch
resetRenderTimer();flushSyncCallbackQueue();}}}function flushSync(fn,a){var prevExecutionContext=executionContext;if((prevExecutionContext&(RenderContext|CommitContext))!==NoContext){{error('flushSync was called from inside a lifecycle method. React cannot '+'flush when React is already rendering. Consider moving this call to '+'a scheduler task or micro task.');}return fn(a);}executionContext|=BatchedContext;{try{if(fn){return runWithPriority$1(ImmediatePriority$1,fn.bind(null,a));}else {return undefined;}}finally{executionContext=prevExecutionContext;// Flush the immediate callbacks that were scheduled during this batch.
// Note that this will happen even if batchedUpdates is higher up
// the stack.
flushSyncCallbackQueue();}}}function pushRenderLanes(fiber,lanes){push(subtreeRenderLanesCursor,subtreeRenderLanes,fiber);subtreeRenderLanes=mergeLanes(subtreeRenderLanes,lanes);workInProgressRootIncludedLanes=mergeLanes(workInProgressRootIncludedLanes,lanes);}function popRenderLanes(fiber){subtreeRenderLanes=subtreeRenderLanesCursor.current;pop(subtreeRenderLanesCursor,fiber);}function prepareFreshStack(root,lanes){root.finishedWork=null;root.finishedLanes=NoLanes;var timeoutHandle=root.timeoutHandle;if(timeoutHandle!==noTimeout){// The root previous suspended and scheduled a timeout to commit a fallback
// state. Now that we have additional work, cancel the timeout.
root.timeoutHandle=noTimeout;// $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
cancelTimeout(timeoutHandle);}if(workInProgress!==null){var interruptedWork=workInProgress.return;while(interruptedWork!==null){unwindInterruptedWork(interruptedWork);interruptedWork=interruptedWork.return;}}workInProgressRoot=root;workInProgress=createWorkInProgress(root.current,null);workInProgressRootRenderLanes=subtreeRenderLanes=workInProgressRootIncludedLanes=lanes;workInProgressRootExitStatus=RootIncomplete;workInProgressRootFatalError=null;workInProgressRootSkippedLanes=NoLanes;workInProgressRootUpdatedLanes=NoLanes;workInProgressRootPingedLanes=NoLanes;{spawnedWorkDuringRender=null;}{ReactStrictModeWarnings.discardPendingWarnings();}}function handleError(root,thrownValue){do{var erroredWork=workInProgress;try{// Reset module-level state that was set during the render phase.
resetContextDependencies();resetHooksAfterThrow();resetCurrentFiber();// TODO: I found and added this missing line while investigating a
// separate issue. Write a regression test using string refs.
ReactCurrentOwner$2.current=null;if(erroredWork===null||erroredWork.return===null){// Expected to be working on a non-root fiber. This is a fatal error
// because there's no ancestor that can handle it; the root is
// supposed to capture all errors that weren't caught by an error
// boundary.
workInProgressRootExitStatus=RootFatalErrored;workInProgressRootFatalError=thrownValue;// Set `workInProgress` to null. This represents advancing to the next
// sibling, or the parent if there are no siblings. But since the root
// has no siblings nor a parent, we set it to null. Usually this is
// handled by `completeUnitOfWork` or `unwindWork`, but since we're
// intentionally not calling those, we need set it here.
// TODO: Consider calling `unwindWork` to pop the contexts.
workInProgress=null;return;}if(enableProfilerTimer&&erroredWork.mode&ProfileMode){// Record the time spent rendering before an error was thrown. This
// avoids inaccurate Profiler durations in the case of a
// suspended render.
stopProfilerTimerIfRunningAndRecordDelta(erroredWork,true);}throwException(root,erroredWork.return,erroredWork,thrownValue,workInProgressRootRenderLanes);completeUnitOfWork(erroredWork);}catch(yetAnotherThrownValue){// Something in the return path also threw.
thrownValue=yetAnotherThrownValue;if(workInProgress===erroredWork&&erroredWork!==null){// If this boundary has already errored, then we had trouble processing
// the error. Bubble it to the next boundary.
erroredWork=erroredWork.return;workInProgress=erroredWork;}else {erroredWork=workInProgress;}continue;}// Return to the normal work loop.
return;}while(true);}function pushDispatcher(){var prevDispatcher=ReactCurrentDispatcher$2.current;ReactCurrentDispatcher$2.current=ContextOnlyDispatcher;if(prevDispatcher===null){// The React isomorphic package does not include a default dispatcher.
// Instead the first renderer will lazily attach one, in order to give
// nicer error messages.
return ContextOnlyDispatcher;}else {return prevDispatcher;}}function popDispatcher(prevDispatcher){ReactCurrentDispatcher$2.current=prevDispatcher;}function pushInteractions(root){{var prevInteractions=tracing$1.__interactionsRef.current;tracing$1.__interactionsRef.current=root.memoizedInteractions;return prevInteractions;}}function popInteractions(prevInteractions){{tracing$1.__interactionsRef.current=prevInteractions;}}function markCommitTimeOfFallback(){globalMostRecentFallbackTime=now();}function markSkippedUpdateLanes(lane){workInProgressRootSkippedLanes=mergeLanes(lane,workInProgressRootSkippedLanes);}function renderDidSuspend(){if(workInProgressRootExitStatus===RootIncomplete){workInProgressRootExitStatus=RootSuspended;}}function renderDidSuspendDelayIfPossible(){if(workInProgressRootExitStatus===RootIncomplete||workInProgressRootExitStatus===RootSuspended){workInProgressRootExitStatus=RootSuspendedWithDelay;}// Check if there are updates that we skipped tree that might have unblocked
// this render.
if(workInProgressRoot!==null&&(includesNonIdleWork(workInProgressRootSkippedLanes)||includesNonIdleWork(workInProgressRootUpdatedLanes))){// Mark the current render as suspended so that we switch to working on
// the updates that were skipped. Usually we only suspend at the end of
// the render phase.
// TODO: We should probably always mark the root as suspended immediately
// (inside this function), since by suspending at the end of the render
// phase introduces a potential mistake where we suspend lanes that were
// pinged or updated while we were rendering.
markRootSuspended$1(workInProgressRoot,workInProgressRootRenderLanes);}}function renderDidError(){if(workInProgressRootExitStatus!==RootCompleted){workInProgressRootExitStatus=RootErrored;}}// Called during render to determine if anything has suspended.
// Returns false if we're not sure.
function renderHasNotSuspendedYet(){// If something errored or completed, we can't really be sure,
// so those are false.
return workInProgressRootExitStatus===RootIncomplete;}function renderRootSync(root,lanes){var prevExecutionContext=executionContext;executionContext|=RenderContext;var prevDispatcher=pushDispatcher();// If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if(workInProgressRoot!==root||workInProgressRootRenderLanes!==lanes){prepareFreshStack(root,lanes);startWorkOnPendingInteractions(root,lanes);}var prevInteractions=pushInteractions(root);do{try{workLoopSync();break;}catch(thrownValue){handleError(root,thrownValue);}}while(true);resetContextDependencies();{popInteractions(prevInteractions);}executionContext=prevExecutionContext;popDispatcher(prevDispatcher);if(workInProgress!==null){// This is a sync render, so we should have finished the whole tree.
{{throw Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");}}}workInProgressRoot=null;workInProgressRootRenderLanes=NoLanes;return workInProgressRootExitStatus;}// The work loop is an extremely hot path. Tell Closure not to inline it.
/** @noinline */function workLoopSync(){// Already timed out, so perform work without checking if we need to yield.
while(workInProgress!==null){performUnitOfWork(workInProgress);}}function renderRootConcurrent(root,lanes){var prevExecutionContext=executionContext;executionContext|=RenderContext;var prevDispatcher=pushDispatcher();// If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if(workInProgressRoot!==root||workInProgressRootRenderLanes!==lanes){resetRenderTimer();prepareFreshStack(root,lanes);startWorkOnPendingInteractions(root,lanes);}var prevInteractions=pushInteractions(root);do{try{workLoopConcurrent();break;}catch(thrownValue){handleError(root,thrownValue);}}while(true);resetContextDependencies();{popInteractions(prevInteractions);}popDispatcher(prevDispatcher);executionContext=prevExecutionContext;if(workInProgress!==null){return RootIncomplete;}else {workInProgressRoot=null;workInProgressRootRenderLanes=NoLanes;// Return the final exit status.
return workInProgressRootExitStatus;}}/** @noinline */function workLoopConcurrent(){// Perform work until Scheduler asks us to yield
while(workInProgress!==null&&!shouldYield()){performUnitOfWork(workInProgress);}}function performUnitOfWork(unitOfWork){// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
var current=unitOfWork.alternate;setCurrentFiber(unitOfWork);var next;if((unitOfWork.mode&ProfileMode)!==NoMode){startProfilerTimer(unitOfWork);next=beginWork$1(current,unitOfWork,subtreeRenderLanes);stopProfilerTimerIfRunningAndRecordDelta(unitOfWork,true);}else {next=beginWork$1(current,unitOfWork,subtreeRenderLanes);}resetCurrentFiber();unitOfWork.memoizedProps=unitOfWork.pendingProps;if(next===null){// If this doesn't spawn new work, complete the current work.
completeUnitOfWork(unitOfWork);}else {workInProgress=next;}ReactCurrentOwner$2.current=null;}function completeUnitOfWork(unitOfWork){// Attempt to complete the current unit of work, then move to the next
// sibling. If there are no more siblings, return to the parent fiber.
var completedWork=unitOfWork;do{// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
var current=completedWork.alternate;var returnFiber=completedWork.return;// Check if the work completed or if something threw.
if((completedWork.flags&Incomplete)===NoFlags){setCurrentFiber(completedWork);var next=void 0;if((completedWork.mode&ProfileMode)===NoMode){next=completeWork(current,completedWork,subtreeRenderLanes);}else {startProfilerTimer(completedWork);next=completeWork(current,completedWork,subtreeRenderLanes);// Update render duration assuming we didn't error.
stopProfilerTimerIfRunningAndRecordDelta(completedWork,false);}resetCurrentFiber();if(next!==null){// Completing this fiber spawned new work. Work on that next.
workInProgress=next;return;}resetChildLanes(completedWork);if(returnFiber!==null&&// Do not append effects to parents if a sibling failed to complete
(returnFiber.flags&Incomplete)===NoFlags){// Append all the effects of the subtree and this fiber onto the effect
// list of the parent. The completion order of the children affects the
// side-effect order.
if(returnFiber.firstEffect===null){returnFiber.firstEffect=completedWork.firstEffect;}if(completedWork.lastEffect!==null){if(returnFiber.lastEffect!==null){returnFiber.lastEffect.nextEffect=completedWork.firstEffect;}returnFiber.lastEffect=completedWork.lastEffect;}// If this fiber had side-effects, we append it AFTER the children's
// side-effects. We can perform certain side-effects earlier if needed,
// by doing multiple passes over the effect list. We don't want to
// schedule our own side-effect on our own list because if end up
// reusing children we'll schedule this effect onto itself since we're
// at the end.
var flags=completedWork.flags;// Skip both NoWork and PerformedWork tags when creating the effect
// list. PerformedWork effect is read by React DevTools but shouldn't be
// committed.
if(flags>PerformedWork){if(returnFiber.lastEffect!==null){returnFiber.lastEffect.nextEffect=completedWork;}else {returnFiber.firstEffect=completedWork;}returnFiber.lastEffect=completedWork;}}}else {// This fiber did not complete because something threw. Pop values off
// the stack without entering the complete phase. If this is a boundary,
// capture values if possible.
var _next=unwindWork(completedWork);// Because this fiber did not complete, don't reset its expiration time.
if(_next!==null){// If completing this work spawned new work, do that next. We'll come
// back here again.
// Since we're restarting, remove anything that is not a host effect
// from the effect tag.
_next.flags&=HostEffectMask;workInProgress=_next;return;}if((completedWork.mode&ProfileMode)!==NoMode){// Record the render duration for the fiber that errored.
stopProfilerTimerIfRunningAndRecordDelta(completedWork,false);// Include the time spent working on failed children before continuing.
var actualDuration=completedWork.actualDuration;var child=completedWork.child;while(child!==null){actualDuration+=child.actualDuration;child=child.sibling;}completedWork.actualDuration=actualDuration;}if(returnFiber!==null){// Mark the parent fiber as incomplete and clear its effect list.
returnFiber.firstEffect=returnFiber.lastEffect=null;returnFiber.flags|=Incomplete;}}var siblingFiber=completedWork.sibling;if(siblingFiber!==null){// If there is more work to do in this returnFiber, do that next.
workInProgress=siblingFiber;return;}// Otherwise, return to the parent
completedWork=returnFiber;// Update the next thing we're working on in case something throws.
workInProgress=completedWork;}while(completedWork!==null);// We've reached the root.
if(workInProgressRootExitStatus===RootIncomplete){workInProgressRootExitStatus=RootCompleted;}}function resetChildLanes(completedWork){if(// TODO: Move this check out of the hot path by moving `resetChildLanes`
// to switch statement in `completeWork`.
(completedWork.tag===LegacyHiddenComponent||completedWork.tag===OffscreenComponent)&&completedWork.memoizedState!==null&&!includesSomeLane(subtreeRenderLanes,OffscreenLane)&&(completedWork.mode&ConcurrentMode)!==NoLanes){// The children of this component are hidden. Don't bubble their
// expiration times.
return;}var newChildLanes=NoLanes;// Bubble up the earliest expiration time.
if((completedWork.mode&ProfileMode)!==NoMode){// In profiling mode, resetChildExpirationTime is also used to reset
// profiler durations.
var actualDuration=completedWork.actualDuration;var treeBaseDuration=completedWork.selfBaseDuration;// When a fiber is cloned, its actualDuration is reset to 0. This value will
// only be updated if work is done on the fiber (i.e. it doesn't bailout).
// When work is done, it should bubble to the parent's actualDuration. If
// the fiber has not been cloned though, (meaning no work was done), then
// this value will reflect the amount of time spent working on a previous
// render. In that case it should not bubble. We determine whether it was
// cloned by comparing the child pointer.
var shouldBubbleActualDurations=completedWork.alternate===null||completedWork.child!==completedWork.alternate.child;var child=completedWork.child;while(child!==null){newChildLanes=mergeLanes(newChildLanes,mergeLanes(child.lanes,child.childLanes));if(shouldBubbleActualDurations){actualDuration+=child.actualDuration;}treeBaseDuration+=child.treeBaseDuration;child=child.sibling;}var isTimedOutSuspense=completedWork.tag===SuspenseComponent&&completedWork.memoizedState!==null;if(isTimedOutSuspense){// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var primaryChildFragment=completedWork.child;if(primaryChildFragment!==null){treeBaseDuration-=primaryChildFragment.treeBaseDuration;}}completedWork.actualDuration=actualDuration;completedWork.treeBaseDuration=treeBaseDuration;}else {var _child=completedWork.child;while(_child!==null){newChildLanes=mergeLanes(newChildLanes,mergeLanes(_child.lanes,_child.childLanes));_child=_child.sibling;}}completedWork.childLanes=newChildLanes;}function commitRoot(root){var renderPriorityLevel=getCurrentPriorityLevel();runWithPriority$1(ImmediatePriority$1,commitRootImpl.bind(null,root,renderPriorityLevel));return null;}function commitRootImpl(root,renderPriorityLevel){do{// `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
// means `flushPassiveEffects` will sometimes result in additional
// passive effects. So we need to keep flushing in a loop until there are
// no more pending effects.
// TODO: Might be better if `flushPassiveEffects` did not automatically
// flush synchronous work at the end, to avoid factoring hazards like this.
flushPassiveEffects();}while(rootWithPendingPassiveEffects!==null);flushRenderPhaseStrictModeWarningsInDEV();if(!((executionContext&(RenderContext|CommitContext))===NoContext)){{throw Error("Should not already be working.");}}var finishedWork=root.finishedWork;var lanes=root.finishedLanes;if(finishedWork===null){return null;}root.finishedWork=null;root.finishedLanes=NoLanes;if(!(finishedWork!==root.current)){{throw Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");}}// commitRoot never returns a continuation; it always finishes synchronously.
// So we can clear these now to allow a new callback to be scheduled.
root.callbackNode=null;// Update the first and last pending times on this root. The new first
// pending time is whatever is left on the root fiber.
var remainingLanes=mergeLanes(finishedWork.lanes,finishedWork.childLanes);markRootFinished(root,remainingLanes);// Clear already finished discrete updates in case that a later call of
// `flushDiscreteUpdates` starts a useless render pass which may cancels
// a scheduled timeout.
if(rootsWithPendingDiscreteUpdates!==null){if(!hasDiscreteLanes(remainingLanes)&&rootsWithPendingDiscreteUpdates.has(root)){rootsWithPendingDiscreteUpdates.delete(root);}}if(root===workInProgressRoot){// We can reset these now that they are finished.
workInProgressRoot=null;workInProgress=null;workInProgressRootRenderLanes=NoLanes;}// Get the list of effects.
var firstEffect;if(finishedWork.flags>PerformedWork){// A fiber's effect list consists only of its children, not itself. So if
// the root has an effect, we need to add it to the end of the list. The
// resulting list is the set that would belong to the root's parent, if it
// had one; that is, all the effects in the tree including the root.
if(finishedWork.lastEffect!==null){finishedWork.lastEffect.nextEffect=finishedWork;firstEffect=finishedWork.firstEffect;}else {firstEffect=finishedWork;}}else {// There is no effect on the root.
firstEffect=finishedWork.firstEffect;}if(firstEffect!==null){var prevExecutionContext=executionContext;executionContext|=CommitContext;var prevInteractions=pushInteractions(root);// Reset this to null before calling lifecycles
ReactCurrentOwner$2.current=null;// The commit phase is broken into several sub-phases. We do a separate pass
// of the effect list for each phase: all mutation effects come before all
// layout effects, and so on.
// The first phase a "before mutation" phase. We use this phase to read the
// state of the host tree right before we mutate it. This is where
// getSnapshotBeforeUpdate is called.
focusedInstanceHandle=prepareForCommit(root.containerInfo);shouldFireAfterActiveInstanceBlur=false;nextEffect=firstEffect;do{{invokeGuardedCallback(null,commitBeforeMutationEffects,null);if(hasCaughtError()){if(!(nextEffect!==null)){{throw Error("Should be working on an effect.");}}var error=clearCaughtError();captureCommitPhaseError(nextEffect,error);nextEffect=nextEffect.nextEffect;}}}while(nextEffect!==null);// We no longer need to track the active instance fiber
focusedInstanceHandle=null;{// Mark the current commit time to be shared by all Profilers in this
// batch. This enables them to be grouped later.
recordCommitTime();}// The next phase is the mutation phase, where we mutate the host tree.
nextEffect=firstEffect;do{{invokeGuardedCallback(null,commitMutationEffects,null,root,renderPriorityLevel);if(hasCaughtError()){if(!(nextEffect!==null)){{throw Error("Should be working on an effect.");}}var _error=clearCaughtError();captureCommitPhaseError(nextEffect,_error);nextEffect=nextEffect.nextEffect;}}}while(nextEffect!==null);resetAfterCommit(root.containerInfo);// The work-in-progress tree is now the current tree. This must come after
// the mutation phase, so that the previous tree is still current during
// componentWillUnmount, but before the layout phase, so that the finished
// work is current during componentDidMount/Update.
root.current=finishedWork;// The next phase is the layout phase, where we call effects that read
// the host tree after it's been mutated. The idiomatic use case for this is
// layout, but class component lifecycles also fire here for legacy reasons.
nextEffect=firstEffect;do{{invokeGuardedCallback(null,commitLayoutEffects,null,root,lanes);if(hasCaughtError()){if(!(nextEffect!==null)){{throw Error("Should be working on an effect.");}}var _error2=clearCaughtError();captureCommitPhaseError(nextEffect,_error2);nextEffect=nextEffect.nextEffect;}}}while(nextEffect!==null);nextEffect=null;// Tell Scheduler to yield at the end of the frame, so the browser has an
// opportunity to paint.
requestPaint();{popInteractions(prevInteractions);}executionContext=prevExecutionContext;}else {// No effects.
root.current=finishedWork;// Measure these anyway so the flamegraph explicitly shows that there were
// no effects.
// TODO: Maybe there's a better way to report this.
{recordCommitTime();}}var rootDidHavePassiveEffects=rootDoesHavePassiveEffects;if(rootDoesHavePassiveEffects){// This commit has passive effects. Stash a reference to them. But don't
// schedule a callback until after flushing layout work.
rootDoesHavePassiveEffects=false;rootWithPendingPassiveEffects=root;pendingPassiveEffectsLanes=lanes;pendingPassiveEffectsRenderPriority=renderPriorityLevel;}else {// We are done with the effect chain at this point so let's clear the
// nextEffect pointers to assist with GC. If we have passive effects, we'll
// clear this in flushPassiveEffects.
nextEffect=firstEffect;while(nextEffect!==null){var nextNextEffect=nextEffect.nextEffect;nextEffect.nextEffect=null;if(nextEffect.flags&Deletion){detachFiberAfterEffects(nextEffect);}nextEffect=nextNextEffect;}}// Read this again, since an effect might have updated it
remainingLanes=root.pendingLanes;// Check if there's remaining work on this root
if(remainingLanes!==NoLanes){{if(spawnedWorkDuringRender!==null){var expirationTimes=spawnedWorkDuringRender;spawnedWorkDuringRender=null;for(var i=0;i<expirationTimes.length;i++){scheduleInteractions(root,expirationTimes[i],root.memoizedInteractions);}}schedulePendingInteractions(root,remainingLanes);}}else {// If there's no remaining work, we can clear the set of already failed
// error boundaries.
legacyErrorBoundariesThatAlreadyFailed=null;}{if(!rootDidHavePassiveEffects){// If there are no passive effects, then we can complete the pending interactions.
// Otherwise, we'll wait until after the passive effects are flushed.
// Wait to do this until after remaining work has been scheduled,
// so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
finishPendingInteractions(root,lanes);}}if(remainingLanes===SyncLane){// Count the number of times the root synchronously re-renders without
// finishing. If there are too many, it indicates an infinite update loop.
if(root===rootWithNestedUpdates){nestedUpdateCount++;}else {nestedUpdateCount=0;rootWithNestedUpdates=root;}}else {nestedUpdateCount=0;}onCommitRoot(finishedWork.stateNode,renderPriorityLevel);{onCommitRoot$1();}// Always call this before exiting `commitRoot`, to ensure that any
// additional work on this root is scheduled.
ensureRootIsScheduled(root,now());if(hasUncaughtError){hasUncaughtError=false;var _error3=firstUncaughtError;firstUncaughtError=null;throw _error3;}if((executionContext&LegacyUnbatchedContext)!==NoContext){// a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
// synchronously, but layout updates should be deferred until the end
// of the batch.
return null;}// If layout work was scheduled, flush it now.
flushSyncCallbackQueue();return null;}function commitBeforeMutationEffects(){while(nextEffect!==null){var current=nextEffect.alternate;if(!shouldFireAfterActiveInstanceBlur&&focusedInstanceHandle!==null){if((nextEffect.flags&Deletion)!==NoFlags){if(doesFiberContain(nextEffect,focusedInstanceHandle)){shouldFireAfterActiveInstanceBlur=true;}}else {// TODO: Move this out of the hot path using a dedicated effect tag.
if(nextEffect.tag===SuspenseComponent&&isSuspenseBoundaryBeingHidden(current,nextEffect)&&doesFiberContain(nextEffect,focusedInstanceHandle)){shouldFireAfterActiveInstanceBlur=true;}}}var flags=nextEffect.flags;if((flags&Snapshot)!==NoFlags){setCurrentFiber(nextEffect);commitBeforeMutationLifeCycles(current,nextEffect);resetCurrentFiber();}if((flags&Passive)!==NoFlags){// If there are passive effects, schedule a callback to flush at
// the earliest opportunity.
if(!rootDoesHavePassiveEffects){rootDoesHavePassiveEffects=true;scheduleCallback(NormalPriority$1,function(){flushPassiveEffects();return null;});}}nextEffect=nextEffect.nextEffect;}}function commitMutationEffects(root,renderPriorityLevel){// TODO: Should probably move the bulk of this function to commitWork.
while(nextEffect!==null){setCurrentFiber(nextEffect);var flags=nextEffect.flags;if(flags&ContentReset){commitResetTextContent(nextEffect);}if(flags&Ref){var current=nextEffect.alternate;if(current!==null){commitDetachRef(current);}}// The following switch statement is only concerned about placement,
// updates, and deletions. To avoid needing to add a case for every possible
// bitmap value, we remove the secondary effects from the effect tag and
// switch on that value.
var primaryFlags=flags&(Placement|Update|Deletion|Hydrating);switch(primaryFlags){case Placement:{commitPlacement(nextEffect);// Clear the "placement" from effect tag so that we know that this is
// inserted, before any life-cycles like componentDidMount gets called.
// TODO: findDOMNode doesn't rely on this any more but isMounted does
// and isMounted is deprecated anyway so we should be able to kill this.
nextEffect.flags&=~Placement;break;}case PlacementAndUpdate:{// Placement
commitPlacement(nextEffect);// Clear the "placement" from effect tag so that we know that this is
// inserted, before any life-cycles like componentDidMount gets called.
nextEffect.flags&=~Placement;// Update
var _current=nextEffect.alternate;commitWork(_current,nextEffect);break;}case Hydrating:{nextEffect.flags&=~Hydrating;break;}case HydratingAndUpdate:{nextEffect.flags&=~Hydrating;// Update
var _current2=nextEffect.alternate;commitWork(_current2,nextEffect);break;}case Update:{var _current3=nextEffect.alternate;commitWork(_current3,nextEffect);break;}case Deletion:{commitDeletion(root,nextEffect);break;}}resetCurrentFiber();nextEffect=nextEffect.nextEffect;}}function commitLayoutEffects(root,committedLanes){while(nextEffect!==null){setCurrentFiber(nextEffect);var flags=nextEffect.flags;if(flags&(Update|Callback)){var current=nextEffect.alternate;commitLifeCycles(root,current,nextEffect);}{if(flags&Ref){commitAttachRef(nextEffect);}}resetCurrentFiber();nextEffect=nextEffect.nextEffect;}}function flushPassiveEffects(){// Returns whether passive effects were flushed.
if(pendingPassiveEffectsRenderPriority!==NoPriority$1){var priorityLevel=pendingPassiveEffectsRenderPriority>NormalPriority$1?NormalPriority$1:pendingPassiveEffectsRenderPriority;pendingPassiveEffectsRenderPriority=NoPriority$1;{return runWithPriority$1(priorityLevel,flushPassiveEffectsImpl);}}return false;}function enqueuePendingPassiveHookEffectMount(fiber,effect){pendingPassiveHookEffectsMount.push(effect,fiber);if(!rootDoesHavePassiveEffects){rootDoesHavePassiveEffects=true;scheduleCallback(NormalPriority$1,function(){flushPassiveEffects();return null;});}}function enqueuePendingPassiveHookEffectUnmount(fiber,effect){pendingPassiveHookEffectsUnmount.push(effect,fiber);{fiber.flags|=PassiveUnmountPendingDev;var alternate=fiber.alternate;if(alternate!==null){alternate.flags|=PassiveUnmountPendingDev;}}if(!rootDoesHavePassiveEffects){rootDoesHavePassiveEffects=true;scheduleCallback(NormalPriority$1,function(){flushPassiveEffects();return null;});}}function invokePassiveEffectCreate(effect){var create=effect.create;effect.destroy=create();}function flushPassiveEffectsImpl(){if(rootWithPendingPassiveEffects===null){return false;}var root=rootWithPendingPassiveEffects;var lanes=pendingPassiveEffectsLanes;rootWithPendingPassiveEffects=null;pendingPassiveEffectsLanes=NoLanes;if(!((executionContext&(RenderContext|CommitContext))===NoContext)){{throw Error("Cannot flush passive effects while already rendering.");}}{isFlushingPassiveEffects=true;}var prevExecutionContext=executionContext;executionContext|=CommitContext;var prevInteractions=pushInteractions(root);// It's important that ALL pending passive effect destroy functions are called
// before ANY passive effect create functions are called.
// Otherwise effects in sibling components might interfere with each other.
// e.g. a destroy function in one component may unintentionally override a ref
// value set by a create function in another component.
// Layout effects have the same constraint.
// First pass: Destroy stale passive effects.
var unmountEffects=pendingPassiveHookEffectsUnmount;pendingPassiveHookEffectsUnmount=[];for(var i=0;i<unmountEffects.length;i+=2){var _effect=unmountEffects[i];var fiber=unmountEffects[i+1];var destroy=_effect.destroy;_effect.destroy=undefined;{fiber.flags&=~PassiveUnmountPendingDev;var alternate=fiber.alternate;if(alternate!==null){alternate.flags&=~PassiveUnmountPendingDev;}}if(typeof destroy==='function'){{setCurrentFiber(fiber);{invokeGuardedCallback(null,destroy,null);}if(hasCaughtError()){if(!(fiber!==null)){{throw Error("Should be working on an effect.");}}var error=clearCaughtError();captureCommitPhaseError(fiber,error);}resetCurrentFiber();}}}// Second pass: Create new passive effects.
var mountEffects=pendingPassiveHookEffectsMount;pendingPassiveHookEffectsMount=[];for(var _i=0;_i<mountEffects.length;_i+=2){var _effect2=mountEffects[_i];var _fiber=mountEffects[_i+1];{setCurrentFiber(_fiber);{invokeGuardedCallback(null,invokePassiveEffectCreate,null,_effect2);}if(hasCaughtError()){if(!(_fiber!==null)){{throw Error("Should be working on an effect.");}}var _error4=clearCaughtError();captureCommitPhaseError(_fiber,_error4);}resetCurrentFiber();}}// Note: This currently assumes there are no passive effects on the root fiber
// because the root is not part of its own effect list.
// This could change in the future.
var effect=root.current.firstEffect;while(effect!==null){var nextNextEffect=effect.nextEffect;// Remove nextEffect pointer to assist GC
effect.nextEffect=null;if(effect.flags&Deletion){detachFiberAfterEffects(effect);}effect=nextNextEffect;}{popInteractions(prevInteractions);finishPendingInteractions(root,lanes);}{isFlushingPassiveEffects=false;}executionContext=prevExecutionContext;flushSyncCallbackQueue();// If additional passive effects were scheduled, increment a counter. If this
// exceeds the limit, we'll fire a warning.
nestedPassiveUpdateCount=rootWithPendingPassiveEffects===null?0:nestedPassiveUpdateCount+1;return true;}function isAlreadyFailedLegacyErrorBoundary(instance){return legacyErrorBoundariesThatAlreadyFailed!==null&&legacyErrorBoundariesThatAlreadyFailed.has(instance);}function markLegacyErrorBoundaryAsFailed(instance){if(legacyErrorBoundariesThatAlreadyFailed===null){legacyErrorBoundariesThatAlreadyFailed=new Set([instance]);}else {legacyErrorBoundariesThatAlreadyFailed.add(instance);}}function prepareToThrowUncaughtError(error){if(!hasUncaughtError){hasUncaughtError=true;firstUncaughtError=error;}}var onUncaughtError=prepareToThrowUncaughtError;function captureCommitPhaseErrorOnRoot(rootFiber,sourceFiber,error){var errorInfo=createCapturedValue(error,sourceFiber);var update=createRootErrorUpdate(rootFiber,errorInfo,SyncLane);enqueueUpdate(rootFiber,update);var eventTime=requestEventTime();var root=markUpdateLaneFromFiberToRoot(rootFiber,SyncLane);if(root!==null){markRootUpdated(root,SyncLane,eventTime);ensureRootIsScheduled(root,eventTime);schedulePendingInteractions(root,SyncLane);}}function captureCommitPhaseError(sourceFiber,error){if(sourceFiber.tag===HostRoot){// Error was thrown at the root. There is no parent, so the root
// itself should capture it.
captureCommitPhaseErrorOnRoot(sourceFiber,sourceFiber,error);return;}var fiber=sourceFiber.return;while(fiber!==null){if(fiber.tag===HostRoot){captureCommitPhaseErrorOnRoot(fiber,sourceFiber,error);return;}else if(fiber.tag===ClassComponent){var ctor=fiber.type;var instance=fiber.stateNode;if(typeof ctor.getDerivedStateFromError==='function'||typeof instance.componentDidCatch==='function'&&!isAlreadyFailedLegacyErrorBoundary(instance)){var errorInfo=createCapturedValue(error,sourceFiber);var update=createClassErrorUpdate(fiber,errorInfo,SyncLane);enqueueUpdate(fiber,update);var eventTime=requestEventTime();var root=markUpdateLaneFromFiberToRoot(fiber,SyncLane);if(root!==null){markRootUpdated(root,SyncLane,eventTime);ensureRootIsScheduled(root,eventTime);schedulePendingInteractions(root,SyncLane);}else {// This component has already been unmounted.
// We can't schedule any follow up work for the root because the fiber is already unmounted,
// but we can still call the log-only boundary so the error isn't swallowed.
//
3 years ago
// TODO This is only a temporary bandaid for the old reconciler fork.
// We can delete this special case once the new fork is merged.
if(typeof instance.componentDidCatch==='function'&&!isAlreadyFailedLegacyErrorBoundary(instance)){try{instance.componentDidCatch(error,errorInfo);}catch(errorToIgnore){// TODO Ignore this error? Rethrow it?
// This is kind of an edge case.
}}}return;}}fiber=fiber.return;}}function pingSuspendedRoot(root,wakeable,pingedLanes){var pingCache=root.pingCache;if(pingCache!==null){// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
pingCache.delete(wakeable);}var eventTime=requestEventTime();markRootPinged(root,pingedLanes);if(workInProgressRoot===root&&isSubsetOfLanes(workInProgressRootRenderLanes,pingedLanes)){// Received a ping at the same priority level at which we're currently
// rendering. We might want to restart this render. This should mirror
// the logic of whether or not a root suspends once it completes.
// TODO: If we're rendering sync either due to Sync, Batched or expired,
// we should probably never restart.
// If we're suspended with delay, or if it's a retry, we'll always suspend
// so we can always restart.
if(workInProgressRootExitStatus===RootSuspendedWithDelay||workInProgressRootExitStatus===RootSuspended&&includesOnlyRetries(workInProgressRootRenderLanes)&&now()-globalMostRecentFallbackTime<FALLBACK_THROTTLE_MS){// Restart from the root.
prepareFreshStack(root,NoLanes);}else {// Even though we can't restart right now, we might get an
// opportunity later. So we mark this render as having a ping.
workInProgressRootPingedLanes=mergeLanes(workInProgressRootPingedLanes,pingedLanes);}}ensureRootIsScheduled(root,eventTime);schedulePendingInteractions(root,pingedLanes);}function retryTimedOutBoundary(boundaryFiber,retryLane){// The boundary fiber (a Suspense component or SuspenseList component)
// previously was rendered in its fallback state. One of the promises that
// suspended it has resolved, which means at least part of the tree was
// likely unblocked. Try rendering again, at a new expiration time.
if(retryLane===NoLane){retryLane=requestRetryLane(boundaryFiber);}// TODO: Special case idle priority?
var eventTime=requestEventTime();var root=markUpdateLaneFromFiberToRoot(boundaryFiber,retryLane);if(root!==null){markRootUpdated(root,retryLane,eventTime);ensureRootIsScheduled(root,eventTime);schedulePendingInteractions(root,retryLane);}}function resolveRetryWakeable(boundaryFiber,wakeable){var retryLane=NoLane;// Default
var retryCache;{retryCache=boundaryFiber.stateNode;}if(retryCache!==null){// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
retryCache.delete(wakeable);}retryTimedOutBoundary(boundaryFiber,retryLane);}// Computes the next Just Noticeable Difference (JND) boundary.
// The theory is that a person can't tell the difference between small differences in time.
// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
// difference in the experience. However, waiting for longer might mean that we can avoid
// showing an intermediate loading state. The longer we have already waited, the harder it
// is to tell small differences in time. Therefore, the longer we've already waited,
// the longer we can wait additionally. At some point we have to give up though.
// We pick a train model where the next boundary commits at a consistent schedule.
// These particular numbers are vague estimates. We expect to adjust them based on research.
function jnd(timeElapsed){return timeElapsed<120?120:timeElapsed<480?480:timeElapsed<1080?1080:timeElapsed<1920?1920:timeElapsed<3000?3000:timeElapsed<4320?4320:ceil(timeElapsed/1960)*1960;}function checkForNestedUpdates(){if(nestedUpdateCount>NESTED_UPDATE_LIMIT){nestedUpdateCount=0;rootWithNestedUpdates=null;{{throw Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.");}}}{if(nestedPassiveUpdateCount>NESTED_PASSIVE_UPDATE_LIMIT){nestedPassiveUpdateCount=0;error('Maximum update depth exceeded. This can happen when a component '+"calls setState inside useEffect, but useEffect either doesn't "+'have a dependency array, or one of the dependencies changes on '+'every render.');}}}function flushRenderPhaseStrictModeWarningsInDEV(){{ReactStrictModeWarnings.flushLegacyContextWarning();{ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();}}}var didWarnStateUpdateForNotYetMountedComponent=null;function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber){{if((executionContext&RenderContext)!==NoContext){// We let the other warning about render phase updates deal with this one.
return;}if(!(fiber.mode&(BlockingMode|ConcurrentMode))){return;}var tag=fiber.tag;if(tag!==IndeterminateComponent&&tag!==HostRoot&&tag!==ClassComponent&&tag!==FunctionComponent&&tag!==ForwardRef&&tag!==MemoComponent&&tag!==SimpleMemoComponent&&tag!==Block){// Only warn for user-defined components, not internal ones like Suspense.
return;}// We show the whole stack but dedupe on the top component's name because
// the problematic code almost always lies inside that component.
var componentName=getComponentName(fiber.type)||'ReactComponent';if(didWarnStateUpdateForNotYetMountedComponent!==null){if(didWarnStateUpdateForNotYetMountedComponent.has(componentName)){return;}didWarnStateUpdateForNotYetMountedComponent.add(componentName);}else {didWarnStateUpdateForNotYetMountedComponent=new Set([componentName]);}var previousFiber=current;try{setCurrentFiber(fiber);error("Can't perform a React state update on a component that hasn't mounted yet. "+'This indicates that you have a side-effect in your render function that '+'asynchronously later calls tries to update the component. Move this work to '+'useEffect instead.');}finally{if(previousFiber){setCurrentFiber(fiber);}else {resetCurrentFiber();}}}}var didWarnStateUpdateForUnmountedComponent=null;function warnAboutUpdateOnUnmountedFiberInDEV(fiber){{var tag=fiber.tag;if(tag!==HostRoot&&tag!==ClassComponent&&tag!==FunctionComponent&&tag!==ForwardRef&&tag!==MemoComponent&&tag!==SimpleMemoComponent&&tag!==Block){// Only warn for user-defined components, not internal ones like Suspense.
return;}// If there are pending passive effects unmounts for this Fiber,
// we can assume that they would have prevented this update.
if((fiber.flags&PassiveUnmountPendingDev)!==NoFlags){return;}// We show the whole stack but dedupe on the top component's name because
// the problematic code almost always lies inside that component.
var componentName=getComponentName(fiber.type)||'ReactComponent';if(didWarnStateUpdateForUnmountedComponent!==null){if(didWarnStateUpdateForUnmountedComponent.has(componentName)){return;}didWarnStateUpdateForUnmountedComponent.add(componentName);}else {didWarnStateUpdateForUnmountedComponent=new Set([componentName]);}if(isFlushingPassiveEffects);else {var previousFiber=current;try{setCurrentFiber(fiber);error("Can't perform a React state update on an unmounted component. This "+'is a no-op, but it indicates a memory leak in your application. To '+'fix, cancel all subscriptions and asynchronous tasks in %s.',tag===ClassComponent?'the componentWillUnmount method':'a useEffect cleanup function');}finally{if(previousFiber){setCurrentFiber(fiber);}else {resetCurrentFiber();}}}}}var beginWork$1;{var dummyFiber=null;beginWork$1=function(current,unitOfWork,lanes){// If a component throws an error, we replay it again in a synchronously
// dispatched event, so that the debugger will treat it as an uncaught
// error See ReactErrorUtils for more information.
// Before entering the begin phase, copy the work-in-progress onto a dummy
// fiber. If beginWork throws, we'll use this to reset the state.
var originalWorkInProgressCopy=assignFiberPropertiesInDEV(dummyFiber,unitOfWork);try{return beginWork(current,unitOfWork,lanes);}catch(originalError){if(originalError!==null&&typeof originalError==='object'&&typeof originalError.then==='function'){// Don't replay promises. Treat everything else like an error.
throw originalError;}// Keep this code in sync with handleError; any changes here must have
// corresponding changes there.
resetContextDependencies();resetHooksAfterThrow();// Don't reset current debug fiber, since we're about to work on the
// same fiber again.
// Unwind the failed stack frame
unwindInterruptedWork(unitOfWork);// Restore the original properties of the fiber.
assignFiberPropertiesInDEV(unitOfWork,originalWorkInProgressCopy);if(unitOfWork.mode&ProfileMode){// Reset the profiler timer.
startProfilerTimer(unitOfWork);}// Run beginWork again.
invokeGuardedCallback(null,beginWork,null,current,unitOfWork,lanes);if(hasCaughtError()){var replayError=clearCaughtError();// `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
// Rethrow this error instead of the original one.
throw replayError;}else {// This branch is reachable if the render phase is impure.
throw originalError;}}};}var didWarnAboutUpdateInRender=false;var didWarnAboutUpdateInRenderForAnotherComponent;{didWarnAboutUpdateInRenderForAnotherComponent=new Set();}function warnAboutRenderPhaseUpdatesInDEV(fiber){{if(isRendering&&(executionContext&RenderContext)!==NoContext&&!getIsUpdatingOpaqueValueInRenderPhaseInDEV()){switch(fiber.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{var renderingComponentName=workInProgress&&getComponentName(workInProgress.type)||'Unknown';// Dedupe by the rendering component because it's the one that needs to be fixed.
var dedupeKey=renderingComponentName;if(!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)){didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);var setStateComponentName=getComponentName(fiber.type)||'Unknown';error('Cannot update a component (`%s`) while rendering a '+'different component (`%s`). To locate the bad setState() call inside `%s`, '+'follow the stack trace as described in https://reactjs.org/link/setstate-in-render',setStateComponentName,renderingComponentName,renderingComponentName);}break;}case ClassComponent:{if(!didWarnAboutUpdateInRender){error('Cannot update during an existing state transition (such as '+'within `render`). Render methods should be a pure '+'function of props and state.');didWarnAboutUpdateInRender=true;}break;}}}}}// a 'shared' variable that changes when act() opens/closes in tests.
var IsThisRendererActing={current:false};function warnIfNotScopedWithMatchingAct(fiber){{if(IsSomeRendererActing.current===true&&IsThisRendererActing.current!==true){var previousFiber=current;try{setCurrentFiber(fiber);error("It looks like you're using the wrong act() around your test interactions.\n"+'Be sure to use the matching version of act() corresponding to your renderer:\n\n'+'// for react-dom:\n'+// Break up imports to avoid accidentally parsing them as dependencies.
'import {act} fr'+"om 'react-dom/test-utils';\n"+'// ...\n'+'act(() => ...);\n\n'+'// for react-test-renderer:\n'+// Break up imports to avoid accidentally parsing them as dependencies.
'import TestRenderer fr'+"om react-test-renderer';\n"+'const {act} = TestRenderer;\n'+'// ...\n'+'act(() => ...);');}finally{if(previousFiber){setCurrentFiber(fiber);}else {resetCurrentFiber();}}}}}function warnIfNotCurrentlyActingEffectsInDEV(fiber){{if((fiber.mode&StrictMode)!==NoMode&&IsSomeRendererActing.current===false&&IsThisRendererActing.current===false){error('An update to %s ran an effect, but was not wrapped in act(...).\n\n'+'When testing, code that causes React state updates should be '+'wrapped into act(...):\n\n'+'act(() => {\n'+' /* fire events that update state */\n'+'});\n'+'/* assert on the output */\n\n'+"This ensures that you're testing the behavior the user would see "+'in the browser.'+' Learn more at https://reactjs.org/link/wrap-tests-with-act',getComponentName(fiber.type));}}}function warnIfNotCurrentlyActingUpdatesInDEV(fiber){{if(executionContext===NoContext&&IsSomeRendererActing.current===false&&IsThisRendererActing.current===false){var previousFiber=current;try{setCurrentFiber(fiber);error('An update to %s inside a test was not wrapped in act(...).\n\n'+'When testing, code that causes React state updates should be '+'wrapped into act(...):\n\n'+'act(() => {\n'+' /* fire events that update state */\n'+'});\n'+'/* assert on the output */\n\n'+"This ensures that you're testing the behavior the user would see "+'in the browser.'+' Learn more at https://reactjs.org/link/wrap-tests-with-act',getComponentName(fiber.type));}finally{if(previousFiber){setCurrentFiber(fiber);}else {resetCurrentFiber();}}}}}var warnIfNotCurrentlyActingUpdatesInDev=warnIfNotCurrentlyActingUpdatesInDEV;// In tests, we want to enforce a mocked scheduler.
var didWarnAboutUnmockedScheduler=false;// TODO Before we release concurrent mode, revisit this and decide whether a mocked
// scheduler is the actual recommendation. The alternative could be a testing build,
// a new lib, or whatever; we dunno just yet. This message is for early adopters
// to get their tests right.
function warnIfUnmockedScheduler(fiber){{if(didWarnAboutUnmockedScheduler===false&&Scheduler.unstable_flushAllWithoutAsserting===undefined){if(fiber.mode&BlockingMode||fiber.mode&ConcurrentMode){didWarnAboutUnmockedScheduler=true;error('In Concurrent or Sync modes, the "scheduler" module needs to be mocked '+'to guarantee consistent behaviour across tests and browsers. '+'For example, with jest: \n'+// Break up requires to avoid accidentally parsing them as dependencies.
"jest.mock('scheduler', () => require"+"('scheduler/unstable_mock'));\n\n"+'For more info, visit https://reactjs.org/link/mock-scheduler');}}}}function computeThreadID(root,lane){// Interaction threads are unique per root and expiration time.
// NOTE: Intentionally unsound cast. All that matters is that it's a number
// and it represents a batch of work. Could make a helper function instead,
// but meh this is fine for now.
return lane*1000+root.interactionThreadID;}function markSpawnedWork(lane){if(spawnedWorkDuringRender===null){spawnedWorkDuringRender=[lane];}else {spawnedWorkDuringRender.push(lane);}}function scheduleInteractions(root,lane,interactions){if(interactions.size>0){var pendingInteractionMap=root.pendingInteractionMap;var pendingInteractions=pendingInteractionMap.get(lane);if(pendingInteractions!=null){interactions.forEach(function(interaction){if(!pendingInteractions.has(interaction)){// Update the pending async work count for previously unscheduled interaction.
interaction.__count++;}pendingInteractions.add(interaction);});}else {pendingInteractionMap.set(lane,new Set(interactions));// Update the pending async work count for the current interactions.
interactions.forEach(function(interaction){interaction.__count++;});}var subscriber=tracing$1.__subscriberRef.current;if(subscriber!==null){var threadID=computeThreadID(root,lane);subscriber.onWorkScheduled(interactions,threadID);}}}function schedulePendingInteractions(root,lane){scheduleInteractions(root,lane,tracing$1.__interactionsRef.current);}function startWorkOnPendingInteractions(root,lanes){// we can accurately attribute time spent working on it, And so that cascading
// work triggered during the render phase will be associated with it.
var interactions=new Set();root.pendingInteractionMap.forEach(function(scheduledInteractions,scheduledLane){if(includesSomeLane(lanes,scheduledLane)){scheduledInteractions.forEach(function(interaction){return interactions.add(interaction);});}});// Store the current set of interactions on the FiberRoot for a few reasons:
// We can re-use it in hot functions like performConcurrentWorkOnRoot()
// without having to recalculate it. We will also use it in commitWork() to
// pass to any Profiler onRender() hooks. This also provides DevTools with a
// way to access it when the onCommitRoot() hook is called.
root.memoizedInteractions=interactions;if(interactions.size>0){var subscriber=tracing$1.__subscriberRef.current;if(subscriber!==null){var threadID=computeThreadID(root,lanes);try{subscriber.onWorkStarted(interactions,threadID);}catch(error){// If the subscriber throws, rethrow it in a separate task
scheduleCallback(ImmediatePriority$1,function(){throw error;});}}}}function finishPendingInteractions(root,committedLanes){var remainingLanesAfterCommit=root.pendingLanes;var subscriber;try{subscriber=tracing$1.__subscriberRef.current;if(subscriber!==null&&root.memoizedInteractions.size>0){// FIXME: More than one lane can finish in a single commit.
var threadID=computeThreadID(root,committedLanes);subscriber.onWorkStopped(root.memoizedInteractions,threadID);}}catch(error){// If the subscriber throws, rethrow it in a separate task
scheduleCallback(ImmediatePriority$1,function(){throw error;});}finally{// Clear completed interactions from the pending Map.
// Unless the render was suspended or cascading work was scheduled,
// In which case leave pending interactions until the subsequent render.
var pendingInteractionMap=root.pendingInteractionMap;pendingInteractionMap.forEach(function(scheduledInteractions,lane){// Only decrement the pending interaction count if we're done.
// If there's still work at the current priority,
// That indicates that we are waiting for suspense data.
if(!includesSomeLane(remainingLanesAfterCommit,lane)){pendingInteractionMap.delete(lane);scheduledInteractions.forEach(function(interaction){interaction.__count--;if(subscriber!==null&&interaction.__count===0){try{subscriber.onInteractionScheduledWorkCompleted(interaction);}catch(error){// If the subscriber throws, rethrow it in a separate task
scheduleCallback(ImmediatePriority$1,function(){throw error;});}}});}});}}// `act` testing API
function shouldForceFlushFallbacksInDEV(){// Never force flush in production. This function should get stripped out.
return actingUpdatesScopeDepth>0;}// so we can tell if any async act() calls try to run in parallel.
var actingUpdatesScopeDepth=0;function detachFiberAfterEffects(fiber){fiber.sibling=null;fiber.stateNode=null;}var resolveFamily=null;// $FlowFixMe Flow gets confused by a WeakSet feature check below.
var failedBoundaries=null;var setRefreshHandler=function(handler){{resolveFamily=handler;}};function resolveFunctionForHotReloading(type){{if(resolveFamily===null){// Hot reloading is disabled.
return type;}var family=resolveFamily(type);if(family===undefined){return type;}// Use the latest known implementation.
return family.current;}}function resolveClassForHotReloading(type){// No implementation differences.
return resolveFunctionForHotReloading(type);}function resolveForwardRefForHotReloading(type){{if(resolveFamily===null){// Hot reloading is disabled.
return type;}var family=resolveFamily(type);if(family===undefined){// Check if we're dealing with a real forwardRef. Don't want to crash early.
if(type!==null&&type!==undefined&&typeof type.render==='function'){// ForwardRef is special because its resolved .type is an object,
// but it's possible that we only have its inner render function in the map.
// If that inner render function is different, we'll build a new forwardRef type.
var currentRender=resolveFunctionForHotReloading(type.render);if(type.render!==currentRender){var syntheticType={$$typeof:REACT_FORWARD_REF_TYPE,render:currentRender};if(type.displayName!==undefined){syntheticType.displayName=type.displayName;}return syntheticType;}}return type;}// Use the latest known implementation.
return family.current;}}function isCompatibleFamilyForHotReloading(fiber,element){{if(resolveFamily===null){// Hot reloading is disabled.
return false;}var prevType=fiber.elementType;var nextType=element.type;// If we got here, we know types aren't === equal.
var needsCompareFamilies=false;var $$typeofNextType=typeof nextType==='object'&&nextType!==null?nextType.$$typeof:null;switch(fiber.tag){case ClassComponent:{if(typeof nextType==='function'){needsCompareFamilies=true;}break;}case FunctionComponent:{if(typeof nextType==='function'){needsCompareFamilies=true;}else if($$typeofNextType===REACT_LAZY_TYPE){// We don't know the inner type yet.
// We're going to assume that the lazy inner type is stable,
// and so it is sufficient to avoid reconciling it away.
// We're not going to unwrap or actually use the new lazy type.
needsCompareFamilies=true;}break;}case ForwardRef:{if($$typeofNextType===REACT_FORWARD_REF_TYPE){needsCompareFamilies=true;}else if($$typeofNextType===REACT_LAZY_TYPE){needsCompareFamilies=true;}break;}case MemoComponent:case SimpleMemoComponent:{if($$typeofNextType===REACT_MEMO_TYPE){// TODO: if it was but can no longer be simple,
// we shouldn't set this.
needsCompareFamilies=true;}else if($$typeofNextType===REACT_LAZY_TYPE){needsCompareFamilies=true;}break;}default:return false;}// Check if both types have a family and it's the same one.
if(needsCompareFamilies){// Note: memo() and forwardRef() we'll compare outer rather than inner type.
// This means both of them need to be registered to preserve state.
// If we unwrapped and compared the inner types for wrappers instead,
// then we would risk falsely saying two separate memo(Foo)
// calls are equivalent because they wrap the same Foo function.
var prevFamily=resolveFamily(prevType);if(prevFamily!==undefined&&prevFamily===resolveFamily(nextType)){return true;}}return false;}}function markFailedErrorBoundaryForHotReloading(fiber){{if(resolveFamily===null){// Hot reloading is disabled.
return;}if(typeof WeakSet!=='function'){return;}if(failedBoundaries===null){failedBoundaries=new WeakSet();}failedBoundaries.add(fiber);}}var scheduleRefresh=function(root,update){{if(resolveFamily===null){// Hot reloading is disabled.
return;}var staleFamilies=update.staleFamilies,updatedFamilies=update.updatedFamilies;flushPassiveEffects();flushSync(function(){scheduleFibersWithFamiliesRecursively(root.current,updatedFamilies,staleFamilies);});}};var scheduleRoot=function(root,element){{if(root.context!==emptyContextObject){// Super edge case: root has a legacy _renderSubtree context
// but we don't know the parentComponent so we can't pass it.
// Just ignore. We'll delete this with _renderSubtree code path later.
return;}flushPassiveEffects();flushSync(function(){updateContainer(element,root,null,null);});}};function scheduleFibersWithFamiliesRecursively(fiber,updatedFamilies,staleFamilies){{var alternate=fiber.alternate,child=fiber.child,sibling=fiber.sibling,tag=fiber.tag,type=fiber.type;var candidateType=null;switch(tag){case FunctionComponent:case SimpleMemoComponent:case ClassComponent:candidateType=type;break;case ForwardRef:candidateType=type.render;break;}if(resolveFamily===null){throw new Error('Expected resolveFamily to be set during hot reload.');}var needsRender=false;var needsRemount=false;if(candidateType!==null){var family=resolveFamily(candidateType);if(family!==undefined){if(staleFamilies.has(family)){needsRemount=true;}else if(updatedFamilies.has(family)){if(tag===ClassComponent){needsRemount=true;}else {needsRender=true;}}}}if(failedBoundaries!==null){if(failedBoundaries.has(fiber)||alternate!==null&&failedBoundaries.has(alternate)){needsRemount=true;}}if(needsRemount){fiber._debugNeedsRemount=true;}if(needsRemount||needsRender){scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);}if(child!==null&&!needsRemount){scheduleFibersWithFamiliesRecursively(child,updatedFamilies,staleFamilies);}if(sibling!==null){scheduleFibersWithFamiliesRecursively(sibling,updatedFamilies,staleFamilies);}}}var findHostInstancesForRefresh=function(root,families){{var hostInstances=new Set();var types=new Set(families.map(function(family){return family.current;}));findHostInstancesForMatchingFibersRecursively(root.current,types,hostInstances);return hostInstances;}};function findHostInstancesForMatchingFibersRecursively(fiber,types,hostInstances){{var child=fiber.child,sibling=fiber.sibling,tag=fiber.tag,type=fiber.type;var candidateType=null;switch(tag){case FunctionComponent:case SimpleMemoComponent:case ClassComponent:candidateType=type;break;case ForwardRef:candidateType=type.render;break;}var didMatch=false;if(candidateType!==null){if(types.has(candidateType)){didMatch=true;}}if(didMatch){// We have a match. This only drills down to the closest host components.
// There's no need to search deeper because for the purpose of giving
// visual feedback, "flashing" outermost parent rectangles is sufficient.
findHostInstancesForFiberShallowly(fiber,hostInstances);}else {// If there's no match, maybe there will be one further down in the child tree.
if(child!==null){findHostInstancesForMatchingFibersRecursively(child,types,hostInstances);}}if(sibling!==null){findHostInstancesForMatchingFibersRecursively(sibling,types,hostInstances);}}}function findHostInstancesForFiberShallowly(fiber,hostInstances){{var foundHostInstances=findChildHostInstancesForFiberShallowly(fiber,hostInstances);if(foundHostInstances){return;}// If we didn't find any host children, fallback to closest host parent.
var node=fiber;while(true){switch(node.tag){case HostComponent:hostInstances.add(node.stateNode);return;case HostPortal:hostInstances.add(node.stateNode.containerInfo);return;case HostRoot:hostInstances.add(node.stateNode.containerInfo);return;}if(node.return===null){throw new Error('Expected to reach root first.');}node=node.return;}}}function findChildHostInstancesForFiberShallowly(fiber,hostInstances){{var node=fiber;var foundHostInstances=false;while(true){if(node.tag===HostComponent){// We got a match.
foundHostInstances=true;hostInstances.add(node.stateNode);// There may still be more, so keep searching.
}else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===fiber){return foundHostInstances;}while(node.sibling===null){if(node.return===null||node.return===fiber){return foundHostInstances;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}}return false;}var hasBadMapPolyfill;{hasBadMapPolyfill=false;try{var nonExtensibleObject=Object.preventExtensions({});/* eslint-disable no-new */new Map([[nonExtensibleObject,null]]);new Set([nonExtensibleObject]);/* eslint-enable no-new */}catch(e){// TODO: Consider warning about bad polyfills
hasBadMapPolyfill=true;}}var debugCounter=1;function FiberNode(tag,pendingProps,key,mode){// Instance
this.tag=tag;this.key=key;this.elementType=null;this.type=null;this.stateNode=null;// Fiber
this.return=null;this.child=null;this.sibling=null;this.index=0;this.ref=null;this.pendingProps=pendingProps;this.memoizedProps=null;this.updateQueue=null;this.memoizedState=null;this.dependencies=null;this.mode=mode;// Effects
this.flags=NoFlags;this.nextEffect=null;this.firstEffect=null;this.lastEffect=null;this.lanes=NoLanes;this.childLanes=NoLanes;this.alternate=null;{// Note: The following is done to avoid a v8 performance cliff.
//
// Initializing the fields below to smis and later updating them with
// double values will cause Fibers to end up having separate shapes.
// This behavior/bug has something to do with Object.preventExtension().
// Fortunately this only impacts DEV builds.
// Unfortunately it makes React unusably slow for some applications.
// To work around this, initialize the fields below with doubles.
//
// Learn more about this here:
// https://github.com/facebook/react/issues/14365
// https://bugs.chromium.org/p/v8/issues/detail?id=8538
this.actualDuration=Number.NaN;this.actualStartTime=Number.NaN;this.selfBaseDuration=Number.NaN;this.treeBaseDuration=Number.NaN;// It's okay to replace the initial doubles with smis after initialization.
// This won't trigger the performance cliff mentioned above,
// and it simplifies other profiler code (including DevTools).
this.actualDuration=0;this.actualStartTime=-1;this.selfBaseDuration=0;this.treeBaseDuration=0;}{// This isn't directly used but is handy for debugging internals:
this._debugID=debugCounter++;this._debugSource=null;this._debugOwner=null;this._debugNeedsRemount=false;this._debugHookTypes=null;if(!hasBadMapPolyfill&&typeof Object.preventExtensions==='function'){Object.preventExtensions(this);}}}// This is a constructor function, rather than a POJO constructor, still
// please ensure we do the following:
// 1) Nobody should add any instance methods on this. Instance methods can be
// more difficult to predict when they get optimized and they are almost
// never inlined properly in static compilers.
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
// always know when it is a fiber.
// 3) We might want to experiment with using numeric keys since they are easier
// to optimize in a non-JIT environment.
// 4) We can easily go from a constructor to a createFiber object literal if that
// is faster.
// 5) It should be easy to port this to a C struct and keep a C implementation
// compatible.
var createFiber=function(tag,pendingProps,key,mode){// $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
return new FiberNode(tag,pendingProps,key,mode);};function shouldConstruct$1(Component){var prototype=Component.prototype;return !!(prototype&&prototype.isReactComponent);}function isSimpleFunctionComponent(type){return typeof type==='function'&&!shouldConstruct$1(type)&&type.defaultProps===undefined;}function resolveLazyComponentTag(Component){if(typeof Component==='function'){return shouldConstruct$1(Component)?ClassComponent:FunctionComponent;}else if(Component!==undefined&&Component!==null){var $$typeof=Component.$$typeof;if($$typeof===REACT_FORWARD_REF_TYPE){return ForwardRef;}if($$typeof===REACT_MEMO_TYPE){return MemoComponent;}}return IndeterminateComponent;}// This is used to create an alternate fiber to do work on.
function createWorkInProgress(current,pendingProps){var workInProgress=current.alternate;if(workInProgress===null){// We use a double buffering pooling technique because we know that we'll
// only ever need at most two versions of a tree. We pool the "other" unused
// node that we're free to reuse. This is lazily created to avoid allocating
// extra objects for things that are never updated. It also allow us to
// reclaim the extra memory if needed.
workInProgress=createFiber(current.tag,pendingProps,current.key,current.mode);workInProgress.elementType=current.elementType;workInProgress.type=current.type;workInProgress.stateNode=current.stateNode;{// DEV-only fields
workInProgress._debugID=current._debugID;workInProgress._debugSource=current._debugSource;workInProgress._debugOwner=current._debugOwner;workInProgress._debugHookTypes=current._debugHookTypes;}workInProgress.alternate=current;current.alternate=workInProgress;}else {workInProgress.pendingProps=pendingProps;// Needed because Blocks store data on type.
workInProgress.type=current.type;// We already have an alternate.
// Reset the effect tag.
workInProgress.flags=NoFlags;// The effect list is no longer valid.
workInProgress.nextEffect=null;workInProgress.firstEffect=null;workInProgress.lastEffect=null;{// We intentionally reset, rather than copy, actualDuration & actualStartTime.
// This prevents time from endlessly accumulating in new commits.
// This has the downside of resetting values for different priority renders,
// But works for yielding (the common case) and should support resuming.
workInProgress.actualDuration=0;workInProgress.actualStartTime=-1;}}workInProgress.childLanes=current.childLanes;workInProgress.lanes=current.lanes;workInProgress.child=current.child;workInProgress.memoizedProps=current.memoizedProps;workInProgress.memoizedState=current.memoizedState;workInProgress.updateQueue=current.updateQueue;// Clone the dependencies object. This is mutated during the render phase, so
// it cannot be shared with the current fiber.
var currentDependencies=current.dependencies;workInProgress.dependencies=currentDependencies===null?null:{lanes:currentDependencies.lanes,firstContext:currentDependencies.firstContext};// These will be overridden during the parent's reconciliation
workInProgress.sibling=current.sibling;workInProgress.index=current.index;workInProgress.ref=current.ref;{workInProgress.selfBaseDuration=current.selfBaseDuration;workInProgress.treeBaseDuration=current.treeBaseDuration;}{workInProgress._debugNeedsRemount=current._debugNeedsRemount;switch(workInProgress.tag){case IndeterminateComponent:case FunctionComponent:case SimpleMemoComponent:workInProgress.type=resolveFunctionForHotReloading(current.type);break;case ClassComponent:workInProgress.type=resolveClassForHotReloading(current.type);break;case ForwardRef:workInProgress.type=resolveForwardRefForHotReloading(current.type);break;}}return workInProgress;}// Used to reuse a Fiber for a second pass.
function resetWorkInProgress(workInProgress,renderLanes){// This resets the Fiber to what createFiber or createWorkInProgress would
// have set the values to before during the first pass. Ideally this wouldn't
// be necessary but unfortunately many code paths reads from the workInProgress
// when they should be reading from current and writing to workInProgress.
// We assume pendingProps, index, key, ref, return are still untouched to
// avoid doing another reconciliation.
// Reset the effect tag but keep any Placement tags, since that's something
// that child fiber is setting, not the reconciliation.
workInProgress.flags&=Placement;// The effect list is no longer valid.
workInProgress.nextEffect=null;workInProgress.firstEffect=null;workInProgress.lastEffect=null;var current=workInProgress.alternate;if(current===null){// Reset to createFiber's initial values.
workInProgress.childLanes=NoLanes;workInProgress.lanes=renderLanes;workInProgress.child=null;workInProgress.memoizedProps=null;workInProgress.memoizedState=null;workInProgress.updateQueue=null;workInProgress.dependencies=null;workInProgress.stateNode=null;{// Note: We don't reset the actualTime counts. It's useful to accumulate
// actual time across multiple render passes.
workInProgress.selfBaseDuration=0;workInProgress.treeBaseDuration=0;}}else {// Reset to the cloned values that createWorkInProgress would've.
workInProgress.childLanes=current.childLanes;workInProgress.lanes=current.lanes;workInProgress.child=current.child;workInProgress.memoizedProps=current.memoizedProps;workInProgress.memoizedState=current.memoizedState;workInProgress.updateQueue=current.updateQueue;// Needed because Blocks store data on type.
workInProgress.type=current.type;// Clone the dependencies object. This is mutated during the render phase, so
// it cannot be shared with the current fiber.
var currentDependencies=current.dependencies;workInProgress.dependencies=currentDependencies===null?null:{lanes:currentDependencies.lanes,firstContext:currentDependencies.firstContext};{// Note: We don't reset the actualTime counts. It's useful to accumulate
// actual time across multiple render passes.
workInProgress.selfBaseDuration=current.selfBaseDuration;workInProgress.treeBaseDuration=current.treeBaseDuration;}}return workInProgress;}function createHostRootFiber(tag){var mode;if(tag===ConcurrentRoot){mode=ConcurrentMode|BlockingMode|StrictMode;}else if(tag===BlockingRoot){mode=BlockingMode|StrictMode;}else {mode=NoMode;}if(isDevToolsPresent){// Always collect profile timings when DevTools are present.
// This enables DevTools to start capturing timing at any point
// Without some nodes in the tree having empty base times.
mode|=ProfileMode;}return createFiber(HostRoot,null,null,mode);}function createFiberFromTypeAndProps(type,// React$ElementType
key,pendingProps,owner,mode,lanes){var fiberTag=IndeterminateComponent;// The resolved type is set if we know what the final type will be. I.e. it's not lazy.
var resolvedType=type;if(typeof type==='function'){if(shouldConstruct$1(type)){fiberTag=ClassComponent;{resolvedType=resolveClassForHotReloading(resolvedType);}}else {{resolvedType=resolveFunctionForHotReloading(resolvedType);}}}else if(typeof type==='string'){fiberTag=HostComponent;}else {getTag:switch(type){case REACT_FRAGMENT_TYPE:return createFiberFromFragment(pendingProps.children,mode,lanes,key);case REACT_DEBUG_TRACING_MODE_TYPE:fiberTag=Mode;mode|=DebugTracingMode;break;case REACT_STRICT_MODE_TYPE:fiberTag=Mode;mode|=StrictMode;break;case REACT_PROFILER_TYPE:return createFiberFromProfiler(pendingProps,mode,lanes,key);case REACT_SUSPENSE_TYPE:return createFiberFromSuspense(pendingProps,mode,lanes,key);case REACT_SUSPENSE_LIST_TYPE:return createFiberFromSuspenseList(pendingProps,mode,lanes,key);case REACT_OFFSCREEN_TYPE:return createFiberFromOffscreen(pendingProps,mode,lanes,key);case REACT_LEGACY_HIDDEN_TYPE:return createFiberFromLegacyHidden(pendingProps,mode,lanes,key);case REACT_SCOPE_TYPE:// eslint-disable-next-line no-fallthrough
default:{if(typeof type==='object'&&type!==null){switch(type.$$typeof){case REACT_PROVIDER_TYPE:fiberTag=ContextProvider;break getTag;case REACT_CONTEXT_TYPE:// This is a consumer
fiberTag=ContextConsumer;break getTag;case REACT_FORWARD_REF_TYPE:fiberTag=ForwardRef;{resolvedType=resolveForwardRefForHotReloading(resolvedType);}break getTag;case REACT_MEMO_TYPE:fiberTag=MemoComponent;break getTag;case REACT_LAZY_TYPE:fiberTag=LazyComponent;resolvedType=null;break getTag;case REACT_BLOCK_TYPE:fiberTag=Block;break getTag;}}var info='';{if(type===undefined||typeof type==='object'&&type!==null&&Object.keys(type).length===0){info+=' You likely forgot to export your component from the file '+"it's defined in, or you might have mixed up default and "+'named imports.';}var ownerName=owner?getComponentName(owner.type):null;if(ownerName){info+='\n\nCheck the render method of `'+ownerName+'`.';}}{{throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: "+(type==null?type:typeof type)+"."+info);}}}}}var fiber=createFiber(fiberTag,pendingProps,key,mode);fiber.elementType=type;fiber.type=resolvedType;fiber.lanes=lanes;{fiber._debugOwner=owner;}return fiber;}function createFiberFromElement(element,mode,lanes){var owner=null;{owner=element._owner;}var type=element.type;var key=element.key;var pendingProps=element.props;var fiber=createFiberFromTypeAndProps(type,key,pendingProps,owner,mode,lanes);{fiber._debugSource=element._source;fiber._debugOwner=element._owner;}return fiber;}function createFiberFromFragment(elements,mode,lanes,key){var fiber=createFiber(Fragment,elements,key,mode);fiber.lanes=lanes;return fiber;}function createFiberFromProfiler(pendingProps,mode,lanes,key){{if(typeof pendingProps.id!=='string'){error('Profiler must specify an "id" as a prop');}}var fiber=createFiber(Profiler,pendingProps,key,mode|ProfileMode);// TODO: The Profiler fiber shouldn't have a type. It has a tag.
fiber.elementType=REACT_PROFILER_TYPE;fiber.type=REACT_PROFILER_TYPE;fiber.lanes=lanes;{fiber.stateNode={effectDuration:0,passiveEffectDuration:0};}return fiber;}function createFiberFromSuspense(pendingProps,mode,lanes,key){var fiber=createFiber(SuspenseComponent,pendingProps,key,mode);// TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
// This needs to be fixed in getComponentName so that it relies on the tag
// instead.
fiber.type=REACT_SUSPENSE_TYPE;fiber.elementType=REACT_SUSPENSE_TYPE;fiber.lanes=lanes;return fiber;}function createFiberFromSuspenseList(pendingProps,mode,lanes,key){var fiber=createFiber(SuspenseListComponent,pendingProps,key,mode);{// TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
// This needs to be fixed in getComponentName so that it relies on the tag
// instead.
fiber.type=REACT_SUSPENSE_LIST_TYPE;}fiber.elementType=REACT_SUSPENSE_LIST_TYPE;fiber.lanes=lanes;return fiber;}function createFiberFromOffscreen(pendingProps,mode,lanes,key){var fiber=createFiber(OffscreenComponent,pendingProps,key,mode);// TODO: The OffscreenComponent fiber shouldn't have a type. It has a tag.
// This needs to be fixed in getComponentName so that it relies on the tag
// instead.
{fiber.type=REACT_OFFSCREEN_TYPE;}fiber.elementType=REACT_OFFSCREEN_TYPE;fiber.lanes=lanes;return fiber;}function createFiberFromLegacyHidden(pendingProps,mode,lanes,key){var fiber=createFiber(LegacyHiddenComponent,pendingProps,key,mode);// TODO: The LegacyHidden fiber shouldn't have a type. It has a tag.
// This needs to be fixed in getComponentName so that it relies on the tag
// instead.
{fiber.type=REACT_LEGACY_HIDDEN_TYPE;}fiber.elementType=REACT_LEGACY_HIDDEN_TYPE;fiber.lanes=lanes;return fiber;}function createFiberFromText(content,mode,lanes){var fiber=createFiber(HostText,content,null,mode);fiber.lanes=lanes;return fiber;}function createFiberFromHostInstanceForDeletion(){var fiber=createFiber(HostComponent,null,null,NoMode);// TODO: These should not need a type.
fiber.elementType='DELETED';fiber.type='DELETED';return fiber;}function createFiberFromPortal(portal,mode,lanes){var pendingProps=portal.children!==null?portal.children:[];var fiber=createFiber(HostPortal,pendingProps,portal.key,mode);fiber.lanes=lanes;fiber.stateNode={containerInfo:portal.containerInfo,pendingChildren:null,// Used by persistent updates
implementation:portal.implementation};return fiber;}// Used for stashing WIP properties to replay failed work in DEV.
function assignFiberPropertiesInDEV(target,source){if(target===null){// This Fiber's initial properties will always be overwritten.
// We only use a Fiber to ensure the same hidden class so DEV isn't slow.
target=createFiber(IndeterminateComponent,null,null,NoMode);}// This is intentionally written as a list of all properties.
// We tried to use Object.assign() instead but this is called in
// the hottest path, and Object.assign() was too slow:
// https://github.com/facebook/react/issues/12502
// This code is DEV-only so size is not a concern.
target.tag=source.tag;target.key=source.key;target.elementType=source.elementType;target.type=source.type;target.stateNode=source.stateNode;target.return=source.return;target.child=source.child;target.sibling=source.sibling;target.index=source.index;target.ref=source.ref;target.pendingProps=source.pendingProps;target.memoizedProps=source.memoizedProps;target.updateQueue=source.updateQueue;target.memoizedState=source.memoizedState;target.dependencies=source.dependencies;target.mode=source.mode;target.flags=source.flags;target.nextEffect=source.nextEffect;target.firstEffect=source.firstEffect;target.lastEffect=source.lastEffect;target.lanes=source.lanes;target.childLanes=source.childLanes;target.alternate=source.alternate;{target.actualDuration=source.actualDuration;target.actualStartTime=source.actualStartTime;target.selfBaseDuration=source.selfBaseDuration;target.treeBaseDuration=source.treeBaseDuration;}target._debugID=source._debugID;target._debugSource=source._debugSource;target._debugOwner=source._debugOwner;target._debugNeedsRemount=source._debugNeedsRemount;target._debugHookTypes=source._debugHookTypes;return target;}function FiberRootNode(containerInfo,tag,hydrate){this.tag=tag;this.containerInfo=containerInfo;this.pendingChildren=null;this.current=null;this.pingCache=null;this.finishedWork=null;this.timeoutHandle=noTimeout;this.context=null;this.pendingContext=null;this.hydrate=hydrate;this.callbackNode=null;this.callbackPriority=NoLanePriority;this.eventTimes=createLaneMap(NoLanes);this.expirationTimes=createLaneMap(NoTimestamp);this.pendingLanes=NoLanes;this.suspendedLanes=NoLanes;this.pingedLanes=NoLanes;this.expiredLanes=NoLanes;this.mutableReadLanes=NoLanes;this.finishedLanes=NoLanes;this.entangledLanes=NoLanes;this.entanglements=createLaneMap(NoLanes);{this.mutableSourceEagerHydrationData=null;}{this.interactionThreadID=tracing$1.unstable_getThreadID();this.memoizedInteractions=new Set();this.pendingInteractionMap=new Map();}{switch(tag){case BlockingRoot:this._debugRootType='createBlockingRoot()';break;case ConcurrentRoot:this._debugRootType='createRoot()';break;case LegacyRoot:this._debugRootType='createLegacyRoot()';break;}}}function createFiberRoot(containerInfo,tag,hydrate,hydrationCallbacks){var root=new FiberRootNode(containerInfo,tag,hydrate);// stateNode is any.
var uninitializedFiber=createHostRootFiber(tag);root.current=uninitializedFiber;uninitializedFiber.stateNode=root;initializeUpdateQueue(uninitializedFiber);return root;}// This ensures that the version used for server rendering matches the one
// that is eventually read during hydration.
// If they don't match there's a potential tear and a full deopt render is required.
function registerMutableSourceForHydration(root,mutableSource){var getVersion=mutableSource._getVersion;var version=getVersion(mutableSource._source);// TODO Clear this data once all pending hydration work is finished.
// Retaining it forever may interfere with GC.
if(root.mutableSourceEagerHydrationData==null){root.mutableSourceEagerHydrationData=[mutableSource,version];}else {root.mutableSourceEagerHydrationData.push(mutableSource,version);}}function createPortal(children,containerInfo,// TODO: figure out the API for cross-renderer implementation.
implementation){var key=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;return {// This tag allow us to uniquely identify this as a React Portal
$$typeof:REACT_PORTAL_TYPE,key:key==null?null:''+key,children:children,containerInfo:containerInfo,implementation:implementation};}var didWarnAboutNestedUpdates;var didWarnAboutFindNodeInStrictMode;{didWarnAboutNestedUpdates=false;didWarnAboutFindNodeInStrictMode={};}function getContextForSubtree(parentComponent){if(!parentComponent){return emptyContextObject;}var fiber=get(parentComponent);var parentContext=findCurrentUnmaskedContext(fiber);if(fiber.tag===ClassComponent){var Component=fiber.type;if(isContextProvider(Component)){return processChildContext(fiber,Component,parentContext);}}return parentContext;}function findHostInstanceWithWarning(component,methodName){{var fiber=get(component);if(fiber===undefined){if(typeof component.render==='function'){{{throw Error("Unable to find node on an unmounted component.");}}}else {{{throw Error("Argument appears to not be a ReactComponent. Keys: "+Object.keys(component));}}}}var hostFiber=findCurrentHostFiber(fiber);if(hostFiber===null){return null;}if(hostFiber.mode&StrictMode){var componentName=getComponentName(fiber.type)||'Component';if(!didWarnAboutFindNodeInStrictMode[componentName]){didWarnAboutFindNodeInStrictMode[componentName]=true;var previousFiber=current;try{setCurrentFiber(hostFiber);if(fiber.mode&StrictMode){error('%s is deprecated in StrictMode. '+'%s was passed an instance of %s which is inside StrictMode. '+'Instead, add a ref directly to the element you want to reference. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-find-node',methodName,methodName,componentName);}else {error('%s is deprecated in StrictMode. '+'%s was passed an instance of %s which renders StrictMode children. '+'Instead, add a ref directly to the element you want to reference. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-find-node',methodName,methodName,componentName);}}finally{// Ideally this should reset to previous but this shouldn't be called in
// render and there's another warning for that anyway.
if(previousFiber){setCurrentFiber(previousFiber);}else {resetCurrentFiber();}}}}return hostFiber.stateNode;}}function createContainer(containerInfo,tag,hydrate,hydrationCallbacks){return createFiberRoot(containerInfo,tag,hydrate);}function updateContainer(element,container,parentComponent,callback){{onScheduleRoot(container,element);}var current$1=container.current;var eventTime=requestEventTime();{// $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
if('undefined'!==typeof jest){warnIfUnmockedScheduler(current$1);warnIfNotScopedWithMatchingAct(current$1);}}var lane=requestUpdateLane(current$1);var context=getContextForSubtree(parentComponent);if(container.context===null){container.context=context;}else {container.pendingContext=context;}{if(isRendering&&current!==null&&!didWarnAboutNestedUpdates){didWarnAboutNestedUpdates=true;error('Render methods should be a pure function of props and state; '+'triggering nested component updates from render is not allowed. '+'If necessary, trigger nested updates in componentDidUpdate.\n\n'+'Check the render method of %s.',getComponentName(current.type)||'Unknown');}}var update=createUpdate(eventTime,lane);// Caution: React DevTools currently depends on this property
// being called "element".
update.payload={element:element};callback=callback===undefined?null:callback;if(callback!==null){{if(typeof callback!=='function'){error('render(...): Expected the last optional `callback` argument to be a '+'function. Instead received: %s.',callback);}}update.callback=callback;}enqueueUpdate(current$1,update);scheduleUpdateOnFiber(current$1,lane,eventTime);return lane;}function getPublicRootInstance(container){var containerFiber=container.current;if(!containerFiber.child){return null;}switch(containerFiber.child.tag){case HostComponent:return getPublicInstance(containerFiber.child.stateNode);default:return containerFiber.child.stateNode;}}function markRetryLaneImpl(fiber,retryLane){var suspenseState=fiber.memoizedState;if(suspenseState!==null&&suspenseState.dehydrated!==null){suspenseState.retryLane=higherPriorityLane(suspenseState.retryLane,retryLane);}}// Increases the priority of thennables when they resolve within this boundary.
function markRetryLaneIfNotHydrated(fiber,retryLane){markRetryLaneImpl(fiber,retryLane);var alternate=fiber.alternate;if(alternate){markRetryLaneImpl(alternate,retryLane);}}function attemptUserBlockingHydration$1(fiber){if(fiber.tag!==SuspenseComponent){// We ignore HostRoots here because we can't increase
// their priority and they should not suspend on I/O,
// since you have to wrap anything that might suspend in
// Suspense.
return;}var eventTime=requestEventTime();var lane=InputDiscreteHydrationLane;scheduleUpdateOnFiber(fiber,lane,eventTime);markRetryLaneIfNotHydrated(fiber,lane);}function attemptContinuousHydration$1(fiber){if(fiber.tag!==SuspenseComponent){// We ignore HostRoots here because we can't increase
// their priority and they should not suspend on I/O,
// since you have to wrap anything that might suspend in
// Suspense.
return;}var eventTime=requestEventTime();var lane=SelectiveHydrationLane;scheduleUpdateOnFiber(fiber,lane,eventTime);markRetryLaneIfNotHydrated(fiber,lane);}function attemptHydrationAtCurrentPriority$1(fiber){if(fiber.tag!==SuspenseComponent){// We ignore HostRoots here because we can't increase
// their priority other than synchronously flush it.
return;}var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);scheduleUpdateOnFiber(fiber,lane,eventTime);markRetryLaneIfNotHydrated(fiber,lane);}function runWithPriority$2(priority,fn){try{setCurrentUpdateLanePriority(priority);return fn();}finally{}}function findHostInstanceWithNoPortals(fiber){var hostFiber=findCurrentHostFiberWithNoPortals(fiber);if(hostFiber===null){return null;}if(hostFiber.tag===FundamentalComponent){return hostFiber.stateNode.instance;}return hostFiber.stateNode;}var shouldSuspendImpl=function(fiber){return false;};function shouldSuspend(fiber){return shouldSuspendImpl(fiber);}var overrideHookState=null;var overrideHookStateDeletePath=null;var overrideHookStateRenamePath=null;var overrideProps=null;var overridePropsDeletePath=null;var overridePropsRenamePath=null;var scheduleUpdate=null;var setSuspenseHandler=null;{var copyWithDeleteImpl=function(obj,path,index){var key=path[index];var updated=Array.isArray(obj)?obj.slice():_assign({},obj);if(index+1===path.length){if(Array.isArray(updated)){updated.splice(key,1);}else {delete updated[key];}return updated;}// $FlowFixMe number or string is fine here
updated[key]=copyWithDeleteImpl(obj[key],path,index+1);return updated;};var copyWithDelete=function(obj,path){return copyWithDeleteImpl(obj,path,0);};var copyWithRenameImpl=function(obj,oldPath,newPath,index){var oldKey=oldPath[index];var updated=Array.isArray(obj)?obj.slice():_assign({},obj);if(index+1===oldPath.length){var newKey=newPath[index];// $FlowFixMe number or string is fine here
updated[newKey]=updated[oldKey];if(Array.isArray(updated)){updated.splice(oldKey,1);}else {delete updated[oldKey];}}else {// $FlowFixMe number or string is fine here
updated[oldKey]=copyWithRenameImpl(// $FlowFixMe number or string is fine here
obj[oldKey],oldPath,newPath,index+1);}return updated;};var copyWithRename=function(obj,oldPath,newPath){if(oldPath.length!==newPath.length){warn('copyWithRename() expects paths of the same length');return;}else {for(var i=0;i<newPath.length-1;i++){if(oldPath[i]!==newPath[i]){warn('copyWithRename() expects paths to be the same except for the deepest key');return;}}}return copyWithRenameImpl(obj,oldPath,newPath,0);};var copyWithSetImpl=function(obj,path,index,value){if(index>=path.length){return value;}var key=path[index];var updated=Array.isArray(obj)?obj.slice():_assign({},obj);// $FlowFixMe number or string is fine here
updated[key]=copyWithSetImpl(obj[key],path,index+1,value);return updated;};var copyWithSet=function(obj,path,value){return copyWithSetImpl(obj,path,0,value);};var findHook=function(fiber,id){// For now, the "id" of stateful hooks is just the stateful hook index.
// This may change in the future with e.g. nested hooks.
var currentHook=fiber.memoizedState;while(currentHook!==null&&id>0){currentHook=currentHook.next;id--;}return currentHook;};// Support DevTools editable values for useState and useReducer.
overrideHookState=function(fiber,id,path,value){var hook=findHook(fiber,id);if(hook!==null){var newState=copyWithSet(hook.memoizedState,path,value);hook.memoizedState=newState;hook.baseState=newState;// We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps=_assign({},fiber.memoizedProps);scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);}};overrideHookStateDeletePath=function(fiber,id,path){var hook=findHook(fiber,id);if(hook!==null){var newState=copyWithDelete(hook.memoizedState,path);hook.memoizedState=newState;hook.baseState=newState;// We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps=_assign({},fiber.memoizedProps);scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);}};overrideHookStateRenamePath=function(fiber,id,oldPath,newPath){var hook=findHook(fiber,id);if(hook!==null){var newState=copyWithRename(hook.memoizedState,oldPath,newPath);hook.memoizedState=newState;hook.baseState=newState;// We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps=_assign({},fiber.memoizedProps);scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);}};// Support DevTools props for function components, forwardRef, memo, host components, etc.
overrideProps=function(fiber,path,value){fiber.pendingProps=copyWithSet(fiber.memoizedProps,path,value);if(fiber.alternate){fiber.alternate.pendingProps=fiber.pendingProps;}scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);};overridePropsDeletePath=function(fiber,path){fiber.pendingProps=copyWithDelete(fiber.memoizedProps,path);if(fiber.alternate){fiber.alternate.pendingProps=fiber.pendingProps;}scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);};overridePropsRenamePath=function(fiber,oldPath,newPath){fiber.pendingProps=copyWithRename(fiber.memoizedProps,oldPath,newPath);if(fiber.alternate){fiber.alternate.pendingProps=fiber.pendingProps;}scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);};scheduleUpdate=function(fiber){scheduleUpdateOnFiber(fiber,SyncLane,NoTimestamp);};setSuspenseHandler=function(newShouldSuspendImpl){shouldSuspendImpl=newShouldSuspendImpl;};}function findHostInstanceByFiber(fiber){var hostFiber=findCurrentHostFiber(fiber);if(hostFiber===null){return null;}return hostFiber.stateNode;}function emptyFindFiberByHostInstance(instance){return null;}function getCurrentFiberForDevTools(){return current;}function injectIntoDevTools(devToolsConfig){var findFiberByHostInstance=devToolsConfig.findFiberByHostInstance;var ReactCurrentDispatcher=ReactSharedInternals.ReactCurrentDispatcher;return injectInternals({bundleType:devToolsConfig.bundleType,version:devToolsConfig.version,rendererPackageName:devToolsConfig.rendererPackageName,rendererConfig:devToolsConfig.rendererConfig,overrideHookState:overrideHookState,overrideHookStateDeletePath:overrideHookStateDeletePath,overrideHookStateRenamePath:overrideHookStateRenamePath,overrideProps:overrideProps,overridePropsDeletePath:overridePropsDeletePath,overridePropsRenamePath:overridePropsRenamePath,setSuspenseHandler:setSuspenseHandler,scheduleUpdate:scheduleUpdate,currentDispatcherRef:ReactCurrentDispatcher,findHostInstanceByFiber:findHostInstanceByFiber,findFiberByHostInstance:findFiberByHostInstance||emptyFindFiberByHostInstance,// React Refresh
findHostInstancesForRefresh:findHostInstancesForRefresh,scheduleRefresh:scheduleRefresh,scheduleRoot:scheduleRoot,setRefreshHandler:setRefreshHandler,// Enables DevTools to append owner stacks to error messages in DEV mode.
getCurrentFiber:getCurrentFiberForDevTools});}function ReactDOMRoot(container,options){this._internalRoot=createRootImpl(container,ConcurrentRoot,options);}function ReactDOMBlockingRoot(container,tag,options){this._internalRoot=createRootImpl(container,tag,options);}ReactDOMRoot.prototype.render=ReactDOMBlockingRoot.prototype.render=function(children){var root=this._internalRoot;{if(typeof arguments[1]==='function'){error('render(...): does not support the second callback argument. '+'To execute a side effect after rendering, declare it in a component body with useEffect().');}var container=root.containerInfo;if(container.nodeType!==COMMENT_NODE){var hostInstance=findHostInstanceWithNoPortals(root.current);if(hostInstance){if(hostInstance.parentNode!==container){error('render(...): It looks like the React-rendered content of the '+'root container was removed without using React. This is not '+'supported and will cause errors. Instead, call '+"root.unmount() to empty a root's container.");}}}}updateContainer(children,root,null,null);};ReactDOMRoot.prototype.unmount=ReactDOMBlockingRoot.prototype.unmount=function(){{if(typeof arguments[0]==='function'){error('unmount(...): does not support a callback argument. '+'To execute a side effect after rendering, declare it in a component body with useEffect().');}}var root=this._internalRoot;var container=root.containerInfo;updateContainer(null,root,null,function(){unmarkContainerAsRoot(container);});};function createRootImpl(container,tag,options){// Tag is either LegacyRoot or Concurrent Root
var hydrate=options!=null&&options.hydrate===true;var hydrationCallbacks=options!=null&&options.hydrationOptions||null;var mutableSources=options!=null&&options.hydrationOptions!=null&&options.hydrationOptions.mutableSources||null;var root=createContainer(container,tag,hydrate);markContainerAsRoot(root.current,container);var containerNodeType=container.nodeType;{var rootContainerElement=container.nodeType===COMMENT_NODE?container.parentNode:container;listenToAllSupportedEvents(rootContainerElement);}if(mutableSources){for(var i=0;i<mutableSources.length;i++){var mutableSource=mutableSources[i];registerMutableSourceForHydration(root,mutableSource);}}return root;}function createLegacyRoot(container,options){return new ReactDOMBlockingRoot(container,LegacyRoot,options);}function isValidContainer(node){return !!(node&&(node.nodeType===ELEMENT_NODE||node.nodeType===DOCUMENT_NODE||node.nodeType===DOCUMENT_FRAGMENT_NODE||node.nodeType===COMMENT_NODE&&node.nodeValue===' react-mount-point-unstable '));}var ReactCurrentOwner$3=ReactSharedInternals.ReactCurrentOwner;var topLevelUpdateWarnings;var warnedAboutHydrateAPI=false;{topLevelUpdateWarnings=function(container){if(container._reactRootContainer&&container.nodeType!==COMMENT_NODE){var hostInstance=findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);if(hostInstance){if(hostInstance.parentNode!==container){error('render(...): It looks like the React-rendered content of this '+'container was removed without using React. This is not '+'supported and will cause errors. Instead, call '+'ReactDOM.unmountComponentAtNode to empty a container.');}}}var isRootRenderedBySomeReact=!!container._reactRootContainer;var rootEl=getReactRootElementInContainer(container);var hasNonRootReactChild=!!(rootEl&&getInstanceFromNode(rootEl));if(hasNonRootReactChild&&!isRootRenderedBySomeReact){error('render(...): Replacing React-rendered children with a new root '+'component. If you intended to update the children of this node, '+'you should instead have the existing children update their state '+'and render the new components instead of calling ReactDOM.render.');}if(container.nodeType===ELEMENT_NODE&&container.tagName&&container.tagName.toUpperCase()==='BODY'){error('render(): Rendering components directly into document.body is '+'discouraged, since its children are often manipulated by third-party '+'scripts and browser extensions. This may lead to subtle '+'reconciliation issues. Try rendering into a container element created '+'for your app.');}};}function getReactRootElementInContainer(container){if(!container){return null;}if(container.nodeType===DOCUMENT_NODE){return container.documentElement;}else {return container.firstChild;}}function shouldHydrateDueToLegacyHeuristic(container){var rootElement=getReactRootElementInContainer(container);return !!(rootElement&&rootElement.nodeType===ELEMENT_NODE&&rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));}function legacyCreateRootFromDOMContainer(container,forceHydrate){var shouldHydrate=forceHydrate||shouldHydrateDueToLegacyHeuristic(container);// First clear any existing content.
if(!shouldHydrate){var warned=false;var rootSibling;while(rootSibling=container.lastChild){{if(!warned&&rootSibling.nodeType===ELEMENT_NODE&&rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)){warned=true;error('render(): Target node has markup rendered by React, but there '+'are unrelated nodes as well. This is most commonly caused by '+'white-space inserted around server-rendered markup.');}}container.removeChild(rootSibling);}}{if(shouldHydrate&&!forceHydrate&&!warnedAboutHydrateAPI){warnedAboutHydrateAPI=true;warn('render(): Calling ReactDOM.render() to hydrate server-rendered markup '+'will stop working in React v18. Replace the ReactDOM.render() call '+'with ReactDOM.hydrate() if you want React to attach to the server HTML.');}}return createLegacyRoot(container,shouldHydrate?{hydrate:true}:undefined);}function warnOnInvalidCallback$1(callback,callerName){{if(callback!==null&&typeof callback!=='function'){error('%s(...): Expected the last optional `callback` argument to be a '+'function. Instead received: %s.',callerName,callback);}}}function legacyRenderSubtreeIntoContainer(parentComponent,children,container,forceHydrate,callback){{topLevelUpdateWarnings(container);warnOnInvalidCallback$1(callback===undefined?null:callback,'render');}// TODO: Without `any` type, Flow says "Property cannot be accessed on any
// member of intersection type." Whyyyyyy.
var root=container._reactRootContainer;var fiberRoot;if(!root){// Initial mount
root=container._reactRootContainer=legacyCreateRootFromDOMContainer(container,forceHydrate);fiberRoot=root._internalRoot;if(typeof callback==='function'){var originalCallback=callback;callback=function(){var instance=getPublicRootInstance(fiberRoot);originalCallback.call(instance);};}// Initial mount should not be batched.
unbatchedUpdates(function(){updateContainer(children,fiberRoot,parentComponent,callback);});}else {fiberRoot=root._internalRoot;if(typeof callback==='function'){var _originalCallback=callback;callback=function(){var instance=getPublicRootInstance(fiberRoot);_originalCallback.call(instance);};}// Update
updateContainer(children,fiberRoot,parentComponent,callback);}return getPublicRootInstance(fiberRoot);}function findDOMNode(componentOrElement){{var owner=ReactCurrentOwner$3.current;if(owner!==null&&owner.stateNode!==null){var warnedAboutRefsInRender=owner.stateNode._warnedAboutRefsInRender;if(!warnedAboutRefsInRender){error('%s is accessing findDOMNode inside its render(). '+'render() should be a pure function of props and state. It should '+'never access something that requires stale data from the previous '+'render, such as refs. Move this logic to componentDidMount and '+'componentDidUpdate instead.',getComponentName(owner.type)||'A component');}owner.stateNode._warnedAboutRefsInRender=true;}}if(componentOrElement==null){return null;}if(componentOrElement.nodeType===ELEMENT_NODE){return componentOrElement;}{return findHostInstanceWithWarning(componentOrElement,'findDOMNode');}}function hydrate(element,container,callback){if(!isValidContainer(container)){{throw Error("Target container is not a DOM element.");}}{var isModernRoot=isContainerMarkedAsRoot(container)&&container._reactRootContainer===undefined;if(isModernRoot){error('You are calling ReactDOM.hydrate() on a container that was previously '+'passed to ReactDOM.createRoot(). This is not supported. '+'Did you mean to call createRoot(container, {hydrate: true}).render(element)?');}}// TODO: throw or warn if we couldn't hydrate?
return legacyRenderSubtreeIntoContainer(null,element,container,true,callback);}function render(element,container,callback){if(!isValidContainer(container)){{throw Error("Target container is not a DOM element.");}}{var isModernRoot=isContainerMarkedAsRoot(container)&&container._reactRootContainer===undefined;if(isModernRoot){error('You are calling ReactDOM.render() on a container that was previously '+'passed to ReactDOM.createRoot(). This is not supported. '+'Did you mean to call root.render(element)?');}}return legacyRenderSubtreeIntoContainer(null,element,container,false,callback);}function unstable_renderSubtreeIntoContainer(parentComponent,element,containerNode,callback){if(!isValidContainer(containerNode)){{throw Error("Target container is not a DOM element.");}}if(!(parentComponent!=null&&has(parentComponent))){{throw Error("parentComponent must be a valid React Component");}}return legacyRenderSubtreeIntoContainer(parentComponent,element,containerNode,false,callback);}function unmountComponentAtNode(container){if(!isValidContainer(container)){{throw Error("unmountComponentAtNode(...): Target container is not a DOM element.");}}{var isModernRoot=isContainerMarkedAsRoot(container)&&container._reactRootContainer===undefined;if(isModernRoot){error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously '+'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?');}}if(container._reactRootContainer){{var rootEl=getReactRootElementInContainer(container);var renderedByDifferentReact=rootEl&&!getInstanceFromNode(rootEl);if(renderedByDifferentReact){error("unmountComponentAtNode(): The node you're attempting to unmount "+'was rendered by another copy of React.');}}// Unmount should not be batched.
unbatchedUpdates(function(){legacyRenderSubtreeIntoContainer(null,null,container,false,function(){// $FlowFixMe This should probably use `delete container._reactRootContainer`
container._reactRootContainer=null;unmarkContainerAsRoot(container);});});// If you call unmountComponentAtNode twice in quick succession, you'll
// get `true` twice. That's probably fine?
return true;}else {{var _rootEl=getReactRootElementInContainer(container);var hasNonRootReactChild=!!(_rootEl&&getInstanceFromNode(_rootEl));// Check if the container itself is a React root node.
var isContainerReactRoot=container.nodeType===ELEMENT_NODE&&isValidContainer(container.parentNode)&&!!container.parentNode._reactRootContainer;if(hasNonRootReactChild){error("unmountComponentAtNode(): The node you're attempting to unmount "+'was rendered by React and is not a top-level container. %s',isContainerReactRoot?'You may have accidentally passed in a React root node instead '+'of its container.':'Instead, have the parent component update its state and '+'rerender in order to remove this component.');}}return false;}}setAttemptUserBlockingHydration(attemptUserBlockingHydration$1);setAttemptContinuousHydration(attemptContinuousHydration$1);setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);setAttemptHydrationAtPriority(runWithPriority$2);var didWarnAboutUnstableCreatePortal=false;{if(typeof Map!=='function'||// $FlowIssue Flow incorrectly thinks Map has no prototype
Map.prototype==null||typeof Map.prototype.forEach!=='function'||typeof Set!=='function'||// $FlowIssue Flow incorrectly thinks Set has no prototype
Set.prototype==null||typeof Set.prototype.clear!=='function'||typeof Set.prototype.forEach!=='function'){error('React depends on Map and Set built-in types. Make sure that you load a '+'polyfill in older browsers. https://reactjs.org/link/react-polyfills');}}setRestoreImplementation(restoreControlledState$3);setBatchingImplementation(batchedUpdates$1,discreteUpdates$1,flushDiscreteUpdates,batchedEventUpdates$1);function createPortal$1(children,container){var key=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(!isValidContainer(container)){{throw Error("Target container is not a DOM element.");}}// TODO: pass ReactDOM portal implementation as third argument
// $FlowFixMe The Flow type is opaque but there's no way to actually create it.
return createPortal(children,container,null,key);}function renderSubtreeIntoContainer(parentComponent,element,containerNode,callback){return unstable_renderSubtreeIntoContainer(parentComponent,element,containerNode,callback);}function unstable_createPortal(children,container){var key=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;{if(!didWarnAboutUnstableCreatePortal){didWarnAboutUnstableCreatePortal=true;warn('The ReactDOM.unstable_createPortal() alias has been deprecated, '+'and will be removed in React 18+. Update your code to use '+'ReactDOM.createPortal() instead. It has the exact same API, '+'but without the "unstable_" prefix.');}}return createPortal$1(children,container,key);}var Internals={// Keep in sync with ReactTestUtils.js, and ReactTestUtilsAct.js.
// This is an array for better minification.
Events:[getInstanceFromNode,getNodeFromInstance,getFiberCurrentPropsFromNode,enqueueStateRestore,restoreStateIfNeeded,flushPassiveEffects,// TODO: This is related to `act`, not events. Move to separate key?
IsThisRendererActing]};var foundDevTools=injectIntoDevTools({findFiberByHostInstance:getClosestInstanceFromNode,bundleType:1,version:ReactVersion,rendererPackageName:'react-dom'});{if(!foundDevTools&&canUseDOM&&window.top===window.self){// If we're in Chrome or Firefox, provide a download link if not installed.
if(navigator.userAgent.indexOf('Chrome')>-1&&navigator.userAgent.indexOf('Edge')===-1||navigator.userAgent.indexOf('Firefox')>-1){var protocol=window.location.protocol;// Don't warn in exotic cases like chrome-extension://.
if(/^(https?|file):$/.test(protocol)){// eslint-disable-next-line react-internal/no-production-logging
console.info('%cDownload the React DevTools '+'for a better development experience: '+'https://reactjs.org/link/react-devtools'+(protocol==='file:'?'\nYou might need to use a local HTTP server (instead of file://): '+'https://reactjs.org/link/react-devtools-faq':''),'font-weight:bold');}}}}exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Internals;exports.createPortal=createPortal$1;exports.findDOMNode=findDOMNode;exports.flushSync=flushSync;exports.hydrate=hydrate;exports.render=render;exports.unmountComponentAtNode=unmountComponentAtNode;exports.unstable_batchedUpdates=batchedUpdates$1;exports.unstable_createPortal=unstable_createPortal;exports.unstable_renderSubtreeIntoContainer=renderSubtreeIntoContainer;exports.version=ReactVersion;})();}
});
var reactDom = createCommonjsModule(function (module) {
{module.exports=reactDom_development;}
});
class AddExpenseModal extends obsidian.Modal {
constructor(plugin, updater, operation, initialState) {
super(plugin.app);
this.onOpen = () => {
reactDom.render(react.createElement(EditTransaction, {
displayFileWarning: !this.plugin.settings.ledgerFile.endsWith('.ledger'),
currencySymbol: this.plugin.settings.currencySymbol,
initialState: this.initialState,
operation: this.operation,
updater: this.updater,
txCache: this.plugin.txCache,
close: () => this.close(),
}), this.contentEl);
};
this.onClose = () => {
reactDom.unmountComponentAtNode(this.contentEl);
this.contentEl.empty();
};
this.plugin = plugin;
this.updater = updater;
this.operation = operation;
this.initialState = initialState || emptyTransaction;
}
}
var moo = createCommonjsModule(function (module) {
(function(root,factory){if(module.exports){module.exports=factory();}else {root.moo=factory();}})(commonjsGlobal,function(){var hasOwnProperty=Object.prototype.hasOwnProperty;var toString=Object.prototype.toString;var hasSticky=typeof new RegExp().sticky==='boolean';/***************************************************************************/function isRegExp(o){return o&&toString.call(o)==='[object RegExp]';}function isObject(o){return o&&typeof o==='object'&&!isRegExp(o)&&!Array.isArray(o);}function reEscape(s){return s.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&');}function reGroups(s){var re=new RegExp('|'+s);return re.exec('').length-1;}function reCapture(s){return '('+s+')';}function reUnion(regexps){if(!regexps.length)return '(?!)';var source=regexps.map(function(s){return "(?:"+s+")";}).join('|');return "(?:"+source+")";}function regexpOrLiteral(obj){if(typeof obj==='string'){return '(?:'+reEscape(obj)+')';}else if(isRegExp(obj)){// TODO: consider /u support
if(obj.ignoreCase)throw new Error('RegExp /i flag not allowed');if(obj.global)throw new Error('RegExp /g flag is implied');if(obj.sticky)throw new Error('RegExp /y flag is implied');if(obj.multiline)throw new Error('RegExp /m flag is implied');return obj.source;}else {throw new Error('Not a pattern: '+obj);}}function objectToRules(object){var keys=Object.getOwnPropertyNames(object);var result=[];for(var i=0;i<keys.length;i++){var key=keys[i];var thing=object[key];var rules=[].concat(thing);if(key==='include'){for(var j=0;j<rules.length;j++){result.push({include:rules[j]});}continue;}var match=[];rules.forEach(function(rule){if(isObject(rule)){if(match.length)result.push(ruleOptions(key,match));result.push(ruleOptions(key,rule));match=[];}else {match.push(rule);}});if(match.length)result.push(ruleOptions(key,match));}return result;}function arrayToRules(array){var result=[];for(var i=0;i<array.length;i++){var obj=array[i];if(obj.include){var include=[].concat(obj.include);for(var j=0;j<include.length;j++){result.push({include:include[j]});}continue;}if(!obj.type){throw new Error('Rule has no type: '+JSON.stringify(obj));}result.push(ruleOptions(obj.type,obj));}return result;}function ruleOptions(type,obj){if(!isObject(obj)){obj={match:obj};}if(obj.include){throw new Error('Matching rules cannot also include states');}// nb. error and fallback imply lineBreaks
var options={defaultType:type,lineBreaks:!!obj.error||!!obj.fallback,pop:false,next:null,push:null,error:false,fallback:false,value:null,type:null,shouldThrow:false};// Avoid Object.assign(), so we support IE9+
for(var key in obj){if(hasOwnProperty.call(obj,key)){options[key]=obj[key];}}// type transform cannot be a string
if(typeof options.type==='string'&&type!==options.type){throw new Error("Type transform cannot be a string (type '"+options.type+"' for token '"+type+"')");}// convert to array
var match=options.match;options.match=Array.isArray(match)?match:match?[match]:[];options.match.sort(function(a,b){return isRegExp(a)&&isRegExp(b)?0:isRegExp(b)?-1:isRegExp(a)?+1:b.length-a.length;});return options;}function toRules(spec){return Array.isArray(spec)?arrayToRules(spec):objectToRules(spec);}var defaultErrorRule=ruleOptions('error',{lineBreaks:true,shouldThrow:true});function compileRules(rules,hasStates){var errorRule=null;var fast=Object.create(null);var fastAllowed=true;var unicodeFlag=null;var groups=[];var parts=[];// If there is a fallback rule, then disable fast matching
for(var i=0;i<rules.length;i++){if(rules[i].fallback){fastAllowed=false;}}for(var i=0;i<rules.length;i++){var options=rules[i];if(options.include){// all valid inclusions are removed by states() preprocessor
throw new Error('Inheritance is not allowed in stateless lexers');}if(options.error||options.fallback){// errorRule can only be set once
if(errorRule){if(!options.fallback===!errorRule.fallback){throw new Error("Multiple "+(options.fallback?"fallback":"error")+" rules not allowed (for token '"+options.defaultType+"')");}else {throw new Error("fallback and error are mutually exclusive (for token '"+options.defaultType+"')");}}errorRule=options;}var match=options.match.slice();if(fastAllowed){while(match.length&&typeof match[0]==='string'&&match[0].length===1){var word=match.shift();fast[word.charCodeAt(0)]=options;}}// Warn about inappropriate state-switching options
if(options.pop||options.push||options.next){if(!hasStates){throw new Error("State-switching options are not allowed in stateless lexers (for token '"+options.defaultType+"')");}if(options.fallback){throw new Error("State-switching options are not allowed on fallback tokens (for token '"+options.defaultType+"')");}}// Only rules with a .match are included in the RegExp
if(match.length===0){continue;}fastAllowed=false;groups.push(options);// Check unicode flag is used everywhere or nowhere
for(var j=0;j<match.length;j++){var obj=match[j];if(!isRegExp(obj)){continue;}if(unicodeFlag===null){unicodeFlag=obj.unicode;}else if(unicodeFlag!==obj.unicode&&options.fallback===false){throw new Error('If one rule is /u then all must be');}}// convert to RegExp
var pat=reUnion(match.map(regexpOrLiteral));// validate
var regexp=new RegExp(pat);if(regexp.test("")){throw new Error("RegExp matches empty string: "+regexp);}var groupCount=reGroups(pat);if(groupCount>0){throw new Error("RegExp has capture groups: "+regexp+"\nUse (?: … ) instead");}// try and detect rules matching newlines
if(!options.lineBreaks&&regexp.test('\n')){throw new Error('Rule should declare lineBreaks: '+regexp);}// store regex
parts.push(reCapture(pat));}// If there's no fallback rule, use the sticky flag so we only look for
// matches at the current index.
//
// If we don't support the sticky flag, then fake it using an irrefutable
// match (i.e. an empty pattern).
var fallbackRule=errorRule&&errorRule.fallback;var flags=hasSticky&&!fallbackRule?'ym':'gm';var suffix=hasSticky||fallbackRule?'':'|';if(unicodeFlag===true)flags+="u";var combined=new RegExp(reUnion(parts)+suffix,flags);return {regexp:combined,groups:groups,fast:fast,error:errorRule||defaultErrorRule};}function compile(rules){var result=compileRules(toRules(rules));return new Lexer({start:result},'start');}function checkStateGroup(g,name,map){var state=g&&(g.push||g.next);if(state&&!map[state]){throw new Error("Missing state '"+state+"' (in token '"+g.defaultType+"' of state '"+name+"')");}if(g&&g.pop&&+g.pop!==1){throw new Error("pop must be 1 (in token '"+g.defaultType+"' of state '"+name+"')");}}function compileStates(states,start){var all=states.$all?toRules(states.$all):[];delete states.$all;var keys=Object.getOwnPropertyNames(states);if(!start)start=keys[0];var ruleMap=Object.create(null);for(var i=0;i<keys.length;i++){var key=keys[i];ruleMap[key]=toRules(states[key]).concat(all);}for(var i=0;i<keys.length;i++){var key=keys[i];var rules=ruleMap[key];var included=Object.create(null);for(var j=0;j<rules.length;j++){var rule=rules[j];if(!rule.include)continue;var splice=[j,1];if(rule.include!==key&&!included[rule.include]){included[rule.include]=true;var newRules=ruleMap[rule.include];if(!newRules){throw new Error("Cannot include nonexistent state '"+rule.include+"' (in state '"+key+"')");}for(var k=0;k<newRules.length;k++){var newRule=newRules[k];if(rules.indexOf(newRule)!==-1)continue;splice.push(newRule);}}rules.splice.apply(rules,splice);j--;}}var map=Object.create(null);for(var i=0;i<keys.length;i++){var key=keys[i];map[key]=compileRules(ruleMap[key],true);}for(var i=0;i<keys.length;i++){var name=keys[i];var state=map[name];var groups=state.groups;for(var j=0;j<groups.length;j++){checkStateGroup(groups[j],name,map);}var fastKeys=Object.getOwnPropertyNames(state.fast);for(var j=0;j<fastKeys.length;j++){checkStateGroup(state.fast[fastKeys[j]],name,map);}}return new Lexer(map,start);}function keywordTransform(map){var reverseMap=Object.create(null);var byLength=Object.create(null);var types=Object.getOwnPropertyNames(map);for(var i=0;i<types.length;i++){var tokenType=types[i];var item=map[tokenType];var keywordList=Array.isArray(item)?item:[item];keywordList.forEach(function(keyword){(byLength[keyword.length]=byLength[keyword.length]||[]).push(keyword);if(typeof keyword!=='string'){throw new Error("keyword must be string (in keyword '"+tokenType+"')");}reverseMap[keyword]=tokenType;});}// fast string lookup
// https://jsperf.com/string-lookups
function str(x){return JSON.stringify(x);}var source='';source+='switch (value.length) {\n';for(var length in byLength){var keywords=byLength[length];source+='case '+length+':\n';source+='switch (value) {\n';keywords.forEach(function(keyword){var tokenType=reverseMap[keyword];source+='case '+str(keyword)+': return '+str(tokenType)+'\n';});source+='}\n';}source+='}\n';return Function('value',source);// type
}/***************************************************************************/var Lexer=function(states,state){this.startState=state;this.states=states;this.buffer='';this.stack=[];this.reset();};Lexer.prototype.reset=function(data,info){this.buffer=data||'';this.index=0;this.line=info?info.line:1;this.col=info?info.col:1;this.queuedToken=info?info.queuedToken:null;this.queuedThrow=info?info.queuedThrow:null;this.setState(info?info.state:this.startState);this.stack=info&&info.stack?info.stack.slice():[];return this;};Lexer.prototype.save=function(){return {line:this.line,col:this.col,state:this.state,stack:this.stack.slice(),queuedToken:this.queuedToken,queuedThrow:this.queuedThrow};};Lexer.prototype.setState=function(state){if(!state||this.state===state)return;this.state=state;var info=this.states[state];this.groups=info.groups;this.error=info.error;this.re=info.regexp;this.fast=info.fast;};Lexer.prototype.popState=function(){this.setState(this.stack.pop());};Lexer.prototype.pushState=function(state){this.stack.push(this.state);this.setState(state);};var eat=hasSticky?function(re,buffer){// assume re is /y
return re.exec(buffer);}:function(re,buffer){// assume re is /g
var match=re.exec(buffer);// will always match, since we used the |(?:) trick
if(match[0].length===0){return null;}return match;};Lexer.prototype._getGroup=function(match){var groupCount=this.groups.length;for(var i=0;i<groupCount;i++){if(match[i+1]!==undefined){return this.groups[i];}}throw new Error('Cannot find token type for matched text');};function tokenToString(){return this.value;}Lexer.prototype.next=function(){var index=this.index;// If a fallback token matched, we don't need to re-run the RegExp
if(this.queuedGroup){var token=this._token(this.queuedGroup,this.queuedText,index);this.queuedGroup=null;this.queuedText="";return token;}var buffer=this.buffer;if(index===buffer.length){return;// EOF
}// Fast matching for single characters
var group=this.fast[buffer.charCodeAt(index)];if(group){return this._token(group,buffer.charAt(index),index);}// Execute RegExp
var re=this.re;re.lastIndex=index;var match=eat(re,buffer);// Error tokens match the remaining buffer
var error=this.error;if(match==null){return this._token(error,buffer.slice(index,buffer.length),index);}var group=this._getGroup(match);var text=match[0];if(error.fallback&&match.index!==index){this.queuedGroup=group;this.queuedText=text;// Fallback tokens contain the unmatched portion of the buffer
return this._token(error,buffer.slice(index,match.index),index);}return this._token(group,text,index);};Lexer.prototype._token=function(group,text,offset){// count line breaks
var lineBreaks=0;if(group.lineBreaks){var matchNL=/\n/g;var nl=1;if(text==='\n'){lineBreaks=1;}else {while(matchNL.exec(text)){lineBreaks++;nl=matchNL.lastIndex;}}}var token={type:typeof group.type==='function'&&group.type(text)||group.defaultType,value:typeof group.value==='function'?group.value(text):text,text:text,toString:tokenToString,offset:offset,lineBreaks:lineBreaks,line:this.line,col:this.col};// nb. adding more props to token object will make V8 sad!
var size=text.length;this.index+=size;this.line+=lineBreaks;if(lineBreaks!==0){this.col=size-nl+1;}else {this.col+=size;}// throw, if no rule with {error: true}
if(group.shouldThrow){throw new Error(this.formatError(token,"invalid syntax"));}if(group.pop)this.popState();else if(group.push)this.pushState(group.push);else if(group.next)this.setState(group.next);return token;};if(typeof Symbol!=='undefined'&&Symbol.iterator){var LexerIterator=function(lexer){this.lexer=lexer;};LexerIterator.prototype.next=function(){var token=this.lexer.next();return {value:token,done:!token};};LexerIterator.prototype[Symbol.iterator]=function(){return this;};Lexer.prototype[Symbol.iterator]=function(){return new LexerIterator(this);};}Lexer.prototype.formatError=function(token,message){if(token==null){// An undefined token indicates EOF
var text=this.buffer.slice(this.index);var token={text:text,offset:this.index,lineBreaks:text.indexOf('\n')===-1?0:1,line:this.line,col:this.col};}var start=Math.max(0,token.offset-token.col+1);var eol=token.lineBreaks?token.text.indexOf('\n'):token.text.length;var firstLine=this.buffer.substring(start,token.offset+eol);message+=" at line "+token.line+" col "+token.col+":\n\n";message+=" "+firstLine+"\n";message+=" "+Array(token.col).join(" ")+"^";return message;};Lexer.prototype.clone=function(){return new Lexer(this.states,this.state);};Lexer.prototype.has=function(tokenType){return true;};return {compile:compile,states:compileStates,error:Object.freeze({error:true}),fallback:Object.freeze({fallback:true}),keywords:keywordTransform};});
});
// Generated automatically by nearley, version 2.20.1
// http://github.com/Hardmath123/nearley
// Bypasses TS6133. Allow declared but unused functions.
// @ts-ignore
function id(d) { return d[0]; }
const lexer = moo.states({
main: {
date: { match: /[0-9]{4}[-\/][0-9]{2}[-\/][0-9]{2}/, next: 'txStart' },
alias: { match: 'alias', next: 'alias' },
comment: { match: /[;#|][^\n]+/, value: (s) => s.slice(1).trim() },
newline: { match: '\n', lineBreaks: true },
},
txStart: {
check: { match: /\([0-9]+\)[ \t]+/, value: (s) => s.trim().slice(1, -1) },
ws: /[ \t]+/,
reconciled: /[!*]/,
6 months ago
payee: { match: /[^!*;#|\n][^!;#|\n]+/, value: (s) => s.trim() },
comment: { match: /[;#|][^\n]+/, value: (s) => s.slice(1).trim() },
newline: { match: '\n', lineBreaks: true, next: 'expenseLine' },
},
expenseLine: {
newline: { match: '\n', lineBreaks: true },
ws: /[ \t]+/,
6 months ago
absoluteNumber: { match: /[0-9.,]+/, value: (s) => s.replace(/,/g, '') },
numberSign: /-/,
currency: /[$£₤€₳₿₹¥¥₩Р₱₽₴₫]/,
reconciled: /[!*]/,
comment: { match: /[;#|][^\n]+/, value: (s) => s.slice(1).trim() },
2 years ago
assertion: { match: /==?\*?/ },
6 months ago
account: { match: /[^$£₤€₳₿₹¥¥₩Р₱₽₴₫;#|\n\-]+/, value: (s) => s.trim() },
},
alias: {
account: { match: /[a-zA-Z0-9: ]+/, value: (s) => s.trim() },
equal: '=',
newline: { match: '\n', lineBreaks: true, next: 'main' },
},
});
const grammar = {
Lexer: lexer,
ParserRules: [
{ "name": "main", "symbols": ["element"] },
{ "name": "main", "symbols": ["main", (lexer.has("newline") ? { type: "newline" } : newline), "element"], "postprocess": ([rest, , l]) => { return [rest, l].flat(1); } },
{ "name": "element", "symbols": ["transaction"], "postprocess": ([t]) => { var l = t.blockLine; delete t.blockLine; return { type: 'tx', blockLine: l, value: t }; } },
{ "name": "element", "symbols": [(lexer.has("comment") ? { type: "comment" } : comment)], "postprocess": ([c]) => { return { type: 'comment', blockLine: c.line, value: c.value }; } },
{ "name": "element", "symbols": ["alias"], "postprocess": ([a]) => { var l = a.blockLine; delete a.blockLine; return { type: 'alias', blockLine: l, value: a }; } },
{ "name": "transaction$ebnf$1", "symbols": ["check"], "postprocess": id },
{ "name": "transaction$ebnf$1", "symbols": [], "postprocess": () => null },
{ "name": "transaction$ebnf$2", "symbols": [(lexer.has("comment") ? { type: "comment" } : comment)], "postprocess": id },
{ "name": "transaction$ebnf$2", "symbols": [], "postprocess": () => null },
{ "name": "transaction", "symbols": [(lexer.has("date") ? { type: "date" } : date), (lexer.has("ws") ? { type: "ws" } : ws), "transaction$ebnf$1", (lexer.has("payee") ? { type: "payee" } : payee), "transaction$ebnf$2", (lexer.has("newline") ? { type: "newline" } : newline), "expenselines"], "postprocess": function (d) {
return {
blockLine: d[0].line,
date: d[0].value,
check: d[2] || undefined,
payee: d[3].value,
comment: d[4]?.value || undefined,
expenselines: d[6]
};
}
},
{ "name": "expenselines", "symbols": ["expenseline"], "postprocess": ([l]) => l },
{ "name": "expenselines", "symbols": ["expenselines", (lexer.has("newline") ? { type: "newline" } : newline), "expenseline"], "postprocess": ([rest, , l]) => { return [rest, l].flat(1); } },
{ "name": "expenseline$ebnf$1", "symbols": [(lexer.has("ws") ? { type: "ws" } : ws)] },
{ "name": "expenseline$ebnf$1", "symbols": ["expenseline$ebnf$1", (lexer.has("ws") ? { type: "ws" } : ws)], "postprocess": (d) => d[0].concat([d[1]]) },
{ "name": "expenseline$ebnf$2", "symbols": ["reconciled"], "postprocess": id },
{ "name": "expenseline$ebnf$2", "symbols": [], "postprocess": () => null },
{ "name": "expenseline$ebnf$3", "symbols": ["amount"], "postprocess": id },
{ "name": "expenseline$ebnf$3", "symbols": [], "postprocess": () => null },
2 years ago
{ "name": "expenseline$ebnf$4", "symbols": ["balance"], "postprocess": id },
{ "name": "expenseline$ebnf$4", "symbols": [], "postprocess": () => null },
{ "name": "expenseline$ebnf$5", "symbols": [] },
{ "name": "expenseline$ebnf$5", "symbols": ["expenseline$ebnf$5", (lexer.has("ws") ? { type: "ws" } : ws)], "postprocess": (d) => d[0].concat([d[1]]) },
{ "name": "expenseline$ebnf$6", "symbols": [(lexer.has("comment") ? { type: "comment" } : comment)], "postprocess": id },
{ "name": "expenseline$ebnf$6", "symbols": [], "postprocess": () => null },
{ "name": "expenseline", "symbols": ["expenseline$ebnf$1", "expenseline$ebnf$2", (lexer.has("account") ? { type: "account" } : account), "expenseline$ebnf$3", "expenseline$ebnf$4", "expenseline$ebnf$5", "expenseline$ebnf$6"], "postprocess": function ([, r, acct, amt, _ba, , cmt]) {
return {
2 years ago
reconcile: r || '',
account: acct.value,
currency: amt?.currency,
amount: amt?.amount,
comment: cmt?.value,
};
}
},
2 years ago
{ "name": "expenseline$ebnf$7", "symbols": [(lexer.has("ws") ? { type: "ws" } : ws)] },
{ "name": "expenseline$ebnf$7", "symbols": ["expenseline$ebnf$7", (lexer.has("ws") ? { type: "ws" } : ws)], "postprocess": (d) => d[0].concat([d[1]]) },
{ "name": "expenseline", "symbols": ["expenseline$ebnf$7", (lexer.has("comment") ? { type: "comment" } : comment)], "postprocess": ([, c]) => { return { comment: c.value }; } },
{ "name": "balance$ebnf$1", "symbols": [] },
{ "name": "balance$ebnf$1", "symbols": ["balance$ebnf$1", (lexer.has("ws") ? { type: "ws" } : ws)], "postprocess": (d) => d[0].concat([d[1]]) },
{ "name": "balance$ebnf$2", "symbols": [(lexer.has("ws") ? { type: "ws" } : ws)] },
{ "name": "balance$ebnf$2", "symbols": ["balance$ebnf$2", (lexer.has("ws") ? { type: "ws" } : ws)], "postprocess": (d) => d[0].concat([d[1]]) },
{ "name": "balance", "symbols": ["balance$ebnf$1", (lexer.has("assertion") ? { type: "assertion" } : assertion), "balance$ebnf$2", "amount"], "postprocess": (d) => { return {}; } },
{ "name": "reconciled$ebnf$1", "symbols": [(lexer.has("ws") ? { type: "ws" } : ws)] },
{ "name": "reconciled$ebnf$1", "symbols": ["reconciled$ebnf$1", (lexer.has("ws") ? { type: "ws" } : ws)], "postprocess": (d) => d[0].concat([d[1]]) },
{ "name": "reconciled", "symbols": [(lexer.has("reconciled") ? { type: "reconciled" } : reconciled), "reconciled$ebnf$1"], "postprocess": ([r,]) => r.value },
{ "name": "alias", "symbols": [{ "literal": "alias" }, (lexer.has("account") ? { type: "account" } : account), (lexer.has("equal") ? { type: "equal" } : equal), (lexer.has("account") ? { type: "account" } : account)], "postprocess": ([, l, , r]) => { return { blockLine: l.line, left: l.value, right: r.value }; } },
6 months ago
{ "name": "amount", "symbols": [(lexer.has("currency") ? { type: "currency" } : currency), (lexer.has("absoluteNumber") ? { type: "absoluteNumber" } : absoluteNumber)], "postprocess": ([c, a]) => { return { currency: c.value, amount: parseFloat(a.value) }; } },
{ "name": "amount", "symbols": [(lexer.has("currency") ? { type: "currency" } : currency), (lexer.has("numberSign") ? { type: "numberSign" } : numberSign), (lexer.has("absoluteNumber") ? { type: "absoluteNumber" } : absoluteNumber)], "postprocess": ([c, ns, a]) => { return { currency: c.value, amount: parseFloat(ns.value + a.value) }; } },
{ "name": "amount", "symbols": [(lexer.has("numberSign") ? { type: "numberSign" } : numberSign), (lexer.has("currency") ? { type: "currency" } : currency), (lexer.has("absoluteNumber") ? { type: "absoluteNumber" } : absoluteNumber)], "postprocess": ([ns, c, a]) => { return { currency: c.value, amount: parseFloat(ns.value + a.value) }; } },
{ "name": "check", "symbols": [(lexer.has("check") ? { type: "check" } : check)], "postprocess": ([c]) => parseFloat(c.value) }
],
ParserStart: "main",
};
var nearley = createCommonjsModule(function (module) {
(function(root,factory){if(module.exports){module.exports=factory();}else {root.nearley=factory();}})(commonjsGlobal,function(){function Rule(name,symbols,postprocess){this.id=++Rule.highestId;this.name=name;this.symbols=symbols;// a list of literal | regex class | nonterminal
this.postprocess=postprocess;return this;}Rule.highestId=0;Rule.prototype.toString=function(withCursorAt){var symbolSequence=typeof withCursorAt==="undefined"?this.symbols.map(getSymbolShortDisplay).join(' '):this.symbols.slice(0,withCursorAt).map(getSymbolShortDisplay).join(' ')+" ● "+this.symbols.slice(withCursorAt).map(getSymbolShortDisplay).join(' ');return this.name+" → "+symbolSequence;};// a State is a rule at a position from a given starting point in the input stream (reference)
function State(rule,dot,reference,wantedBy){this.rule=rule;this.dot=dot;this.reference=reference;this.data=[];this.wantedBy=wantedBy;this.isComplete=this.dot===rule.symbols.length;}State.prototype.toString=function(){return "{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0);};State.prototype.nextState=function(child){var state=new State(this.rule,this.dot+1,this.reference,this.wantedBy);state.left=this;state.right=child;if(state.isComplete){state.data=state.build();// Having right set here will prevent the right state and its children
// form being garbage collected
state.right=undefined;}return state;};State.prototype.build=function(){var children=[];var node=this;do{children.push(node.right.data);node=node.left;}while(node.left);children.reverse();return children;};State.prototype.finish=function(){if(this.rule.postprocess){this.data=this.rule.postprocess(this.data,this.reference,Parser.fail);}};function Column(grammar,index){this.grammar=grammar;this.index=index;this.states=[];this.wants={};// states indexed by the non-terminal they expect
this.scannable=[];// list of states that expect a token
this.completed={};// states that are nullable
}Column.prototype.process=function(nextColumn){var states=this.states;var wants=this.wants;var completed=this.completed;for(var w=0;w<states.length;w++){// nb. we push() during iteration
var state=states[w];if(state.isComplete){state.finish();if(state.data!==Parser.fail){// complete
var wantedBy=state.wantedBy;for(var i=wantedBy.length;i--;){// this line is hot
var left=wantedBy[i];this.complete(left,state);}// special-case nullables
if(state.reference===this.index){// make sure future predictors of this rule get completed.
var exp=state.rule.name;(this.completed[exp]=this.completed[exp]||[]).push(state);}}}else {// queue scannable states
var exp=state.rule.symbols[state.dot];if(typeof exp!=='string'){this.scannable.push(state);continue;}// predict
if(wants[exp]){wants[exp].push(state);if(completed.hasOwnProperty(exp)){var nulls=completed[exp];for(var i=0;i<nulls.length;i++){var right=nulls[i];this.complete(state,right);}}}else {wants[exp]=[state];this.predict(exp);}}}};Column.prototype.predict=function(exp){var rules=this.grammar.byName[exp]||[];for(var i=0;i<rules.length;i++){var r=rules[i];var wantedBy=this.wants[exp];var s=new State(r,0,this.index,wantedBy);this.states.push(s);}};Column.prototype.complete=function(left,right){var copy=left.nextState(right);this.states.push(copy);};function Grammar(rules,start){this.rules=rules;this.start=start||this.rules[0].name;var byName=this.byName={};this.rules.forEach(function(rule){if(!byName.hasOwnProperty(rule.name)){byName[rule.name]=[];}byName[rule.name].push(rule);});}// So we can allow passing (rules, start) directly to Parser for backwards compatibility
Grammar.fromCompiled=function(rules,start){var lexer=rules.Lexer;if(rules.ParserStart){start=rules.ParserStart;rules=rules.ParserRules;}var rules=rules.map(function(r){return new Rule(r.name,r.symbols,r.postprocess);});var g=new Grammar(rules,start);g.lexer=lexer;// nb. storing lexer on Grammar is iffy, but unavoidable
return g;};function StreamLexer(){this.reset("");}StreamLexer.prototype.reset=function(data,state){this.buffer=data;this.index=0;this.line=state?state.line:1;this.lastLineBreak=state?-state.col:0;};StreamLexer.prototype.next=function(){if(this.index<this.buffer.length){var ch=this.buffer[this.index++];if(ch==='\n'){this.line+=1;this.lastLineBreak=this.index;}return {value:ch};}};StreamLexer.prototype.save=function(){return {line:this.line,col:this.index-this.lastLineBreak};};StreamLexer.prototype.formatError=function(token,message){// nb. this gets called after consuming the offending token,
// so the culprit is index-1
var buffer=this.buffer;if(typeof buffer==='string'){var lines=buffer.split("\n").slice(Math.max(0,this.line-5),this.line);var nextLineBreak=buffer.indexOf('\n',this.index);if(nextLineBreak===-1)nextLineBreak=buffer.length;var col=this.index-this.lastLineBreak;var lastLineDigits=String(this.line).length;message+=" at line "+this.line+" col "+col+":\n\n";message+=lines.map(function(line,i){return pad(this.line-lines.length+i+1,lastLineDigits)+" "+line;},this).join("\n");message+="\n"+pad("",lastLineDigits+col)+"^\n";return message;}else {return message+" at index "+(this.index-1);}function pad(n,length){var s=String(n);return Array(length-s.length+1).join(" ")+s;}};function Parser(rules,start,options){if(rules instanceof Grammar){var grammar=rules;var options=start;}else {var grammar=Grammar.fromCompiled(rules,start);}this.grammar=grammar;// Read options
this.options={keepHistory:false,lexer:grammar.lexer||new StreamLexer()};for(var key in options||{}){this.options[key]=options[key];}// Setup lexer
this.lexer=this.options.lexer;this.lexerState=undefined;// Setup a table
var column=new Column(grammar,0);var table=this.table=[column];// I could be expecting anything.
column.wants[grammar.start]=[];column.predict(grammar.start);// TODO what if start rule is nullable?
column.process();this.current=0;// token index
}// create a reserved token for indicating a parse fail
Parser.fail={};Parser.prototype.feed=function(chunk){var lexer=this.lexer;lexer.reset(chunk,this.lexerState);var token;while(true){try{token=lexer.next();if(!token){break;}}catch(e){// Create the next column so that the error reporter
// can display the correctly predicted states.
var nextColumn=new Column(this.grammar,this.current+1);this.table.push(nextColumn);var err=new Error(this.reportLexerError(e));err.offset=this.current;err.token=e.token;throw err;}// We add new states to table[current+1]
var column=this.table[this.current];// GC unused states
if(!this.options.keepHistory){delete this.table[this.current-1];}var n=this.current+1;var nextColumn=new Column(this.grammar,n);this.table.push(nextColumn);// Advance all tokens that expect the symbol
var literal=token.text!==undefined?token.text:token.value;var value=lexer.constructor===StreamLexer?token.value:token;var scannable=column.scannable;for(var w=scannable.length;w--;){var state=scannable[w];var expect=state.rule.symbols[state.dot];// Try to consume the token
// either regex or literal
if(expect.test?expect.test(value):expect.type?expect.type===token.type:expect.literal===literal){// Add it
var next=state.nextState({data:value,token:token,isToken:true,reference:n-1});nextColumn.states.push(next);}}// Next, for each of the rules, we either
// (a) complete it, and try to see if the reference row expected that
// rule
// (b) predict the next nonterminal it expects by adding that
// nonterminal's start state
// To prevent duplication, we also keep track of rules we have already
// added
nextColumn.process();// If needed, throw an error:
if(nextColumn.states.length===0){// No states at all! This is not good.
var err=new Error(this.reportError(token));err.offset=this.current;err.token=token;throw err;}// maybe save lexer state
if(this.options.keepHistory){column.lexerState=lexer.save();}this.current++;}if(column){this.lexerState=lexer.save();}// Incrementally keep track of results
this.results=this.finish();// Allow chaining, for whatever it's worth
return this;};Parser.prototype.reportLexerError=function(lexerError){var tokenDisplay,lexerMessage;// Planning to add a token property to moo's thrown error
// even on erroring tokens to be used in error display below
var token=lexerError.token;if(token){tokenDisplay="input "+JSON.stringify(token.text[0])+" (lexer error)";lexerMessage=this.lexer.formatError(token,"Syntax error");}else {tokenDisplay="input (lexer error)";lexerMessage=lexerError.message;}return this.reportErrorCommon(lexerMessage,tokenDisplay);};Parser.prototype.reportError=function(token){var tokenDisplay=(token.type?token.type+" token: ":"")+JSON.stringify(token.value!==undefined?token.value:token);var lexerMessage=this.lexer.formatError(token,"Syntax error");return this.reportErrorCommon(lexerMessage,tokenDisplay);};Parser.prototype.reportErrorCommon=function(lexerMessage,tokenDisplay){var lines=[];lines.push(lexerMessage);var lastColumnIndex=this.table.length-2;var lastColumn=this.table[lastColumnIndex];var expectantStates=lastColumn.states.filter(function(state){var nextSymbol=state.rule.symbols[state.dot];return nextSymbol&&typeof nextSymbol!=="string";});if(expectantStates.length===0){lines.push('Unexpected '+tokenDisplay+'. I did not expect any more input. Here is the state of my parse table:\n');this.displayStateStack(lastColumn.states,lines);}else {lines.push('Unexpected '+tokenDisplay+'. Instead, I was expecting to see one of the following:\n');// Display a "state stack" for each expectant state
// - which shows you how this state came to be, step by step.
// If there is more than one derivation, we only display the first one.
var stateStacks=expectantStates.map(function(state){return this.buildFirstStateStack(state,[])||[state];},this);// Display each state that is expecting a terminal symbol next.
stateStacks.forEach(function(stateStack){var state=stateStack[0];var nextSymbol=state.rule.symbols[state.dot];var symbolDisplay=this.getSymbolDisplay(nextSymbol);lines.push('A '+symbolDisplay+' based on:');this.displayStateStack(stateStack,lines);},this);}lines.push("");return lines.join("\n");};Parser.prototype.displayStateStack=function(stateStack,lines){var lastDisplay;var sameDisplayCount=0;for(var j=0;j<stateStack.length;j++){var state=stateStack[j];var display=state.rule.toString(state.dot);if(display===lastDisplay){sameDisplayCount++;}else {if(sameDisplayCount>0){lines.push(' ^ '+sameDisplayCount+' more lines identical to this');}sameDisplayCount=0;lines.push(' '+display);}lastDisplay=display;}};Parser.prototype.getSymbolDisplay=function(symbol){return getSymbolLongDisplay(symbol);};/*
Builds a the first state stack. You can think of a state stack as the call stack
of the recursive-descent parser which the Nearley parse algorithm simulates.
A state stack is represented as an array of state objects. Within a
state stack, the first item of the array will be the starting
state, with each successive item in the array going further back into history.
This function needs to be given a starting state and an empty array representing
the visited states, and it returns an single state stack.
*/Parser.prototype.buildFirstStateStack=function(state,visited){if(visited.indexOf(state)!==-1){// Found cycle, return null
// to eliminate this path from the results, because
// we don't know how to display it meaningfully
return null;}if(state.wantedBy.length===0){return [state];}var prevState=state.wantedBy[0];var childVisited=[state].concat(visited);var childResult=this.buildFirstStateStack(prevState,childVisited);if(childResult===null){return null;}return [state].concat(childResult);};Parser.prototype.save=function(){var column=this.table[this.current];column.lexerState=this.lexerState;return column;};Parser.prototype.restore=function(column){var index=column.index;this.current=index;this.table[index]=column;this.table.splice(index+1);this.lexerState=column.lexerState;// Incrementally keep track of results
this.results=this.finish();};// nb. deprecated: use save/restore instead!
Parser.prototype.rewind=function(index){if(!this.options.keepHistory){throw new Error('set option `keepHistory` to enable rewinding');}// nb. recall column (table) indicies fall between token indicies.
// col 0 -- token 0 -- col 1
this.restore(this.table[index]);};Parser.prototype.finish=function(){// Return the possible parsings
var considerations=[];var start=this.grammar.start;var column=this.table[this.table.length-1];column.states.forEach(function(t){if(t.rule.name===start&&t.dot===t.rule.symbols.length&&t.reference===0&&t.data!==Parser.fail){considerations.push(t);}});return considerations.map(function(c){return c.data;});};function getSymbolLongDisplay(symbol){var type=typeof symbol;if(type==="string"){return symbol;}else if(type==="object"){if(symbol.literal){return JSON.stringify(symbol.literal);}else if(symbol instanceof RegExp){return 'character matching '+symbol;}else if(symbol.type){return symbol.type+' token';}else if(symbol.test){return 'token matching '+String(symbol.test);}else {throw new Error('Unknown symbol type: '+symbol);}}}function getSymbolShortDisplay(symbol){var type=typeof symbol;if(type==="string"){return symbol;}else if(type==="object"){if(symbol.literal){return JSON.stringify(symbol.literal);}else if(symbol instanceof RegExp){return symbol.toString();}else if(symbol.type){return '%'+symbol.type;}else if(symbol.test){return '<'+String(symbol.test)+'>';}else {throw new Error('Unknown symbol type: '+symbol);}}}return {Parser:Parser,Grammar:Grammar,Rule:Rule};});
3 years ago
});
const parse$1 = (fileContents, settings) => {
console.time('ledger-file-parse');
const blocks = splitIntoBlocks(fileContents);
const errors = [];
const results = blocks
.map((block) => {
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
// TODO: Sorting may only make sense if comments are not a top-level
// element. They need to be tied to an alias (move all aliases to the top
// of the file) or a transaction (sort by date)
try {
const innerresults = parser.feed(block.block).finish();
if (innerresults.length !== 1) {
// Returning multiple results means that the results were ambiguous
errors.push({
message: 'Ambiguous parsing results for block in ledger file',
block,
});
return undefined;
3 years ago
}
const elements = innerresults[0];
return assignLineNumbersToElements(elements, block);
}
catch (error) {
errors.push({
message: 'Failed to parse block in ledger file',
error,
block,
});
return undefined;
}
})
.filter((val) => !!val)
.flat(1);
const aliases = [];
const comments = [];
const rawTxs = [];
results.forEach((el) => {
switch (el.type) {
case 'alias':
aliases.push(el);
break;
case 'comment':
comments.push(el);
break;
case 'tx':
rawTxs.push(el);
break;
}
});
const aliasMap = parseAliases(aliases);
const txs = rawTxs
.map((tx) => {
let hadError = false;
fillMissingAmount(tx).mapErr((e) => {
errors.push(e);
hadError = true;
3 years ago
});
if (hadError) {
return undefined;
}
try {
const newExpenseLines = tx.value.expenselines.map((line) => {
if (!('account' in line)) {
return line;
}
return {
account: line.account,
dealiasedAccount: dealiasAccount(line.account, aliasMap),
comment: line.comment,
currency: line.currency,
reconcile: line.reconcile,
amount: line.amount || 0, // safe due to fillMissingAmount
};
});
return {
...tx,
value: {
...tx.value,
expenselines: newExpenseLines,
},
};
}
catch (error) {
console.log(tx);
console.error(error);
}
})
.filter((tx) => !!tx);
const payees = lodash.sortedUniq(txs
.map(({ value }) => value.payee)
.sort((a, b) => (a.toLowerCase() > b.toLowerCase() ? 1 : -1)));
const accounts = lodash.sortedUniq(lodash.flatMap(txs, ({ value }) => value.expenselines.flatMap((line) => 'dealiasedAccount' in line ? [line.dealiasedAccount] : [])).sort((a, b) => (a.toLowerCase() > b.toLowerCase() ? 1 : -1)));
const assetAccounts = [];
const expenseAccounts = [];
const incomeAccounts = [];
const liabilityAccounts = [];
accounts.forEach((c) => {
if (c.startsWith(settings.assetAccountsPrefix)) {
assetAccounts.push(c);
}
else if (c.startsWith(settings.expenseAccountsPrefix)) {
expenseAccounts.push(c);
}
else if (c.startsWith(settings.incomeAccountsPrefix)) {
incomeAccounts.push(c);
}
else if (c.startsWith(settings.liabilityAccountsPrefix)) {
liabilityAccounts.push(c);
}
});
const firstTxDate = firstDate(txs);
console.timeLog('ledger-file-parse');
console.timeEnd('ledger-file-parse');
return {
firstDate: firstTxDate,
aliases: aliasMap,
rawAliases: aliases,
rawComments: comments,
transactions: txs,
payees,
accounts,
parsingErrors: errors,
assetAccounts,
expenseAccounts,
incomeAccounts,
liabilityAccounts,
};
};
/**
* splitIntoBlocks takes in the contents of a file and divides it into blocks
* which can be fed into the parser. Blocks are annotated with their start and
* finish line numbers.
*/
const splitIntoBlocks = (fileContents) => {
const blocks = [];
let currentBlock = null;
fileContents.split('\n').forEach((line, i) => {
// If there is a blank line, save this block and start a new one
if (line.trim() === '') {
if (currentBlock) {
blocks.push(currentBlock);
currentBlock = null;
}
return;
}
if (!currentBlock) {
currentBlock = {
block: line,
firstLine: i,
lastLine: i,
};
return;
}
currentBlock.block += '\n' + line;
currentBlock.lastLine = i;
});
if (currentBlock) {
// Don't forget the last one if we don't end with a new line
blocks.push(currentBlock);
}
return blocks;
};
/**
* assignLineNumbersToElements modifies the provided elements, assigning their
* firstLine and lastLine properties based on their relative blockLine property
* and the absolute firstLine and lastLine property in the provided FileBlock.
*/
const assignLineNumbersToElements = (elements, block) => {
if (elements.length === 1) {
return [
{
...elements[0],
block,
},
];
}
// Each Element in a block should have a blockLine property which is 1-offset.
return elements.map((element, i) => {
const firstLine = block.firstLine + element.blockLine - 1;
const lastLine = i === elements.length - 1
? block.lastLine // Last element
: elements[i + 1].blockLine - 2 + block.firstLine;
return {
...element,
block: {
firstLine,
lastLine,
block: block.block
.split('\n')
.slice(element.blockLine - 1, element.blockLine + (lastLine - firstLine))
.join('\n'),
},
};
});
};
const parseAliases = (aliases) => {
const aliasMap = new Map();
aliases.forEach((el) => {
aliasMap.set(el.value.left, el.value.right);
});
return aliasMap;
};
/**
* fillMissingAmmount attempts to fill any empty amount fields in the
* transactions expense lines. Exported only for unit testing. This should not
* be used outside of the parser.
*/
const fillMissingAmount = (tx) => {
const lines = tx.value.expenselines;
let missingLine;
let missingIndex = -1;
let currency = '';
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!('account' in line)) {
// No account means this line shouldn't have an amount
continue;
}
// Explicit compare to undefined to avoide accidentally comparing to 0
if (line.amount === undefined) {
if (missingLine) {
return err({
transaction: tx,
message: 'Transaction has multiple expense lines without an amount. At most one is allowed.',
});
}
missingLine = line;
missingIndex = i;
}
else if (line.currency) {
currency = line.currency;
}
3 years ago
}
if (!missingLine) {
return ok(null);
3 years ago
}
if (currency) {
missingLine.currency = currency;
3 years ago
}
missingLine.amount =
-1 *
lines.reduce((prev, line, i) => {
if (i === missingIndex || !('account' in line)) {
return prev;
}
return line.amount !== undefined ? prev + line.amount : prev;
}, 0);
return ok(null);
};
class LedgerModifier {
constructor(plugin, ledgerFile) {
this.plugin = plugin;
this.ledgerFile = ledgerFile;
3 years ago
}
setLedgerFile(ledgerFile) {
this.ledgerFile = ledgerFile;
3 years ago
}
openExpenseModal(operation, initialState) {
new AddExpenseModal(this.plugin, this, operation, initialState).open();
3 years ago
}
async updateTransaction(oldTx, newTx) {
const vault = this.plugin.app.vault;
const fileContents = await vault.cachedRead(this.ledgerFile);
const lines = fileContents.split('\n');
const newLines = lines.slice(0, oldTx.block.firstLine).join('\n') +
newTx +
'\n' +
lines.slice(oldTx.block.lastLine + 1).join('\n');
return vault.modify(this.ledgerFile, newLines);
3 years ago
}
async deleteTransaction(tx) {
const vault = this.plugin.app.vault;
const fileContents = await vault.cachedRead(this.ledgerFile);
const lines = fileContents.split('\n');
let length = tx.block.lastLine - tx.block.firstLine + 1;
if (lines[tx.block.firstLine + length] === '') {
length++; // Attempt to prevent a double blank line
}
lines.splice(tx.block.firstLine, length);
return vault.modify(this.ledgerFile, lines.join('\n'));
3 years ago
}
async appendLedger(newExpense) {
const vault = this.plugin.app.vault;
const fileContents = await vault.read(this.ledgerFile);
const newFileContents = `${fileContents}\n${newExpense}`;
await vault.modify(this.ledgerFile, newFileContents);
3 years ago
}
}
const getTransactionCache = async (cache, vault, settings, ledgerFilePath) => {
const file = cache.getFirstLinkpathDest(ledgerFilePath, '');
if (!file) {
throw new Error('Ledger: Unable to find Ledger file to parse');
3 years ago
}
const fileContents = await vault.read(file);
return parse$1(fileContents, settings);
};
/**
* Icon used in the side ribbon. Viewbox 100x100
*/
const billIcon = '<path d="m37.5 42.511h12.5a5 4.999 0 0 0 0-9.998h-5v-2.4995a5 4.999 0 0 0-10 0v2.7495a12.5 12.498 0 0 0 2.5 24.745h5a2.5 2.4995 0 0 1 0 4.999h-12.5a5 4.999 0 0 0 0 9.998h5v2.4995a5 4.999 0 0 0 10 0v-2.7495a12.5 12.498 0 0 0-2.5-24.745h-5a2.5 2.4995 0 0 1 0-4.999zm57.5 7.4985h-15v-44.991a5 4.999 0 0 0-2.5-4.3491 5 4.999 0 0 0-5 0l-15 8.5983-15-8.5983a5 4.999 0 0 0-5 0l-15 8.5983-15-8.5983a5 4.999 0 0 0-5 0 5 4.999 0 0 0-2.5 4.3491v79.984a15 14.997 0 0 0 15 14.997h70a15 14.997 0 0 0 15-14.997v-29.994a5 4.999 0 0 0-5-4.999zm-80 39.992a5 4.999 0 0 1-5-4.999v-71.336l10 5.6989a5.4 5.3989 0 0 0 5 0l15-8.5983 15 8.5983a5.4 5.3989 0 0 0 5 0l10-5.6989v71.336a15 14.997 0 0 0 0.9 4.999zm75-4.999a5 4.999 0 0 1-10 0v-24.995h10z" fill="currentColor" stroke-width="4.9995"/>';
const buyMeACoffee = `
<svg width="150" height="42" fill="none" version="1.1" viewBox="0 0 260 73" xmlns="http://www.w3.org/2000/svg">
<path d="M0 11.68C0 5.22932 5.22931 0 11.68 0H248.2C254.651 0 259.88 5.22931 259.88 11.68V61.32C259.88 67.7707 254.651 73 248.2 73H11.68C5.22931 73 0 67.7707 0 61.32V11.68Z" fill="#fd0"/>
<g fill="#0D0C22">
<path d="m52.257 24.008-0.032-0.0189-0.0742-0.0226c0.0298 0.0252 0.0672 0.0398 0.1062 0.0415z"/>
<path d="m52.725 27.346-0.0353 0.0099 0.0353-0.0099z"/>
<path d="m52.27 24.002c-0.0041-5e-4 -0.0082-0.0015-0.0121-0.0029-2e-4 0.0027-2e-4 0.0054 0 0.0081 0.0044-6e-4 0.0086-0.0024 0.0121-0.0052z"/>
<path d="m52.258 24.009h0.0065v-4e-3l-0.0065 4e-3z"/>
<path d="m52.697 27.339 0.054-0.0308 0.0201-0.0113 0.0183-0.0195c-0.0343 0.0148-0.0656 0.0357-0.0924 0.0616z"/>
<path d="m52.348 24.081-0.0528-0.0502-0.0358-0.0195c0.0192 0.0339 0.051 0.059 0.0886 0.0697z"/>
<path d="m39.068 56.469c-0.0422 0.0182-0.0791 0.0468-0.1075 0.083l0.0334-0.0214c0.0226-0.0208 0.0546-0.0453 0.0741-0.0616z"/>
<path d="m46.78 54.952c0-0.0477-0.0233-0.0389-0.0176 0.1308 0-0.0139 0.0057-0.0277 0.0082-0.0409 0.0031-0.0302 0.0056-0.0597 0.0094-0.0899z"/>
<path d="m45.984 56.469c-0.0422 0.0182-0.0791 0.0468-0.1074 0.083l0.0333-0.0214c0.0226-0.0208 0.0546-0.0453 0.0741-0.0616z"/>
<path d="m33.631 56.83c-0.032-0.0278-0.0712-0.0461-0.1131-0.0528 0.0339 0.0164 0.0679 0.0327 0.0905 0.0453l0.0226 0.0075z"/>
<path d="m32.412 55.66c-5e-3 -0.0495-0.0202-0.0974-0.0446-0.1408 0.0173 0.0452 0.0318 0.0914 0.0434 0.1383l0.0012 0.0025z"/>
</g>
<path d="m40.623 34.722c-1.6781 0.7184-3.5826 1.533-6.0508 1.533-1.0325-2e-3 -2.06-0.1437-3.0546-0.4211l1.7071 17.526c0.0604 0.7325 0.3941 1.4156 0.9348 1.9134 0.5408 0.4979 1.249 0.7743 1.984 0.7741 0 0 2.4205 0.1257 3.2281 0.1257 0.8693 0 3.4758-0.1257 3.4758-0.1257 0.7349 0 1.443-0.2764 1.9836-0.7743 0.5406-0.4978 0.8742-1.1808 0.9346-1.9132l1.8284-19.368c-0.8171-0.279-1.6417-0.4644-2.5713-0.4644-1.6077-7e-4 -2.9031 0.5531-4.3997 1.1935z" fill="#fff"/>
<path d="m26.234 27.245 0.0289 0.027 0.0188 0.0113c-0.0145-0.0144-0.0305-0.0273-0.0477-0.0383z" fill="#0D0C22"/>
<path d="m55.491 25.627-0.257-1.2967c-0.2307-1.1634-0.7543-2.2627-1.9485-2.6832-0.3827-0.1345-0.8171-0.1923-1.1106-0.4707-0.2935-0.2785-0.3802-0.7109-0.4481-1.1119-0.1257-0.736-0.2439-1.4726-0.3727-2.2074-0.1113-0.6316-0.1993-1.3412-0.489-1.9207-0.3771-0.7782-1.1597-1.2332-1.9378-1.5343-0.3987-0.1488-0.8056-0.2747-1.2187-0.3771-1.944-0.5129-3.988-0.7014-5.988-0.8089-2.4005-0.1325-4.8074-0.0926-7.2022 0.1194-1.7825 0.1622-3.6599 0.3583-5.3538 0.9749-0.6191 0.2256-1.2571 0.4965-1.7278 0.9748-0.5777 0.5877-0.7662 1.4965-0.3445 2.2294 0.2998 0.5204 0.8077 0.8881 1.3463 1.1313 0.7016 0.3134 1.4344 0.5519 2.186 0.7115 2.093 0.4626 4.2608 0.6443 6.3991 0.7216 2.3699 0.0956 4.7437 0.0181 7.1023-0.232 0.5833-0.0641 1.1655-0.141 1.7467-0.2306 0.6845-0.105 1.1238-1 0.922-1.6235-0.2413-0.7454-0.8899-1.0346-1.6234-0.9221-0.90387 0.14396-1.8534 0.2114-2.6908 0.2835-1.1552 0.0805-2.3136 0.1175-3.4713 0.1194-1.1376 0-2.2759-0.032-3.411-0.1068-1.5689-0.13937-2.9125-0.3062-4.2821-0.6028-0.16844-0.15273-0.10148-0.2725 0.1193-0.3394 0.56768-0.12277 1.1122-0.1975 1.6386-0.2866h0.0038c0.2558-0.017 0.5129-0.0628 0.7674-0.093 2.2147-0.2304 4.4426-0.3089 6.668-0.2351 2.1349 0.05445 3.9508 0.25816 5.9239 0.6235 0.763 0.166 1.7429 0.22 2.0823 1.0559 0.34473 1.2217 0.58881 2.5712 0.8372 3.7272 0.07675 0.3658 0.01169 0.46565-0.3872 0.5525-7.4853 1.254-15.053 0.59949-21.308-0.418-0.7636-0.1257-1.494-0.0628-2.1847 0.3143-0.567 0.3102-1.0259 0.786-1.3155 1.3639-0.2979 0.6159-0.3866 1.2866-0.5198 1.9484-0.1333 0.6618-0.3407 1.374-0.2621 2.0534 0.1691 1.4664 1.1942 2.658 2.6687 2.9245 1.3872 0.2514 2.7819 0.4551 4.1803 0.6286 6.3975 0.58529 12.33 0.67088 17.899 0.103 0.84728-0.06084 1.1341 0.18345 1.0408 1.0333-0.86018 8.2095-1.6016 15.772-2.3632 23.05-0.2389 1.2394-1.078 2.0006-2.3023 2.279-1.1217 0.2553-2.2676 0.3893-3.4179 0.3998-1.2753 0.0069-2.55-0.0497-3.8253-0.0428-1.3613 0.0076-3.0288-0.1182-4.0797-1.1313-0.9233-0.89-1.0509-2.2835-1.1766-3.4884-0.73481-7.0464-1.4562-13.977-2.0496-19.675-0.0717-0.6845-0.5563-1.3545-1.32-1.3199-0.6536 0.0289-1.3965 0.5845-1.3199 1.3199 0.81438 7.8132 1.5812 15.192 2.291 21.991 0.2873 2.6171 2.286 4.0276 4.7611 4.4248 1.4456 0.2325 2.9264 0.2803 4.3934 0.3042 1.8806 0.0302 3.78 0.1024 5.6297-0.2382 2.741-0.5028 4.7976-2.3331 5.0911-5.1722 0.90983-8.8804 1.5778-15.392 2.4116-23.519 0.05345-0.64763 0.11424-0.71456 0.7593-0.829 0.7838-0.1528 1.533-0.4136 2.0905-1.0101 0.8875-0.9497 1.0641-2.1879 0.7504-3.4361zm-2.8774 1.5028c-0.2815 0.2677-0.7058 0.3922-1.125 0.4544-4.7014 0.6977-9.4713 1.0509-14.224 0.895-3.4016-0.1163-6.7673-0.494-10.135-0.9698-1.2935-0.32214-1.1195-1.0715-1.0207-2.2872 0.1018-0.5078 0.2967-1.1848 0.9007-1.257 0.9428-0.1107 2.0376 0.2872 2.9704 0.4286 1.1229 0.1714 2.2501 0.3086 3.3815 0.4117 4.8283 0.44 9.7377 0.3715 14.545-0.2722 0.8761-0.1177 1.7492-0.2545 2.619-0.4104 0.775-0.1389 1.6342-0.3997 2.1025 0.4029 0.3211 0.5468 0.3639 1.2784 0.3142 1.8963-0.0153 0.2692-0.1329 0.5223-0.3287 0.7077z" fill="#0D0C22"/>
<g clip-rule="evenodd" fill-rule="evenodd">
<g fill="#0d0c23">
<path d="m81.13 40.193c-0.2746 0.524-0.6521 0.9803-1.1324 1.3675-0.4803 0.3875-1.0407 0.7029-1.6812 0.9458-0.6405 0.2435-1.2851 0.4069-1.9331 0.4902-0.6483 0.0835-1.2775 0.0763-1.8872-0.0229-0.61-0.0986-1.1289-0.2998-1.5555-0.604l0.4806-4.9916c0.4419-0.1518 0.9983-0.3076 1.6695-0.4672 0.671-0.1594 1.3611-0.2736 2.0704-0.3418 0.7092-0.0686 1.3799-0.0605 2.0131 0.0228 0.6324 0.0836 1.1321 0.2848 1.4981 0.6041 0.1982 0.1822 0.3662 0.3796 0.5035 0.5925 0.137 0.2128 0.2209 0.4331 0.2516 0.661 0.0761 0.6382-0.0229 1.2194-0.2974 1.7436zm-6.9772-10.633c0.3204-0.1975 0.7055-0.3725 1.1553-0.5246 0.4498-0.1515 0.9112-0.2582 1.384-0.3189 0.4725-0.0605 0.9339-0.0686 1.384-0.0229 0.4495 0.0457 0.8465 0.1709 1.1896 0.3759 0.343 0.2054 0.5984 0.5017 0.7661 0.8889 0.1677 0.3878 0.2136 0.8779 0.1373 1.4704-0.061 0.4711-0.2482 0.8701-0.5604 1.1966-0.3126 0.327-0.6942 0.6003-1.1437 0.8206-0.93645 0.47615-1.9244 0.62666-2.8824 0.8091-0.65665 0.10554-1.2342 0.10047-1.8872 0.1368zm9.4477 7.4074c-0.2441-0.5315-0.572-0.9987-0.9835-1.4018-0.4118-0.4025-0.9002-0.6949-1.4641-0.8773 0.2438-0.1975 0.484-0.509 0.7206-0.9346 0.2362-0.4251 0.4382-0.8889 0.6059-1.3903 0.1678-0.5017 0.2824-1.0066 0.3433-1.5158 0.0607-0.5089 0.0378-0.9458-0.0685-1.3108-0.2597-0.9114-0.6674-1.6256-1.2241-2.1424-0.5569-0.5164-1.2046-0.8735-1.9443-1.0713-0.7398-0.1969-1.5556-0.2391-2.4477-0.1252s-1.8036 0.338-2.7334 0.6723c0-0.0758 0.0075-0.1556 0.0229-0.2392 0.0148-0.0832 0.0226-0.1708 0.0226-0.2622 0-0.2279-0.1143-0.4251-0.343-0.5925-0.2287-0.1672-0.4919-0.2658-0.7891-0.2964-0.2974-0.0301-0.5873 0.0341-0.8694 0.1937-0.2824 0.1596-0.4768 0.4526-0.5833 0.8773-0.53219 6.1712-1.0201 11.806-1.5785 17.482 0.0459 0.4103 0.1602 0.7296 0.3433 0.9574 0.1829 0.2282 0.3964 0.3649 0.6405 0.4103 0.2438 0.0457 0.4995 0.0035 0.7662-0.1255 0.2667-0.1286 0.4994-0.3533 0.6979-0.6723 0.6097 0.3343 1.2961 0.5509 2.0588 0.6498 0.7623 0.0986 1.536 0.0986 2.3219 0 0.785-0.0989 1.559-0.2848 2.3217-0.5587 0.7623-0.2732 1.4562-0.6153 2.0816-1.0253 0.6251-0.4104 1.1513-0.8779 1.5785-1.4019 0.4269-0.5245 0.709-1.0904 0.8462-1.698 0.1373-0.6231 0.1753-1.246 0.1144-1.8691-0.061-0.6229-0.2136-1.2-0.4574-1.7324z"/>
<path d="m105.56 50.586c-0.153 0.5543-0.332 1.0598-0.538 1.5158-0.205 0.4557-0.434 0.8238-0.686 1.1052-0.252 0.281-0.522 0.399-0.812 0.3536-0.229-0.0309-0.374-0.1752-0.434-0.4332-0.062-0.2588-0.062-0.5777 0-0.9574 0.24718-1.5033 0.72478-2.4892 1.852-4.0685 0.321-0.4329 0.656-0.794 1.007-1.0826 0.076 0.0911 0.11 0.3189 0.103 0.6839-0.024 1.0105-0.28114 1.977-0.492 2.8832zm8.109-11.476c-0.206-0.2278-0.457-0.3568-0.755-0.3874-0.297-0.0304-0.598 0.1367-0.903 0.5014-0.61981 1.1396-1.7144 1.944-2.642 2.6666-0.298 0.1978-0.53 0.3421-0.698 0.4332-0.061-0.4861-0.096-1.0103-0.103-1.5728-0.0511-1.4302-0.0479-2.6986 0.32-4.1937 0.145-0.8357 0.355-1.6563 0.629-2.4619 0-0.4251-0.099-0.7709-0.297-1.0369-0.199-0.2658-0.439-0.4332-0.721-0.5015-0.282-0.0682-0.571-0.0303-0.869 0.114-0.297 0.1446-0.553 0.4068-0.766 0.7862-0.43653 1.2547-0.94208 2.4564-1.43 3.59-0.55968 1.3301-1.1769 2.4677-2.196 3.4988-0.435 0.4711-0.908 0.8397-1.418 1.1055-0.511 0.266-1.064 0.3837-1.659 0.3533-0.2744-0.076-0.4727-0.281-0.5945-0.6156-0.1222-0.334-0.1945-0.7521-0.2171-1.2535-0.0229-0.5014 0-1.0523 0.0685-1.6526 0.12468-1.2146 0.17778-1.851 0.6521-3.4757 0.137-0.5318 0.266-0.9803 0.389-1.3449 0.183-0.4404 0.183-0.8093 0-1.1055-0.183-0.2963-0.435-0.4936-0.755-0.5927-0.3204-0.0986-0.6561-0.0946-1.0067 0.0115-0.3509 0.1064-0.6025 0.3418-0.7548 0.7065-0.2595 0.6234-0.496 1.322-0.7093 2.097-0.2136 0.7749-0.3851 1.5768-0.5145 2.4046-0.1301 0.8285-0.2026 1.6491-0.2177 2.462-9e-4 0.0529 0.0017 0.1032 0.0014 0.1558-0.3325 0.8834-0.6494 1.5511-0.9504 1.9978-0.3889 0.5778-0.8277 0.8285-1.3155 0.7521-0.2139-0.091-0.3543-0.3036-0.4228-0.6381-0.0694-0.334-0.092-0.7443-0.0694-1.231 0.0235-0.4858 0.0807-1.0366 0.1718-1.6523 0.33831-2.0657 0.78068-3.8995 1.1899-5.8008-0.0154-0.5318-0.1718-0.9381-0.4693-1.2194-0.2972-0.2808-0.713-0.391-1.2464-0.3306-0.366 0.1521-0.6371 0.3499-0.8123 0.5928-0.1756 0.2429-0.3167 0.5546-0.4232 0.9343-0.0612 0.1978-0.1526 0.5928-0.2745 1.1856-0.30793 1.5461-0.7367 3.0418-1.1437 4.4444-0.2595 0.8357-0.5491 1.5921-0.8692 2.2679-0.3204 0.676-0.6712 1.2194-1.0523 1.6297-0.3813 0.41-0.7931 0.5775-1.2354 0.5014-0.2441-0.0457-0.4002-0.2964-0.4687-0.7521-0.0688-0.456-0.0801-1.0178-0.0345-1.6867 0.1758-2.1621 0.68438-4.3968 1.0981-6.3592 0.1219-0.5471 0.2058-0.9118 0.2516-1.0939 0-0.4407-0.0995-0.7938-0.2974-1.0601-0.1985-0.2654-0.4385-0.4329-0.7206-0.5014-0.2824-0.0682-0.572-0.0304-0.8692 0.1139-0.2974 0.1446-0.5528 0.4069-0.7664 0.7863-0.0763 0.4103-0.1756 0.8854-0.2975 1.4247-0.52221 2.1368-0.76636 4.0384-0.9948 5.9489-0.0383 0.4638-0.0575 0.9536-0.0575 1.4701 0 0.517 0.038 1.0297 0.1147 1.5386 0.076 0.5092 0.2133 0.9765 0.4115 1.4016 0.1982 0.4256 0.4765 0.7749 0.8352 1.0485 0.3581 0.2735 0.812 0.4253 1.3611 0.456 0.5638 0.0301 1.0557-0.0113 1.4754-0.1255 0.4193-0.1139 0.8004-0.2926 1.1437-0.5358 0.343-0.2426 0.6556-0.5315 0.9379-0.8661 0.2818-0.3339 0.5604-0.6986 0.835-1.0939 0.2591 0.5778 0.5946 1.0257 1.0064 1.3449 0.4118 0.319 0.8466 0.5092 1.3039 0.5697 0.4574 0.0604 0.9229-0.0035 1.3956-0.1938 0.4725-0.1896 0.8994-0.5126 1.281-0.9687 0.251-0.2796 0.4879-0.5974 0.7102-0.9487 0.0943 0.1645 0.1947 0.3233 0.3076 0.4699 0.3738 0.4867 0.881 0.8206 1.5215 1.0031 0.6861 0.1825 1.3565 0.2131 2.0125 0.0914 0.656-0.1215 1.281-0.3421 1.876-0.661 0.595-0.3193 1.148-0.7027 1.659-1.1512 0.51-0.4482 0.956-0.9152 1.338-1.4019-0.0193 0.68563-0.0345 1.3826-0.046 2.006-0.763 0.532-1.483 1.1702-2.162 1.9145-1.412 1.4729-2.3953 3.0003-2.985 4.9458-0.29 0.8666-0.431 1.6754-0.423 2.4278 7e-3 0.7521 0.187 1.4091 0.537 1.9712 0.351 0.5625 0.923 0.965 1.716 1.2082 0.824 0.2585 1.548 0.2657 2.173 0.0228 0.626-0.2432 1.171-0.646 1.636-1.2081s0.846-1.242 1.144-2.0398c0.297-0.7978 0.533-1.6297 0.709-2.4957 0.175-0.8661 0.286-1.7176 0.331-2.5527 0.046-0.836 0.046-1.5809 0-2.2341 1.312-0.5468 2.387-1.2382 3.226-2.0742 0.839-0.8351 1.532-1.7167 2.081-2.6438 0.168-0.2278 0.225-0.5014 0.172-0.8203-0.053-0.3193-0.183-0.5928-0.389-0.8207z"/>
<path d="m142.53 37.652c0.045-0.3493 0.114-0.718 0.205-1.1055 0.092-0.3875 0.206-0.7637 0.344-1.1283 0.137-0.3646 0.297-0.6798 0.48-0.9459 0.183-0.2657 0.378-0.4557 0.583-0.5699 0.206-0.1136 0.416-0.1024 0.629 0.0341 0.229 0.1371 0.37 0.4257 0.424 0.8661 0.053 0.4412 0 0.912-0.161 1.4134-0.16 0.5017-0.446 0.9724-0.857 1.4131-0.412 0.441-0.969 0.7293-1.67 0.8661-0.031-0.2123-0.023-0.4936 0.023-0.8432zm7.926 0.9342c-0.252-0.0754-0.492-0.0832-0.721-0.0225s-0.374 0.2203-0.434 0.4788c-0.123 0.4861-0.317 0.9838-0.584 1.4927-0.267 0.5092-0.595 0.9915-0.983 1.4475-0.389 0.4558-0.828 0.8586-1.316 1.2079-0.488 0.3496-0.999 0.6003-1.532 0.7521-0.535 0.1674-0.976 0.1862-1.327 0.0569-0.351-0.1286-0.629-0.3493-0.835-0.6607s-0.355-0.6876-0.446-1.1283c-0.092-0.4407-0.145-0.8964-0.16-1.3677 0.869 0.061 1.643-0.0946 2.322-0.4673 0.678-0.3719 1.254-0.8661 1.727-1.4814 0.472-0.6153 0.831-1.3067 1.075-2.0742 0.243-0.7671 0.381-1.5308 0.411-2.2907 0.016-0.7142-0.091-1.318-0.32-1.8119-0.228-0.4936-0.537-0.8779-0.926-1.1511-0.389-0.2736-0.835-0.4332-1.338-0.4786-0.503-0.0457-1.015 0.0228-1.533 0.205-0.626 0.2128-1.155 0.5584-1.59 1.0372-0.434 0.4786-0.797 1.0335-1.086 1.6639-0.29 0.6306-0.519 1.3105-0.687 2.0397-0.168 0.7296-0.29 1.4476-0.366 2.1543-0.068 0.6341-0.105 1.2405-0.118 1.8257-0.25468 0.63556-0.64024 1.2806-0.923 1.8096-0.312 0.5168-0.659 0.9499-1.04 1.2992-0.382 0.3496-0.778 0.4711-1.19 0.3647-0.244-0.0605-0.377-0.3421-0.4-0.8432-0.023-0.5017 3e-3 -1.1246 0.08-1.8692 0.20908-1.6852 0.3451-3.3004 0.412-4.9004 0-0.6839-0.13-1.3408-0.389-1.9718-0.26-0.6301-0.614-1.1546-1.064-1.5725-0.45-0.4181-0.972-0.6954-1.567-0.8319-0.595-0.137-1.235-0.0457-1.921 0.2733-0.687 0.3192-1.232 0.7674-1.636 1.3449-0.404 0.5777-0.774 1.1852-1.109 1.8234-0.123-0.4863-0.301-0.938-0.538-1.3561-0.237-0.4179-0.526-0.7825-0.869-1.0942-0.344-0.3112-0.729-0.5544-1.155-0.7293-0.427-0.1744-0.878-0.262-1.35-0.262-0.458 0-0.881 0.0876-1.27 0.262-0.389 0.1749-0.743 0.3988-1.064 0.6723-0.32 0.2738-0.609 0.5812-0.869 0.9233-0.259 0.3418-0.488 0.6801-0.686 1.0141-0.031-0.395-0.065-0.7406-0.103-1.0372-0.038-0.2961-0.107-0.5468-0.206-0.7519-0.099-0.2053-0.24-0.3608-0.423-0.4672-0.183-0.1062-0.442-0.1597-0.777-0.1597-0.168 0-0.336 0.0342-0.504 0.1024-0.168 0.0685-0.317 0.1637-0.446 0.2851-0.13 0.122-0.229 0.2698-0.297 0.4445-0.069 0.1746-0.088 0.3762-0.058 0.604 0.015 0.1674 0.058 0.3684 0.126 0.6041 0.069 0.2356 0.134 0.5436 0.195 0.923 0.06 0.3799 0.11 0.8397 0.148 1.379 0.11407 1.619-0.0292 3.2633-0.137 4.7295-0.099 1.0485-0.256 2.2642-0.469 3.6466-0.03 0.3193 0.092 0.5778 0.366 0.7753 0.275 0.1972 0.587 0.3111 0.938 0.3418 0.351 0.0303 0.683-0.0307 0.995-0.1822 0.313-0.1524 0.492-0.4181 0.538-0.7978 0.0939-1.6311 0.42556-3.1852 0.743-4.6726 0.31774-1.4971 0.69994-2.7183 1.464-4.1483 0.298-0.5471 0.606-0.9837 0.927-1.3105 0.32-0.3267 0.655-0.4901 1.006-0.4901 0.427 0 0.759 0.1935 0.995 0.5809 0.236 0.3878 0.404 0.8857 0.504 1.493 0.099 0.6081 0.144 1.2732 0.137 1.9946-8.4e-4 1.3437-0.13963 2.6067-0.275 3.8748-0.068 0.5242-0.118 0.8854-0.148 1.0826 0 0.3496 0.133 0.6266 0.4 0.8319 0.266 0.205 0.564 0.3268 0.892 0.3647 0.328 0.0381 0.637-0.0229 0.926-0.1825 0.29-0.1596 0.458-0.4288 0.504-0.8091 0.152-1.0939 0.362-2.1915 0.629-3.2932 0.266-1.1017 0.572-2.0892 0.915-2.9631 0.343-0.8738 0.724-1.5881 1.144-2.1427 0.419-0.5543 0.865-0.8319 1.338-0.8319 0.243 0 0.431 0.1674 0.56 0.5014 0.13 0.3343 0.195 0.79 0.195 1.3675-9e-4 0.94003-0.19458 1.8493-0.343 2.701-0.092 0.4789-0.172 0.9687-0.241 1.4701-0.17553 1.01-0.18874 1.9344 0.012 2.8948 0.076 0.5011 0.221 0.9765 0.434 1.4244 0.214 0.4485 0.507 0.8282 0.881 1.1396 0.374 0.3115 0.85 0.4673 1.43 0.4673 0.869 0 1.639-0.1862 2.31-0.5584 0.77998-0.40452 1.2819-1.0449 1.799-1.5548 0.25428 0.79207 0.96347 1.3663 1.45 1.8171 0.563 0.3646 1.227 0.5659 1.99 0.6041 0.762 0.0376 1.593-0.103 2.493-0.4219 0.671-0.2432 1.254-0.5471 1.75-0.9117 0.495-0.3647 0.941-0.8091 1.338-1.3334 0.397-0.5242 0.759-1.1283 1.087-1.8119 0.328-0.6841 0.659-1.4663 0.995-2.348 0.061-0.2426 4e-3 -0.4591-0.171-0.6494-0.176-0.1897-0.389-0.3227-0.641-0.3991z"/>
</g>
<path d="m162.89 36.043c-0.077 0.4484-0.18 0.9426-0.309 1.4816-0.13 0.5396-0.294 1.098-0.492 1.6754-0.198 0.5775-0.442 1.098-0.732 1.5612-0.29 0.4638-0.621 0.8319-0.995 1.1055-0.374 0.2735-0.804 0.3875-1.293 0.3418-0.244-0.0301-0.431-0.1972-0.56-0.5014-0.13-0.3037-0.198-0.6914-0.206-1.1625-8e-3 -0.4707 0.034-0.9875 0.126-1.5499 0.091-0.5618 0.232-1.113 0.423-1.6525 0.191-0.539 0.423-1.037 0.698-1.493 0.274-0.4557 0.591-0.8091 0.949-1.0598s0.751-0.3681 1.178-0.3533c0.427 0.0153 0.885 0.2278 1.373 0.6382-0.031 0.1978-0.084 0.5207-0.16 0.9687zm8.132 1.7436c-0.237-0.1214-0.481-0.1478-0.732-0.0795-0.252 0.0682-0.431 0.3001-0.538 0.6951-0.061 0.4257-0.198 0.9268-0.411 1.5043-0.214 0.5774-0.477 1.1248-0.79 1.6409-0.312 0.5168-0.671 0.9462-1.075 1.288-0.404 0.342-0.835 0.4979-1.292 0.467-0.382-0.0301-0.649-0.2238-0.801-0.581-0.153-0.3571-0.233-0.805-0.24-1.3449-8e-3 -0.5389 0.046-1.1468 0.16-1.8231 0.114-0.6761 0.252-1.3484 0.412-2.0175 0.16-0.6683 0.324-1.3105 0.492-1.9258 0.167-0.6154 0.304-1.1358 0.412-1.5612 0.122-0.38 0.083-0.7027-0.115-0.969-0.198-0.2654-0.446-0.4557-0.743-0.5696-0.298-0.114-0.599-0.1443-0.904-0.0911s-0.503 0.2166-0.595 0.4898c-0.9-0.7749-1.765-1.1928-2.596-1.2535-0.832-0.0607-1.598 0.1217-2.299 0.5471-0.702 0.4254-1.323 1.0407-1.864 1.8463-0.542 0.8056-0.98 1.6829-1.316 2.6325-0.335 0.9496-0.545 1.9186-0.629 2.9061-0.084 0.9878-0.019 1.8882 0.195 2.7011 0.213 0.8128 0.59 1.4779 1.132 1.994 0.541 0.5168 1.277 0.7753 2.207 0.7753 0.412 0 0.809-0.0836 1.19-0.2507 0.381-0.1675 0.732-0.365 1.052-0.5928 0.32-0.2279 0.602-0.4673 0.847-0.718 0.243-0.2507 0.434-0.4595 0.571-0.6269 0.107 0.5471 0.283 1.0109 0.527 1.3906 0.243 0.3796 0.522 0.6916 0.835 0.9343 0.312 0.2428 0.64 0.4216 0.983 0.5358 0.343 0.1139 0.675 0.1709 0.995 0.1709 0.717 0 1.388-0.2432 2.013-0.7296 0.625-0.4858 1.186-1.0826 1.682-1.789 0.495-0.7067 0.903-1.451 1.223-2.2338 0.321-0.7825 0.534-1.4776 0.641-2.0857 0.107-0.2279 0.087-0.467-0.057-0.7177-0.145-0.2507-0.336-0.4367-0.572-0.5587z" fill="#0D0C23"/>
<path d="m212.19 50.37c-0.13 0.5165-0.332 0.9537-0.607 1.3105-0.274 0.3571-0.617 0.5433-1.029 0.5587-0.259 0.015-0.457-0.1218-0.595-0.4104-0.137-0.2888-0.232-0.661-0.285-1.1167-0.054-0.456-0.077-0.9652-0.069-1.5273 7e-3 -0.5622 0.03-1.1168 0.069-1.6639 0.037-0.5468 0.083-1.0563 0.137-1.5271 0.053-0.4713 0.095-0.8353 0.125-1.0939 0.519 0.0608 0.95 0.2846 1.293 0.6723 0.343 0.3875 0.606 0.847 0.789 1.3791 0.183 0.5317 0.29 1.1054 0.321 1.7208 0.03 0.6153-0.02 1.1812-0.149 1.6979zm-8.281 0c-0.13 0.5165-0.332 0.9537-0.606 1.3105-0.275 0.3571-0.618 0.5433-1.03 0.5587-0.259 0.015-0.457-0.1218-0.594-0.4104-0.138-0.2888-0.233-0.661-0.286-1.1167-0.054-0.456-0.077-0.9652-0.069-1.5273 8e-3 -0.5622 0.03-1.1168 0.069-1.6639 0.037-0.5468 0.083-1.0563 0.137-1.5271 0.053-0.4713 0.095-0.8353 0.126-1.0939 0.518 0.0608 0.949 0.2846 1.292 0.6723 0.343 0.3875 0.606 0.847 0.789 1.3791 0.183 0.5317 0.29 1.1054 0.321 1.7208 0.03 0.6153-0.02 1.1812-0.149 1.6979zm-8.498-12.946c-0.016 0.3643-0.05 0.6873-0.103 0.9684-0.054 0.2816-0.126 0.4597-0.217 0.5358-0.168-0.0914-0.374-0.3265-0.618-0.7067-0.244-0.3797-0.435-0.8094-0.572-1.288-0.137-0.4785-0.18-0.9493-0.126-1.4131 0.053-0.4632 0.294-0.8238 0.721-1.0826 0.167-0.0911 0.312-0.057 0.434 0.1026s0.221 0.3913 0.298 0.6952c0.076 0.3042 0.129 0.6535 0.16 1.0485 0.03 0.3953 0.038 0.7749 0.023 1.1399zm-2.025 4.547c-0.236 0.2504-0.5 0.467-0.789 0.6495-0.29 0.1824-0.587 0.3192-0.892 0.4103-0.305 0.0914-0.58 0.1139-0.824 0.0682-0.686-0.1364-1.212-0.4331-1.578-0.8888-0.366-0.4558-0.599-0.9913-0.698-1.6066-0.099-0.6156-0.088-1.2729 0.035-1.9718 0.121-0.6989 0.327-1.3484 0.617-1.9487s0.641-1.117 1.052-1.5499c0.412-0.4332 0.862-0.7027 1.35-0.8094-0.183 0.775-0.244 1.5768-0.183 2.4047 0.061 0.8282 0.259 1.6069 0.595 2.3362 0.213 0.4412 0.469 0.8434 0.766 1.2081 0.298 0.3649 0.66 0.6763 1.087 0.9346-0.122 0.2585-0.302 0.5129-0.538 0.7636zm25.312-4.3192c0.045-0.3493 0.114-0.7183 0.206-1.1057 0.091-0.3872 0.206-0.7634 0.343-1.1281 0.137-0.3649 0.297-0.6801 0.48-0.9458 0.183-0.2658 0.377-0.456 0.583-0.5699 0.206-0.114 0.416-0.1027 0.629 0.0341 0.229 0.137 0.37 0.4256 0.424 0.866 0.053 0.441 0 0.9117-0.16 1.4134-0.161 0.5014-0.446 0.9725-0.858 1.4129-0.412 0.4412-0.969 0.7295-1.67 0.8663-0.031-0.2125-0.023-0.4936 0.023-0.8432zm9.219 0c0.045-0.3493 0.114-0.7183 0.205-1.1057 0.092-0.3872 0.206-0.7634 0.344-1.1281 0.137-0.3649 0.297-0.6801 0.48-0.9458 0.183-0.2658 0.378-0.456 0.583-0.5699 0.206-0.114 0.416-0.1027 0.629 0.0341 0.229 0.137 0.37 0.4256 0.424 0.866 0.053 0.441 0 0.9117-0.161 1.4134-0.16 0.5014-0.446 0.9725-0.857 1.4129-0.412 0.4412-0.969 0.7295-1.67 0.8663-0.031-0.2125-0.023-0.4936 0.023-0.8432zm8.567 1.3333c-0.176-0.1897-0.389-0.3227-0.641-0.399-0.252-0.0758-0.492-0.0833-0.721-0.0226-0.229 0.0608-0.374 0.2204-0.434 0.4786-0.122 0.4864-0.317 0.984-0.584 1.4927-0.267 0.5095-0.594 0.9918-0.983 1.4475s-0.828 0.8588-1.315 1.2081c-0.489 0.3496-1 0.6003-1.533 0.7518-0.534 0.1678-0.976 0.1866-1.327 0.0573-0.351-0.129-0.629-0.3493-0.835-0.6607-0.206-0.3118-0.354-0.6877-0.446-1.1286-0.091-0.4404-0.145-0.8961-0.16-1.3675 0.869 0.061 1.643-0.0945 2.322-0.4673 0.678-0.3721 1.254-0.8663 1.727-1.4816 0.473-0.6151 0.831-1.3065 1.075-2.0739s0.381-1.5308 0.412-2.2907c0.015-0.7143-0.092-1.3183-0.321-1.8122-0.228-0.4936-0.537-0.8776-0.926-1.1509-0.389-0.2738-0.835-0.4332-1.338-0.4788-0.503-0.0457-1.015 0.0231-1.533 0.205-0.625 0.2131-1.155 0.5586-1.589 1.0372-0.435 0.4789-0.798 1.0338-1.087 1.6638-0.29 0.631-0.519 1.3105-0.687 2.0401-0.168 0.7292-0.29 1.4475-0.365 2.1539-0.075 0.6856-0.115 1.3418-0.124 1.9698-0.28213 0.6786-0.79848 1.3012-1.169 1.8252-0.389 0.4557-0.828 0.8588-1.315 1.2081-0.489 0.3496-0.999 0.6003-1.533 0.7518-0.534 0.1678-0.976 0.1866-1.327 0.0573-0.351-0.129-0.629-0.3493-0.835-0.6607-0.205-0.3118-0.354-0.6877-0.446-1.1286-0.091-0.4404-0.145-0.8961-0.16-1.3675 0.869 0.061 1.643-0.0945 2.322-0.4673 0.678-0.3721 1.254-0.8663 1.727-1.4816 0.472-0.6151 0.831-1.3065 1.075-2.0739s0.381-1.5308 0.412-2.2907c0.015-0.7143-0.092-1.3183-0.32-1.8122-0.229-0.4936-0.538-0.8776-0.927-1.1509-0.389-0.2738-0.835-0.4332-1.33
</g>
</svg>`;
const paypal = `
<svg xmlns="http://www.w3.org/2000/svg" width="150" height="40">
<path fill="#253B80" d="M46.211 6.749h-6.839a.95.95 0 0 0-.939.802l-2.766 17.537a.57.57 0 0 0 .564.658h3.265a.95.95 0 0 0 .939-.803l.746-4.73a.95.95 0 0 1 .938-.803h2.165c4.505 0 7.105-2.18 7.784-6.5.306-1.89.013-3.375-.872-4.415-.972-1.142-2.696-1.746-4.985-1.746zM47 13.154c-.374 2.454-2.249 2.454-4.062 2.454h-1.032l.724-4.583a.57.57 0 0 1 .563-.481h.473c1.235 0 2.4 0 3.002.704.359.42.469 1.044.332 1.906zM66.654 13.075h-3.275a.57.57 0 0 0-.563.481l-.145.916-.229-.332c-.709-1.029-2.29-1.373-3.868-1.373-3.619 0-6.71 2.741-7.312 6.586-.313 1.918.132 3.752 1.22 5.031.998 1.176 2.426 1.666 4.125 1.666 2.916 0 4.533-1.875 4.533-1.875l-.146.91a.57.57 0 0 0 .562.66h2.95a.95.95 0 0 0 .939-.803l1.77-11.209a.568.568 0 0 0-.561-.658zm-4.565 6.374c-.316 1.871-1.801 3.127-3.695 3.127-.951 0-1.711-.305-2.199-.883-.484-.574-.668-1.391-.514-2.301.295-1.855 1.805-3.152 3.67-3.152.93 0 1.686.309 2.184.892.499.589.697 1.411.554 2.317zM84.096 13.075h-3.291a.954.954 0 0 0-.787.417l-4.539 6.686-1.924-6.425a.953.953 0 0 0-.912-.678h-3.234a.57.57 0 0 0-.541.754l3.625 10.638-3.408 4.811a.57.57 0 0 0 .465.9h3.287a.949.949 0 0 0 .781-.408l10.946-15.8a.57.57 0 0 0-.468-.895z"/>
<path fill="#179BD7" d="M94.992 6.749h-6.84a.95.95 0 0 0-.938.802l-2.766 17.537a.569.569 0 0 0 .562.658h3.51a.665.665 0 0 0 .656-.562l.785-4.971a.95.95 0 0 1 .938-.803h2.164c4.506 0 7.105-2.18 7.785-6.5.307-1.89.012-3.375-.873-4.415-.971-1.142-2.694-1.746-4.983-1.746zm.789 6.405c-.373 2.454-2.248 2.454-4.062 2.454h-1.031l.725-4.583a.568.568 0 0 1 .562-.481h.473c1.234 0 2.4 0 3.002.704.359.42.468 1.044.331 1.906zM115.434 13.075h-3.273a.567.567 0 0 0-.562.481l-.145.916-.23-.332c-.709-1.029-2.289-1.373-3.867-1.373-3.619 0-6.709 2.741-7.311 6.586-.312 1.918.131 3.752 1.219 5.031 1 1.176 2.426 1.666 4.125 1.666 2.916 0 4.533-1.875 4.533-1.875l-.146.91a.57.57 0 0 0 .564.66h2.949a.95.95 0 0 0 .938-.803l1.771-11.209a.571.571 0 0 0-.565-.658zm-4.565 6.374c-.314 1.871-1.801 3.127-3.695 3.127-.949 0-1.711-.305-2.199-.883-.484-.574-.666-1.391-.514-2.301.297-1.855 1.805-3.152 3.67-3.152.93 0 1.686.309 2.184.892.501.589.699 1.411.554 2.317zM119.295 7.23l-2.807 17.858a.569.569 0 0 0 .562.658h2.822c.469 0 .867-.34.939-.803l2.768-17.536a.57.57 0 0 0-.562-.659h-3.16a.571.571 0 0 0-.562.482z"/>
<path fill="#253B80" d="M7.266 29.154l.523-3.322-1.165-.027H1.061L4.927 1.292a.316.316 0 0 1 .314-.268h9.38c3.114 0 5.263.648 6.385 1.927.526.6.861 1.227 1.023 1.917.17.724.173 1.589.007 2.644l-.012.077v.676l.526.298a3.69 3.69 0 0 1 1.065.812c.45.513.741 1.165.864 1.938.127.795.085 1.741-.123 2.812-.24 1.232-.628 2.305-1.152 3.183a6.547 6.547 0 0 1-1.825 2c-.696.494-1.523.869-2.458 1.109-.906.236-1.939.355-3.072.355h-.73c-.522 0-1.029.188-1.427.525a2.21 2.21 0 0 0-.744 1.328l-.055.299-.924 5.855-.042.215c-.011.068-.03.102-.058.125a.155.155 0 0 1-.096.035H7.266z"/>
<path fill="#179BD7" d="M23.048 7.667c-.028.179-.06.362-.096.55-1.237 6.351-5.469 8.545-10.874 8.545H9.326c-.661 0-1.218.48-1.321 1.132L6.596 26.83l-.399 2.533a.704.704 0 0 0 .695.814h4.881c.578 0 1.069-.42 1.16-.99l.048-.248.919-5.832.059-.32c.09-.572.582-.992 1.16-.992h.73c4.729 0 8.431-1.92 9.513-7.476.452-2.321.218-4.259-.978-5.622a4.667 4.667 0 0 0-1.336-1.03z"/>
<path fill="#222D65" d="M21.754 7.151a9.757 9.757 0 0 0-1.203-.267 15.284 15.284 0 0 0-2.426-.177h-7.352a1.172 1.172 0 0 0-1.159.992L8.05 17.605l-.045.289a1.336 1.336 0 0 1 1.321-1.132h2.752c5.405 0 9.637-2.195 10.874-8.545.037-.188.068-.371.096-.55a6.594 6.594 0 0 0-1.017-.429 9.045 9.045 0 0 0-.277-.087z"/>
<path fill="#253B80" d="M9.614 7.699a1.169 1.169 0 0 1 1.159-.991h7.352c.871 0 1.684.057 2.426.177a9.757 9.757 0 0 1 1.481.353c.365.121.704.264 1.017.429.368-2.347-.003-3.945-1.272-5.392C20.378.682 17.853 0 14.622 0h-9.38c-.66 0-1.223.48-1.325 1.133L.01 25.898a.806.806 0 0 0 .795.932h5.791l1.454-9.225 1.564-9.906z"/>
</svg>`;
/**
* getWithDefault retrieves a value from a map, setting the map to the provided
* default if the key does not already have a value.
*/
const getWithDefault = (m, key, makeDefault) => {
const val = m.get(key);
if (val !== undefined) {
return val;
}
const newVal = makeDefault();
m.set(key, newVal);
return newVal;
};
const calcNetWorth = (balanceData, settings) => [...balanceData.entries()].reduce((accum, curr) => {
const [acct, bal] = curr;
return acct.startsWith(settings.assetAccountsPrefix) ||
acct.startsWith(settings.liabilityAccountsPrefix)
? accum + bal
: accum;
}, 0);
const makeNetWorthData = (dailyAccountBalanceMap, bucketNames, settings) => bucketNames.map((bucket) => {
const balanceData = dailyAccountBalanceMap.get(bucket);
const netWorth = balanceData ? calcNetWorth(balanceData, settings) : 0;
return {
x: bucket,
y: netWorth,
};
});
/**
* makeBalanceData creates a list of data points representing the balance of an
* account over the provided buckets.
*/
const makeBalanceData = (dailyAccountBalanceMap, bucketNames, account, allAccounts) => {
const accounts = [...findChildAccounts(account, allAccounts), account];
return bucketNames.map((bucket) => {
const accountBalances = dailyAccountBalanceMap.get(bucket);
const balance = accounts.reduce((prev, currentAccount) => (accountBalances?.get(currentAccount) || 0) + prev, 0);
return { x: bucket, y: balance };
});
};
/**
* makeDeltaData creates a list of data points representing the change in
* balance of an account between the provided buckets.
*/
const makeDeltaData = (dailyAccountBalanceMap, bucketBefore, bucketNames, account, allAccounts) => {
const accounts = [...findChildAccounts(account, allAccounts), account];
return bucketNames.map((bucket, i) => {
const prevBucket = i === 0 ? bucketBefore : bucketNames[i - 1];
const accountBalances = dailyAccountBalanceMap.get(bucket);
const prevAccountBalances = dailyAccountBalanceMap.get(prevBucket);
const balance = accounts.reduce((prev, currentAccount) => {
const b1 = prevAccountBalances?.get(currentAccount) || 0;
const b2 = accountBalances?.get(currentAccount) || 0;
return b2 - b1 + prev;
}, 0);
return { x: bucket, y: balance };
});
};
/**
* findChildAccounts returns a list of accounts which are children to the
* provided account.
*/
const findChildAccounts = (account, accounts) => accounts.filter((candidate) => candidate.startsWith(account + ':'));
const renderTree = (output, node, path) => {
let newPath;
if ('label' in node) {
newPath = path ? [path, node.label].join(':') : node.label;
if (node.children.length !== 1 && node.exists) {
output.push(newPath);
}
}
node.children.forEach((child) => renderTree(output, child, newPath));
};
/**
* removeDuplicateAccounts accepts a list of account names and removes any which
* only have a single child. For example, if given the input:
* - Liabilities
* - Liabilities:Credit
* - Liabilities:Credit:Chase
* - Liabilities:Credit:Citi
* it would remove "Liabilities" because it only has a single child
* ("Liabilities:Credit").
*/
const removeDuplicateAccounts = (input) => {
const tree = { children: [] };
input.forEach((path) => {
let parentNode = tree;
path.split(':').forEach((segment, i, segments) => {
const lastSegment = segments.length === i + 1;
let node = parentNode.children.find(({ label }) => label === segment);
if (!node) {
node = {
exists: lastSegment,
label: segment,
children: [],
};
parentNode.children.push(node);
}
else if (lastSegment) {
node.exists = true;
}
parentNode = node;
});
});
const output = [];
renderTree(output, tree);
return output;
};
/**
* makeDailyAccountBalanceChangeMap creates a sparse nested map structure that
* enables looking up the balance change for any account on any date.
*
* If an account has no balance change on a date, that key will not be included
* in the inner map. If a date has no transactions, that key will not be
* included in the outer map.
*/
const makeDailyAccountBalanceChangeMap = (transactions) => {
// This map contains a mapping from every day (YYYY-MM-DD) to account names to
// a list of all balance changes.
const txDateAccountMap = new Map();
const makeDefaultAccountMap = () => new Map();
const makeDefaultBalanceList = () => [];
transactions.forEach((tx) => {
const normalizedDate = window.moment(tx.value.date).format('YYYY-MM-DD');
const accounts = getWithDefault(txDateAccountMap, normalizedDate, makeDefaultAccountMap);
tx.value.expenselines.forEach((line) => {
if (!('account' in line)) {
return; // Must be a comment line
}
getWithDefault(accounts, line.dealiasedAccount, makeDefaultBalanceList).push(line.amount);
});
});
// This map rolls up the balance changes for each day (YYYY-MM-DD) and account
// pair into a single balance change per entry.
const dateAccountTotalMap = new Map();
txDateAccountMap.forEach((accounts, txDate) => {
const rolledUpAccountMap = new Map();
dateAccountTotalMap.set(txDate, rolledUpAccountMap);
accounts.forEach((changes, account) => {
const sum = changes.reduce((prev, curr) => prev + curr, 0);
rolledUpAccountMap.set(account, sum);
});
});
return dateAccountTotalMap;
};
/**
* makeDailyBalanceMap rolls up the provided DailyAccountBalanceChangeMap into
* a daily map of the balance of every account on any given day after the
* provided first date. Unlike the input map, this map is not sparse and will
* include the balance for every account on every day.
*/
const makeDailyBalanceMap = (accounts, input, firstDate, lastDate) => {
const result = new Map();
const currentDate = firstDate.clone();
// All accounts start with 0 balance
let previousData = new Map();
accounts.forEach((accountName) => {
previousData.set(accountName, 0);
});
while (currentDate.isSameOrBefore(lastDate)) {
const currentDateStr = currentDate.format('YYYY-MM-DD');
const innerInputMap = input.get(currentDateStr);
if (innerInputMap) {
const innerResultMap = new Map();
accounts.forEach((accountName) => {
const previousValue = previousData.get(accountName) || 0;
const currentValue = innerInputMap.get(accountName) || 0;
innerResultMap.set(accountName, previousValue + currentValue);
});
result.set(currentDateStr, innerResultMap);
previousData = innerResultMap;
3 years ago
}
else {
result.set(currentDateStr, previousData);
3 years ago
}
currentDate.add(1, 'day');
3 years ago
}
return result;
};
3 years ago
const TreeRow = He.div `
margin-right: 10px;
display: flex;
align-items: stretch;
.selected {
background-color: var(--background-secondary);
}
`;
const AccountName = He.span `
flex-grow: 1;
margin-bottom: 2px;
padding: 1px 6px;
:hover {
background-color: var(--background-primary-alt);
}
`;
const Expander = He.span `
flex-grow: 0;
display: inline-block;
width: 15px;
`;
const Tree = (props) => {
const [expanded, setExpanded] = react.useState(props.data.expanded || false);
const subRows = props.data.subRows;
const hasChildren = subRows !== undefined && subRows.length > 0;
const id = props.data.id;
const selected = props.selectedAccounts.contains(id);
const toggleSelected = () => {
if (selected) {
props.setSelectedAccounts(props.selectedAccounts.filter((account) => account !== id));
}
else {
const newSelected = [...props.selectedAccounts, id];
if (props.txCache.assetAccounts.contains(id) ||
props.txCache.liabilityAccounts.contains(id)) {
props.setSelectedAccounts(deselectRowsWithoutPrefix(newSelected, [
props.settings.assetAccountsPrefix,
props.settings.liabilityAccountsPrefix,
]));
}
else if (props.txCache.expenseAccounts.contains(id) ||
props.txCache.incomeAccounts.contains(id)) {
props.setSelectedAccounts(deselectRowsWithoutPrefix(newSelected, [
props.settings.expenseAccountsPrefix,
props.settings.incomeAccountsPrefix,
]));
}
else {
props.setSelectedAccounts(newSelected);
}
}
};
return (react.createElement(react.Fragment, null,
react.createElement(TreeRow, { style: { paddingLeft: `${props.depth}rem` } },
hasChildren ? (react.createElement(Expander, { onClick: () => setExpanded(!expanded) }, expanded ? '-' : '+')) : (react.createElement(Expander, null)),
react.createElement(AccountName, { className: selected ? 'selected' : '', onClick: toggleSelected }, props.data.account)),
hasChildren && expanded && subRows
? subRows.map((child) => (react.createElement(Tree, { txCache: props.txCache, settings: props.settings, data: child, key: child.id, depth: props.depth + 1, selectedAccounts: props.selectedAccounts, setSelectedAccounts: props.setSelectedAccounts })))
: null));
3 years ago
};
const AccountsList = (props) => {
const data = react.useMemo(() => {
const nodes = [];
props.txCache.accounts.forEach((account) => {
makeAccountTree(nodes, dealiasAccount(account, props.txCache.aliases));
});
sortAccountTree(nodes);
// By default, the top level starts expanded
nodes.forEach((node) => (node.expanded = true));
return nodes;
}, [props.txCache]);
return (react.createElement("div", { className: "ledger-account-list" }, data.map((root) => (react.createElement(Tree, { txCache: props.txCache, settings: props.settings, data: root, key: root.id, depth: 0, selectedAccounts: props.selectedAccounts, setSelectedAccounts: props.setSelectedAccounts })))));
};
/**
* deselecteRowsWithoutPrefix filters the provided list of accounts, removing
* ones which do not start with one of the provided prefixes. This can be used
* to make sure the selected accounts are all of the same type, which helps
* ensure the visualization fits the account type.
*/
const deselectRowsWithoutPrefix = (selectedAccounts, prefixes) => selectedAccounts.filter((account) => prefixes.some((prefix) => account.startsWith(prefix)));
/**
* makeBucketNames creates a list of dates at the provided interval between the
* startDate and the endDate.
*/
const makeBucketNames = (interval, startDate, endDate) => {
// TODO: We need to make sure the end of the range is captured. Right now it
// seems there is either bug here or where we put data into the buckets which
// is preventing all the transactions from being represented in the chart.
const names = [];
const currentDate = startDate.clone();
do {
names.push(currentDate.format('YYYY-MM-DD'));
currentDate.add(1, interval);
} while (currentDate.isSameOrBefore(endDate));
return names;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret='SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';var ReactPropTypesSecret_1=ReactPropTypesSecret;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var printWarning=function(){};{var ReactPropTypesSecret$1=ReactPropTypesSecret_1;var loggedTypeFailures={};var has=Function.call.bind(Object.prototype.hasOwnProperty);printWarning=function(text){var message='Warning: '+text;if(typeof console!=='undefined'){console.error(message);}try{// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);}catch(x){}};}/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/function checkPropTypes(typeSpecs,values,location,componentName,getStack){{for(var typeSpecName in typeSpecs){if(has(typeSpecs,typeSpecName)){var error;// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try{// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if(typeof typeSpecs[typeSpecName]!=='function'){var err=Error((componentName||'React class')+': '+location+' type `'+typeSpecName+'` is invalid; '+'it must be a function, usually from the `prop-types` package, but received `'+typeof typeSpecs[typeSpecName]+'`.');err.name='Invariant Violation';throw err;}error=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,ReactPropTypesSecret$1);}catch(ex){error=ex;}if(error&&!(error instanceof Error)){printWarning((componentName||'React class')+': type specification of '+location+' `'+typeSpecName+'` is invalid; the type checker '+'function must return `null` or an `Error` but returned a '+typeof error+'. '+'You may have forgotten to pass an argument to the type checker '+'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and '+'shape all require an argument).');}if(error instanceof Error&&!(error.message in loggedTypeFailures)){// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message]=true;var stack=getStack?getStack():'';printWarning('Failed '+location+' type: '+error.message+(stack!=null?stack:''));}}}}}/**
* Resets warning cache when testing.
*
* @private
*/checkPropTypes.resetWarningCache=function(){{loggedTypeFailures={};}};var checkPropTypes_1=checkPropTypes;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var has$1=Function.call.bind(Object.prototype.hasOwnProperty);var printWarning$1=function(){};{printWarning$1=function(text){var message='Warning: '+text;if(typeof console!=='undefined'){console.error(message);}try{// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);}catch(x){}};}function emptyFunctionThatReturnsNull(){return null;}var factoryWithTypeCheckers=function(isValidElement,throwOnDirectAccess){/* global Symbol */var ITERATOR_SYMBOL=typeof Symbol==='function'&&Symbol.iterator;var FAUX_ITERATOR_SYMBOL='@@iterator';// Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/function getIteratorFn(maybeIterable){var iteratorFn=maybeIterable&&(ITERATOR_SYMBOL&&maybeIterable[ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL]);if(typeof iteratorFn==='function'){return iteratorFn;}}/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/var ANONYMOUS='<<anonymous>>';// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes={array:createPrimitiveTypeChecker('array'),bool:createPrimitiveTypeChecker('boolean'),func:createPrimitiveTypeChecker('function'),number:createPrimitiveTypeChecker('number'),object:createPrimitiveTypeChecker('object'),string:createPrimitiveTypeChecker('string'),symbol:createPrimitiveTypeChecker('symbol'),any:createAnyTypeChecker(),arrayOf:createArrayOfTypeChecker,element:createElementTypeChecker(),elementType:createElementTypeTypeChecker(),instanceOf:createInstanceTypeChecker,node:createNodeChecker(),objectOf:createObjectOfTypeChecker,oneOf:createEnumTypeChecker,oneOfType:createUnionTypeChecker,shape:createShapeTypeChecker,exact:createStrictShapeTypeChecker};/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/ /*eslint-disable no-self-compare*/function is(x,y){// SameValue algorithm
if(x===y){// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x!==0||1/x===1/y;}else {// Step 6.a: NaN == NaN
return x!==x&&y!==y;}}/*eslint-enable no-self-compare*/ /**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/function PropTypeError(message){this.message=message;this.stack='';}// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype=Error.prototype;function createChainableTypeChecker(validate){{var manualPropTypeCallCache={};var manualPropTypeWarningCount=0;}function checkType(isRequired,props,propName,componentName,location,propFullName,secret){componentName=componentName||ANONYMOUS;propFullName=propFullName||propName;if(secret!==ReactPropTypesSecret_1){if(throwOnDirectAccess){// New behavior only for users of `prop-types` package
var err=new Error('Calling PropTypes validators directly is not supported by the `prop-types` package. '+'Use `PropTypes.checkPropTypes()` to call them. '+'Read more at http://fb.me/use-check-prop-types');err.name='Invariant Violation';throw err;}else if(typeof console!=='undefined'){// Old behavior for people using React.PropTypes
var cacheKey=componentName+':'+propName;if(!manualPropTypeCallCache[cacheKey]&&// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount<3){printWarning$1('You are manually calling a React.PropTypes validation '+'function for the `'+propFullName+'` prop on `'+componentName+'`. This is deprecated '+'and will throw in the standalone `prop-types` package. '+'You may be seeing this warning due to a third-party PropTypes '+'library. See https://fb.me/react-warning-dont-call-proptypes '+'for details.');manualPropTypeCallCache[cacheKey]=true;manualPropTypeWarningCount++;}}}if(props[propName]==null){if(isRequired){if(props[propName]===null){return new PropTypeError('The '+location+' `'+propFullName+'` is marked as required '+('in `'+componentName+'`, but its value is `null`.'));}return new PropTypeError('The '+location+' `'+propFullName+'` is marked as required in '+('`'+componentName+'`, but its value is `undefined`.'));}return null;}else {return validate(props,propName,componentName,location,propFullName);}}var chainedCheckType=checkType.bind(null,false);chainedCheckType.isRequired=checkType.bind(null,true);return chainedCheckType;}function createPrimitiveTypeChecker(expectedType){function validate(props,propName,componentName,location,propFullName,secret){var propValue=props[propName];var propType=getPropType(propValue);if(propType!==expectedType){// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType=getPreciseType(propValue);return new PropTypeError('Invalid '+location+' `'+propFullName+'` of type '+('`'+preciseType+'` supplied to `'+componentName+'`, expected ')+('`'+expectedType+'`.'));}return null;}return createChainableTypeChecker(validate);}function createAnyTypeChecker(){return createChainableTypeChecker(emptyFunctionThatReturnsNull);}function createArrayOfTypeChecker(typeChecker){function validate(props,propName,componentName,location,propFullName){if(typeof typeChecker!=='function'){return new PropTypeError('Property `'+propFullName+'` of component `'+componentName+'` has invalid PropType notation inside arrayOf.');}var propValue=props[propName];if(!Array.isArray(propValue)){var propType=getPropType(propValue);return new PropTypeError('Invalid '+location+' `'+propFullName+'` of type '+('`'+propType+'` supplied to `'+componentName+'`, expected an array.'));}for(var i=0;i<propValue.length;i++){var error=typeChecker(propValue,i,componentName,location,propFullName+'['+i+']',ReactPropTypesSecret_1);if(error instanceof Error){return error;}}return null;}return createChainableTypeChecker(validate);}function createElementTypeChecker(){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];if(!isValidElement(propValue)){var propType=getPropType(propValue);return new PropTypeError('Invalid '+location+' `'+propFullName+'` of type '+('`'+propType+'` supplied to `'+componentName+'`, expected a single ReactElement.'));}return null;}return createChainableTypeChecker(validate);}function createElementTypeTypeChecker(){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];if(!reactIs.isValidElementType(propValue)){var propType=getPropType(propValue);return new PropTypeError('Invalid '+location+' `'+propFullName+'` of type '+('`'+propType+'` supplied to `'+componentName+'`, expected a single ReactElement type.'));}return null;}return createChainableTypeChecker(validate);}function createInstanceTypeChecker(expectedClass){function validate(props,propName,componentName,location,propFullName){if(!(props[propName]instanceof expectedClass)){var expectedClassName=expectedClass.name||ANONYMOUS;var actualClassName=getClassName(props[propName]);return new PropTypeError('Invalid '+location+' `'+propFullName+'` of type '+('`'+actualClassName+'` supplied to `'+componentName+'`, expected ')+('instance of `'+expectedClassName+'`.'));}return null;}return createChainableTypeChecker(validate);}function createEnumTypeChecker(expectedValues){if(!Array.isArray(expectedValues)){{if(arguments.length>1){printWarning$1('Invalid arguments supplied to oneOf, expected an array, got '+arguments.length+' arguments. '+'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).');}else {printWarning$1('Invalid argument supplied to oneOf, expected an array.');}}return emptyFunctionThatReturnsNull;}function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];for(var i=0;i<expectedValues.length;i++){if(is(propValue,expectedValues[i])){return null;}}var valuesString=JSON.stringify(expectedValues,function replacer(key,value){var type=getPreciseType(value);if(type==='symbol'){return String(value);}return value;});return new PropTypeError('Invalid '+location+' `'+propFullName+'` of value `'+String(propValue)+'` '+('supplied to `'+componentName+'`, expected one of '+valuesString+'.'));}return createChainableTypeChecker(validate);}function createObjectOfTypeChecker(typeChecker){function validate(props,propName,componentName,location,propFullName){if(typeof typeChecker!=='function'){return new PropTypeError('Property `'+propFullName+'` of component `'+componentName+'` has invalid PropType notation inside objectOf.');}var propValue=props[propName];var propType=getPropType(propValue);if(propType!=='object'){return new PropTypeError('Invalid '+location+' `'+propFullName+'` of type '+('`'+propType+'` supplied to `'+componentName+'`, expected an object.'));}for(var key in propValue){if(has$1(propValue,key)){var err
// props.
var allKeys=objectAssign({},props[propName],shapeTypes);for(var key in allKeys){var checker=shapeTypes[key];if(!checker){return new PropTypeError('Invalid '+location+' `'+propFullName+'` key `'+key+'` supplied to `'+componentName+'`.'+'\nBad object: '+JSON.stringify(props[propName],null,' ')+'\nValid keys: '+JSON.stringify(Object.keys(shapeTypes),null,' '));}var error=checker(propValue,key,componentName,location,propFullName+'.'+key,ReactPropTypesSecret_1);if(error){return error;}}return null;}return createChainableTypeChecker(validate);}function isNode(propValue){switch(typeof propValue){case'number':case'string':case'undefined':return true;case'boolean':return !propValue;case'object':if(Array.isArray(propValue)){return propValue.every(isNode);}if(propValue===null||isValidElement(propValue)){return true;}var iteratorFn=getIteratorFn(propValue);if(iteratorFn){var iterator=iteratorFn.call(propValue);var step;if(iteratorFn!==propValue.entries){while(!(step=iterator.next()).done){if(!isNode(step.value)){return false;}}}else {// Iterator will provide entry [k,v] tuples rather than values.
while(!(step=iterator.next()).done){var entry=step.value;if(entry){if(!isNode(entry[1])){return false;}}}}}else {return false;}return true;default:return false;}}function isSymbol(propType,propValue){// Native Symbol.
if(propType==='symbol'){return true;}// falsy value can't be a Symbol
if(!propValue){return false;}// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if(propValue['@@toStringTag']==='Symbol'){return true;}// Fallback for non-spec compliant Symbols which are polyfilled.
if(typeof Symbol==='function'&&propValue instanceof Symbol){return true;}return false;}// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue){var propType=typeof propValue;if(Array.isArray(propValue)){return 'array';}if(propValue instanceof RegExp){// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';}if(isSymbol(propType,propValue)){return 'symbol';}return propType;}// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue){if(typeof propValue==='undefined'||propValue===null){return ''+propValue;}var propType=getPropType(propValue);if(propType==='object'){if(propValue instanceof Date){return 'date';}else if(propValue instanceof RegExp){return 'regexp';}}return propType;}// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value){var type=getPreciseType(value);switch(type){case'array':case'object':return 'an '+type;case'boolean':case'date':case'regexp':return 'a '+type;default:return type;}}// Returns class name of the object, if any.
function getClassName(propValue){if(!propValue.constructor||!propValue.constructor.name){return ANONYMOUS;}return propValue.constructor.name;}ReactPropTypes.checkPropTypes=checkPropTypes_1;ReactPropTypes.resetWarningCache=checkPropTypes_1.resetWarningCache;ReactPropTypes.PropTypes=ReactPropTypes;return ReactPropTypes;};
3 years ago
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
var propTypes = createCommonjsModule(function (module) {
{var ReactIs=reactIs;// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess=true;module.exports=factoryWithTypeCheckers(ReactIs.isElement,throwOnDirectAccess);}
});
3 years ago
var chartist = createCommonjsModule(function (module) {
(function(root,factory){if(module.exports){// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports=factory();}else {root['Chartist']=factory();}})(commonjsGlobal,function(){/* Chartist.js 0.11.4
* Copyright © 2019 Gion Kunz
* Free to use under either the WTFPL license or the MIT license.
* https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-WTFPL
* https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-MIT
*/ /**
* The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
*
* @module Chartist.Core
*/var Chartist={version:'0.11.4'};(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;/**
* This object contains all namespaces used within Chartist.
*
* @memberof Chartist.Core
* @type {{svg: string, xmlns: string, xhtml: string, xlink: string, ct: string}}
*/Chartist.namespaces={svg:'http://www.w3.org/2000/svg',xmlns:'http://www.w3.org/2000/xmlns/',xhtml:'http://www.w3.org/1999/xhtml',xlink:'http://www.w3.org/1999/xlink',ct:'http://gionkunz.github.com/chartist-js/ct'};/**
* Helps to simplify functional style code
*
* @memberof Chartist.Core
* @param {*} n This exact value will be returned by the noop function
* @return {*} The same value that was provided to the n parameter
*/Chartist.noop=function(n){return n;};/**
* Generates a-z from a number 0 to 26
*
* @memberof Chartist.Core
* @param {Number} n A number from 0 to 26 that will result in a letter a-z
* @return {String} A character from a-z based on the input number n
*/Chartist.alphaNumerate=function(n){// Limit to a-z
return String.fromCharCode(97+n%26);};/**
* Simple recursive object extend
*
* @memberof Chartist.Core
* @param {Object} target Target object where the source will be merged into
* @param {Object...} sources This object (objects) will be merged into target and then target is returned
* @return {Object} An object that has the same reference as target but is extended and merged with the properties of source
*/Chartist.extend=function(target){var i,source,sourceProp;target=target||{};for(i=1;i<arguments.length;i++){source=arguments[i];for(var prop in source){sourceProp=source[prop];if(typeof sourceProp==='object'&&sourceProp!==null&&!(sourceProp instanceof Array)){target[prop]=Chartist.extend(target[prop],sourceProp);}else {target[prop]=sourceProp;}}}return target;};/**
* Replaces all occurrences of subStr in str with newSubStr and returns a new string.
*
* @memberof Chartist.Core
* @param {String} str
* @param {String} subStr
* @param {String} newSubStr
* @return {String}
*/Chartist.replaceAll=function(str,subStr,newSubStr){return str.replace(new RegExp(subStr,'g'),newSubStr);};/**
* Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.
*
* @memberof Chartist.Core
* @param {Number} value
* @param {String} unit
* @return {String} Returns the passed number value with unit.
*/Chartist.ensureUnit=function(value,unit){if(typeof value==='number'){value=value+unit;}return value;};/**
* Converts a number or string to a quantity object.
*
* @memberof Chartist.Core
* @param {String|Number} input
* @return {Object} Returns an object containing the value as number and the unit as string.
*/Chartist.quantity=function(input){if(typeof input==='string'){var match=/^(\d+)\s*(.*)$/g.exec(input);return {value:+match[1],unit:match[2]||undefined};}return {value:input};};/**
* This is a wrapper around document.querySelector that will return the query if it's already of type Node
*
* @memberof Chartist.Core
* @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly
* @return {Node}
*/Chartist.querySelector=function(query){return query instanceof Node?query:document.querySelector(query);};/**
* Functional style helper to produce array with given length initialized with undefined values
*
* @memberof Chartist.Core
* @param length
* @return {Array}
*/Chartist.times=function(length){return Array.apply(null,new Array(length));};/**
* Sum helper to be used in reduce functions
*
* @memberof Chartist.Core
* @param previous
* @param current
* @return {*}
*/Chartist.sum=function(previous,current){return previous+(current?current:0);};/**
* Multiply helper to be used in `Array.map` for multiplying each value of an array with a factor.
*
* @memberof Chartist.Core
* @param {Number} factor
* @returns {Function} Function that can be used in `Array.map` to multiply each value in an array
*/Chartist.mapMultiply=function(factor){return function(num){return num*factor;};};/**
* Add helper to be used in `Array.map` for adding a addend to each value of an array.
*
* @memberof Chartist.Core
* @param {Number} addend
* @returns {Function} Function that can be used in `Array.map` to add a addend to each value in an array
*/Chartist.mapAdd=function(addend){return function(num){return num+addend;};};/**
* Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).
*
* @memberof Chartist.Core
* @param arr
* @param cb
* @return {Array}
*/Chartist.serialMap=function(arr,cb){var result=[],length=Math.max.apply(null,arr.map(function(e){return e.length;}));Chartist.times(length).forEach(function(e,index){var args=arr.map(function(e){return e[index];});result[index]=cb.apply(null,args);});return result;};/**
* This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit.
*
* @memberof Chartist.Core
* @param {Number} value The value that should be rounded with precision
* @param {Number} [digits] The number of digits after decimal used to do the rounding
* @returns {number} Rounded value
*/Chartist.roundWithPrecision=function(value,digits){var precision=Math.pow(10,digits||Chartist.precision);return Math.round(value*precision)/precision;};/**
* Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.
*
* @memberof Chartist.Core
* @type {number}
*/Chartist.precision=8;/**
* A map with characters to escape for strings to be safely used as attribute values.
*
* @memberof Chartist.Core
* @type {Object}
*/Chartist.escapingMap={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#039;'};/**
* This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.
* If called with null or undefined the function will return immediately with null or undefined.
*
* @memberof Chartist.Core
* @param {Number|String|Object} data
* @return {String}
*/Chartist.serialize=function(data){if(data===null||data===undefined){return data;}else if(typeof data==='number'){data=''+data;}else if(typeof data==='object'){data=JSON.stringify({data:data});}return Object.keys(Chartist.escapingMap).reduce(function(result,key){return Chartist.replaceAll(result,key,Chartist.escapingMap[key]);},data);};/**
* This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.
*
* @memberof Chartist.Core
* @param {String} data
* @return {String|Number|Object}
*/Chartist.deserialize=function(data){if(typeof data!=='string'){return data;}data=Object.keys(Chartist.escapingMap).reduce(function(result,key){return Chartist.replaceAll(result,Chartist.escapingMap[key],key);},data);try{data=JSON.parse(data);data=data.data!==undefined?data.data:data;}catch(e){}return data;};/**
* Create or reinitialize the SVG element for the chart
*
* @memberof Chartist.Core
* @param {Node} container The containing DOM Node object that will be used to plant the SVG element
* @param {String} width Set the width of the SVG element. Default is 100%
* @param {String} height Set the height of the SVG element. Default is 100%
* @param {String} className Specify a class to be added to the SVG element
* @return {Object} The created/reinitialized SVG element
*/Chartist.createSvg=function(container,width,height,className){var svg;width=width||'100%';height=height||'100%';// Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it
// Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/
Array.prototype.slice.call(container.querySelectorAll('svg')).filter(function filterChartistSvgObjects(svg){return svg.getAttributeNS(Chartist.namespaces.xmlns,'ct');}).forEach(function removePreviousElement(svg){container.removeChild(svg);});// Create svg object with width and height or use 100% as default
svg=new Chartist.Svg('svg').attr({width:width,height:height}).addClass(className);svg._node.style.width=width;svg._node.style.height=height;// Add the DOM node to our container
container.appendChild(svg._node);return svg;};/**
* Ensures that the data object passed as second argument to the charts is present and correctly initialized.
*
* @param {Object} data The data object that is passed as second argument to the charts
* @return {Object} The normalized data object
*/Chartist.normalizeData=function(data,reverse,multi){var labelCount;var output={raw:data,normalized:{}};// Check if we should generate some labels based on existing series data
output.normalized.series=Chartist.getDataArray({series:data.series||[]},reverse,multi);// If all elements of the normalized data array are arrays we're dealing with
// multi series data and we need to find the largest series if they are un-even
if(output.normalized.series.every(function(value){return value instanceof Array;})){// Getting the series with the the most elements
labelCount=Math.max.apply(null,output.normalized.series.map(function(series){return series.length;}));}else {// We're dealing with Pie data so we just take the normalized array length
labelCount=output.normalized.series.length;}output.normalized.labels=(data.labels||[]).slice();// Padding the labels to labelCount with empty strings
Array.prototype.push.apply(output.normalized.labels,Chartist.times(Math.max(0,labelCount-output.normalized.labels.length)).map(function(){return '';}));if(reverse){Chartist.reverseData(output.normalized);}return output;};/**
* This function safely checks if an objects has an owned property.
*
* @param {Object} object The object where to check for a property
* @param {string} property The property name
* @returns {boolean} Returns true if the object owns the specified property
*/Chartist.safeHasProperty=function(object,property){return object!==null&&typeof object==='object'&&object.hasOwnProperty(property);};/**
* Checks if a value is considered a hole in the data series.
*
* @param {*} value
* @returns {boolean} True if the value is considered a data hole
*/Chartist.isDataHoleValue=function(value){return value===null||value===undefined||typeof value==='number'&&isNaN(value);};/**
* Reverses the series, labels and series data arrays.
*
* @memberof Chartist.Core
* @param data
*/Chartist.reverseData=function(data){data.labels.reverse();data.series.reverse();for(var i=0;i<data.series.length;i++){if(typeof data.series[i]==='object'&&data.series[i].data!==undefined){data.series[i].data.reverse();}else if(data.series[i]instanceof Array){data.series[i].reverse();}}};/**
* Convert data series into plain array
*
* @memberof Chartist.Core
* @param {Object} data The series object that contains the data to be visualized in the chart
* @param {Boolean} [reverse] If true the whole data is reversed by the getDataArray call. This will modify the data object passed as first parameter. The labels as well as the series order is reversed. The whole series data arrays are reversed too.
* @param {Boolean} [multi] Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created.
* @return {Array} A plain array that contains the data to be visualized in the chart
*/Chartist.getDataArray=function(data,reverse,multi){// Recursively walks through nested arrays and convert string values to numbers and objects with value properties
// to values. Check the tests in data core -> data normalization for a detailed specification of expected values
function recursiveConvert(value){if(Chartist.safeHasProperty(value,'value')){// We are dealing with value object notation so we need to recurse on value property
return recursiveConvert(value.value);}else if(Chartist.safeHasProperty(value,'data')){// We are dealing with series object notation so we need to recurse on data property
return recursiveConvert(value.data);}else if(value instanceof Array){// Data is of type array so we need to recurse on the series
return value.map(recursiveConvert);}else if(Chartist.isDataHoleValue(value)){// We're dealing with a hole in the data and therefore need to return undefined
// We're also returning undefined for multi value output
return undefined;}else {// We need to prepare multi value output (x and y data)
if(multi){var multiValue={};// Single series value arrays are assumed to specify the Y-Axis value
// For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}]
// If multi is a string then it's assumed that it specified which dimension should be filled as default
if(typeof multi==='string'){multiValue[multi]=Chartist.getNumberOrUndefined(value);}else {multiValue.y=Chartist.getNumberOrUndefined(value);}multiValue.x=value.hasOwnProperty('x')?Chartist.getNumberOrUndefined(value.x):multiValue.x;multiValue.y=value.hasOwnProperty('y')?Chartist.getNumberOrUndefined(value.y):multiValue.y;return multiValue;}else {// We can return simple data
return Chartist.getNumberOrUndefined(value);}}}return data.series.map(recursiveConvert);};/**
* Converts a number into a padding object.
*
* @memberof Chartist.Core
* @param {Object|Number} padding
* @param {Number} [fallback] This value is used to fill missing values if a incomplete padding object was passed
* @returns {Object} Returns a padding object containing top, right, bottom, left properties filled with the padding number passed in as argument. If the argument is something else than a number (presumably already a correct padding object) then this argument is directly returned.
*/Chartist.normalizePadding=function(padding,fallback){fallback=fallback||0;return typeof padding==='number'?{top:padding,right:padding,bottom:padding,left:padding}:{top:typeof padding.top==='number'?padding.top:fallback,right:typeof padding.right==='number'?padding.right:fallback,bottom:typeof padding.bottom==='number'?padding.bottom:fallback,left:typeof padding.left==='number'?padding.left:fallback};};Chartist.getMetaData=function(series,index){var value=series.data?series.data[index]:series[index];return value?value.meta:undefined;};/**
* Calculate the order of magnitude for the chart scale
*
* @memberof Chartist.Core
* @param {Number} value The value Range of the chart
* @return {Number} The order of magnitude
*/Chartist.orderOfMagnitude=function(value){return Math.floor(Math.log(Math.abs(value))/Math.LN10);};/**
* Project a data length into screen coordinates (pixels)
*
* @memberof Chartist.Core
* @param {Object} axisLength The svg element for the chart
* @param {Number} length Single data value from a series array
* @param {Object} bounds All the values to set the bounds of the chart
* @return {Number} The projected data length in pixels
*/Chartist.projectLength=function(axisLength,length,bounds){return length/bounds.range*axisLength;};/**
* Get the height of the area in the chart for the data series
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Number} The height of the area in the chart for the data series
*/Chartist.getAvailableHeight=function(svg,options){return Math.max((Chartist.quantity(options.height).value||svg.height())-(options.chartPadding.top+options.chartPadding.bottom)-options.axisX.offset,0);};/**
* Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
*
* @memberof Chartist.Core
* @param {Array} data The array that contains the data to be visualized in the chart
* @param {Object} options The Object that contains the chart options
* @param {String} dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration
* @return {Object} An object that contains the highest and lowest value that will be visualized on the chart.
*/Chartist.getHighLow=function(data,options,dimension){// TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred
options=Chartist.extend({},options,dimension?options['axis'+dimension.toUpperCase()]:{});var highLow={high:options.high===undefined?-Number.MAX_VALUE:+options.high,low:options.low===undefined?Number.MAX_VALUE:+options.low};var findHigh=options.high===undefined;var findLow=options.low===undefined;// Function to recursively walk through arrays and find highest and lowest number
function recursiveHighLow(data){if(data===undefined){return undefined;}else if(data instanceof Array){for(var i=0;i<data.length;i++){recursiveHighLow(data[i]);}}else {var value=dimension?+data[dimension]:+data;if(findHigh&&value>highLow.high){highLow.high=value;}if(findLow&&value<highLow.low){highLow.low=value;}}}// Start to find highest and lowest number recursively
if(findHigh||findLow){recursiveHighLow(data);}// Overrides of high / low based on reference value, it will make sure that the invisible reference value is
// used to generate the chart. This is useful when the chart always needs to contain the position of the
// invisible reference value in the view i.e. for bipolar scales.
if(options.referenceValue||options.referenceValue===0){highLow.high=Math.max(options.referenceValue,highLow.high);highLow.low=Math.min(options.referenceValue,highLow.low);}// If high and low are the same because of misconfiguration or flat data (only the same value) we need
// to set the high or low to 0 depending on the polarity
if(highLow.high<=highLow.low){// If both values are 0 we set high to 1
if(highLow.low===0){highLow.high=1;}else if(highLow.low<0){// If we have the same negative value for the bounds we set bounds.high to 0
highLow.high=0;}else if(highLow.high>0){// If we have the same positive value for the bounds we set bounds.low to 0
highLow.low=0;}else {// If data array was empty, values are Number.MAX_VALUE and -Number.MAX_VALUE. Set bounds to prevent errors
highLow.high=1;highLow.low=0;}}return highLow;};/**
* Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.
*
* @memberof Chartist.Core
* @param value
* @returns {Boolean}
*/Chartist.isNumeric=function(value){return value===null?false:isFinite(value);};/**
* Returns true on all falsey values except the numeric value 0.
*
* @memberof Chartist.Core
* @param value
* @returns {boolean}
*/Chartist.isFalseyButZero=function(value){return !value&&value!==0;};/**
* Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.
*
* @memberof Chartist.Core
* @param value
* @returns {*}
*/Chartist.getNumberOrUndefined=function(value){return Chartist.isNumeric(value)?+value:undefined;};/**
* Checks if provided value object is multi value (contains x or y properties)
*
* @memberof Chartist.Core
* @param value
*/Chartist.isMultiValue=function(value){return typeof value==='object'&&('x'in value||'y'in value);};/**
* Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`.
*
* @memberof Chartist.Core
* @param value
* @param dimension
* @param defaultValue
* @returns {*}
*/Chartist.getMultiValue=function(value,dimension){if(Chartist.isMultiValue(value)){return Chartist.getNumberOrUndefined(value[dimension||'y']);}else {return Chartist.getNumberOrUndefined(value);}};/**
* Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.
*
* @memberof Chartist.Core
* @param {Number} num An integer number where the smallest factor should be searched for
* @returns {Number} The smallest integer factor of the parameter num.
*/Chartist.rho=function(num){if(num===1){return num;}function gcd(p,q){if(p%q===0){return q;}else {return gcd(q,p%q);}}function f(x){return x*x+1;}var x1=2,x2=2,divisor;if(num%2===0){return 2;}do{x1=f(x1)%num;x2=f(f(x2))%num;divisor=gcd(Math.abs(x1-x2),num);}while(divisor===1);return divisor;};/**
* Calculate and retrieve all the bounds for the chart and return them in one array
*
* @memberof Chartist.Core
* @param {Number} axisLength The length of the Axis used for
* @param {Object} highLow An object containing a high and low property indicating the value range of the chart.
* @param {Number} scaleMinSpace The minimum projected length a step should result in
* @param {Boolean} onlyInteger
* @return {Object} All the values to set the bounds of the chart
*/Chartist.getBounds=function(axisLength,highLow,scaleMinSpace,onlyInteger){var i,optimizationCounter=0,newMin,newMax,bounds={high:highLow.high,low:highLow.low};bounds.valueRange=bounds.high-bounds.low;bounds.oom=Chartist.orderOfMagnitude(bounds.valueRange);bounds.step=Math.pow(10,bounds.oom);bounds.min=Math.floor(bounds.low/bounds.step)*bounds.step;bounds.max=Math.ceil(bounds.high/bounds.step)*bounds.step;bounds.range=bounds.max-bounds.min;bounds.numberOfSteps=Math.round(bounds.range/bounds.step);// Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
// If we are already below the scaleMinSpace value we will scale up
var length=Chartist.projectLength(axisLength,bounds.step,bounds);var scaleUp=length<scaleMinSpace;var smallestFactor=onlyInteger?Chartist.rho(bounds.range):0;// First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1
if(onlyInteger&&Chartist.projectLength(axisLength,1,bounds)>=scaleMinSpace){bounds.step=1;}else if(onlyInteger&&smallestFactor<bounds.step&&Chartist.projectLength(axisLength,smallestFactor,bounds)>=scaleMinSpace){// If step 1 was too small, we can try the smallest factor of range
// If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor
// is larger than the scaleMinSpace we should go for it.
bounds.step=smallestFactor;}else {// Trying to divide or multiply by 2 and find the best step value
while(true){if(scaleUp&&Chartist.projectLength(axisLength,bounds.step,bounds)<=scaleMinSpace){bounds.step*=2;}else if(!scaleUp&&Chartist.projectLength(axisLength,bounds.step/2,bounds)>=scaleMinSpace){bounds.step/=2;if(onlyInteger&&bounds.step%1!==0){bounds.step*=2;break;}}else {break;}if(optimizationCounter++>1000){throw new Error('Exceeded maximum number of iterations while optimizing scale step!');}}}var EPSILON=2.221E-16;bounds.step=Math.max(bounds.step,EPSILON);function safeIncrement(value,increment){// If increment is too small use *= (1+EPSILON) as a simple nextafter
if(value===(value+=increment)){value*=1+(increment>0?EPSILON:-EPSILON);}return value;}// Narrow min and max based on new step
newMin=bounds.min;newMax=bounds.max;while(newMin+bounds.step<=bounds.low){newMin=safeIncrement(newMin,bounds.step);}while(newMax-bounds.step>=bounds.high){newMax=safeIncrement(newMax,-bounds.step);}bounds.min=newMin;bounds.max=newMax;bounds.range=bounds.max-bounds.min;var values=[];for(i=bounds.min;i<=bounds.max;i=safeIncrement(i,bounds.step)){var value=Chartist.roundWithPrecision(i);if(value!==values[values.length-1]){values.push(value);}}bounds.values=values;return bounds;};/**
* Calculate cartesian coordinates of polar coordinates
*
* @memberof Chartist.Core
* @param {Number} centerX X-axis coordinates of center point of circle segment
* @param {Number} centerY X-axis coordinates of center point of circle segment
* @param {Number} radius Radius of circle segment
* @param {Number} angleInDegrees Angle of circle segment in degrees
* @return {{x:Number, y:Number}} Coordinates of point on circumference
*/Chartist.polarToCartesian=function(centerX,centerY,radius,angleInDegrees){var angleInRadians=(angleInDegrees-90)*Math.PI/180.0;return {x:centerX+radius*Math.cos(angleInRadians),y:centerY+radius*Math.sin(angleInRadians)};};/**
* Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Number} [fallbackPadding] The fallback padding if partial padding objects are used
* @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements
*/Chartist.createChartRect=function(svg,options,fallbackPadding){var hasAxis=!!(options.axisX||options.axisY);var yAxisOffset=hasAxis?options.axisY.offset:0;var xAxisOffset=hasAxis?options.axisX.offset:0;// If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0
var width=svg.width()||Chartist.quantity(options.width).value||0;var height=svg.height()||Chartist.quantity(options.height).value||0;var normalizedPadding=Chartist.normalizePadding(options.chartPadding,fallbackPadding);// If settings were to small to cope with offset (legacy) and padding, we'll adjust
width=Math.max(width,yAxisOffset+normalizedPadding.left+normalizedPadding.right);height=Math.max(height,xAxisOffset+normalizedPadding.top+normalizedPadding.bottom);var chartRect={padding:normalizedPadding,width:function(){return this.x2-this.x1;},height:function(){return this.y1-this.y2;}};if(hasAxis){if(options.axisX.position==='start'){chartRect.y2=normalizedPadding.top+xAxisOffset;chartRect.y1=Math.max(height-normalizedPadding.bottom,chartRect.y2+1);}else {chartRect.y2=normalizedPadding.top;chartRect.y1=Math.max(height-normalizedPadding.bottom-xAxisOffset,chartRect.y2+1);}if(options.axisY.position==='start'){chartRect.x1=normalizedPadding.left+yAxisOffset;chartRect.x2=Math.max(width-normalizedPadding.right,chartRect.x1+1);}else {chartRect.x1=normalizedPadding.left;chartRect.x2=Math.max(width-normalizedPadding.right-yAxisOffset,chartRect.x1+1);}}else {chartRect.x1=normalizedPadding.left;chartRect.x2=Math.max(width-normalizedPadding.right,chartRect.x1+1);chartRect.y2=normalizedPadding.top;chartRect.y1=Math.max(height-normalizedPadding.bottom,chartRect.y2+1);}return chartRect;};/**
* Creates a grid line based on a projected value.
*
* @memberof Chartist.Core
* @param position
* @param index
* @param axis
* @param offset
* @param length
* @param group
* @param classes
* @param eventEmitter
*/Chartist.createGrid=function(position,index,axis,offset,length,group,classes,eventEmitter){var positionalData={};positionalData[axis.units.pos+'1']=position;positionalData[axis.units.pos+'2']=position;positionalData[axis.counterUnits.pos+'1']=offset;positionalData[axis.counterUnits.pos+'2']=offset+length;var gridElement=group.elem('line',positionalData,classes.join(' '));// Event for grid draw
eventEmitter.emit('draw',Chartist.extend({type:'grid',axis:axis,index:index,group:group,element:gridElement},positionalData));};/**
* Creates a grid background rect and emits the draw event.
*
* @memberof Chartist.Core
* @param gridGroup
* @param chartRect
* @param className
* @param eventEmitter
*/Chartist.createGridBackground=function(gridGroup,chartRect,className,eventEmitter){var gridBackground=gridGroup.elem('rect',{x:chartRect.x1,y:chartRect.y2,width:chartRect.width(),height:chartRect.height()},className,true);// Event for grid background draw
eventEmitter.emit('draw',{type:'gridBackground',group:gridGroup,element:gridBackground});};/**
* Creates a label based on a projected value and an axis.
*
* @memberof Chartist.Core
* @param position
* @param length
* @param index
* @param labels
* @param axis
* @param axisOffset
* @param labelOffset
* @param group
* @param classes
* @param useForeignObject
* @param eventEmitter
*/Chartist.createLabel=function(position,length,index,labels,axis,axisOffset,labelOffset,group,classes,useForeignObject,eventEmitter){var labelElement;var positionalData={};positionalData[axis.units.pos]=position+labelOffset[axis.units.pos];positionalData[axis.counterUnits.pos]=labelOffset[axis.counterUnits.pos];positionalData[axis.units.len]=length;positionalData[axis.counterUnits.len]=Math.max(0,axisOffset-10);if(useForeignObject){// We need to set width and height explicitly to px as span will not expand with width and height being
// 100% in all browsers
var content=document.createElement('span');content.className=classes.join(' ');content.setAttribute('xmlns',Chartist.namespaces.xhtml);content.innerText=labels[index];content.style[axis.units.len]=Math.round(positionalData[axis.units.len])+'px';content.style[axis.counterUnits.len]=Math.round(positionalData[axis.counterUnits.len])+'px';labelElement=group.foreignObject(content,Chartist.extend({style:'overflow: visible;'},positionalData));}else {labelElement=group.elem('text',positionalData,classes.join(' ')).text(labels[index]);}eventEmitter.emit('draw',Chartist.extend({type:'label',axis:axis,index:index,group:group,element:labelElement,text:labels[index]},positionalData));};/**
* Helper to read series specific options from options object. It automatically falls back to the global option if
* there is no option in the series options.
*
* @param {Object} series Series object
* @param {Object} options Chartist options object
* @param {string} key The options key that should be used to obtain the options
* @returns {*}
*/Chartist.getSeriesOption=function(series,options,key){if(series.name&&options.series&&options.series[series.name]){var seriesOptions=options.series[series.name];return seriesOptions.hasOwnProperty(key)?seriesOptions[key]:options[key];}else {return options[key];}};/**
* Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
*
* @memberof Chartist.Core
* @param {Object} options Options set by user
* @param {Array} responsiveOptions Optional functions to add responsive behavior to chart
* @param {Object} eventEmitter The event emitter that will be used to emit the options changed events
* @return {Object} The consolidated options object from the defaults, base and matching responsive options
*/Chartist.optionsProvider=function(options,responsiveOptions,eventEmitter){var baseOptions=Chartist.extend({},options),currentOptions,mediaQueryListeners=[],i;function updateCurrentOptions(mediaEvent){var previousOptions=currentOptions;currentOptions=Chartist.extend({},baseOptions);if(responsiveOptions){for(i=0;i<responsiveOptions.length;i++){var mql=window.matchMedia(responsiveOptions[i][0]);if(mql.matches){currentOptions=Chartist.extend(currentOptions,responsiveOptions[i][1]);}}}if(eventEmitter&&mediaEvent){eventEmitter.emit('optionsChanged',{previousOptions:previousOptions,currentOptions:currentOptions});}}function removeMediaQueryListeners(){mediaQueryListeners.forEach(function(mql){mql.removeListener(updateCurrentOptions);});}if(!window.matchMedia){throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';}else if(responsiveOptions){for(i=0;i<responsiveOptions.length;i++){var mql=window.matchMedia(responsiveOptions[i][0]);mql.addListener(updateCurrentOptions);mediaQueryListeners.push(mql);}}// Execute initially without an event argument so we get the correct options
updateCurrentOptions();return {removeMediaQueryListeners:removeMediaQueryListeners,getCurrentOptions:function getCurrentOptions(){return Chartist.extend({},currentOptions);}};};/**
* Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates
* valueData property describing the segment.
*
* With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any
* points with undefined values are discarded.
*
* **Options**
* The following options are used to determine how segments are formed
* ```javascript
* var options = {
* // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.
* fillHoles: false,
* // If increasingX is true, the coordinates in all segments have strictly increasing x-values.
* increasingX: false
* };
* ```
*
* @memberof Chartist.Core
* @param {Array} pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn]
* @param {Array} values List of associated point values in the form [v1, v2 .. vn]
* @param {Object} options Options set by user
* @return {Array} List of segments, each containing a pathCoordinates and valueData property.
*/Chartist.splitIntoSegments=function(pathCoordinates,valueData,options){var defaultOptions={increasingX:false,fillHoles:false};options=Chartist.extend({},defaultOptions,options);var segments=[];var hole=true;for(var i=0;i<pathCoordinates.length;i+=2){// If this value is a "hole" we set the hole flag
if(Chartist.getMultiValue(valueData[i/2].value)===undefined){// if(valueData[i / 2].value === undefined) {
if(!options.fillHoles){hole=true;}}else {if(options.increasingX&&i>=2&&pathCoordinates[i]<=pathCoordinates[i-2]){// X is not increasing, so we need to make sure we start a new segment
hole=true;}// If it's a valid value we need to check if we're coming out of a hole and create a new empty segment
if(hole){segments.push({pathCoordinates:[],valueData:[]});// As we have a valid value now, we are not in a "hole" anymore
hole=false;}// Add to the segment pathCoordinates and valueData
segments[segments.length-1].pathCoordinates.push(pathCoordinates[i],pathCoordinates[i+1]);segments[segments.length-1].valueData.push(valueData[i/2]);}}return segments;};})(this||commonjsGlobal,Chartist);/**
* Chartist path interpolation functions.
*
* @module Chartist.Interpolation
*/ /* global Chartist */(function(globalRoot,Chartist){Chartist.Interpolation={};/**
* This interpolation function does not smooth the path and the result is only containing lines and no curves.
*
* @example
* var chart = new Chartist.Line('.ct-chart', {
* labels: [1, 2, 3, 4, 5],
* series: [[1, 2, 8, 1, 7]]
* }, {
* lineSmooth: Chartist.Interpolation.none({
* fillHoles: false
* })
* });
*
*
* @memberof Chartist.Interpolation
* @return {Function}
*/Chartist.Interpolation.none=function(options){var defaultOptions={fillHoles:false};options=Chartist.extend({},defaultOptions,options);return function none(pathCoordinates,valueData){var path=new Chartist.Svg.Path();var hole=true;for(var i=0;i<pathCoordinates.length;i+=2){var currX=pathCoordinates[i];var currY=pathCoordinates[i+1];var currData=valueData[i/2];if(Chartist.getMultiValue(currData.value)!==undefined){if(hole){path.move(currX,currY,false,currData);}else {path.line(currX,currY,false,currData);}hole=false;}else if(!options.fillHoles){hole=true;}}return path;};};/**
* Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing.
*
* Simple smoothing can be used instead of `Chartist.Smoothing.cardinal` if you'd like to get rid of the artifacts it produces sometimes. Simple smoothing produces less flowing lines but is accurate by hitting the points and it also doesn't swing below or above the given data point.
*
* All smoothing functions within Chartist are factory functions that accept an options parameter. The simple interpolation function accepts one configuration parameter `divisor`, between 1 and , which controls the smoothing characteristics.
*
* @example
* var chart = new Chartist.Line('.ct-chart', {
* labels: [1, 2, 3, 4, 5],
* series: [[1, 2, 8, 1, 7]]
* }, {
* lineSmooth: Chartist.Interpolation.simple({
* divisor: 2,
* fillHoles: false
* })
* });
*
*
* @memberof Chartist.Interpolation
* @param {Object} options The options of the simple interpolation factory function.
* @return {Function}
*/Chartist.Interpolation.simple=function(options){var defaultOptions={divisor:2,fillHoles:false};options=Chartist.extend({},defaultOptions,options);var d=1/Math.max(1,options.divisor);return function simple(pathCoordinates,valueData){var path=new Chartist.Svg.Path();var prevX,prevY,prevData;for(var i=0;i<pathCoordinates.length;i+=2){var currX=pathCoordinates[i];var currY=pathCoordinates[i+1];var length=(currX-prevX)*d;var currData=valueData[i/2];if(currData.value!==undefined){if(prevData===undefined){path.move(currX,currY,false,currData);}else {path.curve(prevX+length,prevY,currX-length,currY,currX,currY,false,currData);}prevX=currX;prevY=currY;prevData=currData;}else if(!options.fillHoles){prevX=currX=prevData=undefined;}}return path;};};/**
* Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results.
*
* Cardinal splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
*
* All smoothing functions within Chartist are factory functions that accept an options parameter. The cardinal interpolation function accepts one configuration parameter `tension`, between 0 and 1, which controls the smoothing intensity.
*
* @example
* var chart = new Chartist.Line('.ct-chart', {
* labels: [1, 2, 3, 4, 5],
* series: [[1, 2, 8, 1, 7]]
* }, {
* lineSmooth: Chartist.Interpolation.cardinal({
* tension: 1,
* fillHoles: false
* })
* });
*
* @memberof Chartist.Interpolation
* @param {Object} options The options of the cardinal factory function.
* @return {Function}
*/Chartist.Interpolation.cardinal=function(options){var defaultOptions={tension:1,fillHoles:false};options=Chartist.extend({},defaultOptions,options);var t=Math.min(1,Math.max(0,options.tension)),c=1-t;return function cardinal(pathCoordinates,valueData){// First we try to split the coordinates into segments
// This is necessary to treat "holes" in line charts
var segments=Chartist.splitIntoSegments(pathCoordinates,valueData,{fillHoles:options.fillHoles});if(!segments.length){// If there were no segments return 'Chartist.Interpolation.none'
return Chartist.Interpolation.none()([]);}else if(segments.length>1){// If the split resulted in more that one segment we need to interpolate each segment individually and join them
// afterwards together into a single path.
var paths=[];// For each segment we will recurse the cardinal function
segments.forEach(function(segment){paths.push(cardinal(segment.pathCoordinates,segment.valueData));});// Join the segment path data into a single path and return
return Chartist.Svg.Path.join(paths);}else {// If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
// segment
pathCoordinates=segments[0].pathCoordinates;valueData=segments[0].valueData;// If less than two points we need to fallback to no smoothing
if(pathCoordinates.length<=4){return Chartist.Interpolation.none()(pathCoordinates,valueData);}var path=new Chartist.Svg.Path().move(pathCoordinates[0],pathCoordinates[1],false,valueData[0]),z;for(var i=0,iLen=pathCoordinates.length;iLen-2*!z>i;i+=2){var p=[{x:+pathCoordinates[i-2],y:+pathCoordinates[i-1]},{x:+pathCoordinates[i],y:+pathCoordinates[i+1]},{x:+pathCoordinates[i+2],y:+pathCoordinates[i+3]},{x:+pathCoordinates[i+4],y:+pathCoordinates[i+5]}];if(z){if(!i){p[0]={x:+pathCoordinates[iLen-2],y:+pathCoordinates[iLen-1]};}else if(iLen-4===i){p[3]={x:+pathCoordinates[0],y:+pathCoordinates[1]};}else if(iLen-2===i){p[2]={x:+pathCoordinates[0],y:+pathCoordinates[1]};p[3]={x:+pathCoordinates[2],y:+pathCoordinates[3]};}}else {if(iLen-4===i){p[3]=p[2];}else if(!i){p[0]={x:+pathCoordinates[i],y:+pathCoordinates[i+1]};}}path.curve(t*(-p[0].x+6*p[1].x+p[2].x)/6+c*p[2].x,t*(-p[0].y+6*p[1].y+p[2].y)/6+c*p[2].y,t*(p[1].x+6*p[2].x-p[3].x)/6+c*p[2].x,t*(p[1].y+6*p[2].y-p[3].y)/6+c*p[2].y,p[2].x,p[2].y,false,valueData[(i+2)/2]);}return path;}};};/**
* Monotone Cubic spline interpolation produces a smooth curve which preserves monotonicity. Unlike cardinal splines, the curve will not extend beyond the range of y-values of the original data points.
*
* Monotone Cubic splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
*
* The x-values of subsequent points must be increasing to fit a Monotone Cubic spline. If this condition is not met for a pair of adjacent points, then there will be a break in the curve between those data points.
*
* All smoothing functions within Chartist are factory functions that accept an options parameter.
*
* @example
* var chart = new Chartist.Line('.ct-chart', {
* labels: [1, 2, 3, 4, 5],
* series: [[1, 2, 8, 1, 7]]
* }, {
* lineSmooth: Chartist.Interpolation.monotoneCubic({
* fillHoles: false
* })
* });
*
* @memberof Chartist.Interpolation
* @param {Object} options The options of the monotoneCubic factory function.
* @return {Function}
*/Chartist.Interpolation.monotoneCubic=function(options){var defaultOptions={fillHoles:false};options=Chartist.extend({},defaultOptions,options);return function monotoneCubic(pathCoordinates,valueData){// First we try to split the coordinates into segments
// This is necessary to treat "holes" in line charts
var segments=Chartist.splitIntoSegments(pathCoordinates,valueData,{fillHoles:options.fillHoles,increasingX:true});if(!segments.length){// If there were no segments return 'Chartist.Interpolation.none'
return Chartist.Interpolation.none()([]);}else if(segments.length>1){// If the split resulted in more that one segment we need to interpolate each segment individually and join them
// afterwards together into a single path.
var paths=[];// For each segment we will recurse the monotoneCubic fn function
segments.forEach(function(segment){paths.push(monotoneCubic(segment.pathCoordinates,segment.valueData));});// Join the segment path data into a single path and return
return Chartist.Svg.Path.join(paths);}else {// If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
// segment
pathCoordinates=segments[0].pathCoordinates;valueData=segments[0].valueData;// If less than three points we need to fallback to no smoothing
if(pathCoordinates.length<=4){return Chartist.Interpolation.none()(pathCoordinates,valueData);}var xs=[],ys=[],i,n=pathCoordinates.length/2,ms=[],ds=[],dys=[],dxs=[],path;// Populate x and y coordinates into separate arrays, for readability
for(i=0;i<n;i++){xs[i]=pathCoordinates[i*2];ys[i]=pathCoordinates[i*2+1];}// Calculate deltas and derivative
for(i=0;i<n-1;i++){dys[i]=ys[i+1]-ys[i];dxs[i]=xs[i+1]-xs[i];ds[i]=dys[i]/dxs[i];}// Determine desired slope (m) at each point using Fritsch-Carlson method
// See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation
ms[0]=ds[0];ms[n-1]=ds[n-2];for(i=1;i<n-1;i++){if(ds[i]===0||ds[i-1]===0||ds[i-1]>0!==ds[i]>0){ms[i]=0;}else {ms[i]=3*(dxs[i-1]+dxs[i])/((2*dxs[i]+dxs[i-1])/ds[i-1]+(dxs[i]+2*dxs[i-1])/ds[i]);if(!isFinite(ms[i])){ms[i]=0;}}}// Now build a path from the slopes
path=new Chartist.Svg.Path().move(xs[0],ys[0],false,valueData[0]);for(i=0;i<n-1;i++){path.curve(// First control point
xs[i]+dxs[i]/3,ys[i]+ms[i]*dxs[i]/3,// Second control point
xs[i+1]-dxs[i]/3,ys[i+1]-ms[i+1]*dxs[i]/3,// End point
xs[i+1],ys[i+1],false,valueData[i+1]);}return path;}};};/**
* Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the `showPoint` option is enabled.
*
* All smoothing functions within Chartist are factory functions that accept an options parameter. The step interpolation function accepts one configuration parameter `postpone`, that can be `true` or `false`. The default value is `true` and will cause the step to occur where the value actually changes. If a different behaviour is needed where the step is shifted to the left and happens before the actual value, this option can be set to `false`.
*
* @example
* var chart = new Chartist.Line('.ct-chart', {
* labels: [1, 2, 3, 4, 5],
* series: [[1, 2, 8, 1, 7]]
* }, {
* lineSmooth: Chartist.Interpolation.step({
* postpone: true,
* fillHoles: false
* })
* });
*
* @memberof Chartist.Interpolation
* @param options
* @returns {Function}
*/Chartist.Interpolation.step=function(options){var defaultOptions={postpone:true,fillHoles:false};options=Chartist.extend({},defaultOptions,options);return function step(pathCoordinates,valueData){var path=new Chartist.Svg.Path();var prevX,prevY,prevData;for(var i=0;i<pathCoordinates.length;i+=2){var currX=pathCoordinates[i];var currY=pathCoordinates[i+1];var currData=valueData[i/2];// If the current point is also not a hole we can draw the step lines
if(currData.value!==undefined){if(prevData===undefined){path.move(currX,currY,false,currData);}else {if(options.postpone){// If postponed we should draw the step line with the value of the previous value
path.line(currX,prevY,false,prevData);}else {// If not postponed we should draw the step line with the value of the current value
path.line(prevX,currY,false,currData);}// Line to the actual point (this should only be a Y-Axis movement
path.line(currX,currY,false,currData);}prevX=currX;prevY=currY;prevData=currData;}else if(!options.fillHoles){prevX=prevY=prevData=undefined;}}return path;};};})(this||commonjsGlobal,Chartist);/**
* A very basic event module that helps to generate and catch events.
*
* @module Chartist.Event
*/ /* global Chartist */(function(globalRoot,Chartist){Chartist.EventEmitter=function(){var handlers=[];/**
* Add an event handler for a specific event
*
* @memberof Chartist.Event
* @param {String} event The event name
* @param {Function} handler A event handler function
*/function addEventHandler(event,handler){handlers[event]=handlers[event]||[];handlers[event].push(handler);}/**
* Remove an event handler of a specific event name or remove all event handlers for a specific event.
*
* @memberof Chartist.Event
* @param {String} event The event name where a specific or all handlers should be removed
* @param {Function} [handler] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed.
*/function removeEventHandler(event,handler){// Only do something if there are event handlers with this name existing
if(handlers[event]){// If handler is set we will look for a specific handler and only remove this
if(handler){handlers[event].splice(handlers[event].indexOf(handler),1);if(handlers[event].length===0){delete handlers[event];}}else {// If no handler is specified we remove all handlers for this event
delete handlers[event];}}}/**
* Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.
*
* @memberof Chartist.Event
* @param {String} event The event name that should be triggered
* @param {*} data Arbitrary data that will be passed to the event handler callback functions
*/function emit(event,data){// Only do something if there are event handlers with this name existing
if(handlers[event]){handlers[event].forEach(function(handler){handler(data);});}// Emit event to star event handlers
if(handlers['*']){handlers['*'].forEach(function(starHandler){starHandler(event,data);});}}return {addEventHandler:addEventHandler,removeEventHandler:removeEventHandler,emit:emit};};})(this||commonjsGlobal,Chartist);/**
* This module provides some basic prototype inheritance utilities.
*
* @module Chartist.Class
*/ /* global Chartist */(function(globalRoot,Chartist){function listToArray(list){var arr=[];if(list.length){for(var i=0;i<list.length;i++){arr.push(list[i]);}}return arr;}/**
* Method to extend from current prototype.
*
* @memberof Chartist.Class
* @param {Object} properties The object that serves as definition for the prototype that gets created for the new class. This object should always contain a constructor property that is the desired constructor for the newly created class.
* @param {Object} [superProtoOverride] By default extens will use the current class prototype or Chartist.class. With this parameter you can specify any super prototype that will be used.
* @return {Function} Constructor function of the new class
*
* @example
* var Fruit = Class.extend({
* color: undefined,
* sugar: undefined,
*
* constructor: function(color, sugar) {
* this.color = color;
* this.sugar = sugar;
* },
*
* eat: function() {
* this.sugar = 0;
* return this;
* }
* });
*
* var Banana = Fruit.extend({
* length: undefined,
*
* constructor: function(length, sugar) {
* Banana.super.constructor.call(this, 'Yellow', sugar);
* this.length = length;
* }
* });
*
* var banana = new Banana(20, 40);
* console.log('banana instanceof Fruit', banana instanceof Fruit);
* console.log('Fruit is prototype of banana', Fruit.prototype.isPrototypeOf(banana));
* console.log('bananas prototype is Fruit', Object.getPrototypeOf(banana) === Fruit.prototype);
* console.log(banana.sugar);
* console.log(banana.eat().sugar);
* console.log(banana.color);
*/function extend(properties,superProtoOverride){var superProto=superProtoOverride||this.prototype||Chartist.Class;var proto=Object.create(superProto);Chartist.Class.cloneDefinitions(proto,properties);var constr=function(){var fn=proto.constructor||function(){},instance;// If this is linked to the Chartist namespace the constructor was not called with new
// To provide a fallback we will instantiate here and return the instance
instance=this===Chartist?Object.create(proto):this;fn.apply(instance,Array.prototype.slice.call(arguments,0));// If this constructor was not called with new we need to return the instance
// This will not harm when the constructor has been called with new as the returned value is ignored
return instance;};constr.prototype=proto;constr.super=superProto;constr.extend=this.extend;return constr;}// Variable argument list clones args > 0 into args[0] and retruns modified args[0]
function cloneDefinitions(){var args=listToArray(arguments);var target=args[0];args.splice(1,args.length-1).forEach(function(source){Object.getOwnPropertyNames(source).forEach(function(propName){// If this property already exist in target we delete it first
delete target[propName];// Define the property with the descriptor from source
Object.defineProperty(target,propName,Object.getOwnPropertyDescriptor(source,propName));});});return target;}Chartist.Class={extend:extend,cloneDefinitions:cloneDefinitions};})(this||commonjsGlobal,Chartist);/**
* Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
*
* @module Chartist.Base
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;// TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
// This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
// work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
// See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
// Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
// The problem is with the label offsets that can't be converted into percentage and affecting the chart container
3 years ago
/**
* Updates the chart which currently does a full reconstruction of the SVG DOM
*
* @param {Object} [data] Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
* @param {Object} [options] Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.
* @param {Boolean} [override] If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base
* @memberof Chartist.Base
*/function update(data,options,override){if(data){this.data=data||{};this.data.labels=this.data.labels||[];this.data.series=this.data.series||[];// Event for data transformation that allows to manipulate the data before it gets rendered in the charts
this.eventEmitter.emit('data',{type:'update',data:this.data});}if(options){this.options=Chartist.extend({},override?this.options:this.defaultOptions,options);// If chartist was not initialized yet, we just set the options and leave the rest to the initialization
// Otherwise we re-create the optionsProvider at this point
if(!this.initializeTimeoutId){this.optionsProvider.removeMediaQueryListeners();this.optionsProvider=Chartist.optionsProvider(this.options,this.responsiveOptions,this.eventEmitter);}}// Only re-created the chart if it has been initialized yet
if(!this.initializeTimeoutId){this.createChart(this.optionsProvider.getCurrentOptions());}// Return a reference to the chart object to chain up calls
return this;}/**
* This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
*
* @memberof Chartist.Base
*/function detach(){// Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore
// the initializationTimeoutId is still a valid timeout reference, we will clear the timeout
if(!this.initializeTimeoutId){window.removeEventListener('resize',this.resizeListener);this.optionsProvider.removeMediaQueryListeners();}else {window.clearTimeout(this.initializeTimeoutId);}return this;}/**
* Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
*
* @memberof Chartist.Base
* @param {String} event Name of the event. Check the examples for supported events.
* @param {Function} handler The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
*/function on(event,handler){this.eventEmitter.addEventHandler(event,handler);return this;}/**
* Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
*
* @memberof Chartist.Base
* @param {String} event Name of the event for which a handler should be removed
* @param {Function} [handler] The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.
*/function off(event,handler){this.eventEmitter.removeEventHandler(event,handler);return this;}function initialize(){// Add window resize listener that re-creates the chart
window.addEventListener('resize',this.resizeListener);// Obtain current options based on matching media queries (if responsive options are given)
// This will also register a listener that is re-creating the chart based on media changes
this.optionsProvider=Chartist.optionsProvider(this.options,this.responsiveOptions,this.eventEmitter);// Register options change listener that will trigger a chart update
this.eventEmitter.addEventHandler('optionsChanged',function(){this.update();}.bind(this));// Before the first chart creation we need to register us with all plugins that are configured
// Initialize all relevant plugins with our chart object and the plugin options specified in the config
if(this.options.plugins){this.options.plugins.forEach(function(plugin){if(plugin instanceof Array){plugin[0](this,plugin[1]);}else {plugin(this);}}.bind(this));}// Event for data transformation that allows to manipulate the data before it gets rendered in the charts
this.eventEmitter.emit('data',{type:'initial',data:this.data});// Create the first chart
this.createChart(this.optionsProvider.getCurrentOptions());// As chart is initialized from the event loop now we can reset our timeout reference
// This is important if the chart gets initialized on the same element twice
this.initializeTimeoutId=undefined;}/**
* Constructor of chart base class.
*
* @param query
* @param data
* @param defaultOptions
* @param options
* @param responsiveOptions
* @constructor
*/function Base(query,data,defaultOptions,options,responsiveOptions){this.container=Chartist.querySelector(query);this.data=data||{};this.data.labels=this.data.labels||[];this.data.series=this.data.series||[];this.defaultOptions=defaultOptions;this.options=options;this.responsiveOptions=responsiveOptions;this.eventEmitter=Chartist.EventEmitter();this.supportsForeignObject=Chartist.Svg.isSupported('Extensibility');this.supportsAnimations=Chartist.Svg.isSupported('AnimationEventsAttribute');this.resizeListener=function resizeListener(){this.update();}.bind(this);if(this.container){// If chartist was already initialized in this container we are detaching all event listeners first
if(this.container.__chartist__){this.container.__chartist__.detach();}this.container.__chartist__=this;}// Using event loop for first draw to make it possible to register event listeners in the same call stack where
// the chart was created.
this.initializeTimeoutId=setTimeout(initialize.bind(this),0);}// Creating the chart base class
Chartist.Base=Chartist.Class.extend({constructor:Base,optionsProvider:undefined,container:undefined,svg:undefined,eventEmitter:undefined,createChart:function(){throw new Error('Base chart type can\'t be instantiated!');},update:update,detach:detach,on:on,off:off,version:Chartist.version,supportsForeignObject:false});})(this||commonjsGlobal,Chartist);/**
* Chartist SVG module for simple SVG DOM abstraction
3 years ago
*
* @module Chartist.Svg
*/ /* global Chartist */(function(globalRoot,Chartist){var document=globalRoot.document;/**
* Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.
*
* @memberof Chartist.Svg
* @constructor
* @param {String|Element} name The name of the SVG element to create or an SVG dom element which should be wrapped into Chartist.Svg
* @param {Object} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
* @param {String} className This class or class list will be added to the SVG element
* @param {Object} parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child
* @param {Boolean} insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
*/function Svg(name,attributes,className,parent,insertFirst){// If Svg is getting called with an SVG element we just return the wrapper
if(name instanceof Element){this._node=name;}else {this._node=document.createElementNS(Chartist.namespaces.svg,name);// If this is an SVG element created then custom namespace
if(name==='svg'){this.attr({'xmlns:ct':Chartist.namespaces.ct});}}if(attributes){this.attr(attributes);}if(className){this.addClass(className);}if(parent){if(insertFirst&&parent._node.firstChild){parent._node.insertBefore(this._node,parent._node.firstChild);}else {parent._node.appendChild(this._node);}}}/**
* Set attributes on the current SVG element of the wrapper you're currently working on.
*
* @memberof Chartist.Svg
* @param {Object|String} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value.
* @param {String} [ns] If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object.
* @return {Object|String} The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function.
*/function attr(attributes,ns){if(typeof attributes==='string'){if(ns){return this._node.getAttributeNS(ns,attributes);}else {return this._node.getAttribute(attributes);}}Object.keys(attributes).forEach(function(key){// If the attribute value is undefined we can skip this one
if(attributes[key]===undefined){return;}if(key.indexOf(':')!==-1){var namespacedAttribute=key.split(':');this._node.setAttributeNS(Chartist.namespaces[namespacedAttribute[0]],key,attributes[key]);}else {this._node.setAttribute(key,attributes[key]);}}.bind(this));return this;}/**
* Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.
*
* @memberof Chartist.Svg
* @param {String} name The name of the SVG element that should be created as child element of the currently selected element wrapper
* @param {Object} [attributes] An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
* @param {String} [className] This class or class list will be added to the SVG element
* @param {Boolean} [insertFirst] If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
* @return {Chartist.Svg} Returns a Chartist.Svg wrapper object that can be used to modify the containing SVG data
*/function elem(name,attributes,className,insertFirst){return new Chartist.Svg(name,attributes,className,this,insertFirst);}/**
* Returns the parent Chartist.SVG wrapper object
*
* @memberof Chartist.Svg
* @return {Chartist.Svg} Returns a Chartist.Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null.
*/function parent(){return this._node.parentNode instanceof SVGElement?new Chartist.Svg(this._node.parentNode):null;}/**
* This method returns a Chartist.Svg wrapper around the root SVG element of the current tree.
*
* @memberof Chartist.Svg
* @return {Chartist.Svg} The root SVG element wrapped in a Chartist.Svg element
*/function root(){var node=this._node;while(node.nodeName!=='svg'){node=node.parentNode;}return new Chartist.Svg(node);}/**
* Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper.
*
* @memberof Chartist.Svg
* @param {String} selector A CSS selector that is used to query for child SVG elements
* @return {Chartist.Svg} The SVG wrapper for the element found or null if no element was found
*/function querySelector(selector){var foundNode=this._node.querySelector(selector);return foundNode?new Chartist.Svg(foundNode):null;}/**
* Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper.
*
* @memberof Chartist.Svg
* @param {String} selector A CSS selector that is used to query for child SVG elements
* @return {Chartist.Svg.List} The SVG wrapper list for the element found or null if no element was found
*/function querySelectorAll(selector){var foundNodes=this._node.querySelectorAll(selector);return foundNodes.length?new Chartist.Svg.List(foundNodes):null;}/**
* Returns the underlying SVG node for the current element.
*
* @memberof Chartist.Svg
* @returns {Node}
*/function getNode(){return this._node;}/**
* This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.
*
* @memberof Chartist.Svg
* @param {Node|String} content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject
* @param {String} [attributes] An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added.
* @param {String} [className] This class or class list will be added to the SVG element
* @param {Boolean} [insertFirst] Specifies if the foreignObject should be inserted as first child
* @return {Chartist.Svg} New wrapper object that wraps the foreignObject element
*/function foreignObject(content,attributes,className,insertFirst){// If content is string then we convert it to DOM
// TODO: Handle case where content is not a string nor a DOM Node
if(typeof content==='string'){var container=document.createElement('div');container.innerHTML=content;content=container.firstChild;}// Adding namespace to content element
content.setAttribute('xmlns',Chartist.namespaces.xmlns);// Creating the foreignObject without required extension attribute (as described here
// http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)
var fnObj=this.elem('foreignObject',attributes,className,insertFirst);// Add content to foreignObjectElement
fnObj._node.appendChild(content);return fnObj;}/**
* This method adds a new text element to the current Chartist.Svg wrapper.
*
* @memberof Chartist.Svg
* @param {String} t The text that should be added to the text element that is created
* @return {Chartist.Svg} The same wrapper object that was used to add the newly created element
*/function text(t){this._node.appendChild(document.createTextNode(t));return this;}/**
* This method will clear all child nodes of the current wrapper object.
*
* @memberof Chartist.Svg
* @return {Chartist.Svg} The same wrapper object that got emptied
*/function empty(){while(this._node.firstChild){this._node.removeChild(this._node.firstChild);}return this;}/**
* This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure.
*
* @memberof Chartist.Svg
* @return {Chartist.Svg} The parent wrapper object of the element that got removed
*/function remove(){this._node.parentNode.removeChild(this._node);return this.parent();}/**
* This method will replace the element with a new element that can be created outside of the current DOM.
*
* @memberof Chartist.Svg
* @param {Chartist.Svg} newElement The new Chartist.Svg object that will be used to replace the current wrapper object
* @return {Chartist.Svg} The wrapper of the new element
*/function replace(newElement){this._node.parentNode.replaceChild(newElement._node,this._node);return newElement;}/**
* This method will append an element to the current element as a child.
*
* @memberof Chartist.Svg
* @param {Chartist.Svg} element The Chartist.Svg element that should be added as a child
* @param {Boolean} [insertFirst] Specifies if the element should be inserted as first child
* @return {Chartist.Svg} The wrapper of the appended object
*/function append(element,insertFirst){if(insertFirst&&this._node.firstChild){this._node.insertBefore(element._node,this._node.firstChild);}else {this._node.appendChild(element._node);}return this;}/**
* Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.
*
* @memberof Chartist.Svg
* @return {Array} A list of classes or an empty array if there are no classes on the current element
*/function classes(){return this._node.getAttribute('class')?this._node.getAttribute('class').trim().split(/\s+/):[];}/**
* Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.
*
* @memberof Chartist.Svg
* @param {String} names A white space separated list of class names
* @return {Chartist.Svg} The wrapper of the current element
*/function addClass(names){this._node.setAttribute('class',this.classes(this._node).concat(names.trim().split(/\s+/)).filter(function(elem,pos,self){return self.indexOf(elem)===pos;}).join(' '));return this;}/**
* Removes one or a space separated list of classes from the current element.
*
* @memberof Chartist.Svg
* @param {String} names A white space separated list of class names
* @return {Chartist.Svg} The wrapper of the current element
*/function removeClass(names){var removedClasses=names.trim().split(/\s+/);this._node.setAttribute('class',this.classes(this._node).filter(function(name){return removedClasses.indexOf(name)===-1;}).join(' '));return this;}/**
* Removes all classes from the current element.
*
* @memberof Chartist.Svg
* @return {Chartist.Svg} The wrapper of the current element
*/function removeAllClasses(){this._node.setAttribute('class','');return this;}/**
* Get element height using `getBoundingClientRect`
*
* @memberof Chartist.Svg
* @return {Number} The elements height in pixels
*/function height(){return this._node.getBoundingClientRect().height;}/**
* Get element width using `getBoundingClientRect`
*
* @memberof Chartist.Core
* @return {Number} The elements width in pixels
*/function width(){return this._node.getBoundingClientRect().width;}/**
* The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in `Chartist.Svg.Easing` or an array with four numbers specifying a cubic Bézier curve.
* **An animations object could look like this:**
* ```javascript
* element.animate({
* opacity: {
* dur: 1000,
* from: 0,
* to: 1
* },
* x1: {
* dur: '1000ms',
* from: 100,
* to: 200,
* easing: 'easeOutQuart'
* },
* y1: {
* dur: '2s',
* from: 0,
* to: 100
* }
* });
* ```
* **Automatic unit conversion**
* For the `dur` and the `begin` animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds.
* **Guided mode**
* The default behavior of SMIL animations with offset using the `begin` attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation `from` value even before the animation starts. Also if you don't specify `fill="freeze"` on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the `begin` property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it.
* If guided mode is enabled the following behavior is added:
* - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation
* - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation)
* - The animate element will be forced to use `fill="freeze"`
* - The animation will be triggered with `beginElement()` in a timeout where `begin` of the definition object is interpreted in milli seconds. If no `begin` was specified the timeout is triggered immediately.
* - After the animation the element attribute value will be set to the `to` value of the animation
* - The animate element is deleted from the DOM
*
* @memberof Chartist.Svg
* @param {Object} animations An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode.
* @param {Boolean} guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated.
* @param {Object} eventEmitter If specified, this event emitter will be notified when an animation starts or ends.
* @return {Chartist.Svg} The current element where the animation was added
*/function animate(animations,guided,eventEmitter){if(guided===undefined){guided=true;}Object.keys(animations).forEach(function createAnimateForAttributes(attribute){function createAnimate(animationDefinition,guided){var attributeProperties={},animate,timeout,easing;// Check if an easing is specified in the definition object and delete it from the object as it will not
// be part of the animate element attributes.
if(animationDefinition.easing){// If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object
easing=animationDefinition.easing instanceof Array?animationDefinition.easing:Chartist.Svg.Easing[animationDefinition.easing];delete animationDefinition.easing;}// If numeric dur or begin was provided we assume milli seconds
animationDefinition.begin=Chartist.ensureUnit(animationDefinition.begin,'ms');animationDefinition.dur=Chartist.ensureUnit(animationDefinition.dur,'ms');if(easing){animationDefinition.calcMode='spline';animationDefinition.keySplines=easing.join(' ');animationDefinition.keyTimes='0;1';}// Adding "fill: freeze" if we are in guided mode and set initial attribute values
if(guided){animationDefinition.fill='freeze';// Animated property on our element should already be set to the animation from value in guided mode
attributeProperties[attribute]=animationDefinition.from;this.attr(attributeProperties);// In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin
// which needs to be in ms aside
timeout=Chartist.quantity(animationDefinition.begin||0).value;animationDefinition.begin='indefinite';}animate=this.elem('animate',Chartist.extend({attributeName:attribute},animationDefinition));if(guided){// If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout
setTimeout(function(){// If beginElement fails we set the animated attribute to the end position and remove the animate element
// This happens if the SMIL ElementTimeControl interface is not supported or any other problems occured in
// the browser. (Currently FF 34 does not support animate elements in foreignObjects)
try{animate._node.beginElement();}catch(err){// Set animated attribute to current animated value
attributeProperties[attribute]=animationDefinition.to;this.attr(attributeProperties);// Remove the animate element as it's no longer required
animate.remove();}}.bind(this),timeout);}if(eventEmitter){animate._node.addEventListener('beginEvent',function handleBeginEvent(){eventEmitter.emit('animationBegin',{element:this,animate:animate._node,params:animationDefinition});}.bind(this));}animate._node.addEventListener('endEvent',function handleEndEvent(){if(eventEmitter){eventEmitter.emit('animationEnd',{element:this,animate:animate._node,params:animationDefinition});}if(guided){// Set animated attribute to current animated value
attributeProperties[attribute]=animationDefinition.to;this.attr(attributeProperties);// Remove the animate element as it's no longer required
animate.remove();}}.bind(this));}// If current attribute is an array of definition objects we create an animate for each and disable guided mode
if(animations[attribute]instanceof Array){animations[attribute].forEach(function(animationDefinition){createAnimate.bind(this)(animationDefinition,false);}.bind(this));}else {createAnimate.bind(this)(animations[attribute],guided);}}.bind(this));return this;}Chartist.Svg=Chartist.Class.extend({constructor:Svg,attr:attr,elem:elem,parent:parent,root:root,querySelector:querySelector,querySelectorAll:querySelectorAll,getNode:getNode,foreignObject:foreignObject,text:text,empty:empty,remove:remove,replace:replace,append:append,classes:classes,addClass:addClass,removeClass:removeClass,removeAllClasses:removeAllClasses,height:height,width:width,animate:animate});/**
* This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list.
*
* @memberof Chartist.Svg
* @param {String} feature The SVG 1.1 feature that should be checked for support.
* @return {Boolean} True of false if the feature is supported or not
*/Chartist.Svg.isSupported=function(feature){return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#'+feature,'1.1');};/**
* This Object contains some standard easing cubic bezier curves. Then can be used with their name in the `Chartist.Svg.animate`. You can also extend the list and use your own name in the `animate` function. Click the show code button to see the available bezier functions.
*
* @memberof Chartist.Svg
*/var easingCubicBeziers={easeInSine:[0.47,0,0.745,0.715],easeOutSine:[0.39,0.575,0.565,1],easeInOutSine:[0.445,0.05,0.55,0.95],easeInQuad:[0.55,0.085,0.68,0.53],easeOutQuad:[0.25,0.46,0.45,0.94],easeInOutQuad:[0.455,0.03,0.515,0.955],easeInCubic:[0.55,0.055,0.675,0.19],easeOutCubic:[0.215,0.61,0.355,1],easeInOutCubic:[0.645,0.045,0.355,1],easeInQuart:[0.895,0.03,0.685,0.22],easeOutQuart:[0.165,0.84,0.44,1],easeInOutQuart:[0.77,0,0.175,1],easeInQuint:[0.755,0.05,0.855,0.06],easeOutQuint:[0.23,1,0.32,1],easeInOutQuint:[0.86,0,0.07,1],easeInExpo:[0.95,0.05,0.795,0.035],easeOutExpo:[0.19,1,0.22,1],easeInOutExpo:[1,0,0,1],easeInCirc:[0.6,0.04,0.98,0.335],easeOutCirc:[0.075,0.82,0.165,1],easeInOutCirc:[0.785,0.135,0.15,0.86],easeInBack:[0.6,-0.28,0.735,0.045],easeOutBack:[0.175,0.885,0.32,1.275],easeInOutBack:[0.68,-0.55,0.265,1.55]};Chartist.Svg.Easing=easingCubicBeziers;/**
* This helper class is to wrap multiple `Chartist.Svg` elements into a list where you can call the `Chartist.Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Chartist.Svg` on multiple elements.
* An instance of this class is also returned by `Chartist.Svg.querySelectorAll`.
*
* @memberof Chartist.Svg
* @param {Array<Node>|NodeList} nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)
* @constructor
*/function SvgList(nodeList){var list=this;this.svgElements=[];for(var i=0;i<nodeList.length;i++){this.svgElements.push(new Chartist.Svg(nodeList[i]));}// Add delegation methods for Chartist.Svg
Object.keys(Chartist.Svg.prototype).filter(function(prototypeProperty){return ['constructor','parent','querySelector','querySelectorAll','replace','append','classes','height','width'].indexOf(prototypeProperty)===-1;}).forEach(function(prototypeProperty){list[prototypeProperty]=function(){var args=Array.prototype.slice.call(arguments,0);list.svgElements.forEach(function(element){Chartist.Svg.prototype[prototypeProperty].apply(element,args);});return list;};});}Chartist.Svg.List=Chartist.Class.extend({constructor:SvgList});})(this||commonjsGlobal,Chartist);/**
* Chartist SVG path module for SVG path description creation and modification.
3 years ago
*
* @module Chartist.Svg.Path
*/ /* global Chartist */(function(globalRoot,Chartist){/**
* Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.
*
* @memberof Chartist.Svg.Path
* @type {Object}
*/var elementDescriptions={m:['x','y'],l:['x','y'],c:['x1','y1','x2','y2','x','y'],a:['rx','ry','xAr','lAf','sf','x','y']};/**
* Default options for newly created SVG path objects.
*
* @memberof Chartist.Svg.Path
* @type {Object}
*/var defaultOptions={// The accuracy in digit count after the decimal point. This will be used to round numbers in the SVG path. If this option is set to false then no rounding will be performed.
accuracy:3};function element(command,params,pathElements,pos,relative,data){var pathElement=Chartist.extend({command:relative?command.toLowerCase():command.toUpperCase()},params,data?{data:data}:{});pathElements.splice(pos,0,pathElement);}function forEachParam(pathElements,cb){pathElements.forEach(function(pathElement,pathElementIndex){elementDescriptions[pathElement.command.toLowerCase()].forEach(function(paramName,paramIndex){cb(pathElement,paramName,pathElementIndex,paramIndex,pathElements);});});}/**
* Used to construct a new path object.
*
* @memberof Chartist.Svg.Path
* @param {Boolean} close If set to true then this path will be closed when stringified (with a Z at the end)
* @param {Object} options Options object that overrides the default objects. See default options for more details.
* @constructor
*/function SvgPath(close,options){this.pathElements=[];this.pos=0;this.close=close;this.options=Chartist.extend({},defaultOptions,options);}/**
* Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.
*
* @memberof Chartist.Svg.Path
* @param {Number} [pos] If a number is passed then the cursor is set to this position in the path element array.
* @return {Chartist.Svg.Path|Number} If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned.
*/function position(pos){if(pos!==undefined){this.pos=Math.max(0,Math.min(this.pathElements.length,pos));return this;}else {return this.pos;}}/**
* Removes elements from the path starting at the current position.
*
* @memberof Chartist.Svg.Path
* @param {Number} count Number of path elements that should be removed from the current position.
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function remove(count){this.pathElements.splice(this.pos,count);return this;}/**
* Use this function to add a new move SVG path element.
*
* @memberof Chartist.Svg.Path
* @param {Number} x The x coordinate for the move element.
* @param {Number} y The y coordinate for the move element.
* @param {Boolean} [relative] If set to true the move element will be created with relative coordinates (lowercase letter)
* @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function move(x,y,relative,data){element('M',{x:+x,y:+y},this.pathElements,this.pos++,relative,data);return this;}/**
* Use this function to add a new line SVG path element.
*
* @memberof Chartist.Svg.Path
* @param {Number} x The x coordinate for the line element.
* @param {Number} y The y coordinate for the line element.
* @param {Boolean} [relative] If set to true the line element will be created with relative coordinates (lowercase letter)
* @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function line(x,y,relative,data){element('L',{x:+x,y:+y},this.pathElements,this.pos++,relative,data);return this;}/**
* Use this function to add a new curve SVG path element.
*
* @memberof Chartist.Svg.Path
* @param {Number} x1 The x coordinate for the first control point of the bezier curve.
* @param {Number} y1 The y coordinate for the first control point of the bezier curve.
* @param {Number} x2 The x coordinate for the second control point of the bezier curve.
* @param {Number} y2 The y coordinate for the second control point of the bezier curve.
* @param {Number} x The x coordinate for the target point of the curve element.
* @param {Number} y The y coordinate for the target point of the curve element.
* @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
* @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function curve(x1,y1,x2,y2,x,y,relative,data){element('C',{x1:+x1,y1:+y1,x2:+x2,y2:+y2,x:+x,y:+y},this.pathElements,this.pos++,relative,data);return this;}/**
* Use this function to add a new non-bezier curve SVG path element.
*
* @memberof Chartist.Svg.Path
* @param {Number} rx The radius to be used for the x-axis of the arc.
* @param {Number} ry The radius to be used for the y-axis of the arc.
* @param {Number} xAr Defines the orientation of the arc
* @param {Number} lAf Large arc flag
* @param {Number} sf Sweep flag
* @param {Number} x The x coordinate for the target point of the curve element.
* @param {Number} y The y coordinate for the target point of the curve element.
* @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
* @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function arc(rx,ry,xAr,lAf,sf,x,y,relative,data){element('A',{rx:+rx,ry:+ry,xAr:+xAr,lAf:+lAf,sf:+sf,x:+x,y:+y},this.pathElements,this.pos++,relative,data);return this;}/**
* Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object.
*
* @memberof Chartist.Svg.Path
* @param {String} path Any SVG path that contains move (m), line (l) or curve (c) components.
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function parse(path){// Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']]
var chunks=path.replace(/([A-Za-z])([0-9])/g,'$1 $2').replace(/([0-9])([A-Za-z])/g,'$1 $2').split(/[\s,]+/).reduce(function(result,element){if(element.match(/[A-Za-z]/)){result.push([]);}result[result.length-1].push(element);return result;},[]);// If this is a closed path we remove the Z at the end because this is determined by the close option
if(chunks[chunks.length-1][0].toUpperCase()==='Z'){chunks.pop();}// Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters
// For example {command: 'M', x: '10', y: '10'}
var elements=chunks.map(function(chunk){var command=chunk.shift(),description=elementDescriptions[command.toLowerCase()];return Chartist.extend({command:command},description.reduce(function(result,paramName,index){result[paramName]=+chunk[index];return result;},{}));});// Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position
var spliceArgs=[this.pos,0];Array.prototype.push.apply(spliceArgs,elements);Array.prototype.splice.apply(this.pathElements,spliceArgs);// Increase the internal position by the element count
this.pos+=elements.length;return this;}/**
* This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string.
*
* @memberof Chartist.Svg.Path
* @return {String}
*/function stringify(){var accuracyMultiplier=Math.pow(10,this.options.accuracy);return this.pathElements.reduce(function(path,pathElement){var params=elementDescriptions[pathElement.command.toLowerCase()].map(function(paramName){return this.options.accuracy?Math.round(pathElement[paramName]*accuracyMultiplier)/accuracyMultiplier:pathElement[paramName];}.bind(this));return path+pathElement.command+params.join(',');}.bind(this),'')+(this.close?'Z':'');}/**
* Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate.
*
* @memberof Chartist.Svg.Path
* @param {Number} x The number which will be used to scale the x, x1 and x2 of all path elements.
* @param {Number} y The number which will be used to scale the y, y1 and y2 of all path elements.
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function scale(x,y){forEachParam(this.pathElements,function(pathElement,paramName){pathElement[paramName]*=paramName[0]==='x'?x:y;});return this;}/**
* Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate.
*
* @memberof Chartist.Svg.Path
* @param {Number} x The number which will be used to translate the x, x1 and x2 of all path elements.
* @param {Number} y The number which will be used to translate the y, y1 and y2 of all path elements.
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function translate(x,y){forEachParam(this.pathElements,function(pathElement,paramName){pathElement[paramName]+=paramName[0]==='x'?x:y;});return this;}/**
* This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.
* The method signature of the callback function looks like this:
* ```javascript
* function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)
* ```
* If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.
*
* @memberof Chartist.Svg.Path
* @param {Function} transformFnc The callback function for the transformation. Check the signature in the function description.
* @return {Chartist.Svg.Path} The current path object for easy call chaining.
*/function transform(transformFnc){forEachParam(this.pathElements,function(pathElement,paramName,pathElementIndex,paramIndex,pathElements){var transformed=transformFnc(pathElement,paramName,pathElementIndex,paramIndex,pathElements);if(transformed||transformed===0){pathElement[paramName]=transformed;}});return this;}/**
* This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.
*
* @memberof Chartist.Svg.Path
* @param {Boolean} [close] Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.
* @return {Chartist.Svg.Path}
*/function clone(close){var c=new Chartist.Svg.Path(close||this.close);c.pos=this.pos;c.pathElements=this.pathElements.slice().map(function cloneElements(pathElement){return Chartist.extend({},pathElement);});c.options=Chartist.extend({},this.options);return c;}/**
* Split a Svg.Path object by a specific command in the path chain. The path chain will be split and an array of newly created paths objects will be returned. This is useful if you'd like to split an SVG path by it's move commands, for example, in order to isolate chunks of drawings.
*
* @memberof Chartist.Svg.Path
* @param {String} command The command you'd like to use to split the path
* @return {Array<Chartist.Svg.Path>}
*/function splitByCommand(command){var split=[new Chartist.Svg.Path()];this.pathElements.forEach(function(pathElement){if(pathElement.command===command.toUpperCase()&&split[split.length-1].pathElements.length!==0){split.push(new Chartist.Svg.Path());}split[split.length-1].pathElements.push(pathElement);});return split;}/**
* This static function on `Chartist.Svg.Path` is joining multiple paths together into one paths.
*
* @memberof Chartist.Svg.Path
* @param {Array<Chartist.Svg.Path>} paths A list of paths to be joined together. The order is important.
* @param {boolean} close If the newly created path should be a closed path
* @param {Object} options Path options for the newly created path.
* @return {Chartist.Svg.Path}
*/function join(paths,close,options){var joinedPath=new Chartist.Svg.Path(close,options);for(var i=0;i<paths.length;i++){var path=paths[i];for(var j=0;j<path.pathElements.length;j++){joinedPath.pathElements.push(path.pathElements[j]);}}return joinedPath;}Chartist.Svg.Path=Chartist.Class.extend({constructor:SvgPath,position:position,remove:remove,move:move,line:line,curve:curve,arc:arc,scale:scale,translate:translate,transform:transform,parse:parse,stringify:stringify,clone:clone,splitByCommand:splitByCommand});Chartist.Svg.Path.elementDescriptions=elementDescriptions;Chartist.Svg.Path.join=join;})(this||commonjsGlobal,Chartist);/* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;var axisUnits={x:{pos:'x',len:'width',dir:'horizontal',rectStart:'x1',rectEnd:'x2',rectOffset:'y2'},y:{pos:'y',len:'height',dir:'vertical',rectStart:'y2',rectEnd:'y1',rectOffset:'x1'}};function Axis(units,chartRect,ticks,options){this.units=units;this.counterUnits=units===axisUnits.x?axisUnits.y:axisUnits.x;this.chartRect=chartRect;this.axisLength=chartRect[units.rectEnd]-chartRect[units.rectStart];this.gridOffset=chartRect[units.rectOffset];this.ticks=ticks;this.options=options;}function createGridAndLabels(gridGroup,labelGroup,useForeignObject,chartOptions,eventEmitter){var axisOptions=chartOptions['axis'+this.units.pos.toUpperCase()];var projectedValues=this.ticks.map(this.projectValue.bind(this));var labelValues=this.ticks.map(axisOptions.labelInterpolationFnc);projectedValues.forEach(function(projectedValue,index){var labelOffset={x:0,y:0};// TODO: Find better solution for solving this problem
// Calculate how much space we have available for the label
var labelLength;if(projectedValues[index+1]){// If we still have one label ahead, we can calculate the distance to the next tick / label
labelLength=projectedValues[index+1]-projectedValue;}else {// If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to
// on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will
// still be visible inside of the chart padding.
labelLength=Math.max(this.axisLength-projectedValue,30);}// Skip grid lines and labels where interpolated label values are falsey (execpt for 0)
if(Chartist.isFalseyButZero(labelValues[index])&&labelValues[index]!==''){return;}// Transform to global coordinates using the chartRect
// We also need to set the label offset for the createLabel function
if(this.units.pos==='x'){projectedValue=this.chartRect.x1+projectedValue;labelOffset.x=chartOptions.axisX.labelOffset.x;// If the labels should be positioned in start position (top side for vertical axis) we need to set a
// different offset as for positioned with end (bottom)
if(chartOptions.axisX.position==='start'){labelOffset.y=this.chartRect.padding.top+chartOptions.axisX.labelOffset.y+(useForeignObject?5:20);}else {labelOffset.y=this.chartRect.y1+chartOptions.axisX.labelOffset.y+(useForeignObject?5:20);}}else {projectedValue=this.chartRect.y1-projectedValue;labelOffset.y=chartOptions.axisY.labelOffset.y-(useForeignObject?labelLength:0);// If the labels should be positioned in start position (left side for horizontal axis) we need to set a
// different offset as for positioned with end (right side)
if(chartOptions.axisY.position==='start'){labelOffset.x=useForeignObject?this.chartRect.padding.left+chartOptions.axisY.labelOffset.x:this.chartRect.x1-10;}else {labelOffset.x=this.chartRect.x2+chartOptions.axisY.labelOffset.x+10;}}if(axisOptions.showGrid){Chartist.createGrid(projectedValue,index,this,this.gridOffset,this.chartRect[this.counterUnits.len](),gridGroup,[chartOptions.classNames.grid,chartOptions.classNames[this.units.dir]],eventEmitter);}if(axisOptions.showLabel){Chartist.createLabel(projectedValue,labelLength,index,labelValues,this,axisOptions.offset,labelOffset,labelGroup,[chartOptions.classNames.label,chartOptions.classNames[this.units.dir],axisOptions.position==='start'?chartOptions.classNames[axisOptions.position]:chartOptions.classNames['end']],useForeignObject,eventEmitter);}}.bind(this));}Chartist.Axis=Chartist.Class.extend({constructor:Axis,createGridAndLabels:createGridAndLabels,projectValue:function(value,index,data){throw new Error('Base axis can\'t be instantiated!');}});Chartist.Axis.units=axisUnits;})(this||commonjsGlobal,Chartist);/**
* The auto scale axis uses standard linear scale projection of values along an axis. It uses order of magnitude to find a scale automatically and evaluates the available space in order to find the perfect amount of ticks for your chart.
* **Options**
* The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
* ```javascript
* var options = {
* // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
* high: 100,
* // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
* low: 0,
* // This option will be used when finding the right scale division settings. The amount of ticks on the scale will be determined so that as many ticks as possible will be displayed, while not violating this minimum required space (in pixel).
* scaleMinSpace: 20,
* // Can be set to true or false. If set to true, the scale will be generated with whole numbers only.
* onlyInteger: true,
* // The reference value can be used to make sure that this value will always be on the chart. This is especially useful on bipolar charts where the bipolar center always needs to be part of the chart.
* referenceValue: 5
* };
* ```
3 years ago
*
* @module Chartist.AutoScaleAxis
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;function AutoScaleAxis(axisUnit,data,chartRect,options){// Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options
var highLow=options.highLow||Chartist.getHighLow(data,options,axisUnit.pos);this.bounds=Chartist.getBounds(chartRect[axisUnit.rectEnd]-chartRect[axisUnit.rectStart],highLow,options.scaleMinSpace||20,options.onlyInteger);this.range={min:this.bounds.min,max:this.bounds.max};Chartist.AutoScaleAxis.super.constructor.call(this,axisUnit,chartRect,this.bounds.values,options);}function projectValue(value){return this.axisLength*(+Chartist.getMultiValue(value,this.units.pos)-this.bounds.min)/this.bounds.range;}Chartist.AutoScaleAxis=Chartist.Axis.extend({constructor:AutoScaleAxis,projectValue:projectValue});})(this||commonjsGlobal,Chartist);/**
* The fixed scale axis uses standard linear projection of values along an axis. It makes use of a divisor option to divide the range provided from the minimum and maximum value or the options high and low that will override the computed minimum and maximum.
* **Options**
* The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
* ```javascript
* var options = {
* // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
* high: 100,
* // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
* low: 0,
* // If specified then the value range determined from minimum to maximum (or low and high) will be divided by this number and ticks will be generated at those division points. The default divisor is 1.
* divisor: 4,
* // If ticks is explicitly set, then the axis will not compute the ticks with the divisor, but directly use the data in ticks to determine at what points on the axis a tick need to be generated.
* ticks: [1, 10, 20, 30]
* };
* ```
3 years ago
*
* @module Chartist.FixedScaleAxis
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;function FixedScaleAxis(axisUnit,data,chartRect,options){var highLow=options.highLow||Chartist.getHighLow(data,options,axisUnit.pos);this.divisor=options.divisor||1;this.ticks=options.ticks||Chartist.times(this.divisor).map(function(value,index){return highLow.low+(highLow.high-highLow.low)/this.divisor*index;}.bind(this));this.ticks.sort(function(a,b){return a-b;});this.range={min:highLow.low,max:highLow.high};Chartist.FixedScaleAxis.super.constructor.call(this,axisUnit,chartRect,this.ticks,options);this.stepLength=this.axisLength/this.divisor;}function projectValue(value){return this.axisLength*(+Chartist.getMultiValue(value,this.units.pos)-this.range.min)/(this.range.max-this.range.min);}Chartist.FixedScaleAxis=Chartist.Axis.extend({constructor:FixedScaleAxis,projectValue:projectValue});})(this||commonjsGlobal,Chartist);/**
* The step axis for step based charts like bar chart or step based line charts. It uses a fixed amount of ticks that will be equally distributed across the whole axis length. The projection is done using the index of the data value rather than the value itself and therefore it's only useful for distribution purpose.
* **Options**
* The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
* ```javascript
* var options = {
* // Ticks to be used to distribute across the axis length. As this axis type relies on the index of the value rather than the value, arbitrary data that can be converted to a string can be used as ticks.
* ticks: ['One', 'Two', 'Three'],
* // If set to true the full width will be used to distribute the values where the last value will be at the maximum of the axis length. If false the spaces between the ticks will be evenly distributed instead.
* stretch: true
* };
* ```
3 years ago
*
* @module Chartist.StepAxis
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;function StepAxis(axisUnit,data,chartRect,options){Chartist.StepAxis.super.constructor.call(this,axisUnit,chartRect,options.ticks,options);var calc=Math.max(1,options.ticks.length-(options.stretch?1:0));this.stepLength=this.axisLength/calc;}function projectValue(value,index){return this.stepLength*index;}Chartist.StepAxis=Chartist.Axis.extend({constructor:StepAxis,projectValue:projectValue});})(this||commonjsGlobal,Chartist);/**
* The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global `Chartist` namespace where you find the `Line` function as a main entry point.
3 years ago
*
* For examples on how to use the line chart please check the examples of the `Chartist.Line` method.
3 years ago
*
* @module Chartist.Line
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;/**
* Default options in line charts. Expand the code view to see a detailed list of options with comments.
*
* @memberof Chartist.Line
*/var defaultOptions={// Options for X-Axis
axisX:{// The offset of the labels to the chart area
offset:30,// Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
position:'end',// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset:{x:0,y:0},// If labels should be shown or not
showLabel:true,// If the axis grid should be drawn or not
showGrid:true,// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc:Chartist.noop,// Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
type:undefined},// Options for Y-Axis
axisY:{// The offset of the labels to the chart area
offset:40,// Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
position:'start',// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset:{x:0,y:0},// If labels should be shown or not
showLabel:true,// If the axis grid should be drawn or not
showGrid:true,// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc:Chartist.noop,// Set the axis type to be used to project values on this axis. If not defined, Chartist.AutoScaleAxis will be used for the Y-Axis, where the high and low options will be set to the global high and low options. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
type:undefined,// This value specifies the minimum height in pixel of the scale steps
scaleMinSpace:20,// Use only integer values (whole numbers) for the scale steps
onlyInteger:false},// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width:undefined,// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height:undefined,// If the line should be drawn or not
showLine:true,// If dots should be drawn or not
showPoint:true,// If the line chart should draw an area
showArea:false,// The base for the area chart that will be used to close the area shape (is normally 0)
areaBase:0,// Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description.
lineSmooth:true,// If the line chart should add a background fill to the .ct-grids group.
showGridBackground:false,// Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
low:undefined,// Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
high:undefined,// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding:{top:15,right:15,bottom:5,left:10},// When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler.
fullWidth:false,// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData:false,// Override the class names that get used to generate the SVG structure of the chart
classNames:{chart:'ct-chart-line',label:'ct-label',labelGroup:'ct-labels',series:'ct-series',line:'ct-line',point:'ct-point',area:'ct-area',grid:'ct-grid',gridGroup:'ct-grids',gridBackground:'ct-grid-background',vertical:'ct-vertical',horizontal:'ct-horizontal',start:'ct-start',end:'ct-end'}};/**
* Creates a new chart
*
*/function createChart(options){var data=Chartist.normalizeData(this.data,options.reverseData,true);// Create new svg object
this.svg=Chartist.createSvg(this.container,options.width,options.height,options.classNames.chart);// Create groups for labels, grid and series
var gridGroup=this.svg.elem('g').addClass(options.classNames.gridGroup);var seriesGroup=this.svg.elem('g');var labelGroup=this.svg.elem('g').addClass(options.classNames.labelGroup);var chartRect=Chartist.createChartRect(this.svg,options,defaultOptions.padding);var axisX,axisY;if(options.axisX.type===undefined){axisX=new Chartist.StepAxis(Chartist.Axis.units.x,data.normalized.series,chartRect,Chartist.extend({},options.axisX,{ticks:data.normalized.labels,stretch:options.fullWidth}));}else {axisX=options.axisX.type.call(Chartist,Chartist.Axis.units.x,data.normalized.series,chartRect,options.axisX);}if(options.axisY.type===undefined){axisY=new Chartist.AutoScaleAxis(Chartist.Axis.units.y,data.normalized.series,chartRect,Chartist.extend({},options.axisY,{high:Chartist.isNumeric(options.high)?options.high:options.axisY.high,low:Chartist.isNumeric(options.low)?options.low:options.axisY.low}));}else {axisY=options.axisY.type.call(Chartist,Chartist.Axis.units.y,data.normalized.series,chartRect,options.axisY);}axisX.createGridAndLabels(gridGroup,labelGroup,this.supportsForeignObject,options,this.eventEmitter);axisY.createGridAndLabels(gridGroup,labelGroup,this.supportsForeignObject,options,this.eventEmitter);if(options.showGridBackground){Chartist.createGridBackground(gridGroup,chartRect,options.classNames.gridBackground,this.eventEmitter);}// Draw the series
data.raw.series.forEach(function(series,seriesIndex){var seriesElement=seriesGroup.elem('g');// Write attributes to series group element. If series name or meta is undefined the attributes will not be written
seriesElement.attr({'ct:series-name':series.name,'ct:meta':Chartist.serialize(series.meta)});// Use series class from series data or if not set generate one
seriesElement.addClass([options.classNames.series,series.className||options.classNames.series+'-'+Chartist.alphaNumerate(seriesIndex)].join(' '));var pathCoordinates=[],pathData=[];data.normalized.series[seriesIndex].forEach(function(value,valueIndex){var p={x:chartRect.x1+axisX.projectValue(value,valueIndex,data.normalized.series[seriesIndex]),y:chartRect.y1-axisY.projectValue(value,valueIndex,data.normalized.series[seriesIndex])};pathCoordinates.push(p.x,p.y);pathData.push({value:value,valueIndex:valueIndex,meta:Chartist.getMetaData(series,valueIndex)});}.bind(this));var seriesOptions={lineSmooth:Chartist.getSeriesOption(series,options,'lineSmooth'),showPoint:Chartist.getSeriesOption(series,options,'showPoint'),showLine:Chartist.getSeriesOption(series,options,'showLine'),showArea:Chartist.getSeriesOption(series,options,'showArea'),areaBase:Chartist.getSeriesOption(series,options,'areaBase')};var smoothing=typeof seriesOptions.lineSmooth==='function'?seriesOptions.lineSmooth:seriesOptions.lineSmooth?Chartist.Interpolation.monotoneCubic():Chartist.Interpolation.none();// Interpolating path where pathData will be used to annotate each path element so we can trace back the original
// index, value and meta data
var path=smoothing(pathCoordinates,pathData);// If we should show points we need to create them now to avoid secondary loop
// Points are drawn from the pathElements returned by the interpolation function
// Small offset for Firefox to render squares correctly
if(seriesOptions.showPoint){path.pathElements.forEach(function(pathElement){var point=seriesElement.elem('line',{x1:pathElement.x,y1:pathElement.y,x2:pathElement.x+0.01,y2:pathElement.y},options.classNames.point).attr({'ct:value':[pathElement.data.value.x,pathElement.data.value.y].filter(Chartist.isNumeric).join(','),'ct:meta':Chartist.serialize(pathElement.data.meta)});this.eventEmitter.emit('draw',{type:'point',value:pathElement.data.value,index:pathElement.data.valueIndex,meta:pathElement.data.meta,series:series,seriesIndex:seriesIndex,axisX:axisX,axisY:axisY,group:seriesElement,element:point,x:pathElement.x,y:pathElement.y});}.bind(this));}if(seriesOptions.showLine){var line=seriesElement.elem('path',{d:path.stringify()},options.classNames.line,true);this.eventEmitter.emit('draw',{type:'line',values:data.normalized.series[seriesIndex],path:path.clone(),chartRect:chartRect,index:seriesIndex,series:series,seriesIndex:seriesIndex,seriesMeta:series.meta,axisX:axisX,axisY:axisY,group:seriesElement,element:line});}// Area currently only works with axes that support a range!
if(seriesOptions.showArea&&axisY.range){// If areaBase is outside the chart area (< min or > max) we need to set it respectively so that
// the area is not drawn outside the chart area.
var areaBase=Math.max(Math.min(seriesOptions.areaBase,axisY.range.max),axisY.range.min);// We project the areaBase value into screen coordinates
var areaBaseProjected=chartRect.y1-axisY.projectValue(areaBase);// In order to form the area we'll first split the path by move commands so we can chunk it up into segments
path.splitByCommand('M').filter(function onlySolidSegments(pathSegment){// We filter only "solid" segments that contain more than one point. Otherwise there's no need for an area
return pathSegment.pathElements.length>1;}).map(function convertToArea(solidPathSegments){// Receiving the filtered solid path segments we can now convert those segments into fill areas
var firstElement=solidPathSegments.pathElements[0];var lastElement=solidPathSegments.pathElements[solidPathSegments.pathElements.length-1];// Cloning the solid path segment with closing option and removing the first move command from the clone
// We then insert a new move that should start at the area base and draw a straight line up or down
// at the end of the path we add an additional straight line to the projected area base value
// As the closing option is set our path will be automatically closed
return solidPathSegments.clone(true).position(0).remove(1).move(firstElement.x,areaBaseProjected).line(firstElement.x,firstElement.y).position(solidPathSegments.pathElements.length+1).line(lastElement.x,areaBaseProjected);}).forEach(function createArea(areaPath){// For each of our newly created area paths, we'll now create path elements by stringifying our path objects
// and adding the created DOM elements to the correct series group
var area=seriesElement.elem('path',{d:areaPath.stringify()},options.classNames.area,true);// Emit an event for each area that was drawn
this.eventEmitter.emit('draw',{type:'area',values:data.normalized.series[seriesIndex],path:areaPath.clone(),series:series,seriesIndex:seriesIndex,axisX:axisX,axisY:axisY,chartRect:chartRect,index:seriesIndex,group:seriesElement,element:area});}.bind(this));}}.bind(this));this.eventEmitter.emit('created',{bounds:axisY.bounds,chartRect:chartRect,axisX:axisX,axisY:axisY,svg:this.svg,options:options});}/**
* This method creates a new line chart.
*
* @memberof Chartist.Line
* @param {String|Node} query A selector query string or directly a DOM element
* @param {Object} data The data object that needs to consist of a labels and a series array
* @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
* @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
* @return {Object} An object which exposes the API for the created chart
*
* @example
* // Create a simple line chart
* var data = {
* // A labels array that can contain any sort of values
* labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
* // Our series array that contains series objects or in this case series data arrays
* series: [
* [5, 2, 4, 2, 0]
* ]
* };
*
* // As options we currently only set a static size of 300x200 px
* var options = {
* width: '300px',
* height: '200px'
* };
*
* // In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options
* new Chartist.Line('.ct-chart', data, options);
*
* @example
* // Use specific interpolation function with configuration from the Chartist.Interpolation module
*
* var chart = new Chartist.Line('.ct-chart', {
* labels: [1, 2, 3, 4, 5],
* series: [
* [1, 1, 8, 1, 7]
* ]
* }, {
* lineSmooth: Chartist.Interpolation.cardinal({
* tension: 0.2
* })
* });
*
* @example
* // Create a line chart with responsive options
*
* var data = {
* // A labels array that can contain any sort of values
* labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
* // Our series array that contains series objects or in this case series data arrays
* series: [
* [5, 2, 4, 2, 0]
* ]
* };
*
* // In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
* var responsiveOptions = [
* ['screen and (min-width: 641px) and (max-width: 1024px)', {
* showPoint: false,
* axisX: {
* labelInterpolationFnc: function(value) {
* // Will return Mon, Tue, Wed etc. on medium screens
* return value.slice(0, 3);
* }
* }
* }],
* ['screen and (max-width: 640px)', {
* showLine: false,
* axisX: {
* labelInterpolationFnc: function(value) {
* // Will return M, T, W etc. on small screens
* return value[0];
* }
* }
* }]
* ];
*
* new Chartist.Line('.ct-chart', data, null, responsiveOptions);
*
*/function Line(query,data,options,responsiveOptions){Chartist.Line.super.constructor.call(this,query,data,defaultOptions,Chartist.extend({},defaultOptions,options),responsiveOptions);}// Creating line chart type in Chartist namespace
Chartist.Line=Chartist.Base.extend({constructor:Line,createChart:createChart});})(this||commonjsGlobal,Chartist);/**
* The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts.
*
* @module Chartist.Bar
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;/**
* Default options in bar charts. Expand the code view to see a detailed list of options with comments.
*
* @memberof Chartist.Bar
*/var defaultOptions={// Options for X-Axis
axisX:{// The offset of the chart drawing area to the border of the container
offset:30,// Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
position:'end',// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset:{x:0,y:0},// If labels should be shown or not
showLabel:true,// If the axis grid should be drawn or not
showGrid:true,// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc:Chartist.noop,// This value specifies the minimum width in pixel of the scale steps
scaleMinSpace:30,// Use only integer values (whole numbers) for the scale steps
onlyInteger:false},// Options for Y-Axis
axisY:{// The offset of the chart drawing area to the border of the container
offset:40,// Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
position:'start',// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset:{x:0,y:0},// If labels should be shown or not
showLabel:true,// If the axis grid should be drawn or not
showGrid:true,// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc:Chartist.noop,// This value specifies the minimum height in pixel of the scale steps
scaleMinSpace:20,// Use only integer values (whole numbers) for the scale steps
onlyInteger:false},// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width:undefined,// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height:undefined,// Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
high:undefined,// Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
low:undefined,// Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale.
referenceValue:0,// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding:{top:15,right:15,bottom:5,left:10},// Specify the distance in pixel of bars in a group
seriesBarDistance:15,// If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options.
stackBars:false,// If set to 'overlap' this property will force the stacked bars to draw from the zero line.
// If set to 'accumulate' this property will form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect.
stackMode:'accumulate',// Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values.
horizontalBars:false,// If set to true then each bar will represent a series and the data array is expected to be a one dimensional array of data values rather than a series array of series. This is useful if the bar chart should represent a profile rather than some data over time.
distributeSeries:false,// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData:false,// If the bar chart should add a background fill to the .ct-grids group.
showGridBackground:false,// Override the class names that get used to generate the SVG structure of the chart
classNames:{chart:'ct-chart-bar',horizontalBars:'ct-horizontal-bars',label:'ct-label',labelGroup:'ct-labels',series:'ct-series',bar:'ct-bar',grid:'ct-grid',gridGroup:'ct-grids',gridBackground:'ct-grid-background',vertical:'ct-vertical',horizontal:'ct-horizontal',start:'ct-start',end:'ct-end'}};/**
* Creates a new chart
*
*/function createChart(options){var data;var highLow;if(options.distributeSeries){data=Chartist.normalizeData(this.data,options.reverseData,options.horizontalBars?'x':'y');data.normalized.series=data.normalized.series.map(function(value){return [value];});}else {data=Chartist.normalizeData(this.data,options.reverseData,options.horizontalBars?'x':'y');}// Create new svg element
this.svg=Chartist.createSvg(this.container,options.width,options.height,options.classNames.chart+(options.horizontalBars?' '+options.classNames.horizontalBars:''));// Drawing groups in correct order
var gridGroup=this.svg.elem('g').addClass(options.classNames.gridGroup);var seriesGroup=this.svg.elem('g');var labelGroup=this.svg.elem('g').addClass(options.classNames.labelGroup);if(options.stackBars&&data.normalized.series.length!==0){// If stacked bars we need to calculate the high low from stacked values from each series
var serialSums=Chartist.serialMap(data.normalized.series,function serialSums(){return Array.prototype.slice.call(arguments).map(function(value){return value;}).reduce(function(prev,curr){return {x:prev.x+(curr&&curr.x)||0,y:prev.y+(curr&&curr.y)||0};},{x:0,y:0});});highLow=Chartist.getHighLow([serialSums],options,options.horizontalBars?'x':'y');}else {highLow=Chartist.getHighLow(data.normalized.series,options,options.horizontalBars?'x':'y');}// Overrides of high / low from settings
highLow.high=+options.high||(options.high===0?0:highLow.high);highLow.low=+options.low||(options.low===0?0:highLow.low);var chartRect=Chartist.createChartRect(this.svg,options,defaultOptions.padding);var valueAxis,labelAxisTicks,labelAxis,axisX,axisY;// We need to set step count based on some options combinations
if(options.distributeSeries&&options.stackBars){// If distributed series are enabled and bars need to be stacked, we'll only have one bar and therefore should
// use only the first label for the step axis
labelAxisTicks=data.normalized.labels.slice(0,1);}else {// If distributed series are enabled but stacked bars aren't, we should use the series labels
// If we are drawing a regular bar chart with two dimensional series data, we just use the labels array
// as the bars are normalized
labelAxisTicks=data.normalized.labels;}// Set labelAxis and valueAxis based on the horizontalBars setting. This setting will flip the axes if necessary.
if(options.horizontalBars){if(options.axisX.type===undefined){valueAxis=axisX=new Chartist.AutoScaleAxis(Chartist.Axis.units.x,data.normalized.series,chartRect,Chartist.extend({},options.axisX,{highLow:highLow,referenceValue:0}));}else {valueAxis=axisX=options.axisX.type.call(Chartist,Chartist.Axis.units.x,data.normalized.series,chartRect,Chartist.extend({},options.axisX,{highLow:highLow,referenceValue:0}));}if(options.axisY.type===undefined){labelAxis=axisY=new Chartist.StepAxis(Chartist.Axis.units.y,data.normalized.series,chartRect,{ticks:labelAxisTicks});}else {labelAxis=axisY=options.axisY.type.call(Chartist,Chartist.Axis.units.y,data.normalized.series,chartRect,options.axisY);}}else {if(options.axisX.type===undefined){labelAxis=axisX=new Chartist.StepAxis(Chartist.Axis.units.x,data.normalized.series,chartRect,{ticks:labelAxisTicks});}else {labelAxis=axisX=options.axisX.type.call(Chartist,Chartist.Axis.units.x,data.normalized.series,chartRect,options.axisX);}if(options.axisY.type===undefined){valueAxis=axisY=new Chartist.AutoScaleAxis(Chartist.Axis.units.y,data.normalized.series,chartRect,Chartist.extend({},options.axisY,{highLow:highLow,referenceValue:0}));}else {valueAxis=axisY=options.axisY.type.call(Chartist,Chartist.Axis.units.y,data.normalized.series,chartRect,Chartist.extend({},options.axisY,{highLow:highLow,referenceValue:0}));}}// Projected 0 point
var zeroPoint=options.horizontalBars?chartRect.x1+valueAxis.projectValue(0):chartRect.y1-valueAxis.projectValue(0);// Used to track the screen coordinates of stacked bars
var stackedBarValues=[];labelAxis.createGridAndLabels(gridGroup,labelGroup,this.supportsForeignObject,options,this.eventEmitter);valueAxis.createGridAndLabels(gridGroup,labelGroup,this.supportsForeignObject,options,this.eventEmitter);if(options.showGridBackground){Chartist.createGridBackground(gridGroup,chartRect,options.classNames.gridBackground,this.eventEmitter);}// Draw the series
data.raw.series.forEach(function(series,seriesIndex){// Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc.
var biPol=seriesIndex-(data.raw.series.length-1)/2;// Half of the period width between vertical grid lines used to position bars
var periodHalfLength;// Current series SVG element
var seriesElement;// We need to set periodHalfLength based on some options combinations
if(options.distributeSeries&&!options.stackBars){// If distributed series are enabled but stacked bars aren't, we need to use the length of the normaizedData array
// which is the series count and divide by 2
periodHalfLength=labelAxis.axisLength/data.normalized.series.length/2;}else if(options.distributeSeries&&options.stackBars){// If distributed series and stacked bars are enabled we'll only get one bar so we should just divide the axis
// length by 2
periodHalfLength=labelAxis.axisLength/2;}else {// On regular bar charts we should just use the series length
periodHalfLength=labelAxis.axisLength/data.normalized.series[seriesIndex].length/2;}// Adding the series group to the series element
seriesElement=seriesGroup.elem('g');// Write attributes to series group element. If series name or meta is undefined the attributes will not be written
seriesElement.attr({'ct:series-name':series.name,'ct:meta':Chartist.serialize(series.meta)});// Use series class from series data or if not set generate one
seriesElement.addClass([options.classNames.series,series.className||options.classNames.series+'-'+Chartist.alphaNumerate(seriesIndex)].join(' '));data.normalized.series[seriesIndex].forEach(function(value,valueIndex){var projected,bar,previousStack,labelAxisValueIndex;// We need to set labelAxisValueIndex based on some options combinations
if(options.distributeSeries&&!options.stackBars){// If distributed series are enabled but stacked bars aren't, we can use the seriesIndex for later projection
// on the step axis for label positioning
labelAxisValueIndex=seriesIndex;}else if(options.distributeSeries&&options.stackBars){// If distributed series and stacked bars are enabled, we will only get one bar and therefore always use
// 0 for projection on the label step axis
labelAxisValueIndex=0;}else {// On regular bar charts we just use the value index to project on the label step axis
labelAxisValueIndex=valueIndex;}// We need to transform coordinates differently based on the chart layout
if(options.horizontalBars){projected={x:chartRect.x1+valueAxis.projectValue(value&&value.x?value.x:0,valueIndex,data.normalized.series[seriesIndex]),y:chartRect.y1-labelAxis.projectValue(value&&value.y?value.y:0,labelAxisValueIndex,data.normalized.series[seriesIndex])};}else {projected={x:chartRect.x1+labelAxis.projectValue(value&&value.x?value.x:0,labelAxisValueIndex,data.normalized.series[seriesIndex]),y:chartRect.y1-valueAxis.projectValue(value&&value.y?value.y:0,valueIndex,data.normalized.series[seriesIndex])};}// If the label axis is a step based axis we will offset the bar into the middle of between two steps using
// the periodHalfLength value. Also we do arrange the different series so that they align up to each other using
// the seriesBarDistance. If we don't have a step axis, the bar positions can be chosen freely so we should not
// add any automated positioning.
if(labelAxis instanceof Chartist.StepAxis){// Offset to center bar between grid lines, but only if the step axis is not stretched
if(!labelAxis.options.stretch){projected[labelAxis.units.pos]+=periodHalfLength*(options.horizontalBars?-1:1);}// Using bi-polar offset for multiple series if no stacked bars or series distribution is used
projected[labelAxis.units.pos]+=options.stackBars||options.distributeSeries?0:biPol*options.seriesBarDistance*(options.horizontalBars?-1:1);}// Enter value in stacked bar values used to remember previous screen value for stacking up bars
previousStack=stackedBarValues[valueIndex]||zeroPoint;stackedBarValues[valueIndex]=previousStack-(zeroPoint-projected[labelAxis.counterUnits.pos]);// Skip if value is undefined
if(value===undefined){return;}var positions={};positions[labelAxis.units.pos+'1']=projected[labelAxis.units.pos];positions[labelAxis.units.pos+'2']=projected[labelAxis.units.pos];if(options.stackBars&&(options.stackMode==='accumulate'||!options.stackMode)){// Stack mode: accumulate (default)
// If bars are stacked we use the stackedBarValues reference and otherwise base all bars off the zero line
// We want backwards compatibility, so the expected fallback without the 'stackMode' option
// to be the original behaviour (accumulate)
positions[labelAxis.counterUnits.pos+'1']=previousStack;positions[labelAxis.counterUnits.pos+'2']=stackedBarValues[valueIndex];}else {// Draw from the zero line normally
// This is also the same code for Stack mode: overlap
positions[labelAxis.counterUnits.pos+'1']=zeroPoint;positions[labelAxis.counterUnits.pos+'2']=projected[labelAxis.counterUnits.pos];}// Limit x and y so that they are within the chart rect
positions.x1=Math.min(Math.max(positions.x1,chartRect.x1),chartRect.x2);positions.x2=Math.min(Math.max(positions.x2,chartRect.x1),chartRect.x2);positions.y1=Math.min(Math.max(positions.y1,chartRect.y2),chartRect.y1);positions.y2=Math.min(Math.max(positions.y2,chartRect.y2),chartRect.y1);var metaData=Chartist.getMetaData(series,valueIndex);// Create bar element
bar=seriesElement.elem('line',positions,options.classNames.bar).attr({'ct:value':[value.x,value.y].filter(Chartist.isNumeric).join(','),'ct:meta':Chartist.serialize(metaData)});this.eventEmitter.emit('draw',Chartist.extend({type:'bar',value:value,index:valueIndex,meta:metaData,series:series,seriesIndex:seriesIndex,axisX:axisX,axisY:axisY,chartRect:chartRect,group:seriesElement,element:bar},positions));}.bind(this));}.bind(this));this.eventEmitter.emit('created',{bounds:valueAxis.bounds,chartRect:chartRect,axisX:axisX,axisY:axisY,svg:this.svg,options:options});}/**
* This method creates a new bar chart and returns API object that you can use for later changes.
*
* @memberof Chartist.Bar
* @param {String|Node} query A selector query string or directly a DOM element
* @param {Object} data The data object that needs to consist of a labels and a series array
* @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
* @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
* @return {Object} An object which exposes the API for the created chart
*
* @example
* // Create a simple bar chart
* var data = {
* labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
* series: [
* [5, 2, 4, 2, 0]
* ]
* };
*
* // In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object.
* new Chartist.Bar('.ct-chart', data);
*
* @example
* // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
* new Chartist.Bar('.ct-chart', {
* labels: [1, 2, 3, 4, 5, 6, 7],
* series: [
* [1, 3, 2, -5, -3, 1, -6],
* [-5, -2, -4, -1, 2, -3, 1]
* ]
* }, {
* seriesBarDistance: 12,
* low: -10,
* high: 10
* });
*
*/function Bar(query,data,options,responsiveOptions){Chartist.Bar.super.constructor.call(this,query,data,defaultOptions,Chartist.extend({},defaultOptions,options),responsiveOptions);}// Creating bar chart type in Chartist namespace
Chartist.Bar=Chartist.Base.extend({constructor:Bar,createChart:createChart});})(this||commonjsGlobal,Chartist);/**
* The pie chart module of Chartist that can be used to draw pie, donut or gauge charts
*
* @module Chartist.Pie
*/ /* global Chartist */(function(globalRoot,Chartist){var window=globalRoot.window;var document=globalRoot.document;/**
* Default options in line charts. Expand the code view to see a detailed list of options with comments.
*
* @memberof Chartist.Pie
*/var defaultOptions={// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width:undefined,// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height:undefined,// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding:5,// Override the class names that are used to generate the SVG structure of the chart
classNames:{chartPie:'ct-chart-pie',chartDonut:'ct-chart-donut',series:'ct-series',slicePie:'ct-slice-pie',sliceDonut:'ct-slice-donut',sliceDonutSolid:'ct-slice-donut-solid',label:'ct-label'},// The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise.
startAngle:0,// An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts.
total:undefined,// If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices.
donut:false,// If specified the donut segments will be drawn as shapes instead of strokes.
donutSolid:false,// Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future.
// This option can be set as number or string to specify a relative width (i.e. 100 or '30%').
donutWidth:60,// If a label should be shown or not
showLabel:true,// Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center.
labelOffset:0,// This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option.
labelPosition:'inside',// An interpolation function for the label value
labelInterpolationFnc:Chartist.noop,// Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center.
labelDirection:'neutral',// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData:false,// If true empty values will be ignored to avoid drawing unncessary slices and labels
ignoreEmptyValues:false};/**
* Determines SVG anchor position based on direction and center parameter
*
* @param center
* @param label
* @param direction
* @return {string}
*/function determineAnchorPosition(center,label,direction){var toTheRight=label.x>center.x;if(toTheRight&&direction==='explode'||!toTheRight&&direction==='implode'){return 'start';}else if(toTheRight&&direction==='implode'||!toTheRight&&direction==='explode'){return 'end';}else {return 'middle';}}/**
* Creates the pie chart
*
* @param options
*/function createChart(options){var data=Chartist.normalizeData(this.data);var seriesGroups=[],labelsGroup,chartRect,radius,labelRadius,totalDataSum,startAngle=options.startAngle;// Create SVG.js draw
this.svg=Chartist.createSvg(this.container,options.width,options.height,options.donut?options.classNames.chartDonut:options.classNames.chartPie);// Calculate charting rect
chartRect=Chartist.createChartRect(this.svg,options,defaultOptions.padding);// Get biggest circle radius possible within chartRect
radius=Math.min(chartRect.width()/2,chartRect.height()/2);// Calculate total of all series to get reference value or use total reference from optional options
totalDataSum=options.total||data.normalized.series.reduce(function(previousValue,currentValue){return previousValue+currentValue;},0);var donutWidth=Chartist.quantity(options.donutWidth);if(donutWidth.unit==='%'){donutWidth.value*=radius/100;}// If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside
// Unfortunately this is not possible with the current SVG Spec
// See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html
radius-=options.donut&&!options.donutSolid?donutWidth.value/2:0;// If labelPosition is set to `outside` or a donut chart is drawn then the label position is at the radius,
// if regular pie chart it's half of the radius
if(options.labelPosition==='outside'||options.donut&&!options.donutSolid){labelRadius=radius;}else if(options.labelPosition==='center'){// If labelPosition is center we start with 0 and will later wait for the labelOffset
labelRadius=0;}else if(options.donutSolid){labelRadius=radius-donutWidth.value/2;}else {// Default option is 'inside' where we use half the radius so the label will be placed in the center of the pie
// slice
labelRadius=radius/2;}// Add the offset to the labelRadius where a negative offset means closed to the center of the chart
labelRadius+=options.labelOffset;// Calculate end angle based on total sum and current data value and offset with padding
var center={x:chartRect.x1+chartRect.width()/2,y:chartRect.y2+chartRect.height()/2};// Check if there is only one non-zero value in the series array.
var hasSingleValInSeries=data.raw.series.filter(function(val){return val.hasOwnProperty('value')?val.value!==0:val!==0;}).length===1;// Creating the series groups
data.raw.series.forEach(function(series,index){seriesGroups[index]=this.svg.elem('g',null,null);}.bind(this));//if we need to show labels we create the label group now
if(options.showLabel){labelsGroup=this.svg.elem('g',null,null);}// Draw the series
// initialize series groups
data.raw.series.forEach(function(series,index){// If current value is zero and we are ignoring empty values then skip to next value
if(data.normalized.series[index]===0&&options.ignoreEmptyValues)return;// If the series is an object and contains a name or meta data we add a custom attribute
seriesGroups[index].attr({'ct:series-name':series.name});// Use series class from series data or if not set generate one
seriesGroups[index].addClass([options.classNames.series,series.className||options.classNames.series+'-'+Chartist.alphaNumerate(index)].join(' '));// If the whole dataset is 0 endAngle should be zero. Can't divide by 0.
var endAngle=totalDataSum>0?startAngle+data.normalized.series[index]/totalDataSum*360:0;// Use slight offset so there are no transparent hairline issues
var overlappigStartAngle=Math.max(0,startAngle-(index===0||hasSingleValInSeries?0:0.2));// If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle
// with Z and use 359.99 degrees
if(endAngle-overlappigStartAngle>=359.99){endAngle=overlappigStartAngle+359.99;}var start=Chartist.polarToCartesian(center.x,center.y,radius,overlappigStartAngle),end=Chartist.polarToCartesian(center.x,center.y,radius,endAngle);var innerStart,innerEnd,donutSolidRadius;// Create a new path element for the pie chart. If this isn't a donut chart we should close the path for a correct stroke
var path=new Chartist.Svg.Path(!options.donut||options.donutSolid).move(end.x,end.y).arc(radius,radius,0,endAngle-startAngle>180,0,start.x,start.y);// If regular pie chart (no donut) we add a line to the center of the circle for completing the pie
if(!options.donut){path.line(center.x,center.y);}else if(options.donutSolid){donutSolidRadius=radius-donutWidth.value;innerStart=Chartist.polarToCartesian(center.x,center.y,donutSolidRadius,startAngle-(index===0||hasSingleValInSeries?0:0.2));innerEnd=Chartist.polarToCartesian(center.x,center.y,donutSolidRadius,endAngle);path.line(innerStart.x,innerStart.y);path.arc(donutSolidRadius,donutSolidRadius,0,endAngle-startAngle>180,1,innerEnd.x,innerEnd.y);}// Create the SVG path
// If this is a donut chart we add the donut class, otherwise just a regular slice
var pathClassName=options.classNames.slicePie;if(options.donut){pathClassName=options.classNames.sliceDonut;if(options.donutSolid){pathClassName=options.classNames.sliceDonutSolid;}}var pathElement=seriesGroups[index].elem('path',{d:path.stringify()},pathClassName);// Adding the pie series value to the path
pathElement.attr({'ct:value':data.normalized.series[index],'ct:meta':Chartist.serialize(series.meta)});// If this is a donut, we add the stroke-width as style attribute
if(options.donut&&!options.donutSolid){pathElement._node.style.strokeWidth=donutWidth.value+'px';}// Fire off draw event
this.eventEmitter.emit('draw',{type:'slice',value:data.normalized.series[index],totalDataSum:totalDataSum,index:index,meta:series.meta,series:series,group:seriesGroups[index],element:pathElement,path:path.clone(),center:center,radius:radius,startAngle:startAngle,endAngle:endAngle});// If we need to show labels we need to add the label for this slice now
if(options.showLabel){var labelPosition;if(data.raw.series.length===1){// If we have only 1 series, we can position the label in the center of the pie
labelPosition={x:center.x,y:center.y};}else {// Position at the labelRadius distance from center and between start and end angle
labelPosition=Chartist.polarToCartesian(center.x,center.y,labelRadius,startAngle+(endAngle-startAngle)/2);}var rawValue;if(data.normalized.labels&&!Chartist.isFalseyButZero(data.normalized.labels[index])){rawValue=data.normalized.labels[index];}else {rawValue=data.normalized.series[index];}var interpolatedValue=options.labelInterpolationFnc(rawValue,index);if(interpolatedValue||interpolatedValue===0){var labelElement=labelsGroup.elem('text',{dx:labelPosition.x,dy:labelPosition.y,'text-anchor':determineAnchorPosition(center,labelPosition,options.labelDirection)},options.classNames.label).text(''+interpolatedValue);// Fire off draw event
this.eventEmitter.emit('draw',{type:'label',index:index,group:labelsGroup,element:labelElement,text:''+interpolatedValue,x:labelPosition.x,y:labelPosition.y});}}// Set next startAngle to current endAngle.
// (except for last slice)
startAngle=endAngle;}.bind(this));this.eventEmitter.emit('created',{chartRect:chartRect,svg:this.svg,options:options});}/**
* This method creates a new pie chart and returns an object that can be used to redraw the chart.
*
* @memberof Chartist.Pie
* @param {String|Node} query A selector query string or directly a DOM element
* @param {Object} data The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group.
* @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
* @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
* @return {Object} An object with a version and an update method to manually redraw the chart
*
* @example
* // Simple pie chart example with four series
* new Chartist.Pie('.ct-chart', {
* series: [10, 2, 4, 3]
* });
*
* @example
* // Drawing a donut chart
* new Chartist.Pie('.ct-chart', {
* series: [10, 2, 4, 3]
* }, {
* donut: true
* });
*
* @example
* // Using donut, startAngle and total to draw a gauge chart
* new Chartist.Pie('.ct-chart', {
* series: [20, 10, 30, 40]
* }, {
* donut: true,
* donutWidth: 20,
* startAngle: 270,
* total: 200
* });
*
* @example
* // Drawing a pie chart with padding and labels that are outside the pie
* new Chartist.Pie('.ct-chart', {
* series: [20, 10, 30, 40]
* }, {
* chartPadding: 30,
* labelOffset: 50,
* labelDirection: 'explode'
* });
*
* @example
* // Overriding the class names for individual series as well as a name and meta data.
* // The name will be written as ct:series-name attribute and the meta data will be serialized and written
* // to a ct:meta attribute.
* new Chartist.Pie('.ct-chart', {
* series: [{
* value: 20,
* name: 'Series 1',
* className: 'my-custom-class-one',
* meta: 'Meta One'
* }, {
* value: 10,
* name: 'Series 2',
* className: 'my-custom-class-two',
* meta: 'Meta Two'
* }, {
* value: 70,
* name: 'Series 3',
* className: 'my-custom-class-three',
* meta: 'Meta Three'
* }]
* });
*/function Pie(query,data,options,responsiveOptions){Chartist.Pie.super.constructor.call(this,query,data,defaultOptions,Chartist.extend({},defaultOptions,options),responsiveOptions);}// Creating pie chart type in Chartist namespace
Chartist.Pie=Chartist.Base.extend({constructor:Pie,createChart:createChart,determineAnchorPosition:determineAnchorPosition});})(this||commonjsGlobal,Chartist);return Chartist;});
});
3 years ago
var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _react2=_interopRequireDefault(react);var _propTypes2=_interopRequireDefault(propTypes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&(typeof call==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var ChartistGraph=function(_Component){_inherits(ChartistGraph,_Component);function ChartistGraph(){_classCallCheck(this,ChartistGraph);return _possibleConstructorReturn(this,(ChartistGraph.__proto__||Object.getPrototypeOf(ChartistGraph)).apply(this,arguments));}_createClass(ChartistGraph,[{key:'componentWillUnmount',value:function componentWillUnmount(){if(this.chartist){try{this.chartist.detach();}catch(err){throw new Error('Internal chartist error',err);}}}},{key:'componentDidMount',value:function componentDidMount(){this.updateChart(this.props);}},{key:'componentDidUpdate',value:function componentDidUpdate(){this.updateChart(this.props);}},{key:'updateChart',value:function updateChart(config){var Chartist=chartist;var type=config.type,data=config.data;var options=config.options||{};var responsiveOptions=config.responsiveOptions||[];var event=void 0;if(this.chartist){this.chartist.update(data,options,responsiveOptions);}else {this.chartist=new Chartist[type](this.chart,data,options,responsiveOptions);if(config.listener){for(event in config.listener){if(config.listener.hasOwnProperty(event)){this.chartist.on(event,config.listener[event]);}}}}return this.chartist;}},{key:'render',value:function render(){var _this2=this;var _props=this.props,className=_props.className,style=_props.style,children=_props.children,data=_props.data,type=_props.type;var childrenWithProps=children&&react.Children.map(children,function(child){return (0, react.cloneElement)(child,{type:type,data:data});});return _react2.default.createElement('div',{className:'ct-chart '+(className||''),ref:function ref(_ref){return _this2.chart=_ref;},style:style},childrenWithProps);}}]);return ChartistGraph;}(react.Component);ChartistGraph.propTypes={type:_propTypes2.default.oneOf(['Line','Bar','Pie']).isRequired,data:_propTypes2.default.object.isRequired,className:_propTypes2.default.string,options:_propTypes2.default.object,responsiveOptions:_propTypes2.default.array,style:_propTypes2.default.object};var _default$1=ChartistGraph;
3 years ago
const ChartHeader = He.div `
display: flex;
`;
const Legend = He.div `
margin-left: auto;
flex-shrink: 1;
`;
const ChartTypeSelector = He.div `
flex-shrink: 1;
flex-grow: 0;
`;
const Chart = He.div `
.ct-label {
color: var(--text-muted);
}
`;
const AccountVisualization = (props) => {
// TODO: Set the default mode based on the type of account selected
const [mode, setMode] = react.useState('balance');
console.log(props.dailyAccountBalanceMap);
const filteredAccounts = removeDuplicateAccounts(props.selectedAccounts);
const dateBuckets = makeBucketNames(props.interval, props.startDate, props.endDate);
const visualization = mode === 'balance' ? (react.createElement(BalanceVisualization, { dailyAccountBalanceMap: props.dailyAccountBalanceMap, allAccounts: props.allAccounts, accounts: filteredAccounts, dateBuckets: dateBuckets })) : (react.createElement(DeltaVisualization, { dailyAccountBalanceMap: props.dailyAccountBalanceMap, allAccounts: props.allAccounts, accounts: filteredAccounts, dateBuckets: dateBuckets, startDate: props.startDate, interval: props.interval }));
return (react.createElement(react.Fragment, null,
react.createElement(ChartHeader, null,
react.createElement(ChartTypeSelector, null,
react.createElement("select", { className: "dropdown", value: mode, onChange: (e) => {
setMode(e.target.value);
} },
react.createElement("option", { value: "balance" }, "Account Balance"),
react.createElement("option", { value: "pnl" }, "Profit and Loss"))),
react.createElement(Legend, null,
react.createElement("ul", { className: "ct-legend" }, filteredAccounts.map((account, i) => (react.createElement("li", { key: account, className: `ct-series-${i}` }, account)))))),
react.createElement(Chart, null, visualization)));
};
const BalanceVisualization = (props) => {
const data = {
labels: props.dateBuckets,
series: props.accounts.map((account) => makeBalanceData(props.dailyAccountBalanceMap, props.dateBuckets, account, props.allAccounts)),
};
const options = {
height: '300px',
width: '100%',
showArea: false,
showPoint: true,
};
return react.createElement(_default$1, { data: data, options: options, type: "Line" });
};
const DeltaVisualization = (props) => {
const data = {
labels: props.dateBuckets,
series: props.accounts.map((account) => makeDeltaData(props.dailyAccountBalanceMap, props.startDate
.clone()
.subtract(1, props.interval)
.format('YYYY-MM-DD'), props.dateBuckets, account, props.allAccounts)),
};
const options = {
height: '300px',
width: '100%',
};
return react.createElement(_default$1, { data: data, options: options, type: "Bar" });
};
3 years ago
const FlexContainer = He.div `
display: flex;
`;
const FlexShrink = He.div `
flex-grow: 0;
flex-shrink: 1;
`;
const FlexFloatRight = He.div `
margin-left: auto;
flex-shrink: 1;
`;
const FlexMainContent = He.div `
flex-basis: auto;
flex-grow: 1;
flex-shrink: 1;
`;
const DatePicker = He.input `
background: var(--background-modifier-form-field);
border: 1px solid var(--background-modifier-border);
color: var(--text-normal);
padding: 5px 14px;
border-radius: 4px;
height: 30px;
`;
const Button = (props) => {
const className = [props.className, props.selected ? 'mod-cta' : null]
.filter((n) => n)
.join(' ');
return (react.createElement("button", { className: className, onClick: props.action }, props.children));
};
3 years ago
const MarginSpan = He.span `
margin: 0 12px;
`;
const DateRangeSelector = (props) => (react.createElement(FlexContainer, null,
react.createElement(FlexFloatRight, { className: "ledger-interval-selectors" },
react.createElement(Button, { selected: props.interval === 'day', action: () => {
props.setInterval('day');
validateAndUpdateEndDate('day', props.startDate, props.endDate, props.setEndDate);
} }, "Daily"),
react.createElement(Button, { selected: props.interval === 'week', action: () => {
props.setInterval('week');
validateAndUpdateEndDate('week', props.startDate, props.endDate, props.setEndDate);
} }, "Weekly"),
react.createElement(Button, { selected: props.interval === 'month', action: () => {
props.setInterval('month');
validateAndUpdateEndDate('month', props.startDate, props.endDate, props.setEndDate);
} }, "Monthly")),
react.createElement(FlexShrink, { className: "ledger-daterange-selectors" },
react.createElement(DatePicker, { type: "date", placeholder: "Start", value: props.startDate.format('YYYY-MM-DD'), onChange: (e) => {
const newDate = window.moment(e.target.value);
props.setStartDate(newDate);
if (newDate.isAfter(props.endDate)) {
props.setEndDate(newDate);
}
else {
validateAndUpdateEndDate(props.interval, newDate, props.endDate, props.setEndDate);
}
} }),
react.createElement(MarginSpan, null, "\u279C"),
react.createElement(DatePicker, { type: "date", placeholder: "End", value: props.endDate.format('YYYY-MM-DD'), max: window.moment().format('YYYY-MM-DD'), onChange: (e) => {
const newDate = window.moment(e.target.value);
props.setEndDate(newDate.clone());
if (newDate.isBefore(props.startDate)) {
props.setStartDate(newDate);
}
else {
validateAndUpdateStartDate(props.interval, props.startDate, newDate, props.setStartDate);
}
} }))));
const validateAndUpdateStartDate = (interval, startDate, endDate, setStartDate) => {
if (endDate.diff(startDate, interval) > 15) {
new obsidian.Notice('Exceeded maximum time window. Adjusting start date.');
setStartDate(endDate.subtract(15, interval));
}
};
const validateAndUpdateEndDate = (interval, startDate, endDate, setEndDate) => {
if (endDate.diff(startDate, interval) > 15) {
new obsidian.Notice('Exceeded maximum time window. Adjusting end date.');
setEndDate(startDate.clone().add(15, interval));
}
};
3 years ago
const Chart$1 = He.div `
.ct-label {
color: var(--text-muted);
}
`;
const NetWorthVisualization = (props) => {
const dateBuckets = makeBucketNames(props.interval, props.startDate, props.endDate);
const data = {
labels: dateBuckets,
series: [
makeNetWorthData(props.dailyAccountBalanceMap, dateBuckets, props.settings),
],
};
const options = {
height: '300px',
width: '100%',
showArea: false,
showPoint: true,
};
const type = 'Line';
return (react.createElement(react.Fragment, null,
react.createElement("h2", null, "Net Worth"),
react.createElement("i", null, "Assets minus liabilities"),
react.createElement(Chart$1, null,
react.createElement(_default$1, { data: data, options: options, type: type }))));
};
3 years ago
const ErrorDiv = He.div `
color: var(--text-error);
background: var(--background-secondary);
padding: 10px;
margin: 10px 10px 10px 0;
cursor: pointer;
`;
const ErrorDetailsDiv = He.div `
background: var(--background-primary-alt);
padding: 20px;
margin: 10px;
`;
const ParseErrors = (props) => (react.createElement("div", null, props.txCache.parsingErrors.map((error, i) => (react.createElement(ErrorDetail, { key: i, error: error })))));
const ErrorDetail = (props) => {
const [expanded, setExpanded] = react.useState(false);
const expandedDetails = 'transaction' in props.error ? (react.createElement(react.Fragment, null,
react.createElement("p", null, "The erroneous transaction:"),
react.createElement("pre", null, props.error.transaction.block
? props.error.transaction.block.block
: `${props.error.transaction.value.date} ${props.error.transaction.value.payee}`))) : (react.createElement(react.Fragment, null,
react.createElement("p", null, "The erroneous transaction:"),
react.createElement("pre", null, props.error.block.block)));
return (react.createElement(ErrorDiv, { onClick: () => {
setExpanded(!expanded);
} },
"Parsing Error: ",
props.error.message,
expanded ? react.createElement(ErrorDetailsDiv, null, expandedDetails) : null));
};
3 years ago
var reactTable_production_min = createCommonjsModule(function (module, exports) {
!function(e,t){t(exports,react);}(commonjsGlobal,function(e,t){function n(e,t,n,o,r,i,u){try{var l=e[i](u),s=l.value;}catch(e){return void n(e);}l.done?t(s):Promise.resolve(s).then(o,r);}function o(e){return function(){var t=this,o=arguments;return new Promise(function(r,i){var u=e.apply(t,o);function l(e){n(u,r,i,l,s,"next",e);}function s(e){n(u,r,i,l,s,"throw",e);}l(void 0);});};}function r(){return (r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);}return e;}).apply(this,arguments);}function i(e,t){if(null==e)return {};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(r[n]=e[n]);return r;}function u(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.");}return ("string"===t?String:Number)(e);}(e,"string");return "symbol"==typeof t?t:String(t);}t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var l={init:"init"},s=function(e){var t=e.value;return void 0===t?"":t;},a=function(){return t.createElement(t.Fragment,null," ");},c={Cell:s,width:150,minWidth:0,maxWidth:Number.MAX_SAFE_INTEGER};function d(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.reduce(function(e,t){var n=t.style,o=t.className;return e=r({},e,{},i(t,["style","className"])),n&&(e.style=e.style?r({},e.style||{},{},n||{}):n),o&&(e.className=e.className?e.className+" "+o:o),""===e.className&&delete e.className,e;},{});}var f=function(e,t){return void 0===t&&(t={}),function(n){return void 0===n&&(n={}),[].concat(e,[n]).reduce(function(e,o){return function e(t,n,o){return "function"==typeof n?e({},n(t,o)):Array.isArray(n)?d.apply(void 0,[t].concat(n)):d(t,n);}(e,o,r({},t,{userProps:n}));},{});};},p=function(e,t,n,o){return void 0===n&&(n={}),e.reduce(function(e,t){return t(e,n);},t);},g=function(e,t,n){return void 0===n&&(n={}),e.forEach(function(e){e(t,n);});};function v(e,t,n,o){e.findIndex(function(e){return e.pluginName===n;});t.forEach(function(t){e.findIndex(function(e){return e.pluginName===t;});});}function m(e,t){return "function"==typeof e?e(t):e;}function h(e){var n=t.useRef();return n.current=e,t.useCallback(function(){return n.current;},[]);}var y="undefined"!=typeof document?t.useLayoutEffect:t.useEffect;function w(e,n){var o=t.useRef(!1);y(function(){o.current&&e(),o.current=!0;},n);}function R(e,t,n){return void 0===n&&(n={}),function(o,i){void 0===i&&(i={});var u="string"==typeof o?t[o]:o;if(void 0===u)throw console.info(t),new Error("Renderer Error ☝️");return b(u,r({},e,{column:t},n,{},i));};}function b(e,n){return function(e){return "function"==typeof e&&(t=Object.getPrototypeOf(e)).prototype&&t.prototype.isReactComponent;var t;}(o=e)||"function"==typeof o||function(e){return "object"==typeof e&&"symbol"==typeof e.$$typeof&&["react.memo","react.forward_ref"].includes(e.$$typeof.description);}(o)?t.createElement(e,n):e;var o;}function S(e,t,n){return void 0===n&&(n=0),e.map(function(e){return x(e=r({},e,{parent:t,depth:n})),e.columns&&(e.columns=S(e.columns,e,n+1)),e;});}function C(e){return G(e,"columns");}function x(e){var t=e.id,n=e.accessor,o=e.Header;if("string"==typeof n){t=t||n;var r=n.split(".");n=function(e){return function(e,t,n){if(!t)return e;var o,r="function"==typeof t?t:JSON.stringify(t),i=E.get(r)||function(){var e=function(e){return function e(t,n){void 0===n&&(n=[]);if(Array.isArray(t))for(var o=0;o<t.length;o+=1)e(t[o],n);else n.push(t);return n;}(e).map(function(e){return String(e).replace(".","_");}).join(".").replace(W,".").replace(O,"").split(".");}(t);return E.set(r,e),e;}();try{o=i.reduce(function(e,t){return e[t];},e);}catch(e){}return void 0!==o?o:n;}(e,r);};}if(!t&&"string"==typeof o&&o&&(t=o),!t&&e.columns)throw console.error(e),new Error('A column ID (or unique "Header" value) is required!');if(!t)throw console.error(e),new Error("A column ID (or
});
3 years ago
var reactTable_development = createCommonjsModule(function (module, exports) {
(function(global,factory){factory(exports,react);})(commonjsGlobal,function(exports,React){React=React&&Object.prototype.hasOwnProperty.call(React,'default')?React['default']:React;function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else {Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return {};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function _toPrimitive(input,hint){if(typeof input!=="object"||input===null)return input;var prim=input[Symbol.toPrimitive];if(prim!==undefined){var res=prim.call(input,hint||"default");if(typeof res!=="object")return res;throw new TypeError("@@toPrimitive must return a primitive value.");}return (hint==="string"?String:Number)(input);}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return typeof key==="symbol"?key:String(key);}var renderErr='Renderer Error ☝️';var actions={init:'init'};var defaultRenderer=function defaultRenderer(_ref){var _ref$value=_ref.value,value=_ref$value===void 0?'':_ref$value;return value;};var emptyRenderer=function emptyRenderer(){return React.createElement(React.Fragment,null,"\xA0");};var defaultColumn={Cell:defaultRenderer,width:150,minWidth:0,maxWidth:Number.MAX_SAFE_INTEGER};function mergeProps(){for(var _len=arguments.length,propList=new Array(_len),_key=0;_key<_len;_key++){propList[_key]=arguments[_key];}return propList.reduce(function(props,next){var style=next.style,className=next.className,rest=_objectWithoutPropertiesLoose(next,["style","className"]);props=_extends({},props,{},rest);if(style){props.style=props.style?_extends({},props.style||{},{},style||{}):style;}if(className){props.className=props.className?props.className+' '+className:className;}if(props.className===''){delete props.className;}return props;},{});}function handlePropGetter(prevProps,userProps,meta){// Handle a lambda, pass it the previous props
if(typeof userProps==='function'){return handlePropGetter({},userProps(prevProps,meta));}// Handle an array, merge each item as separate props
if(Array.isArray(userProps)){return mergeProps.apply(void 0,[prevProps].concat(userProps));}// Handle an object by default, merge the two objects
return mergeProps(prevProps,userProps);}var makePropGetter=function makePropGetter(hooks,meta){if(meta===void 0){meta={};}return function(userProps){if(userProps===void 0){userProps={};}return [].concat(hooks,[userProps]).reduce(function(prev,next){return handlePropGetter(prev,next,_extends({},meta,{userProps:userProps}));},{});};};var reduceHooks=function reduceHooks(hooks,initial,meta,allowUndefined){if(meta===void 0){meta={};}return hooks.reduce(function(prev,next){var nextValue=next(prev,meta);{if(!allowUndefined&&typeof nextValue==='undefined'){console.info(next);throw new Error('React Table: A reducer hook ☝️ just returned undefined! This is not allowed.');}}return nextValue;},initial);};var loopHooks=function loopHooks(hooks,context,meta){if(meta===void 0){meta={};}return hooks.forEach(function(hook){var nextValue=hook(context,meta);{if(typeof nextValue!=='undefined'){console.info(hook,nextValue);throw new Error('React Table: A loop-type hook ☝️ just returned a value! This is not allowed.');}}});};function ensurePluginOrder(plugins,befores,pluginName,afters){if(afters){throw new Error("Defining plugins in the \"after\" section of ensurePluginOrder is no longer supported (see plugin "+pluginName+")");}var pluginIndex=plugins.findIndex(function(plugin){return plugin.pluginName===pluginName;});if(pluginIndex===-1){{throw new Error("The plugin \""+pluginName+"\" was not found in the plugin list!\nThis usually means you need to need to name your plugin hook by setting the 'pluginName' property of the hook function, eg:\n\n "+pluginName+".pluginName = '"+pluginName+"'\n");}}befores.forEach(function(before){var beforeIndex=plugins.findIndex(function(plugin){return plugin.pluginName===before;});if(beforeIndex>-1&&beforeIndex>pluginIndex){{throw new Error("React Table: The "+pluginName+" plugin hook must be placed after the "+before+" plugin hook!");}}});}function functionalUpdate(updater,old){return typeof updater==='function'?updater(old):updater;}function useGetLatest(obj){var ref=React.useRef();ref.current=obj;return React.useCallback(function(){return ref.current;},[]);}// SSR has issues with useLayoutEffect still, so use useEffect during SSR
var safeUseLayoutEffect=typeof document!=='undefined'?React.useLayoutEffect:React.useEffect;function useMountedLayoutEffect(fn,deps){var mountedRef=React.useRef(false);safeUseLayoutEffect(function(){if(mountedRef.current){fn();}mountedRef.current=true;// eslint-disable-next-line
},deps);}function useAsyncDebounce(defaultFn,defaultWait){if(defaultWait===void 0){defaultWait=0;}var debounceRef=React.useRef({});var getDefaultFn=useGetLatest(defaultFn);var getDefaultWait=useGetLatest(defaultWait);return React.useCallback(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee2(){var _len2,args,_key2,_args2=arguments;return regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:for(_len2=_args2.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=_args2[_key2];}if(!debounceRef.current.promise){debounceRef.current.promise=new Promise(function(resolve,reject){debounceRef.current.resolve=resolve;debounceRef.current.reject=reject;});}if(debounceRef.current.timeout){clearTimeout(debounceRef.current.timeout);}debounceRef.current.timeout=setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee(){return regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:delete debounceRef.current.timeout;_context.prev=1;_context.t0=debounceRef.current;_context.next=5;return getDefaultFn().apply(void 0,args);case 5:_context.t1=_context.sent;_context.t0.resolve.call(_context.t0,_context.t1);_context.next=12;break;case 9:_context.prev=9;_context.t2=_context["catch"](1);debounceRef.current.reject(_context.t2);case 12:_context.prev=12;delete debounceRef.current.promise;return _context.finish(12);case 15:case"end":return _context.stop();}}},_callee,null,[[1,9,12,15]]);})),getDefaultWait());return _context2.abrupt("return",debounceRef.current.promise);case 5:case"end":return _context2.stop();}}},_callee2);}));return function(){return _ref2.apply(this,arguments);};}(),[getDefaultFn,getDefaultWait]);}function makeRenderer(instance,column,meta){if(meta===void 0){meta={};}return function(type,userProps){if(userProps===void 0){userProps={};}var Comp=typeof type==='string'?column[type]:type;if(typeof Comp==='undefined'){console.info(column);throw new Error(renderErr);}return flexRender(Comp,_extends({},instance,{column:column},meta,{},userProps));};}function flexRender(Comp,props){return isReactComponent(Comp)?React.createElement(Comp,props):Comp;}function isReactComponent(component){return isClassComponent(component)||typeof component==='function'||isExoticComponent(component);}function isClassComponent(component){return typeof component==='function'&&function(){var proto=Object.getPrototypeOf(component);return proto.prototype&&proto.prototype.isReactComponent;}();}function isExoticComponent(component){return typeof component==='object'&&typeof component.$$typeof==='symbol'&&['react.memo','react.forward_ref'].includes(component.$$typeof.description);}function linkColumnStructure(columns,parent,depth){if(depth===void 0){depth=0;}return columns.map(function(column){column=_extends({},column,{parent:parent,depth:depth});assignColumnAccessor(column);if(column.columns){column.columns=linkColumnStructure(column.columns,column,depth+1);}return column;});}function flattenColumns(columns){return flattenBy(columns,'columns');}function assignColumnAccessor(column){// First check for string accessor
var id=column.id,accessor=column.accessor,Header=column.Header;if(typeof accessor==='string'){id=id||accessor;var accessorPath=accessor.split('.');accessor=function accessor(row){return getBy(row,accessorPath);};}if(!id&&typeof Header==='string'&&Header){id=Header;}if(!id&&column.columns){console.error(column);throw new Error('A column ID (or unique "Header" value) is required!');}if(!id){console.error(column);throw new Error('A column ID (or string accessor) is required!');}Object.assign(column,{id:id,accessor:accessor});return column;}function decorateColumn(column,userDefaultColumn){if(!userDefaultColumn){throw new Error();}Object.assign(column,_extends({// Make sure there is a fallback header, just in case
Header:emptyRenderer,Footer:emptyRenderer},defaultColumn,{},userDefaultColumn,{},column));Object.assign(column,{originalWidth:column.width});return column;}// Build the header groups from the bottom up
function makeHeaderGroups(allColumns,defaultColumn,additionalHeaderProperties){if(additionalHeaderProperties===void 0){additionalHeaderProperties=function additionalHeaderProperties(){return {};};}var headerGroups=[];var scanColumns=allColumns;var uid=0;var getUID=function getUID(){return uid++;};var _loop=function _loop(){// The header group we are creating
var headerGroup={headers:[]};// The parent columns we're going to scan next
var parentColumns=[];var hasParents=scanColumns.some(function(d){return d.parent;});// Scan each column for parents
scanColumns.forEach(function(column){// What is the latest (last) parent column?
var latestParentColumn=[].concat(parentColumns).reverse()[0];var newParent;if(hasParents){// If the column has a parent, add it if necessary
if(column.parent){newParent=_extends({},column.parent,{originalId:column.parent.id,id:column.parent.id+"_"+getUID(),headers:[column]},additionalHeaderProperties(column));}else {// If other columns have parents, we'll need to add a place holder if necessary
var originalId=column.id+"_placeholder";newParent=decorateColumn(_extends({originalId:originalId,id:column.id+"_placeholder_"+getUID(),placeholderOf:column,headers:[column]},additionalHeaderProperties(column)),defaultColumn);}// If the resulting parent columns are the same, just add
// the column and increment the header span
if(latestParentColumn&&latestParentColumn.originalId===newParent.originalId){latestParentColumn.headers.push(column);}else {parentColumns.push(newParent);}}headerGroup.headers.push(column);});headerGroups.push(headerGroup);// Start scanning the parent columns
scanColumns=parentColumns;};while(scanColumns.length){_loop();}return headerGroups.reverse();}var pathObjCache=new Map();function getBy(obj,path,def){if(!path){return obj;}var cacheKey=typeof path==='function'?path:JSON.stringify(path);var pathObj=pathObjCache.get(cacheKey)||function(){var pathObj=makePathArray(path);pathObjCache.set(cacheKey,pathObj);return pathObj;}();var val;try{val=pathObj.reduce(function(cursor,pathPart){return cursor[pathPart];},obj);}catch(e){// continue regardless of error
}return typeof val!=='undefined'?val:def;}function getFirstDefined(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}for(var i=0;i<args.length;i+=1){if(typeof args[i]!=='undefined'){return args[i];}}}function isFunction(a){if(typeof a==='function'){return a;}}function flattenBy(arr,key){var flat=[];var recurse=function recurse(arr){arr.forEach(function(d){if(!d[key]){flat.push(d);}else {recurse(d[key]);}});};recurse(arr);return flat;}function expandRows(rows,_ref){var manualExpandedKey=_ref.manualExpandedKey,expanded=_ref.expanded,_ref$expandSubRows=_ref.expandSubRows,expandSubRows=_ref$expandSubRows===void 0?true:_ref$expandSubRows;var expandedRows=[];var handleRow=function handleRow(row,addToExpandedRows){if(addToExpandedRows===void 0){addToExpandedRows=true;}row.isExpanded=row.original&&row.original[manualExpandedKey]||expanded[row.id];row.canExpand=row.subRows&&!!row.subRows.length;if(addToExpandedRows){expandedRows.push(row);}if(row.subRows&&row.subRows.length&&row.isExpanded){row.subRows.forEach(function(row){return handleRow(row,expandSubRows);});}};rows.forEach(function(row){return handleRow(row);});return expandedRows;}function getFilterMethod(filter,userFilterTypes,filterTypes){return isFunction(filter)||userFilterTypes[filter]||filterTypes[filter]||filterTypes.text;}function shouldAutoRemoveFilter(autoRemove,value,column){return autoRemove?autoRemove(value,column):typeof value==='undefined';}function unpreparedAccessWarning(){throw new Error('React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.');}var passiveSupported=null;function passiveEventSupported(){// memoize support to avoid adding multiple test events
if(typeof passiveSupported==='boolean')return passiveSupported;var supported=false;try{var options={get passive(){supported=true;return false;}};window.addEventListener('test',null,options);window.removeEventListener('test',null,options);}catch(err){supported=false;}passiveSupported=supported;return passiveSupported;}//
var reOpenBracket=/\[/g;var reCloseBracket=/\]/g;function makePathArray(obj){return flattenDeep(obj)// remove all periods in parts
.map(function(d){return String(d).replace('.','_');})// join parts using period
.join('.')// replace brackets with periods
.replace(reOpenBracket,'.').replace(reCloseBracket,'')// split it back out on periods
.split('.');}function flattenDeep(arr,newArr){if(newArr===void 0){newArr=[];}if(!Array.isArray(arr)){newArr.push(arr);}else {for(var i=0;i<arr.length;i+=1){flattenDeep(arr[i],newArr);}}return newArr;}var defaultGetTableProps=function defaultGetTableProps(props){return _extends({role:'table'},props);};var defaultGetTableBodyProps=function defaultGetTableBodyProps(props){return _extends({role:'rowgroup'},props);};var defaultGetHeaderProps=function defaultGetHeaderProps(props,_ref){var column=_ref.column;return _extends({key:"header_"+column.id,colSpan:column.totalVisibleHeaderCount,role:'columnheader'},props);};var defaultGetFooterProps=function defaultGetFooterProps(props,_ref2){var column=_ref2.column;return _extends({key:"footer_"+column.id,colSpan:column.totalVisibleHeaderCount},props);};var defaultGetHeaderGroupProps=function defaultGetHeaderGroupProps(props,_ref3){var index=_ref3.index;return _extends({key:"headerGroup_"+index,role:'row'},props);};var defaultGetFooterGroupProps=function defaultGetFooterGroupProps(props,_ref4){var index=_ref4.index;return _extends({key:"footerGroup_"+index},props);};var defaultGetRowProps=function defaultGetRowProps(props,_ref5){var row=_ref5.row;return _extends({key:"row_"+row.id,role:'row'},props);};var defaultGetCellProps=function defaultGetCellProps(props,_ref6){var cell=_ref6.cell;return _extends({key:"cell_"+cell.row.id+"_"+cell.column.id,role:'cell'},props);};function makeDefaultPluginHooks(){return {useOptions:[],stateReducers:[],useControlledState:[],columns:[],columnsDeps:[],allColumns:[],allColumnsDeps:[],accessValue:[],materializedColumns:[],materializedColumnsDeps:[],useInstanceAfterData:[],visibleColumns:[],visibleColumnsDeps:[],headerGroups:[],headerGroupsDeps:[],useInstanceBeforeDimensions:[],useInstance:[],prepareRow:[],getTableProps:[defaultGetTableProps],getTableBodyProps:[defaultGetTableBodyProps],getHeaderGroupProps:[defaultGetHeaderGroupProps],getFooterGroupProps:[defaultGetFooterGroupProps],getHeaderProps:[defaultGetHeaderProps],getFooterProps:[defaultGetFooterProps],getRowProps:[defaultGetRowProps],getCellProps:[defaultGetCellProps],useFinalInstance:[]};}actions.resetHiddenColumns='resetHiddenColumns';actions.toggleHideColumn='toggleHideColumn';actions.setHiddenColumns='setHiddenColumns';actions.toggleHideAllColumns='toggleHideAllColumns';var useColumnVisibility=function useColumnVisibility(hooks){hooks.getToggleHiddenProps=[defaultGetToggleHiddenProps];hooks.getToggleHideAllColumnsProps=[defaultGetToggleHideAllColumnsProps];hooks.stateReducers.push(reducer);hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions);hooks.headerGroupsDeps.push(function(deps,_ref){var instance=_ref.instance;return [].concat(deps,[instance.state.hiddenColumns]);});hooks.useInstance.push(useInstance);};useColumnVisibility.pluginName='useColumnVisibility';var defaultGetToggleHiddenProps=function defaultGetToggleHiddenProps(props,_ref2){var column=_ref2.column;return [props,{onChange:function onChange(e){column.toggleHidden(!e.target.checked);},style:{cursor:'pointer'},checked:column.isVisible,title:'Toggle Column Visible'}];};var defaultGetToggleHideAllColumnsProps=function defaultGetToggleHideAllColumnsProps(props,_ref3){var instance=_ref3.instance;return [props,{onChange:function onChange(e){instance.toggleHideAllColumns(!e.target.checked);},style:{cursor:'pointer'},checked:!instance.allColumnsHidden&&!instance.state.hiddenColumns.length,title:'Toggle All Columns Hidden',indeterminate:!instance.allColumnsHidden&&instance.state.hiddenColumns.length}];};function reducer(state,action,previousState,instance){if(action.type===actions.init){return _extends({hiddenColumns:[]},state);}if(action.type===actions.resetHiddenColumns){return _extends({},state,{hiddenColumns:instance.initialState.hiddenColumns||[]});}if(action.type===actions.toggleHideColumn){var should=typeof action.value!=='undefined'?action.value:!state.hiddenColumns.includes(action.columnId);var hiddenColumns=should?[].concat(state.hiddenColumns,[action.columnId]):state.hiddenColumns.filter(function(d){return d!==
props=applyDefaults(props);// Add core plugins
plugins=[useColumnVisibility].concat(plugins);// Create the table instance
var instanceRef=React.useRef({});// Create a getter for the instance (helps avoid a lot of potential memory leaks)
var getInstance=useGetLatest(instanceRef.current);// Assign the props, plugins and hooks to the instance
Object.assign(getInstance(),_extends({},props,{plugins:plugins,hooks:makeDefaultPluginHooks()}));// Allow plugins to register hooks as early as possible
plugins.filter(Boolean).forEach(function(plugin){plugin(getInstance().hooks);});// Consume all hooks and make a getter for them
var getHooks=useGetLatest(getInstance().hooks);getInstance().getHooks=getHooks;delete getInstance().hooks;// Allow useOptions hooks to modify the options coming into the table
Object.assign(getInstance(),reduceHooks(getHooks().useOptions,applyDefaults(props)));var _getInstance=getInstance(),data=_getInstance.data,userColumns=_getInstance.columns,initialState=_getInstance.initialState,defaultColumn=_getInstance.defaultColumn,getSubRows=_getInstance.getSubRows,getRowId=_getInstance.getRowId,stateReducer=_getInstance.stateReducer,useControlledState=_getInstance.useControlledState;// Setup user reducer ref
var getStateReducer=useGetLatest(stateReducer);// Build the reducer
var reducer=React.useCallback(function(state,action){// Detect invalid actions
if(!action.type){console.info({action:action});throw new Error('Unknown Action 👆');}// Reduce the state from all plugin reducers
return [].concat(getHooks().stateReducers,Array.isArray(getStateReducer())?getStateReducer():[getStateReducer()]).reduce(function(s,handler){return handler(s,action,state,getInstance())||s;},state);},[getHooks,getStateReducer,getInstance]);// Start the reducer
var _React$useReducer=React.useReducer(reducer,undefined,function(){return reducer(initialState,{type:actions.init});}),reducerState=_React$useReducer[0],dispatch=_React$useReducer[1];// Allow the user to control the final state with hooks
var state=reduceHooks([].concat(getHooks().useControlledState,[useControlledState]),reducerState,{instance:getInstance()});Object.assign(getInstance(),{state:state,dispatch:dispatch});// Decorate All the columns
var columns=React.useMemo(function(){return linkColumnStructure(reduceHooks(getHooks().columns,userColumns,{instance:getInstance()}));},[getHooks,getInstance,userColumns].concat(reduceHooks(getHooks().columnsDeps,[],{instance:getInstance()})));getInstance().columns=columns;// Get the flat list of all columns and allow hooks to decorate
// those columns (and trigger this memoization via deps)
var allColumns=React.useMemo(function(){return reduceHooks(getHooks().allColumns,flattenColumns(columns),{instance:getInstance()}).map(assignColumnAccessor);},[columns,getHooks,getInstance].concat(reduceHooks(getHooks().allColumnsDeps,[],{instance:getInstance()})));getInstance().allColumns=allColumns;// Access the row model using initial columns
var _React$useMemo=React.useMemo(function(){var rows=[];var flatRows=[];var rowsById={};var allColumnsQueue=[].concat(allColumns);while(allColumnsQueue.length){var column=allColumnsQueue.shift();accessRowsForColumn({data:data,rows:rows,flatRows:flatRows,rowsById:rowsById,column:column,getRowId:getRowId,getSubRows:getSubRows,accessValueHooks:getHooks().accessValue,getInstance:getInstance});}return [rows,flatRows,rowsById];},[allColumns,data,getRowId,getSubRows,getHooks,getInstance]),rows=_React$useMemo[0],flatRows=_React$useMemo[1],rowsById=_React$useMemo[2];Object.assign(getInstance(),{rows:rows,initialRows:[].concat(rows),flatRows:flatRows,rowsById:rowsById// materializedColumns,
});loopHooks(getHooks().useInstanceAfterData,getInstance());// Get the flat list of all columns AFTER the rows
// have been access, and allow hooks to decorate
// those columns (and trigger this memoization via deps)
var visibleColumns=React.useMemo(function(){return reduceHooks(getHooks().visibleColumns,allColumns,{instance:getInstance()}).map(function(d){return decorateColumn(d,defaultColumn);});},[getHooks,allColumns,getInstance,defaultColumn].concat(reduceHooks(getHooks().visibleColumnsDeps,[],{instance:getInstance()})));// Combine new visible columns with all columns
allColumns=React.useMemo(function(){var columns=[].concat(visibleColumns);allColumns.forEach(function(column){if(!columns.find(function(d){return d.id===column.id;})){columns.push(column);}});return columns;},[allColumns,visibleColumns]);getInstance().allColumns=allColumns;{var duplicateColumns=allColumns.filter(function(column,i){return allColumns.findIndex(function(d){return d.id===column.id;})!==i;});if(duplicateColumns.length){console.info(allColumns);throw new Error("Duplicate columns were found with ids: \""+duplicateColumns.map(function(d){return d.id;}).join(', ')+"\" in the columns array above");}}// Make the headerGroups
var headerGroups=React.useMemo(function(){return reduceHooks(getHooks().headerGroups,makeHeaderGroups(visibleColumns,defaultColumn),getInstance());},[getHooks,visibleColumns,defaultColumn,getInstance].concat(reduceHooks(getHooks().headerGroupsDeps,[],{instance:getInstance()})));getInstance().headerGroups=headerGroups;// Get the first level of headers
var headers=React.useMemo(function(){return headerGroups.length?headerGroups[0].headers:[];},[headerGroups]);getInstance().headers=headers;// Provide a flat header list for utilities
getInstance().flatHeaders=headerGroups.reduce(function(all,headerGroup){return [].concat(all,headerGroup.headers);},[]);loopHooks(getHooks().useInstanceBeforeDimensions,getInstance());// Filter columns down to visible ones
var visibleColumnsDep=visibleColumns.filter(function(d){return d.isVisible;}).map(function(d){return d.id;}).sort().join('_');visibleColumns=React.useMemo(function(){return visibleColumns.filter(function(d){return d.isVisible;});},// eslint-disable-next-line react-hooks/exhaustive-deps
[visibleColumns,visibleColumnsDep]);getInstance().visibleColumns=visibleColumns;// Header Visibility is needed by this point
var _calculateHeaderWidth=calculateHeaderWidths(headers),totalColumnsMinWidth=_calculateHeaderWidth[0],totalColumnsWidth=_calculateHeaderWidth[1],totalColumnsMaxWidth=_calculateHeaderWidth[2];getInstance().totalColumnsMinWidth=totalColumnsMinWidth;getInstance().totalColumnsWidth=totalColumnsWidth;getInstance().totalColumnsMaxWidth=totalColumnsMaxWidth;loopHooks(getHooks().useInstance,getInstance())// Each materialized header needs to be assigned a render function and other
// prop getter properties here.
;[].concat(getInstance().flatHeaders,getInstance().allColumns).forEach(function(column){// Give columns/headers rendering power
column.render=makeRenderer(getInstance(),column);// Give columns/headers a default getHeaderProps
column.getHeaderProps=makePropGetter(getHooks().getHeaderProps,{instance:getInstance(),column:column});// Give columns/headers a default getFooterProps
column.getFooterProps=makePropGetter(getHooks().getFooterProps,{instance:getInstance(),column:column});});getInstance().headerGroups=React.useMemo(function(){return headerGroups.filter(function(headerGroup,i){// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers=headerGroup.headers.filter(function(column){var recurse=function recurse(headers){return headers.filter(function(column){if(column.headers){return recurse(column.headers);}return column.isVisible;}).length;};if(column.headers){return recurse(column.headers);}return column.isVisible;});// Give headerGroups getRowProps
if(headerGroup.headers.length){headerGroup.getHeaderGroupProps=makePropGetter(getHooks().getHeaderGroupProps,{instance:getInstance(),headerGroup:headerGroup,index:i});headerGroup.getFooterGroupProps=makePropGetter(getHooks().getFooterGroupProps,{instance:getInstance(),headerGroup:headerGroup,index:i});return true;}return false;});},[headerGroups,getInstance,getHooks]);getInstance().footerGroups=[].concat(getInstance().headerGroups).reverse();// The prepareRow function is absolutely necessary and MUST be called on
// any rows the user wishes to be displayed.
getInstance().prepareRow=React.useCallback(function(row){row.getRowProps=makePropGetter(getHooks().getRowProps,{instance:getInstance(),row:row});// Build the visible cells for each row
row.allCells=allColumns.map(function(column){var value=row.values[column.id];var cell={column:column,row:row,value:value};// Give each cell a getCellProps base
cell.getCellProps=makePropGetter(getHooks().getCellProps,{instance:getInstance(),cell:cell});// Give each cell a renderer function (supports multiple renderers)
cell.render=makeRenderer(getInstance(),column,{row:row,cell:cell,value:value});return cell;});row.cells=visibleColumns.map(function(column){return row.allCells.find(function(cell){return cell.column.id===column.id;});});// need to apply any row specific hooks (useExpanded requires this)
loopHooks(getHooks().prepareRow,row,{instance:getInstance()});},[getHooks,getInstance,allColumns,visibleColumns]);getInstance().getTableProps=makePropGetter(getHooks().getTableProps,{instance:getInstance()});getInstance().getTableBodyProps=makePropGetter(getHooks().getTableBodyProps,{instance:getInstance()});loopHooks(getHooks().useFinalInstance,getInstance());return getInstance();};function calculateHeaderWidths(headers,left){if(left===void 0){left=0;}var sumTotalMinWidth=0;var sumTotalWidth=0;var sumTotalMaxWidth=0;var sumTotalFlexWidth=0;headers.forEach(function(header){var subHeaders=header.headers;header.totalLeft=left;if(subHeaders&&subHeaders.length){var _calculateHeaderWidth2=calculateHeaderWidths(subHeaders,left),totalMinWidth=_calculateHeaderWidth2[0],totalWidth=_calculateHeaderWidth2[1],totalMaxWidth=_calculateHeaderWidth2[2],totalFlexWidth=_calculateHeaderWidth2[3];header.totalMinWidth=totalMinWidth;header.totalWidth=totalWidth;header.totalMaxWidth=totalMaxWidth;header.totalFlexWidth=totalFlexWidth;}else {header.totalMinWidth=header.minWidth;header.totalWidth=Math.min(Math.max(header.minWidth,header.width),header.maxWidth);header.totalMaxWidth=header.maxWidth;header.totalFlexWidth=header.canResize?header.totalWidth:0;}if(header.isVisible){left+=header.totalWidth;sumTotalMinWidth+=header.totalMinWidth;sumTotalWidth+=header.totalWidth;sumTotalMaxWidth+=header.totalMaxWidth;sumTotalFlexWidth+=header.totalFlexWidth;}});return [sumTotalMinWidth,sumTotalWidth,sumTotalMaxWidth,sumTotalFlexWidth];}function accessRowsForColumn(_ref){var data=_ref.data,rows=_ref.rows,flatRows=_ref.flatRows,rowsById=_ref.rowsById,column=_ref.column,getRowId=_ref.getRowId,getSubRows=_ref.getSubRows,accessValueHooks=_ref.accessValueHooks,getInstance=_ref.getInstance;// Access the row's data column-by-column
// We do it this way so we can incrementally add materialized
// columns after the first pass and avoid excessive looping
var accessRow=function accessRow(originalRow,rowIndex,depth,parent,parentRows){if(depth===void 0){depth=0;}// Keep the original reference around
var original=originalRow;var id=getRowId(originalRow,rowIndex,parent);var row=rowsById[id];// If the row hasn't been created, let's make it
if(!row){row={id:id,original:original,index:rowIndex,depth:depth,cells:[{}]// This is a dummy cell
};// Override common array functions (and the dummy cell's getCellProps function)
// to show an error if it is accessed without calling prepareRow
row.cells.map=unpreparedAccessWarning;row.cells.filter=unpreparedAccessWarning;row.cells.forEach=unpreparedAccessWarning;row.cells[0].getCellProps=unpreparedAccessWarning;// Create the cells and values
row.values={};// Push this row into the parentRows array
parentRows.push(row);// Keep track of every row in a flat array
flatRows.push(row);// Also keep track of every row by its ID
rowsById[id]=row;// Get the original subrows
row.originalSubRows=getSubRows(originalRow,rowIndex);// Then recursively access them
if(row.originalSubRows){var subRows=[];row.originalSubRows.forEach(function(d,i){return accessRow(d,i,depth+1,row,subRows);});// Keep the new subRows array on the row
row.subRows=subRows;}}else if(row.subRows){// If the row exists, then it's already been accessed
// Keep recursing, but don't worry about passing the
// accumlator array (those rows already exist)
row.originalSubRows.forEach(function(d,i){return accessRow(d,i,depth+1,row);});}// If the column has an accessor, use it to get a value
if(column.accessor){row.values[column.id]=column.accessor(originalRow,rowIndex,row,parentRows,data);}// Allow plugins to manipulate the column value
row.values[column.id]=reduceHooks(accessValueHooks,row.values[column.id],{row:row,column:column,instance:getInstance()},true);};data.forEach(function(originalRow,rowIndex){return accessRow(originalRow,rowIndex,0,undefined,rows);});}actions.resetExpanded='resetExpanded';actions.toggleRowExpanded='toggleRowExpanded';actions.toggleAllRowsExpanded='toggleAllRowsExpanded';var useExpanded=function useExpanded(hooks){hooks.getToggleAllRowsExpandedProps=[defaultGetToggleAllRowsExpandedProps];hooks.getToggleRowExpandedProps=[defaultGetToggleRowExpandedProps];hooks.stateReducers.push(reducer$1);hooks.useInstance.push(useInstance$1);hooks.prepareRow.push(prepareRow);};useExpanded.pluginName='useExpanded';var defaultGetToggleAllRowsExpandedProps=function defaultGetToggleAllRowsExpandedProps(props,_ref){var instance=_ref.instance;return [props,{onClick:function onClick(e){instance.toggleAllRowsExpanded();},style:{cursor:'pointer'},title:'Toggle All Rows Expanded'}];};var defaultGetToggleRowExpandedProps=function defaultGetToggleRowExpandedProps(props,_ref2){var row=_ref2.row;return [props,{onClick:function onClick(){row.toggleRowExpanded();},style:{cursor:'pointer'},title:'Toggle Row Expanded'}];};// Reducer
function reducer$1(state,action,previousState,instance){if(action.type===actions.init){return _extends({expanded:{}},state);}if(action.type===actions.resetExpanded){return _extends({},state,{expanded:instance.initialState.expanded||{}});}if(action.type===actions.toggleAllRowsExpanded){var value=action.value;var isAllRowsExpanded=instance.isAllRowsExpanded,rowsById=instance.rowsById;var expandAll=typeof value!=='undefined'?value:!isAllRowsExpanded;if(expandAll){var expanded={};Object.keys(rowsById).forEach(function(rowId){expanded[rowId]=true;});return _extends({},state,{expanded:expanded});}return _extends({},state,{expanded:{}});}if(action.type===actions.toggleRowExpanded){var id=action.id,setExpanded=action.value;var exists=state.expanded[id];var shouldExist=typeof setExpanded!=='undefined'?setExpanded:!exists;if(!exists&&shouldExist){var _extends2;return _extends({},state,{expanded:_extends({},state.expanded,(_extends2={},_extends2[id]=true,_extends2))});}else if(exists&&!shouldExist){var _state$expanded=state.expanded,_=_state$expanded[id],rest=_objectWithoutPropertiesLoose(_state$expanded,[id].map(_toPropertyKey));return _extends({},state,{expanded:rest});}else {return state;}}}function useInstance$1(instance){var data=instance.data,rows=instance.rows,rowsById=instance.rowsById,_instance$manualExpan=instance.manualExpandedKey,manualExpandedKey=_instance$manualExpan===void 0?'expanded':_instance$manualExpan,_instance$paginateExp=instance.paginateExpandedRows,paginateExpandedRows=_instance$paginateExp===void 0?true:_instance$paginateExp,_instance$expandSubRo=instance.expandSubRows,expandSubRows=_instance$expandSubRo===void 0?true:_instance$expandSubRo,_instance$autoResetEx=instance.autoResetExpanded,autoResetExpanded=_instance$autoResetEx===void 0?true:_instance$autoResetEx,getHooks=instance.getHooks,plugins=instance.plugins,expanded=instance.state.expanded,dispatch=instance.dispatch;ensurePluginOrder(plugins,['useSortBy','useGroupBy','usePivotColumns','useGlobalFilter'],'useExpanded');var getAutoResetExpanded=useGetLatest(autoResetExpanded);var isAllRowsExpanded=Boolean(Object.keys(rowsById).length&&Object.keys(expanded).length);if(isAllRowsExpanded){if(Object.keys(rowsById).some(function(id){return !expanded[id];})){isAllRowsExpanded=false;}}// Bypass any effects from firing when this changes
useMountedLayoutEffect(function(){if(getAutoResetExpanded()){dispatch({type:actions.resetExpanded});}},[dispatch,data]);var toggleRowExpanded=React.useCallback(function(id,value){dispatch({type:actions.toggleRowExpanded,id:id,value:value});},[dispatch]);var toggleAllRowsExpanded=React.useCallback(function(value){return dispatch({type:actions.toggleAllRowsExpanded,value:value});},[dispatch]);var expandedRows=React.useMemo(function(){if(paginateExpandedRows){return expandRows(rows,{manualExpandedKey:manualExpandedKey,expanded:expanded,expandSubRows:expandSubRows});}return rows;},[paginateExpandedRows,rows,manualExpandedKey,expanded,expandSubRows]);var expandedDepth=React.useMemo(function(){return findExpandedDepth(expanded);},[expanded]);var getInstance=useGetLatest(instance);var getToggleAllRowsExpandedProps=makePropGetter(getHooks().getToggleAllRowsExpandedProps,{instance:getInstance()});Object.assign(instance,{preExpandedRows:rows,expandedRows:expandedRows,rows:expandedRows,expandedDepth:expandedDepth,isAllRowsExpanded:isAllRowsExpanded,toggleRowExpanded:toggleRowExpanded,toggleAllRowsExpanded:toggleAllRowsExpanded,getToggleAllRowsExpandedProps:getToggleAllRowsExpandedProps});}function prepareRow(row,_ref3){var getHooks=_ref3.instance.getHooks,instance=_ref3.instance;row.toggleRowExpanded=function(set){return instance.toggleRowExpanded(row.id,set);};row.getToggleRowExpandedProps=makePropGetter(getHooks().getToggleRowExpandedProps,{instance:instance,row:row});}function findExpandedDepth(expanded){var maxDepth=0;Object.keys(expanded).forEach(function(id){var splitId=id.split('.');maxDepth=Math.max(maxDepth,splitId.length);});return maxDepth;}var text=function text(rows,ids,filterValue){rows=rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return String(rowValue).toLowerCase().includes(String(filterValue).toLowerCase());});});return rows;};text.autoRemove=function(val){return !val;};var exactText=function exactText(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue!==undefined?String(rowValue).toLowerCase()===String(filterValue).toLowerCase():true;});});};exactText.autoRemove=function(val){return !val;};var exactTextCase=function exactTextCase(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue!==undefined?String(rowValue)===String(filterValue):true;});});};exactTextCase.autoRemove=function(val){return !val;};var includes=function includes(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue.includes(filterValue);});});};includes.autoRemove=function(val){return !val||!val.length;};var includesAll=function includesAll(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue&&rowValue.length&&filterValue.every(function(val){return rowValue.includes(val);});});});};includesAll.autoRemove=function(val){return !val||!val.length;};var includesSome=function includesSome(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue&&rowValue.length&&filterValue.some(function(val){return rowValue.includes(val);});});});};includesSome.autoRemove=function(val){return !val||!val.length;};var includesValue=function includesValue(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return filterValue.includes(rowValue);});});};includesValue.autoRemove=function(val){return !val||!val.length;};var exact=function exact(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue===filterValue;});});};exact.autoRemove=function(val){return typeof val==='undefined';};var equals=function equals(rows,ids,filterValue){return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];// eslint-disable-next-
return rowValue==filterValue;});});};equals.autoRemove=function(val){return val==null;};var between=function between(rows,ids,filterValue){var _ref=filterValue||[],min=_ref[0],max=_ref[1];min=typeof min==='number'?min:-Infinity;max=typeof max==='number'?max:Infinity;if(min>max){var temp=min;min=max;max=temp;}return rows.filter(function(row){return ids.some(function(id){var rowValue=row.values[id];return rowValue>=min&&rowValue<=max;});});};between.autoRemove=function(val){return !val||typeof val[0]!=='number'&&typeof val[1]!=='number';};var filterTypes=/*#__PURE__*/Object.freeze({__proto__:null,text:text,exactText:exactText,exactTextCase:exactTextCase,includes:includes,includesAll:includesAll,includesSome:includesSome,includesValue:includesValue,exact:exact,equals:equals,between:between});actions.resetFilters='resetFilters';actions.setFilter='setFilter';actions.setAllFilters='setAllFilters';var useFilters=function useFilters(hooks){hooks.stateReducers.push(reducer$2);hooks.useInstance.push(useInstance$2);};useFilters.pluginName='useFilters';function reducer$2(state,action,previousState,instance){if(action.type===actions.init){return _extends({filters:[]},state);}if(action.type===actions.resetFilters){return _extends({},state,{filters:instance.initialState.filters||[]});}if(action.type===actions.setFilter){var columnId=action.columnId,filterValue=action.filterValue;var allColumns=instance.allColumns,userFilterTypes=instance.filterTypes;var column=allColumns.find(function(d){return d.id===columnId;});if(!column){throw new Error("React-Table: Could not find a column with id: "+columnId);}var filterMethod=getFilterMethod(column.filter,userFilterTypes||{},filterTypes);var previousfilter=state.filters.find(function(d){return d.id===columnId;});var newFilter=functionalUpdate(filterValue,previousfilter&&previousfilter.value);//
if(shouldAutoRemoveFilter(filterMethod.autoRemove,newFilter,column)){return _extends({},state,{filters:state.filters.filter(function(d){return d.id!==columnId;})});}if(previousfilter){return _extends({},state,{filters:state.filters.map(function(d){if(d.id===columnId){return {id:columnId,value:newFilter};}return d;})});}return _extends({},state,{filters:[].concat(state.filters,[{id:columnId,value:newFilter}])});}if(action.type===actions.setAllFilters){var filters=action.filters;var _allColumns=instance.allColumns,_userFilterTypes=instance.filterTypes;return _extends({},state,{// Filter out undefined values
filters:functionalUpdate(filters,state.filters).filter(function(filter){var column=_allColumns.find(function(d){return d.id===filter.id;});var filterMethod=getFilterMethod(column.filter,_userFilterTypes||{},filterTypes);if(shouldAutoRemoveFilter(filterMethod.autoRemove,filter.value,column)){return false;}return true;})});}}function useInstance$2(instance){var data=instance.data,rows=instance.rows,flatRows=instance.flatRows,rowsById=instance.rowsById,allColumns=instance.allColumns,userFilterTypes=instance.filterTypes,manualFilters=instance.manualFilters,_instance$defaultCanF=instance.defaultCanFilter,defaultCanFilter=_instance$defaultCanF===void 0?false:_instance$defaultCanF,disableFilters=instance.disableFilters,filters=instance.state.filters,dispatch=instance.dispatch,_instance$autoResetFi=instance.autoResetFilters,autoResetFilters=_instance$autoResetFi===void 0?true:_instance$autoResetFi;var setFilter=React.useCallback(function(columnId,filterValue){dispatch({type:actions.setFilter,columnId:columnId,filterValue:filterValue});},[dispatch]);var setAllFilters=React.useCallback(function(filters){dispatch({type:actions.setAllFilters,filters:filters});},[dispatch]);allColumns.forEach(function(column){var id=column.id,accessor=column.accessor,columnDefaultCanFilter=column.defaultCanFilter,columnDisableFilters=column.disableFilters;// Determine if a column is filterable
column.canFilter=accessor?getFirstDefined(columnDisableFilters===true?false:undefined,disableFilters===true?false:undefined,true):getFirstDefined(columnDefaultCanFilter,defaultCanFilter,false);// Provide the column a way of updating the filter value
column.setFilter=function(val){return setFilter(column.id,val);};// Provide the current filter value to the column for
// convenience
var found=filters.find(function(d){return d.id===id;});column.filterValue=found&&found.value;});var _React$useMemo=React.useMemo(function(){if(manualFilters||!filters.length){return [rows,flatRows,rowsById];}var filteredFlatRows=[];var filteredRowsById={};// Filters top level and nested rows
var filterRows=function filterRows(rows,depth){if(depth===void 0){depth=0;}var filteredRows=rows;filteredRows=filters.reduce(function(filteredSoFar,_ref){var columnId=_ref.id,filterValue=_ref.value;// Find the filters column
var column=allColumns.find(function(d){return d.id===columnId;});if(!column){return filteredSoFar;}if(depth===0){column.preFilteredRows=filteredSoFar;}var filterMethod=getFilterMethod(column.filter,userFilterTypes||{},filterTypes);if(!filterMethod){console.warn("Could not find a valid 'column.filter' for column with the ID: "+column.id+".");return filteredSoFar;}// Pass the rows, id, filterValue and column to the filterMethod
// to get the filtered rows back
column.filteredRows=filterMethod(filteredSoFar,[columnId],filterValue);return column.filteredRows;},rows);// Apply the filter to any subRows
// We technically could do this recursively in the above loop,
// but that would severely hinder the API for the user, since they
// would be required to do that recursion in some scenarios
filteredRows.forEach(function(row){filteredFlatRows.push(row);filteredRowsById[row.id]=row;if(!row.subRows){return;}row.subRows=row.subRows&&row.subRows.length>0?filterRows(row.subRows,depth+1):row.subRows;});return filteredRows;};return [filterRows(rows),filteredFlatRows,filteredRowsById];},[manualFilters,filters,rows,flatRows,rowsById,allColumns,userFilterTypes]),filteredRows=_React$useMemo[0],filteredFlatRows=_React$useMemo[1],filteredRowsById=_React$useMemo[2];React.useMemo(function(){// Now that each filtered column has it's partially filtered rows,
// lets assign the final filtered rows to all of the other columns
var nonFilteredColumns=allColumns.filter(function(column){return !filters.find(function(d){return d.id===column.id;});});// This essentially enables faceted filter options to be built easily
// using every column's preFilteredRows value
nonFilteredColumns.forEach(function(column){column.preFilteredRows=filteredRows;column.filteredRows=filteredRows;});},[filteredRows,filters,allColumns]);var getAutoResetFilters=useGetLatest(autoResetFilters);useMountedLayoutEffect(function(){if(getAutoResetFilters()){dispatch({type:actions.resetFilters});}},[dispatch,manualFilters?null:data]);Object.assign(instance,{preFilteredRows:rows,preFilteredFlatRows:flatRows,preFilteredRowsById:rowsById,filteredRows:filteredRows,filteredFlatRows:filteredFlatRows,filteredRowsById:filteredRowsById,rows:filteredRows,flatRows:filteredFlatRows,rowsById:filteredRowsById,setFilter:setFilter,setAllFilters:setAllFilters});}actions.resetGlobalFilter='resetGlobalFilter';actions.setGlobalFilter='setGlobalFilter';var useGlobalFilter=function useGlobalFilter(hooks){hooks.stateReducers.push(reducer$3);hooks.useInstance.push(useInstance$3);};useGlobalFilter.pluginName='useGlobalFilter';function reducer$3(state,action,previousState,instance){if(action.type===actions.resetGlobalFilter){return _extends({},state,{globalFilter:instance.initialState.globalFilter||undefined});}if(action.type===actions.setGlobalFilter){var filterValue=action.filterValue;var userFilterTypes=instance.userFilterTypes;var filterMethod=getFilterMethod(instance.globalFilter,userFilterTypes||{},filterTypes);var newFilter=functionalUpdate(filterValue,state.globalFilter);//
if(shouldAutoRemoveFilter(filterMethod.autoRemove,newFilter)){var globalFilter=state.globalFilter,stateWithoutGlobalFilter=_objectWithoutPropertiesLoose(state,["globalFilter"]);return stateWithoutGlobalFilter;}return _extends({},state,{globalFilter:newFilter});}}function useInstance$3(instance){var data=instance.data,rows=instance.rows,flatRows=instance.flatRows,rowsById=instance.rowsById,allColumns=instance.allColumns,userFilterTypes=instance.filterTypes,globalFilter=instance.globalFilter,manualGlobalFilter=instance.manualGlobalFilter,globalFilterValue=instance.state.globalFilter,dispatch=instance.dispatch,_instance$autoResetGl=instance.autoResetGlobalFilter,autoResetGlobalFilter=_instance$autoResetGl===void 0?true:_instance$autoResetGl,disableGlobalFilter=instance.disableGlobalFilter;var setGlobalFilter=React.useCallback(function(filterValue){dispatch({type:actions.setGlobalFilter,filterValue:filterValue});},[dispatch]);// TODO: Create a filter cache for incremental high speed multi-filtering
// This gets pretty complicated pretty fast, since you have to maintain a
// cache for each row group (top-level rows, and each row's recursive subrows)
// This would make multi-filtering a lot faster though. Too far?
var _React$useMemo=React.useMemo(function(){if(manualGlobalFilter||typeof globalFilterValue==='undefined'){return [rows,flatRows,rowsById];}var filteredFlatRows=[];var filteredRowsById={};var filterMethod=getFilterMethod(globalFilter,userFilterTypes||{},filterTypes);if(!filterMethod){console.warn("Could not find a valid 'globalFilter' option.");return rows;}allColumns.forEach(function(column){var columnDisableGlobalFilter=column.disableGlobalFilter;column.canFilter=getFirstDefined(columnDisableGlobalFilter===true?false:undefined,disableGlobalFilter===true?false:undefined,true);});var filterableColumns=allColumns.filter(function(c){return c.canFilter===true;});// Filters top level and nested rows
var filterRows=function filterRows(filteredRows){filteredRows=filterMethod(filteredRows,filterableColumns.map(function(d){return d.id;}),globalFilterValue);filteredRows.forEach(function(row){filteredFlatRows.push(row);filteredRowsById[row.id]=row;row.subRows=row.subRows&&row.subRows.length?filterRows(row.subRows):row.subRows;});return filteredRows;};return [filterRows(rows),filteredFlatRows,filteredRowsById];},[manualGlobalFilter,globalFilterValue,globalFilter,userFilterTypes,allColumns,rows,flatRows,rowsById,disableGlobalFilter]),globalFilteredRows=_React$useMemo[0],globalFilteredFlatRows=_React$useMemo[1],globalFilteredRowsById=_React$useMemo[2];var getAutoResetGlobalFilter=useGetLatest(autoResetGlobalFilter);useMountedLayoutEffect(function(){if(getAutoResetGlobalFilter()){dispatch({type:actions.resetGlobalFilter});}},[dispatch,manualGlobalFilter?null:data]);Object.assign(instance,{preGlobalFilteredRows:rows,preGlobalFilteredFlatRows:flatRows,preGlobalFilteredRowsById:rowsById,globalFilteredRows:globalFilteredRows,globalFilteredFlatRows:globalFilteredFlatRows,globalFilteredRowsById:globalFilteredRowsById,rows:globalFilteredRows,flatRows:globalFilteredFlatRows,rowsById:globalFilteredRowsById,setGlobalFilter:setGlobalFilter,disableGlobalFilter:disableGlobalFilter});}function sum(values,aggregatedValues){// It's faster to just add the aggregations together instead of
// process leaf nodes individually
return aggregatedValues.reduce(function(sum,next){return sum+(typeof next==='number'?next:0);},0);}function min(values){var min=values[0]||0;values.forEach(function(value){if(typeof value==='number'){min=Math.min(min,value);}});return min;}function max(values){var max=values[0]||0;values.forEach(function(value){if(typeof value==='number'){max=Math.max(max,value);}});return max;}function minMax(values){var min=values[0]||0;var max=values[0]||0;values.forEach(function(value){if(typeof value==='number'){min=Math.min(min,value);max=Math.max(max,value);}});return min+".."+max;}function average(values){return sum(null,values)/values.length;}function median(values){if(!values.length){return null;}var mid=Math.floor(values.length/2);var nums=[].concat(values).sort(function(a,b){return a-b;});return values.length%2!==0?nums[mid]:(nums[mid-1]+nums[mid])/2;}function unique(values){return Array.from(new Set(values).values());}function uniqueCount(values){return new Set(values).size;}function count(values){return values.length;}var aggregations=/*#__PURE__*/Object.freeze({__proto__:null,sum:sum,min:min,max:max,minMax:minMax,average:average,median:median,unique:unique,uniqueCount:uniqueCount,count:count});var emptyArray=[];var emptyObject={};// Actions
actions.resetGroupBy='resetGroupBy';actions.setGroupBy='setGroupBy';actions.toggleGroupBy='toggleGroupBy';var useGroupBy=function useGroupBy(hooks){hooks.getGroupByToggleProps=[defaultGetGroupByToggleProps];hooks.stateReducers.push(reducer$4);hooks.visibleColumnsDeps.push(function(deps,_ref){var instance=_ref.instance;return [].concat(deps,[instance.state.groupBy]);});hooks.visibleColumns.push(visibleColumns);hooks.useInstance.push(useInstance$4);hooks.prepareRow.push(prepareRow$1);};useGroupBy.pluginName='useGroupBy';var defaultGetGroupByToggleProps=function defaultGetGroupByToggleProps(props,_ref2){var header=_ref2.header;return [props,{onClick:header.canGroupBy?function(e){e.persist();header.toggleGroupBy();}:undefined,style:{cursor:header.canGroupBy?'pointer':undefined},title:'Toggle GroupBy'}];};// Reducer
function reducer$4(state,action,previousState,instance){if(action.type===actions.init){return _extends({groupBy:[]},state);}if(action.type===actions.resetGroupBy){return _extends({},state,{groupBy:instance.initialState.groupBy||[]});}if(action.type===actions.setGroupBy){var value=action.value;return _extends({},state,{groupBy:value});}if(action.type===actions.toggleGroupBy){var columnId=action.columnId,setGroupBy=action.value;var resolvedGroupBy=typeof setGroupBy!=='undefined'?setGroupBy:!state.groupBy.includes(columnId);if(resolvedGroupBy){return _extends({},state,{groupBy:[].concat(state.groupBy,[columnId])});}return _extends({},state,{groupBy:state.groupBy.filter(function(d){return d!==columnId;})});}}function visibleColumns(columns,_ref3){var groupBy=_ref3.instance.state.groupBy;// Sort grouped columns to the start of the column list
// before the headers are built
var groupByColumns=groupBy.map(function(g){return columns.find(function(col){return col.id===g;});}).filter(Boolean);var nonGroupByColumns=columns.filter(function(col){return !groupBy.includes(col.id);});columns=[].concat(groupByColumns,nonGroupByColumns);columns.forEach(function(column){column.isGrouped=groupBy.includes(column.id);column.groupedIndex=groupBy.indexOf(column.id);});return columns;}var defaultUserAggregations={};function useInstance$4(instance){var data=instance.data,rows=instance.rows,flatRows=instance.flatRows,rowsById=instance.rowsById,allColumns=instance.allColumns,flatHeaders=instance.flatHeaders,_instance$groupByFn=instance.groupByFn,groupByFn=_instance$groupByFn===void 0?defaultGroupByFn:_instance$groupByFn,manualGroupBy=instance.manualGroupBy,_instance$aggregation=instance.aggregations,userAggregations=_instance$aggregation===void 0?defaultUserAggregations:_instance$aggregation,plugins=instance.plugins,groupBy=instance.state.groupBy,dispatch=instance.dispatch,_instance$autoResetGr=instance.autoResetGroupBy,autoResetGroupBy=_instance$autoResetGr===void 0?true:_instance$autoResetGr,disableGroupBy=instance.disableGroupBy,defaultCanGroupBy=instance.defaultCanGroupBy,getHooks=instance.getHooks;ensurePluginOrder(plugins,['useColumnOrder','useFilters'],'useGroupBy');var getInstance=useGetLatest(instance);allColumns.forEach(function(column){var accessor=column.accessor,defaultColumnGroupBy=column.defaultGroupBy,columnDisableGroupBy=column.disableGroupBy;column.canGroupBy=accessor?getFirstDefined(column.canGroupBy,columnDisableGroupBy===true?false:undefined,disableGroupBy===true?false:undefined,true):getFirstDefined(column.canGroupBy,defaultColumnGroupBy,defaultCanGroupBy,false);if(column.canGroupBy){column.toggleGroupBy=function(){return instance.toggleGroupBy(column.id);};}column.Aggregated=column.Aggregated||column.Cell;});var toggleGroupBy=React.useCallback(function(columnId,value){dispatch({type:actions.toggleGroupBy,columnId:columnId,value:value});},[dispatch]);var setGroupBy=React.useCallback(function(value){dispatch({type:actions.setGroupBy,value:value});},[dispatch]);flatHeaders.forEach(function(header){header.getGroupByToggleProps=makePropGetter(getHooks().getGroupByToggleProps,{instance:getInstance(),header:header});});var _React$useMemo=React.useMemo(function(){if(manualGroupBy||!groupBy.length){return [rows,flatRows,rowsById,emptyArray,emptyObject,flatRows,rowsById];}// Ensure that the list of filtered columns exist
var existingGroupBy=groupBy.filter(function(g){return allColumns.find(function(col){return col.id===g;});});// Find the columns that can or are aggregating
// Uses each column to aggregate rows into a single value
var aggregateRowsToValues=function aggregateRowsToValues(leafRows,groupedRows,depth){var values={};allColumns.forEach(function(column){// Don't aggregate columns that are in the groupBy
if(existingGroupBy.includes(column.id)){values[column.id]=groupedRows[0]?groupedRows[0].values[column.id]:null;return;}// Aggregate the values
var aggregateFn=typeof column.aggregate==='function'?column.aggregate:userAggregations[column.aggregate]||aggregations[column.aggregate];if(aggregateFn){// Get the columnValues to aggregate
var groupedValues=groupedRows.map(function(row){return row.values[column.id];});// Get the columnValues to aggregate
var leafValues=leafRows.map(function(row){var columnValue=row.values[column.id];if(!depth&&column.aggregateValue){var aggregateValueFn=typeof column.aggregateValue==='function'?column.aggregateValue:userAggregations[column.aggregateValue]||aggregations[column.aggregateValue];if(!aggregateValueFn){console.info({column:column});throw new Error("React Table: Invalid column.aggregateValue option for column listed above");}columnValue=aggregateValueFn(columnValue,row,column);}return columnValue;});values[column.id]=aggregateFn(leafValues,groupedValues);}else if(column.aggregate){console.info({column:column});throw new Error("React Table: Invalid column.aggregate option for column listed above");}else {values[column.id]=null;}});return values;};var groupedFlatRows=[];var groupedRowsById={};var onlyGroupedFlatRows=[];var onlyGroupedRowsById={};var nonGroupedFlatRows=[];var nonGroupedRowsById={};// Recursively group the data
var groupUpRecursively=function groupUpRecursively(rows,depth,parentId){if(depth===void 0){depth=0;}// This is the last level, just return the rows
if(depth===existingGroupBy.length){return rows;}var columnId=existingGroupBy[depth];// Group the rows together for this level
var rowGroupsMap=groupByFn(rows,columnId);// Peform aggregations for each group
var aggregatedGroupedRows=Object.entries(rowGroupsMap).map(function(_ref4,index){var groupByVal=_ref4[0],groupedRows=_ref4[1];var id=columnId+":"+groupByVal;id=parentId?parentId+">"+id:id;// First, Recurse to group sub rows before aggregation
var subRows=groupUpRecursively(groupedRows,depth+1,id);// Flatten the leaf rows of the rows in this group
var leafRows=depth?flattenBy(groupedRows,'leafRows'):groupedRows;var values=aggregateRowsToValues(leafRows,groupedRows,depth);var row={id:id,isGrouped:true,groupByID:columnId,groupByVal:groupByVal,values:values,subRows:subRows,leafRows:leafRows,depth:depth,index:index};subRows.forEach(function(subRow){groupedFlatRows.push(subRow);groupedRowsById[subRow.id]=subRow;if(subRow.isGrouped){onlyGroupedFlatRows.push(subRow);onlyGroupedRowsById[subRow.id]=subRow;}else {nonGroupedFlatRows.push(subRow);nonGroupedRowsById[subRow.id]=subRow;}});return row;});return aggregatedGroupedRows;};var groupedRows=groupUpRecursively(rows);groupedRows.forEach(function(subRow){groupedFlatRows.push(subRow);groupedRowsById[subRow.id]=subRow;if(subRow.isGrouped){onlyGroupedFlatRows.push(subRow);onlyGroupedRowsById[subRow.id]=subRow;}else {nonGroupedFlatRows.push(subRow);nonGroupedRowsById[subRow.id]=subRow;}});// Assign the new data
return [groupedRows,groupedFlatRows,groupedRowsById,onlyGroupedFlatRows,onlyGroupedRowsById,nonGroupedFlatRows,nonGroupedRowsById];},[manualGroupBy,groupBy,rows,flatRows,rowsById,allColumns,userAggregations,groupByFn]),groupedRows=_React$useMemo[0],groupedFlatRows=_React$useMemo[1],groupedRowsById=_React$useMemo[2],onlyGroupedFlatRows=_React$useMemo[3],onlyGroupedRowsById=_React$useMemo[4],nonGroupedFlatRows=_React$useMemo[5],nonGroupedRowsById=_React$useMemo[6];var getAutoResetGroupBy=useGetLatest(autoResetGroupBy);useMountedLayoutEffect(function(){if(getAutoResetGroupBy()){dispatch({type:actions.resetGroupBy});}},[dispatch,manualGroupBy?null:data]);Object.assign(instance,{preGroupedRows:rows,preGroupedFlatRow:flatRows,preGroupedRowsById:rowsById,groupedRows:groupedRows,groupedFlatRows:groupedFlatRows,groupedRowsById:groupedRowsById,onlyGroupedFlatRows:onlyGroupedFlatRows,onlyGroupedRowsById:onlyGroupedRowsById,nonGroupedFlatRows:nonGroupedFlatRows,nonGroupedRowsById:nonGroupedRowsById,rows:groupedRows,flatRows:groupedFlatRows,rowsById:groupedRowsById,toggleGroupBy:toggleGroupBy,setGroupBy:setGroupBy});}function prepareRow$1(row){row.allCells.forEach(function(cell){var _row$subRows;// Grouped cells are in the groupBy and the pivot cell for the row
cell.isGrouped=cell.column.isGrouped&&cell.column.id===row.groupByID;// Placeholder cells are any columns in the groupBy that are not grouped
cell.isPlaceholder=!cell.isGrouped&&cell.column.isGrouped;// Aggregated cells are not grouped, not repeated, but still have subRows
cell.isAggregated=!cell.isGrouped&&!cell.isPlaceholder&&((_row$subRows=row.subRows)==null?void 0:_row$subRows.length);});}function defaultGroupByFn(rows,columnId){return rows.reduce(function(prev,row,i){// TODO: Might want to implement a key serializer here so
// irregular column values can still be grouped if needed?
var resKey=""+row.values[columnId];prev[resKey]=Array.isArray(prev[resKey])?prev[resKey]:[];prev[resKey].push(row);return prev;},{});}var reSplitAlphaNumeric=/([0-9]+)/gm;// Mixed sorting is slow, but very inclusive of many edge cases.
// It handles numbers, mixed alphanumeric combinations, and even
// null, undefined, and Infinity
var alphanumeric=function alphanumeric(rowA,rowB,columnId){var _getRowValuesByColumn=getRowValuesByColumnID(rowA,rowB,columnId),a=_getRowValuesByColumn[0],b=_getRowValuesByColumn[1];// Force to strings (or "" for unsupported types)
a=toString(a);b=toString(b);// Split on number groups, but keep the delimiter
// Then remove falsey split values
a=a.split(reSplitAlphaNumeric).filter(Boolean);b=b.split(reSplitAlphaNumeric).filter(Boolean);// While
while(a.length&&b.length){var aa=a.shift();var bb=b.shift();var an=parseInt(aa,10);var bn=parseInt(bb,10);var combo=[an,bn].sort();// Both are string
if(isNaN(combo[0])){if(aa>bb){return 1;}if(bb>aa){return -1;}continue;}// One is a string, one is a number
if(isNaN(combo[1])){return isNaN(an)?-1:1;}// Both are numbers
if(an>bn){return 1;}if(bn>an){return -1;}}return a.length-b.length;};function datetime(rowA,rowB,columnId){var _getRowValuesByColumn2=getRowValuesByColumnID(rowA,rowB,columnId),a=_getRowValuesByColumn2[0],b=_getRowValuesByColumn2[1];a=a.getTime();b=b.getTime();return compareBasic(a,b);}function basic(rowA,rowB,columnId){var _getRowValuesByColumn3=getRowValuesByColumnID(rowA,rowB,columnId),a=_getRowValuesByColumn3[0],b=_getRowValuesByColumn3[1];return compareBasic(a,b);}function string(rowA,rowB,columnId){var _getRowValuesByColumn4=getRowValuesByColumnID(rowA,rowB,columnId),a=_getRowValuesByColumn4[0],b=_getRowValuesByColumn4[1];a=a.split('').filter(Boolean);b=b.split('').filter(Boolean);while(a.length&&b.length){var aa=a.shift();var bb=b.shift();var alower=aa.toLowerCase();var blower=bb.toLowerCase();// Case insensitive comparison until characters match
if(alower>blower){return 1;}if(blower>alower){return -1;}// If lowercase characters are identical
if(aa>bb){return 1;}if(bb>aa){return -1;}continue;}return a.length-b.length;}function number(rowA,rowB,columnId){var _getRowValuesByColumn5=getRowValuesByColumnID(rowA,rowB,columnId),a=_getRowValuesByColumn5[0],b=_getRowValuesByColumn5[1];var replaceNonNumeric=/[^0-9.]/gi;a=Number(String(a).replace(replaceNonNumeric,''));b=Number(String(b).replace(replaceNonNumeric,''));return compareBasic(a,b);}// Utils
function compareBasic(a,b){return a===b?0:a>b?1:-1;}function getRowValuesByColumnID(row1,row2,columnId){return [row1.values[columnId],row2.values[columnId]];}function toString(a){if(typeof a==='number'){if(isNaN(a)||a===Infinity||a===-Infinity){return '';}return String(a);}if(typeof a==='string'){return a;}return '';}var sortTypes=/*#__PURE__*/Object.freeze({__proto__:null,alphanumeric:alphanumeric,datetime:datetime,basic:basic,string:string,number:number});actions.resetSortBy='resetSortBy';actions.setSortBy='setSortBy';actions.toggleSortBy='toggleSortBy';actions.clearSortBy='clearSortBy';defaultColumn.sortType='alphanumeric';defaultColumn.sortDescFirst=false;var useSortBy=function useSortBy(hooks){hooks.getSortByToggleProps=[defaultGetSortByToggleProps];hooks.stateReducers.push(reducer$5);hooks.useInstance.push(useInstance$5);};useSortBy.pluginName='useSortBy';var defaultGetSortByToggleProps=function defaultGetSortByToggleProps(props,_ref){var instance=_ref.instance,column=_ref.column;var _instance$isMultiSort=instance.isMultiSortEvent,isMultiSortEvent=_instance$isMultiSort===void 0?function(e){return e.shiftKey;}:_instance$isMultiSort;return [props,{onClick:column.canSort?function(e){e.persist();column.toggleSortBy(undefined,!instance.disableMultiSort&&isMultiSortEvent(e));}:undefined,style:{cursor:column.canSort?'pointer':undefined},title:column.canSort?'Toggle SortBy':undefined}];};// Reducer
function reducer$5(state,action,previousState,instance){if(action.type===actions.init){return _extends({sortBy:[]},state);}if(action.type===actions.resetSortBy){return _extends({},state,{sortBy:instance.initialState.sortBy||[]});}if(action.type===actions.clearSortBy){var sortBy=state.sortBy;var newSortBy=sortBy.filter(function(d){return d.id!==action.columnId;});return _extends({},state,{sortBy:newSortBy});}if(action.type===actions.setSortBy){var _sortBy=action.sortBy;return _extends({},state,{sortBy:_sortBy});}if(action.type===actions.toggleSortBy){var columnId=action.columnId,desc=action.desc,multi=action.multi;var allColumns=instance.allColumns,disableMultiSort=instance.disableMultiSort,disableSortRemove=instance.disableSortRemove,disableMultiRemove=instance.disableMultiRemove,_instance$maxMultiSor=instance.maxMultiSortColCount,maxMultiSortColCount=_instance$maxMultiSor===void 0?Number.MAX_SAFE_INTEGER:_instance$maxMultiSor;var _sortBy2=state.sortBy;// Find the column for this columnId
var column=allColumns.find(function(d){return d.id===columnId;});var sortDescFirst=column.sortDescFirst;// Find any existing sortBy for this column
var existingSortBy=_sortBy2.find(function(d){return d.id===columnId;});var existingIndex=_sortBy2.findIndex(function(d){return d.id===columnId;});var hasDescDefined=typeof desc!=='undefined'&&desc!==null;var _newSortBy=[];// What should we do with this sort action?
var sortAction;if(!disableMultiSort&&multi){if(existingSortBy){sortAction='toggle';}else {sortAction='add';}}else {// Normal mode
if(existingIndex!==_sortBy2.length-1||_sortBy2.length!==1){sortAction='replace';}else if(existingSortBy){sortAction='toggle';}else {sortAction='replace';}}// Handle toggle states that will remove the sortBy
if(sortAction==='toggle'&&// Must be toggling
!disableSortRemove&&// If disableSortRemove, disable in general
!hasDescDefined&&(// Must not be setting desc
multi?!disableMultiRemove:true)&&(// If multi, don't allow if disableMultiRemove
existingSortBy&&// Finally, detect if it should indeed be removed
existingSortBy.desc&&!sortDescFirst||!existingSortBy.desc&&sortDescFirst)){sortAction='remove';}if(sortAction==='replace'){_newSortBy=[{id:columnId,desc:hasDescDefined?desc:sortDescFirst}];}else if(sortAction==='add'){_newSortBy=[].concat(_sortBy2,[{id:columnId,desc:hasDescDefined?desc:sortDescFirst}]);// Take latest n columns
_newSortBy.splice(0,_newSortBy.length-maxMultiSortColCount);}else if(sortAction==='toggle'){// This flips (or sets) the
_newSortBy=_sortBy2.map(function(d){if(d.id===columnId){return _extends({},d,{desc:hasDescDefined?desc:!existingSortBy.desc});}return d;});}else if(sortAction==='remove'){_newSortBy=_sortBy2.filter(function(d){return d.id!==columnId;});}return _extends({},state,{sortBy:_newSortBy});}}function useInstance$5(instance){var data=instance.data,rows=instance.rows,flatRows=instance.flatRows,allColumns=instance.allColumns,_instance$orderByFn=instance.orderByFn,orderByFn=_instance$orderByFn===void 0?defaultOrderByFn:_instance$orderByFn,userSortTypes=instance.sortTypes,manualSortBy=instance.manualSortBy,defaultCanSort=instance.defaultCanSort,disableSortBy=instance.disableSortBy,flatHeaders=instance.flatHeaders,sortBy=instance.state.sortBy,dispatch=instance.dispatch,plugins=instance.plugins,getHooks=instance.getHooks,_instance$autoResetSo=instance.autoResetSortBy,autoResetSortBy=_instance$autoResetSo===void 0?true:_instance$autoResetSo;ensurePluginOrder(plugins,['useFilters','useGlobalFilter','useGroupBy','usePivotColumns'],'useSortBy');var setSortBy=React.useCallback(function(sortBy){dispatch({type:actions.setSortBy,sortBy:sortBy});},[dispatch]);// Updates sorting based on a columnId, desc flag and multi flag
var toggleSortBy=React.useCallback(function(columnId,desc,multi){dispatch({type:actions.toggleSortBy,columnId:columnId,desc:desc,multi:multi});},[dispatch]);// use reference to avoid memory leak in #1608
var getInstance=useGetLatest(instance);// Add the getSortByToggleProps method to columns and headers
flatHeaders.forEach(function(column){var accessor=column.accessor,defaultColumnCanSort=column.canSort,columnDisableSortBy=column.disableSortBy,id=column.id;var canSort=accessor?getFirstDefined(columnDisableSortBy===true?false:undefined,disableSortBy===true?false:undefined,true):getFirstDefined(defaultCanSort,defaultColumnCanSort,false);column.canSort=canSort;if(column.canSort){column.toggleSortBy=function(desc,multi){return toggleSortBy(column.id,desc,multi);};column.clearSortBy=function(){dispatch({type:actions.clearSortBy,columnId:column.id});};}column.getSortByToggleProps=makePropGetter(getHooks().getSortByToggleProps,{instance:getInstance(),column:column});var columnSort=sortBy.find(function(d){return d.id===id;});column.isSorted=!!columnSort;column.sortedIndex=sortBy.findIndex(function(d){return d.id===id;});column.isSortedDesc=column.isSorted?columnSort.desc:undefined;});var _React$useMemo=React.useMemo(function(){if(manualSortBy||!sortBy.length){return [rows,flatRows];}var sortedFlatRows=[];// Filter out sortBys that correspond to non existing columns
var availableSortBy=sortBy.filter(function(sort){return allColumns.find(function(col){return col.id===sort.id;});});var sortData=function sortData(rows){// Use the orderByFn to compose multiple sortBy's together.
// This will also perform a stable sorting using the row index
// if needed.
var sortedData=orderByFn(rows,availableSortBy.map(function(sort){// Support custom sorting methods for each column
var column=allColumns.find(function(d){return d.id===sort.id;});if(!column){throw new Error("React-Table: Could not find a column with id: "+sort.id+" while sorting");}var sortType=column.sortType;// Look up sortBy functions in this order:
// column function
// column string lookup on user sortType
// column string lookup on built-in sortType
// default function
// default string lookup on user sortType
// default string lookup on built-in sortType
var sortMethod=isFunction(sortType)||(userSortTypes||{})[sortType]||sortTypes[sortType];if(!sortMethod){throw new Error("React-Table: Could not find a valid sortType of '"+sortType+"' for column '"+sort.id+"'.");}// Return the correct sortFn.
// This function should always return in ascending order
return function(a,b){return sortMethod(a,b,sort.id,sort.desc);};}),// Map the directions
availableSortBy.map(function(sort){// Detect and use the sortInverted option
var column=allColumns.find(function(d){return d.id===sort.id;});if(column&&column.sortInverted){return sort.desc;}return !sort.desc;}));// If there are sub-rows, sort them
sortedData.forEach(function(row){sortedFlatRows.push(row);if(!row.subRows||row.subRows.length===0){return;}row.subRows=sortData(row.subRows);});return sortedData;};return [sortData(rows),sortedFlatRows];},[manualSortBy,sortBy,rows,flatRows,allColumns,orderByFn,userSortTypes]),sortedRows=_React$useMemo[0],sortedFlatRows=_React$useMemo[1];var getAutoResetSortBy=useGetLatest(autoResetSortBy);useMountedLayoutEffect(function(){if(getAutoResetSortBy()){dispatch({type:actions.resetSortBy});}},[manualSortBy?null:data]);Object.assign(instance,{preSortedRows:rows,preSortedFlatRows:flatRows,sortedRows:sortedRows,sortedFlatRows:sortedFlatRows,rows:sortedRows,flatRows:sortedFlatRows,setSortBy:setSortBy,toggleSortBy:toggleSortBy});}function defaultOrderByFn(arr,funcs,dirs){return [].concat(arr).sort(function(rowA,rowB){for(var i=0;i<funcs.length;i+=1){var sortFn=funcs[i];var desc=dirs[i]===false||dirs[i]==='desc';var sortInt=sortFn(rowA,rowB);if(sortInt!==0){return desc?-sortInt:sortInt;}}return dirs[0]?rowA.index-rowB.index:rowB.index-rowA.index;});}var pluginName='usePagination';// Actions
actions.resetPage='resetPage';actions.gotoPage='gotoPage';actions.setPageSize='setPageSize';var usePagination=function usePagination(hooks){hooks.stateReducers.push(reducer$6);hooks.useInstance.push(useInstance$6);};usePagination.pluginName=pluginName;function reducer$6(state,action,previousState,instance){if(action.type===actions.init){return _extends({pageSize:10,pageIndex:0},state);}if(action.type===actions.resetPage){return _extends({},state,{pageIndex:instance.initialState.pageIndex||0});}if(action.type===actions.gotoPage){var pageCount=instance.pageCount,page=instance.page;var newPageIndex=functionalUpdate(action.pageIndex,state.pageIndex);var canNavigate=false;if(newPageIndex>state.pageIndex){// next page
canNavigate=pageCount===-1?page.length>=state.pageSize:newPageIndex<pageCount;}else if(newPageIndex<state.pageIndex){// prev page
canNavigate=newPageIndex>-1;}if(!canNavigate){return state;}return _extends({},state,{pageIndex:newPageIndex});}if(action.type===actions.setPageSize){var pageSize=action.pageSize;var topRowIndex=state.pageSize*state.pageIndex;var pageIndex=Math.floor(topRowIndex/pageSize);return _extends({},state,{pageIndex:pageIndex,pageSize:pageSize});}}function useInstance$6(instance){var rows=instance.rows,_instance$autoResetPa=instance.autoResetPage,autoResetPage=_instance$autoResetPa===void 0?true:_instance$autoResetPa,_instance$manualExpan=instance.manualExpandedKey,manualExpandedKey=_instance$manualExpan===void 0?'expanded':_instance$manualExpan,plugins=instance.plugins,userPageCount=instance.pageCount,_instance$paginateExp=instance.paginateExpandedRows,paginateExpandedRows=_instance$paginateExp===void 0?true:_instance$paginateExp,_instance$expandSubRo=instance.expandSubRows,expandSubRows=_instance$expandSubRo===void 0?true:_instance$expandSubRo,_instance$state=instance.state,pageSize=_instance$state.pageSize,pageIndex=_instance$state.pageIndex,expanded=_instance$state.expanded,globalFilter=_instance$state.globalFilter,filters=_instance$state.filters,groupBy=_instance$state.groupBy,sortBy=_instance$state.sortBy,dispatch=instance.dispatch,data=instance.data,manualPagination=instance.manualPagination;ensurePluginOrder(plugins,['useGlobalFilter','useFilters','useGroupBy','useSortBy','useExpanded'],'usePagination');var getAutoResetPage=useGetLatest(autoResetPage);useMountedLayoutEffect(function(){if(getAutoResetPage()){dispatch({type:actions.resetPage});}},[dispatch,manualPagination?null:data,globalFilter,filters,groupBy,sortBy]);var pageCount=manualPagination?userPageCount:Math.ceil(rows.length/pageSize);var pageOptions=React.useMemo(function(){return pageCount>0?[].concat(new Array(pageCount)).fill(null).map(function(d,i){return i;}):[];},[pageCount]);var page=React.useMemo(function(){var page;if(manualPagination){page=rows;}else {var pageStart=pageSize*pageIndex;var pageEnd=pageStart+pageSize;page=rows.slice(pageStart,pageEnd);}if(paginateExpandedRows){return page;}return expandRows(page,{manualExpandedKey:manualExpandedKey,expanded:expanded,expandSubRows:expandSubRows});},[expandSubRows,expanded,manualExpandedKey,manualPagination,pageIndex,pageSize,paginateExpandedRows,rows]);var canPreviousPage=pageIndex>0;var canNextPage=pageCount===-1?page.length>=pageSize:pageIndex<pageCount-1;var gotoPage=React.useCallback(function(pageIndex){dispatch({type:actions.gotoPage,pageIndex:pageIndex});},[dispatch]);var previousPage=React.useCallback(function(){return gotoPage(function(old){return old-1;});},[gotoPage]);var nextPage=React.useCallback(function(){return gotoPage(function(old){return old+1;});},[gotoPage]);var setPageSize=React.useCallback(function(pageSize){dispatch({type:actions.setPageSize,pageSize:pageSize});},[dispatch]);Object.assign(instance,{pageOptions:pageOptions,pageCount:pageCount,page:page,canPreviousPage:canPreviousPage,canNextPage:canNextPage,gotoPage:gotoPage,previousPage:previousPage,nextPage:nextPage,setPageSize:setPageSize});}actions.resetPivot='resetPivot';actions.togglePivot='togglePivot';var _UNSTABLE_usePivotColumns=function _UNSTABLE_usePivotColumns(hooks){hooks.getPivotToggleProps=[defaultGetPivotToggleProps];hooks.stateReducers.push(reducer$7);hooks.useInstanceAfterData.push(useInstanceAfterData);hooks.allColumns.push(allColumns);hooks.accessValue.push(accessValue);hooks.materializedColumns.push(materializedColumns);hooks.materializedColumnsDeps.push(materializedColumnsDeps);hooks.visibleColumns.push(visibleColumns$1);hooks.visibleColumnsDeps.push(visibleColumnsDeps);hooks.useInstance.push(useInstance$7);hooks.prepareRow.push(prepareRow$2);};_UNSTABLE_usePivotColumns.pluginName='usePivotColumns';var defaultPivotColumns=[];var defaultGetPivotToggleProps=function defaultGetPivotToggleProps(props,_ref){var header=_ref.header;return [props,{onClick:header.canPivot?function(e){e.persist();header.togglePivot();}:undefined,style:{cursor:header.canPivot?'pointer':undefined},title:'Toggle Pivot'}];};// Reducer
function reducer$7(state,action,previousState,instance){if(action.type===actions.init){return _extends({pivotColumns:defaultPivotColumns},state);}if(action.type===actions.resetPivot){return _extends({},state,{pivotColumns:instance.initialState.pivotColumns||defaultPivotColumns});}if(action.type===actions.togglePivot){var columnId=action.columnId,setPivot=action.value;var resolvedPivot=typeof setPivot!=='undefined'?setPivot:!state.pivotColumns.includes(columnId);if(resolvedPivot){return _extends({},state,{pivotColumns:[].concat(state.pivotColumns,[columnId])});}return _extends({},state,{pivotColumns:state.pivotColumns.filter(function(d){return d!==columnId;})});}}function useInstanceAfterData(instance){instance.allColumns.forEach(function(column){column.isPivotSource=instance.state.pivotColumns.includes(column.id);});}function allColumns(columns,_ref2){var instance=_ref2.instance;columns.forEach(function(column){column.isPivotSource=instance.state.pivotColumns.includes(column.id);column.uniqueValues=new Set();});return columns;}function accessValue(value,_ref3){var column=_ref3.column;if(column.uniqueValues&&typeof value!=='undefined'){column.uniqueValues.add(value);}return value;}function materializedColumns(materialized,_ref4){var instance=_ref4.instance;var allColumns=instance.allColumns,state=instance.state;if(!state.pivotColumns.length||!state.groupBy||!state.groupBy.length){return materialized;}var pivotColumns=state.pivotColumns.map(function(id){return allColumns.find(function(d){return d.id===id;});}).filter(Boolean);var sourceColumns=allColumns.filter(function(d){return !d.isPivotSource&&!state.groupBy.includes(d.id)&&!state.pivotColumns.includes(d.id);});var buildPivotColumns=function buildPivotColumns(depth,parent,pivotFilters){if(depth===void 0){depth=0;}if(pivotFilters===void 0){pivotFilters=[];}var pivotColumn=pivotColumns[depth];if(!pivotColumn){return sourceColumns.map(function(sourceColumn){// TODO: We could offer support here for renesting pivoted
// columns inside copies of their header groups. For now,
// that seems like it would be (1) overkill on nesting, considering
// you already get nesting for every pivot level and (2)
// really hard. :)
return _extends({},sourceColumn,{canPivot:false,isPivoted:true,parent:parent,depth:depth,id:""+(parent?parent.id+"."+sourceColumn.id:sourceColumn.id),accessor:function accessor(originalRow,i,row){if(pivotFilters.every(function(filter){return filter(row);})){return row.values[sourceColumn.id];}}});});}var uniqueValues=Array.from(pivotColumn.uniqueValues).sort();return uniqueValues.map(function(uniqueValue){var columnGroup=_extends({},pivotColumn,{Header:pivotColumn.PivotHeader||typeof pivotColumn.header==='string'?pivotColumn.Header+": "+uniqueValue:uniqueValue,isPivotGroup:true,parent:parent,depth:depth,id:parent?parent.id+"."+pivotColumn.id+"."+uniqueValue:pivotColumn.id+"."+uniqueValue,pivotValue:uniqueValue});columnGroup.columns=buildPivotColumns(depth+1,columnGroup,[].concat(pivotFilters,[function(row){return row.values[pivotColumn.id]===uniqueValue;}]));return columnGroup;});};var newMaterialized=flattenColumns(buildPivotColumns());return [].concat(materialized,newMaterialized);}function materializedColumnsDeps(deps,_ref5){var _ref5$instance$state=_ref5.instance.state,pivotColumns=_ref5$instance$state.pivotColumns,groupBy=_ref5$instance$state.groupBy;return [].concat(deps,[pivotColumns,groupBy]);}function visibleColumns$1(visibleColumns,_ref6){var state=_ref6.instance.state;visibleColumns=visibleColumns.filter(function(d){return !d.isPivotSource;});if(state.pivotColumns.length&&state.groupBy&&state.groupBy.length){visibleColumns=visibleColumns.filter(function(column){return column.isGrouped||column.isPivoted;});}return visibleColumns;}function visibleColumnsDeps(deps,_ref7){var instance=_ref7.instance;return [].concat(deps,[instance.state.pivotColumns,instance.state.groupBy]);}function useInstance$7(instance){var columns=instance.columns,allColumns=instance.allColumns,flatHeaders=instance.flatHeaders,getHooks=instance.getHooks,plugins=instance.plugins,dispatch=instance.dispatch,_instance$autoResetPi=instance.autoResetPivot,autoResetPivot=_instance$autoResetPi===void 0?true:_instance$autoResetPi,manaulPivot=instance.manaulPivot,disablePivot=instance.disablePivot,defaultCanPivot=instance.defaultCanPivot;ensurePluginOrder(plugins,['useGroupBy'],'usePivotColumns');var getInstance=useGetLatest(instance);allColumns.forEach(function(column){var accessor=column.accessor,defaultColumnPivot=column.defaultPivot,columnDisablePivot=column.disablePivot;column.canPivot=accessor?getFirstDefined(column.canPivot,columnDisablePivot===true?false:undefined,disablePivot===true?false:undefined,true):getFirstDefined(column.canPivot,defaultColumnPivot,defaultCanPivot,false);if(column.canPivot){column.togglePivot=function(){return instance.togglePivot(column.id);};}column.Aggregated=column.Aggregated||column.Cell;});var togglePivot=function togglePivot(columnId,value){dispatch({type:actions.togglePivot,columnId:columnId,value:value});};flatHeaders.forEach(function(header){header.getPivotToggleProps=makePropGetter(getHooks().getPivotToggleProps,{instance:getInstance(),header:header});});var getAutoResetPivot=useGetLatest(autoResetPivot);useMountedLayoutEffect(function(){if(getAutoResetPivot()){dispatch({type:actions.resetPivot});}},[dispatch,manaulPivot?null:columns]);Object.assign(instance,{togglePivot:togglePivot});}function prepareRow$2(row){row.allCells.forEach(function(cell){// Grouped cells are in the pivotColumns and the pivot cell for the row
cell.isPivoted=cell.column.isPivoted;});}var pluginName$1='useRowSelect';// Actions
actions.resetSelectedRows='resetSelectedRows';actions.toggleAllRowsSelected='toggleAllRowsSelected';actions.toggleRowSelected='toggleRowSelected';actions.toggleAllPageRowsSelected='toggleAllPageRowsSelected';var useRowSelect=function useRowSelect(hooks){hooks.getToggleRowSelectedProps=[defaultGetToggleRowSelectedProps];hooks.getToggleAllRowsSelectedProps=[defaultGetToggleAllRowsSelectedProps];hooks.getToggleAllPageRowsSelectedProps=[defaultGetToggleAllPageRowsSelectedProps];hooks.stateReducers.push(reducer$8);hooks.useInstance.push(useInstance$8);hooks.prepareRow.push(prepareRow$3);};useRowSelect.pluginName=pluginName$1;var defaultGetToggleRowSelectedProps=function defaultGetToggleRowSelectedProps(props,_ref){var instance=_ref.instance,row=_ref.row;var _instance$manualRowSe=instance.manualRowSelectedKey,manualRowSelectedKey=_instance$manualRowSe===void 0?'isSelected':_instance$manualRowSe;var checked=false;if(row.original&&row.original[manualRowSelectedKey]){checked=true;}else {checked=row.isSelected;}return [props,{onChange:function onChange(e){row.toggleRowSelected(e.target.checked);},style:{cursor:'pointer'},checked:checked,title:'Toggle Row Selected',indeterminate:row.isSomeSelected}];};var defaultGetToggleAllRowsSelectedProps=function defaultGetToggleAllRowsSelectedProps(props,_ref2){var instance=_ref2.instance;return [props,{onChange:function onChange(e){instance.toggleAllRowsSelected(e.target.checked);},style:{cursor:'pointer'},checked:instance.isAllRowsSelected,title:'Toggle All Rows Selected',indeterminate:Boolean(!instance.isAllRowsSelected&&Object.keys(instance.state.selectedRowIds).length)}];};var defaultGetToggleAllPageRowsSelectedProps=function defaultGetToggleAllPageRowsSelectedProps(props,_ref3){var instance=_ref3.instance;return [props,{onChange:function onChange(e){instance.toggleAllPageRowsSelected(e.target.checked);},style:{cursor:'pointer'},checked:instance.isAllPageRowsSelected,title:'Toggle All Current Page Rows Selected',indeterminate:Boolean(!instance.isAllPageRowsSelected&&instance.page.some(function(_ref4){var id=_ref4.id;return instance.state.selectedRowIds[id];}))}];};// eslint-disable-next-line max-params
function reducer$8(state,action,previousState,instance){if(action.type===actions.init){return _extends({selectedRowIds:{}},state);}if(action.type===actions.resetSelectedRows){return _extends({},state,{selectedRowIds:instance.initialState.selectedRowIds||{}});}if(action.type===actions.toggleAllRowsSelected){var setSelected=action.value;var isAllRowsSelected=instance.isAllRowsSelected,rowsById=instance.rowsById,_instance$nonGroupedR=instance.nonGroupedRowsById,nonGroupedRowsById=_instance$nonGroupedR===void 0?rowsById:_instance$nonGroupedR;var selectAll=typeof setSelected!=='undefined'?setSelected:!isAllRowsSelected;// Only remove/add the rows that are visible on the screen
// Leave all the other rows that are selected alone.
var selectedRowIds=Object.assign({},state.selectedRowIds);if(selectAll){Object.keys(nonGroupedRowsById).forEach(function(rowId){selectedRowIds[rowId]=true;});}else {Object.keys(nonGroupedRowsById).forEach(function(rowId){delete selectedRowIds[rowId];});}return _extends({},state,{selectedRowIds:selectedRowIds});}if(action.type===actions.toggleRowSelected){var id=action.id,_setSelected=action.value;var _rowsById=instance.rowsById,_instance$selectSubRo=instance.selectSubRows,selectSubRows=_instance$selectSubRo===void 0?true:_instance$selectSubRo,getSubRows=instance.getSubRows;var isSelected=state.selectedRowIds[id];var shouldExist=typeof _setSelected!=='undefined'?_setSelected:!isSelected;if(isSelected===shouldExist){return state;}var newSelectedRowIds=_extends({},state.selectedRowIds);var handleRowById=function handleRowById(id){var row=_rowsById[id];if(!row.isGrouped){if(shouldExist){newSelectedRowIds[id]=true;}else {delete newSelectedRowIds[id];}}if(selectSubRows&&getSubRows(row)){return getSubRows(row).forEach(function(row){return handleRowById(row.id);});}};handleRowById(id);return _extends({},state,{selectedRowIds:newSelectedRowIds});}if(action.type===actions.toggleAllPageRowsSelected){var _setSelected2=action.value;var page=instance.page,_rowsById2=instance.rowsById,_instance$selectSubRo2=instance.selectSubRows,_selectSubRows=_instance$selectSubRo2===void 0?true:_instance$selectSubRo2,isAllPageRowsSelected=instance.isAllPageRowsSelected,_getSubRows=instance.getSubRows;var _selectAll=typeof _setSelected2!=='undefined'?_setSelected2:!isAllPageRowsSelected;var _newSelectedRowIds=_extends({},state.selectedRowIds);var _handleRowById=function _handleRowById(id){var row=_rowsById2[id];if(!row.isGrouped){if(_selectAll){_newSelectedRowIds[id]=true;}else {delete _newSelectedRowIds[id];}}if(_selectSubRows&&_getSubRows(row)){return _getSubRows(row).forEach(function(row){return _handleRowById(row.id);});}};page.forEach(function(row){return _handleRowById(row.id);});return _extends({},state,{selectedRowIds:_newSelectedRowIds});}return state;}function useInstance$8(instance){var data=instance.data,rows=instance.rows,getHooks=instance.getHooks,plugins=instance.plugins,rowsById=instance.rowsById,_instance$nonGroupedR2=instance.nonGroupedRowsById,nonGroupedRowsById=_instance$nonGroupedR2===void 0?rowsById:_instance$nonGroupedR2,_instance$autoResetSe=instance.autoResetSelectedRows,autoResetSelectedRows=_instance$autoResetSe===void 0?true:_instance$autoResetSe,selectedRowIds=instance.state.selectedRowIds,_instance$selectSubRo3=instance.selectSubRows,selectSubRows=_instance$selectSubRo3===void 0?true:_instance$selectSubRo3,dispatch=instance.dispatch,page=instance.page,getSubRows=instance.getSubRows;ensurePluginOrder(plugins,['useFilters','useGroupBy','useSortBy','useExpanded','usePagination'],'useRowSelect');var selectedFlatRows=React.useMemo(function(){var selectedFlatRows=[];rows.forEach(function(row){var isSelected=selectSubRows?getRowIsSelected(row,selectedRowIds,getSubRows):!!selectedRowIds[row.id];row.isSelected=!!isSelected;row.isSomeSelected=isSelected===null;if(isSelected){selectedFlatRows.push(row);}});return selectedFlatRows;},[rows,selectSubRows,selectedRowIds,getSubRows]);var isAllRowsSelected=Boolean(Object.keys(nonGroupedRowsById).length&&Object.keys(selectedRowIds).length);var isAllPageRowsSelected=isAllRowsSelected;if(isAllRowsSelected){if(Object.keys(nonGroupedRowsById).some(function(id){return !selectedRowIds[id];})){isAllRowsSelected=false;}}if(!isAllRowsSelected){if(page&&page.length&&page.some(function(_ref5){var id=_ref5.id;return !selectedRowIds[id];})){isAllPageRowsSelected=false;}}var getAutoResetSelectedRows=useGetLatest(autoResetSelectedRows);useMountedLayoutEffect(function(){if(getAutoResetSelectedRows()){dispatch({type:actions.resetSelectedRows});}},[dispatch,data]);var toggleAllRowsSelected=React.useCallback(function(value){return dispatch({type:actions.toggleAllRowsSelected,value:value});},[dispatch]);var toggleAllPageRowsSelected=React.useCallback(function(value){return dispatch({type:actions.toggleAllPa
if(someSelected&&!allChildrenSelected){return;}if(getRowIsSelected(subRow,selectedRowIds,getSubRows)){someSelected=true;}else {allChildrenSelected=false;}});return allChildrenSelected?true:someSelected?null:false;}return false;}var defaultInitialRowStateAccessor=function defaultInitialRowStateAccessor(row){return {};};var defaultInitialCellStateAccessor=function defaultInitialCellStateAccessor(cell){return {};};// Actions
actions.setRowState='setRowState';actions.setCellState='setCellState';actions.resetRowState='resetRowState';var useRowState=function useRowState(hooks){hooks.stateReducers.push(reducer$9);hooks.useInstance.push(useInstance$9);hooks.prepareRow.push(prepareRow$4);};useRowState.pluginName='useRowState';function reducer$9(state,action,previousState,instance){var _instance$initialRowS=instance.initialRowStateAccessor,initialRowStateAccessor=_instance$initialRowS===void 0?defaultInitialRowStateAccessor:_instance$initialRowS,_instance$initialCell=instance.initialCellStateAccessor,initialCellStateAccessor=_instance$initialCell===void 0?defaultInitialCellStateAccessor:_instance$initialCell,rowsById=instance.rowsById;if(action.type===actions.init){return _extends({rowState:{}},state);}if(action.type===actions.resetRowState){return _extends({},state,{rowState:instance.initialState.rowState||{}});}if(action.type===actions.setRowState){var _extends2;var rowId=action.rowId,value=action.value;var oldRowState=typeof state.rowState[rowId]!=='undefined'?state.rowState[rowId]:initialRowStateAccessor(rowsById[rowId]);return _extends({},state,{rowState:_extends({},state.rowState,(_extends2={},_extends2[rowId]=functionalUpdate(value,oldRowState),_extends2))});}if(action.type===actions.setCellState){var _oldRowState$cellStat,_rowsById$_rowId,_rowsById$_rowId$cell,_extends3,_extends4;var _rowId=action.rowId,columnId=action.columnId,_value=action.value;var _oldRowState=typeof state.rowState[_rowId]!=='undefined'?state.rowState[_rowId]:initialRowStateAccessor(rowsById[_rowId]);var oldCellState=typeof(_oldRowState==null?void 0:(_oldRowState$cellStat=_oldRowState.cellState)==null?void 0:_oldRowState$cellStat[columnId])!=='undefined'?_oldRowState.cellState[columnId]:initialCellStateAccessor((_rowsById$_rowId=rowsById[_rowId])==null?void 0:(_rowsById$_rowId$cell=_rowsById$_rowId.cells)==null?void 0:_rowsById$_rowId$cell.find(function(cell){return cell.column.id===columnId;}));return _extends({},state,{rowState:_extends({},state.rowState,(_extends4={},_extends4[_rowId]=_extends({},_oldRowState,{cellState:_extends({},_oldRowState.cellState||{},(_extends3={},_extends3[columnId]=functionalUpdate(_value,oldCellState),_extends3))}),_extends4))});}}function useInstance$9(instance){var _instance$autoResetRo=instance.autoResetRowState,autoResetRowState=_instance$autoResetRo===void 0?true:_instance$autoResetRo,data=instance.data,dispatch=instance.dispatch;var setRowState=React.useCallback(function(rowId,value){return dispatch({type:actions.setRowState,rowId:rowId,value:value});},[dispatch]);var setCellState=React.useCallback(function(rowId,columnId,value){return dispatch({type:actions.setCellState,rowId:rowId,columnId:columnId,value:value});},[dispatch]);var getAutoResetRowState=useGetLatest(autoResetRowState);useMountedLayoutEffect(function(){if(getAutoResetRowState()){dispatch({type:actions.resetRowState});}},[data]);Object.assign(instance,{setRowState:setRowState,setCellState:setCellState});}function prepareRow$4(row,_ref){var instance=_ref.instance;var _instance$initialRowS2=instance.initialRowStateAccessor,initialRowStateAccessor=_instance$initialRowS2===void 0?defaultInitialRowStateAccessor:_instance$initialRowS2,_instance$initialCell2=instance.initialCellStateAccessor,initialCellStateAccessor=_instance$initialCell2===void 0?defaultInitialCellStateAccessor:_instance$initialCell2,rowState=instance.state.rowState;if(row){row.state=typeof rowState[row.id]!=='undefined'?rowState[row.id]:initialRowStateAccessor(row);row.setState=function(updater){return instance.setRowState(row.id,updater);};row.cells.forEach(function(cell){if(!row.state.cellState){row.state.cellState={};}cell.state=typeof row.state.cellState[cell.column.id]!=='undefined'?row.state.cellState[cell.column.id]:initialCellStateAccessor(cell);cell.setState=function(updater){return instance.setCellState(row.id,cell.column.id,updater);};});}}actions.resetColumnOrder='resetColumnOrder';actions.setColumnOrder='setColumnOrder';var useColumnOrder=function useColumnOrder(hooks){hooks.stateReducers.push(
if(!columnOrder||!columnOrder.length){return columns;}var columnOrderCopy=[].concat(columnOrder);// If there is an order, make a copy of the columns
var columnsCopy=[].concat(columns);// And make a new ordered array of the columns
var columnsInOrder=[];// Loop over the columns and place them in order into the new array
var _loop=function _loop(){var targetColumnId=columnOrderCopy.shift();var foundIndex=columnsCopy.findIndex(function(d){return d.id===targetColumnId;});if(foundIndex>-1){columnsInOrder.push(columnsCopy.splice(foundIndex,1)[0]);}};while(columnsCopy.length&&columnOrderCopy.length){_loop();}// If there are any columns left, add them to the end
return [].concat(columnsInOrder,columnsCopy);}function useInstance$a(instance){var dispatch=instance.dispatch;instance.setColumnOrder=React.useCallback(function(columnOrder){return dispatch({type:actions.setColumnOrder,columnOrder:columnOrder});},[dispatch]);}defaultColumn.canResize=true;// Actions
actions.columnStartResizing='columnStartResizing';actions.columnResizing='columnResizing';actions.columnDoneResizing='columnDoneResizing';actions.resetResize='resetResize';var useResizeColumns=function useResizeColumns(hooks){hooks.getResizerProps=[defaultGetResizerProps];hooks.getHeaderProps.push({style:{position:'relative'}});hooks.stateReducers.push(reducer$b);hooks.useInstance.push(useInstance$b);hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions$1);};var defaultGetResizerProps=function defaultGetResizerProps(props,_ref){var instance=_ref.instance,header=_ref.header;var dispatch=instance.dispatch;var onResizeStart=function onResizeStart(e,header){var isTouchEvent=false;if(e.type==='touchstart'){// lets not respond to multiple touches (e.g. 2 or 3 fingers)
if(e.touches&&e.touches.length>1){return;}isTouchEvent=true;}var headersToResize=getLeafHeaders(header);var headerIdWidths=headersToResize.map(function(d){return [d.id,d.totalWidth];});var clientX=isTouchEvent?Math.round(e.touches[0].clientX):e.clientX;var dispatchMove=function dispatchMove(clientXPos){dispatch({type:actions.columnResizing,clientX:clientXPos});};var dispatchEnd=function dispatchEnd(){return dispatch({type:actions.columnDoneResizing});};var handlersAndEvents={mouse:{moveEvent:'mousemove',moveHandler:function moveHandler(e){return dispatchMove(e.clientX);},upEvent:'mouseup',upHandler:function upHandler(e){document.removeEventListener('mousemove',handlersAndEvents.mouse.moveHandler);document.removeEventListener('mouseup',handlersAndEvents.mouse.upHandler);dispatchEnd();}},touch:{moveEvent:'touchmove',moveHandler:function moveHandler(e){if(e.cancelable){e.preventDefault();e.stopPropagation();}dispatchMove(e.touches[0].clientX);return false;},upEvent:'touchend',upHandler:function upHandler(e){document.removeEventListener(handlersAndEvents.touch.moveEvent,handlersAndEvents.touch.moveHandler);document.removeEventListener(handlersAndEvents.touch.upEvent,handlersAndEvents.touch.moveHandler);dispatchEnd();}}};var events=isTouchEvent?handlersAndEvents.touch:handlersAndEvents.mouse;var passiveIfSupported=passiveEventSupported()?{passive:false}:false;document.addEventListener(events.moveEvent,events.moveHandler,passiveIfSupported);document.addEventListener(events.upEvent,events.upHandler,passiveIfSupported);dispatch({type:actions.columnStartResizing,columnId:header.id,columnWidth:header.totalWidth,headerIdWidths:headerIdWidths,clientX:clientX});};return [props,{onMouseDown:function onMouseDown(e){return e.persist()||onResizeStart(e,header);},onTouchStart:function onTouchStart(e){return e.persist()||onResizeStart(e,header);},style:{cursor:'col-resize'},draggable:false,role:'separator'}];};useResizeColumns.pluginName='useResizeColumns';function reducer$b(state,action){if(action.type===actions.init){return _extends({columnResizing:{columnWidths:{}}},state);}if(action.type===actions.resetResize){return _extends({},state,{columnResizing:{columnWidths:{}}});}if(action.type===actions.columnStartResizing){var clientX=action.clientX,columnId=action.columnId,columnWidth=action.columnWidth,headerIdWidths=action.headerIdWidths;return _extends({},state,{columnResizing:_extends({},state.columnResizing,{startX:clientX,headerIdWidths:headerIdWidths,columnWidth:columnWidth,isResizingColumn:columnId})});}if(action.type===actions.columnResizing){var _clientX=action.clientX;var _state$columnResizing=state.columnResizing,startX=_state$columnResizing.startX,_columnWidth=_state$columnResizing.columnWidth,_state$columnResizing2=_state$columnResizing.headerIdWidths,_headerIdWidths=_state$columnResizing2===void 0?[]:_state$columnResizing2;var deltaX=_clientX-startX;var percentageDeltaX=deltaX/_columnWidth;var newColumnWidths={};_headerIdWidths.forEach(function(_ref2){var headerId=_ref2[0],headerWidth=_ref2[1];newColumnWidths[headerId]=Math.max(headerWidth+headerWidth*percentageDeltaX,0);});return _extends({},state,{columnResizing:_extends({},state.columnResizing,{columnWidths:_extends({},state.columnResizing.columnWidths,{},newColumnWidths)})});}if(action.type===actions.columnDoneResizing){return _extends({},state,{columnResizing:_extends({},state.columnResizing,{startX:null,isResizingColumn:null})});}}var useInstanceBeforeDimensions$1=function useInstanceBeforeDimensions(instance){var flatHeaders=instance.flatHeaders,disableResizing=instance.disableResizing,getHooks=instance.getHooks,columnResizing=instance.state.columnResizing;var getInstance=useGetLatest(instance);flatHeaders.forEach(function(header){var canResize=getFirstDefined(header.disableResizing===true?false:undefined,disableResizing===true?false:undefined,true);header.canResize=canResize;header.width=columnResizing.columnWidths[header.id]||header.originalWidth||header.width;header.isResizing=columnResizing.isResizingColumn===header.id;if(canResize){header.getResizerProps=makePropG
}}];};function reducer$c(state,action,previousState,instance){if(action.type==="init"){return _extends({gridLayout:{columnWidths:instance.columns.map(function(){return "auto";})}},state);}if(action.type==="columnStartResizing"){var columnId=action.columnId;var columnIndex=instance.visibleColumns.findIndex(function(col){return col.id===columnId;});var elWidth=getElementWidth(columnId);if(elWidth!==undefined){return _extends({},state,{gridLayout:_extends({},state.gridLayout,{columnId:columnId,columnIndex:columnIndex,startingWidth:elWidth})});}else {return state;}}if(action.type==="columnResizing"){var _state$gridLayout=state.gridLayout,_columnIndex=_state$gridLayout.columnIndex,startingWidth=_state$gridLayout.startingWidth,columnWidths=_state$gridLayout.columnWidths;var change=state.columnResizing.startX-action.clientX;var newWidth=startingWidth-change;var columnWidthsCopy=[].concat(columnWidths);columnWidthsCopy[_columnIndex]=newWidth+"px";return _extends({},state,{gridLayout:_extends({},state.gridLayout,{columnWidths:columnWidthsCopy})});}}function getElementWidth(columnId){var _document$getElementB;var width=(_document$getElementB=document.getElementById("header-cell-"+columnId))==null?void 0:_document$getElementB.offsetWidth;if(width!==undefined){return width;}}exports._UNSTABLE_usePivotColumns=_UNSTABLE_usePivotColumns;exports.actions=actions;exports.defaultColumn=defaultColumn;exports.defaultGroupByFn=defaultGroupByFn;exports.defaultOrderByFn=defaultOrderByFn;exports.defaultRenderer=defaultRenderer;exports.emptyRenderer=emptyRenderer;exports.ensurePluginOrder=ensurePluginOrder;exports.flexRender=flexRender;exports.functionalUpdate=functionalUpdate;exports.loopHooks=loopHooks;exports.makePropGetter=makePropGetter;exports.makeRenderer=makeRenderer;exports.reduceHooks=reduceHooks;exports.safeUseLayoutEffect=safeUseLayoutEffect;exports.useAbsoluteLayout=useAbsoluteLayout;exports.useAsyncDebounce=useAsyncDebounce;exports.useBlockLayout=useBlockLayout;exports.useColumnOrder=useColumnOrder;exports.useExpanded=useExpanded;exports.useFilters=useFilters;exports.useFlexLayout=useFlexLayout;exports.useGetLatest=useGetLatest;exports.useGlobalFilter=useGlobalFilter;exports.useGridLayout=useGridLayout;exports.useGroupBy=useGroupBy;exports.useMountedLayoutEffect=useMountedLayoutEffect;exports.usePagination=usePagination;exports.useResizeColumns=useResizeColumns;exports.useRowSelect=useRowSelect;exports.useRowState=useRowState;exports.useSortBy=useSortBy;exports.useTable=useTable;Object.defineProperty(exports,'__esModule',{value:true});});
});
3 years ago
var reactTable = createCommonjsModule(function (module) {
{module.exports=reactTable_development;}
});
3 years ago
const TableStyles = He.div `
padding-right: 1rem;
3 years ago
table {
width: 100%;
border-spacing: 0;
border: 1px solid var(--background-modifier-border);
3 years ago
tr {
:last-child {
td {
border-bottom: 0;
}
}
:hover {
background: var(--background-secondary);
}
}
3 years ago
th {
text-align: left;
background: var(--background-primary-alt);
}
3 years ago
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid var(--background-modifier-border);
}
}
3 years ago
tr:hover svg {
fill: var(--text-muted);
}
3 years ago
svg {
margin-left: 10px;
cursor: pointer;
fill: none;
stroke: none;
}
`;
const buildTableRows = (transactions, currencySymbol, updater) => {
const makeClone = (tx) => (react.createElement(react.Fragment, null,
react.createElement("svg", { onClick: () => {
updater.openExpenseModal('modify', tx);
}, width: "16", height: "16", version: "1.1", viewBox: "0 0 100 100", xmlns: "http://www.w3.org/2000/svg" },
react.createElement("path", { transform: "scale(5.5556)", d: "m15.533 0.63086c-0.474 0-0.94594 0.18813-1.3047 0.54688l-0.35156 0.35156 2.5938 2.5938 0.35156-0.35156c0.71861-0.71861 0.71861-1.8927 0-2.6113h-2e-3v-0.00195c-0.35848-0.33966-0.83006-0.52735-1.2871-0.52735zm-2.0957 1.457-0.0098 0.00195c-0.10358 0.020715-0.19358 0.06467-0.26172 0.13281l-11.668 11.67c-0.073201 0.0488-0.12225 0.12572-0.14453 0.21484l-0.7207 2.6973c-0.044708 0.15648 0.002068 0.32043 0.11328 0.43164 0.11121 0.11121 0.27321 0.15604 0.42969 0.11133l2.7012-0.71875 0.00391-2e-3c0.071076-0.02369 0.13619-0.06783 0.19727-0.12891l11.682-11.682c0.17582-0.17582 0.17582-0.45699 0-0.63281-0.17582-0.17582-0.45504-0.17582-0.63086 0l-11.547 11.564-1.3301-1.3301 11.564-11.564c0.1309-0.1309 0.17558-0.33127 0.08594-0.49609-0.07115-0.17891-0.24833-0.26953-0.41992-0.26953z" })),
react.createElement("svg", { onClick: () => {
updater.openExpenseModal('clone', tx);
}, width: "16", height: "16", version: "1.1", viewBox: "0 0 28 28", xmlns: "http://www.w3.org/2000/svg" },
react.createElement("path", { d: "m2 2h16v4h2v-4c0-1.1046-0.89543-2-2-2h-16c-1.1046 0-2 0.89543-2 2v16c0 1.1046 0.89543 2 2 2h4v-2h-4z" }),
react.createElement("path", { d: "m26 8h-16c-1.1046 0-2 0.89543-2 2v16c0 1.1046 0.89543 2 2 2h16c1.1046 0 2-0.89543 2-2v-16c0-1.1046-0.89543-2-2-2zm0 18h-16v-16h16z" }),
react.createElement("path", { d: "m17 24h2v-5h5v-2h-5v-5h-2v5h-5v2h5z" })),
react.createElement("svg", { onClick: () => updater.deleteTransaction(tx), width: "16", height: "16", version: "1.1", viewBox: "0 0 28 28", xmlns: "http://www.w3.org/2000/svg" },
react.createElement("path", { d: "m6.6465 5.2324-1.4141 1.4141 7.3535 7.3535-7.3535 7.3535 1.4141 1.4141 7.3535-7.3535 7.3535 7.3535 1.4141-1.4141-7.3535-7.3535 7.3535-7.3535-1.4141-1.4141-7.3535 7.3535-7.3535-7.3535z" }))));
const tableRows = transactions.map((tx) => {
const nonCommentLines = tx.value.expenselines.filter((line) => 'account' in line);
if (nonCommentLines.length < 2) {
// This should not make it past the parser, but this is necessary for type checking.
throw new Error('Unexpected transaction with fewer than two account lines');
}
if (nonCommentLines.length === 2) {
// If there are only two lines, then this is a simple 'from->to' transaction
return {
date: tx.value.date,
payee: tx.value.payee,
total: getTotal(tx, currencySymbol),
from: nonCommentLines[1].account,
to: nonCommentLines[0].account,
actions: makeClone(tx),
};
}
// Otherwise, there are multiple 'to' lines to consider
return {
date: tx.value.date,
payee: tx.value.payee,
total: getTotal(tx, currencySymbol),
from: nonCommentLines[nonCommentLines.length - 1].account,
to: react.createElement("i", null, "Multiple"),
actions: makeClone(tx),
};
});
// Sort so most recent transactions come first
tableRows.sort((a, b) => {
const aDate = window.moment(a.date);
const bDate = window.moment(b.date);
if (aDate.isSame(bDate)) {
return 0;
}
return aDate.isBefore(bDate) ? 1 : -1;
});
return tableRows;
};
// TODO: Clicking in a transaction should open it in the transaction modal and allow editing.
const RecentTransactionList = (props) => {
const data = react.useMemo(() => {
let filteredTransactions = filterTransactions(props.txCache.transactions, filterByStartDate(props.startDate));
filteredTransactions = filterTransactions(filteredTransactions, filterByEndDate(props.endDate));
if (filteredTransactions.length > 10) {
filteredTransactions = filteredTransactions.slice(-10);
}
return buildTableRows(filteredTransactions, props.currencySymbol, props.updater);
}, [props.txCache, props.startDate, props.endDate]);
return (react.createElement(react.Fragment, null,
react.createElement("h2", null, "Last 10 Transactions for Selected Dates"),
react.createElement(TransactionTable, { data: data })));
};
const TransactionList = (props) => {
const data = react.useMemo(() => {
// Filters are applied sequentially when they need to be and-ed together.
// This might not be the most efficient solution...
let filteredTransactions = filterTransactions(props.txCache.transactions, ...props.selectedAccounts.map((a) => filterByAccount(a)));
filteredTransactions = filterTransactions(filteredTransactions, filterByStartDate(props.startDate));
filteredTransactions = filterTransactions(filteredTransactions, filterByEndDate(props.endDate));
return buildTableRows(filteredTransactions, props.currencySymbol, props.updater);
}, [props.txCache, props.selectedAccounts, props.startDate, props.endDate]);
return react.createElement(TransactionTable, { data: data });
};
const TransactionTable = ({ data }) => {
if (data.length === 0) {
// TODO: Style and center this
return react.createElement("p", null, "No transactions for the selected time period.");
}
const columns = react.useMemo(() => [
{
Header: 'Date',
accessor: 'date',
},
{
Header: 'Payee',
accessor: 'payee',
},
{
Header: 'Total',
accessor: 'total',
},
{
Header: 'From Account',
accessor: 'from',
},
{
Header: 'To Account',
accessor: 'to',
},
{
Header: '',
accessor: 'actions',
},
], []);
const tableInstance = reactTable.useTable({ columns, data }, reactTable.useFilters, reactTable.useSortBy);
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance;
return (react.createElement(TableStyles, null,
react.createElement("table", Object.assign({}, getTableProps()),
react.createElement("thead", null, headerGroups.map((headerGroup) => (react.createElement("tr", Object.assign({}, headerGroup.getHeaderGroupProps()), headerGroup.headers.map((column) => (react.createElement("th", Object.assign({}, column.getHeaderProps(column.getSortByToggleProps())),
column.render('Header'),
react.createElement("span", null, column.isSorted ? (column.isSortedDesc ? ' ↑' : ' ↓') : '')))))))),
react.createElement("tbody", Object.assign({}, getTableBodyProps()), rows.map((row) => {
prepareRow(row);
return (react.createElement("tr", Object.assign({}, row.getRowProps()), row.cells.map((cell) => (react.createElement("td", Object.assign({}, cell.getCellProps()), cell.render('Cell'))))));
})))));
};
3 years ago
/*!
* Intro.js v4.3.0
* https://introjs.com
*
* Copyright (C) 2012-2021 Afshin Mehrabani (@afshinmeh).
* https://raw.githubusercontent.com/usablica/intro.js/master/license.md
*
* Date: Sat, 06 Nov 2021 14:22:05 GMT
*/
3 years ago
var intro = createCommonjsModule(function (module, exports) {
(function(global,factory){module.exports=factory();})(commonjsGlobal,function(){function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function(obj){return typeof obj;};}else {_typeof=function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* via: http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically
*
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/function mergeOptions(obj1,obj2){var obj3={};var attrname;for(attrname in obj1){obj3[attrname]=obj1[attrname];}for(attrname in obj2){obj3[attrname]=obj2[attrname];}return obj3;}/**
* Mark any object with an incrementing number
* used for keeping track of objects
*
* @param Object obj Any object or DOM Element
* @param String key
* @return Object
*/var stamp=function(){var keys={};return function stamp(obj){var key=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"introjs-stamp";// each group increments from 0
keys[key]=keys[key]||0;// stamp only once per object
if(obj[key]===undefined){// increment key for each new object
obj[key]=keys[key]++;}return obj[key];};}();/**
* Iterates arrays
*
* @param {Array} arr
* @param {Function} forEachFnc
* @param {Function} [completeFnc]
* @return {Null}
*/function forEach(arr,forEachFnc,completeFnc){// in case arr is an empty query selector node list
if(arr){for(var i=0,len=arr.length;i<len;i++){forEachFnc(arr[i],i);}}if(typeof completeFnc==="function"){completeFnc();}}/**
* DOMEvent Handles all DOM events
*
* methods:
*
* on - add event handler
* off - remove event
*/var DOMEvent=function(){function DOMEvent(){var events_key="introjs_event";/**
* Gets a unique ID for an event listener
*
* @param obj Object
* @param type event type
* @param listener Function
* @param context Object
* @return String
*/this._id=function(obj,type,listener,context){return type+stamp(listener)+(context?"_".concat(stamp(context)):"");};/**
* Adds event listener
*
* @param obj Object obj
* @param type String
* @param listener Function
* @param context Object
* @param useCapture Boolean
* @return null
*/this.on=function(obj,type,listener,context,useCapture){var id=this._id.apply(this,arguments);var handler=function handler(e){return listener.call(context||obj,e||window.event);};if("addEventListener"in obj){obj.addEventListener(type,handler,useCapture);}else if("attachEvent"in obj){obj.attachEvent("on".concat(type),handler);}obj[events_key]=obj[events_key]||{};obj[events_key][id]=handler;};/**
* Removes event listener
*
* @param obj Object
* @param type String
* @param listener Function
* @param context Object
* @param useCapture Boolean
* @return null
*/this.off=function(obj,type,listener,context,useCapture){var id=this._id.apply(this,arguments);var handler=obj[events_key]&&obj[events_key][id];if(!handler){return;}if("removeEventListener"in obj){obj.removeEventListener(type,handler,useCapture);}else if("detachEvent"in obj){obj.detachEvent("on".concat(type),handler);}obj[events_key][id]=null;};}return new DOMEvent();}();var commonjsGlobal$1=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof commonjsGlobal!=='undefined'?commonjsGlobal:typeof self!=='undefined'?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports;}var check=function(it){return it&&it.Math==Math&&it;};// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1=// eslint-disable-next-line es/no-global-this -- safe
check(typeof globalThis=='object'&&globalThis)||check(typeof window=='object'&&window)||// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self=='object'&&self)||check(typeof commonjsGlobal$1=='object'&&commonjsGlobal$1)||// eslint-disable-next-line no-new-func -- fallback
function(){return this;}()||Function('return this')();var fails=function(exec){try{return !!exec();}catch(error){return true;}};// Detect IE8's incomplete defineProperty implementation
var descriptors=!fails(function(){// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({},1,{get:function(){return 7;}})[1]!=7;});var call$2=Function.prototype.call;var functionCall=call$2.bind?call$2.bind(call$2):function(){return call$2.apply(call$2,arguments);};var $propertyIsEnumerable={}.propertyIsEnumerable;// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$1=Object.getOwnPropertyDescriptor;// Nashorn ~ JDK8 bug
var NASHORN_BUG=getOwnPropertyDescriptor$1&&!$propertyIsEnumerable.call({1:2},1);// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
var f$4=NASHORN_BUG?function propertyIsEnumerable(V){var descriptor=getOwnPropertyDescriptor$1(this,V);return !!descriptor&&descriptor.enumerable;}:$propertyIsEnumerable;var objectPropertyIsEnumerable={f:f$4};var createPropertyDescriptor=function(bitmap,value){return {enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value};};var FunctionPrototype$2=Function.prototype;var bind$2=FunctionPrototype$2.bind;var call$1=FunctionPrototype$2.call;var callBind=bind$2&&bind$2.bind(call$1);var functionUncurryThis=bind$2?function(fn){return fn&&callBind(call$1,fn);}:function(fn){return fn&&function(){return call$1.apply(fn,arguments);};};var toString$1=functionUncurryThis({}.toString);var stringSlice$5=functionUncurryThis(''.slice);var classofRaw=function(it){return stringSlice$5(toString$1(it),8,-1);};var Object$4=global_1.Object;var split=functionUncurryThis(''.split);// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject=fails(function(){// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !Object$4('z').propertyIsEnumerable(0);})?function(it){return classofRaw(it)=='String'?split(it,''):Object$4(it);}:Object$4;var TypeError$c=global_1.TypeError;// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible=function(it){if(it==undefined)throw TypeError$c("Can't call method on "+it);return it;};// toObject with fallback for non-array-like ES3 strings
var toIndexedObject=function(it){return indexedObject(requireObjectCoercible(it));};// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
var isCallable=function(argument){return typeof argument=='function';};var isObject=function(it){return typeof it=='object'?it!==null:isCallable(it);};var aFunction=function(argument){return isCallable(argument)?argument:undefined;};var getBuiltIn=function(namespace,method){return arguments.length<2?aFunction(global_1[namespace]):global_1[namespace]&&global_1[namespace][method];};var objectIsPrototypeOf=functionUncurryThis({}.isPrototypeOf);var engineUserAgent=getBuiltIn('navigator','userAgent')||'';var process=global_1.process;var Deno=global_1.Deno;var versions=process&&process.versions||Deno&&Deno.version;var v8=versions&&versions.v8;var match,version$1;if(v8){match=v8.split('.');// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version$1=match[0]>0&&match[0]<4?1:+(match[0]+match[1]);}// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if(!version$1&&engineUserAgent){match=engineUserAgent.match(/Edge\/(\d+)/);if(!match||match[1]>=74){match=engineUserAgent.match(/Chrome\/(\d+)/);if(match)version$1=+match[1];}}var engineV8Version=version$1;/* eslint-disable es/no-symbol -- required for testing */ // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
var nativeSymbol=!!Object.getOwnPropertySymbols&&!fails(function(){var symbol=Symbol();// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
return !String(symbol)||!(Object(symbol)instanceof Symbol)||// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham&&engineV8Version&&engineV8Version<41;});/* eslint-disable es/no-symbol -- required for testing */var useSymbolAsUid=nativeSymbol&&!Symbol.sham&&typeof Symbol.iterator=='symbol';var Object$3=global_1.Object;var isSymbol=useSymbolAsUid?function(it){return typeof it=='symbol';}:function(it){var $Symbol=getBuiltIn('Symbol');return isCallable($Symbol)&&objectIsPrototypeOf($Symbol.prototype,Object$3(it));};var String$3=global_1.String;var tryToString=function(argument){try{return String$3(argument);}catch(error){return 'Object';}};var TypeError$b=global_1.TypeError;// `Assert: IsCallable(argument) is true`
var aCallable=function(argument){if(isCallable(argument))return argument;throw TypeError$b(tryToString(argument)+' is not a function');};// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
var getMethod=function(V,P){var func=V[P];return func==null?undefined:aCallable(func);};var TypeError$a=global_1.TypeError;// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
var ordinaryToPrimitive=function(input,pref){var fn,val;if(pref==='string'&&isCallable(fn=input.toString)&&!isObject(val=functionCall(fn,input)))return val;if(isCallable(fn=input.valueOf)&&!isObject(val=functionCall(fn,input)))return val;if(pref!=='string'&&isCallable(fn=input.toString)&&!isObject(val=functionCall(fn,input)))return val;throw TypeError$a("Can't convert object to primitive value");};// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty$1=Object.defineProperty;var setGlobal=function(key,value){try{defineProperty$1(global_1,key,{value:value,configurable:true,writable:true});}catch(error){global_1[key]=value;}return value;};var SHARED='__core-js_shared__';var store$1=global_1[SHARED]||setGlobal(SHARED,{});var sharedStore=store$1;var shared=createCommonjsModule(function(module){(module.exports=function(key,value){return sharedStore[key]||(sharedStore[key]=value!==undefined?value:{});})('versions',[]).push({version:'3.19.1',mode:'global',copyright:'© 2021 Denis Pushkarev (zloirock.ru)'});});var Object$2=global_1.Object;// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
var toObject=function(argument){return Object$2(requireObjectCoercible(argument));};var hasOwnProperty=functionUncurryThis({}.hasOwnProperty);// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
var hasOwnProperty_1=Object.hasOwn||function hasOwn(it,key){return hasOwnProperty(toObject(it),key);};var id=0;var postfix=Math.random();var toString=functionUncurryThis(1.0.toString);var uid=function(key){return 'Symbol('+(key===undefined?'':key)+')_'+toString(++id+postfix,36);};var WellKnownSymbolsStore=shared('wks');var Symbol$1=global_1.Symbol;var symbolFor=Symbol$1&&Symbol$1['for'];var createWellKnownSymbol=useSymbolAsUid?Symbol$1:Symbol$1&&Symbol$1.withoutSetter||uid;var wellKnownSymbol=function(name){if(!hasOwnProperty_1(WellKnownSymbolsStore,name)||!(nativeSymbol||typeof WellKnownSymbolsStore[name]=='string')){var description='Symbol.'+name;if(nativeSymbol&&hasOwnProperty_1(Symbol$1,name)){WellKnownSymbolsStore[name]=Symbol$1[name];}else if(useSymbolAsUid&&symbolFor){WellKnownSymbolsStore[name]=symbolFor(description);}else {WellKnownSymbolsStore[name]=createWellKnownSymbol(description);}}return WellKnownSymbolsStore[name];};var TypeError$9=global_1.TypeError;var TO_PRIMITIVE=wellKnownSymbol('toPrimitive');// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
var toPrimitive=function(input,pref){if(!isObject(input)||isSymbol(input))return input;var exoticToPrim=getMethod(input,TO_PRIMITIVE);var result;if(exoticToPrim){if(pref===undefined)pref='default';result=functionCall(exoticToPrim,input,pref);if(!isObject(result)||isSymbol(result))return result;throw TypeError$9("Can't convert object to primitive value");}if(pref===undefined)pref='number';return ordinaryToPrimitive(input,pref);};// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
var toPropertyKey=function(argument){var key=toPrimitive(argument,'string');return isSymbol(key)?key:key+'';};var document$1=global_1.document;// typeof document.createElement is 'object' in old IE
var EXISTS$1=isObject(document$1)&&isObject(document$1.createElement);var documentCreateElement=function(it){return EXISTS$1?document$1.createElement(it):{};};// Thank's IE8 for his funny defineProperty
var ie8DomDefine=!descriptors&&!fails(function(){// eslint-disable-next-line es/no-object-defineproperty -- requied for testing
return Object.defineProperty(documentCreateElement('div'),'a',{get:function(){return 7;}}).a!=7;});// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
var f$3=descriptors?$getOwnPropertyDescriptor:function getOwnPropertyDescriptor(O,P){O=toIndexedObject(O);P=toPropertyKey(P);if(ie8DomDefine)try{return $getOwnPropertyDescriptor(O,P);}catch(error){/* empty */}if(hasOwnProperty_1(O,P))return createPropertyDescriptor(!functionCall(objectPropertyIsEnumerable.f,O,P),O[P]);};var objectGetOwnPropertyDescriptor={f:f$3};var String$2=global_1.String;var TypeError$8=global_1.TypeError;// `Assert: Type(argument) is Object`
var anObject=function(argument){if(isObject(argument))return argument;throw TypeError$8(String$2(argument)+' is not an object');};var TypeError$7=global_1.TypeError;// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty=Object.defineProperty;// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
var f$2=descriptors?$defineProperty:function defineProperty(O,P,Attributes){anObject(O);P=toPropertyKey(P);anObject(Attributes);if(ie8DomDefine)try{return $defineProperty(O,P,Attributes);}catch(error){/* empty */}if('get'in Attributes||'set'in Attributes)throw TypeError$7('Accessors not supported');if('value'in Attributes)O[P]=Attributes.value;return O;};var objectDefineProperty={f:f$2};var createNonEnumerableProperty=descriptors?function(object,key,value){return objectDefineProperty.f(object,key,createPropertyDescriptor(1,value));}:function(object,key,value){object[key]=value;return object;};var functionToString=functionUncurryThis(Function.toString);// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if(!isCallable(sharedStore.inspectSource)){sharedStore.inspectSource=function(it){return functionToString(it);};}var inspectSource=sharedStore.inspectSource;var WeakMap$1=global_1.WeakMap;var nativeWeakMap=isCallable(WeakMap$1)&&/native code/.test(inspectSource(WeakMap$1));var keys=shared('keys');var sharedKey=function(key){return keys[key]||(keys[key]=uid(key));};var hiddenKeys$1={};var OBJECT_ALREADY_INITIALIZED='Object already initialized';var TypeError$6=global_1.TypeError;var WeakMap=global_1.WeakMap;var set,get,has;var enforce=function(it){return has(it)?get(it):set(it,{});};var getterFor=function(TYPE){return function(it){var state;if(!isObject(it)||(state=get(it)).type!==TYPE){throw TypeError$6('Incompatible receiver, '+TYPE+' required');}return state;};};if(nativeWeakMap||sharedStore.state){var store=sharedStore.state||(sharedStore.state=new WeakMap());var wmget=functionUncurryThis(store.get);var wmhas=functionUncurryThis(store.has);var wmset=functionUncurryThis(store.set);set=function(it,metadata){if(wmhas(store,it))throw new TypeError$6(OBJECT_ALREADY_INITIALIZED);metadata.facade=it;wmset(store,it,metadata);return metadata;};get=function(it){return wmget(store,it)||{};};has=function(it){return wmhas(store,it);};}else {var STATE=sharedKey('state');hiddenKeys$1[STATE]=true;set=function(it,metadata){if(hasOwnProperty_1(it,STATE))throw new TypeError$6(OBJECT_ALREADY_INITIALIZED);metadata.facade=it;createNonEnumerableProperty(it,STATE,metadata);return metadata;};get=function(it){return hasOwnProperty_1(it,STATE)?it[STATE]:{};};has=function(it){return hasOwnProperty_1(it,STATE);};}var internalState={set:set,get:get,has:has,enforce:enforce,getterFor:getterFor};var FunctionPrototype$1=Function.prototype;// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor=descriptors&&Object.getOwnPropertyDescriptor;var EXISTS=hasOwnProperty_1(FunctionPrototype$1,'name');// additional protection from minified / mangled / dropped function names
var PROPER=EXISTS&&function something(){/* empty */}.name==='something';var CONFIGURABLE=EXISTS&&(!descriptors||descriptors&&getDescriptor(FunctionPrototype$1,'name').configurable);var functionName={EXISTS:EXISTS,PROPER:PROPER,CONFIGURABLE:CONFIGURABLE};var redefine=createCommonjsModule(function(module){var CONFIGURABLE_FUNCTION_NAME=functionName.CONFIGURABLE;var getInternalState=internalState.get;var enforceInternalState=internalState.enforce;var TEMPLATE=String(String).split('String');(module.exports=function(O,key,value,options){var unsafe=options?!!options.unsafe:false;var simple=options?!!options.enumerable:false;var noTargetGet=options?!!options.noTargetGet:false;var name=options&&options.name!==undefined?options.name:key;var state;if(isCallable(value)){if(String(name).slice(0,7)==='Symbol('){name='['+String(name).replace(/^Symbol\(([^)]*)\)/,'$1')+']';}if(!hasOwnProperty_1(value,'name')||CONFIGURABLE_FUNCTION_NAME&&value.name!==name){createNonEnumerableProperty(value,'name',name);}state=enforceInternalState(value);if(!state.source){state.source=TEMPLATE.join(typeof name=='string'?name:'');}}if(O===global_1){if(simple)O[key]=value;else setGlobal(key,value);return;}else if(!unsafe){delete O[key];}else if(!noTargetGet&&O[key]){simple=true;}if(simple)O[key]=value;else createNonEnumerableProperty(O,key,value);// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype,'toString',function toString(){return isCallable(this)&&getInternalState(this).source||inspectSource(this);});});var ceil=Math.ceil;var floor$2=Math.floor;// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
var toIntegerOrInfinity=function(argument){var number=+argument;// eslint-disable-next-line no-self-compare -- safe
return number!==number||number===0?0:(number>0?floor$2:ceil)(number);};var max$3=Math.max;var min$4=Math.min;// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
var toAbsoluteIndex=function(index,length){var integer=toIntegerOrInfinity(index);return integer<0?max$3(integer+length,0):min$4(integer,length);};var min$3=Math.min;// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
var toLength=function(argument){return argument>0?min$3(toIntegerOrInfinity(argument),0x1FFFFFFFFFFFFF):0;// 2 ** 53 - 1 == 9007199254740991
};// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
var lengthOfArrayLike=function(obj){return toLength(obj.length);};// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod$2=function(IS_INCLUDES){return function($this,el,fromIndex){var O=toIndexedObject($this);var length=lengthOfArrayLike(O);var index=toAbsoluteIndex(fromIndex,length);var value;// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if(IS_INCLUDES&&el!=el)while(length>index){value=O[index++];// eslint-disable-next-line no-self-compare -- NaN check
if(value!=value)return true;// Array#indexOf ignores holes, Array#includes - not
}else for(;length>index;index++){if((IS_INCLUDES||index in O)&&O[index]===el)return IS_INCLUDES||index||0;}return !IS_INCLUDES&&-1;};};var arrayIncludes={// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes:createMethod$2(true),// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf:createMethod$2(false)};var indexOf$1=arrayIncludes.indexOf;var push$4=functionUncurryThis([].push);var objectKeysInternal=function(object,names){var O=toIndexedObject(object);var i=0;var result=[];var key;for(key in O)!hasOwnProperty_1(hiddenKeys$1,key)&&hasOwnProperty_1(O,key)&&push$4(result,key);// Don't enum bug & hidden keys
while(names.length>i)if(hasOwnProperty_1(O,key=names[i++])){~indexOf$1(result,key)||push$4(result,key);}return result;};// IE8- don't enum bug keys
var enumBugKeys=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'];var hiddenKeys=enumBugKeys.concat('length','prototype');// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
var f$1=Object.getOwnPropertyNames||function getOwnPropertyNames(O){return objectKeysInternal(O,hiddenKeys);};var objectGetOwnPropertyNames={f:f$1};// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
var f=Object.getOwnPropertySymbols;var objectGetOwnPropertySymbols={f:f};var concat$2=functionUncurryThis([].concat);// all object keys, includes non-enumerable and symbols
var ownKeys=getBuiltIn('Reflect','ownKeys')||function ownKeys(it){var keys=objectGetOwnPropertyNames.f(anObject(it));var getOwnPropertySymbols=objectGetOwnPropertySymbols.f;return getOwnPropertySymbols?concat$2(keys,getOwnPropertySymbols(it)):keys;};var copyConstructorProperties=function(target,source){var keys=ownKeys(source);var defineProperty=objectDefineProperty.f;var getOwnPropertyDescriptor=objectGetOwnPropertyDescriptor.f;for(var i=0;i<keys.length;i++){var key=keys[i];if(!hasOwnProperty_1(target,key))defineProperty(target,key,getOwnPropertyDescriptor(source,key));}};var replacement=/#|\.prototype\./;var isForced=function(feature,detection){var value=data[normalize(feature)];return value==POLYFILL?true:value==NATIVE?false:isCallable(detection)?fails(detection):!!detection;};var normalize=isForced.normalize=function(string){return String(string).replace(replacement,'.').toLowerCase();};var data=isForced.data={};var NATIVE=isForced.NATIVE='N';var POLYFILL=isForced.POLYFILL='P';var isForced_1=isForced;var getOwnPropertyDescriptor=objectGetOwnPropertyDescriptor.f;/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/var _export=function(options,source){var TARGET=options.target;var GLOBAL=options.global;var STATIC=options.stat;var FORCED,target,key,targetProperty,sourceProperty,descriptor;if(GLOBAL){target=global_1;}else if(STATIC){target=global_1[TARGET]||setGlobal(TARGET,{});}else {target=(global_1[TARGET]||{}).prototype;}if(target)for(key in source){sourceProperty=source[key];if(options.noTargetGet){descriptor=getOwnPropertyDescriptor(target,key);targetProperty=descriptor&&descriptor.value;}else targetProperty=target[key];FORCED=isForced_1(GLOBAL?key:TARGET+(STATIC?'.':'#')+key,options.forced);// contained in target
if(!FORCED&&targetProperty!==undefined){if(typeof sourceProperty==typeof targetProperty)continue;copyConstructorProperties(sourceProperty,targetProperty);}// add a flag to not completely full polyfills
if(options.sham||targetProperty&&targetProperty.sham){createNonEnumerableProperty(sourceProperty,'sham',true);}// extend global
redefine(target,key,sourceProperty,options);}};var TO_STRING_TAG$1=wellKnownSymbol('toStringTag');var test$1={};test$1[TO_STRING_TAG$1]='z';var toStringTagSupport=String(test$1)==='[object z]';var TO_STRING_TAG=wellKnownSymbol('toStringTag');var Object$1=global_1.Object;// ES3 wrong here
var CORRECT_ARGUMENTS=classofRaw(function(){return arguments;}())=='Arguments';// fallback for IE11 Script Access Denied error
var tryGet=function(it,key){try{return it[key];}catch(error){/* empty */}};// getting tag from ES6+ `Object.prototype.toString`
var classof=toStringTagSupport?classofRaw:function(it){var O,tag,result;return it===undefined?'Undefined':it===null?'Null'// @@toStringTag case
:typeof(tag=tryGet(O=Object$1(it),TO_STRING_TAG))=='string'?tag// builtinTag case
:CORRECT_ARGUMENTS?classofRaw(O)// ES3 arguments fallback
:(result=classofRaw(O))=='Object'&&isCallable(O.callee)?'Arguments':result;};var String$1=global_1.String;var toString_1=function(argument){if(classof(argument)==='Symbol')throw TypeError('Cannot convert a Symbol value to a string');return String$1(argument);};// `RegExp.prototype.flags` getter implementation
// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
var regexpFlags=function(){var that=anObject(this);var result='';if(that.global)result+='g';if(that.ignoreCase)result+='i';if(that.multiline)result+='m';if(that.dotAll)result+='s';if(that.unicode)result+='u';if(that.sticky)result+='y';return result;};// babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError
var $RegExp$2=global_1.RegExp;var UNSUPPORTED_Y$2=fails(function(){var re=$RegExp$2('a','y');re.lastIndex=2;return re.exec('abcd')!=null;});var BROKEN_CARET=fails(function(){// https://bugzilla.mozilla.org/show_bug.cgi?id=773687
var re=$RegExp$2('^r','gy');re.lastIndex=2;return re.exec('str')!=null;});var regexpStickyHelpers={UNSUPPORTED_Y:UNSUPPORTED_Y$2,BROKEN_CARET:BROKEN_CARET};// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
var objectKeys=Object.keys||function keys(O){return objectKeysInternal(O,enumBugKeys);};// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
var objectDefineProperties=descriptors?Object.defineProperties:function defineProperties(O,Properties){anObject(O);var props=toIndexedObject(Properties);var keys=objectKeys(Properties);var length=keys.length;var index=0;var key;while(length>index)objectDefineProperty.f(O,key=keys[index++],props[key]);return O;};var html=getBuiltIn('document','documentElement');/* global ActiveXObject -- old IE, WSH */var GT='>';var LT='<';var PROTOTYPE='prototype';var SCRIPT='script';var IE_PROTO=sharedKey('IE_PROTO');var EmptyConstructor=function(){/* empty */};var scriptTag=function(content){return LT+SCRIPT+GT+content+LT+'/'+SCRIPT+GT;};// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX=function(activeXDocument){activeXDocument.write(scriptTag(''));activeXDocument.close();var temp=activeXDocument.parentWindow.Object;activeXDocument=null;// avoid memory leak
return temp;};// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame=function(){// Thrash, waste and sodomy: IE GC bug
var iframe=documentCreateElement('iframe');var JS='java'+SCRIPT+':';var iframeDocument;iframe.style.display='none';html.appendChild(iframe);// https://github.com/zloirock/core-js/issues/475
iframe.src=String(JS);iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write(scriptTag('document.F=Object'));iframeDocument.close();return iframeDocument.F;};// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;var NullProtoObject=function(){try{activeXDocument=new ActiveXObject('htmlfile');}catch(error){/* ignore */}NullProtoObject=typeof document!='undefined'?document.domain&&activeXDocument?NullProtoObjectViaActiveX(activeXDocument)// old IE
:NullProtoObjectViaIFrame():NullProtoObjectViaActiveX(activeXDocument);// WSH
var length=enumBugKeys.length;while(length--)delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];return NullProtoObject();};hiddenKeys$1[IE_PROTO]=true;// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
var objectCreate=Object.create||function create(O,Properties){var result;if(O!==null){EmptyConstructor[PROTOTYPE]=anObject(O);result=new EmptyConstructor();EmptyConstructor[PROTOTYPE]=null;// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO]=O;}else result=NullProtoObject();return Properties===undefined?result:objectDefineProperties(result,Properties);};// babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError
var $RegExp$1=global_1.RegExp;var regexpUnsupportedDotAll=fails(function(){var re=$RegExp$1('.','s');return !(re.dotAll&&re.exec('\n')&&re.flags==='s');});// babel-minify and Closure Compiler transpiles RegExp('(?<a>b)', 'g') -> /(?<a>b)/g and it causes SyntaxError
var $RegExp=global_1.RegExp;var regexpUnsupportedNcg=fails(function(){var re=$RegExp('(?<a>b)','g');return re.exec('b').groups.a!=='b'||'b'.replace(re,'$<a>c')!=='bc';});/* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */ /* eslint-disable regexp/no-useless-quantifier -- testing */var getInternalState=internalState.get;var nativeReplace=shared('native-string-replace',String.prototype.replace);var nativeExec=RegExp.prototype.exec;var patchedExec=nativeExec;var charAt$3=functionUncurryThis(''.charAt);var indexOf=functionUncurryThis(''.indexOf);var replace$1=functionUncurryThis(''.replace);var stringSlice$4=functionUncurryThis(''.slice);var UPDATES_LAST_INDEX_WRONG=function(){var re1=/a/;var re2=/b*/g;functionCall(nativeExec,re1,'a');functionCall(nativeExec,re2,'a');return re1.lastIndex!==0||re2.lastIndex!==0;}();var UNSUPPORTED_Y$1=regexpStickyHelpers.UNSUPPORTED_Y||regexpStickyHelpers.BROKEN_CARET;// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED=/()??/.exec('')[1]!==undefined;var PATCH=UPDATES_LAST_INDEX_WRONG||NPCG_INCLUDED||UNSUPPORTED_Y$1||regexpUnsupportedDotAll||regexpUnsupportedNcg;if(PATCH){// eslint-disable-next-line max-statements -- TODO
patchedExec=function exec(string){var re=this;var state=getInternalState(re);var str=toString_1(string);var raw=state.raw;var result,reCopy,lastIndex,match,i,object,group;if(raw){raw.lastIndex=re.lastIndex;result=functionCall(patchedExec,raw,str);re.lastIndex=raw.lastIndex;return result;}var groups=state.groups;var sticky=UNSUPPORTED_Y$1&&re.sticky;var flags=functionCall(regexpFlags,re);var source=re.source;var charsAdded=0;var strCopy=str;if(sticky){flags=replace$1(flags,'y','');if(indexOf(flags,'g')===-1){flags+='g';}strCopy=stringSlice$4(str,re.lastIndex);// Support anchored sticky behavior.
if(re.lastIndex>0&&(!re.multiline||re.multiline&&charAt$3(str,re.lastIndex-1)!=='\n')){source='(?: '+source+')';strCopy=' '+strCopy;charsAdded++;}// ^(? + rx + ) is needed, in combination with some str slicing, to
// simulate the 'y' flag.
reCopy=new RegExp('^(?:'+source+')',flags);}if(NPCG_INCLUDED){reCopy=new RegExp('^'+source+'$(?!\\s)',flags);}if(UPDATES_LAST_INDEX_WRONG)lastIndex=re.lastIndex;match=functionCall(nativeExec,sticky?reCopy:re,strCopy);if(sticky){if(match){match.input=stringSlice$4(match.input,charsAdded);match[0]=stringSlice$4(match[0],charsAdded);match.index=re.lastIndex;re.lastIndex+=match[0].length;}else re.lastIndex=0;}else if(UPDATES_LAST_INDEX_WRONG&&match){re.lastIndex=re.global?match.index+match[0].length:lastIndex;}if(NPCG_INCLUDED&&match&&match.length>1){// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
functionCall(nativeReplace,match[0],reCopy,function(){for(i=1;i<arguments.length-2;i++){if(arguments[i]===undefined)match[i]=undefined;}});}if(match&&groups){match.groups=object=objectCreate(null);for(i=0;i<groups.length;i++){group=groups[i];object[group[0]]=match[group[1]];}}return match;};}var regexpExec=patchedExec;// `RegExp.prototype.exec` method
// https://tc39.es/ecma262/#sec-regexp.prototype.exec
_export({target:'RegExp',proto:true,forced:/./.exec!==regexpExec},{exec:regexpExec});// TODO: Remove from `core-js@4` since it's moved to entry points
var SPECIES$4=wellKnownSymbol('species');var RegExpPrototype$1=RegExp.prototype;var fixRegexpWellKnownSymbolLogic=function(KEY,exec,FORCED,SHAM){var SYMBOL=wellKnownSymbol(KEY);var DELEGATES_TO_SYMBOL=!fails(function(){// String methods call symbol-named RegEp methods
var O={};O[SYMBOL]=function(){return 7;};return ''[KEY](O)!=7;});var DELEGATES_TO_EXEC=DELEGATES_TO_SYMBOL&&!fails(function(){// Symbol-named RegExp methods call .exec
var execCalled=false;var re=/a/;if(KEY==='split'){// We can't use real regex here since it causes deoptimization
// and serious performance degradation in V8
// https://github.com/zloirock/core-js/issues/306
re={};// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor={};re.constructor[SPECIES$4]=function(){return re;};re.flags='';re[SYMBOL]=/./[SYMBOL];}re.exec=function(){execCalled=true;return null;};re[SYMBOL]('');return !execCalled;});if(!DELEGATES_TO_SYMBOL||!DELEGATES_TO_EXEC||FORCED){var uncurriedNativeRegExpMethod=functionUncurryThis(/./[SYMBOL]);var methods=exec(SYMBOL,''[KEY],function(nativeMethod,regexp,str,arg2,forceStringMethod){var uncurriedNativeMethod=functionUncurryThis(nativeMethod);var $exec=regexp.exec;if($exec===regexpExec||$exec===RegExpPrototype$1.exec){if(DELEGATES_TO_SYMBOL&&!forceStringMethod){// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return {done:true,value:uncurriedNativeRegExpMethod(regexp,str,arg2)};}return {done:true,value:uncurriedNativeMethod(str,regexp,arg2)};}return {done:false};});redefine(String.prototype,KEY,methods[0]);redefine(RegExpPrototype$1,SYMBOL,methods[1]);}if(SHAM)createNonEnumerableProperty(RegExpPrototype$1[SYMBOL],'sham',true);};var charAt$2=functionUncurryThis(''.charAt);var charCodeAt=functionUncurryThis(''.charCodeAt);var stringSlice$3=functionUncurryThis(''.slice);var createMethod$1=function(CONVERT_TO_STRING){return function($this,pos){var S=toString_1(requireObjectCoercible($this));var position=toIntegerOrInfinity(pos);var size=S.length;var first,second;if(position<0||position>=size)return CONVERT_TO_STRING?'':undefined;first=charCodeAt(S,position);return first<0xD800||first>0xDBFF||position+1===size||(second=charCodeAt(S,position+1))<0xDC00||second>0xDFFF?CONVERT_TO_STRING?charAt$2(S,position):first:CONVERT_TO_STRING?stringSlice$3(S,position,position+2):(first-0xD800<<10)+(second-0xDC00)+0x10000;};};var stringMultibyte={// `String.prototype.codePointAt` method
// https://tc39.es/ecma262/#sec-string.prototype.codepointat
codeAt:createMethod$1(false),// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt:createMethod$1(true)};var charAt$1=stringMultibyte.charAt;// `AdvanceStringIndex` abstract operation
// https://tc39.es/ecma262/#sec-advancestringindex
var advanceStringIndex=function(S,index,unicode){return index+(unicode?charAt$1(S,index).length:1);};var TypeError$5=global_1.TypeError;// `RegExpExec` abstract operation
// https://tc39.es/ecma262/#sec-regexpexec
var regexpExecAbstract=function(R,S){var exec=R.exec;if(isCallable(exec)){var result=functionCall(exec,R,S);if(result!==null)anObject(result);return result;}if(classofRaw(R)==='RegExp')return functionCall(regexpExec,R,S);throw TypeError$5('RegExp#exec called on incompatible receiver');};// @@match logic
fixRegexpWellKnownSymbolLogic('match',function(MATCH,nativeMatch,maybeCallNative){return [// `String.prototype.match` method
// https://tc39.es/ecma262/#sec-string.prototype.match
function match(regexp){var O=requireObjectCoercible(this);var matcher=regexp==undefined?undefined:getMethod(regexp,MATCH);return matcher?functionCall(matcher,regexp,O):new RegExp(regexp)[MATCH](toString_1(O));},// `RegExp.prototype[@@match]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@match
function(string){var rx=anObject(this);var S=toString_1(string);var res=maybeCallNative(nativeMatch,rx,S);if(res.done)return res.value;if(!rx.global)return regexpExecAbstract(rx,S);var fullUnicode=rx.unicode;rx.lastIndex=0;var A=[];var n=0;var result;while((result=regexpExecAbstract(rx,S))!==null){var matchStr=toString_1(result[0]);A[n]=matchStr;if(matchStr==='')rx.lastIndex=advanceStringIndex(S,toLength(rx.lastIndex),fullUnicode);n++;}return n===0?null:A;}];});// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es/no-array-isarray -- safe
var isArray=Array.isArray||function isArray(argument){return classofRaw(argument)=='Array';};var createProperty=function(object,key,value){var propertyKey=toPropertyKey(key);if(propertyKey in object)objectDefineProperty.f(object,propertyKey,createPropertyDescriptor(0,value));else object[propertyKey]=value;};var noop=function(){/* empty */};var empty=[];var construct=getBuiltIn('Reflect','construct');var constructorRegExp=/^\s*(?:class|function)\b/;var exec$1=functionUncurryThis(constructorRegExp.exec);var INCORRECT_TO_STRING=!constructorRegExp.exec(noop);var isConstructorModern=function(argument){if(!isCallable(argument))return false;try{construct(noop,empty,argument);return true;}catch(error){return false;}};var isConstructorLegacy=function(argument){if(!isCallable(argument))return false;switch(classof(argument)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return false;// we can't check .prototype since constructors produced by .bind haven't it
}return INCORRECT_TO_STRING||!!exec$1(constructorRegExp,inspectSource(argument));};// `IsConstructor` abstract operation
// https://tc39.es/ecma262/#sec-isconstructor
var isConstructor=!construct||fails(function(){var called;return isConstructorModern(isConstructorModern.call)||!isConstructorModern(Object)||!isConstructorModern(function(){called=true;})||called;})?isConstructorLegacy:isConstructorModern;var SPECIES$3=wellKnownSymbol('species');var Array$2=global_1.Array;// a part of `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesConstructor=function(originalArray){var C;if(isArray(originalArray)){C=originalArray.constructor;// cross-realm fallback
if(isConstructor(C)&&(C===Array$2||isArray(C.prototype)))C=undefined;else if(isObject(C)){C=C[SPECIES$3];if(C===null)C=undefined;}}return C===undefined?Array$2:C;};// `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate=function(originalArray,length){return new(arraySpeciesConstructor(originalArray))(length===0?0:length);};var SPECIES$2=wellKnownSymbol('species');var arrayMethodHasSpeciesSupport=function(METHOD_NAME){// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return engineV8Version>=51||!fails(function(){var array=[];var constructor=array.constructor={};constructor[SPECIES$2]=function(){return {foo:1};};return array[METHOD_NAME](Boolean).foo!==1;});};var IS_CONCAT_SPREADABLE=wellKnownSymbol('isConcatSpreadable');var MAX_SAFE_INTEGER$1=0x1FFFFFFFFFFFFF;var MAXIMUM_ALLOWED_INDEX_EXCEEDED='Maximum allowed index exceeded';var TypeError$4=global_1.TypeError;// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT=engineV8Version>=51||!fails(function(){var array=[];array[IS_CONCAT_SPREADABLE]=false;return array.concat()[0]!==array;});var SPECIES_SUPPORT=arrayMethodHasSpeciesSupport('concat');var isConcatSpreadable=function(O){if(!isObject(O))return false;var spreadable=O[IS_CONCAT_SPREADABLE];return spreadable!==undefined?!!spreadable:isArray(O);};var FORCED$1=!IS_CONCAT_SPREADABLE_SUPPORT||!SPECIES_SUPPORT;// `Array.prototype.concat` method
// https://tc39.es/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
_export({target:'Array',proto:true,forced:FORCED$1},{// eslint-disable-next-line no-unused-vars -- required for `.length`
concat:function concat(arg){var O=toObject(this);var A=arraySpeciesCreate(O,0);var n=0;var i,k,length,len,E;for(i=-1,length=arguments.length;i<length;i++){E=i===-1?O:arguments[i];if(isConcatSpreadable(E)){len=lengthOfArrayLike(E);if(n+len>MAX_SAFE_INTEGER$1)throw TypeError$4(MAXIMUM_ALLOWED_INDEX_EXCEEDED);for(k=0;k<len;k++,n++)if(k in E)createProperty(A,n,E[k]);}else {if(n>=MAX_SAFE_INTEGER$1)throw TypeError$4(MAXIMUM_ALLOWED_INDEX_EXCEEDED);createProperty(A,n++,E);}}A.length=n;return A;}});// `Object.prototype.toString` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.tostring
var objectToString=toStringTagSupport?{}.toString:function toString(){return '[object '+classof(this)+']';};// `Object.prototype.toString` method
// https://tc39.es/ecma262/#sec-object.prototype.tostring
if(!toStringTagSupport){redefine(Object.prototype,'toString',objectToString,{unsafe:true});}var PROPER_FUNCTION_NAME=functionName.PROPER;var TO_STRING='toString';var RegExpPrototype=RegExp.prototype;var n$ToString=RegExpPrototype[TO_STRING];var getFlags=functionUncurryThis(regexpFlags);var NOT_GENERIC=fails(function(){return n$ToString.call({source:'a',flags:'b'})!='/a/b';});// FF44- RegExp#toString has a wrong name
var INCORRECT_NAME=PROPER_FUNCTION_NAME&&n$ToString.name!=TO_STRING;// `RegExp.prototype.toString` method
// https://tc39.es/ecma262/#sec-regexp.prototype.tostring
if(NOT_GENERIC||INCORRECT_NAME){redefine(RegExp.prototype,TO_STRING,function toString(){var R=anObject(this);var p=toString_1(R.source);var rf=R.flags;var f=toString_1(rf===undefined&&objectIsPrototypeOf(RegExpPrototype,R)&&!('flags'in RegExpPrototype)?getFlags(R):rf);return '/'+p+'/'+f;},{unsafe:true});}var FunctionPrototype=Function.prototype;var apply=FunctionPrototype.apply;var bind$1=FunctionPrototype.bind;var call=FunctionPrototype.call;// eslint-disable-next-line es/no-reflect -- safe
var functionApply=typeof Reflect=='object'&&Reflect.apply||(bind$1?call.bind(apply):function(){return call.apply(apply,arguments);});var MATCH$1=wellKnownSymbol('match');// `IsRegExp` abstract operation
// https://tc39.es/ecma262/#sec-isregexp
var isRegexp=function(it){var isRegExp;return isObject(it)&&((isRegExp=it[MATCH$1])!==undefined?!!isRegExp:classofRaw(it)=='RegExp');};var TypeError$3=global_1.TypeError;// `Assert: IsConstructor(argument) is true`
var aConstructor=function(argument){if(isConstructor(argument))return argument;throw TypeError$3(tryToString(argument)+' is not a constructor');};var SPECIES$1=wellKnownSymbol('species');// `SpeciesConstructor` abstract operation
// https://tc39.es/ecma262/#sec-speciesconstructor
var speciesConstructor=function(O,defaultConstructor){var C=anObject(O).constructor;var S;return C===undefined||(S=anObject(C)[SPECIES$1])==undefined?defaultConstructor:aConstructor(S);};var arraySlice=functionUncurryThis([].slice);var UNSUPPORTED_Y=regexpStickyHelpers.UNSUPPORTED_Y;var MAX_UINT32=0xFFFFFFFF;var min$2=Math.min;var $push=[].push;var exec=functionUncurryThis(/./.exec);var push$3=functionUncurryThis($push);var stringSlice$2=functionUncurryThis(''.slice);// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
// Weex JS has frozen built-in prototypes, so use try / catch wrapper
var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC=!fails(function(){// eslint-disable-next-line regexp/no-empty-group -- required for testing
var re=/(?:)/;var originalExec=re.exec;re.exec=function(){return originalExec.apply(this,arguments);};var result='ab'.split(re);return result.length!==2||result[0]!=='a'||result[1]!=='b';});// @@split logic
fixRegexpWellKnownSymbolLogic('split',function(SPLIT,nativeSplit,maybeCallNative){var internalSplit;if('abbc'.split(/(b)*/)[1]=='c'||// eslint-disable-next-line regexp/no-empty-group -- required for testing
'test'.split(/(?:)/,-1).length!=4||'ab'.split(/(?:ab)*/).length!=2||'.'.split(/(.?)(.?)/).length!=4||// eslint-disable-next-line regexp/no-empty-capturing-group, regexp/no-empty-group -- required for testing
'.'.split(/()()/).length>1||''.split(/.?/).length){// based on es5-shim implementation, need to rework it
internalSplit=function(separator,limit){var string=toString_1(requireObjectCoercible(this));var lim=limit===undefined?MAX_UINT32:limit>>>0;if(lim===0)return [];if(separator===undefined)return [string];// If `separator` is not a regex, use native split
if(!isRegexp(separator)){return functionCall(nativeSplit,string,separator,lim);}var output=[];var flags=(separator.ignoreCase?'i':'')+(separator.multiline?'m':'')+(separator.unicode?'u':'')+(separator.sticky?'y':'');var lastLastIndex=0;// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy=new RegExp(separator.source,flags+'g');var match,lastIndex,lastLength;while(match=functionCall(regexpExec,separatorCopy,string)){lastIndex=separatorCopy.lastIndex;if(lastIndex>lastLastIndex){push$3(output,stringSlice$2(string,lastLastIndex,match.index));if(match.length>1&&match.index<string.length)functionApply($push,output,arraySlice(match,1));lastLength=match[0].length;lastLastIndex=lastIndex;if(output.length>=lim)break;}if(separatorCopy.lastIndex===match.index)separatorCopy.lastIndex++;// Avoid an infinite loop
}if(lastLastIndex===string.length){if(lastLength||!exec(separatorCopy,''))push$3(output,'');}else push$3(output,stringSlice$2(string,lastLastIndex));return output.length>lim?arraySlice(output,0,lim):output;};// Chakra, V8
}else if('0'.split(undefined,0).length){internalSplit=function(separator,limit){return separator===undefined&&limit===0?[]:functionCall(nativeSplit,this,separator,limit);};}else internalSplit=nativeSplit;return [// `String.prototype.split` method
// https://tc39.es/ecma262/#sec-string.prototype.split
function split(separator,limit){var O=requireObjectCoercible(this);var splitter=separator==undefined?undefined:getMethod(separator,SPLIT);return splitter?functionCall(splitter,separator,O,limit):functionCall(internalSplit,toString_1(O),separator,limit);},// `RegExp.prototype[@@split]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@split
//
// NOTE: This cannot be properly polyfilled in engines that don't support
// the 'y' flag.
function(string,limit){var rx=anObject(this);var S=toString_1(string);var res=maybeCallNative(internalSplit,rx,S,limit,internalSplit!==nativeSplit);if(res.done)return res.value;var C=speciesConstructor(rx,RegExp);var unicodeMatching=rx.unicode;var flags=(rx.ignoreCase?'i':'')+(rx.multiline?'m':'')+(rx.unicode?'u':'')+(UNSUPPORTED_Y?'g':'y');// ^(? + rx + ) is needed, in combination with some S slicing, to
// simulate the 'y' flag.
var splitter=new C(UNSUPPORTED_Y?'^(?:'+rx.source+')':rx,flags);var lim=limit===undefined?MAX_UINT32:limit>>>0;if(lim===0)return [];if(S.length===0)return regexpExecAbstract(splitter,S)===null?[S]:[];var p=0;var q=0;var A=[];while(q<S.length){splitter.lastIndex=UNSUPPORTED_Y?0:q;var z=regexpExecAbstract(splitter,UNSUPPORTED_Y?stringSlice$2(S,q):S);var e;if(z===null||(e=min$2(toLength(splitter.lastIndex+(UNSUPPORTED_Y?q:0)),S.length))===p){q=advanceStringIndex(S,q,unicodeMatching);}else {push$3(A,stringSlice$2(S,p,q));if(A.length===lim)return A;for(var i=1;i<=z.length-1;i++){push$3(A,z[i]);if(A.length===lim)return A;}q=p=e;}}push$3(A,stringSlice$2(S,p));return A;}];},!SPLIT_WORKS_WITH_OVERWRITTEN_EXEC,UNSUPPORTED_Y);/**
* Append a class to an element
*
* @api private
* @method _addClass
* @param {Object} element
* @param {String} className
* @returns null
*/function addClass(element,className){if(element instanceof SVGElement){// svg
var pre=element.getAttribute("class")||"";if(!pre.match(className)){// check if element doesn't already have className
element.setAttribute("class","".concat(pre," ").concat(className));}}else {if(element.classList!==undefined){// check for modern classList property
var classes=className.split(" ");forEach(classes,function(cls){element.classList.add(cls);});}else if(!element.className.match(className)){// check if element doesn't already have className
element.className+=" ".concat(className);}}}/**
* Get an element CSS property on the page
* Thanks to JavaScript Kit: http://www.javascriptkit.com/dhtmltutors/dhtmlcascade4.shtml
*
* @api private
* @method _getPropValue
* @param {Object} element
* @param {String} propName
* @returns string property value
*/function getPropValue(element,propName){var propValue="";if(element.currentStyle){//IE
propValue=element.currentStyle[propName];}else if(document.defaultView&&document.defaultView.getComputedStyle){//Others
propValue=document.defaultView.getComputedStyle(element,null).getPropertyValue(propName);}//Prevent exception in IE
if(propValue&&propValue.toLowerCase){return propValue.toLowerCase();}else {return propValue;}}/**
* To set the show element
* This function set a relative (in most cases) position and changes the z-index
*
* @api private
* @method _setShowElement
* @param {Object} targetElement
*/function setShowElement(_ref){var element=_ref.element;addClass(element,"introjs-showElement");var currentElementPosition=getPropValue(element,"position");if(currentElementPosition!=="absolute"&&currentElementPosition!=="relative"&&currentElementPosition!=="sticky"&&currentElementPosition!=="fixed"){//change to new intro item
addClass(element,"introjs-relativePosition");}}/**
* Find the nearest scrollable parent
* copied from https://stackoverflow.com/questions/35939886/find-first-scrollable-parent
*
* @param Element element
* @return Element
*/function getScrollParent(element){var style=window.getComputedStyle(element);var excludeStaticParent=style.position==="absolute";var overflowRegex=/(auto|scroll)/;if(style.position==="fixed")return document.body;for(var parent=element;parent=parent.parentElement;){style=window.getComputedStyle(parent);if(excludeStaticParent&&style.position==="static"){continue;}if(overflowRegex.test(style.overflow+style.overflowY+style.overflowX))return parent;}return document.body;}/**
* scroll a scrollable element to a child element
*
* @param {Object} targetElement
*/function scrollParentToElement(targetElement){var element=targetElement.element;if(!this._options.scrollToElement)return;var parent=getScrollParent(element);if(parent===document.body)return;parent.scrollTop=element.offsetTop-parent.offsetTop;}/**
* Provides a cross-browser way to get the screen dimensions
* via: http://stackoverflow.com/questions/5864467/internet-explorer-innerheight
*
* @api private
* @method _getWinSize
* @returns {Object} width and height attributes
*/function getWinSize(){if(window.innerWidth!==undefined){return {width:window.innerWidth,height:window.innerHeight};}else {var D=document.documentElement;return {width:D.clientWidth,height:D.clientHeight};}}/**
* Check to see if the element is in the viewport or not
* http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
*
* @api private
* @method _elementInViewport
* @param {Object} el
*/function elementInViewport(el){var rect=el.getBoundingClientRect();return rect.top>=0&&rect.left>=0&&rect.bottom+80<=window.innerHeight&&// add 80 to get the text right
rect.right<=window.innerWidth;}/**
* To change the scroll of `window` after highlighting an element
*
* @api private
* @param {String} scrollTo
* @param {Object} targetElement
* @param {Object} tooltipLayer
*/function scrollTo(scrollTo,_ref,tooltipLayer){var element=_ref.element;if(scrollTo==="off")return;var rect;if(!this._options.scrollToElement)return;if(scrollTo==="tooltip"){rect=tooltipLayer.getBoundingClientRect();}else {rect=element.getBoundingClientRect();}if(!elementInViewport(element)){var winHeight=getWinSize().height;var top=rect.bottom-(rect.bottom-rect.top);// TODO (afshinm): do we need scroll padding now?
// I have changed the scroll option and now it scrolls the window to
// the center of the target element or tooltip.
if(top<0||element.clientHeight>winHeight){window.scrollBy(0,rect.top-(winHeight/2-rect.height/2)-this._options.scrollPadding);// 30px padding from edge to look nice
//Scroll down
}else {window.scrollBy(0,rect.top-(winHeight/2-rect.height/2)+this._options.scrollPadding);// 30px padding from edge to look nice
}}}/**
* Setting anchors to behave like buttons
*
* @api private
* @method _setAnchorAsButton
*/function setAnchorAsButton(anchor){anchor.setAttribute("role","button");anchor.tabIndex=0;}// eslint-disable-next-line es/no-object-assign -- safe
var $assign=Object.assign;// eslint-disable-next-line es/no-object-defineproperty -- required for testing
var defineProperty=Object.defineProperty;var concat$1=functionUncurryThis([].concat);// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
var objectAssign=!$assign||fails(function(){// should have correct order of operations (Edge bug)
if(descriptors&&$assign({b:1},$assign(defineProperty({},'a',{enumerable:true,get:function(){defineProperty(this,'b',{value:3,enumerable:false});}}),{b:2})).b!==1)return true;// should work with symbols and should have deterministic property order (V8 bug)
var A={};var B={};// eslint-disable-next-line es/no-symbol -- safe
var symbol=Symbol();var alphabet='abcdefghijklmnopqrst';A[symbol]=7;alphabet.split('').forEach(function(chr){B[chr]=chr;});return $assign({},A)[symbol]!=7||objectKeys($assign({},B)).join('')!=alphabet;})?function assign(target,source){// eslint-disable-line no-unused-vars -- required for `.length`
var T=toObject(target);var argumentsLength=arguments.length;var index=1;var getOwnPropertySymbols=objectGetOwnPropertySymbols.f;var propertyIsEnumerable=objectPropertyIsEnumerable.f;while(argumentsLength>index){var S=indexedObject(arguments[index++]);var keys=getOwnPropertySymbols?concat$1(objectKeys(S),getOwnPropertySymbols(S)):objectKeys(S);var length=keys.length;var j=0;var key;while(length>j){key=keys[j++];if(!descriptors||functionCall(propertyIsEnumerable,S,key))T[key]=S[key];}}return T;}:$assign;// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es/no-object-assign -- required for testing
_export({target:'Object',stat:true,forced:Object.assign!==objectAssign},{assign:objectAssign});/**
* Checks to see if target element (or parents) position is fixed or not
*
* @api private
* @method _isFixed
* @param {Object} element
* @returns Boolean
*/function isFixed(element){var p=element.parentNode;if(!p||p.nodeName==="HTML"){return false;}if(getPropValue(element,"position")==="fixed"){return true;}return isFixed(p);}/**
* Get an element position on the page relative to another element (or body)
* Thanks to `meouw`: http://stackoverflow.com/a/442474/375966
*
* @api private
* @method getOffset
* @param {Object} element
* @param {Object} relativeEl
* @returns Element's position info
*/function getOffset(element,relativeEl){var body=document.body;var docEl=document.documentElement;var scrollTop=window.pageYOffset||docEl.scrollTop||body.scrollTop;var scrollLeft=window.pageXOffset||docEl.scrollLeft||body.scrollLeft;relativeEl=relativeEl||body;var x=element.getBoundingClientRect();var xr=relativeEl.getBoundingClientRect();var relativeElPosition=getPropValue(relativeEl,"position");var obj={width:x.width,height:x.height};if(relativeEl.tagName.toLowerCase()!=="body"&&relativeElPosition==="relative"||relativeElPosition==="sticky"){// when the container of our target element is _not_ body and has either "relative" or "sticky" position, we should not
// consider the scroll position but we need to include the relative x/y of the container element
return Object.assign(obj,{top:x.top-xr.top,left:x.left-xr.left});}else {if(isFixed(element)){return Object.assign(obj,{top:x.top,left:x.left});}else {return Object.assign(obj,{top:x.top+scrollTop,left:x.left+scrollLeft});}}}var floor$1=Math.floor;var charAt=functionUncurryThis(''.charAt);var replace=functionUncurryThis(''.replace);var stringSlice$1=functionUncurryThis(''.slice);var SUBSTITUTION_SYMBOLS=/\$([$&'`]|\d{1,2}|<[^>]*>)/g;var SUBSTITUTION_SYMBOLS_NO_NAMED=/\$([$&'`]|\d{1,2})/g;// `GetSubstitution` abstract operation
// https://tc39.es/ecma262/#sec-getsubstitution
var getSubstitution=function(matched,str,position,captures,namedCaptures,replacement){var tailPos=position+matched.length;var m=captures.length;var symbols=SUBSTITUTION_SYMBOLS_NO_NAMED;if(namedCaptures!==undefined){namedCaptures=toObject(namedCaptures);symbols=SUBSTITUTION_SYMBOLS;}return replace(replacement,symbols,function(match,ch){var capture;switch(charAt(ch,0)){case'$':return '$';case'&':return matched;case'`':return stringSlice$1(str,0,position);case"'":return stringSlice$1(str,tailPos);case'<':capture=namedCaptures[stringSlice$1(ch,1,-1)];break;default:// \d\d?
var n=+ch;if(n===0)return match;if(n>m){var f=floor$1(n/10);if(f===0)return match;if(f<=m)return captures[f-1]===undefined?charAt(ch,1):captures[f-1]+charAt(ch,1);return match;}capture=captures[n-1];}return capture===undefined?'':capture;});};var REPLACE=wellKnownSymbol('replace');var max$2=Math.max;var min$1=Math.min;var concat=functionUncurryThis([].concat);var push$2=functionUncurryThis([].push);var stringIndexOf$1=functionUncurryThis(''.indexOf);var stringSlice=functionUncurryThis(''.slice);var maybeToString=function(it){return it===undefined?it:String(it);};// IE <= 11 replaces $0 with the whole match, as if it was $&
// https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0
var REPLACE_KEEPS_$0=function(){// eslint-disable-next-line regexp/prefer-escape-replacement-dollar-char -- required for testing
return 'a'.replace(/./,'$0')==='$0';}();// Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string
var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE=function(){if(/./[REPLACE]){return /./[REPLACE]('a','$0')==='';}return false;}();var REPLACE_SUPPORTS_NAMED_GROUPS=!fails(function(){var re=/./;re.exec=function(){var result=[];result.groups={a:'7'};return result;};// eslint-disable-next-line regexp/no-useless-dollar-replacements -- false positive
return ''.replace(re,'$<a>')!=='7';});// @@replace logic
fixRegexpWellKnownSymbolLogic('replace',function(_,nativeReplace,maybeCallNative){var UNSAFE_SUBSTITUTE=REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE?'$':'$0';return [// `String.prototype.replace` method
// https://tc39.es/ecma262/#sec-string.prototype.replace
function replace(searchValue,replaceValue){var O=requireObjectCoercible(this);var replacer=searchValue==undefined?undefined:getMethod(searchValue,REPLACE);return replacer?functionCall(replacer,searchValue,O,replaceValue):functionCall(nativeReplace,toString_1(O),searchValue,replaceValue);},// `RegExp.prototype[@@replace]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
function(string,replaceValue){var rx=anObject(this);var S=toString_1(string);if(typeof replaceValue=='string'&&stringIndexOf$1(replaceValue,UNSAFE_SUBSTITUTE)===-1&&stringIndexOf$1(replaceValue,'$<')===-1){var res=maybeCallNative(nativeReplace,rx,S,replaceValue);if(res.done)return res.value;}var functionalReplace=isCallable(replaceValue);if(!functionalReplace)replaceValue=toString_1(replaceValue);var global=rx.global;if(global){var fullUnicode=rx.unicode;rx.lastIndex=0;}var results=[];while(true){var result=regexpExecAbstract(rx,S);if(result===null)break;push$2(results,result);if(!global)break;var matchStr=toString_1(result[0]);if(matchStr==='')rx.lastIndex=advanceStringIndex(S,toLength(rx.lastIndex),fullUnicode);}var accumulatedResult='';var nextSourcePosition=0;for(var i=0;i<results.length;i++){result=results[i];var matched=toString_1(result[0]);var position=max$2(min$1(toIntegerOrInfinity(result.index),S.length),0);var captures=[];// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for(var j=1;j<result.length;j++)push$2(captures,maybeToString(result[j]));var namedCaptures=result.groups;if(functionalReplace){var replacerArgs=concat([matched],captures,position,S);if(namedCaptures!==undefined)push$2(replacerArgs,namedCaptures);var replacement=toString_1(functionApply(replaceValue,undefined,replacerArgs));}else {replacement=getSubstitution(matched,S,position,captures,namedCaptures,replaceValue);}if(position>=nextSourcePosition){accumulatedResult+=stringSlice(S,nextSourcePosition,position)+replacement;nextSourcePosition=position+matched.length;}}return accumulatedResult+stringSlice(S,nextSourcePosition);}];},!REPLACE_SUPPORTS_NAMED_GROUPS||!REPLACE_KEEPS_$0||REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE);/**
* Remove a class from an element
*
* @api private
* @method _removeClass
* @param {Object} element
* @param {RegExp|String} classNameRegex can be regex or string
* @returns null
*/function removeClass(element,classNameRegex){if(element instanceof SVGElement){var pre=element.getAttribute("class")||"";element.setAttribute("class",pre.replace(classNameRegex,"").replace(/^\s+|\s+$/g,""));}else {element.className=element.className.replace(classNameRegex,"").replace(/^\s+|\s+$/g,"");}}/**
* Sets the style of an DOM element
*
* @param {Object} element
* @param {Object|string} style
* @return null
*/function setStyle(element,style){var cssText="";if(element.style.cssText){cssText+=element.style.cssText;}if(typeof style==="string"){cssText+=style;}else {for(var rule in style){cssText+="".concat(rule,":").concat(style[rule],";");}}element.style.cssText=cssText;}/**
* Update the position of the helper layer on the screen
*
* @api private
* @method _setHelperLayerPosition
* @param {Object} helperLayer
*/function setHelperLayerPosition(helperLayer){if(helperLayer){//prevent error when `this._currentStep` in undefined
if(!this._introItems[this._currentStep])return;var currentElement=this._introItems[this._currentStep];var elementPosition=getOffset(currentElement.element,this._targetElement);var widthHeightPadding=this._options.helperElementPadding;// If the target element is fixed, the tooltip should be fixed as well.
// Otherwise, remove a fixed class that may be left over from the previous
// step.
if(isFixed(currentElement.element)){addClass(helperLayer,"introjs-fixedTooltip");}else {removeClass(helperLayer,"introjs-fixedTooltip");}if(currentElement.position==="floating"){widthHeightPadding=0;}//set new position to helper layer
setStyle(helperLayer,{width:"".concat(elementPosition.width+widthHeightPadding,"px"),height:"".concat(elementPosition.height+widthHeightPadding,"px"),top:"".concat(elementPosition.top-widthHeightPadding/2,"px"),left:"".concat(elementPosition.left-widthHeightPadding/2,"px")});}}var UNSCOPABLES=wellKnownSymbol('unscopables');var ArrayPrototype=Array.prototype;// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if(ArrayPrototype[UNSCOPABLES]==undefined){objectDefineProperty.f(ArrayPrototype,UNSCOPABLES,{configurable:true,value:objectCreate(null)});}// add a key to Array.prototype[@@unscopables]
var addToUnscopables=function(key){ArrayPrototype[UNSCOPABLES][key]=true;};var $includes=arrayIncludes.includes;// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
_export({target:'Array',proto:true},{includes:function includes(el/* , fromIndex = 0 */){return $includes(this,el,arguments.length>1?arguments[1]:undefined);}});// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');var HAS_SPECIES_SUPPORT$2=arrayMethodHasSpeciesSupport('slice');var SPECIES=wellKnownSymbol('species');var Array$1=global_1.Array;var max$1=Math.max;// `Array.prototype.slice` method
// https://tc39.es/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
_export({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT$2},{slice:function slice(start,end){var O=toIndexedObject(this);var length=lengthOfArrayLike(O);var k=toAbsoluteIndex(start,length);var fin=toAbsoluteIndex(end===undefined?length:end,length);// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor,result,n;if(isArray(O)){Constructor=O.constructor;// cross-realm fallback
if(isConstructor(Constructor)&&(Constructor===Array$1||isArray(Constructor.prototype))){Constructor=undefined;}else if(isObject(Constructor)){Constructor=Constructor[SPECIES];if(Constructor===null)Constructor=undefined;}if(Constructor===Array$1||Constructor===undefined){return arraySlice(O,k,fin);}}result=new(Constructor===undefined?Array$1:Constructor)(max$1(fin-k,0));for(n=0;k<fin;k++,n++)if(k in O)createProperty(result,n,O[k]);result.length=n;return result;}});var TypeError$2=global_1.TypeError;var notARegexp=function(it){if(isRegexp(it)){throw TypeError$2("The method doesn't accept regular expressions");}return it;};var MATCH=wellKnownSymbol('match');var correctIsRegexpLogic=function(METHOD_NAME){var regexp=/./;try{'/./'[METHOD_NAME](regexp);}catch(error1){try{regexp[MATCH]=false;return '/./'[METHOD_NAME](regexp);}catch(error2){/* empty */}}return false;};var stringIndexOf=functionUncurryThis(''.indexOf);// `String.prototype.includes` method
// https://tc39.es/ecma262/#sec-string.prototype.includes
_export({target:'String',proto:true,forced:!correctIsRegexpLogic('includes')},{includes:function includes(searchString/* , position = 0 */){return !!~stringIndexOf(toString_1(requireObjectCoercible(this)),toString_1(notARegexp(searchString)),arguments.length>1?arguments[1]:undefined);}});var arrayMethodIsStrict=function(METHOD_NAME,argument){var method=[][METHOD_NAME];return !!method&&fails(function(){// eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing
method.call(null,argument||function(){throw 1;},1);});};var un$Join=functionUncurryThis([].join);var ES3_STRINGS=indexedObject!=Object;var STRICT_METHOD$1=arrayMethodIsStrict('join',',');// `Array.prototype.join` method
// https://tc39.es/ecma262/#sec-array.prototype.join
_export({target:'Array',proto:true,forced:ES3_STRINGS||!STRICT_METHOD$1},{join:function join(separator){return un$Join(toIndexedObject(this),separator===undefined?',':separator);}});var bind=functionUncurryThis(functionUncurryThis.bind);// optional / simple context binding
var functionBindContext=function(fn,that){aCallable(fn);return that===undefined?fn:bind?bind(fn,that):function/* ...args */(){return fn.apply(that,arguments);};};var push$1=functionUncurryThis([].push);// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
var createMethod=function(TYPE){var IS_MAP=TYPE==1;var IS_FILTER=TYPE==2;var IS_SOME=TYPE==3;var IS_EVERY=TYPE==4;var IS_FIND_INDEX=TYPE==6;var IS_FILTER_REJECT=TYPE==7;var NO_HOLES=TYPE==5||IS_FIND_INDEX;return function($this,callbackfn,that,specificCreate){var O=toObject($this);var self=indexedObject(O);var boundFunction=functionBindContext(callbackfn,that);var length=lengthOfArrayLike(self);var index=0;var create=specificCreate||arraySpeciesCreate;var target=IS_MAP?create($this,length):IS_FILTER||IS_FILTER_REJECT?create($this,0):undefined;var value,result;for(;length>index;index++)if(NO_HOLES||index in self){value=self[index];result=boundFunction(value,index,O);if(TYPE){if(IS_MAP)target[index]=result;// map
else if(result)switch(TYPE){case 3:return true;// some
case 5:return value;// find
case 6:return index;// findIndex
case 2:push$1(target,value);// filter
}else switch(TYPE){case 4:return false;// every
case 7:push$1(target,value);// filterReject
}}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:target;};};var arrayIteration={// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
forEach:createMethod(0),// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
map:createMethod(1),// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
filter:createMethod(2),// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
some:createMethod(3),// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
every:createMethod(4),// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
find:createMethod(5),// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findIndex
findIndex:createMethod(6),// `Array.prototype.filterReject` method
// https://github.com/tc39/proposal-array-filtering
filterReject:createMethod(7)};var $filter=arrayIteration.filter;var HAS_SPECIES_SUPPORT$1=arrayMethodHasSpeciesSupport('filter');// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
// with adding support of @@species
_export({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT$1},{filter:function filter(callbackfn/* , thisArg */){return $filter(this,callbackfn,arguments.length>1?arguments[1]:undefined);}});/**
* Set tooltip left so it doesn't go off the right side of the window
*
* @return boolean true, if tooltipLayerStyleLeft is ok. false, otherwise.
*/function checkRight(targetOffset,tooltipLayerStyleLeft,tooltipOffset,windowSize,tooltipLayer){if(targetOffset.left+tooltipLayerStyleLeft+tooltipOffset.width>windowSize.width){// off the right side of the window
tooltipLayer.style.left="".concat(windowSize.width-tooltipOffset.width-targetOffset.left,"px");return false;}tooltipLayer.style.left="".concat(tooltipLayerStyleLeft,"px");return true;}/**
* Set tooltip right so it doesn't go off the left side of the window
*
* @return boolean true, if tooltipLayerStyleRight is ok. false, otherwise.
*/function checkLeft(targetOffset,tooltipLayerStyleRight,tooltipOffset,tooltipLayer){if(targetOffset.left+targetOffset.width-tooltipLayerStyleRight-tooltipOffset.width<0){// off the left side of the window
tooltipLayer.style.left="".concat(-targetOffset.left,"px");return false;}tooltipLayer.style.right="".concat(tooltipLayerStyleRight,"px");return true;}var HAS_SPECIES_SUPPORT=arrayMethodHasSpeciesSupport('splice');var TypeError$1=global_1.TypeError;var max=Math.max;var min=Math.min;var MAX_SAFE_INTEGER=0x1FFFFFFFFFFFFF;var MAXIMUM_ALLOWED_LENGTH_EXCEEDED='Maximum allowed length exceeded';// `Array.prototype.splice` method
// https://tc39.es/ecma262/#sec-array.prototype.splice
// with adding support of @@species
_export({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT},{splice:function splice(start,deleteCount/* , ...items */){var O=toObject(this);var len=lengthOfArrayLike(O);var actualStart=toAbsoluteIndex(start,len);var argumentsLength=arguments.length;var insertCount,actualDeleteCount,A,k,from,to;if(argumentsLength===0){insertCount=actualDeleteCount=0;}else if(argumentsLength===1){insertCount=0;actualDeleteCount=len-actualStart;}else {insertCount=argumentsLength-2;actualDeleteCount=min(max(toIntegerOrInfinity(deleteCount),0),len-actualStart);}if(len+insertCount-actualDeleteCount>MAX_SAFE_INTEGER){throw TypeError$1(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);}A=arraySpeciesCreate(O,actualDeleteCount);for(k=0;k<actualDeleteCount;k++){from=actualStart+k;if(from in O)createProperty(A,k,O[from]);}A.length=actualDeleteCount;if(insertCount<actualDeleteCount){for(k=actualStart;k<len-actualDeleteCount;k++){from=k+actualDeleteCount;to=k+insertCount;if(from in O)O[to]=O[from];else delete O[to];}for(k=len;k>len-actualDeleteCount+insertCount;k--)delete O[k-1];}else if(insertCount>actualDeleteCount){for(k=len-actualDeleteCount;k>actualStart;k--){from=k+actualDeleteCount-1;to=k+insertCount-1;if(from in O)O[to]=O[from];else delete O[to];}}for(k=0;k<insertCount;k++){O[k+actualStart]=arguments[k+2];}O.length=len-actualDeleteCount+insertCount;return A;}});/**
* Remove an entry from a string array if it's there, does nothing if it isn't there.
*
* @param {Array} stringArray
* @param {String} stringToRemove
*/function removeEntry(stringArray,stringToRemove){if(stringArray.includes(stringToRemove)){stringArray.splice(stringArray.indexOf(stringToRemove),1);}}/**
* auto-determine alignment
* @param {Integer} offsetLeft
* @param {Integer} tooltipWidth
* @param {Object} windowSize
* @param {String} desiredAlignment
* @return {String} calculatedAlignment
*/function _determineAutoAlignment(offsetLeft,tooltipWidth,_ref,desiredAlignment){var width=_ref.width;var halfTooltipWidth=tooltipWidth/2;var winWidth=Math.min(width,window.screen.width);var possibleAlignments=["-left-aligned","-middle-aligned","-right-aligned"];var calculatedAlignment="";// valid left must be at least a tooltipWidth
// away from right side
if(winWidth-offsetLeft<tooltipWidth){removeEntry(possibleAlignments,"-left-aligned");}// valid middle must be at least half
// width away from both sides
if(offsetLeft<halfTooltipWidth||winWidth-offsetLeft<halfTooltipWidth){removeEntry(possibleAlignments,"-middle-aligned");}// valid right must be at least a tooltipWidth
// width away from left side
if(offsetLeft<tooltipWidth){removeEntry(possibleAlignments,"-right-aligned");}if(possibleAlignments.length){if(possibleAlignments.includes(desiredAlignment)){// the desired alignment is valid
calculatedAlignment=desiredAlignment;}else {// pick the first valid position, in order
calculatedAlignment=possibleAlignments[0];}}else {// if screen width is too small
// for ANY alignment, middle is
// probably the best for visibility
calculatedAlignment="-middle-aligned";}return calculatedAlignment;}/**
* Determines the position of the tooltip based on the position precedence and availability
* of screen space.
*
* @param {Object} targetElement
* @param {Object} tooltipLayer
* @param {String} desiredTooltipPosition
* @return {String} calculatedPosition
*/function _determineAutoPosition(targetElement,tooltipLayer,desiredTooltipPosition){// Take a clone of position precedence. These will be the available
var possiblePositions=this._options.positionPrecedence.slice();var windowSize=getWinSize();var tooltipHeight=getOffset(tooltipLayer).height+10;var tooltipWidth=getOffset(tooltipLayer).width+20;var targetElementRect=targetElement.getBoundingClientRect();// If we check all the possible areas, and there are no valid places for the tooltip, the element
// must take up most of the screen real estate. Show the tooltip floating in the middle of the screen.
var calculatedPosition="floating";/*
* auto determine position
*/ // Check for space below
if(targetElementRect.bottom+tooltipHeight>windowSize.height){removeEntry(possiblePositions,"bottom");}// Check for space above
if(targetElementRect.top-tooltipHeight<0){removeEntry(possiblePositions,"top");}// Check for space to the right
if(targetElementRect.right+tooltipWidth>windowSize.width){removeEntry(possiblePositions,"right");}// Check for space to the left
if(targetElementRect.left-tooltipWidth<0){removeEntry(possiblePositions,"left");}// @var {String} ex: 'right-aligned'
var desiredAlignment=function(pos){var hyphenIndex=pos.indexOf("-");if(hyphenIndex!==-1){// has alignment
return pos.substr(hyphenIndex);}return "";}(desiredTooltipPosition||"");// strip alignment from position
if(desiredTooltipPosition){// ex: "bottom-right-aligned"
// should return 'bottom'
desiredTooltipPosition=desiredTooltipPosition.split("-")[0];}if(possiblePositions.length){if(possiblePositions.includes(desiredTooltipPosition)){// If the requested position is in the list, choose that
calculatedPosition=desiredTooltipPosition;}else {// Pick the first valid position, in order
calculatedPosition=possiblePositions[0];}}// only top and bottom positions have optional alignments
if(["top","bottom"].includes(calculatedPosition)){calculatedPosition+=_determineAutoAlignment(targetElementRect.left,tooltipWidth,windowSize,desiredAlignment);}return calculatedPosition;}/**
* Render tooltip box in the page
*
* @api private
* @method placeTooltip
* @param {HTMLElement} targetElement
* @param {HTMLElement} tooltipLayer
* @param {HTMLElement} arrowLayer
* @param {Boolean} hintMode
*/function placeTooltip(targetElement,tooltipLayer,arrowLayer,hintMode){var tooltipCssClass="";var currentStepObj;var tooltipOffset;var targetOffset;var windowSize;var currentTooltipPosition;hintMode=hintMode||false;//reset the old style
tooltipLayer.style.top=null;tooltipLayer.style.right=null;tooltipLayer.style.bottom=null;tooltipLayer.style.left=null;tooltipLayer.style.marginLeft=null;tooltipLayer.style.marginTop=null;arrowLayer.style.display="inherit";//prevent error when `this._currentStep` is undefined
if(!this._introItems[this._currentStep])return;//if we have a custom css class for each step
currentStepObj=this._introItems[this._currentStep];if(typeof currentStepObj.tooltipClass==="string"){tooltipCssClass=currentStepObj.tooltipClass;}else {tooltipCssClass=this._options.tooltipClass;}tooltipLayer.className=["introjs-tooltip",tooltipCssClass].filter(Boolean).join(" ");tooltipLayer.setAttribute("role","dialog");currentTooltipPosition=this._introItems[this._currentStep].position;// Floating is always valid, no point in calculating
if(currentTooltipPosition!=="floating"&&this._options.autoPosition){currentTooltipPosition=_determineAutoPosition.call(this,targetElement,tooltipLayer,currentTooltipPosition);}var tooltipLayerStyleLeft;targetOffset=getOffset(targetElement);tooltipOffset=getOffset(tooltipLayer);windowSize=getWinSize();addClass(tooltipLayer,"introjs-".concat(currentTooltipPosition));switch(currentTooltipPosition){case"top-right-aligned":arrowLayer.className="introjs-arrow bottom-right";var tooltipLayerStyleRight=0;checkLeft(targetOffset,tooltipLayerStyleRight,tooltipOffset,tooltipLayer);tooltipLayer.style.bottom="".concat(targetOffset.height+20,"px");break;case"top-middle-aligned":arrowLayer.className="introjs-arrow bottom-middle";var tooltipLayerStyleLeftRight=targetOffset.width/2-tooltipOffset.width/2;// a fix for middle aligned hints
if(hintMode){tooltipLayerStyleLeftRight+=5;}if(checkLeft(targetOffset,tooltipLayerStyleLeftRight,tooltipOffset,tooltipLayer)){tooltipLayer.style.right=null;checkRight(targetOffset,tooltipLayerStyleLeftRight,tooltipOffset,windowSize,tooltipLayer);}tooltipLayer.style.bottom="".concat(targetOffset.height+20,"px");break;case"top-left-aligned":// top-left-aligned is the same as the default top
case"top":arrowLayer.className="introjs-arrow bottom";tooltipLayerStyleLeft=hintMode?0:15;checkRight(targetOffset,tooltipLayerStyleLeft,tooltipOffset,windowSize,tooltipLayer);tooltipLayer.style.bottom="".concat(targetOffset.height+20,"px");break;case"right":tooltipLayer.style.left="".concat(targetOffset.width+20,"px");if(targetOffset.top+tooltipOffset.height>windowSize.height){// In this case, right would have fallen below the bottom of the screen.
// Modify so that the bottom of the tooltip connects with the target
arrowLayer.className="introjs-arrow left-bottom";tooltipLayer.style.top="-".concat(tooltipOffset.height-targetOffset.height-20,"px");}else {arrowLayer.className="introjs-arrow left";}break;case"left":if(!hintMode&&this._options.showStepNumbers===true){tooltipLayer.style.top="15px";}if(targetOffset.top+tooltipOffset.height>windowSize.height){// In this case, left would have fallen below the bottom of the screen.
// Modify so that the bottom of the tooltip connects with the target
tooltipLayer.style.top="-".concat(tooltipOffset.height-targetOffset.height-20,"px");arrowLayer.className="introjs-arrow right-bottom";}else {arrowLayer.className="introjs-arrow right";}tooltipLayer.style.right="".concat(targetOffset.width+20,"px");break;case"floating":arrowLayer.style.display="none";//we have to adjust the top and left of layer manually for intro items without element
tooltipLayer.style.left="50%";tooltipLayer.style.top="50%";tooltipLayer.style.marginLeft="-".concat(tooltipOffset.width/2,"px");tooltipLayer.style.marginTop="-".concat(tooltipOffset.height/2,"px");break;case"bottom-right-aligned":arrowLayer.className="introjs-arrow top-right";tooltipLayerStyleRight=0;checkLeft(targetOffset,tooltipLayerStyleRight,tooltipOffset,tooltipLayer);tooltipLayer.style.top="".concat(targetOffset.height+20,"px");break;case"bottom-middle-aligned":arrowLayer.className="introjs-arrow top-middle";tooltipLayerStyleLeftRight=targetOffset.width/2-tooltipOffset.width/2;// a fix for middle aligned hints
if(hintMode){tooltipLayerStyleLeftRight+=5;}if(checkLeft(targetOffset,tooltipLayerStyleLeftRight,tooltipOffset,tooltipLayer)){tooltipLayer.style.right=null;checkRight(targetOffset,tooltipLayerStyleLeftRight,tooltipOffset,windowSize,tooltipLayer);}tooltipLayer.style.top="".concat(targetOffset.height+20,"px");break;// case 'bottom-left-aligned':
// Bottom-left-aligned is the same as the default bottom
// case 'bottom':
// Bottom going to follow the default behavior
default:arrowLayer.className="introjs-arrow top";tooltipLayerStyleLeft=0;checkRight(targetOffset,tooltipLayerStyleLeft,tooltipOffset,windowSize,tooltipLayer);tooltipLayer.style.top="".concat(targetOffset.height+20,"px");}}/**
* To remove all show element(s)
*
* @api private
* @method _removeShowElement
*/function removeShowElement(){var elms=document.querySelectorAll(".introjs-showElement");forEach(elms,function(elm){removeClass(elm,/introjs-[a-zA-Z]+/g);});}function _createElement(tagname,attrs){var element=document.createElement(tagname);attrs=attrs||{};// regex for matching attributes that need to be set with setAttribute
var setAttRegex=/^(?:role|data-|aria-)/;for(var k in attrs){var v=attrs[k];if(k==="style"){setStyle(element,v);}else if(k.match(setAttRegex)){element.setAttribute(k,v);}else {element[k]=v;}}return element;}/**
* Appends `element` to `parentElement`
*
* @param {Element} parentElement
* @param {Element} element
* @param {Boolean} [animate=false]
*/function appendChild(parentElement,element,animate){if(animate){var existingOpacity=element.style.opacity||"1";setStyle(element,{opacity:"0"});window.setTimeout(function(){setStyle(element,{opacity:existingOpacity});},10);}parentElement.appendChild(element);}/**
* Gets the current progress percentage
*
* @api private
* @method _getProgress
* @returns current progress percentage
*/function _getProgress(){// Steps are 0 indexed
var currentStep=parseInt(this._currentStep+1,10);return currentStep/this._introItems.length*100;}/**
* Add disableinteraction layer and adjust the size and position of the layer
*
* @api private
* @method _disableInteraction
*/function _disableInteraction(){var disableInteractionLayer=document.querySelector(".introjs-disableInteraction");if(disableInteractionLayer===null){disableInteractionLayer=_createElement("div",{className:"introjs-disableInteraction"});this._targetElement.appendChild(disableInteractionLayer);}setHelperLayerPosition.call(this,disableInteractionLayer);}/**
* Creates the bullets layer
* @returns HTMLElement
* @private
*/function _createBullets(targetElement){var self=this;var bulletsLayer=_createElement("div",{className:"introjs-bullets"});if(this._options.showBullets===false){bulletsLayer.style.display="none";}var ulContainer=_createElement("ul");ulContainer.setAttribute("role","tablist");var anchorClick=function anchorClick(){self.goToStep(this.getAttribute("data-stepnumber"));};forEach(this._introItems,function(_ref,i){var step=_ref.step;var innerLi=_createElement("li");var anchorLink=_createElement("a");innerLi.setAttribute("role","presentation");anchorLink.setAttribute("role","tab");anchorLink.onclick=anchorClick;if(i===targetElement.step-1){anchorLink.className="active";}setAnchorAsButton(anchorLink);anchorLink.innerHTML="&nbsp;";anchorLink.setAttribute("data-stepnumber",step);innerLi.appendChild(anchorLink);ulContainer.appendChild(innerLi);});bulletsLayer.appendChild(ulContainer);return bulletsLayer;}/**
* Deletes and recreates the bullets layer
* @param oldReferenceLayer
* @param targetElement
* @private
*/function _recreateBullets(oldReferenceLayer,targetElement){if(this._options.showBullets){var existing=document.querySelector(".introjs-bullets");existing.parentNode.replaceChild(_createBullets.call(this,targetElement),existing);}}/**
* Updates the bullets
*
* @param oldReferenceLayer
* @param targetElement
*/function _updateBullets(oldReferenceLayer,targetElement){if(this._options.showBullets){oldReferenceLayer.querySelector(".introjs-bullets li > a.active").className="";oldReferenceLayer.querySelector(".introjs-bullets li > a[data-stepnumber=\"".concat(targetElement.step,"\"]")).className="active";}}/**
* Creates the progress-bar layer and elements
* @returns {*}
* @private
*/function _createProgressBar(){var progressLayer=_createElement("div");progressLayer.className="introjs-progress";if(this._options.showProgress===false){progressLayer.style.display="none";}var progressBar=_createElement("div",{className:"introjs-progressbar"});if(this._options.progressBarAdditionalClass){progressBar.className+=" "+this._options.progressBarAdditionalClass;}progressBar.setAttribute("role","progress");progressBar.setAttribute("aria-valuemin",0);progressBar.setAttribute("aria-valuemax",100);progressBar.setAttribute("aria-valuenow",_getProgress.call(this));progressBar.style.cssText="width:".concat(_getProgress.call(this),"%;");progressLayer.appendChild(progressBar);return progressLayer;}/**
* Updates an existing progress bar variables
* @param oldReferenceLayer
* @private
*/function _updateProgressBar(oldReferenceLayer){oldReferenceLayer.querySelector(".introjs-progress .introjs-progressbar").style.cssText="width:".concat(_getProgress.call(this),"%;");oldReferenceLayer.querySelector(".introjs-progress .introjs-progressbar").setAttribute("aria-valuenow",_getProgress.call(this));}/**
* Show an element on the page
*
* @api private
* @method _showElement
* @param {Object} targetElement
*/function _showElement(targetElement){var _this=this;if(typeof this._introChangeCallback!=="undefined"){this._introChangeCallback.call(this,targetElement.element);}var self=this;var oldHelperLayer=document.querySelector(".introjs-helperLayer");var oldReferenceLayer=document.querySelector(".introjs-tooltipReferenceLayer");var highlightClass="introjs-helperLayer";var nextTooltipButton;var prevTooltipButton;var skipTooltipButton;//check for a current step highlight class
if(typeof targetElement.highlightClass==="string"){highlightClass+=" ".concat(targetElement.highlightClass);}//check for options highlight class
if(typeof this._options.highlightClass==="string"){highlightClass+=" ".concat(this._options.highlightClass);}if(oldHelperLayer!==null&&oldReferenceLayer!==null){var oldHelperNumberLayer=oldReferenceLayer.querySelector(".introjs-helperNumberLayer");var oldtooltipLayer=oldReferenceLayer.querySelector(".introjs-tooltiptext");var oldTooltipTitleLayer=oldReferenceLayer.querySelector(".introjs-tooltip-title");var oldArrowLayer=oldReferenceLayer.querySelector(".introjs-arrow");var oldtooltipContainer=oldReferenceLayer.querySelector(".introjs-tooltip");skipTooltipButton=oldReferenceLayer.querySelector(".introjs-skipbutton");prevTooltipButton=oldReferenceLayer.querySelector(".introjs-prevbutton");nextTooltipButton=oldReferenceLayer.querySelector(".introjs-nextbutton");//update or reset the helper highlight class
oldHelperLayer.className=highlightClass;//hide the tooltip
oldtooltipContainer.style.opacity=0;oldtooltipContainer.style.display="none";// if the target element is within a scrollable element
scrollParentToElement.call(self,targetElement);// set new position to helper layer
setHelperLayerPosition.call(self,oldHelperLayer);setHelperLayerPosition.call(self,oldReferenceLayer);//remove old classes if the element still exist
removeShowElement();//we should wait until the CSS3 transition is competed (it's 0.3 sec) to prevent incorrect `height` and `width` calculation
if(self._lastShowElementTimer){window.clearTimeout(self._lastShowElementTimer);}self._lastShowElementTimer=window.setTimeout(function(){// set current step to the label
if(oldHelperNumberLayer!==null){oldHelperNumberLayer.innerHTML="".concat(targetElement.step," of ").concat(_this._introItems.length);}// set current tooltip text
oldtooltipLayer.innerHTML=targetElement.intro;// set current tooltip title
oldTooltipTitleLayer.innerHTML=targetElement.title;//set the tooltip position
oldtooltipContainer.style.display="block";placeTooltip.call(self,targetElement.element,oldtooltipContainer,oldArrowLayer);//change active bullet
_updateBullets.call(self,oldReferenceLayer,targetElement);_updateProgressBar.call(self,oldReferenceLayer);//show the tooltip
oldtooltipContainer.style.opacity=1;//reset button focus
if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null&&/introjs-donebutton/gi.test(nextTooltipButton.className)){// skip button is now "done" button
nextTooltipButton.focus();}else if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){//still in the tour, focus on next
nextTooltipButton.focus();}// change the scroll of the window, if needed
scrollTo.call(self,targetElement.scrollTo,targetElement,oldtooltipLayer);},350);// end of old element if-else condition
}else {var helperLayer=_createElement("div",{className:highlightClass});var referenceLayer=_createElement("div",{className:"introjs-tooltipReferenceLayer"});var arrowLayer=_createElement("div",{className:"introjs-arrow"});var tooltipLayer=_createElement("div",{className:"introjs-tooltip"});var tooltipTextLayer=_createElement("div",{className:"introjs-tooltiptext"});var tooltipHeaderLayer=_createElement("div",{className:"introjs-tooltip-header"});var tooltipTitleLayer=_createElement("h1",{className:"introjs-tooltip-title"});var buttonsLayer=_createElement("div");setStyle(helperLayer,{"box-shadow":"0 0 1px 2px rgba(33, 33, 33, 0.8), rgba(33, 33, 33, ".concat(self._options.overlayOpacity.toString(),") 0 0 0 5000px")});// target is within a scrollable element
scrollParentToElement.call(self,targetElement);//set new position to helper layer
setHelperLayerPosition.call(self,helperLayer);setHelperLayerPosition.call(self,referenceLayer);//add helper layer to target element
appendChild(this._targetElement,helperLayer,true);appendChild(this._targetElement,referenceLayer);tooltipTextLayer.innerHTML=targetElement.intro;tooltipTitleLayer.innerHTML=targetElement.title;buttonsLayer.className="introjs-tooltipbuttons";if(this._options.showButtons===false){buttonsLayer.style.display="none";}tooltipHeaderLayer.appendChild(tooltipTitleLayer);tooltipLayer.appendChild(tooltipHeaderLayer);tooltipLayer.appendChild(tooltipTextLayer);tooltipLayer.appendChild(_createBullets.call(this,targetElement));tooltipLayer.appendChild(_createProgressBar.call(this));// add helper layer number
var helperNumberLayer=_createElement("div");if(this._options.showStepNumbers===true){helperNumberLayer.className="introjs-helperNumberLayer";helperNumberLayer.innerHTML="".concat(targetElement.step," of ").concat(this._introItems.length);tooltipLayer.appendChild(helperNumberLayer);}tooltipLayer.appendChild(arrowLayer);referenceLayer.appendChild(tooltipLayer);//next button
nextTooltipButton=_createElement("a");nextTooltipButton.onclick=function(){if(self._introItems.length-1!==self._currentStep){nextStep.call(self);}else if(/introjs-donebutton/gi.test(nextTooltipButton.className)){if(typeof self._introCompleteCallback==="function"){self._introCompleteCallback.call(self,self._currentStep,"done");}exitIntro.call(self,self._targetElement);}};setAnchorAsButton(nextTooltipButton);nextTooltipButton.innerHTML=this._options.nextLabel;//previous button
prevTooltipButton=_createElement("a");prevTooltipButton.onclick=function(){if(self._currentStep!==0){previousStep.call(self);}};setAnchorAsButton(prevTooltipButton);prevTooltipButton.innerHTML=this._options.prevLabel;//skip button
skipTooltipButton=_createElement("a",{className:"introjs-skipbutton"});setAnchorAsButton(skipTooltipButton);skipTooltipButton.innerHTML=this._options.skipLabel;skipTooltipButton.onclick=function(){if(self._introItems.length-1===self._currentStep&&typeof self._introCompleteCallback==="function"){self._introCompleteCallback.call(self,self._currentStep,"skip");}if(typeof self._introSkipCallback==="function"){self._introSkipCallback.call(self);}exitIntro.call(self,self._targetElement);};tooltipHeaderLayer.appendChild(skipTooltipButton);//in order to prevent displaying previous button always
if(this._introItems.length>1){buttonsLayer.appendChild(prevTooltipButton);}// we always need the next button because this
// button changes to "Done" in the last step of the tour
buttonsLayer.appendChild(nextTooltipButton);tooltipLayer.appendChild(buttonsLayer);//set proper position
placeTooltip.call(self,targetElement.element,tooltipLayer,arrowLayer);// change the scroll of the window, if needed
scrollTo.call(this,targetElement.scrollTo,targetElement,tooltipLayer);//end of new element if-else condition
}// removing previous disable interaction layer
var disableInteractionLayer=self._targetElement.querySelector(".introjs-disableInteraction");if(disableInteractionLayer){disableInteractionLayer.parentNode.removeChild(disableInteractionLayer);}//disable interaction
if(targetElement.disableInteraction){_disableInteraction.call(self);}// when it's the first step of tour
if(this._currentStep===0&&this._introItems.length>1){if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){nextTooltipButton.className="".concat(this._options.buttonClass," introjs-nextbutton");nextTooltipButton.innerHTML=this._options.nextLabel;}if(this._options.hidePrev===true){if(typeof prevTooltipButton!=="undefined"&&prevTooltipButton!==null){prevTooltipButton.className="".concat(this._options.buttonClass," introjs-prevbutton introjs-hidden");}if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){addClass(nextTooltipButton,"introjs-fullbutton");}}else {if(typeof prevTooltipButton!=="undefined"&&prevTooltipButton!==null){prevTooltipButton.className="".concat(this._options.buttonClass," introjs-prevbutton introjs-disabled");}}}else if(this._introItems.length-1===this._currentStep||this._introItems.length===1){// last step of tour
if(typeof prevTooltipButton!=="undefined"&&prevTooltipButton!==null){prevTooltipButton.className="".concat(this._options.buttonClass," introjs-prevbutton");}if(this._options.hideNext===true){if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){nextTooltipButton.className="".concat(this._options.buttonClass," introjs-nextbutton introjs-hidden");}if(typeof prevTooltipButton!=="undefined"&&prevTooltipButton!==null){addClass(prevTooltipButton,"introjs-fullbutton");}}else {if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){if(this._options.nextToDone===true){nextTooltipButton.innerHTML=this._options.doneLabel;addClass(nextTooltipButton,"".concat(this._options.buttonClass," introjs-nextbutton introjs-donebutton"));}else {nextTooltipButton.className="".concat(this._options.buttonClass," introjs-nextbutton introjs-disabled");}}}}else {// steps between start and end
if(typeof prevTooltipButton!=="undefined"&&prevTooltipButton!==null){prevTooltipButton.className="".concat(this._options.buttonClass," introjs-prevbutton");}if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){nextTooltipButton.className="".concat(this._options.buttonClass," introjs-nextbutton");nextTooltipButton.innerHTML=this._options.nextLabel;}}if(typeof prevTooltipButton!=="undefined"&&prevTooltipButton!==null){prevTooltipButton.setAttribute("role","button");}if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){nextTooltipButton.setAttribute("role","button");}if(typeof skipTooltipButton!=="undefined"&&skipTooltipButton!==null){skipTooltipButton.setAttribute("role","button");}//Set focus on "next" button, so that hitting Enter always moves you onto the next step
if(typeof nextTooltipButton!=="undefined"&&nextTooltipButton!==null){nextTooltipButton.focus();}setShowElement(targetElement);if(typeof this._introAfterChangeCallback!=="undefined"){this._introAfterChangeCallback.call(this,targetElement.element);}}/**
* Go to specific step of introduction
*
* @api private
* @method _goToStep
*/function goToStep(step){//because steps starts with zero
this._currentStep=step-2;if(typeof this._introItems!=="undefined"){nextStep.call(this);}}/**
* Go to the specific step of introduction with the explicit [data-step] number
*
* @api private
* @method _goToStepNumber
*/function goToStepNumber(step){this._currentStepNumber=step;if(typeof this._introItems!=="undefined"){nextStep.call(this);}}/**
* Go to next step on intro
*
* @api private
* @method _nextStep
*/function nextStep(){var _this=this;this._direction="forward";if(typeof this._currentStepNumber!=="undefined"){forEach(this._introItems,function(_ref,i){var step=_ref.step;if(step===_this._currentStepNumber){_this._currentStep=i-1;_this._currentStepNumber=undefined;}});}if(typeof this._currentStep==="undefined"){this._currentStep=0;}else {++this._currentStep;}var nextStep=this._introItems[this._currentStep];var continueStep=true;if(typeof this._introBeforeChangeCallback!=="undefined"){continueStep=this._introBeforeChangeCallback.call(this,nextStep&&nextStep.element);}// if `onbeforechange` returned `false`, stop displaying the element
if(continueStep===false){--this._currentStep;return false;}if(this._introItems.length<=this._currentStep){//end of the intro
//check if any callback is defined
if(typeof this._introCompleteCallback==="function"){this._introCompleteCallback.call(this,this._currentStep,"end");}exitIntro.call(this,this._targetElement);return;}_showElement.call(this,nextStep);}/**
* Go to previous step on intro
*
* @api private
* @method _previousStep
*/function previousStep(){this._direction="backward";if(this._currentStep===0){return false;}--this._currentStep;var nextStep=this._introItems[this._currentStep];var continueStep=true;if(typeof this._introBeforeChangeCallback!=="undefined"){continueStep=this._introBeforeChangeCallback.call(this,nextStep&&nextStep.element);}// if `onbeforechange` returned `false`, stop displaying the element
if(continueStep===false){++this._currentStep;return false;}_showElement.call(this,nextStep);}/**
* Returns the current step of the intro
*
* @returns {number | boolean}
*/function currentStep(){return this._currentStep;}/**
* on keyCode:
* https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
* This feature has been removed from the Web standards.
* Though some browsers may still support it, it is in
* the process of being dropped.
* Instead, you should use KeyboardEvent.code,
* if it's implemented.
*
* jQuery's approach is to test for
* (1) e.which, then
* (2) e.charCode, then
* (3) e.keyCode
* https://github.com/jquery/jquery/blob/a6b0705294d336ae2f63f7276de0da1195495363/src/event.js#L638
*
* @param type var
* @return type
*/function onKeyDown(e){var code=e.code===undefined?e.which:e.code;// if e.which is null
if(code===null){code=e.charCode===null?e.keyCode:e.charCode;}if((code==="Escape"||code===27)&&this._options.exitOnEsc===true){//escape key pressed, exit the intro
//check if exit callback is defined
exitIntro.call(this,this._targetElement);}else if(code==="ArrowLeft"||code===37){//left arrow
previousStep.call(this);}else if(code==="ArrowRight"||code===39){//right arrow
nextStep.call(this);}else if(code==="Enter"||code==="NumpadEnter"||code===13){//srcElement === ie
var target=e.target||e.srcElement;if(target&&target.className.match("introjs-prevbutton")){//user hit enter while focusing on previous button
previousStep.call(this);}else if(target&&target.className.match("introjs-skipbutton")){//user hit enter while focusing on skip button
if(this._introItems.length-1===this._currentStep&&typeof this._introCompleteCallback==="function"){this._introCompleteCallback.call(this,this._currentStep,"skip");}exitIntro.call(this,this._targetElement);}else if(target&&target.getAttribute("data-stepnumber")){// user hit enter while focusing on step bullet
target.click();}else {//default behavior for responding to enter
nextStep.call(this);}//prevent default behaviour on hitting Enter, to prevent steps being skipped in some browsers
if(e.preventDefault){e.preventDefault();}else {e.returnValue=false;}}}/*
* makes a copy of the object
* @api private
* @method _cloneObject
*/function cloneObject(object){if(object===null||_typeof(object)!=="object"||typeof object.nodeType!=="undefined"){return object;}var temp={};for(var key in object){if(typeof window.jQuery!=="undefined"&&object[key]instanceof window.jQuery){temp[key]=object[key];}else {temp[key]=cloneObject(object[key]);}}return temp;}function debounce(func,timeout){var _this=this;var timer;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}clearTimeout(timer);timer=setTimeout(function(){func.apply(_this,args);},timeout);};}/**
* Get a queryselector within the hint wrapper
*
* @param {String} selector
* @return {NodeList|Array}
*/function hintQuerySelectorAll(selector){var hintsWrapper=document.querySelector(".introjs-hints");return hintsWrapper?hintsWrapper.querySelectorAll(selector):[];}/**
* Hide a hint
*
* @api private
* @method hideHint
*/function hideHint(stepId){var hint=hintQuerySelectorAll(".introjs-hint[data-step=\"".concat(stepId,"\"]"))[0];removeHintTooltip.call(this);if(hint){addClass(hint,"introjs-hidehint");}// call the callback function (if any)
if(typeof this._hintCloseCallback!=="undefined"){this._hintCloseCallback.call(this,stepId);}}/**
* Hide all hints
*
* @api private
* @method hideHints
*/function hideHints(){var _this=this;var hints=hintQuerySelectorAll(".introjs-hint");forEach(hints,function(hint){hideHint.call(_this,hint.getAttribute("data-step"));});}/**
* Show all hints
*
* @api private
* @method _showHints
*/function showHints(){var _this2=this;var hints=hintQuerySelectorAll(".introjs-hint");if(hints&&hints.length){forEach(hints,function(hint){showHint.call(_this2,hint.getAttribute("data-step"));});}else {populateHints.call(this,this._targetElement);}}/**
* Show a hint
*
* @api private
* @method showHint
*/function showHint(stepId){var hint=hintQuerySelectorAll(".introjs-hint[data-step=\"".concat(stepId,"\"]"))[0];if(hint){removeClass(hint,/introjs-hidehint/g);}}/**
* Removes all hint elements on the page
* Useful when you want to destroy the elements and add them again (e.g. a modal or popup)
*
* @api private
* @method removeHints
*/function removeHints(){var _this3=this;var hints=hintQuerySelectorAll(".introjs-hint");forEach(hints,function(hint){removeHint.call(_this3,hint.getAttribute("data-step"));});DOMEvent.off(document,"click",removeHintTooltip,this,false);DOMEvent.off(window,"resize",reAlignHints,this,true);if(this._hintsAutoRefreshFunction)DOMEvent.off(window,"scroll",this._hintsAutoRefreshFunction,this,true);}/**
* Remove one single hint element from the page
* Useful when you want to destroy the element and add them again (e.g. a modal or popup)
* Use removeHints if you want to remove all elements.
*
* @api private
* @method removeHint
*/function removeHint(stepId){var hint=hintQuerySelectorAll(".introjs-hint[data-step=\"".concat(stepId,"\"]"))[0];if(hint){hint.parentNode.removeChild(hint);}}/**
* Add all available hints to the page
*
* @api private
* @method addHints
*/function addHints(){var _this4=this;var self=this;var hintsWrapper=document.querySelector(".introjs-hints");if(hintsWrapper===null){hintsWrapper=_createElement("div",{className:"introjs-hints"});}/**
* Returns an event handler unique to the hint iteration
*
* @param {Integer} i
* @return {Function}
*/var getHintClick=function getHintClick(i){return function(e){var evt=e?e:window.event;if(evt.stopPropagation){evt.stopPropagation();}if(evt.cancelBubble!==null){evt.cancelBubble=true;}showHintDialog.call(self,i);};};forEach(this._introItems,function(item,i){// avoid append a hint twice
if(document.querySelector(".introjs-hint[data-step=\"".concat(i,"\"]"))){return;}var hint=_createElement("a",{className:"introjs-hint"});setAnchorAsButton(hint);hint.onclick=getHintClick(i);if(!item.hintAnimation){addClass(hint,"introjs-hint-no-anim");}// hint's position should be fixed if the target element's position is fixed
if(isFixed(item.element)){addClass(hint,"introjs-fixedhint");}var hintDot=_createElement("div",{className:"introjs-hint-dot"});var hintPulse=_createElement("div",{className:"introjs-hint-pulse"});hint.appendChild(hintDot);hint.appendChild(hintPulse);hint.setAttribute("data-step",i);// we swap the hint element with target element
// because _setHelperLayerPosition uses `element` property
item.targetElement=item.element;item.element=hint;// align the hint position
alignHintPosition.call(_this4,item.hintPosition,hint,item.targetElement);hintsWrapper.appendChild(hint);});// adding the hints wrapper
document.body.appendChild(hintsWrapper);// call the callback function (if any)
if(typeof this._hintsAddedCallback!=="undefined"){this._hintsAddedCallback.call(this);}if(this._options.hintAutoRefreshInterval>=0){this._hintsAutoRefreshFunction=debounce(function(){return reAlignHints.call(_this4);},this._options.hintAutoRefreshInterval);DOMEvent.on(window,"scroll",this._hintsAutoRefreshFunction,this,true);}}/**
* Aligns hint position
*
* @api private
* @method alignHintPosition
* @param {String} position
* @param {Object} hint
* @param {Object} element
*/function alignHintPosition(position,_ref,element){var style=_ref.style;// get/calculate offset of target element
var offset=getOffset.call(this,element);var iconWidth=20;var iconHeight=20;// align the hint element
switch(position){default:case"top-left":style.left="".concat(offset.left,"px");style.top="".concat(offset.top,"px");break;case"top-right":style.left="".concat(offset.left+offset.width-iconWidth,"px");style.top="".concat(offset.top,"px");break;case"bottom-left":style.left="".concat(offset.left,"px");style.top="".concat(offset.top+offset.height-iconHeight,"px");break;case"bottom-right":style.left="".concat(offset.left+offset.width-iconWidth,"px");style.top="".concat(offset.top+offset.height-iconHeight,"px");break;case"middle-left":style.left="".concat(offset.left,"px");style.top="".concat(offset.top+(offset.height-iconHeight)/2,"px");break;case"middle-right":style.left="".concat(offset.left+offset.width-iconWidth,"px");style.top="".concat(offset.top+(offset.height-iconHeight)/2,"px");break;case"middle-middle":style.left="".concat(offset.left+(offset.width-iconWidth)/2,"px");style.top="".concat(offset.top+(offset.height-iconHeight)/2,"px");break;case"bottom-middle":style.left="".concat(offset.left+(offset.width-iconWidth)/2,"px");style.top="".concat(offset.top+offset.height-iconHeight,"px");break;case"top-middle":style.left="".concat(offset.left+(offset.width-iconWidth)/2,"px");style.top="".concat(offset.top,"px");break;}}/**
* Triggers when user clicks on the hint element
*
* @api private
* @method _showHintDialog
* @param {Number} stepId
*/function showHintDialog(stepId){var hintElement=document.querySelector(".introjs-hint[data-step=\"".concat(stepId,"\"]"));var item=this._introItems[stepId];// call the callback function (if any)
if(typeof this._hintClickCallback!=="undefined"){this._hintClickCallback.call(this,hintElement,item,stepId);}// remove all open tooltips
var removedStep=removeHintTooltip.call(this);// to toggle the tooltip
if(parseInt(removedStep,10)===stepId){return;}var tooltipLayer=_createElement("div",{className:"introjs-tooltip"});var tooltipTextLayer=_createElement("div");var arrowLayer=_createElement("div");var referenceLayer=_createElement("div");tooltipLayer.onclick=function(e){//IE9 & Other Browsers
if(e.stopPropagation){e.stopPropagation();}//IE8 and Lower
else {e.cancelBubble=true;}};tooltipTextLayer.className="introjs-tooltiptext";var tooltipWrapper=_createElement("p");tooltipWrapper.innerHTML=item.hint;tooltipTextLayer.appendChild(tooltipWrapper);if(this._options.hintShowButton){var closeButton=_createElement("a");closeButton.className=this._options.buttonClass;closeButton.setAttribute("role","button");closeButton.innerHTML=this._options.hintButtonLabel;closeButton.onclick=hideHint.bind(this,stepId);tooltipTextLayer.appendChild(closeButton);}arrowLayer.className="introjs-arrow";tooltipLayer.appendChild(arrowLayer);tooltipLayer.appendChild(tooltipTextLayer);// set current step for _placeTooltip function
this._currentStep=hintElement.getAttribute("data-step");// align reference layer position
referenceLayer.className="introjs-tooltipReferenceLayer introjs-hintReference";referenceLayer.setAttribute("data-step",hintElement.getAttribute("data-step"));setHelperLayerPosition.call(this,referenceLayer);referenceLayer.appendChild(tooltipLayer);document.body.appendChild(referenceLayer);//set proper position
placeTooltip.call(this,hintElement,tooltipLayer,arrowLayer,true);}/**
* Removes open hint (tooltip hint)
*
* @api private
* @method _removeHintTooltip
*/function removeHintTooltip(){var tooltip=document.querySelector(".introjs-hintReference");if(tooltip){var step=tooltip.getAttribute("data-step");tooltip.parentNode.removeChild(tooltip);return step;}}/**
* Start parsing hint items
*
* @api private
* @param {Object} targetElm
* @method _startHint
*/function populateHints(targetElm){var _this5=this;this._introItems=[];if(this._options.hints){forEach(this._options.hints,function(hint){var currentItem=cloneObject(hint);if(typeof currentItem.element==="string"){//grab the element with given selector from the page
currentItem.element=document.querySelector(currentItem.element);}currentItem.hintPosition=currentItem.hintPosition||_this5._options.hintPosition;currentItem.hintAnimation=currentItem.hintAnimation||_this5._options.hintAnimation;if(currentItem.element!==null){_this5._introItems.push(currentItem);}});}else {var hints=targetElm.querySelectorAll("*[data-hint]");if(!hints||!hints.length){return false;}//first add intro items with data-step
forEach(hints,function(currentElement){// hint animation
var hintAnimation=currentElement.getAttribute("data-hintanimation");if(hintAnimation){hintAnimation=hintAnimation==="true";}else {hintAnimation=_this5._options.hintAnimation;}_this5._introItems.push({element:currentElement,hint:currentElement.getAttribute("data-hint"),hintPosition:currentElement.getAttribute("data-hintposition")||_this5._options.hintPosition,hintAnimation:hintAnimation,tooltipClass:currentElement.getAttribute("data-tooltipclass"),position:currentElement.getAttribute("data-position")||_this5._options.tooltipPosition});});}addHints.call(this);DOMEvent.on(document,"click",removeHintTooltip,this,false);DOMEvent.on(window,"resize",reAlignHints,this,true);}/**
* Re-aligns all hint elements
*
* @api private
* @method _reAlignHints
*/function reAlignHints(){var _this6=this;forEach(this._introItems,function(_ref2){var targetElement=_ref2.targetElement,hintPosition=_ref2.hintPosition,element=_ref2.element;if(typeof targetElement==="undefined"){return;}alignHintPosition.call(_this6,hintPosition,element,targetElement);});}var floor=Math.floor;var mergeSort=function(array,comparefn){var length=array.length;var middle=floor(length/2);return length<8?insertionSort(array,comparefn):merge(array,mergeSort(arraySlice(array,0,middle),comparefn),mergeSort(arraySlice(array,middle),comparefn),comparefn);};var insertionSort=function(array,comparefn){var length=array.length;var i=1;var element,j;while(i<length){j=i;element=array[i];while(j&&comparefn(array[j-1],element)>0){array[j]=array[--j];}if(j!==i++)array[j]=element;}return array;};var merge=function(array,left,right,comparefn){var llength=left.length;var rlength=right.length;var lindex=0;var rindex=0;while(lindex<llength||rindex<rlength){array[lindex+rindex]=lindex<llength&&rindex<rlength?comparefn(left[lindex],right[rindex])<=0?left[lindex++]:right[rindex++]:lindex<llength?left[lindex++]:right[rindex++];}return array;};var arraySort=mergeSort;var firefox=engineUserAgent.match(/firefox\/(\d+)/i);var engineFfVersion=!!firefox&&+firefox[1];var engineIsIeOrEdge=/MSIE|Trident/.test(engineUserAgent);var webkit=engineUserAgent.match(/AppleWebKit\/(\d+)\./);var engineWebkitVersion=!!webkit&&+webkit[1];var test=[];var un$Sort=functionUncurryThis(test.sort);var push=functionUncurryThis(test.push);// IE8-
var FAILS_ON_UNDEFINED=fails(function(){test.sort(undefined);});// V8 bug
var FAILS_ON_NULL=fails(function(){test.sort(null);});// Old WebKit
var STRICT_METHOD=arrayMethodIsStrict('sort');var STABLE_SORT=!fails(function(){// feature detection can be too slow, so check engines versions
if(engineV8Version)return engineV8Version<70;if(engineFfVersion&&engineFfVersion>3)return;if(engineIsIeOrEdge)return true;if(engineWebkitVersion)return engineWebkitVersion<603;var result='';var code,chr,value,index;// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for(code=65;code<76;code++){chr=String.fromCharCode(code);switch(code){case 66:case 69:case 70:case 72:value=3;break;case 68:case 71:value=4;break;default:value=2;}for(index=0;index<47;index++){test.push({k:chr+index,v:value});}}test.sort(function(a,b){return b.v-a.v;});for(index=0;index<test.length;index++){chr=test[index].k.charAt(0);if(result.charAt(result.length-1)!==chr)result+=chr;}return result!=='DGBEFHACIJK';});var FORCED=FAILS_ON_UNDEFINED||!FAILS_ON_NULL||!STRICT_METHOD||!STABLE_SORT;var getSortCompare=function(comparefn){return function(x,y){if(y===undefined)return -1;if(x===undefined)return 1;if(comparefn!==undefined)return +comparefn(x,y)||0;return toString_1(x)>toString_1(y)?1:-1;};};// `Array.prototype.sort` method
// https://tc39.es/ecma262/#sec-array.prototype.sort
_export({target:'Array',proto:true,forced:FORCED},{sort:function sort(comparefn){if(comparefn!==undefined)aCallable(comparefn);var array=toObject(this);if(STABLE_SORT)return comparefn===undefined?un$Sort(array):un$Sort(array,comparefn);var items=[];var arrayLength=lengthOfArrayLike(array);var itemsLength,index;for(index=0;index<arrayLength;index++){if(index in array)push(items,array[index]);}arraySort(items,getSortCompare(comparefn));itemsLength=items.length;index=0;while(index<itemsLength)array[index]=items[index++];while(index<arrayLength)delete array[index++];return array;}});/**
* Finds all Intro steps from the data-* attributes and the options.steps array
*
* @api private
* @param targetElm
* @returns {[]}
*/function fetchIntroSteps(targetElm){var _this=this;var allIntroSteps=targetElm.querySelectorAll("*[data-intro]");var introItems=[];if(this._options.steps){//use steps passed programmatically
forEach(this._options.steps,function(step){var currentItem=cloneObject(step);//set the step
currentItem.step=introItems.length+1;currentItem.title=currentItem.title||"";//use querySelector function only when developer used CSS selector
if(typeof currentItem.element==="string"){//grab the element with given selector from the page
currentItem.element=document.querySelector(currentItem.element);}//intro without element
if(typeof currentItem.element==="undefined"||currentItem.element===null){var floatingElementQuery=document.querySelector(".introjsFloatingElement");if(floatingElementQuery===null){floatingElementQuery=_createElement("div",{className:"introjsFloatingElement"});document.body.appendChild(floatingElementQuery);}currentItem.element=floatingElementQuery;currentItem.position="floating";}currentItem.position=currentItem.position||_this._options.tooltipPosition;currentItem.scrollTo=currentItem.scrollTo||_this._options.scrollTo;if(typeof currentItem.disableInteraction==="undefined"){currentItem.disableInteraction=_this._options.disableInteraction;}if(currentItem.element!==null){introItems.push(currentItem);}});}else {//use steps from data-* annotations
var elmsLength=allIntroSteps.length;var disableInteraction;//if there's no element to intro
if(elmsLength<1){return [];}forEach(allIntroSteps,function(currentElement){// start intro for groups of elements
if(_this._options.group&&currentElement.getAttribute("data-intro-group")!==_this._options.group){return;}// skip hidden elements
if(currentElement.style.display==="none"){return;}var step=parseInt(currentElement.getAttribute("data-step"),10);if(currentElement.hasAttribute("data-disable-interaction")){disableInteraction=!!currentElement.getAttribute("data-disable-interaction");}else {disableInteraction=_this._options.disableInteraction;}if(step>0){introItems[step-1]={element:currentElement,title:currentElement.getAttribute("data-title")||"",intro:currentElement.getAttribute("data-intro"),step:parseInt(currentElement.getAttribute("data-step"),10),tooltipClass:currentElement.getAttribute("data-tooltipclass"),highlightClass:currentElement.getAttribute("data-highlightclass"),position:currentElement.getAttribute("data-position")||_this._options.tooltipPosition,scrollTo:currentElement.getAttribute("data-scrollto")||_this._options.scrollTo,disableInteraction:disableInteraction};}});//next add intro items without data-step
//todo: we need a cleanup here, two loops are redundant
var nextStep=0;forEach(allIntroSteps,function(currentElement){// start intro for groups of elements
if(_this._options.group&&currentElement.getAttribute("data-intro-group")!==_this._options.group){return;}if(currentElement.getAttribute("data-step")===null){while(true){if(typeof introItems[nextStep]==="undefined"){break;}else {nextStep++;}}if(currentElement.hasAttribute("data-disable-interaction")){disableInteraction=!!currentElement.getAttribute("data-disable-interaction");}else {disableInteraction=_this._options.disableInteraction;}introItems[nextStep]={element:currentElement,title:currentElement.getAttribute("data-title")||"",intro:currentElement.getAttribute("data-intro"),step:nextStep+1,tooltipClass:currentElement.getAttribute("data-tooltipclass"),highlightClass:currentElement.getAttribute("data-highlightclass"),position:currentElement.getAttribute("data-position")||_this._options.tooltipPosition,scrollTo:currentElement.getAttribute("data-scrollto")||_this._options.scrollTo,disableInteraction:disableInteraction};}});}//removing undefined/null elements
var tempIntroItems=[];for(var z=0;z<introItems.length;z++){if(introItems[z]){// copy non-falsy values to the end of the array
tempIntroItems.push(introItems[z]);}}introItems=tempIntroItems;//Ok, sort all items with given steps
introItems.sort(function(a,b){return a.step-b.step;});return introItems;}/**
* Update placement of the intro objects on the screen
* @api private
* @param {boolean} refreshSteps to refresh the intro steps as well
*/function refresh(refreshSteps){var referenceLayer=document.querySelector(".introjs-tooltipReferenceLayer");var helperLayer=document.querySelector(".introjs-helperLayer");var disableInteractionLayer=document.querySelector(".introjs-disableInteraction");// re-align intros
setHelperLayerPosition.call(this,helperLayer);setHelperLayerPosition.call(this,referenceLayer);setHelperLayerPosition.call(this,disableInteractionLayer);if(refreshSteps){this._introItems=fetchIntroSteps.call(this,this._targetElement);_recreateBullets.call(this,referenceLayer,this._introItems[this._currentStep]);_updateProgressBar.call(this,referenceLayer);}// re-align tooltip
if(this._currentStep!==undefined&&this._currentStep!==null){var oldArrowLayer=document.querySelector(".introjs-arrow");var oldtooltipContainer=document.querySelector(".introjs-tooltip");if(oldtooltipContainer&&oldArrowLayer){placeTooltip.call(this,this._introItems[this._currentStep].element,oldtooltipContainer,oldArrowLayer);}}//re-align hints
reAlignHints.call(this);return this;}function onResize(){refresh.call(this);}/**
* Removes `element` from `parentElement`
*
* @param {Element} element
* @param {Boolean} [animate=false]
*/function removeChild(element,animate){if(!element||!element.parentElement)return;var parentElement=element.parentElement;if(animate){setStyle(element,{opacity:"0"});window.setTimeout(function(){try{// removeChild(..) throws an exception if the child has already been removed (https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild)
// this try-catch is added to make sure this function doesn't throw an exception if the child has been removed
// this scenario can happen when start()/exit() is called multiple times and the helperLayer is removed by the
// previous exit() call (note: this is a timeout)
parentElement.removeChild(element);}catch(e){}},500);}else {parentElement.removeChild(element);}}/**
* Exit from intro
*
* @api private
* @method _exitIntro
* @param {Object} targetElement
* @param {Boolean} force - Setting to `true` will skip the result of beforeExit callback
*/function exitIntro(targetElement,force){var continueExit=true;// calling onbeforeexit callback
//
// If this callback return `false`, it would halt the process
if(this._introBeforeExitCallback!==undefined){continueExit=this._introBeforeExitCallback.call(this);}// skip this check if `force` parameter is `true`
// otherwise, if `onbeforeexit` returned `false`, don't exit the intro
if(!force&&continueExit===false)return;// remove overlay layers from the page
var overlayLayers=targetElement.querySelectorAll(".introjs-overlay");if(overlayLayers&&overlayLayers.length){forEach(overlayLayers,function(overlayLayer){return removeChild(overlayLayer);});}//remove all helper layers
var helperLayer=targetElement.querySelector(".introjs-helperLayer");removeChild(helperLayer,true);var referenceLayer=targetElement.querySelector(".introjs-tooltipReferenceLayer");removeChild(referenceLayer);//remove disableInteractionLayer
var disableInteractionLayer=targetElement.querySelector(".introjs-disableInteraction");removeChild(disableInteractionLayer);//remove intro floating element
var floatingElement=document.querySelector(".introjsFloatingElement");removeChild(floatingElement);removeShowElement();//clean listeners
DOMEvent.off(window,"keydown",onKeyDown,this,true);DOMEvent.off(window,"resize",onResize,this,true);//check if any callback is defined
if(this._introExitCallback!==undefined){this._introExitCallback.call(this);}//set the step to zero
this._currentStep=undefined;}/**
* Add overlay layer to the page
*
* @api private
* @method _addOverlayLayer
* @param {Object} targetElm
*/function addOverlayLayer(targetElm){var _this=this;var overlayLayer=_createElement("div",{className:"introjs-overlay"});setStyle(overlayLayer,{top:0,bottom:0,left:0,right:0,position:"fixed"});targetElm.appendChild(overlayLayer);if(this._options.exitOnOverlayClick===true){setStyle(overlayLayer,{cursor:"pointer"});overlayLayer.onclick=function(){exitIntro.call(_this,targetElm);};}return true;}/**
* Initiate a new introduction/guide from an element in the page
*
* @api private
* @method introForElement
* @param {Object} targetElm
* @returns {Boolean} Success or not?
*/function introForElement(targetElm){if(this._introStartCallback!==undefined){this._introStartCallback.call(this,targetElm);}//set it to the introJs object
var steps=fetchIntroSteps.call(this,targetElm);if(steps.length===0){return false;}this._introItems=steps;//add overlay layer to the page
if(addOverlayLayer.call(this,targetElm)){//then, start the show
nextStep.call(this);if(this._options.keyboardNavigation){DOMEvent.on(window,"keydown",onKeyDown,this,true);}//for window resize
DOMEvent.on(window,"resize",onResize,this,true);}return false;}var version="4.3.0";/**
* IntroJs main class
*
* @class IntroJs
*/function IntroJs(obj){this._targetElement=obj;this._introItems=[];this._options={/* Next button label in tooltip box */nextLabel:"Next",/* Previous button label in tooltip box */prevLabel:"Back",/* Skip button label in tooltip box */skipLabel:"×",/* Done button label in tooltip box */doneLabel:"Done",/* Hide previous button in the first step? Otherwise, it will be disabled button. */hidePrev:false,/* Hide next button in the last step? Otherwise, it will be disabled button (note: this will also hide the "Done" button) */hideNext:false,/* Change the Next button to Done in the last step of the intro? otherwise, it will render a disabled button */nextToDone:true,/* Default tooltip box position */tooltipPosition:"bottom",/* Next CSS class for tooltip boxes */tooltipClass:"",/* Start intro for a group of elements */group:"",/* CSS class that is added to the helperLayer */highlightClass:"",/* Close introduction when pressing Escape button? */exitOnEsc:true,/* Close introduction when clicking on overlay layer? */exitOnOverlayClick:true,/* Show step numbers in introduction? */showStepNumbers:false,/* Let user use keyboard to navigate the tour? */keyboardNavigation:true,/* Show tour control buttons? */showButtons:true,/* Show tour bullets? */showBullets:true,/* Show tour progress? */showProgress:false,/* Scroll to highlighted element? */scrollToElement:true,/*
* Should we scroll the tooltip or target element?
*
* Options are: 'element' or 'tooltip'
*/scrollTo:"element",/* Padding to add after scrolling when element is not in the viewport (in pixels) */scrollPadding:30,/* Set the overlay opacity */overlayOpacity:0.5,/* To determine the tooltip position automatically based on the window.width/height */autoPosition:true,/* Precedence of positions, when auto is enabled */positionPrecedence:["bottom","top","right","left"],/* Disable an interaction with element? */disableInteraction:false,/* Set how much padding to be used around helper element */helperElementPadding:10,/* Default hint position */hintPosition:"top-middle",/* Hint button label */hintButtonLabel:"Got it",/* Display the "Got it" button? */hintShowButton:true,/* Hints auto-refresh interval in ms (set to -1 to disable) */hintAutoRefreshInterval:10,/* Adding animation to hints? */hintAnimation:true,/* additional classes to put on the buttons */buttonClass:"introjs-button",/* additional classes to put on progress bar */progressBarAdditionalClass:false};}var introJs=function introJs(targetElm){var instance;if(_typeof(targetElm)==="object"){//Ok, create a new instance
instance=new IntroJs(targetElm);}else if(typeof targetElm==="string"){//select the target element with query selector
var targetElement=document.querySelector(targetElm);if(targetElement){instance=new IntroJs(targetElement);}else {throw new Error("There is no element with given selector.");}}else {instance=new IntroJs(document.body);}// add instance to list of _instances
// passing group to stamp to increment
// from 0 onward somewhat reliably
introJs.instances[stamp(instance,"introjs-instance")]=instance;return instance;};/**
* Current IntroJs version
*
* @property version
* @type String
*/introJs.version=version;/**
* key-val object helper for introJs instances
*
* @property instances
* @type Object
*/introJs.instances={};//Prototype
introJs.fn=IntroJs.prototype={clone:function clone(){return new IntroJs(this);},setOption:function setOption(option,value){this._options[option]=value;return this;},setOptions:function setOptions(options){this._options=mergeOptions(this._options,options);return this;},start:function start(){introForElement.call(this,this._targetElement);return this;},goToStep:function goToStep$1(step){goToStep.call(this,step);return this;},addStep:function addStep(options){if(!this._options.steps){this._options.steps=[];}this._options.steps.push(options);return this;},addSteps:function addSteps(steps){if(!steps.length)return;for(var index=0;index<steps.length;index++){this.addStep(steps[index]);}return this;},goToStepNumber:function goToStepNumber$1(step){goToStepNumber.call(this,step);return this;},nextStep:function nextStep$1(){nextStep.call(this);return this;},previousStep:function previousStep$1(){previousStep.call(this);return this;},currentStep:function currentStep$1(){return currentStep.call(this);},exit:function exit(force){exitIntro.call(this,this._targetElement,force);return this;},refresh:function refresh$1(refreshSteps){refresh.call(this,refreshSteps);return this;},onbeforechange:function onbeforechange(providedCallback){if(typeof providedCallback==="function"){this._introBeforeChangeCallback=providedCallback;}else {throw new Error("Provided callback for onbeforechange was not a function");}return this;},onchange:function onchange(providedCallback){if(typeof providedCallback==="function"){this._introChangeCallback=providedCallback;}else {throw new Error("Provided callback for onchange was not a function.");}return this;},onafterchange:function onafterchange(providedCallback){if(typeof providedCallback==="function"){this._introAfterChangeCallback=providedCallback;}else {throw new Error("Provided callback for onafterchange was not a function");}return this;},oncomplete:function oncomplete(providedCallback){if(typeof providedCallback==="function"){this._introCompleteCallback=providedCallback;}else {throw new Error("Provided callback for oncomplete was not a function.");}return this;},onhintsadded:function onhintsadded(providedCallback){if(typeof providedCallback==="function"){this._hintsAddedCallback=providedCallback;}else {throw new Error("Provided callback for onhintsadded was not a function.");}return this;},onhintclick:function onhintclick(providedCallback){if(typeof providedCallback==="function"){this._hintClickCallback=providedCallback;}else {throw new Error("Provided callback for onhintclick was not a function.");}return this;},onhintclose:function onhintclose(providedCallback){if(typeof providedCallback==="function"){this._hintCloseCallback=providedCallback;}else {throw new Error("Provided callback for onhintclose was not a function.");}return this;},onstart:function onstart(providedCallback){if(typeof providedCallback==="function"){this._introStartCallback=providedCallback;}else {throw new Error("Provided callback for onstart was not a function.");}return this;},onexit:function onexit(providedCallback){if(typeof providedCallback==="function"){this._introExitCallback=providedCallback;}else {throw new Error("Provided callback for onexit was not a function.");}return this;},onskip:function onskip(providedCallback){if(typeof providedCallback==="function"){this._introSkipCallback=providedCallback;}else {throw new Error("Provided callback for onskip was not a function.");}return this;},onbeforeexit:function onbeforeexit(providedCallback){if(typeof providedCallback==="function"){this._introBeforeExitCallback=providedCallback;}else {throw new Error("Provided callback for onbeforeexit was not a function.");}return this;},addHints:function addHints(){populateHints.call(this,this._targetElement);return this;},hideHint:function hideHint$1(stepId){hideHint.call(this,stepId);return this;},hideHints:function hideHints$1(){hideHints.call(this);return this;},showHint:function showHint$1(stepId){showHint.call(this,stepId);return this;},showHints:function showHints$1(){showHints.call(this);return this;},removeHints:function removeHints$1
});
3 years ago
/** @license React v17.0.2
* react-dom-server.browser.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var q$1=60106,r=60107,u=60108,z$1=60114,B$2=60109,aa=60110,ba$1=60112,D$2=60113,ca=60120,da$1=60115,ea$1=60116,fa$1=60121,ha=60117,ia=60119,ja=60129,ka=60131;if("function"===typeof Symbol&&Symbol.for){var E$2=Symbol.for;q$1=E$2("react.portal");r=E$2("react.fragment");u=E$2("react.strict_mode");z$1=E$2("react.profiler");B$2=E$2("react.provider");aa=E$2("react.context");ba$1=E$2("react.forward_ref");D$2=E$2("react.suspense");ca=E$2("react.suspense_list");da$1=E$2("react.memo");ea$1=E$2("react.lazy");fa$1=E$2("react.block");ha=E$2("react.fundamental");ia=E$2("react.scope");ja=E$2("react.debug_trace_mode");ka=E$2("react.legacy_hidden");}var la=react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;for(var J$1=new Uint16Array(16),K$1=0;15>K$1;K$1++)J$1[K$1]=K$1+1;J$1[15]=0;function M$1(a,b,c,d,f,h,t){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=h;this.removeEmptyString=t;}var N$1={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){N$1[a]=new M$1(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];N$1[b]=new M$1(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){N$1[a]=new M$1(a,2,!1,a.toLowerCase(),null,!1,!1);});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){N$1[a]=new M$1(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){N$1[a]=new M$1(a,3,!1,a.toLowerCase(),null,!1,!1);});["checked","multiple","muted","selected"].forEach(function(a){N$1[a]=new M$1(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){N$1[a]=new M$1(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){N$1[a]=new M$1(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){N$1[a]=new M$1(a,5,!1,a.toLowerCase(),null,!1,!1);});var va=/[\-:]([a-z])/g;function wa$1(a){return a[1].toUpperCase();}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(va,wa$1);N$1[b]=new M$1(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(va,wa$1);N$1[b]=new M$1(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(va,wa$1);N$1[b]=new M$1(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){N$1[a]=new M$1(a,1,!1,a.toLowerCase(),null,!1,!1);});N$1.xlinkHref=new M$1("xlinkHref",1,!1,"xlink:href","http://www.w3.
3 years ago
/** @license React v17.0.2
* react-dom-server.browser.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
3 years ago
var reactDomServer_browser_development = createCommonjsModule(function (module, exports) {
{(function(){var React=react;var _assign=objectAssign;// Do not require this module directly! Use normal `invariant` calls with
// template literal strings. The messages will be replaced with error codes
// during build.
function formatProdErrorMessage(code){var url='https://reactjs.org/docs/error-decoder.html?invariant='+code;for(var i=1;i<arguments.length;i++){url+='&args[]='+encodeURIComponent(arguments[i]);}return "Minified React error #"+code+"; visit "+url+" for the full message or "+'use the non-minified dev environment for full errors and additional '+'helpful warnings.';}// TODO: this is special because it gets imported during build.
var ReactVersion='17.0.2';var ReactSharedInternals=React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format){{for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}printWarning('warn',format,args);}}function error(format){{for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}printWarning('error',format,args);}}function printWarning(level,format,args){// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;var stack=ReactDebugCurrentFrame.getStackAddendum();if(stack!==''){format+='%s';args=args.concat([stack]);}var argsWithFormat=args.map(function(item){return ''+item;});// Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: '+format);// We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level],console,argsWithFormat);}}// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE=0xeac7;var REACT_PORTAL_TYPE=0xeaca;var REACT_FRAGMENT_TYPE=0xeacb;var REACT_STRICT_MODE_TYPE=0xeacc;var REACT_PROFILER_TYPE=0xead2;var REACT_PROVIDER_TYPE=0xeacd;var REACT_CONTEXT_TYPE=0xeace;var REACT_FORWARD_REF_TYPE=0xead0;var REACT_SUSPENSE_TYPE=0xead1;var REACT_SUSPENSE_LIST_TYPE=0xead8;var REACT_MEMO_TYPE=0xead3;var REACT_LAZY_TYPE=0xead4;var REACT_BLOCK_TYPE=0xead9;var REACT_SERVER_BLOCK_TYPE=0xeada;var REACT_FUNDAMENTAL_TYPE=0xead5;var REACT_SCOPE_TYPE=0xead7;var REACT_OPAQUE_ID_TYPE=0xeae0;var REACT_DEBUG_TRACING_MODE_TYPE=0xeae1;var REACT_OFFSCREEN_TYPE=0xeae2;var REACT_LEGACY_HIDDEN_TYPE=0xeae3;if(typeof Symbol==='function'&&Symbol.for){var symbolFor=Symbol.for;REACT_ELEMENT_TYPE=symbolFor('react.element');REACT_PORTAL_TYPE=symbolFor('react.portal');REACT_FRAGMENT_TYPE=symbolFor('react.fragment');REACT_STRICT_MODE_TYPE=symbolFor('react.strict_mode');REACT_PROFILER_TYPE=symbolFor('react.profiler');REACT_PROVIDER_TYPE=symbolFor('react.provider');REACT_CONTEXT_TYPE=symbolFor('react.context');REACT_FORWARD_REF_TYPE=symbolFor('react.forward_ref');REACT_SUSPENSE_TYPE=symbolFor('react.suspense');REACT_SUSPENSE_LIST_TYPE=symbolFor('react.suspense_list');REACT_MEMO_TYPE=symbolFor('react.memo');REACT_LAZY_TYPE=symbolFor('react.lazy');REACT_BLOCK_TYPE=symbolFor('react.block');REACT_SERVER_BLOCK_TYPE=symbolFor('react.server.block');REACT_FUNDAMENTAL_TYPE=symbolFor('react.fundamental');REACT_SCOPE_TYPE=symbolFor('react.scope');REACT_OPAQUE_ID_TYPE=symbolFor('react.opaque.id');REACT_DEBUG_TRACING_MODE_TYPE=symbolFor('react.debug_trace_mode');REACT_OFFSCREEN_TYPE=symbolFor('react.offscreen');REACT_LEGACY_HIDDEN_TYPE=symbolFor('react.legacy_hidden');}function getWrappedName(outerType,innerType,wrapperName){var functionName=innerType.displayName||innerType.name||'';return outerType.displayName||(functionName!==''?wrapperName+"("+functionName+")":wrapperName);}function getContextName(type){return type.displayName||'Context';}function getComponentName(type){if(type==null){// Host root, text node or just invalid type.
return null;}{if(typeof type.tag==='number'){error('Received an unexpected object in getComponentName(). '+'This is likely a bug in React. Please file an issue.');}}if(typeof type==='function'){return type.displayName||type.name||null;}if(typeof type==='string'){return type;}switch(type){case REACT_FRAGMENT_TYPE:return 'Fragment';case REACT_PORTAL_TYPE:return 'Portal';case REACT_PROFILER_TYPE:return 'Profiler';case REACT_STRICT_MODE_TYPE:return 'StrictMode';case REACT_SUSPENSE_TYPE:return 'Suspense';case REACT_SUSPENSE_LIST_TYPE:return 'SuspenseList';}if(typeof type==='object'){switch(type.$$typeof){case REACT_CONTEXT_TYPE:var context=type;return getContextName(context)+'.Consumer';case REACT_PROVIDER_TYPE:var provider=type;return getContextName(provider._context)+'.Provider';case REACT_FORWARD_REF_TYPE:return getWrappedName(type,type.render,'ForwardRef');case REACT_MEMO_TYPE:return getComponentName(type.type);case REACT_BLOCK_TYPE:return getComponentName(type._render);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{return getComponentName(init(payload));}catch(x){return null;}}}}return null;}// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableSuspenseServerRenderer=false;// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth=0;var prevLog;var prevInfo;var prevWarn;var prevError;var prevGroup;var prevGroupCollapsed;var prevGroupEnd;function disabledLog(){}disabledLog.__reactDisabledLog=true;function disableLogs(){{if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */prevLog=console.log;prevInfo=console.info;prevWarn=console.warn;prevError=console.error;prevGroup=console.group;prevGroupCollapsed=console.groupCollapsed;prevGroupEnd=console.groupEnd;// https://github.com/facebook/react/issues/19099
var props={configurable:true,enumerable:true,value:disabledLog,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{info:props,log:props,warn:props,error:props,group:props,groupCollapsed:props,groupEnd:props});/* eslint-enable react-internal/no-production-logging */}disabledDepth++;}}function reenableLogs(){{disabledDepth--;if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */var props={configurable:true,enumerable:true,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{log:_assign({},props,{value:prevLog}),info:_assign({},props,{value:prevInfo}),warn:_assign({},props,{value:prevWarn}),error:_assign({},props,{value:prevError}),group:_assign({},props,{value:prevGroup}),groupCollapsed:_assign({},props,{value:prevGroupCollapsed}),groupEnd:_assign({},props,{value:prevGroupEnd})});/* eslint-enable react-internal/no-production-logging */}if(disabledDepth<0){error('disabledDepth fell below zero. '+'This is a bug in React. Please file an issue.');}}}var ReactCurrentDispatcher=ReactSharedInternals.ReactCurrentDispatcher;var prefix;function describeBuiltInComponentFrame(name,source,ownerFn){{if(prefix===undefined){// Extract the VM specific prefix used by each line.
try{throw Error();}catch(x){var match=x.stack.trim().match(/\n( *(at )?)/);prefix=match&&match[1]||'';}}// We use the prefix to ensure our stacks line up with native stack frames.
return '\n'+prefix+name;}}var reentry=false;var componentFrameCache;{var PossiblyWeakMap=typeof WeakMap==='function'?WeakMap:Map;componentFrameCache=new PossiblyWeakMap();}function describeNativeComponentFrame(fn,construct){// If something asked for a stack inside a fake render, it should get ignored.
if(!fn||reentry){return '';}{var frame=componentFrameCache.get(fn);if(frame!==undefined){return frame;}}var control;reentry=true;var previousPrepareStackTrace=Error.prepareStackTrace;// $FlowFixMe It does accept undefined.
Error.prepareStackTrace=undefined;var previousDispatcher;{previousDispatcher=ReactCurrentDispatcher.current;// Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher.current=null;disableLogs();}try{// This should throw.
if(construct){// Something should be setting the props in the constructor.
var Fake=function(){throw Error();};// $FlowFixMe
Object.defineProperty(Fake.prototype,'props',{set:function(){// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();}});if(typeof Reflect==='object'&&Reflect.construct){// We construct a different control for this case to include any extra
// frames added by the construct call.
try{Reflect.construct(Fake,[]);}catch(x){control=x;}Reflect.construct(fn,[],Fake);}else {try{Fake.call();}catch(x){control=x;}fn.call(Fake.prototype);}}else {try{throw Error();}catch(x){control=x;}fn();}}catch(sample){// This is inlined manually because closure doesn't do it for us.
if(sample&&control&&typeof sample.stack==='string'){// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines=sample.stack.split('\n');var controlLines=control.stack.split('\n');var s=sampleLines.length-1;var c=controlLines.length-1;while(s>=1&&c>=0&&sampleLines[s]!==controlLines[c]){// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;}for(;s>=1&&c>=0;s--,c--){// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if(sampleLines[s]!==controlLines[c]){// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if(s!==1||c!==1){do{s--;c--;// We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if(c<0||sampleLines[s]!==controlLines[c]){// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame='\n'+sampleLines[s].replace(' at new ',' at ');{if(typeof fn==='function'){componentFrameCache.set(fn,_frame);}}// Return the line we found.
return _frame;}}while(s>=1&&c>=0);}break;}}}}finally{reentry=false;{ReactCurrentDispatcher.current=previousDispatcher;reenableLogs();}Error.prepareStackTrace=previousPrepareStackTrace;}// Fallback to just using the name if we couldn't make it throw.
var name=fn?fn.displayName||fn.name:'';var syntheticFrame=name?describeBuiltInComponentFrame(name):'';{if(typeof fn==='function'){componentFrameCache.set(fn,syntheticFrame);}}return syntheticFrame;}function describeFunctionComponentFrame(fn,source,ownerFn){{return describeNativeComponentFrame(fn,false);}}function shouldConstruct(Component){var prototype=Component.prototype;return !!(prototype&&prototype.isReactComponent);}function describeUnknownElementTypeFrameInDEV(type,source,ownerFn){if(type==null){return '';}if(typeof type==='function'){{return describeNativeComponentFrame(type,shouldConstruct(type));}}if(typeof type==='string'){return describeBuiltInComponentFrame(type);}switch(type){case REACT_SUSPENSE_TYPE:return describeBuiltInComponentFrame('Suspense');case REACT_SUSPENSE_LIST_TYPE:return describeBuiltInComponentFrame('SuspenseList');}if(typeof type==='object'){switch(type.$$typeof){case REACT_FORWARD_REF_TYPE:return describeFunctionComponentFrame(type.render);case REACT_MEMO_TYPE:// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type,source,ownerFn);case REACT_BLOCK_TYPE:return describeFunctionComponentFrame(type._render);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload),source,ownerFn);}catch(x){}}}}return '';}var loggedTypeFailures={};var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;function setCurrentlyValidatingElement(element){{if(element){var owner=element._owner;var stack=describeUnknownElementTypeFrameInDEV(element.type,element._source,owner?owner.type:null);ReactDebugCurrentFrame.setExtraStackFrame(stack);}else {ReactDebugCurrentFrame.setExtraStackFrame(null);}}}function checkPropTypes(typeSpecs,values,location,componentName,element){{// $FlowFixMe This is okay but Flow doesn't know it.
var has=Function.call.bind(Object.prototype.hasOwnProperty);for(var typeSpecName in typeSpecs){if(has(typeSpecs,typeSpecName)){var error$1=void 0;// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try{// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if(typeof typeSpecs[typeSpecName]!=='function'){var err=Error((componentName||'React class')+': '+location+' type `'+typeSpecName+'` is invalid; '+'it must be a function, usually from the `prop-types` package, but received `'+typeof typeSpecs[typeSpecName]+'`.'+'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');err.name='Invariant Violation';throw err;}error$1=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');}catch(ex){error$1=ex;}if(error$1&&!(error$1 instanceof Error)){setCurrentlyValidatingElement(element);error('%s: type specification of %s'+' `%s` is invalid; the type checker '+'function must return `null` or an `Error` but returned a %s. '+'You may have forgotten to pass an argument to the type checker '+'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and '+'shape all require an argument).',componentName||'React class',location,typeSpecName,typeof error$1);setCurrentlyValidatingElement(null);}if(error$1 instanceof Error&&!(error$1.message in loggedTypeFailures)){// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message]=true;setCurrentlyValidatingElement(element);error('Failed %s type: %s',location,error$1.message);setCurrentlyValidatingElement(null);}}}}}var didWarnAboutInvalidateContextType;{didWarnAboutInvalidateContextType=new Set();}var emptyObject={};{Object.freeze(emptyObject);}function maskContext(type,context){var contextTypes=type.contextTypes;if(!contextTypes){return emptyObject;}var maskedContext={};for(var contextName in contextTypes){maskedContext[contextName]=context[contextName];}return maskedContext;}function checkContextTypes(typeSpecs,values,location){{checkPropTypes(typeSpecs,values,location,'Component');}}function validateContextBounds(context,threadID){// If we don't have enough slots in this context to store this threadID,
// fill it in without leaving any holes to ensure that the VM optimizes
// this as non-holey index properties.
// (Note: If `react` package is < 16.6, _threadCount is undefined.)
for(var i=context._threadCount|0;i<=threadID;i++){// We assume that this is the same as the defaultValue which might not be
// true if we're rendering inside a secondary renderer but they are
// secondary because these use cases are very rare.
context[i]=context._currentValue2;context._threadCount=i+1;}}function processContext(type,context,threadID,isClass){if(isClass){var contextType=type.contextType;{if('contextType'in type){var isValid=// Allow null for conditional declaration
contextType===null||contextType!==undefined&&contextType.$$typeof===REACT_CONTEXT_TYPE&&contextType._context===undefined;// Not a <Context.Consumer>
if(!isValid&&!didWarnAboutInvalidateContextType.has(type)){didWarnAboutInvalidateContextType.add(type);var addendum='';if(contextType===undefined){addendum=' However, it is set to undefined. '+'This can be caused by a typo or by mixing up named and default imports. '+'This can also happen due to a circular dependency, so '+'try moving the createContext() call to a separate file.';}else if(typeof contextType!=='object'){addendum=' However, it is set to a '+typeof contextType+'.';}else if(contextType.$$typeof===REACT_PROVIDER_TYPE){addendum=' Did you accidentally pass the Context.Provider instead?';}else if(contextType._context!==undefined){// <Context.Consumer>
addendum=' Did you accidentally pass the Context.Consumer instead?';}else {addendum=' However, it is set to an object with keys {'+Object.keys(contextType).join(', ')+'}.';}error('%s defines an invalid contextType. '+'contextType should point to the Context object returned by React.createContext().%s',getComponentName(type)||'Component',addendum);}}}if(typeof contextType==='object'&&contextType!==null){validateContextBounds(contextType,threadID);return contextType[threadID];}{var maskedContext=maskContext(type,context);{if(type.contextTypes){checkContextTypes(type.contextTypes,maskedContext,'context');}}return maskedContext;}}else {{var _maskedContext=maskContext(type,context);{if(type.contextTypes){checkContextTypes(type.contextTypes,_maskedContext,'context');}}return _maskedContext;}}}var nextAvailableThreadIDs=new Uint16Array(16);for(var i=0;i<15;i++){nextAvailableThreadIDs[i]=i+1;}nextAvailableThreadIDs[15]=0;function growThreadCountAndReturnNextAvailable(){var oldArray=nextAvailableThreadIDs;var oldSize=oldArray.length;var newSize=oldSize*2;if(!(newSize<=0x10000)){{throw Error("Maximum number of concurrent React renderers exceeded. This can happen if you are not properly destroying the Readable provided by React. Ensure that you call .destroy() on it if you no longer want to read from it, and did not read to the end. If you use .pipe() this should be automatic.");}}var newArray=new Uint16Array(newSize);newArray.set(oldArray);nextAvailableThreadIDs=newArray;nextAvailableThreadIDs[0]=oldSize+1;for(var _i=oldSize;_i<newSize-1;_i++){nextAvailableThreadIDs[_i]=_i+1;}nextAvailableThreadIDs[newSize-1]=0;return oldSize;}function allocThreadID(){var nextID=nextAvailableThreadIDs[0];if(nextID===0){return growThreadCountAndReturnNextAvailable();}nextAvailableThreadIDs[0]=nextAvailableThreadIDs[nextID];return nextID;}function freeThreadID(id){nextAvailableThreadIDs[id]=nextAvailableThreadIDs[0];nextAvailableThreadIDs[0]=id;}// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED=0;// A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.
var STRING=1;// A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.
var BOOLEANISH_STRING=2;// A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
var BOOLEAN=3;// An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.
var OVERLOADED_BOOLEAN=4;// An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.
var NUMERIC=5;// An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.
var POSITIVE_NUMERIC=6;/* eslint-disable max-len */var ATTRIBUTE_NAME_START_CHAR=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";/* eslint-enable max-len */var ATTRIBUTE_NAME_CHAR=ATTRIBUTE_NAME_START_CHAR+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";var ROOT_ATTRIBUTE_NAME='data-reactroot';var VALID_ATTRIBUTE_NAME_REGEX=new RegExp('^['+ATTRIBUTE_NAME_START_CHAR+']['+ATTRIBUTE_NAME_CHAR+']*$');var hasOwnProperty=Object.prototype.hasOwnProperty;var illegalAttributeNameCache={};var validatedAttributeNameCache={};function isAttributeNameSafe(attributeName){if(hasOwnProperty.call(validatedAttributeNameCache,attributeName)){return true;}if(hasOwnProperty.call(illegalAttributeNameCache,attributeName)){return false;}if(VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)){validatedAttributeNameCache[attributeName]=true;return true;}illegalAttributeNameCache[attributeName]=true;{error('Invalid attribute name: `%s`',attributeName);}return false;}function shouldIgnoreAttribute(name,propertyInfo,isCustomComponentTag){if(propertyInfo!==null){return propertyInfo.type===RESERVED;}if(isCustomComponentTag){return false;}if(name.length>2&&(name[0]==='o'||name[0]==='O')&&(name[1]==='n'||name[1]==='N')){return true;}return false;}function shouldRemoveAttributeWithWarning(name,value,propertyInfo,isCustomComponentTag){if(propertyInfo!==null&&propertyInfo.type===RESERVED){return false;}switch(typeof value){case'function':// $FlowIssue symbol is perfectly valid here
case'symbol':// eslint-disable-line
return true;case'boolean':{if(isCustomComponentTag){return false;}if(propertyInfo!==null){return !propertyInfo.acceptsBooleans;}else {var prefix=name.toLowerCase().slice(0,5);return prefix!=='data-'&&prefix!=='aria-';}}default:return false;}}function shouldRemoveAttribute(name,value,propertyInfo,isCustomComponentTag){if(value===null||typeof value==='undefined'){return true;}if(shouldRemoveAttributeWithWarning(name,value,propertyInfo,isCustomComponentTag)){return true;}if(isCustomComponentTag){return false;}if(propertyInfo!==null){switch(propertyInfo.type){case BOOLEAN:return !value;case OVERLOADED_BOOLEAN:return value===false;case NUMERIC:return isNaN(value);case POSITIVE_NUMERIC:return isNaN(value)||value<1;}}return false;}function getPropertyInfo(name){return properties.hasOwnProperty(name)?properties[name]:null;}function PropertyInfoRecord(name,type,mustUseProperty,attributeName,attributeNamespace,sanitizeURL,removeEmptyString){this.acceptsBooleans=type===BOOLEANISH_STRING||type===BOOLEAN||type===OVERLOADED_BOOLEAN;this.attributeName=attributeName;this.attributeNamespace=attributeNamespace;this.mustUseProperty=mustUseProperty;this.propertyName=name;this.type=type;this.sanitizeURL=sanitizeURL;this.removeEmptyString=removeEmptyString;}// When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.
var properties={};// These props are reserved by React. They shouldn't be written to the DOM.
var reservedProps=['children','dangerouslySetInnerHTML',// TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue','defaultChecked','innerHTML','suppressContentEditableWarning','suppressHydrationWarning','style'];reservedProps.forEach(function(name){properties[name]=new PropertyInfoRecord(name,RESERVED,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.
[['acceptCharset','accept-charset'],['className','class'],['htmlFor','for'],['httpEquiv','http-equiv']].forEach(function(_ref){var name=_ref[0],attributeName=_ref[1];properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
['contentEditable','draggable','spellCheck','value'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEANISH_STRING,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.
['autoReverse','externalResourcesRequired','focusable','preserveAlpha'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEANISH_STRING,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML boolean attributes.
['allowFullScreen','async',// Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus','autoPlay','controls','default','defer','disabled','disablePictureInPicture','disableRemotePlayback','formNoValidate','hidden','loop','noModule','noValidate','open','playsInline','readOnly','required','reversed','scoped','seamless',// Microdata
'itemScope'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEAN,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.
['checked',// Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple','muted','selected'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEAN,true,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.
['capture','download'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,OVERLOADED_BOOLEAN,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that must be positive numbers.
['cols','rows','size','span'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,POSITIVE_NUMERIC,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that must be numbers.
['rowSpan','start'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,NUMERIC,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});var CAMELIZE=/[\-\:]([a-z])/g;var capitalize=function(token){return token[1].toUpperCase();};// This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.
['accent-height','alignment-baseline','arabic-form','baseline-shift','cap-height','clip-path','clip-rule','color-interpolation','color-interpolation-filters','color-profile','color-rendering','dominant-baseline','enable-background','fill-opacity','fill-rule','flood-color','flood-opacity','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','glyph-name','glyph-orientation-horizontal','glyph-orientation-vertical','horiz-adv-x','horiz-origin-x','image-rendering','letter-spacing','lighting-color','marker-end','marker-mid','marker-start','overline-position','overline-thickness','paint-order','panose-1','pointer-events','rendering-intent','shape-rendering','stop-color','stop-opacity','strikethrough-position','strikethrough-thickness','stroke-dasharray','stroke-dashoffset','stroke-linecap','stroke-linejoin','stroke-miterlimit','stroke-opacity','stroke-width','text-anchor','text-decoration','text-rendering','underline-position','underline-thickness','unicode-bidi','unicode-range','units-per-em','v-alphabetic','v-hanging','v-ideographic','v-mathematical','vector-effect','vert-adv-y','vert-origin-x','vert-origin-y','word-spacing','writing-mode','xmlns:xlink','x-height'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,null,// attributeNamespace
false,// sanitizeURL
false);});// String SVG attributes with the xlink namespace.
['xlink:actuate','xlink:arcrole','xlink:role','xlink:show','xlink:title','xlink:type'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,'http://www.w3.org/1999/xlink',false,// sanitizeURL
false);});// String SVG attributes with the xml namespace.
['xml:base','xml:lang','xml:space'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,'http://www.w3.org/XML/1998/namespace',false,// sanitizeURL
false);});// These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.
['tabIndex','crossOrigin'].forEach(function(attributeName){properties[attributeName]=new PropertyInfoRecord(attributeName,STRING,false,// mustUseProperty
attributeName.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.
var xlinkHref='xlinkHref';properties[xlinkHref]=new PropertyInfoRecord('xlinkHref',STRING,false,// mustUseProperty
'xlink:href','http://www.w3.org/1999/xlink',true,// sanitizeURL
false);['src','href','action','formAction'].forEach(function(attributeName){properties[attributeName]=new PropertyInfoRecord(attributeName,STRING,false,// mustUseProperty
attributeName.toLowerCase(),// attributeName
null,// attributeNamespace
true,// sanitizeURL
true);});// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space
/* eslint-disable max-len */var isJavaScriptProtocol=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;var didWarn=false;function sanitizeURL(url){{if(!didWarn&&isJavaScriptProtocol.test(url)){didWarn=true;error('A future version of React will block javascript: URLs as a security precaution. '+'Use event handlers instead if you can. If you need to generate unsafe HTML try '+'using dangerouslySetInnerHTML instead. React was passed %s.',JSON.stringify(url));}}}// code copied and modified from escape-html
/**
* Module variables.
* @private
*/var matchHtmlRegExp=/["'&<>]/;/**
* Escapes special characters and HTML entities in a given html string.
*
* @param {string} string HTML string to escape for later insertion
* @return {string}
* @public
*/function escapeHtml(string){var str=''+string;var match=matchHtmlRegExp.exec(str);if(!match){return str;}var escape;var html='';var index;var lastIndex=0;for(index=match.index;index<str.length;index++){switch(str.charCodeAt(index)){case 34:// "
escape='&quot;';break;case 38:// &
escape='&amp;';break;case 39:// '
escape='&#x27;';// modified from escape-html; used to be '&#39'
break;case 60:// <
escape='&lt;';break;case 62:// >
escape='&gt;';break;default:continue;}if(lastIndex!==index){html+=str.substring(lastIndex,index);}lastIndex=index+1;html+=escape;}return lastIndex!==index?html+str.substring(lastIndex,index):html;}// end code copied and modified from escape-html
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/function escapeTextForBrowser(text){if(typeof text==='boolean'||typeof text==='number'){// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
return ''+text;}return escapeHtml(text);}/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/function quoteAttributeValueForBrowser(value){return '"'+escapeTextForBrowser(value)+'"';}function createMarkupForRoot(){return ROOT_ATTRIBUTE_NAME+'=""';}/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/function createMarkupForProperty(name,value){var propertyInfo=getPropertyInfo(name);if(name!=='style'&&shouldIgnoreAttribute(name,propertyInfo,false)){return '';}if(shouldRemoveAttribute(name,value,propertyInfo,false)){return '';}if(propertyInfo!==null){var attributeName=propertyInfo.attributeName;var type=propertyInfo.type;if(type===BOOLEAN||type===OVERLOADED_BOOLEAN&&value===true){return attributeName+'=""';}else {if(propertyInfo.sanitizeURL){value=''+value;sanitizeURL(value);}return attributeName+'='+quoteAttributeValueForBrowser(value);}}else if(isAttributeNameSafe(name)){return name+'='+quoteAttributeValueForBrowser(value);}return '';}/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/function createMarkupForCustomAttribute(name,value){if(!isAttributeNameSafe(name)||value==null){return '';}return name+'='+quoteAttributeValueForBrowser(value);}/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y// eslint-disable-line no-self-compare
;}var objectIs=typeof Object.is==='function'?Object.is:is;var currentlyRenderingComponent=null;var firstWorkInProgressHook=null;var workInProgressHook=null;// Whether the work-in-progress hook is a re-rendered hook
var isReRender=false;// Whether an update was scheduled during the currently executing render pass.
var didScheduleRenderPhaseUpdate=false;// Lazily created map of render-phase updates
var renderPhaseUpdates=null;// Counter to prevent infinite loops.
var numberOfReRenders=0;var RE_RENDER_LIMIT=25;var isInHookUserCodeInDev=false;// In DEV, this is the name of the currently executing primitive hook
var currentHookNameInDev;function resolveCurrentlyRenderingComponent(){if(!(currentlyRenderingComponent!==null)){{throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");}}{if(isInHookUserCodeInDev){error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. '+'You can only call Hooks at the top level of your React function. '+'For more information, see '+'https://reactjs.org/link/rules-of-hooks');}}return currentlyRenderingComponent;}function areHookInputsEqual(nextDeps,prevDeps){if(prevDeps===null){{error('%s received a final argument during this render, but not during '+'the previous render. Even though the final argument is optional, '+'its type cannot change between renders.',currentHookNameInDev);}return false;}{// Don't bother comparing lengths in prod because these arrays should be
// passed inline.
if(nextDeps.length!==prevDeps.length){error('The final argument passed to %s changed size between renders. The '+'order and size of this array must remain constant.\n\n'+'Previous: %s\n'+'Incoming: %s',currentHookNameInDev,"["+nextDeps.join(', ')+"]","["+prevDeps.join(', ')+"]");}}for(var i=0;i<prevDeps.length&&i<nextDeps.length;i++){if(objectIs(nextDeps[i],prevDeps[i])){continue;}return false;}return true;}function createHook(){if(numberOfReRenders>0){{{throw Error("Rendered more hooks than during the previous render");}}}return {memoizedState:null,queue:null,next:null};}function createWorkInProgressHook(){if(workInProgressHook===null){// This is the first hook in the list
if(firstWorkInProgressHook===null){isReRender=false;firstWorkInProgressHook=workInProgressHook=createHook();}else {// There's already a work-in-progress. Reuse it.
isReRender=true;workInProgressHook=firstWorkInProgressHook;}}else {if(workInProgressHook.next===null){isReRender=false;// Append to the end of the list
workInProgressHook=workInProgressHook.next=createHook();}else {// There's already a work-in-progress. Reuse it.
isReRender=true;workInProgressHook=workInProgressHook.next;}}return workInProgressHook;}function prepareToUseHooks(componentIdentity){currentlyRenderingComponent=componentIdentity;{isInHookUserCodeInDev=false;}// The following should have already been reset
// didScheduleRenderPhaseUpdate = false;
// firstWorkInProgressHook = null;
// numberOfReRenders = 0;
// renderPhaseUpdates = null;
// workInProgressHook = null;
}function finishHooks(Component,props,children,refOrContext){// This must be called after every function component to prevent hooks from
// being used in classes.
while(didScheduleRenderPhaseUpdate){// Updates were scheduled during the render phase. They are stored in
// the `renderPhaseUpdates` map. Call the component again, reusing the
// work-in-progress hooks and applying the additional updates on top. Keep
// restarting until no more updates are scheduled.
didScheduleRenderPhaseUpdate=false;numberOfReRenders+=1;// Start over from the beginning of the list
workInProgressHook=null;children=Component(props,refOrContext);}resetHooksState();return children;}// Reset the internal hooks state if an error occurs while rendering a component
function resetHooksState(){{isInHookUserCodeInDev=false;}currentlyRenderingComponent=null;didScheduleRenderPhaseUpdate=false;firstWorkInProgressHook=null;numberOfReRenders=0;renderPhaseUpdates=null;workInProgressHook=null;}function readContext(context,observedBits){var threadID=currentPartialRenderer.threadID;validateContextBounds(context,threadID);{if(isInHookUserCodeInDev){error('Context can only be read while React is rendering. '+'In classes, you can read it in the render method or getDerivedStateFromProps. '+'In function components, you can read it directly in the function body, but not '+'inside Hooks like useReducer() or useMemo().');}}return context[threadID];}function useContext(context,observedBits){{currentHookNameInDev='useContext';}resolveCurrentlyRenderingComponent();var threadID=currentPartialRenderer.threadID;validateContextBounds(context,threadID);return context[threadID];}function basicStateReducer(state,action){// $FlowFixMe: Flow doesn't like mixed types
return typeof action==='function'?action(state):action;}function useState(initialState){{currentHookNameInDev='useState';}return useReducer(basicStateReducer,// useReducer has a special case to support lazy useState initializers
initialState);}function useReducer(reducer,initialArg,init){{if(reducer!==basicStateReducer){currentHookNameInDev='useReducer';}}currentlyRenderingComponent=resolveCurrentlyRenderingComponent();workInProgressHook=createWorkInProgressHook();if(isReRender){// This is a re-render. Apply the new render phase updates to the previous
// current hook.
var queue=workInProgressHook.queue;var dispatch=queue.dispatch;if(renderPhaseUpdates!==null){// Render phase updates are stored in a map of queue -> linked list
var firstRenderPhaseUpdate=renderPhaseUpdates.get(queue);if(firstRenderPhaseUpdate!==undefined){renderPhaseUpdates.delete(queue);var newState=workInProgressHook.memoizedState;var update=firstRenderPhaseUpdate;do{// Process this render phase update. We don't have to check the
// priority because it will always be the same as the current
// render's.
var action=update.action;{isInHookUserCodeInDev=true;}newState=reducer(newState,action);{isInHookUserCodeInDev=false;}update=update.next;}while(update!==null);workInProgressHook.memoizedState=newState;return [newState,dispatch];}}return [workInProgressHook.memoizedState,dispatch];}else {{isInHookUserCodeInDev=true;}var initialState;if(reducer===basicStateReducer){// Special case for `useState`.
initialState=typeof initialArg==='function'?initialArg():initialArg;}else {initialState=init!==undefined?init(initialArg):initialArg;}{isInHookUserCodeInDev=false;}workInProgressHook.memoizedState=initialState;var _queue=workInProgressHook.queue={last:null,dispatch:null};var _dispatch=_queue.dispatch=dispatchAction.bind(null,currentlyRenderingComponent,_queue);return [workInProgressHook.memoizedState,_dispatch];}}function useMemo(nextCreate,deps){currentlyRenderingComponent=resolveCurrentlyRenderingComponent();workInProgressHook=createWorkInProgressHook();var nextDeps=deps===undefined?null:deps;if(workInProgressHook!==null){var prevState=workInProgressHook.memoizedState;if(prevState!==null){if(nextDeps!==null){var prevDeps=prevState[1];if(areHookInputsEqual(nextDeps,prevDeps)){return prevState[0];}}}}{isInHookUserCodeInDev=true;}var nextValue=nextCreate();{isInHookUserCodeInDev=false;}workInProgressHook.memoizedState=[nextValue,nextDeps];return nextValue;}function useRef(initialValue){currentlyRenderingComponent=resolveCurrentlyRenderingComponent();workInProgressHook=createWorkInProgressHook();var previousRef=workInProgressHook.memoizedState;if(previousRef===null){var ref={current:initialValue};{Object.seal(ref);}workInProgressHook.memoizedState=ref;return ref;}else {return previousRef;}}function useLayoutEffect(create,inputs){{currentHookNameInDev='useLayoutEffect';error('useLayoutEffect does nothing on the server, because its effect cannot '+"be encoded into the server renderer's output format. This will lead "+'to a mismatch between the initial, non-hydrated UI and the intended '+'UI. To avoid this, useLayoutEffect should only be used in '+'components that render exclusively on the client. '+'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');}}function dispatchAction(componentIdentity,queue,action){if(!(numberOfReRenders<RE_RENDER_LIMIT)){{throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");}}if(componentIdentity===currentlyRenderingComponent){// This is a render phase update. Stash it in a lazily-created map of
// queue -> linked list of updates. After this render pass, we'll restart
// and apply the stashed updates on top of the work-in-progress hook.
didScheduleRenderPhaseUpdate=true;var update={action:action,next:null};if(renderPhaseUpdates===null){renderPhaseUpdates=new Map();}var firstRenderPhaseUpdate=renderPhaseUpdates.get(queue);if(firstRenderPhaseUpdate===undefined){renderPhaseUpdates.set(queue,update);}else {// Append the update to the end of the list.
var lastRenderPhaseUpdate=firstRenderPhaseUpdate;while(lastRenderPhaseUpdate.next!==null){lastRenderPhaseUpdate=lastRenderPhaseUpdate.next;}lastRenderPhaseUpdate.next=update;}}}function useCallback(callback,deps){return useMemo(function(){return callback;},deps);}// TODO Decide on how to implement this hook for server rendering.
// If a mutation occurs during render, consider triggering a Suspense boundary
// and falling back to client rendering.
function useMutableSource(source,getSnapshot,subscribe){resolveCurrentlyRenderingComponent();return getSnapshot(source._source);}function useDeferredValue(value){resolveCurrentlyRenderingComponent();return value;}function useTransition(){resolveCurrentlyRenderingComponent();var startTransition=function(callback){callback();};return [startTransition,false];}function useOpaqueIdentifier(){return (currentPartialRenderer.identifierPrefix||'')+'R:'+(currentPartialRenderer.uniqueID++).toString(36);}function noop(){}var currentPartialRenderer=null;function setCurrentPartialRenderer(renderer){currentPartialRenderer=renderer;}var Dispatcher={readContext:readContext,useContext:useContext,useMemo:useMemo,useReducer:useReducer,useRef:useRef,useState:useState,useLayoutEffect:useLayoutEffect,useCallback:useCallback,// useImperativeHandle is not run in the server environment
useImperativeHandle:noop,// Effects are not run in the server environment.
useEffect:noop,// Debugging effect
useDebugValue:noop,useDeferredValue:useDeferredValue,useTransition:useTransition,useOpaqueIdentifier:useOpaqueIdentifier,// Subscriptions are not setup in a server environment.
useMutableSource:useMutableSource};var HTML_NAMESPACE='http://www.w3.org/1999/xhtml';var MATH_NAMESPACE='http://www.w3.org/1998/Math/MathML';var SVG_NAMESPACE='http://www.w3.org/2000/svg';var Namespaces={html:HTML_NAMESPACE,mathml:MATH_NAMESPACE,svg:SVG_NAMESPACE};// Assumes there is no parent namespace.
function getIntrinsicNamespace(type){switch(type){case'svg':return SVG_NAMESPACE;case'math':return MATH_NAMESPACE;default:return HTML_NAMESPACE;}}function getChildNamespace(parentNamespace,type){if(parentNamespace==null||parentNamespace===HTML_NAMESPACE){// No (or default) parent namespace: potential entry point.
return getIntrinsicNamespace(type);}if(parentNamespace===SVG_NAMESPACE&&type==='foreignObject'){// We're leaving SVG.
return HTML_NAMESPACE;}// By default, pass namespace below.
return parentNamespace;}var hasReadOnlyValue={button:true,checkbox:true,image:true,hidden:true,radio:true,reset:true,submit:true};function checkControlledValueProps(tagName,props){{if(!(hasReadOnlyValue[props.type]||props.onChange||props.onInput||props.readOnly||props.disabled||props.value==null)){error('You provided a `value` prop to a form field without an '+'`onChange` handler. This will render a read-only field. If '+'the field should be mutable use `defaultValue`. Otherwise, '+'set either `onChange` or `readOnly`.');}if(!(props.onChange||props.readOnly||props.disabled||props.checked==null)){error('You provided a `checked` prop to a form field without an '+'`onChange` handler. This will render a read-only field. If '+'the field should be mutable use `defaultChecked`. Otherwise, '+'set either `onChange` or `readOnly`.');}}}// For HTML, certain tags should omit their close tag. We keep a list for
// those special-case tags.
var omittedCloseTags={area:true,base:true,br:true,col:true,embed:true,hr:true,img:true,input:true,keygen:true,link:true,meta:true,param:true,source:true,track:true,wbr:true// NOTE: menuitem's close tag should be omitted, but that causes problems.
};// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags=_assign({menuitem:true},omittedCloseTags);var HTML='__html';function assertValidProps(tag,props){if(!props){return;}// Note the use of `==` which checks for null or undefined.
if(voidElementTags[tag]){if(!(props.children==null&&props.dangerouslySetInnerHTML==null)){{throw Error(tag+" is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");}}}if(props.dangerouslySetInnerHTML!=null){if(!(props.children==null)){{throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");}}if(!(typeof props.dangerouslySetInnerHTML==='object'&&HTML in props.dangerouslySetInnerHTML)){{throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");}}}{if(!props.suppressContentEditableWarning&&props.contentEditable&&props.children!=null){error('A component is `contentEditable` and contains `children` managed by '+'React. It is now your responsibility to guarantee that none of '+'those nodes are unexpectedly modified or duplicated. This is '+'probably not intentional.');}}if(!(props.style==null||typeof props.style==='object')){{throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");}}}/**
* CSS properties which accept numbers but are not in units of "px".
*/var isUnitlessNumber={animationIterationCount:true,borderImageOutset:true,borderImageSlice:true,borderImageWidth:true,boxFlex:true,boxFlexGroup:true,boxOrdinalGroup:true,columnCount:true,columns:true,flex:true,flexGrow:true,flexPositive:true,flexShrink:true,flexNegative:true,flexOrder:true,gridArea:true,gridRow:true,gridRowEnd:true,gridRowSpan:true,gridRowStart:true,gridColumn:true,gridColumnEnd:true,gridColumnSpan:true,gridColumnStart:true,fontWeight:true,lineClamp:true,lineHeight:true,opacity:true,order:true,orphans:true,tabSize:true,widows:true,zIndex:true,zoom:true,// SVG-related properties
fillOpacity:true,floodOpacity:true,stopOpacity:true,strokeDasharray:true,strokeDashoffset:true,strokeMiterlimit:true,strokeOpacity:true,strokeWidth:true};/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/function prefixKey(prefix,key){return prefix+key.charAt(0).toUpperCase()+key.substring(1);}/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/var prefixes=['Webkit','ms','Moz','O'];// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function(prop){prefixes.forEach(function(prefix){isUnitlessNumber[prefixKey(prefix,prop)]=isUnitlessNumber[prop];});});/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/function dangerousStyleValue(name,value,isCustomProperty){// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty=value==null||typeof value==='boolean'||value==='';if(isEmpty){return '';}if(!isCustomProperty&&typeof value==='number'&&value!==0&&!(isUnitlessNumber.hasOwnProperty(name)&&isUnitlessNumber[name])){return value+'px';// Presumes implicit 'px' suffix for unitless numbers
}return (''+value).trim();}var uppercasePattern=/([A-Z])/g;var msPattern=/^ms-/;/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*/function hyphenateStyleName(name){return name.replace(uppercasePattern,'-$1').toLowerCase().replace(msPattern,'-ms-');}function isCustomComponent(tagName,props){if(tagName.indexOf('-')===-1){return typeof props.is==='string';}switch(tagName){// These are reserved SVG and MathML elements.
// We don't mind this list too much because we expect it to never grow.
// The alternative is to track the namespace in a few places which is convoluted.
// https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
case'annotation-xml':case'color-profile':case'font-face':case'font-face-src':case'font-face-uri':case'font-face-format':case'font-face-name':case'missing-glyph':return false;default:return true;}}var warnValidStyle=function(){};{// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern=/^(?:webkit|moz|o)[A-Z]/;var msPattern$1=/^-ms-/;var hyphenPattern=/-(.)/g;// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern=/;\s*$/;var warnedStyleNames={};var warnedStyleValues={};var warnedForNaNValue=false;var warnedForInfinityValue=false;var camelize=function(string){return string.replace(hyphenPattern,function(_,character){return character.toUpperCase();});};var warnHyphenatedStyleName=function(name){if(warnedStyleNames.hasOwnProperty(name)&&warnedStyleNames[name]){return;}warnedStyleNames[name]=true;error('Unsupported style property %s. Did you mean %s?',name,// As Andi Smith suggests
// (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
// is converted to lowercase `ms`.
camelize(name.replace(msPattern$1,'ms-')));};var warnBadVendoredStyleName=function(name){if(warnedStyleNames.hasOwnProperty(name)&&warnedStyleNames[name]){return;}warnedStyleNames[name]=true;error('Unsupported vendor-prefixed style property %s. Did you mean %s?',name,name.charAt(0).toUpperCase()+name.slice(1));};var warnStyleValueWithSemicolon=function(name,value){if(warnedStyleValues.hasOwnProperty(value)&&warnedStyleValues[value]){return;}warnedStyleValues[value]=true;error("Style property values shouldn't contain a semicolon. "+'Try "%s: %s" instead.',name,value.replace(badStyleValueWithSemicolonPattern,''));};var warnStyleValueIsNaN=function(name,value){if(warnedForNaNValue){return;}warnedForNaNValue=true;error('`NaN` is an invalid value for the `%s` css style property.',name);};var warnStyleValueIsInfinity=function(name,value){if(warnedForInfinityValue){return;}warnedForInfinityValue=true;error('`Infinity` is an invalid value for the `%s` css style property.',name);};warnValidStyle=function(name,value){if(name.indexOf('-')>-1){warnHyphenatedStyleName(name);}else if(badVendoredStyleNamePattern.test(name)){warnBadVendoredStyleName(name);}else if(badStyleValueWithSemicolonPattern.test(value)){warnStyleValueWithSemicolon(name,value);}if(typeof value==='number'){if(isNaN(value)){warnStyleValueIsNaN(name,value);}else if(!isFinite(value)){warnStyleValueIsInfinity(name,value);}}};}var warnValidStyle$1=warnValidStyle;var ariaProperties={'aria-current':0,// state
'aria-details':0,'aria-disabled':0,// state
'aria-hidden':0,// state
'aria-invalid':0,// state
'aria-keyshortcuts':0,'aria-label':0,'aria-roledescription':0,// Widget Attributes
'aria-autocomplete':0,'aria-checked':0,'aria-expanded':0,'aria-haspopup':0,'aria-level':0,'aria-modal':0,'aria-multiline':0,'aria-multiselectable':0,'aria-orientation':0,'aria-placeholder':0,'aria-pressed':0,'aria-readonly':0,'aria-required':0,'aria-selected':0,'aria-sort':0,'aria-valuemax':0,'aria-valuemin':0,'aria-valuenow':0,'aria-valuetext':0,// Live Region Attributes
'aria-atomic':0,'aria-busy':0,'aria-live':0,'aria-relevant':0,// Drag-and-Drop Attributes
'aria-dropeffect':0,'aria-grabbed':0,// Relationship Attributes
'aria-activedescendant':0,'aria-colcount':0,'aria-colindex':0,'aria-colspan':0,'aria-controls':0,'aria-describedby':0,'aria-errormessage':0,'aria-flowto':0,'aria-labelledby':0,'aria-owns':0,'aria-posinset':0,'aria-rowcount':0,'aria-rowindex':0,'aria-rowspan':0,'aria-setsize':0};var warnedProperties={};var rARIA=new RegExp('^(aria)-['+ATTRIBUTE_NAME_CHAR+']*$');var rARIACamel=new RegExp('^(aria)[A-Z]['+ATTRIBUTE_NAME_CHAR+']*$');var hasOwnProperty$1=Object.prototype.hasOwnProperty;function validateProperty(tagName,name){{if(hasOwnProperty$1.call(warnedProperties,name)&&warnedProperties[name]){return true;}if(rARIACamel.test(name)){var ariaName='aria-'+name.slice(4).toLowerCase();var correctName=ariaProperties.hasOwnProperty(ariaName)?ariaName:null;// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if(correctName==null){error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.',name);warnedProperties[name]=true;return true;}// aria-* attributes should be lowercase; suggest the lowercase version.
if(name!==correctName){error('Invalid ARIA attribute `%s`. Did you mean `%s`?',name,correctName);warnedProperties[name]=true;return true;}}if(rARIA.test(name)){var lowerCasedName=name.toLowerCase();var standardName=ariaProperties.hasOwnProperty(lowerCasedName)?lowerCasedName:null;// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if(standardName==null){warnedProperties[name]=true;return false;}// aria-* attributes should be lowercase; suggest the lowercase version.
if(name!==standardName){error('Unknown ARIA attribute `%s`. Did you mean `%s`?',name,standardName);warnedProperties[name]=true;return true;}}}return true;}function warnInvalidARIAProps(type,props){{var invalidProps=[];for(var key in props){var isValid=validateProperty(type,key);if(!isValid){invalidProps.push(key);}}var unknownPropString=invalidProps.map(function(prop){return '`'+prop+'`';}).join(', ');if(invalidProps.length===1){error('Invalid aria prop %s on <%s> tag. '+'For details, see https://reactjs.org/link/invalid-aria-props',unknownPropString,type);}else if(invalidProps.length>1){error('Invalid aria props %s on <%s> tag. '+'For details, see https://reactjs.org/link/invalid-aria-props',unknownPropString,type);}}}function validateProperties(type,props){if(isCustomComponent(type,props)){return;}warnInvalidARIAProps(type,props);}var didWarnValueNull=false;function validateProperties$1(type,props){{if(type!=='input'&&type!=='textarea'&&type!=='select'){return;}if(props!=null&&props.value===null&&!didWarnValueNull){didWarnValueNull=true;if(type==='select'&&props.multiple){error('`value` prop on `%s` should not be null. '+'Consider using an empty array when `multiple` is set to `true` '+'to clear the component or `undefined` for uncontrolled components.',type);}else {error('`value` prop on `%s` should not be null. '+'Consider using an empty string to clear the component or `undefined` '+'for uncontrolled components.',type);}}}}// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames={// HTML
accept:'accept',acceptcharset:'acceptCharset','accept-charset':'acceptCharset',accesskey:'accessKey',action:'action',allowfullscreen:'allowFullScreen',alt:'alt',as:'as',async:'async',autocapitalize:'autoCapitalize',autocomplete:'autoComplete',autocorrect:'autoCorrect',autofocus:'autoFocus',autoplay:'autoPlay',autosave:'autoSave',capture:'capture',cellpadding:'cellPadding',cellspacing:'cellSpacing',challenge:'challenge',charset:'charSet',checked:'checked',children:'children',cite:'cite',class:'className',classid:'classID',classname:'className',cols:'cols',colspan:'colSpan',content:'content',contenteditable:'contentEditable',contextmenu:'contextMenu',controls:'controls',controlslist:'controlsList',coords:'coords',crossorigin:'crossOrigin',dangerouslysetinnerhtml:'dangerouslySetInnerHTML',data:'data',datetime:'dateTime',default:'default',defaultchecked:'defaultChecked',defaultvalue:'defaultValue',defer:'defer',dir:'dir',disabled:'disabled',disablepictureinpicture:'disablePictureInPicture',disableremoteplayback:'disableRemotePlayback',download:'download',draggable:'draggable',enctype:'encType',enterkeyhint:'enterKeyHint',for:'htmlFor',form:'form',formmethod:'formMethod',formaction:'formAction',formenctype:'formEncType',formnovalidate:'formNoValidate',formtarget:'formTarget',frameborder:'frameBorder',headers:'headers',height:'height',hidden:'hidden',high:'high',href:'href',hreflang:'hrefLang',htmlfor:'htmlFor',httpequiv:'httpEquiv','http-equiv':'httpEquiv',icon:'icon',id:'id',innerhtml:'innerHTML',inputmode:'inputMode',integrity:'integrity',is:'is',itemid:'itemID',itemprop:'itemProp',itemref:'itemRef',itemscope:'itemScope',itemtype:'itemType',keyparams:'keyParams',keytype:'keyType',kind:'kind',label:'label',lang:'lang',list:'list',loop:'loop',low:'low',manifest:'manifest',marginwidth:'marginWidth',marginheight:'marginHeight',max:'max',maxlength:'maxLength',media:'media',mediagroup:'mediaGroup',method:'method',min:'min',minlength:'minLength',multiple:'multiple',muted:'muted',name:'name',nomodule:'noModule',nonce:'nonce',novalidate:'noValidate',open:'open',optimum:'optimum',pattern:'pattern',placeholder:'placeholder',playsinline:'playsInline',poster:'poster',preload:'preload',profile:'profile',radiogroup:'radioGroup',readonly:'readOnly',referrerpolicy:'referrerPolicy',rel:'rel',required:'required',reversed:'reversed',role:'role',rows:'rows',rowspan:'rowSpan',sandbox:'sandbox',scope:'scope',scoped:'scoped',scrolling:'scrolling',seamless:'seamless',selected:'selected',shape:'shape',size:'size',sizes:'sizes',span:'span',spellcheck:'spellCheck',src:'src',srcdoc:'srcDoc',srclang:'srcLang',srcset:'srcSet',start:'start',step:'step',style:'style',summary:'summary',tabindex:'tabIndex',target:'target',title:'title',type:'type',usemap:'useMap',value:'value',width:'width',wmode:'wmode',wrap:'wrap',// SVG
about:'about',accentheight:'accentHeight','accent-height':'accentHeight',accumulate:'accumulate',additive:'additive',alignmentbaseline:'alignmentBaseline','alignment-baseline':'alignmentBaseline',allowreorder:'allowReorder',alphabetic:'alphabetic',amplitude:'amplitude',arabicform:'arabicForm','arabic-form':'arabicForm',ascent:'ascent',attributename:'attributeName',attributetype:'attributeType',autoreverse:'autoReverse',azimuth:'azimuth',basefrequency:'baseFrequency',baselineshift:'baselineShift','baseline-shift':'baselineShift',baseprofile:'baseProfile',bbox:'bbox',begin:'begin',bias:'bias',by:'by',calcmode:'calcMode',capheight:'capHeight','cap-height':'capHeight',clip:'clip',clippath:'clipPath','clip-path':'clipPath',clippathunits:'clipPathUnits',cliprule:'clipRule','clip-rule':'clipRule',color:'color',colorinterpolation:'colorInterpolation','color-interpolation':'colorInterpolation',colorinterpolationfilters:'colorInterpolationFilters','color-interpolation-filters':'colorInterpolationFilters',colorprofile:'colorProfile','color-profile':'colorProfile',colorrendering:'colorRendering','color-rendering':'colorRendering',contentscripttype:'contentScriptType',contentstyletype:'contentStyleType',cursor:'cursor',cx:'cx',cy:'cy',d:'d',datatype:'datatype',decelerate:'decelerate',descent:'descent',diffuseconstant:'diffuseConstant',direction:'direction',display:'display',divisor:'divisor',dominantbaseline:'dominantBaseline','dominant-baseline':'dominantBaseline',dur:'dur',dx:'dx',dy:'dy',edgemode:'edgeMode',elevation:'elevation',enablebackground:'enableBackground','enable-background':'enableBackground',end:'end',exponent:'exponent',externalresourcesrequired:'externalResourcesRequired',fill:'fill',fillopacity:'fillOpacity','fill-opacity':'fillOpacity',fillrule:'fillRule','fill-rule':'fillRule',filter:'filter',filterres:'filterRes',filterunits:'filterUnits',floodopacity:'floodOpacity','flood-opacity':'floodOpacity',floodcolor:'floodColor','flood-color':'floodColor',focusable:'focusable',fontfamily:'fontFamily','font-family':'fontFamily',fontsize:'fontSize','font-size':'fontSize',fontsizeadjust:'fontSizeAdjust','font-size-adjust':'fontSizeAdjust',fontstretch:'fontStretch','font-stretch':'fontStretch',fontstyle:'fontStyle','font-style':'fontStyle',fontvariant:'fontVariant','font-variant':'fontVariant',fontweight:'fontWeight','font-weight':'fontWeight',format:'format',from:'from',fx:'fx',fy:'fy',g1:'g1',g2:'g2',glyphname:'glyphName','glyph-name':'glyphName',glyphorientationhorizontal:'glyphOrientationHorizontal','glyph-orientation-horizontal':'glyphOrientationHorizontal',glyphorientationvertical:'glyphOrientationVertical','glyph-orientation-vertical':'glyphOrientationVertical',glyphref:'glyphRef',gradienttransform:'gradientTransform',gradientunits:'gradientUnits',hanging:'hanging',horizadvx:'horizAdvX','horiz-adv-x':'horizAdvX',horizoriginx:'horizOriginX','horiz-origin-x':'horizOriginX',ideographic:'ideographic',imagerendering:'imageRendering','image-rendering':'imageRendering',in2:'in2',in:'in',inlist:'inlist',intercept:'intercept',k1:'k1',k2:'k2',k3:'k3',k4:'k4',k:'k',kernelmatrix:'kernelMatrix',kernelunitlength:'kernelUnitLength',kerning:'kerning',keypoints:'keyPoints',keysplines:'keySplines',keytimes:'keyTimes',lengthadjust:'lengthAdjust',letterspacing:'letterSpacing','letter-spacing':'letterSpacing',lightingcolor:'lightingColor','lighting-color':'lightingColor',limitingconeangle:'limitingConeAngle',local:'local',markerend:'markerEnd','marker-end':'markerEnd',markerheight:'markerHeight',markermid:'markerMid','marker-mid':'markerMid',markerstart:'markerStart','marker-start':'markerStart',markerunits:'markerUnits',markerwidth:'markerWidth',mask:'mask',maskcontentunits:'maskContentUnits',maskunits:'maskUnits',mathematical:'mathematical',mode:'mode',numoctaves:'numOctaves',offset:'offset',opacity:'opacity',operator:'operator',order:'order',orient:'orient',orientation:'orientation',origin:'origin',overflow:'overflow',overlineposition:'overlinePosition','overline-position':'overlinePosition',overlinethickness:'overlineThickness','overli
if(eventRegistry!=null){var registrationNameDependencies=eventRegistry.registrationNameDependencies,possibleRegistrationNames=eventRegistry.possibleRegistrationNames;if(registrationNameDependencies.hasOwnProperty(name)){return true;}var registrationName=possibleRegistrationNames.hasOwnProperty(lowerCasedName)?possibleRegistrationNames[lowerCasedName]:null;if(registrationName!=null){error('Invalid event handler property `%s`. Did you mean `%s`?',name,registrationName);warnedProperties$1[name]=true;return true;}if(EVENT_NAME_REGEX.test(name)){error('Unknown event handler property `%s`. It will be ignored.',name);warnedProperties$1[name]=true;return true;}}else if(EVENT_NAME_REGEX.test(name)){// If no event plugins have been injected, we are in a server environment.
// So we can't tell if the event name is correct for sure, but we can filter
// out known bad ones like `onclick`. We can't suggest a specific replacement though.
if(INVALID_EVENT_NAME_REGEX.test(name)){error('Invalid event handler property `%s`. '+'React events use the camelCase naming convention, for example `onClick`.',name);}warnedProperties$1[name]=true;return true;}// Let the ARIA attribute hook validate ARIA attributes
if(rARIA$1.test(name)||rARIACamel$1.test(name)){return true;}if(lowerCasedName==='innerhtml'){error('Directly setting property `innerHTML` is not permitted. '+'For more information, lookup documentation on `dangerouslySetInnerHTML`.');warnedProperties$1[name]=true;return true;}if(lowerCasedName==='aria'){error('The `aria` attribute is reserved for future use in React. '+'Pass individual `aria-` attributes instead.');warnedProperties$1[name]=true;return true;}if(lowerCasedName==='is'&&value!==null&&value!==undefined&&typeof value!=='string'){error('Received a `%s` for a string attribute `is`. If this is expected, cast '+'the value to a string.',typeof value);warnedProperties$1[name]=true;return true;}if(typeof value==='number'&&isNaN(value)){error('Received NaN for the `%s` attribute. If this is expected, cast '+'the value to a string.',name);warnedProperties$1[name]=true;return true;}var propertyInfo=getPropertyInfo(name);var isReserved=propertyInfo!==null&&propertyInfo.type===RESERVED;// Known attributes should match the casing specified in the property config.
if(possibleStandardNames.hasOwnProperty(lowerCasedName)){var standardName=possibleStandardNames[lowerCasedName];if(standardName!==name){error('Invalid DOM property `%s`. Did you mean `%s`?',name,standardName);warnedProperties$1[name]=true;return true;}}else if(!isReserved&&name!==lowerCasedName){// Unknown attributes should have lowercase casing since that's how they
// will be cased anyway with server rendering.
error('React does not recognize the `%s` prop on a DOM element. If you '+'intentionally want it to appear in the DOM as a custom '+'attribute, spell it as lowercase `%s` instead. '+'If you accidentally passed it from a parent component, remove '+'it from the DOM element.',name,lowerCasedName);warnedProperties$1[name]=true;return true;}if(typeof value==='boolean'&&shouldRemoveAttributeWithWarning(name,value,propertyInfo,false)){if(value){error('Received `%s` for a non-boolean attribute `%s`.\n\n'+'If you want to write it to the DOM, pass a string instead: '+'%s="%s" or %s={value.toString()}.',value,name,name,value,name);}else {error('Received `%s` for a non-boolean attribute `%s`.\n\n'+'If you want to write it to the DOM, pass a string instead: '+'%s="%s" or %s={value.toString()}.\n\n'+'If you used to conditionally omit it with %s={condition && value}, '+'pass %s={condition ? value : undefined} instead.',value,name,name,value,name,name,name);}warnedProperties$1[name]=true;return true;}// Now that we've validated casing, do not validate
// data types for reserved props
if(isReserved){return true;}// Warn when a known attribute is a bad type
if(shouldRemoveAttributeWithWarning(name,value,propertyInfo,false)){warnedProperties$1[name]=true;return false;}// Warn when passing the strings 'false' or 'true' into a boolean prop
if((value==='false'||value==='true')&&propertyInfo!==null&&propertyInfo.type===BOOLEAN){error('Received the string `%s` for the boolean attribute `%s`. '+'%s '+'Did you mean %s={%s}?',value,name,value==='false'?'The browser will interpret it as a truthy value.':'Although this works, it will not work as expected if you pass the string "false".',name,value);warnedProperties$1[name]=true;return true;}return true;};}var warnUnknownProperties=function(type,props,eventRegistry){{var unknownProps=[];for(var key in props){var isValid=validateProperty$1(type,key,props[key],eventRegistry);if(!isValid){unknownProps.push(key);}}var unknownPropString=unknownProps.map(function(prop){return '`'+prop+'`';}).join(', ');if(unknownProps.length===1){error('Invalid value for prop %s on <%s> tag. Either remove it from the element, '+'or pass a string or number value to keep it in the DOM. '+'For details, see https://reactjs.org/link/attribute-behavior ',unknownPropString,type);}else if(unknownProps.length>1){error('Invalid values for props %s on <%s> tag. Either remove them from the element, '+'or pass a string or number value to keep them in the DOM. '+'For details, see https://reactjs.org/link/attribute-behavior ',unknownPropString,type);}}};function validateProperties$2(type,props,eventRegistry){if(isCustomComponent(type,props)){return;}warnUnknownProperties(type,props,eventRegistry);}var toArray=React.Children.toArray;// This is only used in DEV.
// Each entry is `this.stack` from a currently executing renderer instance.
// (There may be more than one because ReactDOMServer is reentrant).
// Each stack is an array of frames which may contain nested stacks of elements.
var currentDebugStacks=[];var ReactCurrentDispatcher$1=ReactSharedInternals.ReactCurrentDispatcher;var ReactDebugCurrentFrame$1;var prevGetCurrentStackImpl=null;var getCurrentServerStackImpl=function(){return '';};var describeStackFrame=function(element){return '';};var validatePropertiesInDevelopment=function(type,props){};var pushCurrentDebugStack=function(stack){};var pushElementToDebugStack=function(element){};var popCurrentDebugStack=function(){};var hasWarnedAboutUsingContextAsConsumer=false;{ReactDebugCurrentFrame$1=ReactSharedInternals.ReactDebugCurrentFrame;validatePropertiesInDevelopment=function(type,props){validateProperties(type,props);validateProperties$1(type,props);validateProperties$2(type,props,null);};describeStackFrame=function(element){return describeUnknownElementTypeFrameInDEV(element.type,element._source,null);};pushCurrentDebugStack=function(stack){currentDebugStacks.push(stack);if(currentDebugStacks.length===1){// We are entering a server renderer.
// Remember the previous (e.g. client) global stack implementation.
prevGetCurrentStackImpl=ReactDebugCurrentFrame$1.getCurrentStack;ReactDebugCurrentFrame$1.getCurrentStack=getCurrentServerStackImpl;}};pushElementToDebugStack=function(element){// For the innermost executing ReactDOMServer call,
var stack=currentDebugStacks[currentDebugStacks.length-1];// Take the innermost executing frame (e.g. <Foo>),
var frame=stack[stack.length-1];// and record that it has one more element associated with it.
frame.debugElementStack.push(element);// We only need this because we tail-optimize single-element
// children and directly handle them in an inner loop instead of
// creating separate frames for them.
};popCurrentDebugStack=function(){currentDebugStacks.pop();if(currentDebugStacks.length===0){// We are exiting the server renderer.
// Restore the previous (e.g. client) global stack implementation.
ReactDebugCurrentFrame$1.getCurrentStack=prevGetCurrentStackImpl;prevGetCurrentStackImpl=null;}};getCurrentServerStackImpl=function(){if(currentDebugStacks.length===0){// Nothing is currently rendering.
return '';}// ReactDOMServer is reentrant so there may be multiple calls at the same time.
// Take the frames from the innermost call which is the last in the array.
var frames=currentDebugStacks[currentDebugStacks.length-1];var stack='';// Go through every frame in the stack from the innermost one.
for(var i=frames.length-1;i>=0;i--){var frame=frames[i];// Every frame might have more than one debug element stack entry associated with it.
// This is because single-child nesting doesn't create materialized frames.
// Instead it would push them through `pushElementToDebugStack()`.
var debugElementStack=frame.debugElementStack;for(var ii=debugElementStack.length-1;ii>=0;ii--){stack+=describeStackFrame(debugElementStack[ii]);}}return stack;};}var didWarnDefaultInputValue=false;var didWarnDefaultChecked=false;var didWarnDefaultSelectValue=false;var didWarnDefaultTextareaValue=false;var didWarnInvalidOptionChildren=false;var didWarnAboutNoopUpdateForComponent={};var didWarnAboutBadClass={};var didWarnAboutModulePatternComponent={};var didWarnAboutDeprecatedWillMount={};var didWarnAboutUndefinedDerivedState={};var didWarnAboutUninitializedState={};var valuePropNames=['value','defaultValue'];var newlineEatingTags={listing:true,pre:true,textarea:true};// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/;// Simplified subset
var validatedTagCache={};function validateDangerousTag(tag){if(!validatedTagCache.hasOwnProperty(tag)){if(!VALID_TAG_REGEX.test(tag)){{throw Error("Invalid tag: "+tag);}}validatedTagCache[tag]=true;}}var styleNameCache={};var processStyleName=function(styleName){if(styleNameCache.hasOwnProperty(styleName)){return styleNameCache[styleName];}var result=hyphenateStyleName(styleName);styleNameCache[styleName]=result;return result;};function createMarkupForStyles(styles){var serialized='';var delimiter='';for(var styleName in styles){if(!styles.hasOwnProperty(styleName)){continue;}var isCustomProperty=styleName.indexOf('--')===0;var styleValue=styles[styleName];{if(!isCustomProperty){warnValidStyle$1(styleName,styleValue);}}if(styleValue!=null){serialized+=delimiter+(isCustomProperty?styleName:processStyleName(styleName))+':';serialized+=dangerousStyleValue(styleName,styleValue,isCustomProperty);delimiter=';';}}return serialized||null;}function warnNoop(publicInstance,callerName){{var _constructor=publicInstance.constructor;var componentName=_constructor&&getComponentName(_constructor)||'ReactClass';var warningKey=componentName+'.'+callerName;if(didWarnAboutNoopUpdateForComponent[warningKey]){return;}error('%s(...): Can only update a mounting component. '+'This usually means you called %s() outside componentWillMount() on the server. '+'This is a no-op.\n\nPlease check the code for the %s component.',callerName,callerName,componentName);didWarnAboutNoopUpdateForComponent[warningKey]=true;}}function shouldConstruct$1(Component){return Component.prototype&&Component.prototype.isReactComponent;}function getNonChildrenInnerMarkup(props){var innerHTML=props.dangerouslySetInnerHTML;if(innerHTML!=null){if(innerHTML.__html!=null){return innerHTML.__html;}}else {var content=props.children;if(typeof content==='string'||typeof content==='number'){return escapeTextForBrowser(content);}}return null;}function flattenTopLevelChildren(children){if(!React.isValidElement(children)){return toArray(children);}var element=children;if(element.type!==REACT_FRAGMENT_TYPE){return [element];}var fragmentChildren=element.props.children;if(!React.isValidElement(fragmentChildren)){return toArray(fragmentChildren);}var fragmentChildElement=fragmentChildren;return [fragmentChildElement];}function flattenOptionChildren(children){if(children===undefined||children===null){return children;}var content='';// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
React.Children.forEach(children,function(child){if(child==null){return;}content+=child;{if(!didWarnInvalidOptionChildren&&typeof child!=='string'&&typeof child!=='number'){didWarnInvalidOptionChildren=true;error('Only strings and numbers are supported as <option> children.');}}});return content;}var hasOwnProperty$2=Object.prototype.hasOwnProperty;var STYLE='style';var RESERVED_PROPS={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null,suppressHydrationWarning:null};function createOpenTagMarkup(tagVerbatim,tagLowercase,props,namespace,makeStaticMarkup,isRootElement){var ret='<'+tagVerbatim;var isCustomComponent$1=isCustomComponent(tagLowercase,props);for(var propKey in props){if(!hasOwnProperty$2.call(props,propKey)){continue;}var propValue=props[propKey];if(propValue==null){continue;}if(propKey===STYLE){propValue=createMarkupForStyles(propValue);}var markup=null;if(isCustomComponent$1){if(!RESERVED_PROPS.hasOwnProperty(propKey)){markup=createMarkupForCustomAttribute(propKey,propValue);}}else {markup=createMarkupForProperty(propKey,propValue);}if(markup){ret+=' '+markup;}}// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if(makeStaticMarkup){return ret;}if(isRootElement){ret+=' '+createMarkupForRoot();}return ret;}function validateRenderResult(child,type){if(child===undefined){{{throw Error((getComponentName(type)||'Component')+"(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.");}}}}function resolve(child,context,threadID){while(React.isValidElement(child)){// Safe because we just checked it's an element.
var element=child;var Component=element.type;{pushElementToDebugStack(element);}if(typeof Component!=='function'){break;}processChild(element,Component);}// Extra closure so queue and replace can be captured properly
function processChild(element,Component){var isClass=shouldConstruct$1(Component);var publicContext=processContext(Component,context,threadID,isClass);var queue=[];var replace=false;var updater={isMounted:function(publicInstance){return false;},enqueueForceUpdate:function(publicInstance){if(queue===null){warnNoop(publicInstance,'forceUpdate');return null;}},enqueueReplaceState:function(publicInstance,completeState){replace=true;queue=[completeState];},enqueueSetState:function(publicInstance,currentPartialState){if(queue===null){warnNoop(publicInstance,'setState');return null;}queue.push(currentPartialState);}};var inst;if(isClass){inst=new Component(element.props,publicContext,updater);if(typeof Component.getDerivedStateFromProps==='function'){{if(inst.state===null||inst.state===undefined){var componentName=getComponentName(Component)||'Unknown';if(!didWarnAboutUninitializedState[componentName]){error('`%s` uses `getDerivedStateFromProps` but its initial state is '+'%s. This is not recommended. Instead, define the initial state by '+'assigning an object to `this.state` in the constructor of `%s`. '+'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.',componentName,inst.state===null?'null':'undefined',componentName);didWarnAboutUninitializedState[componentName]=true;}}}var partialState=Component.getDerivedStateFromProps.call(null,element.props,inst.state);{if(partialState===undefined){var _componentName=getComponentName(Component)||'Unknown';if(!didWarnAboutUndefinedDerivedState[_componentName]){error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. '+'You have returned undefined.',_componentName);didWarnAboutUndefinedDerivedState[_componentName]=true;}}}if(partialState!=null){inst.state=_assign({},inst.state,partialState);}}}else {{if(Component.prototype&&typeof Component.prototype.render==='function'){var _componentName2=getComponentName(Component)||'Unknown';if(!didWarnAboutBadClass[_componentName2]){error("The <%s /> component appears to have a render method, but doesn't extend React.Component. "+'This is likely to cause errors. Change %s to extend React.Component instead.',_componentName2,_componentName2);didWarnAboutBadClass[_componentName2]=true;}}}var componentIdentity={};prepareToUseHooks(componentIdentity);inst=Component(element.props,publicContext,updater);inst=finishHooks(Component,element.props,inst,publicContext);{// Support for module components is deprecated and is removed behind a flag.
// Whether or not it would crash later, we want to show a good message in DEV first.
if(inst!=null&&inst.render!=null){var _componentName3=getComponentName(Component)||'Unknown';if(!didWarnAboutModulePatternComponent[_componentName3]){error('The <%s /> component appears to be a function component that returns a class instance. '+'Change %s to a class that extends React.Component instead. '+"If you can't use a class try assigning the prototype on the function as a workaround. "+"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it "+'cannot be called with `new` by React.',_componentName3,_componentName3,_componentName3);didWarnAboutModulePatternComponent[_componentName3]=true;}}}// If the flag is on, everything is assumed to be a function component.
// Otherwise, we also do the unfortunate dynamic checks.
if(inst==null||inst.render==null){child=inst;validateRenderResult(child,Component);return;}}inst.props=element.props;inst.context=publicContext;inst.updater=updater;var initialState=inst.state;if(initialState===undefined){inst.state=initialState=null;}if(typeof inst.UNSAFE_componentWillMount==='function'||typeof inst.componentWillMount==='function'){if(typeof inst.componentWillMount==='function'){{if(inst.componentWillMount.__suppressDeprecationWarning!==true){var _componentName4=getComponentName(Component)||'Unknown';if(!didWarnAboutDeprecatedWillMount[_componentName4]){warn(// keep this warning in sync with ReactStrictModeWarning.js
'componentWillMount has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move code from componentWillMount to componentDidMount (preferred in most cases) '+'or the constructor.\n'+'\nPlease update the following components: %s',_componentName4);didWarnAboutDeprecatedWillMount[_componentName4]=true;}}}// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for any component with the new gDSFP.
if(typeof Component.getDerivedStateFromProps!=='function'){inst.componentWillMount();}}if(typeof inst.UNSAFE_componentWillMount==='function'&&typeof Component.getDerivedStateFromProps!=='function'){// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for any component with the new gDSFP.
inst.UNSAFE_componentWillMount();}if(queue.length){var oldQueue=queue;var oldReplace=replace;queue=null;replace=false;if(oldReplace&&oldQueue.length===1){inst.state=oldQueue[0];}else {var nextState=oldReplace?oldQueue[0]:inst.state;var dontMutate=true;for(var i=oldReplace?1:0;i<oldQueue.length;i++){var partial=oldQueue[i];var _partialState=typeof partial==='function'?partial.call(inst,nextState,element.props,publicContext):partial;if(_partialState!=null){if(dontMutate){dontMutate=false;nextState=_assign({},nextState,_partialState);}else {_assign(nextState,_partialState);}}}inst.state=nextState;}}else {queue=null;}}child=inst.render();{if(child===undefined&&inst.render._isMockFunction){// This is probably bad practice. Consider warning here and
// deprecating this convenience.
child=null;}}validateRenderResult(child,Component);var childContext;{if(typeof inst.getChildContext==='function'){var _childContextTypes=Component.childContextTypes;if(typeof _childContextTypes==='object'){childContext=inst.getChildContext();for(var contextKey in childContext){if(!(contextKey in _childContextTypes)){{throw Error((getComponentName(Component)||'Unknown')+".getChildContext(): key \""+contextKey+"\" is not defined in childContextTypes.");}}}}else {{error('%s.getChildContext(): childContextTypes must be defined in order to '+'use getChildContext().',getComponentName(Component)||'Unknown');}}}if(childContext){context=_assign({},context,childContext);}}}return {child:child,context:context};}var ReactDOMServerRenderer=/*#__PURE__*/function(){// TODO: type this more strictly:
// DEV-only
function ReactDOMServerRenderer(children,makeStaticMarkup,options){var flatChildren=flattenTopLevelChildren(children);var topFrame={type:null,// Assume all trees start in the HTML namespace (not totally true, but
// this is what we did historically)
domNamespace:Namespaces.html,children:flatChildren,childIndex:0,context:emptyObject,footer:''};{topFrame.debugElementStack=[];}this.threadID=allocThreadID();this.stack=[topFrame];this.exhausted=false;this.currentSelectValue=null;this.previousWasTextNode=false;this.makeStaticMarkup=makeStaticMarkup;this.suspenseDepth=0;// Context (new API)
this.contextIndex=-1;this.contextStack=[];this.contextValueStack=[];// useOpaqueIdentifier ID
this.uniqueID=0;this.identifierPrefix=options&&options.identifierPrefix||'';{this.contextProviderStack=[];}}var _proto=ReactDOMServerRenderer.prototype;_proto.destroy=function destroy(){if(!this.exhausted){this.exhausted=true;this.clearProviders();freeThreadID(this.threadID);}}/**
* Note: We use just two stacks regardless of how many context providers you have.
* Providers are always popped in the reverse order to how they were pushed
* so we always know on the way down which provider you'll encounter next on the way up.
* On the way down, we push the current provider, and its context value *before*
* we mutated it, onto the stacks. Therefore, on the way up, we always know which
* provider needs to be "restored" to which value.
* https://github.com/facebook/react/pull/12985#issuecomment-396301248
*/;_proto.pushProvider=function pushProvider(provider){var index=++this.contextIndex;var context=provider.type._context;var threadID=this.threadID;validateContextBounds(context,threadID);var previousValue=context[threadID];// Remember which value to restore this context to on our way up.
this.contextStack[index]=context;this.contextValueStack[index]=previousValue;{// Only used for push/pop mismatch warnings.
this.contextProviderStack[index]=provider;}// Mutate the current value.
context[threadID]=provider.props.value;};_proto.popProvider=function popProvider(provider){var index=this.contextIndex;{if(index<0||provider!==this.contextProviderStack[index]){error('Unexpected pop.');}}var context=this.contextStack[index];var previousValue=this.contextValueStack[index];// "Hide" these null assignments from Flow by using `any`
// because conceptually they are deletions--as long as we
// promise to never access values beyond `this.contextIndex`.
this.contextStack[index]=null;this.contextValueStack[index]=null;{this.contextProviderStack[index]=null;}this.contextIndex--;// Restore to the previous value we stored as we were walking down.
// We've already verified that this context has been expanded to accommodate
// this thread id, so we don't need to do it again.
context[this.threadID]=previousValue;};_proto.clearProviders=function clearProviders(){// Restore any remaining providers on the stack to previous values
for(var index=this.contextIndex;index>=0;index--){var context=this.contextStack[index];var previousValue=this.contextValueStack[index];context[this.threadID]=previousValue;}};_proto.read=function read(bytes){if(this.exhausted){return null;}var prevPartialRenderer=currentPartialRenderer;setCurrentPartialRenderer(this);var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=Dispatcher;try{// Markup generated within <Suspense> ends up buffered until we know
// nothing in that boundary suspended
var out=[''];var suspended=false;while(out[0].length<bytes){if(this.stack.length===0){this.exhausted=true;freeThreadID(this.threadID);break;}var frame=this.stack[this.stack.length-1];if(suspended||frame.childIndex>=frame.children.length){var footer=frame.footer;if(footer!==''){this.previousWasTextNode=false;}this.stack.pop();if(frame.type==='select'){this.currentSelectValue=null;}else if(frame.type!=null&&frame.type.type!=null&&frame.type.type.$$typeof===REACT_PROVIDER_TYPE){var provider=frame.type;this.popProvider(provider);}else if(frame.type===REACT_SUSPENSE_TYPE){this.suspenseDepth--;var buffered=out.pop();if(suspended){suspended=false;// If rendering was suspended at this boundary, render the fallbackFrame
var fallbackFrame=frame.fallbackFrame;if(!fallbackFrame){{throw Error(true?"ReactDOMServer did not find an internal fallback frame for Suspense. This is a bug in React. Please file an issue.":formatProdErrorMessage(303));}}this.stack.push(fallbackFrame);out[this.suspenseDepth]+='<!--$!-->';// Skip flushing output since we're switching to the fallback
continue;}else {out[this.suspenseDepth]+=buffered;}}// Flush output
out[this.suspenseDepth]+=footer;continue;}var child=frame.children[frame.childIndex++];var outBuffer='';if(true){pushCurrentDebugStack(this.stack);// We're starting work on this frame, so reset its inner stack.
frame.debugElementStack.length=0;}try{outBuffer+=this.render(child,frame.context,frame.domNamespace);}catch(err){if(err!=null&&typeof err.then==='function'){if(enableSuspenseServerRenderer);else {if(!false){{throw Error(true?"ReactDOMServer does not yet support Suspense.":formatProdErrorMessage(294));}}}}else {throw err;}}finally{if(true){popCurrentDebugStack();}}if(out.length<=this.suspenseDepth){out.push('');}out[this.suspenseDepth]+=outBuffer;}return out[0];}finally{ReactCurrentDispatcher$1.current=prevDispatcher;setCurrentPartialRenderer(prevPartialRenderer);resetHooksState();}};_proto.render=function render(child,context,parentNamespace){if(typeof child==='string'||typeof child==='number'){var text=''+child;if(text===''){return '';}if(this.makeStaticMarkup){return escapeTextForBrowser(text);}if(this.previousWasTextNode){return '<!-- -->'+escapeTextForBrowser(text);}this.previousWasTextNode=true;return escapeTextForBrowser(text);}else {var nextChild;var _resolve=resolve(child,context,this.threadID);nextChild=_resolve.child;context=_resolve.context;if(nextChild===null||nextChild===false){return '';}else if(!React.isValidElement(nextChild)){if(nextChild!=null&&nextChild.$$typeof!=null){// Catch unexpected special types early.
var $$typeof=nextChild.$$typeof;if(!($$typeof!==REACT_PORTAL_TYPE)){{throw Error("Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render.");}}// Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type.
{{throw Error("Unknown element-like object type: "+$$typeof.toString()+". This is likely a bug in React. Please file an issue.");}}}var nextChildren=toArray(nextChild);var frame={type:null,domNamespace:parentNamespace,children:nextChildren,childIndex:0,context:context,footer:''};{frame.debugElementStack=[];}this.stack.push(frame);return '';}// Safe because we just checked it's an element.
var nextElement=nextChild;var elementType=nextElement.type;if(typeof elementType==='string'){return this.renderDOM(nextElement,context,parentNamespace);}switch(elementType){// TODO: LegacyHidden acts the same as a fragment. This only works
// because we currently assume that every instance of LegacyHidden is
// accompanied by a host component wrapper. In the hidden mode, the host
// component is given a `hidden` attribute, which ensures that the
// initial HTML is not visible. To support the use of LegacyHidden as a
// true fragment, without an extra DOM node, we would have to hide the
// initial HTML in some other way.
case REACT_LEGACY_HIDDEN_TYPE:case REACT_DEBUG_TRACING_MODE_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_PROFILER_TYPE:case REACT_SUSPENSE_LIST_TYPE:case REACT_FRAGMENT_TYPE:{var _nextChildren=toArray(nextChild.props.children);var _frame={type:null,domNamespace:parentNamespace,children:_nextChildren,childIndex:0,context:context,footer:''};{_frame.debugElementStack=[];}this.stack.push(_frame);return '';}case REACT_SUSPENSE_TYPE:{{{{throw Error("ReactDOMServer does not yet support Suspense.");}}}}// eslint-disable-next-line-no-fallthrough
case REACT_SCOPE_TYPE:{{{throw Error("ReactDOMServer does not yet support scope components.");}}}}if(typeof elementType==='object'&&elementType!==null){switch(elementType.$$typeof){case REACT_FORWARD_REF_TYPE:{var element=nextChild;var _nextChildren5;var componentIdentity={};prepareToUseHooks(componentIdentity);_nextChildren5=elementType.render(element.props,element.ref);_nextChildren5=finishHooks(elementType.render,element.props,_nextChildren5,element.ref);_nextChildren5=toArray(_nextChildren5);var _frame5={type:null,domNamespace:parentNamespace,children:_nextChildren5,childIndex:0,context:context,footer:''};{_frame5.debugElementStack=[];}this.stack.push(_frame5);return '';}case REACT_MEMO_TYPE:{var _element=nextChild;var _nextChildren6=[React.createElement(elementType.type,_assign({ref:_element.ref},_element.props))];var _frame6={type:null,domNamespace:parentNamespace,children:_nextChildren6,childIndex:0,context:context,footer:''};{_frame6.debugElementStack=[];}this.stack.push(_frame6);return '';}case REACT_PROVIDER_TYPE:{var provider=nextChild;var nextProps=provider.props;var _nextChildren7=toArray(nextProps.children);var _frame7={type:provider,domNamespace:parentNamespace,children:_nextChildren7,childIndex:0,context:context,footer:''};{_frame7.debugElementStack=[];}this.pushProvider(provider);this.stack.push(_frame7);return '';}case REACT_CONTEXT_TYPE:{var reactContext=nextChild.type;// The logic below for Context differs depending on PROD or DEV mode. In
// DEV mode, we create a separate object for Context.Consumer that acts
// like a proxy to Context. This proxy object adds unnecessary code in PROD
// so we use the old behaviour (Context.Consumer references Context) to
// reduce size and overhead. The separate object references context via
// a property called "_context", which also gives us the ability to check
// in DEV mode if this property exists or not and warn if it does not.
{if(reactContext._context===undefined){// This may be because it's a Context (rather than a Consumer).
// Or it may be because it's older React where they're the same thing.
// We only want to warn if we're sure it's a new React.
if(reactContext!==reactContext.Consumer){if(!hasWarnedAboutUsingContextAsConsumer){hasWarnedAboutUsingContextAsConsumer=true;error('Rendering <Context> directly is not supported and will be removed in '+'a future major release. Did you mean to render <Context.Consumer> instead?');}}}else {reactContext=reactContext._context;}}var _nextProps=nextChild.props;var threadID=this.threadID;validateContextBounds(reactContext,threadID);var nextValue=reactContext[threadID];var _nextChildren8=toArray(_nextProps.children(nextValue));var _frame8={type:nextChild,domNamespace:parentNamespace,children:_nextChildren8,childIndex:0,context:context,footer:''};{_frame8.debugElementStack=[];}this.stack.push(_frame8);return '';}// eslint-disable-next-line-no-fallthrough
case REACT_FUNDAMENTAL_TYPE:{{{throw Error("ReactDOMServer does not yet support the fundamental API.");}}}// eslint-disable-next-line-no-fallthrough
case REACT_LAZY_TYPE:{var _element2=nextChild;var lazyComponent=nextChild.type;// Attempt to initialize lazy component regardless of whether the
// suspense server-side renderer is enabled so synchronously
// resolved constructors are supported.
var payload=lazyComponent._payload;var init=lazyComponent._init;var result=init(payload);var _nextChildren10=[React.createElement(result,_assign({ref:_element2.ref},_element2.props))];var _frame10={type:null,domNamespace:parentNamespace,children:_nextChildren10,childIndex:0,context:context,footer:''};{_frame10.debugElementStack=[];}this.stack.push(_frame10);return '';}}}var info='';{var owner=nextElement._owner;if(elementType===undefined||typeof elementType==='object'&&elementType!==null&&Object.keys(elementType).length===0){info+=' You likely forgot to export your component from the file '+"it's defined in, or you might have mixed up default and "+'named imports.';}var ownerName=owner?getComponentName(owner):null;if(ownerName){info+='\n\nCheck the render method of `'+ownerName+'`.';}}{{throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: "+(elementType==null?elementType:typeof elementType)+"."+info);}}}};_proto.renderDOM=function renderDOM(element,context,parentNamespace){var tag=element.type.toLowerCase();var namespace=parentNamespace;if(parentNamespace===Namespaces.html){namespace=getIntrinsicNamespace(tag);}{if(namespace===Namespaces.html){// Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
if(tag!==element.type){error('<%s /> is using incorrect casing. '+'Use PascalCase for React components, '+'or lowercase for HTML elements.',element.type);}}}validateDangerousTag(tag);var props=element.props;if(tag==='input'){{checkControlledValueProps('input',props);if(props.checked!==undefined&&props.defaultChecked!==undefined&&!didWarnDefaultChecked){error('%s contains an input of type %s with both checked and defaultChecked props. '+'Input elements must be either controlled or uncontrolled '+'(specify either the checked prop, or the defaultChecked prop, but not '+'both). Decide between using a controlled or uncontrolled input '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components','A component',props.type);didWarnDefaultChecked=true;}if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnDefaultInputValue){error('%s contains an input of type %s with both value and defaultValue props. '+'Input elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled input '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components','A component',props.type);didWarnDefaultInputValue=true;}}props=_assign({type:undefined},props,{defaultChecked:undefined,defaultValue:undefined,value:props.value!=null?props.value:props.defaultValue,checked:props.checked!=null?props.checked:props.defaultChecked});}else if(tag==='textarea'){{checkControlledValueProps('textarea',props);if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnDefaultTextareaValue){error('Textarea elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled textarea '+'and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components');didWarnDefaultTextareaValue=true;}}var initialValue=props.value;if(initialValue==null){var defaultValue=props.defaultValue;// TODO (yungsters): Remove support for children content in <textarea>.
var textareaChildren=props.children;if(textareaChildren!=null){{error('Use the `defaultValue` or `value` props instead of setting '+'children on <textarea>.');}if(!(defaultValue==null)){{throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");}}if(Array.isArray(textareaChildren)){if(!(textareaChildren.length<=1)){{throw Error("<textarea> can only have at most one child.");}}textareaChildren=textareaChildren[0];}defaultValue=''+textareaChildren;}if(defaultValue==null){defaultValue='';}initialValue=defaultValue;}props=_assign({},props,{value:undefined,children:''+initialValue});}else if(tag==='select'){{checkControlledValueProps('select',props);for(var i=0;i<valuePropNames.length;i++){var propName=valuePropNames[i];if(props[propName]==null){continue;}var isArray=Array.isArray(props[propName]);if(props.multiple&&!isArray){error('The `%s` prop supplied to <select> must be an array if '+'`multiple` is true.',propName);}else if(!props.multiple&&isArray){error('The `%s` prop supplied to <select> must be a scalar '+'value if `multiple` is false.',propName);}}if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnDefaultSelectValue){error('Select elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled select '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components');didWarnDefaultSelectValue=true;}}this.currentSelectValue=props.value!=null?props.value:props.defaultValue;props=_assign({},props,{value:undefined});}else if(tag==='option'){var selected=null;var selectValue=this.currentSelectValue;var optionChildren=flattenOptionChildren(props.children);if(selectValue!=null){var value;if(props.value!=null){value=props.value+'';}else {value=optionChildren;}selected=false;if(Array.isArray(selectValue)){// multiple
for(var j=0;j<selectValue.length;j++){if(''+selectValue[j]===value){selected=true;break;}}}else {selected=''+selectValue===value;}props=_assign({selected:undefined,children:undefined},props,{selected:selected,children:optionChildren});}}{validatePropertiesInDevelopment(tag,props);}assertValidProps(tag,props);var out=createOpenTagMarkup(element.type,tag,props,namespace,this.makeStaticMarkup,this.stack.length===1);var footer='';if(omittedCloseTags.hasOwnProperty(tag)){out+='/>';}else {out+='>';footer='</'+element.type+'>';}var children;var innerMarkup=getNonChildrenInnerMarkup(props);if(innerMarkup!=null){children=[];if(newlineEatingTags.hasOwnProperty(tag)&&innerMarkup.charAt(0)==='\n'){// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
out+='\n';}out+=innerMarkup;}else {children=toArray(props.children);}var frame={domNamespace:getChildNamespace(parentNamespace,element.type),type:tag,children:children,childIndex:0,context:context,footer:footer};{frame.debugElementStack=[];}this.stack.push(frame);this.previousWasTextNode=false;return out;};return ReactDOMServerRenderer;}();/**
* Render a ReactElement to its initial HTML. This should only be used on the
* server.
* See https://reactjs.org/docs/react-dom-server.html#rendertostring
*/function renderToString(element,options){var renderer=new ReactDOMServerRenderer(element,false,options);try{var markup=renderer.read(Infinity);return markup;}finally{renderer.destroy();}}/**
* Similar to renderToString, except this doesn't create extra DOM attributes
* such as data-react-id that React uses internally.
* See https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup
*/function renderToStaticMarkup(element,options){var renderer=new ReactDOMServerRenderer(element,true,options);try{var markup=renderer.read(Infinity);return markup;}finally{renderer.destroy();}}function renderToNodeStream(){{{throw Error("ReactDOMServer.renderToNodeStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToString() instead.");}}}function renderToStaticNodeStream(){{{throw Error("ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.");}}}exports.renderToNodeStream=renderToNodeStream;exports.renderToStaticMarkup=renderToStaticMarkup;exports.renderToStaticNodeStream=renderToStaticNodeStream;exports.renderToString=renderToString;exports.version=ReactVersion;})();}
});
3 years ago
var server_browser = createCommonjsModule(function (module) {
{module.exports=reactDomServer_browser_development;}
});
3 years ago
var proptypes = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:true});exports.options=exports.hintPosition=exports.tooltipPosition=void 0;var _propTypes=_interopRequireDefault(propTypes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}/**
* Intro.js tooltip position proptype.
* @type {Function}
*/var tooltipPosition=_propTypes["default"].oneOf(['top','right','bottom','left','bottom-left-aligned','bottom-middle-aligned','bottom-right-aligned','top-left-aligned','top-middle-aligned','top-right-aligned','auto']);/**
* Intro.js hint position proptype.
* @type {Function}
*/exports.tooltipPosition=tooltipPosition;var hintPosition=_propTypes["default"].oneOf(['top-middle','top-left','top-right','bottom-left','bottom-right','bottom-middle','middle-left','middle-right','middle-middle']);exports.hintPosition=hintPosition;var options=_propTypes["default"].shape({nextLabel:_propTypes["default"].string,prevLabel:_propTypes["default"].string,skipLabel:_propTypes["default"].string,doneLabel:_propTypes["default"].string,hidePrev:_propTypes["default"].bool,hideNext:_propTypes["default"].bool,tooltipPosition:tooltipPosition,tooltipClass:_propTypes["default"].string,highlightClass:_propTypes["default"].string,exitOnEsc:_propTypes["default"].bool,exitOnOverlayClick:_propTypes["default"].bool,showStepNumbers:_propTypes["default"].bool,keyboardNavigation:_propTypes["default"].bool,showButtons:_propTypes["default"].bool,showBullets:_propTypes["default"].bool,showProgress:_propTypes["default"].bool,scrollToElement:_propTypes["default"].bool,overlayOpacity:_propTypes["default"].number,scrollPadding:_propTypes["default"].number,positionPrecedence:_propTypes["default"].arrayOf(_propTypes["default"].string),disableInteraction:_propTypes["default"].bool,hintPosition:hintPosition,hintButtonLabel:_propTypes["default"].string,hintAnimation:_propTypes["default"].bool});exports.options=options;
});
3 years ago
var defaultProps = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:true});exports.options=void 0;/**
* Intro.js options default proptypes.
* @type {Object}
*/var options={hidePrev:true,hideNext:true};exports.options=options;
});
3 years ago
var Steps_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _intro=_interopRequireDefault(intro);var _propTypes=_interopRequireDefault(propTypes);var introJsPropTypes=_interopRequireWildcard(proptypes);var introJsDefaultProps=_interopRequireWildcard(defaultProps);function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap();_getRequireWildcardCache=function _getRequireWildcardCache(){return cache;};return cache;}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return {"default":obj};}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else {newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else {_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable;});keys.push.apply(keys,symbols);}return keys;}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach(function(key){_defineProperty(target,key,source[key]);});}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source));}else {ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}}return target;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else {result=Super.apply(this,arguments);}return _possibleConstructorReturn(this,result);};}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new
* Intro.js Steps Component.
*/var Steps=/*#__PURE__*/function(_Component){_inherits(Steps,_Component);var _super=_createSuper(Steps);/**
* React Props
* @type {Object}
*/ /**
* React Default Props
* @type {Object}
*/ /**
* Creates a new instance of the component.
* @class
* @param {Object} props - The props of the component.
*/function Steps(props){var _this;_classCallCheck(this,Steps);_this=_super.call(this,props);_defineProperty(_assertThisInitialized(_this),"onExit",function(){var onExit=_this.props.onExit;_this.isVisible=false;onExit(_this.introJs._currentStep);});_defineProperty(_assertThisInitialized(_this),"onBeforeExit",function(){var onBeforeExit=_this.props.onBeforeExit;if(onBeforeExit){return onBeforeExit(_this.introJs._currentStep);}return true;});_defineProperty(_assertThisInitialized(_this),"onBeforeChange",function(){if(!_this.isVisible){return true;}var _this$props=_this.props,onBeforeChange=_this$props.onBeforeChange,onPreventChange=_this$props.onPreventChange;if(onBeforeChange){var continueStep=onBeforeChange(_this.introJs._currentStep);if(continueStep===false&&onPreventChange){setTimeout(function(){onPreventChange(_this.introJs._currentStep);},0);}return continueStep;}return true;});_defineProperty(_assertThisInitialized(_this),"onAfterChange",function(element){if(!_this.isVisible){return;}var onAfterChange=_this.props.onAfterChange;if(onAfterChange){onAfterChange(_this.introJs._currentStep,element);}});_defineProperty(_assertThisInitialized(_this),"onChange",function(element){if(!_this.isVisible){return;}var onChange=_this.props.onChange;if(onChange){onChange(_this.introJs._currentStep,element);}});_defineProperty(_assertThisInitialized(_this),"onComplete",function(){var onComplete=_this.props.onComplete;if(onComplete){onComplete();}});_defineProperty(_assertThisInitialized(_this),"updateStepElement",function(stepIndex){var element=document.querySelector(_this.introJs._options.steps[stepIndex].element);if(element){_this.introJs._introItems[stepIndex].element=element;_this.introJs._introItems[stepIndex].position=_this.introJs._options.steps[stepIndex].position||'auto';}});_this.introJs=null;_this.isConfigured=false;// We need to manually keep track of the visibility state to avoid a callback hell.
_this.isVisible=false;_this.installIntroJs();return _this;}/**
* Lifecycle: componentDidMount.
* We use this event to enable Intro.js steps at mount time if enabled right from the start.
*/_createClass(Steps,[{key:"componentDidMount",value:function componentDidMount(){if(this.props.enabled){this.configureIntroJs();this.renderSteps();}}/**
* Lifecycle: componentDidUpdate.
* @param {Object} prevProps - The previous props.
*/},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this$props2=this.props,enabled=_this$props2.enabled,steps=_this$props2.steps,options=_this$props2.options;if(!this.isConfigured||prevProps.steps!==steps||prevProps.options!==options){this.configureIntroJs();this.renderSteps();}if(prevProps.enabled!==enabled){this.renderSteps();}}/**
* Lifecycle: componentWillUnmount.
* We use this even to hide the steps when the component is unmounted.
*/},{key:"componentWillUnmount",value:function componentWillUnmount(){this.introJs.exit();}/**
* Triggered when Intro.js steps are exited.
*/},{key:"installIntroJs",/**
* Installs Intro.js.
*/value:function installIntroJs(){this.introJs=(0, _intro["default"])();this.introJs.onexit(this.onExit);this.introJs.onbeforeexit(this.onBeforeExit);this.introJs.onbeforechange(this.onBeforeChange);this.introJs.onafterchange(this.onAfterChange);this.introJs.onchange(this.onChange);this.introJs.oncomplete(this.onComplete);}/**
* Configures Intro.js if not already configured.
*/},{key:"configureIntroJs",value:function configureIntroJs(){var _this$props3=this.props,options=_this$props3.options,steps=_this$props3.steps;var sanitizedSteps=steps.map(function(step){if((0, react.isValidElement)(step.intro)){return _objectSpread(_objectSpread({},step),{},{intro:(0, server_browser.renderToStaticMarkup)(step.intro)});}return step;});this.introJs.setOptions(_objectSpread(_objectSpread({},options),{},{steps:sanitizedSteps}));this.isConfigured=true;}/**
* Renders the Intro.js steps.
*/},{key:"renderSteps",value:function renderSteps(){var _this$props4=this.props,enabled=_this$props4.enabled,initialStep=_this$props4.initialStep,steps=_this$props4.steps,onStart=_this$props4.onStart;if(enabled&&steps.length>0&&!this.isVisible){this.introJs.start();this.isVisible=true;this.introJs.goToStepNumber(initialStep+1);if(onStart){onStart(this.introJs._currentStep);}}else if(!enabled&&this.isVisible){this.isVisible=false;this.introJs.exit();}}/**
* Renders the component.
* @return {null} We do not want to render anything.
*/},{key:"render",value:function render(){return null;}}]);return Steps;}(react.Component);exports["default"]=Steps;_defineProperty(Steps,"propTypes",{enabled:_propTypes["default"].bool,initialStep:_propTypes["default"].number.isRequired,steps:_propTypes["default"].arrayOf(_propTypes["default"].shape({element:_propTypes["default"].string,intro:_propTypes["default"].node.isRequired,position:introJsPropTypes.tooltipPosition,tooltipClass:_propTypes["default"].string,highlightClass:_propTypes["default"].string})).isRequired,onStart:_propTypes["default"].func,onExit:_propTypes["default"].func.isRequired,onBeforeExit:_propTypes["default"].func,onBeforeChange:_propTypes["default"].func,onAfterChange:_propTypes["default"].func,onChange:_propTypes["default"].func,onPreventChange:_propTypes["default"].func,onComplete:_propTypes["default"].func,options:introJsPropTypes.options});_defineProperty(Steps,"defaultProps",{enabled:false,onStart:null,onBeforeExit:null,onBeforeChange:null,onAfterChange:null,onChange:null,onPreventChange:null,onComplete:null,options:introJsDefaultProps.options});
3 years ago
});
3 years ago
var Hints_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _intro=_interopRequireDefault(intro);var _propTypes=_interopRequireDefault(propTypes);var introJsPropTypes=_interopRequireWildcard(proptypes);var introJsDefaultProps=_interopRequireWildcard(defaultProps);function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap();_getRequireWildcardCache=function _getRequireWildcardCache(){return cache;};return cache;}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return {"default":obj};}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else {newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else {_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable;});keys.push.apply(keys,symbols);}return keys;}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach(function(key){_defineProperty(target,key,source[key]);});}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source));}else {ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}}return target;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else {result=Super.apply(this,arguments);}return _possibleConstructorReturn(this,result);};}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new
* Intro.js Hints Component.
*/var Hints=/*#__PURE__*/function(_Component){_inherits(Hints,_Component);var _super=_createSuper(Hints);/**
* React Props
* @type {Object}
*/ /**
* React Default Props
* @type {Object}
*/ /**
* Creates a new instance of the component.
* @class
* @param {Object} props - The props of the component.
*/function Hints(props){var _this;_classCallCheck(this,Hints);_this=_super.call(this,props);_this.introJs=null;_this.isConfigured=false;_this.installIntroJs();return _this;}/**
* Lifecycle: componentDidMount.
* We use this event to enable Intro.js hints at mount time if enabled right from the start.
*/_createClass(Hints,[{key:"componentDidMount",value:function componentDidMount(){if(this.props.enabled){this.configureIntroJs();this.renderHints();}}/**
* Lifecycle: componentDidUpdate.
* @param {Object} prevProps - The previous props.
*/},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this$props=this.props,enabled=_this$props.enabled,hints=_this$props.hints,options=_this$props.options;if(!this.isConfigured||prevProps.hints!==hints||prevProps.options!==options){this.configureIntroJs();this.renderHints();}if(prevProps.enabled!==enabled){this.renderHints();}}/**
* Lifecycle: componentWillUnmount.
* We use this even to hide the hints when the component is unmounted.
*/},{key:"componentWillUnmount",value:function componentWillUnmount(){this.introJs.hideHints();}/**
* Installs Intro.js.
*/},{key:"installIntroJs",value:function installIntroJs(){this.introJs=(0, _intro["default"])();var _this$props2=this.props,onClick=_this$props2.onClick,onClose=_this$props2.onClose;if(onClick){this.introJs.onhintclick(onClick);}if(onClose){this.introJs.onhintclose(onClose);}}/**
* Configures Intro.js if not already configured.
*/},{key:"configureIntroJs",value:function configureIntroJs(){var _this$props3=this.props,options=_this$props3.options,hints=_this$props3.hints;// We need to remove all hints otherwise new hints won't be added.
this.introJs.removeHints();this.introJs.setOptions(_objectSpread(_objectSpread({},options),{},{hints:hints}));this.isConfigured=true;}/**
* Renders the Intro.js hints.
*/},{key:"renderHints",value:function renderHints(){var _this$props4=this.props,enabled=_this$props4.enabled,hints=_this$props4.hints;if(enabled&&hints.length>0){this.introJs.showHints();}else if(!enabled){this.introJs.hideHints();}}/**
* Renders the component.
* @return {null} We do not want to render anything.
*/},{key:"render",value:function render(){return null;}}]);return Hints;}(react.Component);exports["default"]=Hints;_defineProperty(Hints,"propTypes",{enabled:_propTypes["default"].bool,hints:_propTypes["default"].arrayOf(_propTypes["default"].shape({element:_propTypes["default"].string.isRequired,hint:_propTypes["default"].string.isRequired,hintPosition:introJsPropTypes.hintPosition})).isRequired,onClick:_propTypes["default"].func,onClose:_propTypes["default"].func,options:introJsPropTypes.options});_defineProperty(Hints,"defaultProps",{enabled:false,onClick:null,onClose:null,options:introJsDefaultProps.options});
});
var lib = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"Steps",{enumerable:true,get:function get(){return _Steps["default"];}});Object.defineProperty(exports,"Hints",{enumerable:true,get:function get(){return _Hints["default"];}});var _Steps=_interopRequireDefault(Steps_1);var _Hints=_interopRequireDefault(Hints_1);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}
});
const FlexSidebar = He(FlexShrink) `
flex-basis: 20%;
3 years ago
`;
const LedgerDashboard = (props) => {
if (!props.txCache) {
return react.createElement("p", null, "Loading...");
}
const [tutorialIndex, setTutorialIndex] = react.useState(props.tutorialIndex);
const setTutorialIndexWrapper = (index) => {
setTutorialIndex(index); // This updates the current state
props.setTutorialIndex(index); // This updates the saved state
3 years ago
};
return obsidian.Platform.isMobile ? (react.createElement(MobileDashboard, { settings: props.settings, txCache: props.txCache })) : (react.createElement(DesktopDashboard, { tutorialIndex: tutorialIndex, setTutorialIndex: setTutorialIndexWrapper, settings: props.settings, txCache: props.txCache, updater: props.updater }));
};
const Header = (props) => (react.createElement("div", null,
react.createElement(FlexContainer, null,
react.createElement(FlexSidebar, null,
react.createElement("h2", null, "Ledger")),
react.createElement(FlexFloatRight, null, props.children))));
const MobileDashboard = (props) => {
const [selectedTab, setSelectedTab] = react.useState('transactions');
/*
return (
<MobileTransactionList
currencySymbol={props.settings.currencySymbol}
txCache={props.txCache}
/>
);
*/
return react.createElement("p", null, "Dashboard not yet supported on mobile.");
};
const DesktopDashboard = (props) => {
const dailyAccountBalanceMap = react.useMemo(() => {
console.time('daily-balance-map');
const changeMap = makeDailyAccountBalanceChangeMap(props.txCache.transactions);
const balanceMap = makeDailyBalanceMap(props.txCache.accounts, changeMap, props.txCache.firstDate, window.moment());
console.timeLog('daily-balance-map');
console.timeEnd('daily-balance-map');
return balanceMap;
}, [props.txCache]);
const [selectedAccounts, setSelectedAccounts] = react.useState([]);
const [startDate, setStartDate] = react.useState(window.moment().subtract(2, 'months'));
const [endDate, setEndDate] = react.useState(window.moment());
const [interval, setInterval] = react.useState('week');
return (react.createElement(react.Fragment, null,
react.createElement(Header, null,
react.createElement(DateRangeSelector, { startDate: startDate, endDate: endDate, setStartDate: setStartDate, setEndDate: setEndDate, interval: interval, setInterval: setInterval }),
props.tutorialIndex !== -1 ? (react.createElement(Tutorial, { tutorialIndex: props.tutorialIndex, setTutorialIndex: props.setTutorialIndex })) : null),
react.createElement(FlexContainer, null,
react.createElement(FlexSidebar, null,
react.createElement(AccountsList, { txCache: props.txCache, settings: props.settings, selectedAccounts: selectedAccounts, setSelectedAccounts: setSelectedAccounts })),
react.createElement(FlexMainContent, null,
props.txCache.parsingErrors.length > 0 ? (react.createElement(ParseErrors, { txCache: props.txCache })) : null,
selectedAccounts.length === 0 ? (react.createElement(react.Fragment, null,
react.createElement(NetWorthVisualization, { dailyAccountBalanceMap: dailyAccountBalanceMap, startDate: startDate, endDate: endDate, interval: interval, settings: props.settings }),
react.createElement(RecentTransactionList, { currencySymbol: props.settings.currencySymbol, txCache: props.txCache, updater: props.updater, startDate: startDate, endDate: endDate }))) : (react.createElement(react.Fragment, null,
react.createElement(AccountVisualization, { dailyAccountBalanceMap: dailyAccountBalanceMap, allAccounts: props.txCache.accounts, selectedAccounts: selectedAccounts, startDate: startDate, endDate: endDate, interval: interval }),
react.createElement(TransactionList, { currencySymbol: props.settings.currencySymbol, txCache: props.txCache, updater: props.updater, selectedAccounts: selectedAccounts, setSelectedAccount: (account) => setSelectedAccounts([account]), startDate: startDate, endDate: endDate })))))));
};
const Tutorial = (props) => {
const steps = [
{
intro: 'Welcome to the Obsidian Ledger plugin. Let me show you around a bit!',
tooltipClass: 'ledger-tutorial-tooltip',
},
{
intro: 'Click on account names to view their transactions and balance.',
element: '.ledger-account-list',
tooltipClass: 'ledger-tutorial-tooltip',
},
{
intro: 'Change the interval over which transactions are rolled up.',
element: '.ledger-interval-selectors',
tooltipClass: 'ledger-tutorial-tooltip',
},
{
intro: 'Only transactions within this date range will be displayed.',
element: '.ledger-daterange-selectors',
tooltipClass: 'ledger-tutorial-tooltip',
},
{
intro: 'Click here to edit your Ledger file as raw text.',
element: 'a[aria-label="Switch to Markdown View"]',
tooltipClass: 'ledger-tutorial-tooltip',
},
{
intro: 'There are more helpful tips in your Ledger file. Go take a look at it in raw text mode.',
tooltipClass: 'ledger-tutorial-tooltip',
},
{
intro: (react.createElement("p", null,
"If you have any questions, please visit the",
' ',
react.createElement("a", { href: "https://github.com/tgrosinger/ledger-obsidian/discussions" }, "Github Discussions Page"),
".")),
tooltipClass: 'ledger-tutorial-tooltip',
},
];
const onExit = (index) => {
if (index + 1 === steps.length) {
props.setTutorialIndex(-1);
3 years ago
}
else {
props.setTutorialIndex(index);
3 years ago
}
};
return (react.createElement(lib.Steps, { enabled: true, steps: steps, onExit: onExit, initialStep: props.tutorialIndex }));
};
const LedgerViewType = 'ledger';
class LedgerView extends obsidian.TextFileView {
constructor(leaf, plugin) {
super(leaf);
this.redraw = () => {
console.debug('Ledger: Creating dashboard view');
const contentEl = this.containerEl.children[1];
if (this.currentFilePath && this.updateInterface) {
reactDom.render(react.createElement(LedgerDashboard, {
tutorialIndex: this.plugin.settings.tutorialIndex,
setTutorialIndex: this.setTutorialIndex,
settings: this.plugin.settings,
txCache: this.txCache,
updater: this.updateInterface,
}), this.contentEl);
}
else {
contentEl.empty();
const span = contentEl.createSpan();
span.setText('Loading...');
}
};
this.setTutorialIndex = (index) => {
this.plugin.settings.tutorialIndex = index;
this.plugin.saveData(this.plugin.settings);
};
this.handleTxCacheUpdate = (txCache) => {
console.debug('Ledger: received an updated txCache for dashboard');
this.txCache = txCache;
// The plugin only monitors the ledger file for changes, so we will only be
// notified for that file. If we are viewing a different file currently then
// we should not redraw for this event.
if (this.currentFilePath === this.plugin.settings.ledgerFile) {
this.redraw();
}
};
this.plugin = plugin;
this.txCache = plugin.txCache;
this.currentFilePath = null;
this.updateInterface = null;
this.addAction('pencil', 'Switch to Markdown View', () => {
const state = leaf.view.getState();
leaf.setViewState({
type: 'markdown',
state,
popstate: true,
}, { focus: true });
});
this.redraw();
}
canAcceptExtension(extension) {
return extension === 'ledger';
}
getViewType() {
return LedgerViewType;
}
getDisplayText() {
return 'Ledger';
}
getIcon() {
return 'ledger';
}
getViewData() {
console.debug('Ledger: returning view data');
return this.data;
}
setViewData(data, clear) {
console.debug('Ledger: setting view data');
// TODO: Update the txCache and call redraw()
// TODO: This might not tell me about all file modify events
}
clear() {
console.debug('Ledger: clearing view');
}
onload() {
console.debug('Ledger: loading dashboard');
this.plugin.registerTxCacheSubscription(this.handleTxCacheUpdate);
}
onunload() {
console.debug('Ledger: unloading dashboard');
this.plugin.deregisterTxCacheSubscription(this.handleTxCacheUpdate);
}
async onLoadFile(file) {
console.debug('Ledger: File being loaded: ' + file.path);
if (file.path === this.plugin.settings.ledgerFile) {
this.txCache = this.plugin.txCache;
3 years ago
}
else {
// TODO: Setup a file watch for modifications while this file is open.
console.debug('Ledger: Generating txCache for other Ledger file: ' + file.path);
this.txCache = await getTransactionCache(this.plugin.app.metadataCache, this.plugin.app.vault, this.plugin.settings, file.path);
3 years ago
}
if (this.currentFilePath !== file.path) {
this.currentFilePath = file.path;
this.updateInterface = new LedgerModifier(this.plugin, file);
this.redraw();
3 years ago
}
}
async onUnloadFile(file) {
console.debug('Ledger: File being unloaded: ' + file.path);
// TODO: Use this to persist any changes that need to be saved.
// TODO: Tear down the file watch if this is a non-default file.
}
}
const defaultSettings = {
tutorialIndex: 0,
currencySymbol: '$',
ledgerFile: 'transactions.ledger',
assetAccountsPrefix: 'Assets',
expenseAccountsPrefix: 'Expenses',
incomeAccountsPrefix: 'Income',
liabilityAccountsPrefix: 'Liabilities',
};
const settingsWithDefaults = (settings) => ({
...defaultSettings,
...settings,
});
class SettingsTab extends obsidian.PluginSettingTab {
constructor(plugin) {
super(plugin.app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Ledger Plugin - Settings' });
new obsidian.Setting(containerEl)
.setName('Currency Symbol')
.setDesc('Prefixes all transaction amounts')
.addText((text) => {
text.setPlaceholder('$').setValue(this.plugin.settings.currencySymbol);
text.inputEl.onblur = (e) => {
this.plugin.settings.currencySymbol = e.target.value;
this.plugin.saveData(this.plugin.settings);
};
});
new obsidian.Setting(containerEl)
.setName('Ledger File')
.setDesc('Path in the Vault to your Ledger file. NOTE: If you use Obsidian Sync, you must enable "Sync all other types".')
.addText((text) => {
text
.setValue(this.plugin.settings.ledgerFile)
.setPlaceholder('transactions.ledger');
text.inputEl.onblur = (e) => {
const target = e.target;
const newValue = target.value;
if (newValue.endsWith('.ledger')) {
target.setCustomValidity('');
this.plugin.settings.ledgerFile = newValue;
this.plugin.saveData(this.plugin.settings);
}
else {
target.setCustomValidity('File must end with .ledger');
}
target.reportValidity();
};
});
containerEl.createEl('h3', 'Transaction Account Prefixes');
containerEl.createEl('p', {
text: "Ledger uses accounts to group expense types. Accounts are grouped into a hierarchy by separating with a colon. For example 'expenses:food:grocery' and 'expenses:food:restaurants",
});
new obsidian.Setting(containerEl)
.setName('Asset Account Prefix')
.setDesc('The account prefix used for grouping asset accounts. If you use aliases in your Ledger file, this must be the **unaliased** account prefix. e.g. "Assets" instead of "a"')
.addText((text) => {
text.setValue(this.plugin.settings.assetAccountsPrefix);
text.inputEl.onblur = (e) => {
this.plugin.settings.assetAccountsPrefix = e.target.value;
this.plugin.saveData(this.plugin.settings);
};
});
new obsidian.Setting(containerEl)
.setName('Expense Account Prefix')
.setDesc('The account prefix used for grouping expense accounts. If you use aliases in your Ledger file, this must be the **unaliased** account prefix. e.g. "Expenses" instead of "e"')
.addText((text) => {
text.setValue(this.plugin.settings.expenseAccountsPrefix);
text.inputEl.onblur = (e) => {
this.plugin.settings.expenseAccountsPrefix = e.target.value;
this.plugin.saveData(this.plugin.settings);
};
});
new obsidian.Setting(containerEl)
.setName('Income Account Prefix')
.setDesc('The account prefix used for grouping income accounts. If you use aliases in your Ledger file, this must be the **unaliased** account prefix. e.g. "Income" instead of "i"')
.addText((text) => {
text.setValue(this.plugin.settings.incomeAccountsPrefix);
text.inputEl.onblur = (e) => {
this.plugin.settings.incomeAccountsPrefix = e.target.value;
this.plugin.saveData(this.plugin.settings);
};
});
new obsidian.Setting(containerEl)
.setName('Liability Account Prefix')
.setDesc('The account prefix used for grouping liability accounts. If you use aliases in your Ledger file, this must be the **unaliased** account prefix. e.g. "Liabilities" instead of "l"')
.addText((text) => {
text.setValue(this.plugin.settings.liabilityAccountsPrefix);
text.inputEl.onblur = (e) => {
this.plugin.settings.liabilityAccountsPrefix = e.target.value;
this.plugin.saveData(this.plugin.settings);
};
});
const div = containerEl.createEl('div', {
cls: 'ledger-donation',
});
const donateText = document.createElement('p');
donateText.appendText('If this plugin adds value for you and you would like to help support ' +
'continued development, please use the buttons below:');
div.appendChild(donateText);
const parser = new DOMParser();
div.appendChild(createDonateButton('https://paypal.me/tgrosinger', parser.parseFromString(paypal, 'text/xml').documentElement));
div.appendChild(createDonateButton('https://www.buymeacoffee.com/tgrosinger', parser.parseFromString(buyMeACoffee, 'text/xml').documentElement));
}
}
const createDonateButton = (link, img) => {
const a = document.createElement('a');
a.setAttribute('href', link);
a.addClass('ledger-donate-button');
a.appendChild(img);
return a;
3 years ago
};
3 years ago
3 years ago
function around(obj,factories){const removers=Object.keys(factories).map(key=>around1(obj,key,factories[key]));return removers.length===1?removers[0]:function(){removers.forEach(r=>r());};}function around1(obj,method,createWrapper){const original=obj[method],hadOwn=obj.hasOwnProperty(method);let current=createWrapper(original);// Let our wrapper inherit static props from the wrapping method,
// and the wrapping method, props from the original method
if(original)Object.setPrototypeOf(current,original);Object.setPrototypeOf(wrapper,current);obj[method]=wrapper;// Return a callback to allow safe removal
return remove;function wrapper(...args){// If we have been deactivated and are no longer wrapped, remove ourselves
if(current===original&&obj[method]===wrapper)remove();return current.apply(this,args);}function remove(){// If no other patches, just do a direct removal
if(obj[method]===wrapper){if(hadOwn)obj[method]=original;else delete obj[method];}if(current===original)return;// Else pass future calls through, and remove wrapper from the prototype chain
current=original;Object.setPrototypeOf(wrapper,original||Function);}}
3 years ago
class LedgerPlugin extends obsidian.Plugin {
constructor() {
super(...arguments);
3 years ago
/**
* registerTxCacheSubscriptions takes a function which will be called any time
* the transaction cache is updated. The cache will automatically be updated
* whenever the ledger file is modified.
*/
this.registerTxCacheSubscription = (fn) => {
this.txCacheSubscriptions.push(fn);
};
/**
* deregisterTxCacheSubscription removes a function which was added using
* registerTxCacheSubscription.
*/
this.deregisterTxCacheSubscription = (fn) => {
this.txCacheSubscriptions.remove(fn);
};
3 years ago
this.createLedgerFileIfMissing = async () => {
let ledgerTFile = this.app.vault
.getFiles()
.find((file) => file.path === this.settings.ledgerFile);
if (!ledgerTFile) {
ledgerTFile = await this.app.vault.create(this.settings.ledgerFile, this.generateLedgerFileExampleContent());
await this.updateTransactionCache();
}
return ledgerTFile;
};
this.openLedgerDashboard = async () => {
let leaf = this.app.workspace.activeLeaf;
if (!leaf) {
new obsidian.Notice('Unable to find active leaf');
return;
}
if (leaf.getViewState().pinned) {
leaf = this.app.workspace.splitActiveLeaf('horizontal');
}
const ledgerTFile = await this.createLedgerFileIfMissing();
leaf.openFile(ledgerTFile);
};
3 years ago
this.generateLedgerFileExampleContent = () => `alias a=${this.settings.assetAccountsPrefix}
alias b=${this.settings.assetAccountsPrefix}:Banking
alias c=${this.settings.liabilityAccountsPrefix}:Credit
alias l=${this.settings.liabilityAccountsPrefix}
alias e=${this.settings.expenseAccountsPrefix}
alias i=${this.settings.incomeAccountsPrefix}
; Lines starting with a semicolon are comments and will not be parsed.
; This is an example of what a transaction looks like.
; Every transaction must balance to 0 if you add up all the lines.
; If the last line is left empty, it will automatically balance the transaction.
;
; 2021-12-25 Starbucks Coffee
; e:Food:Treats $5.25 ; To this account
; c:Chase ; From this account
; Use this transaction to fill in the balances from your bank accounts.
; This only needs to be done once, and enables you to reconcile your
; Ledger file with your bank account statements.
${window.moment().format('YYYY-MM-DD')} Starting Balances
; Add a line for each bank account or credit card
c:Chase $-250.45
b:BankOfAmerica $450.27
StartingBalance ; Leave this line alone
; I highly recommend reading through the Ledger documentation about the basics
; of accounting with Ledger
; https://www.ledger-cli.org/3.0/doc/ledger3.html#Principles-of-Accounting-with-Ledger
; Lots more information about this format can be found on the
; Ledger CLI homepage. Please note however that not quite all
; of the Ledger CLI functionality is supported by this plugin.
; https://www.ledger-cli.org
; You can add transactions here easily using the "Add to Ledger"
; Command in Obsidian. You can even make a shortcut to it on your
; mobile phone homescreen. See the README for more information.
; If you have questions, please use the Github discussions:
; https://github.com/tgrosinger/ledger-obsidian/discussions/landing
; If you encounter issues, please search the existing Github issues,
; and create a new one if your issue has not already been solved.
; https://github.com/tgrosinger/ledger-obsidian/issues
`;
3 years ago
/**
* updateTransactionCache is called whenever a modification to the ledger file
* is detected. The file will be reparsed and the txCache on this object will
* be replaced. Subscriptions will be notified with the new txCache.
*/
3 years ago
this.updateTransactionCache = async () => {
3 years ago
console.debug('ledger: Updating the transaction cache');
3 years ago
this.txCache = await getTransactionCache(this.app.metadataCache, this.app.vault, this.settings, this.settings.ledgerFile);
3 years ago
this.txCacheSubscriptions.forEach((fn) => fn(this.txCache));
3 years ago
};
this.handleProtocolAction = async (params) => {
3 years ago
// TODO: Support pre-populating fields, or even completely skipping the form
// by passing the correct data here.
const ledgerFile = await this.createLedgerFileIfMissing();
new LedgerModifier(this, ledgerFile).openExpenseModal('new');
3 years ago
};
3 years ago
}
3 years ago
async onload() {
console.log('ledger: Loading plugin v' + this.manifest.version);
3 years ago
this.txCacheSubscriptions = [];
3 years ago
await this.loadSettings();
this.addSettingTab(new SettingsTab(this));
obsidian.addIcon('ledger', billIcon);
3 years ago
this.addRibbonIcon('ledger', 'Add to Ledger', async () => {
const ledgerFile = await this.createLedgerFileIfMissing();
new LedgerModifier(this, ledgerFile).openExpenseModal('new');
3 years ago
});
3 years ago
this.registerObsidianProtocolHandler('ledger', this.handleProtocolAction);
3 years ago
this.registerView(LedgerViewType, (leaf) => new LedgerView(leaf, this));
this.registerExtensions(['ledger'], LedgerViewType);
3 years ago
this.registerEvent(this.app.vault.on('modify', (file) => {
if (file.path === this.settings.ledgerFile) {
3 years ago
this.updateTransactionCache();
3 years ago
}
}));
3 years ago
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
/*
let addedOnce = false;
this.register(
around(MarkdownView.prototype, {
addAction(next) {
return function (icon, title, callback) {
console.log('Add actions called: ' + title);
if (!addedOnce) {
addedOnce = true;
this.addAction('ledger', 'testing', () => {
console.log('clicked!');
});
3 years ago
}
3 years ago
return next.call(icon, title, callback);
};
3 years ago
},
3 years ago
}),
);
*/
this.register(around(obsidian.MarkdownView.prototype, {
onMoreOptionsMenu(next) {
return function (menu) {
if (this.file.path === self.settings.ledgerFile) {
menu
.addItem((item) => {
item
.setTitle('Open as Ledger file')
.setIcon('ledger')
.onClick(() => {
const state = this.leaf.view.getState();
this.leaf.setViewState({
type: LedgerViewType,
state: { file: state.file },
popstate: true,
});
});
})
.addSeparator();
}
next.call(this, menu);
};
},
}));
3 years ago
this.addCommand({
3 years ago
id: 'ledger-add-transaction',
name: 'Add to Ledger',
icon: 'ledger',
3 years ago
callback: async () => {
const ledgerFile = await this.createLedgerFileIfMissing();
new LedgerModifier(this, ledgerFile).openExpenseModal('new');
3 years ago
},
});
3 years ago
this.addCommand({
id: 'ledger-open-dashboard',
name: 'Open Ledger dashboard',
icon: 'ledger',
callback: this.openLedgerDashboard,
});
this.addCommand({
id: 'ledger-intro-tutorial',
name: 'Reset Ledger Tutorial progress',
icon: 'ledger',
callback: () => {
this.settings.tutorialIndex = 0;
this.saveData(this.settings);
},
});
3 years ago
this.app.workspace.onLayoutReady(() => {
this.updateTransactionCache();
3 years ago
});
}
3 years ago
async loadSettings() {
this.settings = settingsWithDefaults(await this.loadData());
this.saveData(this.settings);
3 years ago
}
}
module.exports = LedgerPlugin;
6 months ago
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFpbi5qcyIsInNvdXJjZXMiOlsibm9kZV9tb2R1bGVzL2xvZGFzaC9sb2Rhc2guanMiLCJzcmMvdHJhbnNhY3Rpb24tdXRpbHMudHMiLCJub2RlX21vZHVsZXMvb2JqZWN0LWFzc2lnbi9pbmRleC5qcyIsIm5vZGVfbW9kdWxlcy9yZWFjdC9janMvcmVhY3QucHJvZHVjdGlvbi5taW4uanMiLCJub2RlX21vZHVsZXMvcmVhY3QvY2pzL3JlYWN0LmRldmVsb3BtZW50LmpzIiwibm9kZV9tb2R1bGVzL3JlYWN0L2luZGV4LmpzIiwibm9kZV9tb2R1bGVzL3JlYWN0LWlzL2Nqcy9yZWFjdC1pcy5kZXZlbG9wbWVudC5qcyIsIm5vZGVfbW9kdWxlcy9yZWFjdC1pcy9pbmRleC5qcyIsIm5vZGVfbW9kdWxlcy9AZW1vdGlvbi9zdHlsaXMvZGlzdC9zdHlsaXMuYnJvd3Nlci5lc20uanMiLCJub2RlX21vZHVsZXMvQGVtb3Rpb24vdW5pdGxlc3MvZGlzdC91bml0bGVzcy5janMuZGV2LmpzIiwibm9kZV9tb2R1bGVzL0BlbW90aW9uL3VuaXRsZXNzL2Rpc3QvdW5pdGxlc3MuY2pzLmpzIiwibm9kZV9tb2R1bGVzL0BlbW90aW9uL21lbW9pemUvZGlzdC9tZW1vaXplLmJyb3dzZXIuZXNtLmpzIiwibm9kZV9tb2R1bGVzL0BlbW90aW9uL2lzLXByb3AtdmFsaWQvZGlzdC9pcy1wcm9wLXZhbGlkLmJyb3dzZXIuZXNtLmpzIiwibm9kZV9tb2R1bGVzL2hvaXN0LW5vbi1yZWFjdC1zdGF0aWNzL2Rpc3QvaG9pc3Qtbm9uLXJlYWN0LXN0YXRpY3MuY2pzLmpzIiwic3JjL3VpL0N1cnJlbmN5SW5wdXQudHN4Iiwibm9kZV9tb2R1bGVzL2Z1c2UuanMvZGlzdC9mdXNlLmVzbS5qcyIsIm5vZGVfbW9kdWxlcy9yZWFjdC1wb3BwZXIvbGliL2VzbS91dGlscy5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZW51bXMuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9nZXROb2RlTmFtZS5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldFdpbmRvdy5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2luc3RhbmNlT2YuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL21vZGlmaWVycy9hcHBseVN0eWxlcy5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvdXRpbHMvZ2V0QmFzZVBsYWNlbWVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldEJvdW5kaW5nQ2xpZW50UmVjdC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldExheW91dFJlY3QuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9jb250YWlucy5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldENvbXB1dGVkU3R5bGUuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9pc1RhYmxlRWxlbWVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldERvY3VtZW50RWxlbWVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldFBhcmVudE5vZGUuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9nZXRPZmZzZXRQYXJlbnQuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL3V0aWxzL2dldE1haW5BeGlzRnJvbVBsYWNlbWVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvdXRpbHMvbWF0aC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvdXRpbHMvd2l0aGluLmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi91dGlscy9nZXRGcmVzaFNpZGVPYmplY3QuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL3V0aWxzL21lcmdlUGFkZGluZ09iamVjdC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvdXRpbHMvZXhwYW5kVG9IYXNoTWFwLmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi9tb2RpZmllcnMvYXJyb3cuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL21vZGlmaWVycy9jb21wdXRlU3R5bGVzLmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi9tb2RpZmllcnMvZXZlbnRMaXN0ZW5lcnMuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL3V0aWxzL2dldE9wcG9zaXRlUGxhY2VtZW50LmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi91dGlscy9nZXRPcHBvc2l0ZVZhcmlhdGlvblBsYWNlbWVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldFdpbmRvd1Njcm9sbC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldFdpbmRvd1Njcm9sbEJhclguanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9nZXRWaWV3cG9ydFJlY3QuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9nZXREb2N1bWVudFJlY3QuanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL2RvbS11dGlscy9pc1Njcm9sbFBhcmVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2dldFNjcm9sbFBhcmVudC5qcyIsIm5vZGVfbW9kdWxlcy9AcG9wcGVyanMvY29yZS9saWIvZG9tLXV0aWxzL2xpc3RTY3JvbGxQYXJlbnRzLmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi91dGlscy9yZWN0VG9DbGllbnRSZWN0LmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi9kb20tdXRpbHMvZ2V0Q2xpcHBpbmdSZWN0LmpzIiwibm9kZV9tb2R1bGVzL0Bwb3BwZXJqcy9jb3JlL2xpYi91dGlscy9nZXRWYXJpYXRpb24uanMiLCJub2RlX21vZHVsZXMvQHBvcHBlcmpzL2NvcmUvbGliL3V0aWxzL2NvbXB1dGVPZmZzZXRzLmpzIiwibm9