'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var _commonjsHelpers = require('../_commonjsHelpers-4ed3570f.js'); var React = require('react'); var React__default = _interopDefault(React); var styleInject_es = require('../style-inject.es-dcee06b6.js'); var Draft = require('../Draft-7ee7c163.js'); var _reactDom_commonjsExternal = require('../_react-dom_commonjs-external-55867475.js'); require('react-dom'); var server = _interopDefault(require('react-dom/server')); var immutable = _commonjsHelpers.createCommonjsModule(function (module, exports) { /** * Copyright (c) 2014-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. */ (function (global, factory) { factory(exports) ; }(_commonjsHelpers.commonjsGlobal, (function (exports) { // Used for setting prototype methods that IE8 chokes on. var DELETE = 'delete'; // Constants describing the size of trie nodes. var SHIFT = 5; // Resulted in best performance after ______? var SIZE = 1 << SHIFT; var MASK = SIZE - 1; // A consistent shared value representing "not set" which equals nothing other // than itself, and nothing that could be provided externally. var NOT_SET = {}; // Boolean references, Rough equivalent of `bool &`. function MakeRef() { return { value: false }; } function SetRef(ref) { if (ref) { ref.value = true; } } // A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {} function ensureSize(iter) { if (iter.size === undefined) { iter.size = iter.__iterate(returnTrue); } return iter.size; } function wrapIndex(iter, index) { // This implements "is array index" which the ECMAString spec defines as: // // A String property name P is an array index if and only if // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal // to 2^32−1. // // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects if (typeof index !== 'number') { var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 if ('' + uint32Index !== index || uint32Index === 4294967295) { return NaN; } index = uint32Index; } return index < 0 ? ensureSize(iter) + index : index; } function returnTrue() { return true; } function wholeSlice(begin, end, size) { return ( ((begin === 0 && !isNeg(begin)) || (size !== undefined && begin <= -size)) && (end === undefined || (size !== undefined && end >= size)) ); } function resolveBegin(begin, size) { return resolveIndex(begin, size, 0); } function resolveEnd(end, size) { return resolveIndex(end, size, size); } function resolveIndex(index, size, defaultIndex) { // Sanitize indices using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 return index === undefined ? defaultIndex : isNeg(index) ? size === Infinity ? size : Math.max(0, size + index) | 0 : size === undefined || size === index ? index : Math.min(size, index) | 0; } function isNeg(value) { // Account for -0 which is negative, but not less than 0. return value < 0 || (value === 0 && 1 / value === -Infinity); } // Note: value is unchanged to not break immutable-devtools. var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@'; function isCollection(maybeCollection) { return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]); } var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@'; function isKeyed(maybeKeyed) { return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]); } var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@'; function isIndexed(maybeIndexed) { return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]); } function isAssociative(maybeAssociative) { return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); } var Collection = function Collection(value) { return isCollection(value) ? value : Seq(value); }; var KeyedCollection = /*@__PURE__*/(function (Collection) { function KeyedCollection(value) { return isKeyed(value) ? value : KeyedSeq(value); } if ( Collection ) KeyedCollection.__proto__ = Collection; KeyedCollection.prototype = Object.create( Collection && Collection.prototype ); KeyedCollection.prototype.constructor = KeyedCollection; return KeyedCollection; }(Collection)); var IndexedCollection = /*@__PURE__*/(function (Collection) { function IndexedCollection(value) { return isIndexed(value) ? value : IndexedSeq(value); } if ( Collection ) IndexedCollection.__proto__ = Collection; IndexedCollection.prototype = Object.create( Collection && Collection.prototype ); IndexedCollection.prototype.constructor = IndexedCollection; return IndexedCollection; }(Collection)); var SetCollection = /*@__PURE__*/(function (Collection) { function SetCollection(value) { return isCollection(value) && !isAssociative(value) ? value : SetSeq(value); } if ( Collection ) SetCollection.__proto__ = Collection; SetCollection.prototype = Object.create( Collection && Collection.prototype ); SetCollection.prototype.constructor = SetCollection; return SetCollection; }(Collection)); Collection.Keyed = KeyedCollection; Collection.Indexed = IndexedCollection; Collection.Set = SetCollection; var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@'; function isSeq(maybeSeq) { return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]); } var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@'; function isRecord(maybeRecord) { return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]); } function isImmutable(maybeImmutable) { return isCollection(maybeImmutable) || isRecord(maybeImmutable); } var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@'; function isOrdered(maybeOrdered) { return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]); } var ITERATE_KEYS = 0; var ITERATE_VALUES = 1; var ITERATE_ENTRIES = 2; var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; var Iterator = function Iterator(next) { this.next = next; }; Iterator.prototype.toString = function toString () { return '[Iterator]'; }; Iterator.KEYS = ITERATE_KEYS; Iterator.VALUES = ITERATE_VALUES; Iterator.ENTRIES = ITERATE_ENTRIES; Iterator.prototype.inspect = Iterator.prototype.toSource = function() { return this.toString(); }; Iterator.prototype[ITERATOR_SYMBOL] = function() { return this; }; function iteratorValue(type, k, v, iteratorResult) { var value = type === 0 ? k : type === 1 ? v : [k, v]; iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { value: value, done: false, }); return iteratorResult; } function iteratorDone() { return { value: undefined, done: true }; } function hasIterator(maybeIterable) { return !!getIteratorFn(maybeIterable); } function isIterator(maybeIterator) { return maybeIterator && typeof maybeIterator.next === 'function'; } function getIterator(iterable) { var iteratorFn = getIteratorFn(iterable); return iteratorFn && iteratorFn.call(iterable); } function getIteratorFn(iterable) { var iteratorFn = iterable && ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || iterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } var hasOwnProperty = Object.prototype.hasOwnProperty; function isArrayLike(value) { if (Array.isArray(value) || typeof value === 'string') { return true; } return ( value && typeof value === 'object' && Number.isInteger(value.length) && value.length >= 0 && (value.length === 0 ? // Only {length: 0} is considered Array-like. Object.keys(value).length === 1 : // An object is only Array-like if it has a property where the last value // in the array-like may be found (which could be undefined). value.hasOwnProperty(value.length - 1)) ); } var Seq = /*@__PURE__*/(function (Collection$$1) { function Seq(value) { return value === null || value === undefined ? emptySequence() : isImmutable(value) ? value.toSeq() : seqFromValue(value); } if ( Collection$$1 ) Seq.__proto__ = Collection$$1; Seq.prototype = Object.create( Collection$$1 && Collection$$1.prototype ); Seq.prototype.constructor = Seq; Seq.prototype.toSeq = function toSeq () { return this; }; Seq.prototype.toString = function toString () { return this.__toString('Seq {', '}'); }; Seq.prototype.cacheResult = function cacheResult () { if (!this._cache && this.__iterateUncached) { this._cache = this.entrySeq().toArray(); this.size = this._cache.length; } return this; }; // abstract __iterateUncached(fn, reverse) Seq.prototype.__iterate = function __iterate (fn, reverse) { var cache = this._cache; if (cache) { var size = cache.length; var i = 0; while (i !== size) { var entry = cache[reverse ? size - ++i : i++]; if (fn(entry[1], entry[0], this) === false) { break; } } return i; } return this.__iterateUncached(fn, reverse); }; // abstract __iteratorUncached(type, reverse) Seq.prototype.__iterator = function __iterator (type, reverse) { var cache = this._cache; if (cache) { var size = cache.length; var i = 0; return new Iterator(function () { if (i === size) { return iteratorDone(); } var entry = cache[reverse ? size - ++i : i++]; return iteratorValue(type, entry[0], entry[1]); }); } return this.__iteratorUncached(type, reverse); }; return Seq; }(Collection)); var KeyedSeq = /*@__PURE__*/(function (Seq) { function KeyedSeq(value) { return value === null || value === undefined ? emptySequence().toKeyedSeq() : isCollection(value) ? isKeyed(value) ? value.toSeq() : value.fromEntrySeq() : isRecord(value) ? value.toSeq() : keyedSeqFromValue(value); } if ( Seq ) KeyedSeq.__proto__ = Seq; KeyedSeq.prototype = Object.create( Seq && Seq.prototype ); KeyedSeq.prototype.constructor = KeyedSeq; KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () { return this; }; return KeyedSeq; }(Seq)); var IndexedSeq = /*@__PURE__*/(function (Seq) { function IndexedSeq(value) { return value === null || value === undefined ? emptySequence() : isCollection(value) ? isKeyed(value) ? value.entrySeq() : value.toIndexedSeq() : isRecord(value) ? value.toSeq().entrySeq() : indexedSeqFromValue(value); } if ( Seq ) IndexedSeq.__proto__ = Seq; IndexedSeq.prototype = Object.create( Seq && Seq.prototype ); IndexedSeq.prototype.constructor = IndexedSeq; IndexedSeq.of = function of (/*...values*/) { return IndexedSeq(arguments); }; IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () { return this; }; IndexedSeq.prototype.toString = function toString () { return this.__toString('Seq [', ']'); }; return IndexedSeq; }(Seq)); var SetSeq = /*@__PURE__*/(function (Seq) { function SetSeq(value) { return (isCollection(value) && !isAssociative(value) ? value : IndexedSeq(value) ).toSetSeq(); } if ( Seq ) SetSeq.__proto__ = Seq; SetSeq.prototype = Object.create( Seq && Seq.prototype ); SetSeq.prototype.constructor = SetSeq; SetSeq.of = function of (/*...values*/) { return SetSeq(arguments); }; SetSeq.prototype.toSetSeq = function toSetSeq () { return this; }; return SetSeq; }(Seq)); Seq.isSeq = isSeq; Seq.Keyed = KeyedSeq; Seq.Set = SetSeq; Seq.Indexed = IndexedSeq; Seq.prototype[IS_SEQ_SYMBOL] = true; // #pragma Root Sequences var ArraySeq = /*@__PURE__*/(function (IndexedSeq) { function ArraySeq(array) { this._array = array; this.size = array.length; } if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq; ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); ArraySeq.prototype.constructor = ArraySeq; ArraySeq.prototype.get = function get (index, notSetValue) { return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; ArraySeq.prototype.__iterate = function __iterate (fn, reverse) { var array = this._array; var size = array.length; var i = 0; while (i !== size) { var ii = reverse ? size - ++i : i++; if (fn(array[ii], ii, this) === false) { break; } } return i; }; ArraySeq.prototype.__iterator = function __iterator (type, reverse) { var array = this._array; var size = array.length; var i = 0; return new Iterator(function () { if (i === size) { return iteratorDone(); } var ii = reverse ? size - ++i : i++; return iteratorValue(type, ii, array[ii]); }); }; return ArraySeq; }(IndexedSeq)); var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) { function ObjectSeq(object) { var keys = Object.keys(object); this._object = object; this._keys = keys; this.size = keys.length; } if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq; ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype ); ObjectSeq.prototype.constructor = ObjectSeq; ObjectSeq.prototype.get = function get (key, notSetValue) { if (notSetValue !== undefined && !this.has(key)) { return notSetValue; } return this._object[key]; }; ObjectSeq.prototype.has = function has (key) { return hasOwnProperty.call(this._object, key); }; ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) { var object = this._object; var keys = this._keys; var size = keys.length; var i = 0; while (i !== size) { var key = keys[reverse ? size - ++i : i++]; if (fn(object[key], key, this) === false) { break; } } return i; }; ObjectSeq.prototype.__iterator = function __iterator (type, reverse) { var object = this._object; var keys = this._keys; var size = keys.length; var i = 0; return new Iterator(function () { if (i === size) { return iteratorDone(); } var key = keys[reverse ? size - ++i : i++]; return iteratorValue(type, key, object[key]); }); }; return ObjectSeq; }(KeyedSeq)); ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true; var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) { function CollectionSeq(collection) { this._collection = collection; this.size = collection.length || collection.size; } if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq; CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype ); CollectionSeq.prototype.constructor = CollectionSeq; CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var collection = this._collection; var iterator = getIterator(collection); var iterations = 0; if (isIterator(iterator)) { var step; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } } return iterations; }; CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var collection = this._collection; var iterator = getIterator(collection); if (!isIterator(iterator)) { return new Iterator(iteratorDone); } var iterations = 0; return new Iterator(function () { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; return CollectionSeq; }(IndexedSeq)); // # pragma Helper functions var EMPTY_SEQ; function emptySequence() { return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } function keyedSeqFromValue(value) { var seq = Array.isArray(value) ? new ArraySeq(value) : hasIterator(value) ? new CollectionSeq(value) : undefined; if (seq) { return seq.fromEntrySeq(); } if (typeof value === 'object') { return new ObjectSeq(value); } throw new TypeError( 'Expected Array or collection object of [k, v] entries, or keyed object: ' + value ); } function indexedSeqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (seq) { return seq; } throw new TypeError( 'Expected Array or collection object of values: ' + value ); } function seqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (seq) { return seq; } if (typeof value === 'object') { return new ObjectSeq(value); } throw new TypeError( 'Expected Array or collection object of values, or keyed object: ' + value ); } function maybeIndexedSeqFromValue(value) { return isArrayLike(value) ? new ArraySeq(value) : hasIterator(value) ? new CollectionSeq(value) : undefined; } var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@'; function isMap(maybeMap) { return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]); } function isOrderedMap(maybeOrderedMap) { return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } function isValueObject(maybeValue) { return Boolean( maybeValue && typeof maybeValue.equals === 'function' && typeof maybeValue.hashCode === 'function' ); } /** * An extension of the "same-value" algorithm as [described for use by ES6 Map * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) * * NaN is considered the same as NaN, however -0 and 0 are considered the same * value, which is different from the algorithm described by * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * This is extended further to allow Objects to describe the values they * represent, by way of `valueOf` or `equals` (and `hashCode`). * * Note: because of this extension, the key equality of Immutable.Map and the * value equality of Immutable.Set will differ from ES6 Map and Set. * * ### Defining custom values * * The easiest way to describe the value an object represents is by implementing * `valueOf`. For example, `Date` represents a value by returning a unix * timestamp for `valueOf`: * * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... * var date2 = new Date(1234567890000); * date1.valueOf(); // 1234567890000 * assert( date1 !== date2 ); * assert( Immutable.is( date1, date2 ) ); * * Note: overriding `valueOf` may have other implications if you use this object * where JavaScript expects a primitive, such as implicit string coercion. * * For more complex types, especially collections, implementing `valueOf` may * not be performant. An alternative is to implement `equals` and `hashCode`. * * `equals` takes another object, presumably of similar type, and returns true * if it is equal. Equality is symmetrical, so the same result should be * returned if this and the argument are flipped. * * assert( a.equals(b) === b.equals(a) ); * * `hashCode` returns a 32bit integer number representing the object which will * be used to determine how to store the value object in a Map or Set. You must * provide both or neither methods, one must not exist without the other. * * Also, an important relationship between these methods must be upheld: if two * values are equal, they *must* return the same hashCode. If the values are not * equal, they might have the same hashCode; this is called a hash collision, * and while undesirable for performance reasons, it is acceptable. * * if (a.equals(b)) { * assert( a.hashCode() === b.hashCode() ); * } * * All Immutable collections are Value Objects: they implement `equals()` * and `hashCode()`. */ function is(valueA, valueB) { if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } if ( typeof valueA.valueOf === 'function' && typeof valueB.valueOf === 'function' ) { valueA = valueA.valueOf(); valueB = valueB.valueOf(); if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } } return !!( isValueObject(valueA) && isValueObject(valueB) && valueA.equals(valueB) ); } var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? Math.imul : function imul(a, b) { a |= 0; // int b |= 0; // int var c = a & 0xffff; var d = b & 0xffff; // Shift by 0 fixes the sign on the high part. return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int }; // v8 has an optimization for storing 31-bit signed numbers. // Values which have either 00 or 11 as the high order bits qualify. // This function drops the highest order bit in a signed number, maintaining // the sign bit. function smi(i32) { return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff); } var defaultValueOf = Object.prototype.valueOf; function hash(o) { switch (typeof o) { case 'boolean': // The hash values for built-in constants are a 1 value for each 5-byte // shift region expect for the first, which encodes the value. This // reduces the odds of a hash collision for these common values. return o ? 0x42108421 : 0x42108420; case 'number': return hashNumber(o); case 'string': return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); case 'object': case 'function': if (o === null) { return 0x42108422; } if (typeof o.hashCode === 'function') { // Drop any high bits from accidentally long hash codes. return smi(o.hashCode(o)); } if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') { o = o.valueOf(o); } return hashJSObj(o); case 'undefined': return 0x42108423; default: if (typeof o.toString === 'function') { return hashString(o.toString()); } throw new Error('Value type ' + typeof o + ' cannot be hashed.'); } } // Compress arbitrarily large numbers into smi hashes. function hashNumber(n) { if (n !== n || n === Infinity) { return 0; } var hash = n | 0; if (hash !== n) { hash ^= n * 0xffffffff; } while (n > 0xffffffff) { n /= 0xffffffff; hash ^= n; } return smi(hash); } function cachedHashString(string) { var hashed = stringHashCache[string]; if (hashed === undefined) { hashed = hashString(string); if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { STRING_HASH_CACHE_SIZE = 0; stringHashCache = {}; } STRING_HASH_CACHE_SIZE++; stringHashCache[string] = hashed; } return hashed; } // http://jsperf.com/hashing-strings function hashString(string) { // This is the hash from JVM // The hash code for a string is computed as // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], // where s[i] is the ith character of the string and n is the length of // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 // (exclusive) by dropping high bits. var hashed = 0; for (var ii = 0; ii < string.length; ii++) { hashed = (31 * hashed + string.charCodeAt(ii)) | 0; } return smi(hashed); } function hashJSObj(obj) { var hashed; if (usingWeakMap) { hashed = weakMap.get(obj); if (hashed !== undefined) { return hashed; } } hashed = obj[UID_HASH_KEY]; if (hashed !== undefined) { return hashed; } if (!canDefineProperty) { hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; if (hashed !== undefined) { return hashed; } hashed = getIENodeHash(obj); if (hashed !== undefined) { return hashed; } } hashed = ++objHashUID; if (objHashUID & 0x40000000) { objHashUID = 0; } if (usingWeakMap) { weakMap.set(obj, hashed); } else if (isExtensible !== undefined && isExtensible(obj) === false) { throw new Error('Non-extensible objects are not allowed as keys.'); } else if (canDefineProperty) { Object.defineProperty(obj, UID_HASH_KEY, { enumerable: false, configurable: false, writable: false, value: hashed, }); } else if ( obj.propertyIsEnumerable !== undefined && obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable ) { // Since we can't define a non-enumerable property on the object // we'll hijack one of the less-used non-enumerable properties to // save our hash on it. Since this is a function it will not show up in // `JSON.stringify` which is what we want. obj.propertyIsEnumerable = function() { return this.constructor.prototype.propertyIsEnumerable.apply( this, arguments ); }; obj.propertyIsEnumerable[UID_HASH_KEY] = hashed; } else if (obj.nodeType !== undefined) { // At this point we couldn't get the IE `uniqueID` to use as a hash // and we couldn't use a non-enumerable property to exploit the // dontEnum bug so we simply add the `UID_HASH_KEY` on the node // itself. obj[UID_HASH_KEY] = hashed; } else { throw new Error('Unable to set a non-enumerable property on object.'); } return hashed; } // Get references to ES5 object methods. var isExtensible = Object.isExtensible; // True if Object.defineProperty works as expected. IE8 fails this test. var canDefineProperty = (function() { try { Object.defineProperty({}, '@', {}); return true; } catch (e) { return false; } })(); // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it // and avoid memory leaks from the IE cloneNode bug. function getIENodeHash(node) { if (node && node.nodeType > 0) { switch (node.nodeType) { case 1: // Element return node.uniqueID; case 9: // Document return node.documentElement && node.documentElement.uniqueID; } } } // If possible, use a WeakMap. var usingWeakMap = typeof WeakMap === 'function'; var weakMap; if (usingWeakMap) { weakMap = new WeakMap(); } var objHashUID = 0; var UID_HASH_KEY = '__immutablehash__'; if (typeof Symbol === 'function') { UID_HASH_KEY = Symbol(UID_HASH_KEY); } var STRING_HASH_CACHE_MIN_STRLEN = 16; var STRING_HASH_CACHE_MAX_SIZE = 255; var STRING_HASH_CACHE_SIZE = 0; var stringHashCache = {}; var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq$$1) { function ToKeyedSequence(indexed, useKeys) { this._iter = indexed; this._useKeys = useKeys; this.size = indexed.size; } if ( KeyedSeq$$1 ) ToKeyedSequence.__proto__ = KeyedSeq$$1; ToKeyedSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype ); ToKeyedSequence.prototype.constructor = ToKeyedSequence; ToKeyedSequence.prototype.get = function get (key, notSetValue) { return this._iter.get(key, notSetValue); }; ToKeyedSequence.prototype.has = function has (key) { return this._iter.has(key); }; ToKeyedSequence.prototype.valueSeq = function valueSeq () { return this._iter.valueSeq(); }; ToKeyedSequence.prototype.reverse = function reverse () { var this$1 = this; var reversedSequence = reverseFactory(this, true); if (!this._useKeys) { reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); }; } return reversedSequence; }; ToKeyedSequence.prototype.map = function map (mapper, context) { var this$1 = this; var mappedSequence = mapFactory(this, mapper, context); if (!this._useKeys) { mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); }; } return mappedSequence; }; ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse); }; ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) { return this._iter.__iterator(type, reverse); }; return ToKeyedSequence; }(KeyedSeq)); ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true; var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq$$1) { function ToIndexedSequence(iter) { this._iter = iter; this.size = iter.size; } if ( IndexedSeq$$1 ) ToIndexedSequence.__proto__ = IndexedSeq$$1; ToIndexedSequence.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype ); ToIndexedSequence.prototype.constructor = ToIndexedSequence; ToIndexedSequence.prototype.includes = function includes (value) { return this._iter.includes(value); }; ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; var i = 0; reverse && ensureSize(this); return this._iter.__iterate( function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); }, reverse ); }; ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) { var this$1 = this; var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var i = 0; reverse && ensureSize(this); return new Iterator(function () { var step = iterator.next(); return step.done ? step : iteratorValue( type, reverse ? this$1.size - ++i : i++, step.value, step ); }); }; return ToIndexedSequence; }(IndexedSeq)); var ToSetSequence = /*@__PURE__*/(function (SetSeq$$1) { function ToSetSequence(iter) { this._iter = iter; this.size = iter.size; } if ( SetSeq$$1 ) ToSetSequence.__proto__ = SetSeq$$1; ToSetSequence.prototype = Object.create( SetSeq$$1 && SetSeq$$1.prototype ); ToSetSequence.prototype.constructor = ToSetSequence; ToSetSequence.prototype.has = function has (key) { return this._iter.includes(key); }; ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse); }; ToSetSequence.prototype.__iterator = function __iterator (type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function () { var step = iterator.next(); return step.done ? step : iteratorValue(type, step.value, step.value, step); }); }; return ToSetSequence; }(SetSeq)); var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq$$1) { function FromEntriesSequence(entries) { this._iter = entries; this.size = entries.size; } if ( KeyedSeq$$1 ) FromEntriesSequence.__proto__ = KeyedSeq$$1; FromEntriesSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype ); FromEntriesSequence.prototype.constructor = FromEntriesSequence; FromEntriesSequence.prototype.entrySeq = function entrySeq () { return this._iter.toSeq(); }; FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; return this._iter.__iterate(function (entry) { // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedCollection = isCollection(entry); return fn( indexedCollection ? entry.get(1) : entry[1], indexedCollection ? entry.get(0) : entry[0], this$1 ); } }, reverse); }; FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function () { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedCollection = isCollection(entry); return iteratorValue( type, indexedCollection ? entry.get(0) : entry[0], indexedCollection ? entry.get(1) : entry[1], step ); } } }); }; return FromEntriesSequence; }(KeyedSeq)); ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; function flipFactory(collection) { var flipSequence = makeSequence(collection); flipSequence._iter = collection; flipSequence.size = collection.size; flipSequence.flip = function () { return collection; }; flipSequence.reverse = function() { var reversedSequence = collection.reverse.apply(this); // super.reverse() reversedSequence.flip = function () { return collection.reverse(); }; return reversedSequence; }; flipSequence.has = function (key) { return collection.includes(key); }; flipSequence.includes = function (key) { return collection.has(key); }; flipSequence.cacheResult = cacheResultThrough; flipSequence.__iterateUncached = function(fn, reverse) { var this$1 = this; return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse); }; flipSequence.__iteratorUncached = function(type, reverse) { if (type === ITERATE_ENTRIES) { var iterator = collection.__iterator(type, reverse); return new Iterator(function () { var step = iterator.next(); if (!step.done) { var k = step.value[0]; step.value[0] = step.value[1]; step.value[1] = k; } return step; }); } return collection.__iterator( type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse ); }; return flipSequence; } function mapFactory(collection, mapper, context) { var mappedSequence = makeSequence(collection); mappedSequence.size = collection.size; mappedSequence.has = function (key) { return collection.has(key); }; mappedSequence.get = function (key, notSetValue) { var v = collection.get(key, NOT_SET); return v === NOT_SET ? notSetValue : mapper.call(context, v, key, collection); }; mappedSequence.__iterateUncached = function(fn, reverse) { var this$1 = this; return collection.__iterate( function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; }, reverse ); }; mappedSequence.__iteratorUncached = function(type, reverse) { var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); return new Iterator(function () { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; return iteratorValue( type, key, mapper.call(context, entry[1], key, collection), step ); }); }; return mappedSequence; } function reverseFactory(collection, useKeys) { var this$1 = this; var reversedSequence = makeSequence(collection); reversedSequence._iter = collection; reversedSequence.size = collection.size; reversedSequence.reverse = function () { return collection; }; if (collection.flip) { reversedSequence.flip = function() { var flipSequence = flipFactory(collection); flipSequence.reverse = function () { return collection.flip(); }; return flipSequence; }; } reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); }; reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); }; reversedSequence.includes = function (value) { return collection.includes(value); }; reversedSequence.cacheResult = cacheResultThrough; reversedSequence.__iterate = function(fn, reverse) { var this$1 = this; var i = 0; reverse && ensureSize(collection); return collection.__iterate( function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); }, !reverse ); }; reversedSequence.__iterator = function (type, reverse) { var i = 0; reverse && ensureSize(collection); var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse); return new Iterator(function () { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; return iteratorValue( type, useKeys ? entry[0] : reverse ? this$1.size - ++i : i++, entry[1], step ); }); }; return reversedSequence; } function filterFactory(collection, predicate, context, useKeys) { var filterSequence = makeSequence(collection); if (useKeys) { filterSequence.has = function (key) { var v = collection.get(key, NOT_SET); return v !== NOT_SET && !!predicate.call(context, v, key, collection); }; filterSequence.get = function (key, notSetValue) { var v = collection.get(key, NOT_SET); return v !== NOT_SET && predicate.call(context, v, key, collection) ? v : notSetValue; }; } filterSequence.__iterateUncached = function(fn, reverse) { var this$1 = this; var iterations = 0; collection.__iterate(function (v, k, c) { if (predicate.call(context, v, k, c)) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$1); } }, reverse); return iterations; }; filterSequence.__iteratorUncached = function(type, reverse) { var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); var iterations = 0; return new Iterator(function () { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; var value = entry[1]; if (predicate.call(context, value, key, collection)) { return iteratorValue(type, useKeys ? key : iterations++, value, step); } } }); }; return filterSequence; } function countByFactory(collection, grouper, context) { var groups = Map().asMutable(); collection.__iterate(function (v, k) { groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; }); }); return groups.asImmutable(); } function groupByFactory(collection, grouper, context) { var isKeyedIter = isKeyed(collection); var groups = (isOrdered(collection) ? OrderedMap() : Map()).asMutable(); collection.__iterate(function (v, k) { groups.update( grouper.call(context, v, k, collection), function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); } ); }); var coerce = collectionClass(collection); return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable(); } function sliceFactory(collection, begin, end, useKeys) { var originalSize = collection.size; if (wholeSlice(begin, end, originalSize)) { return collection; } var resolvedBegin = resolveBegin(begin, originalSize); var resolvedEnd = resolveEnd(end, originalSize); // begin or end will be NaN if they were provided as negative numbers and // this collection's size is unknown. In that case, cache first so there is // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys); } // Note: resolvedEnd is undefined when the original sequence's length is // unknown and this slice did not supply an end and should contain all // elements after resolvedBegin. // In that case, resolvedSize will be NaN and sliceSize will remain undefined. var resolvedSize = resolvedEnd - resolvedBegin; var sliceSize; if (resolvedSize === resolvedSize) { sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(collection); // If collection.size is undefined, the size of the realized sliceSeq is // unknown at this point unless the number of items to slice is 0 sliceSeq.size = sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined; if (!useKeys && isSeq(collection) && sliceSize >= 0) { sliceSeq.get = function(index, notSetValue) { index = wrapIndex(this, index); return index >= 0 && index < sliceSize ? collection.get(index + resolvedBegin, notSetValue) : notSetValue; }; } sliceSeq.__iterateUncached = function(fn, reverse) { var this$1 = this; if (sliceSize === 0) { return 0; } if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var skipped = 0; var isSkipping = true; var iterations = 0; collection.__iterate(function (v, k) { if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { iterations++; return ( fn(v, useKeys ? k : iterations - 1, this$1) !== false && iterations !== sliceSize ); } }); return iterations; }; sliceSeq.__iteratorUncached = function(type, reverse) { if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. if (sliceSize === 0) { return new Iterator(iteratorDone); } var iterator = collection.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new Iterator(function () { while (skipped++ < resolvedBegin) { iterator.next(); } if (++iterations > sliceSize) { return iteratorDone(); } var step = iterator.next(); if (useKeys || type === ITERATE_VALUES || step.done) { return step; } if (type === ITERATE_KEYS) { return iteratorValue(type, iterations - 1, undefined, step); } return iteratorValue(type, iterations - 1, step.value[1], step); }); }; return sliceSeq; } function takeWhileFactory(collection, predicate, context) { var takeSequence = makeSequence(collection); takeSequence.__iterateUncached = function(fn, reverse) { var this$1 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; collection.__iterate( function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); } ); return iterations; }; takeSequence.__iteratorUncached = function(type, reverse) { var this$1 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); var iterating = true; return new Iterator(function () { if (!iterating) { return iteratorDone(); } var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var k = entry[0]; var v = entry[1]; if (!predicate.call(context, v, k, this$1)) { iterating = false; return iteratorDone(); } return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return takeSequence; } function skipWhileFactory(collection, predicate, context, useKeys) { var skipSequence = makeSequence(collection); skipSequence.__iterateUncached = function(fn, reverse) { var this$1 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var isSkipping = true; var iterations = 0; collection.__iterate(function (v, k, c) { if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$1); } }); return iterations; }; skipSequence.__iteratorUncached = function(type, reverse) { var this$1 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); var skipping = true; var iterations = 0; return new Iterator(function () { var step; var k; var v; do { step = iterator.next(); if (step.done) { if (useKeys || type === ITERATE_VALUES) { return step; } if (type === ITERATE_KEYS) { return iteratorValue(type, iterations++, undefined, step); } return iteratorValue(type, iterations++, step.value[1], step); } var entry = step.value; k = entry[0]; v = entry[1]; skipping && (skipping = predicate.call(context, v, k, this$1)); } while (skipping); return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return skipSequence; } function concatFactory(collection, values) { var isKeyedCollection = isKeyed(collection); var iters = [collection] .concat(values) .map(function (v) { if (!isCollection(v)) { v = isKeyedCollection ? keyedSeqFromValue(v) : indexedSeqFromValue(Array.isArray(v) ? v : [v]); } else if (isKeyedCollection) { v = KeyedCollection(v); } return v; }) .filter(function (v) { return v.size !== 0; }); if (iters.length === 0) { return collection; } if (iters.length === 1) { var singleton = iters[0]; if ( singleton === collection || (isKeyedCollection && isKeyed(singleton)) || (isIndexed(collection) && isIndexed(singleton)) ) { return singleton; } } var concatSeq = new ArraySeq(iters); if (isKeyedCollection) { concatSeq = concatSeq.toKeyedSeq(); } else if (!isIndexed(collection)) { concatSeq = concatSeq.toSetSeq(); } concatSeq = concatSeq.flatten(true); concatSeq.size = iters.reduce(function (sum, seq) { if (sum !== undefined) { var size = seq.size; if (size !== undefined) { return sum + size; } } }, 0); return concatSeq; } function flattenFactory(collection, depth, useKeys) { var flatSequence = makeSequence(collection); flatSequence.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; var stopped = false; function flatDeep(iter, currentDepth) { iter.__iterate(function (v, k) { if ((!depth || currentDepth < depth) && isCollection(v)) { flatDeep(v, currentDepth + 1); } else { iterations++; if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) { stopped = true; } } return !stopped; }, reverse); } flatDeep(collection, 0); return iterations; }; flatSequence.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = collection.__iterator(type, reverse); var stack = []; var iterations = 0; return new Iterator(function () { while (iterator) { var step = iterator.next(); if (step.done !== false) { iterator = stack.pop(); continue; } var v = step.value; if (type === ITERATE_ENTRIES) { v = v[1]; } if ((!depth || stack.length < depth) && isCollection(v)) { stack.push(iterator); iterator = v.__iterator(type, reverse); } else { return useKeys ? step : iteratorValue(type, iterations++, v, step); } } return iteratorDone(); }); }; return flatSequence; } function flatMapFactory(collection, mapper, context) { var coerce = collectionClass(collection); return collection .toSeq() .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); }) .flatten(true); } function interposeFactory(collection, separator) { var interposedSequence = makeSequence(collection); interposedSequence.size = collection.size && collection.size * 2 - 1; interposedSequence.__iterateUncached = function(fn, reverse) { var this$1 = this; var iterations = 0; collection.__iterate( function (v) { return (!iterations || fn(separator, iterations++, this$1) !== false) && fn(v, iterations++, this$1) !== false; }, reverse ); return iterations; }; interposedSequence.__iteratorUncached = function(type, reverse) { var iterator = collection.__iterator(ITERATE_VALUES, reverse); var iterations = 0; var step; return new Iterator(function () { if (!step || iterations % 2) { step = iterator.next(); if (step.done) { return step; } } return iterations % 2 ? iteratorValue(type, iterations++, separator) : iteratorValue(type, iterations++, step.value, step); }); }; return interposedSequence; } function sortFactory(collection, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } var isKeyedCollection = isKeyed(collection); var index = 0; var entries = collection .toSeq() .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; }) .valueSeq() .toArray(); entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach( isKeyedCollection ? function (v, i) { entries[i].length = 2; } : function (v, i) { entries[i] = v[1]; } ); return isKeyedCollection ? KeyedSeq(entries) : isIndexed(collection) ? IndexedSeq(entries) : SetSeq(entries); } function maxFactory(collection, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } if (mapper) { var entry = collection .toSeq() .map(function (v, k) { return [v, mapper(v, k, collection)]; }) .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); }); return entry && entry[0]; } return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); }); } function maxCompare(comparator, a, b) { var comp = comparator(b, a); // b is considered the new max if the comparator declares them equal, but // they are not equal and b is in fact a nullish value. return ( (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0 ); } function zipWithFactory(keyIter, zipper, iters, zipAll) { var zipSequence = makeSequence(keyIter); var sizes = new ArraySeq(iters).map(function (i) { return i.size; }); zipSequence.size = zipAll ? sizes.max() : sizes.min(); // Note: this a generic base implementation of __iterate in terms of // __iterator which may be more generically useful in the future. zipSequence.__iterate = function(fn, reverse) { /* generic: var iterator = this.__iterator(ITERATE_ENTRIES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { iterations++; if (fn(step.value[1], step.value[0], this) === false) { break; } } return iterations; */ // indexed: var iterator = this.__iterator(ITERATE_VALUES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } return iterations; }; zipSequence.__iteratorUncached = function(type, reverse) { var iterators = iters.map( function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); } ); var iterations = 0; var isDone = false; return new Iterator(function () { var steps; if (!isDone) { steps = iterators.map(function (i) { return i.next(); }); isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; }); } if (isDone) { return iteratorDone(); } return iteratorValue( type, iterations++, zipper.apply(null, steps.map(function (s) { return s.value; })) ); }); }; return zipSequence; } // #pragma Helper Functions function reify(iter, seq) { return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq); } function validateEntry(entry) { if (entry !== Object(entry)) { throw new TypeError('Expected [K, V] tuple: ' + entry); } } function collectionClass(collection) { return isKeyed(collection) ? KeyedCollection : isIndexed(collection) ? IndexedCollection : SetCollection; } function makeSequence(collection) { return Object.create( (isKeyed(collection) ? KeyedSeq : isIndexed(collection) ? IndexedSeq : SetSeq ).prototype ); } function cacheResultThrough() { if (this._iter.cacheResult) { this._iter.cacheResult(); this.size = this._iter.size; return this; } return Seq.prototype.cacheResult.call(this); } function defaultComparator(a, b) { if (a === undefined && b === undefined) { return 0; } if (a === undefined) { return 1; } if (b === undefined) { return -1; } return a > b ? 1 : a < b ? -1 : 0; } // http://jsperf.com/copy-array-inline function arrCopy(arr, offset) { offset = offset || 0; var len = Math.max(0, arr.length - offset); var newArr = new Array(len); for (var ii = 0; ii < len; ii++) { newArr[ii] = arr[ii + offset]; } return newArr; } function invariant(condition, error) { if (!condition) { throw new Error(error); } } function assertNotInfinite(size) { invariant( size !== Infinity, 'Cannot perform this action with an infinite size.' ); } function coerceKeyPath(keyPath) { if (isArrayLike(keyPath) && typeof keyPath !== 'string') { return keyPath; } if (isOrdered(keyPath)) { return keyPath.toArray(); } throw new TypeError( 'Invalid keyPath: expected Ordered Collection or Array: ' + keyPath ); } function isPlainObj(value) { return ( value && (typeof value.constructor !== 'function' || value.constructor.name === 'Object') ); } /** * Returns true if the value is a potentially-persistent data structure, either * provided by Immutable.js or a plain Array or Object. */ function isDataStructure(value) { return ( typeof value === 'object' && (isImmutable(value) || Array.isArray(value) || isPlainObj(value)) ); } /** * Converts a value to a string, adding quotes if a string was provided. */ function quoteString(value) { try { return typeof value === 'string' ? JSON.stringify(value) : String(value); } catch (_ignoreError) { return JSON.stringify(value); } } function has(collection, key) { return isImmutable(collection) ? collection.has(key) : isDataStructure(collection) && hasOwnProperty.call(collection, key); } function get(collection, key, notSetValue) { return isImmutable(collection) ? collection.get(key, notSetValue) : !has(collection, key) ? notSetValue : typeof collection.get === 'function' ? collection.get(key) : collection[key]; } function shallowCopy(from) { if (Array.isArray(from)) { return arrCopy(from); } var to = {}; for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } return to; } function remove(collection, key) { if (!isDataStructure(collection)) { throw new TypeError( 'Cannot update non-data-structure value: ' + collection ); } if (isImmutable(collection)) { if (!collection.remove) { throw new TypeError( 'Cannot update immutable value without .remove() method: ' + collection ); } return collection.remove(key); } if (!hasOwnProperty.call(collection, key)) { return collection; } var collectionCopy = shallowCopy(collection); if (Array.isArray(collectionCopy)) { collectionCopy.splice(key, 1); } else { delete collectionCopy[key]; } return collectionCopy; } function set(collection, key, value) { if (!isDataStructure(collection)) { throw new TypeError( 'Cannot update non-data-structure value: ' + collection ); } if (isImmutable(collection)) { if (!collection.set) { throw new TypeError( 'Cannot update immutable value without .set() method: ' + collection ); } return collection.set(key, value); } if (hasOwnProperty.call(collection, key) && value === collection[key]) { return collection; } var collectionCopy = shallowCopy(collection); collectionCopy[key] = value; return collectionCopy; } function updateIn(collection, keyPath, notSetValue, updater) { if (!updater) { updater = notSetValue; notSetValue = undefined; } var updatedValue = updateInDeeply( isImmutable(collection), collection, coerceKeyPath(keyPath), 0, notSetValue, updater ); return updatedValue === NOT_SET ? notSetValue : updatedValue; } function updateInDeeply( inImmutable, existing, keyPath, i, notSetValue, updater ) { var wasNotSet = existing === NOT_SET; if (i === keyPath.length) { var existingValue = wasNotSet ? notSetValue : existing; var newValue = updater(existingValue); return newValue === existingValue ? existing : newValue; } if (!wasNotSet && !isDataStructure(existing)) { throw new TypeError( 'Cannot update within non-data-structure value in path [' + keyPath.slice(0, i).map(quoteString) + ']: ' + existing ); } var key = keyPath[i]; var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET); var nextUpdated = updateInDeeply( nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting), nextExisting, keyPath, i + 1, notSetValue, updater ); return nextUpdated === nextExisting ? existing : nextUpdated === NOT_SET ? remove(existing, key) : set( wasNotSet ? (inImmutable ? emptyMap() : {}) : existing, key, nextUpdated ); } function setIn(collection, keyPath, value) { return updateIn(collection, keyPath, NOT_SET, function () { return value; }); } function setIn$1(keyPath, v) { return setIn(this, keyPath, v); } function removeIn(collection, keyPath) { return updateIn(collection, keyPath, function () { return NOT_SET; }); } function deleteIn(keyPath) { return removeIn(this, keyPath); } function update(collection, key, notSetValue, updater) { return updateIn(collection, [key], notSetValue, updater); } function update$1(key, notSetValue, updater) { return arguments.length === 1 ? key(this) : update(this, key, notSetValue, updater); } function updateIn$1(keyPath, notSetValue, updater) { return updateIn(this, keyPath, notSetValue, updater); } function merge() { var iters = [], len = arguments.length; while ( len-- ) iters[ len ] = arguments[ len ]; return mergeIntoKeyedWith(this, iters); } function mergeWith(merger) { var iters = [], len = arguments.length - 1; while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; if (typeof merger !== 'function') { throw new TypeError('Invalid merger function: ' + merger); } return mergeIntoKeyedWith(this, iters, merger); } function mergeIntoKeyedWith(collection, collections, merger) { var iters = []; for (var ii = 0; ii < collections.length; ii++) { var collection$1 = KeyedCollection(collections[ii]); if (collection$1.size !== 0) { iters.push(collection$1); } } if (iters.length === 0) { return collection; } if ( collection.toSeq().size === 0 && !collection.__ownerID && iters.length === 1 ) { return collection.constructor(iters[0]); } return collection.withMutations(function (collection) { var mergeIntoCollection = merger ? function (value, key) { update( collection, key, NOT_SET, function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); } ); } : function (value, key) { collection.set(key, value); }; for (var ii = 0; ii < iters.length; ii++) { iters[ii].forEach(mergeIntoCollection); } }); } function merge$1(collection) { var sources = [], len = arguments.length - 1; while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; return mergeWithSources(collection, sources); } function mergeWith$1(merger, collection) { var sources = [], len = arguments.length - 2; while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ]; return mergeWithSources(collection, sources, merger); } function mergeDeep(collection) { var sources = [], len = arguments.length - 1; while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; return mergeDeepWithSources(collection, sources); } function mergeDeepWith(merger, collection) { var sources = [], len = arguments.length - 2; while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ]; return mergeDeepWithSources(collection, sources, merger); } function mergeDeepWithSources(collection, sources, merger) { return mergeWithSources(collection, sources, deepMergerWith(merger)); } function mergeWithSources(collection, sources, merger) { if (!isDataStructure(collection)) { throw new TypeError( 'Cannot merge into non-data-structure value: ' + collection ); } if (isImmutable(collection)) { return typeof merger === 'function' && collection.mergeWith ? collection.mergeWith.apply(collection, [ merger ].concat( sources )) : collection.merge ? collection.merge.apply(collection, sources) : collection.concat.apply(collection, sources); } var isArray = Array.isArray(collection); var merged = collection; var Collection$$1 = isArray ? IndexedCollection : KeyedCollection; var mergeItem = isArray ? function (value) { // Copy on write if (merged === collection) { merged = shallowCopy(merged); } merged.push(value); } : function (value, key) { var hasVal = hasOwnProperty.call(merged, key); var nextVal = hasVal && merger ? merger(merged[key], value, key) : value; if (!hasVal || nextVal !== merged[key]) { // Copy on write if (merged === collection) { merged = shallowCopy(merged); } merged[key] = nextVal; } }; for (var i = 0; i < sources.length; i++) { Collection$$1(sources[i]).forEach(mergeItem); } return merged; } function deepMergerWith(merger) { function deepMerger(oldValue, newValue, key) { return isDataStructure(oldValue) && isDataStructure(newValue) ? mergeWithSources(oldValue, [newValue], deepMerger) : merger ? merger(oldValue, newValue, key) : newValue; } return deepMerger; } function mergeDeep$1() { var iters = [], len = arguments.length; while ( len-- ) iters[ len ] = arguments[ len ]; return mergeDeepWithSources(this, iters); } function mergeDeepWith$1(merger) { var iters = [], len = arguments.length - 1; while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; return mergeDeepWithSources(this, iters, merger); } function mergeIn(keyPath) { var iters = [], len = arguments.length - 1; while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); }); } function mergeDeepIn(keyPath) { var iters = [], len = arguments.length - 1; while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ]; return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); } ); } function withMutations(fn) { var mutable = this.asMutable(); fn(mutable); return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; } function asMutable() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); } function asImmutable() { return this.__ensureOwner(); } function wasAltered() { return this.__altered; } var Map = /*@__PURE__*/(function (KeyedCollection$$1) { function Map(value) { return value === null || value === undefined ? emptyMap() : isMap(value) && !isOrdered(value) ? value : emptyMap().withMutations(function (map) { var iter = KeyedCollection$$1(value); assertNotInfinite(iter.size); iter.forEach(function (v, k) { return map.set(k, v); }); }); } if ( KeyedCollection$$1 ) Map.__proto__ = KeyedCollection$$1; Map.prototype = Object.create( KeyedCollection$$1 && KeyedCollection$$1.prototype ); Map.prototype.constructor = Map; Map.of = function of () { var keyValues = [], len = arguments.length; while ( len-- ) keyValues[ len ] = arguments[ len ]; return emptyMap().withMutations(function (map) { for (var i = 0; i < keyValues.length; i += 2) { if (i + 1 >= keyValues.length) { throw new Error('Missing value for key: ' + keyValues[i]); } map.set(keyValues[i], keyValues[i + 1]); } }); }; Map.prototype.toString = function toString () { return this.__toString('Map {', '}'); }; // @pragma Access Map.prototype.get = function get (k, notSetValue) { return this._root ? this._root.get(0, undefined, k, notSetValue) : notSetValue; }; // @pragma Modification Map.prototype.set = function set (k, v) { return updateMap(this, k, v); }; Map.prototype.remove = function remove (k) { return updateMap(this, k, NOT_SET); }; Map.prototype.deleteAll = function deleteAll (keys) { var collection = Collection(keys); if (collection.size === 0) { return this; } return this.withMutations(function (map) { collection.forEach(function (key) { return map.remove(key); }); }); }; Map.prototype.clear = function clear () { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }; // @pragma Composition Map.prototype.sort = function sort (comparator) { // Late binding return OrderedMap(sortFactory(this, comparator)); }; Map.prototype.sortBy = function sortBy (mapper, comparator) { // Late binding return OrderedMap(sortFactory(this, comparator, mapper)); }; Map.prototype.map = function map (mapper, context) { return this.withMutations(function (map) { map.forEach(function (value, key) { map.set(key, mapper.call(context, value, key, map)); }); }); }; // @pragma Mutability Map.prototype.__iterator = function __iterator (type, reverse) { return new MapIterator(this, type, reverse); }; Map.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; var iterations = 0; this._root && this._root.iterate(function (entry) { iterations++; return fn(entry[1], entry[0], this$1); }, reverse); return iterations; }; Map.prototype.__ensureOwner = function __ensureOwner (ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { if (this.size === 0) { return emptyMap(); } this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }; return Map; }(KeyedCollection)); Map.isMap = isMap; var MapPrototype = Map.prototype; MapPrototype[IS_MAP_SYMBOL] = true; MapPrototype[DELETE] = MapPrototype.remove; MapPrototype.removeAll = MapPrototype.deleteAll; MapPrototype.setIn = setIn$1; MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn; MapPrototype.update = update$1; MapPrototype.updateIn = updateIn$1; MapPrototype.merge = MapPrototype.concat = merge; MapPrototype.mergeWith = mergeWith; MapPrototype.mergeDeep = mergeDeep$1; MapPrototype.mergeDeepWith = mergeDeepWith$1; MapPrototype.mergeIn = mergeIn; MapPrototype.mergeDeepIn = mergeDeepIn; MapPrototype.withMutations = withMutations; MapPrototype.wasAltered = wasAltered; MapPrototype.asImmutable = asImmutable; MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable; MapPrototype['@@transducer/step'] = function(result, arr) { return result.set(arr[0], arr[1]); }; MapPrototype['@@transducer/result'] = function(obj) { return obj.asImmutable(); }; // #pragma Trie Nodes var ArrayMapNode = function ArrayMapNode(ownerID, entries) { this.ownerID = ownerID; this.entries = entries; }; ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var entries = this.entries; var idx = 0; var len = entries.length; for (; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && entries.length === 1) { return; // undefined } if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { return createNodes(ownerID, entries, key, value); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new ArrayMapNode(ownerID, newEntries); }; var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) { this.ownerID = ownerID; this.bitmap = bitmap; this.nodes = nodes; }; BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK); var bitmap = this.bitmap; return (bitmap & bit) === 0 ? notSetValue : this.nodes[popCount(bitmap & (bit - 1))].get( shift + SHIFT, keyHash, key, notSetValue ); }; BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var bit = 1 << keyHashFrag; var bitmap = this.bitmap; var exists = (bitmap & bit) !== 0; if (!exists && value === NOT_SET) { return this; } var idx = popCount(bitmap & (bit - 1)); var nodes = this.nodes; var node = exists ? nodes[idx] : undefined; var newNode = updateNode( node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter ); if (newNode === node) { return this; } if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); } if ( exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1]) ) { return nodes[idx ^ 1]; } if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { return newNode; } var isEditable = ownerID && ownerID === this.ownerID; var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit; var newNodes = exists ? newNode ? setAt(nodes, idx, newNode, isEditable) : spliceOut(nodes, idx, isEditable) : spliceIn(nodes, idx, newNode, isEditable); if (isEditable) { this.bitmap = newBitmap; this.nodes = newNodes; return this; } return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) { this.ownerID = ownerID; this.count = count; this.nodes = nodes; }; HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var node = this.nodes[idx]; return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; }; HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var removed = value === NOT_SET; var nodes = this.nodes; var node = nodes[idx]; if (removed && !node) { return this; } var newNode = updateNode( node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter ); if (newNode === node) { return this; } var newCount = this.count; if (!node) { newCount++; } else if (!newNode) { newCount--; if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { return packNodes(ownerID, nodes, newCount, idx); } } var isEditable = ownerID && ownerID === this.ownerID; var newNodes = setAt(nodes, idx, newNode, isEditable); if (isEditable) { this.count = newCount; this.nodes = newNodes; return this; } return new HashArrayMapNode(ownerID, newCount, newNodes); }; var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) { this.ownerID = ownerID; this.keyHash = keyHash; this.entries = entries; }; HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var removed = value === NOT_SET; if (keyHash !== this.keyHash) { if (removed) { return this; } SetRef(didAlter); SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); } var entries = this.entries; var idx = 0; var len = entries.length; for (; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && len === 2) { return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new HashCollisionNode(ownerID, this.keyHash, newEntries); }; var ValueNode = function ValueNode(ownerID, keyHash, entry) { this.ownerID = ownerID; this.keyHash = keyHash; this.entry = entry; }; ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) { return is(key, this.entry[0]) ? this.entry[1] : notSetValue; }; ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var keyMatch = is(key, this.entry[0]); if (keyMatch ? value === this.entry[1] : removed) { return this; } SetRef(didAlter); if (removed) { SetRef(didChangeSize); return; // undefined } if (keyMatch) { if (ownerID && ownerID === this.ownerID) { this.entry[1] = value; return this; } return new ValueNode(ownerID, this.keyHash, [key, value]); } SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); }; // #pragma Iterators ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function( fn, reverse ) { var entries = this.entries; for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { return false; } } }; BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function( fn, reverse ) { var nodes = this.nodes; for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { var node = nodes[reverse ? maxIndex - ii : ii]; if (node && node.iterate(fn, reverse) === false) { return false; } } }; // eslint-disable-next-line no-unused-vars ValueNode.prototype.iterate = function(fn, reverse) { return fn(this.entry); }; var MapIterator = /*@__PURE__*/(function (Iterator$$1) { function MapIterator(map, type, reverse) { this._type = type; this._reverse = reverse; this._stack = map._root && mapIteratorFrame(map._root); } if ( Iterator$$1 ) MapIterator.__proto__ = Iterator$$1; MapIterator.prototype = Object.create( Iterator$$1 && Iterator$$1.prototype ); MapIterator.prototype.constructor = MapIterator; MapIterator.prototype.next = function next () { var type = this._type; var stack = this._stack; while (stack) { var node = stack.node; var index = stack.index++; var maxIndex = (void 0); if (node.entry) { if (index === 0) { return mapIteratorValue(type, node.entry); } } else if (node.entries) { maxIndex = node.entries.length - 1; if (index <= maxIndex) { return mapIteratorValue( type, node.entries[this._reverse ? maxIndex - index : index] ); } } else { maxIndex = node.nodes.length - 1; if (index <= maxIndex) { var subNode = node.nodes[this._reverse ? maxIndex - index : index]; if (subNode) { if (subNode.entry) { return mapIteratorValue(type, subNode.entry); } stack = this._stack = mapIteratorFrame(subNode, stack); } continue; } } stack = this._stack = this._stack.__prev; } return iteratorDone(); }; return MapIterator; }(Iterator)); function mapIteratorValue(type, entry) { return iteratorValue(type, entry[0], entry[1]); } function mapIteratorFrame(node, prev) { return { node: node, index: 0, __prev: prev, }; } function makeMap(size, root, ownerID, hash$$1) { var map = Object.create(MapPrototype); map.size = size; map._root = root; map.__ownerID = ownerID; map.__hash = hash$$1; map.__altered = false; return map; } var EMPTY_MAP; function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); } function updateMap(map, k, v) { var newRoot; var newSize; if (!map._root) { if (v === NOT_SET) { return map; } newSize = 1; newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); } else { var didChangeSize = MakeRef(); var didAlter = MakeRef(); newRoot = updateNode( map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter ); if (!didAlter.value) { return map; } newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0); } if (map.__ownerID) { map.size = newSize; map._root = newRoot; map.__hash = undefined; map.__altered = true; return map; } return newRoot ? makeMap(newSize, newRoot) : emptyMap(); } function updateNode( node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter ) { if (!node) { if (value === NOT_SET) { return node; } SetRef(didAlter); SetRef(didChangeSize); return new ValueNode(ownerID, keyHash, [key, value]); } return node.update( ownerID, shift, keyHash, key, value, didChangeSize, didAlter ); } function isLeafNode(node) { return ( node.constructor === ValueNode || node.constructor === HashCollisionNode ); } function mergeIntoNode(node, ownerID, shift, keyHash, entry) { if (node.keyHash === keyHash) { return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); } var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var newNode; var nodes = idx1 === idx2 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); } function createNodes(ownerID, entries, key, value) { if (!ownerID) { ownerID = new OwnerID(); } var node = new ValueNode(ownerID, hash(key), [key, value]); for (var ii = 0; ii < entries.length; ii++) { var entry = entries[ii]; node = node.update(ownerID, 0, undefined, entry[0], entry[1]); } return node; } function packNodes(ownerID, nodes, count, excluding) { var bitmap = 0; var packedII = 0; var packedNodes = new Array(count); for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { var node = nodes[ii]; if (node !== undefined && ii !== excluding) { bitmap |= bit; packedNodes[packedII++] = node; } } return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } function expandNodes(ownerID, nodes, bitmap, including, node) { var count = 0; var expandedNodes = new Array(SIZE); for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; } expandedNodes[including] = node; return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } function popCount(x) { x -= (x >> 1) & 0x55555555; x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x += x >> 8; x += x >> 16; return x & 0x7f; } function setAt(array, idx, val, canEdit) { var newArray = canEdit ? array : arrCopy(array); newArray[idx] = val; return newArray; } function spliceIn(array, idx, val, canEdit) { var newLen = array.length + 1; if (canEdit && idx + 1 === newLen) { array[idx] = val; return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { newArray[ii] = val; after = -1; } else { newArray[ii] = array[ii + after]; } } return newArray; } function spliceOut(array, idx, canEdit) { var newLen = array.length - 1; if (canEdit && idx === newLen) { array.pop(); return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { after = 1; } newArray[ii] = array[ii + after]; } return newArray; } var MAX_ARRAY_MAP_SIZE = SIZE / 4; var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@'; function isList(maybeList) { return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]); } var List = /*@__PURE__*/(function (IndexedCollection$$1) { function List(value) { var empty = emptyList(); if (value === null || value === undefined) { return empty; } if (isList(value)) { return value; } var iter = IndexedCollection$$1(value); var size = iter.size; if (size === 0) { return empty; } assertNotInfinite(size); if (size > 0 && size < SIZE) { return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); } return empty.withMutations(function (list) { list.setSize(size); iter.forEach(function (v, i) { return list.set(i, v); }); }); } if ( IndexedCollection$$1 ) List.__proto__ = IndexedCollection$$1; List.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype ); List.prototype.constructor = List; List.of = function of (/*...values*/) { return this(arguments); }; List.prototype.toString = function toString () { return this.__toString('List [', ']'); }; // @pragma Access List.prototype.get = function get (index, notSetValue) { index = wrapIndex(this, index); if (index >= 0 && index < this.size) { index += this._origin; var node = listNodeFor(this, index); return node && node.array[index & MASK]; } return notSetValue; }; // @pragma Modification List.prototype.set = function set (index, value) { return updateList(this, index, value); }; List.prototype.remove = function remove (index) { return !this.has(index) ? this : index === 0 ? this.shift() : index === this.size - 1 ? this.pop() : this.splice(index, 1); }; List.prototype.insert = function insert (index, value) { return this.splice(index, 0, value); }; List.prototype.clear = function clear () { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = this._origin = this._capacity = 0; this._level = SHIFT; this._root = this._tail = null; this.__hash = undefined; this.__altered = true; return this; } return emptyList(); }; List.prototype.push = function push (/*...values*/) { var values = arguments; var oldSize = this.size; return this.withMutations(function (list) { setListBounds(list, 0, oldSize + values.length); for (var ii = 0; ii < values.length; ii++) { list.set(oldSize + ii, values[ii]); } }); }; List.prototype.pop = function pop () { return setListBounds(this, 0, -1); }; List.prototype.unshift = function unshift (/*...values*/) { var values = arguments; return this.withMutations(function (list) { setListBounds(list, -values.length); for (var ii = 0; ii < values.length; ii++) { list.set(ii, values[ii]); } }); }; List.prototype.shift = function shift () { return setListBounds(this, 1); }; // @pragma Composition List.prototype.concat = function concat (/*...collections*/) { var arguments$1 = arguments; var seqs = []; for (var i = 0; i < arguments.length; i++) { var argument = arguments$1[i]; var seq = IndexedCollection$$1( typeof argument !== 'string' && hasIterator(argument) ? argument : [argument] ); if (seq.size !== 0) { seqs.push(seq); } } if (seqs.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && seqs.length === 1) { return this.constructor(seqs[0]); } return this.withMutations(function (list) { seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); }); }); }; List.prototype.setSize = function setSize (size) { return setListBounds(this, 0, size); }; List.prototype.map = function map (mapper, context) { var this$1 = this; return this.withMutations(function (list) { for (var i = 0; i < this$1.size; i++) { list.set(i, mapper.call(context, list.get(i), i, list)); } }); }; // @pragma Iteration List.prototype.slice = function slice (begin, end) { var size = this.size; if (wholeSlice(begin, end, size)) { return this; } return setListBounds( this, resolveBegin(begin, size), resolveEnd(end, size) ); }; List.prototype.__iterator = function __iterator (type, reverse) { var index = reverse ? this.size : 0; var values = iterateList(this, reverse); return new Iterator(function () { var value = values(); return value === DONE ? iteratorDone() : iteratorValue(type, reverse ? --index : index++, value); }); }; List.prototype.__iterate = function __iterate (fn, reverse) { var index = reverse ? this.size : 0; var values = iterateList(this, reverse); var value; while ((value = values()) !== DONE) { if (fn(value, reverse ? --index : index++, this) === false) { break; } } return index; }; List.prototype.__ensureOwner = function __ensureOwner (ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { if (this.size === 0) { return emptyList(); } this.__ownerID = ownerID; this.__altered = false; return this; } return makeList( this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash ); }; return List; }(IndexedCollection)); List.isList = isList; var ListPrototype = List.prototype; ListPrototype[IS_LIST_SYMBOL] = true; ListPrototype[DELETE] = ListPrototype.remove; ListPrototype.merge = ListPrototype.concat; ListPrototype.setIn = setIn$1; ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn; ListPrototype.update = update$1; ListPrototype.updateIn = updateIn$1; ListPrototype.mergeIn = mergeIn; ListPrototype.mergeDeepIn = mergeDeepIn; ListPrototype.withMutations = withMutations; ListPrototype.wasAltered = wasAltered; ListPrototype.asImmutable = asImmutable; ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable; ListPrototype['@@transducer/step'] = function(result, arr) { return result.push(arr); }; ListPrototype['@@transducer/result'] = function(obj) { return obj.asImmutable(); }; var VNode = function VNode(array, ownerID) { this.array = array; this.ownerID = ownerID; }; // TODO: seems like these methods are very similar VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) { if (index === level ? 1 << level : this.array.length === 0) { return this; } var originIndex = (index >>> level) & MASK; if (originIndex >= this.array.length) { return new VNode([], ownerID); } var removingFirst = originIndex === 0; var newChild; if (level > 0) { var oldChild = this.array[originIndex]; newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); if (newChild === oldChild && removingFirst) { return this; } } if (removingFirst && !newChild) { return this; } var editable = editableVNode(this, ownerID); if (!removingFirst) { for (var ii = 0; ii < originIndex; ii++) { editable.array[ii] = undefined; } } if (newChild) { editable.array[originIndex] = newChild; } return editable; }; VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) { if (index === (level ? 1 << level : 0) || this.array.length === 0) { return this; } var sizeIndex = ((index - 1) >>> level) & MASK; if (sizeIndex >= this.array.length) { return this; } var newChild; if (level > 0) { var oldChild = this.array[sizeIndex]; newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); if (newChild === oldChild && sizeIndex === this.array.length - 1) { return this; } } var editable = editableVNode(this, ownerID); editable.array.splice(sizeIndex + 1); if (newChild) { editable.array[sizeIndex] = newChild; } return editable; }; var DONE = {}; function iterateList(list, reverse) { var left = list._origin; var right = list._capacity; var tailPos = getTailOffset(right); var tail = list._tail; return iterateNodeOrLeaf(list._root, list._level, 0); function iterateNodeOrLeaf(node, level, offset) { return level === 0 ? iterateLeaf(node, offset) : iterateNode(node, level, offset); } function iterateLeaf(node, offset) { var array = offset === tailPos ? tail && tail.array : node && node.array; var from = offset > left ? 0 : left - offset; var to = right - offset; if (to > SIZE) { to = SIZE; } return function () { if (from === to) { return DONE; } var idx = reverse ? --to : from++; return array && array[idx]; }; } function iterateNode(node, level, offset) { var values; var array = node && node.array; var from = offset > left ? 0 : (left - offset) >> level; var to = ((right - offset) >> level) + 1; if (to > SIZE) { to = SIZE; } return function () { while (true) { if (values) { var value = values(); if (value !== DONE) { return value; } values = null; } if (from === to) { return DONE; } var idx = reverse ? --to : from++; values = iterateNodeOrLeaf( array && array[idx], level - SHIFT, offset + (idx << level) ); } }; } } function makeList(origin, capacity, level, root, tail, ownerID, hash) { var list = Object.create(ListPrototype); list.size = capacity - origin; list._origin = origin; list._capacity = capacity; list._level = level; list._root = root; list._tail = tail; list.__ownerID = ownerID; list.__hash = hash; list.__altered = false; return list; } var EMPTY_LIST; function emptyList() { return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); } function updateList(list, index, value) { index = wrapIndex(list, index); if (index !== index) { return list; } if (index >= list.size || index < 0) { return list.withMutations(function (list) { index < 0 ? setListBounds(list, index).set(0, value) : setListBounds(list, 0, index + 1).set(index, value); }); } index += list._origin; var newTail = list._tail; var newRoot = list._root; var didAlter = MakeRef(); if (index >= getTailOffset(list._capacity)) { newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); } else { newRoot = updateVNode( newRoot, list.__ownerID, list._level, index, value, didAlter ); } if (!didAlter.value) { return list; } if (list.__ownerID) { list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(list._origin, list._capacity, list._level, newRoot, newTail); } function updateVNode(node, ownerID, level, index, value, didAlter) { var idx = (index >>> level) & MASK; var nodeHas = node && idx < node.array.length; if (!nodeHas && value === undefined) { return node; } var newNode; if (level > 0) { var lowerNode = node && node.array[idx]; var newLowerNode = updateVNode( lowerNode, ownerID, level - SHIFT, index, value, didAlter ); if (newLowerNode === lowerNode) { return node; } newNode = editableVNode(node, ownerID); newNode.array[idx] = newLowerNode; return newNode; } if (nodeHas && node.array[idx] === value) { return node; } if (didAlter) { SetRef(didAlter); } newNode = editableVNode(node, ownerID); if (value === undefined && idx === newNode.array.length - 1) { newNode.array.pop(); } else { newNode.array[idx] = value; } return newNode; } function editableVNode(node, ownerID) { if (ownerID && node && ownerID === node.ownerID) { return node; } return new VNode(node ? node.array.slice() : [], ownerID); } function listNodeFor(list, rawIndex) { if (rawIndex >= getTailOffset(list._capacity)) { return list._tail; } if (rawIndex < 1 << (list._level + SHIFT)) { var node = list._root; var level = list._level; while (node && level > 0) { node = node.array[(rawIndex >>> level) & MASK]; level -= SHIFT; } return node; } } function setListBounds(list, begin, end) { // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin |= 0; } if (end !== undefined) { end |= 0; } var owner = list.__ownerID || new OwnerID(); var oldOrigin = list._origin; var oldCapacity = list._capacity; var newOrigin = oldOrigin + begin; var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; if (newOrigin === oldOrigin && newCapacity === oldCapacity) { return list; } // If it's going to end after it starts, it's empty. if (newOrigin >= newCapacity) { return list.clear(); } var newLevel = list._level; var newRoot = list._root; // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode( newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner ); newLevel += SHIFT; offsetShift += 1 << newLevel; } if (offsetShift) { newOrigin += offsetShift; oldOrigin += offsetShift; newCapacity += offsetShift; oldCapacity += offsetShift; } var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode( newRoot && newRoot.array.length ? [newRoot] : [], owner ); newLevel += SHIFT; } // Locate or create the new tail. var oldTail = list._tail; var newTail = newTailOffset < oldTailOffset ? listNodeFor(list, newCapacity - 1) : newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; // Merge Tail into tree. if ( oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length ) { newRoot = editableVNode(newRoot, owner); var node = newRoot; for (var level = newLevel; level > SHIFT; level -= SHIFT) { var idx = (oldTailOffset >>> level) & MASK; node = node.array[idx] = editableVNode(node.array[idx], owner); } node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } // If the size has been reduced, there's a chance the tail needs to be trimmed. if (newCapacity < oldCapacity) { newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } // If the new origin is within the tail, then we do not need a root. if (newOrigin >= newTailOffset) { newOrigin -= newTailOffset; newCapacity -= newTailOffset; newLevel = SHIFT; newRoot = null; newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); // Otherwise, if the root has been trimmed, garbage collect. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { offsetShift = 0; // Identify the new top root node of the subtree of the old root. while (newRoot) { var beginIndex = (newOrigin >>> newLevel) & MASK; if ((beginIndex !== newTailOffset >>> newLevel) & MASK) { break; } if (beginIndex) { offsetShift += (1 << newLevel) * beginIndex; } newLevel -= SHIFT; newRoot = newRoot.array[beginIndex]; } // Trim the new sides of the new root. if (newRoot && newOrigin > oldOrigin) { newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } if (newRoot && newTailOffset < oldTailOffset) { newRoot = newRoot.removeAfter( owner, newLevel, newTailOffset - offsetShift ); } if (offsetShift) { newOrigin -= offsetShift; newCapacity -= offsetShift; } } if (list.__ownerID) { list.size = newCapacity - newOrigin; list._origin = newOrigin; list._capacity = newCapacity; list._level = newLevel; list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); } function getTailOffset(size) { return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT; } var OrderedMap = /*@__PURE__*/(function (Map$$1) { function OrderedMap(value) { return value === null || value === undefined ? emptyOrderedMap() : isOrderedMap(value) ? value : emptyOrderedMap().withMutations(function (map) { var iter = KeyedCollection(value); assertNotInfinite(iter.size); iter.forEach(function (v, k) { return map.set(k, v); }); }); } if ( Map$$1 ) OrderedMap.__proto__ = Map$$1; OrderedMap.prototype = Object.create( Map$$1 && Map$$1.prototype ); OrderedMap.prototype.constructor = OrderedMap; OrderedMap.of = function of (/*...values*/) { return this(arguments); }; OrderedMap.prototype.toString = function toString () { return this.__toString('OrderedMap {', '}'); }; // @pragma Access OrderedMap.prototype.get = function get (k, notSetValue) { var index = this._map.get(k); return index !== undefined ? this._list.get(index)[1] : notSetValue; }; // @pragma Modification OrderedMap.prototype.clear = function clear () { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._map.clear(); this._list.clear(); return this; } return emptyOrderedMap(); }; OrderedMap.prototype.set = function set (k, v) { return updateOrderedMap(this, k, v); }; OrderedMap.prototype.remove = function remove (k) { return updateOrderedMap(this, k, NOT_SET); }; OrderedMap.prototype.wasAltered = function wasAltered () { return this._map.wasAltered() || this._list.wasAltered(); }; OrderedMap.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; return this._list.__iterate( function (entry) { return entry && fn(entry[1], entry[0], this$1); }, reverse ); }; OrderedMap.prototype.__iterator = function __iterator (type, reverse) { return this._list.fromEntrySeq().__iterator(type, reverse); }; OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); var newList = this._list.__ensureOwner(ownerID); if (!ownerID) { if (this.size === 0) { return emptyOrderedMap(); } this.__ownerID = ownerID; this._map = newMap; this._list = newList; return this; } return makeOrderedMap(newMap, newList, ownerID, this.__hash); }; return OrderedMap; }(Map)); OrderedMap.isOrderedMap = isOrderedMap; OrderedMap.prototype[IS_ORDERED_SYMBOL] = true; OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; function makeOrderedMap(map, list, ownerID, hash) { var omap = Object.create(OrderedMap.prototype); omap.size = map ? map.size : 0; omap._map = map; omap._list = list; omap.__ownerID = ownerID; omap.__hash = hash; return omap; } var EMPTY_ORDERED_MAP; function emptyOrderedMap() { return ( EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())) ); } function updateOrderedMap(omap, k, v) { var map = omap._map; var list = omap._list; var i = map.get(k); var has = i !== undefined; var newMap; var newList; if (v === NOT_SET) { // removed if (!has) { return omap; } if (list.size >= SIZE && list.size >= map.size * 2) { newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; }); newMap = newList .toKeyedSeq() .map(function (entry) { return entry[0]; }) .flip() .toMap(); if (omap.__ownerID) { newMap.__ownerID = newList.__ownerID = omap.__ownerID; } } else { newMap = map.remove(k); newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); } } else if (has) { if (v === list.get(i)[1]) { return omap; } newMap = map; newList = list.set(i, [k, v]); } else { newMap = map.set(k, list.size); newList = list.set(list.size, [k, v]); } if (omap.__ownerID) { omap.size = newMap.size; omap._map = newMap; omap._list = newList; omap.__hash = undefined; return omap; } return makeOrderedMap(newMap, newList); } var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@'; function isStack(maybeStack) { return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]); } var Stack = /*@__PURE__*/(function (IndexedCollection$$1) { function Stack(value) { return value === null || value === undefined ? emptyStack() : isStack(value) ? value : emptyStack().pushAll(value); } if ( IndexedCollection$$1 ) Stack.__proto__ = IndexedCollection$$1; Stack.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype ); Stack.prototype.constructor = Stack; Stack.of = function of (/*...values*/) { return this(arguments); }; Stack.prototype.toString = function toString () { return this.__toString('Stack [', ']'); }; // @pragma Access Stack.prototype.get = function get (index, notSetValue) { var head = this._head; index = wrapIndex(this, index); while (head && index--) { head = head.next; } return head ? head.value : notSetValue; }; Stack.prototype.peek = function peek () { return this._head && this._head.value; }; // @pragma Modification Stack.prototype.push = function push (/*...values*/) { var arguments$1 = arguments; if (arguments.length === 0) { return this; } var newSize = this.size + arguments.length; var head = this._head; for (var ii = arguments.length - 1; ii >= 0; ii--) { head = { value: arguments$1[ii], next: head, }; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pushAll = function pushAll (iter) { iter = IndexedCollection$$1(iter); if (iter.size === 0) { return this; } if (this.size === 0 && isStack(iter)) { return iter; } assertNotInfinite(iter.size); var newSize = this.size; var head = this._head; iter.__iterate(function (value) { newSize++; head = { value: value, next: head, }; }, /* reverse */ true); if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pop = function pop () { return this.slice(1); }; Stack.prototype.clear = function clear () { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._head = undefined; this.__hash = undefined; this.__altered = true; return this; } return emptyStack(); }; Stack.prototype.slice = function slice (begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } var resolvedBegin = resolveBegin(begin, this.size); var resolvedEnd = resolveEnd(end, this.size); if (resolvedEnd !== this.size) { // super.slice(begin, end); return IndexedCollection$$1.prototype.slice.call(this, begin, end); } var newSize = this.size - resolvedBegin; var head = this._head; while (resolvedBegin--) { head = head.next; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; // @pragma Mutability Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { if (this.size === 0) { return emptyStack(); } this.__ownerID = ownerID; this.__altered = false; return this; } return makeStack(this.size, this._head, ownerID, this.__hash); }; // @pragma Iteration Stack.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; if (reverse) { return new ArraySeq(this.toArray()).__iterate( function (v, k) { return fn(v, k, this$1); }, reverse ); } var iterations = 0; var node = this._head; while (node) { if (fn(node.value, iterations++, this) === false) { break; } node = node.next; } return iterations; }; Stack.prototype.__iterator = function __iterator (type, reverse) { if (reverse) { return new ArraySeq(this.toArray()).__iterator(type, reverse); } var iterations = 0; var node = this._head; return new Iterator(function () { if (node) { var value = node.value; node = node.next; return iteratorValue(type, iterations++, value); } return iteratorDone(); }); }; return Stack; }(IndexedCollection)); Stack.isStack = isStack; var StackPrototype = Stack.prototype; StackPrototype[IS_STACK_SYMBOL] = true; StackPrototype.shift = StackPrototype.pop; StackPrototype.unshift = StackPrototype.push; StackPrototype.unshiftAll = StackPrototype.pushAll; StackPrototype.withMutations = withMutations; StackPrototype.wasAltered = wasAltered; StackPrototype.asImmutable = asImmutable; StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable; StackPrototype['@@transducer/step'] = function(result, arr) { return result.unshift(arr); }; StackPrototype['@@transducer/result'] = function(obj) { return obj.asImmutable(); }; function makeStack(size, head, ownerID, hash) { var map = Object.create(StackPrototype); map.size = size; map._head = head; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_STACK; function emptyStack() { return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); } var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@'; function isSet(maybeSet) { return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]); } function isOrderedSet(maybeOrderedSet) { return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } function deepEqual(a, b) { if (a === b) { return true; } if ( !isCollection(b) || (a.size !== undefined && b.size !== undefined && a.size !== b.size) || (a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash) || isKeyed(a) !== isKeyed(b) || isIndexed(a) !== isIndexed(b) || isOrdered(a) !== isOrdered(b) ) { return false; } if (a.size === 0 && b.size === 0) { return true; } var notAssociative = !isAssociative(a); if (isOrdered(a)) { var entries = a.entries(); return ( b.every(function (v, k) { var entry = entries.next().value; return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); }) && entries.next().done ); } var flipped = false; if (a.size === undefined) { if (b.size === undefined) { if (typeof a.cacheResult === 'function') { a.cacheResult(); } } else { flipped = true; var _ = a; a = b; b = _; } } var allEqual = true; var bSize = b.__iterate(function (v, k) { if ( notAssociative ? !a.has(v) : flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v) ) { allEqual = false; return false; } }); return allEqual && a.size === bSize; } /** * Contributes additional methods to a constructor */ function mixin(ctor, methods) { var keyCopier = function (key) { ctor.prototype[key] = methods[key]; }; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor; } function toJS(value) { if (!value || typeof value !== 'object') { return value; } if (!isCollection(value)) { if (!isDataStructure(value)) { return value; } value = Seq(value); } if (isKeyed(value)) { var result$1 = {}; value.__iterate(function (v, k) { result$1[k] = toJS(v); }); return result$1; } var result = []; value.__iterate(function (v) { result.push(toJS(v)); }); return result; } var Set = /*@__PURE__*/(function (SetCollection$$1) { function Set(value) { return value === null || value === undefined ? emptySet() : isSet(value) && !isOrdered(value) ? value : emptySet().withMutations(function (set) { var iter = SetCollection$$1(value); assertNotInfinite(iter.size); iter.forEach(function (v) { return set.add(v); }); }); } if ( SetCollection$$1 ) Set.__proto__ = SetCollection$$1; Set.prototype = Object.create( SetCollection$$1 && SetCollection$$1.prototype ); Set.prototype.constructor = Set; Set.of = function of (/*...values*/) { return this(arguments); }; Set.fromKeys = function fromKeys (value) { return this(KeyedCollection(value).keySeq()); }; Set.intersect = function intersect (sets) { sets = Collection(sets).toArray(); return sets.length ? SetPrototype.intersect.apply(Set(sets.pop()), sets) : emptySet(); }; Set.union = function union (sets) { sets = Collection(sets).toArray(); return sets.length ? SetPrototype.union.apply(Set(sets.pop()), sets) : emptySet(); }; Set.prototype.toString = function toString () { return this.__toString('Set {', '}'); }; // @pragma Access Set.prototype.has = function has (value) { return this._map.has(value); }; // @pragma Modification Set.prototype.add = function add (value) { return updateSet(this, this._map.set(value, value)); }; Set.prototype.remove = function remove (value) { return updateSet(this, this._map.remove(value)); }; Set.prototype.clear = function clear () { return updateSet(this, this._map.clear()); }; // @pragma Composition Set.prototype.map = function map (mapper, context) { var this$1 = this; var removes = []; var adds = []; this.forEach(function (value) { var mapped = mapper.call(context, value, value, this$1); if (mapped !== value) { removes.push(value); adds.push(mapped); } }); return this.withMutations(function (set) { removes.forEach(function (value) { return set.remove(value); }); adds.forEach(function (value) { return set.add(value); }); }); }; Set.prototype.union = function union () { var iters = [], len = arguments.length; while ( len-- ) iters[ len ] = arguments[ len ]; iters = iters.filter(function (x) { return x.size !== 0; }); if (iters.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && iters.length === 1) { return this.constructor(iters[0]); } return this.withMutations(function (set) { for (var ii = 0; ii < iters.length; ii++) { SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); }); } }); }; Set.prototype.intersect = function intersect () { var iters = [], len = arguments.length; while ( len-- ) iters[ len ] = arguments[ len ]; if (iters.length === 0) { return this; } iters = iters.map(function (iter) { return SetCollection$$1(iter); }); var toRemove = []; this.forEach(function (value) { if (!iters.every(function (iter) { return iter.includes(value); })) { toRemove.push(value); } }); return this.withMutations(function (set) { toRemove.forEach(function (value) { set.remove(value); }); }); }; Set.prototype.subtract = function subtract () { var iters = [], len = arguments.length; while ( len-- ) iters[ len ] = arguments[ len ]; if (iters.length === 0) { return this; } iters = iters.map(function (iter) { return SetCollection$$1(iter); }); var toRemove = []; this.forEach(function (value) { if (iters.some(function (iter) { return iter.includes(value); })) { toRemove.push(value); } }); return this.withMutations(function (set) { toRemove.forEach(function (value) { set.remove(value); }); }); }; Set.prototype.sort = function sort (comparator) { // Late binding return OrderedSet(sortFactory(this, comparator)); }; Set.prototype.sortBy = function sortBy (mapper, comparator) { // Late binding return OrderedSet(sortFactory(this, comparator, mapper)); }; Set.prototype.wasAltered = function wasAltered () { return this._map.wasAltered(); }; Set.prototype.__iterate = function __iterate (fn, reverse) { var this$1 = this; return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse); }; Set.prototype.__iterator = function __iterator (type, reverse) { return this._map.__iterator(type, reverse); }; Set.prototype.__ensureOwner = function __ensureOwner (ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); if (!ownerID) { if (this.size === 0) { return this.__empty(); } this.__ownerID = ownerID; this._map = newMap; return this; } return this.__make(newMap, ownerID); }; return Set; }(SetCollection)); Set.isSet = isSet; var SetPrototype = Set.prototype; SetPrototype[IS_SET_SYMBOL] = true; SetPrototype[DELETE] = SetPrototype.remove; SetPrototype.merge = SetPrototype.concat = SetPrototype.union; SetPrototype.withMutations = withMutations; SetPrototype.asImmutable = asImmutable; SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable; SetPrototype['@@transducer/step'] = function(result, arr) { return result.add(arr); }; SetPrototype['@@transducer/result'] = function(obj) { return obj.asImmutable(); }; SetPrototype.__empty = emptySet; SetPrototype.__make = makeSet; function updateSet(set, newMap) { if (set.__ownerID) { set.size = newMap.size; set._map = newMap; return set; } return newMap === set._map ? set : newMap.size === 0 ? set.__empty() : set.__make(newMap); } function makeSet(map, ownerID) { var set = Object.create(SetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_SET; function emptySet() { return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); } /** * Returns a lazy seq of nums from start (inclusive) to end * (exclusive), by step, where start defaults to 0, step to 1, and end to * infinity. When start is equal to end, returns empty list. */ var Range = /*@__PURE__*/(function (IndexedSeq$$1) { function Range(start, end, step) { if (!(this instanceof Range)) { return new Range(start, end, step); } invariant(step !== 0, 'Cannot step a Range by 0'); start = start || 0; if (end === undefined) { end = Infinity; } step = step === undefined ? 1 : Math.abs(step); if (end < start) { step = -step; } this._start = start; this._end = end; this._step = step; this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); if (this.size === 0) { if (EMPTY_RANGE) { return EMPTY_RANGE; } EMPTY_RANGE = this; } } if ( IndexedSeq$$1 ) Range.__proto__ = IndexedSeq$$1; Range.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype ); Range.prototype.constructor = Range; Range.prototype.toString = function toString () { if (this.size === 0) { return 'Range []'; } return ( 'Range [ ' + this._start + '...' + this._end + (this._step !== 1 ? ' by ' + this._step : '') + ' ]' ); }; Range.prototype.get = function get (index, notSetValue) { return this.has(index) ? this._start + wrapIndex(this, index) * this._step : notSetValue; }; Range.prototype.includes = function includes (searchValue) { var possibleIndex = (searchValue - this._start) / this._step; return ( possibleIndex >= 0 && possibleIndex < this.size && possibleIndex === Math.floor(possibleIndex) ); }; Range.prototype.slice = function slice (begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } begin = resolveBegin(begin, this.size); end = resolveEnd(end, this.size); if (end <= begin) { return new Range(0, 0); } return new Range( this.get(begin, this._end), this.get(end, this._end), this._step ); }; Range.prototype.indexOf = function indexOf (searchValue) { var offsetValue = searchValue - this._start; if (offsetValue % this._step === 0) { var index = offsetValue / this._step; if (index >= 0 && index < this.size) { return index; } } return -1; }; Range.prototype.lastIndexOf = function lastIndexOf (searchValue) { return this.indexOf(searchValue); }; Range.prototype.__iterate = function __iterate (fn, reverse) { var size = this.size; var step = this._step; var value = reverse ? this._start + (size - 1) * step : this._start; var i = 0; while (i !== size) { if (fn(value, reverse ? size - ++i : i++, this) === false) { break; } value += reverse ? -step : step; } return i; }; Range.prototype.__iterator = function __iterator (type, reverse) { var size = this.size; var step = this._step; var value = reverse ? this._start + (size - 1) * step : this._start; var i = 0; return new Iterator(function () { if (i === size) { return iteratorDone(); } var v = value; value += reverse ? -step : step; return iteratorValue(type, reverse ? size - ++i : i++, v); }); }; Range.prototype.equals = function equals (other) { return other instanceof Range ? this._start === other._start && this._end === other._end && this._step === other._step : deepEqual(this, other); }; return Range; }(IndexedSeq)); var EMPTY_RANGE; function getIn(collection, searchKeyPath, notSetValue) { var keyPath = coerceKeyPath(searchKeyPath); var i = 0; while (i !== keyPath.length) { collection = get(collection, keyPath[i++], NOT_SET); if (collection === NOT_SET) { return notSetValue; } } return collection; } function getIn$1(searchKeyPath, notSetValue) { return getIn(this, searchKeyPath, notSetValue); } function hasIn(collection, keyPath) { return getIn(collection, keyPath, NOT_SET) !== NOT_SET; } function hasIn$1(searchKeyPath) { return hasIn(this, searchKeyPath); } function toObject() { assertNotInfinite(this.size); var object = {}; this.__iterate(function (v, k) { object[k] = v; }); return object; } // Note: all of these methods are deprecated. Collection.isIterable = isCollection; Collection.isKeyed = isKeyed; Collection.isIndexed = isIndexed; Collection.isAssociative = isAssociative; Collection.isOrdered = isOrdered; Collection.Iterator = Iterator; mixin(Collection, { // ### Conversion to other types toArray: function toArray() { assertNotInfinite(this.size); var array = new Array(this.size || 0); var useTuples = isKeyed(this); var i = 0; this.__iterate(function (v, k) { // Keyed collections produce an array of tuples. array[i++] = useTuples ? [k, v] : v; }); return array; }, toIndexedSeq: function toIndexedSeq() { return new ToIndexedSequence(this); }, toJS: function toJS$1() { return toJS(this); }, toKeyedSeq: function toKeyedSeq() { return new ToKeyedSequence(this, true); }, toMap: function toMap() { // Use Late Binding here to solve the circular dependency. return Map(this.toKeyedSeq()); }, toObject: toObject, toOrderedMap: function toOrderedMap() { // Use Late Binding here to solve the circular dependency. return OrderedMap(this.toKeyedSeq()); }, toOrderedSet: function toOrderedSet() { // Use Late Binding here to solve the circular dependency. return OrderedSet(isKeyed(this) ? this.valueSeq() : this); }, toSet: function toSet() { // Use Late Binding here to solve the circular dependency. return Set(isKeyed(this) ? this.valueSeq() : this); }, toSetSeq: function toSetSeq() { return new ToSetSequence(this); }, toSeq: function toSeq() { return isIndexed(this) ? this.toIndexedSeq() : isKeyed(this) ? this.toKeyedSeq() : this.toSetSeq(); }, toStack: function toStack() { // Use Late Binding here to solve the circular dependency. return Stack(isKeyed(this) ? this.valueSeq() : this); }, toList: function toList() { // Use Late Binding here to solve the circular dependency. return List(isKeyed(this) ? this.valueSeq() : this); }, // ### Common JavaScript methods and properties toString: function toString() { return '[Collection]'; }, __toString: function __toString(head, tail) { if (this.size === 0) { return head + tail; } return ( head + ' ' + this.toSeq() .map(this.__toStringMapper) .join(', ') + ' ' + tail ); }, // ### ES6 Collection methods (ES6 Array and Map) concat: function concat() { var values = [], len = arguments.length; while ( len-- ) values[ len ] = arguments[ len ]; return reify(this, concatFactory(this, values)); }, includes: function includes(searchValue) { return this.some(function (value) { return is(value, searchValue); }); }, entries: function entries() { return this.__iterator(ITERATE_ENTRIES); }, every: function every(predicate, context) { assertNotInfinite(this.size); var returnValue = true; this.__iterate(function (v, k, c) { if (!predicate.call(context, v, k, c)) { returnValue = false; return false; } }); return returnValue; }, filter: function filter(predicate, context) { return reify(this, filterFactory(this, predicate, context, true)); }, find: function find(predicate, context, notSetValue) { var entry = this.findEntry(predicate, context); return entry ? entry[1] : notSetValue; }, forEach: function forEach(sideEffect, context) { assertNotInfinite(this.size); return this.__iterate(context ? sideEffect.bind(context) : sideEffect); }, join: function join(separator) { assertNotInfinite(this.size); separator = separator !== undefined ? '' + separator : ','; var joined = ''; var isFirst = true; this.__iterate(function (v) { isFirst ? (isFirst = false) : (joined += separator); joined += v !== null && v !== undefined ? v.toString() : ''; }); return joined; }, keys: function keys() { return this.__iterator(ITERATE_KEYS); }, map: function map(mapper, context) { return reify(this, mapFactory(this, mapper, context)); }, reduce: function reduce$1(reducer, initialReduction, context) { return reduce( this, reducer, initialReduction, context, arguments.length < 2, false ); }, reduceRight: function reduceRight(reducer, initialReduction, context) { return reduce( this, reducer, initialReduction, context, arguments.length < 2, true ); }, reverse: function reverse() { return reify(this, reverseFactory(this, true)); }, slice: function slice(begin, end) { return reify(this, sliceFactory(this, begin, end, true)); }, some: function some(predicate, context) { return !this.every(not(predicate), context); }, sort: function sort(comparator) { return reify(this, sortFactory(this, comparator)); }, values: function values() { return this.__iterator(ITERATE_VALUES); }, // ### More sequential methods butLast: function butLast() { return this.slice(0, -1); }, isEmpty: function isEmpty() { return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; }); }, count: function count(predicate, context) { return ensureSize( predicate ? this.toSeq().filter(predicate, context) : this ); }, countBy: function countBy(grouper, context) { return countByFactory(this, grouper, context); }, equals: function equals(other) { return deepEqual(this, other); }, entrySeq: function entrySeq() { var collection = this; if (collection._cache) { // We cache as an entries array, so we can just return the cache! return new ArraySeq(collection._cache); } var entriesSequence = collection .toSeq() .map(entryMapper) .toIndexedSeq(); entriesSequence.fromEntrySeq = function () { return collection.toSeq(); }; return entriesSequence; }, filterNot: function filterNot(predicate, context) { return this.filter(not(predicate), context); }, findEntry: function findEntry(predicate, context, notSetValue) { var found = notSetValue; this.__iterate(function (v, k, c) { if (predicate.call(context, v, k, c)) { found = [k, v]; return false; } }); return found; }, findKey: function findKey(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLast: function findLast(predicate, context, notSetValue) { return this.toKeyedSeq() .reverse() .find(predicate, context, notSetValue); }, findLastEntry: function findLastEntry(predicate, context, notSetValue) { return this.toKeyedSeq() .reverse() .findEntry(predicate, context, notSetValue); }, findLastKey: function findLastKey(predicate, context) { return this.toKeyedSeq() .reverse() .findKey(predicate, context); }, first: function first(notSetValue) { return this.find(returnTrue, null, notSetValue); }, flatMap: function flatMap(mapper, context) { return reify(this, flatMapFactory(this, mapper, context)); }, flatten: function flatten(depth) { return reify(this, flattenFactory(this, depth, true)); }, fromEntrySeq: function fromEntrySeq() { return new FromEntriesSequence(this); }, get: function get(searchKey, notSetValue) { return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue); }, getIn: getIn$1, groupBy: function groupBy(grouper, context) { return groupByFactory(this, grouper, context); }, has: function has(searchKey) { return this.get(searchKey, NOT_SET) !== NOT_SET; }, hasIn: hasIn$1, isSubset: function isSubset(iter) { iter = typeof iter.includes === 'function' ? iter : Collection(iter); return this.every(function (value) { return iter.includes(value); }); }, isSuperset: function isSuperset(iter) { iter = typeof iter.isSubset === 'function' ? iter : Collection(iter); return iter.isSubset(this); }, keyOf: function keyOf(searchValue) { return this.findKey(function (value) { return is(value, searchValue); }); }, keySeq: function keySeq() { return this.toSeq() .map(keyMapper) .toIndexedSeq(); }, last: function last(notSetValue) { return this.toSeq() .reverse() .first(notSetValue); }, lastKeyOf: function lastKeyOf(searchValue) { return this.toKeyedSeq() .reverse() .keyOf(searchValue); }, max: function max(comparator) { return maxFactory(this, comparator); }, maxBy: function maxBy(mapper, comparator) { return maxFactory(this, comparator, mapper); }, min: function min(comparator) { return maxFactory( this, comparator ? neg(comparator) : defaultNegComparator ); }, minBy: function minBy(mapper, comparator) { return maxFactory( this, comparator ? neg(comparator) : defaultNegComparator, mapper ); }, rest: function rest() { return this.slice(1); }, skip: function skip(amount) { return amount === 0 ? this : this.slice(Math.max(0, amount)); }, skipLast: function skipLast(amount) { return amount === 0 ? this : this.slice(0, -Math.max(0, amount)); }, skipWhile: function skipWhile(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, true)); }, skipUntil: function skipUntil(predicate, context) { return this.skipWhile(not(predicate), context); }, sortBy: function sortBy(mapper, comparator) { return reify(this, sortFactory(this, comparator, mapper)); }, take: function take(amount) { return this.slice(0, Math.max(0, amount)); }, takeLast: function takeLast(amount) { return this.slice(-Math.max(0, amount)); }, takeWhile: function takeWhile(predicate, context) { return reify(this, takeWhileFactory(this, predicate, context)); }, takeUntil: function takeUntil(predicate, context) { return this.takeWhile(not(predicate), context); }, update: function update(fn) { return fn(this); }, valueSeq: function valueSeq() { return this.toIndexedSeq(); }, // ### Hashable Object hashCode: function hashCode() { return this.__hash || (this.__hash = hashCollection(this)); }, // ### Internal // abstract __iterate(fn, reverse) // abstract __iterator(type, reverse) }); var CollectionPrototype = Collection.prototype; CollectionPrototype[IS_COLLECTION_SYMBOL] = true; CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values; CollectionPrototype.toJSON = CollectionPrototype.toArray; CollectionPrototype.__toStringMapper = quoteString; CollectionPrototype.inspect = CollectionPrototype.toSource = function() { return this.toString(); }; CollectionPrototype.chain = CollectionPrototype.flatMap; CollectionPrototype.contains = CollectionPrototype.includes; mixin(KeyedCollection, { // ### More sequential methods flip: function flip() { return reify(this, flipFactory(this)); }, mapEntries: function mapEntries(mapper, context) { var this$1 = this; var iterations = 0; return reify( this, this.toSeq() .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); }) .fromEntrySeq() ); }, mapKeys: function mapKeys(mapper, context) { var this$1 = this; return reify( this, this.toSeq() .flip() .map(function (k, v) { return mapper.call(context, k, v, this$1); }) .flip() ); }, }); var KeyedCollectionPrototype = KeyedCollection.prototype; KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true; KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries; KeyedCollectionPrototype.toJSON = toObject; KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); }; mixin(IndexedCollection, { // ### Conversion to other types toKeyedSeq: function toKeyedSeq() { return new ToKeyedSequence(this, false); }, // ### ES6 Collection methods (ES6 Array and Map) filter: function filter(predicate, context) { return reify(this, filterFactory(this, predicate, context, false)); }, findIndex: function findIndex(predicate, context) { var entry = this.findEntry(predicate, context); return entry ? entry[0] : -1; }, indexOf: function indexOf(searchValue) { var key = this.keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function lastIndexOf(searchValue) { var key = this.lastKeyOf(searchValue); return key === undefined ? -1 : key; }, reverse: function reverse() { return reify(this, reverseFactory(this, false)); }, slice: function slice(begin, end) { return reify(this, sliceFactory(this, begin, end, false)); }, splice: function splice(index, removeNum /*, ...values*/) { var numArgs = arguments.length; removeNum = Math.max(removeNum || 0, 0); if (numArgs === 0 || (numArgs === 2 && !removeNum)) { return this; } // If index is negative, it should resolve relative to the size of the // collection. However size may be expensive to compute if not cached, so // only call count() if the number is in fact negative. index = resolveBegin(index, index < 0 ? this.count() : this.size); var spliced = this.slice(0, index); return reify( this, numArgs === 1 ? spliced : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) ); }, // ### More collection methods findLastIndex: function findLastIndex(predicate, context) { var entry = this.findLastEntry(predicate, context); return entry ? entry[0] : -1; }, first: function first(notSetValue) { return this.get(0, notSetValue); }, flatten: function flatten(depth) { return reify(this, flattenFactory(this, depth, false)); }, get: function get(index, notSetValue) { index = wrapIndex(this, index); return index < 0 || (this.size === Infinity || (this.size !== undefined && index > this.size)) ? notSetValue : this.find(function (_, key) { return key === index; }, undefined, notSetValue); }, has: function has(index) { index = wrapIndex(this, index); return ( index >= 0 && (this.size !== undefined ? this.size === Infinity || index < this.size : this.indexOf(index) !== -1) ); }, interpose: function interpose(separator) { return reify(this, interposeFactory(this, separator)); }, interleave: function interleave(/*...collections*/) { var collections = [this].concat(arrCopy(arguments)); var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections); var interleaved = zipped.flatten(true); if (zipped.size) { interleaved.size = zipped.size * collections.length; } return reify(this, interleaved); }, keySeq: function keySeq() { return Range(0, this.size); }, last: function last(notSetValue) { return this.get(-1, notSetValue); }, skipWhile: function skipWhile(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, false)); }, zip: function zip(/*, ...collections */) { var collections = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, collections)); }, zipAll: function zipAll(/*, ...collections */) { var collections = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, collections, true)); }, zipWith: function zipWith(zipper /*, ...collections */) { var collections = arrCopy(arguments); collections[0] = this; return reify(this, zipWithFactory(this, zipper, collections)); }, }); var IndexedCollectionPrototype = IndexedCollection.prototype; IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true; IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true; mixin(SetCollection, { // ### ES6 Collection methods (ES6 Array and Map) get: function get(value, notSetValue) { return this.has(value) ? value : notSetValue; }, includes: function includes(value) { return this.has(value); }, // ### More sequential methods keySeq: function keySeq() { return this.valueSeq(); }, }); SetCollection.prototype.has = CollectionPrototype.includes; SetCollection.prototype.contains = SetCollection.prototype.includes; // Mixin subclasses mixin(KeyedSeq, KeyedCollection.prototype); mixin(IndexedSeq, IndexedCollection.prototype); mixin(SetSeq, SetCollection.prototype); // #pragma Helper functions function reduce(collection, reducer, reduction, context, useFirst, reverse) { assertNotInfinite(collection.size); collection.__iterate(function (v, k, c) { if (useFirst) { useFirst = false; reduction = v; } else { reduction = reducer.call(context, reduction, v, k, c); } }, reverse); return reduction; } function keyMapper(v, k) { return k; } function entryMapper(v, k) { return [k, v]; } function not(predicate) { return function() { return !predicate.apply(this, arguments); }; } function neg(predicate) { return function() { return -predicate.apply(this, arguments); }; } function defaultZipper() { return arrCopy(arguments); } function defaultNegComparator(a, b) { return a < b ? 1 : a > b ? -1 : 0; } function hashCollection(collection) { if (collection.size === Infinity) { return 0; } var ordered = isOrdered(collection); var keyed = isKeyed(collection); var h = ordered ? 1 : 0; var size = collection.__iterate( keyed ? ordered ? function (v, k) { h = (31 * h + hashMerge(hash(v), hash(k))) | 0; } : function (v, k) { h = (h + hashMerge(hash(v), hash(k))) | 0; } : ordered ? function (v) { h = (31 * h + hash(v)) | 0; } : function (v) { h = (h + hash(v)) | 0; } ); return murmurHashOfSize(size, h); } function murmurHashOfSize(size, h) { h = imul(h, 0xcc9e2d51); h = imul((h << 15) | (h >>> -15), 0x1b873593); h = imul((h << 13) | (h >>> -13), 5); h = ((h + 0xe6546b64) | 0) ^ size; h = imul(h ^ (h >>> 16), 0x85ebca6b); h = imul(h ^ (h >>> 13), 0xc2b2ae35); h = smi(h ^ (h >>> 16)); return h; } function hashMerge(a, b) { return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int } var OrderedSet = /*@__PURE__*/(function (Set$$1) { function OrderedSet(value) { return value === null || value === undefined ? emptyOrderedSet() : isOrderedSet(value) ? value : emptyOrderedSet().withMutations(function (set) { var iter = SetCollection(value); assertNotInfinite(iter.size); iter.forEach(function (v) { return set.add(v); }); }); } if ( Set$$1 ) OrderedSet.__proto__ = Set$$1; OrderedSet.prototype = Object.create( Set$$1 && Set$$1.prototype ); OrderedSet.prototype.constructor = OrderedSet; OrderedSet.of = function of (/*...values*/) { return this(arguments); }; OrderedSet.fromKeys = function fromKeys (value) { return this(KeyedCollection(value).keySeq()); }; OrderedSet.prototype.toString = function toString () { return this.__toString('OrderedSet {', '}'); }; return OrderedSet; }(Set)); OrderedSet.isOrderedSet = isOrderedSet; var OrderedSetPrototype = OrderedSet.prototype; OrderedSetPrototype[IS_ORDERED_SYMBOL] = true; OrderedSetPrototype.zip = IndexedCollectionPrototype.zip; OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith; OrderedSetPrototype.__empty = emptyOrderedSet; OrderedSetPrototype.__make = makeOrderedSet; function makeOrderedSet(map, ownerID) { var set = Object.create(OrderedSetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_ORDERED_SET; function emptyOrderedSet() { return ( EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())) ); } var Record = function Record(defaultValues, name) { var hasInitialized; var RecordType = function Record(values) { var this$1 = this; if (values instanceof RecordType) { return values; } if (!(this instanceof RecordType)) { return new RecordType(values); } if (!hasInitialized) { hasInitialized = true; var keys = Object.keys(defaultValues); var indices = (RecordTypePrototype._indices = {}); // Deprecated: left to attempt not to break any external code which // relies on a ._name property existing on record instances. // Use Record.getDescriptiveName() instead RecordTypePrototype._name = name; RecordTypePrototype._keys = keys; RecordTypePrototype._defaultValues = defaultValues; for (var i = 0; i < keys.length; i++) { var propName = keys[i]; indices[propName] = i; if (RecordTypePrototype[propName]) { /* eslint-disable no-console */ typeof console === 'object' && console.warn && console.warn( 'Cannot define ' + recordName(this) + ' with property "' + propName + '" since that property name is part of the Record API.' ); /* eslint-enable no-console */ } else { setProp(RecordTypePrototype, propName); } } } this.__ownerID = undefined; this._values = List().withMutations(function (l) { l.setSize(this$1._keys.length); KeyedCollection(values).forEach(function (v, k) { l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v); }); }); }; var RecordTypePrototype = (RecordType.prototype = Object.create( RecordPrototype )); RecordTypePrototype.constructor = RecordType; if (name) { RecordType.displayName = name; } return RecordType; }; Record.prototype.toString = function toString () { var str = recordName(this) + ' { '; var keys = this._keys; var k; for (var i = 0, l = keys.length; i !== l; i++) { k = keys[i]; str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k)); } return str + ' }'; }; Record.prototype.equals = function equals (other) { return ( this === other || (other && this._keys === other._keys && recordSeq(this).equals(recordSeq(other))) ); }; Record.prototype.hashCode = function hashCode () { return recordSeq(this).hashCode(); }; // @pragma Access Record.prototype.has = function has (k) { return this._indices.hasOwnProperty(k); }; Record.prototype.get = function get (k, notSetValue) { if (!this.has(k)) { return notSetValue; } var index = this._indices[k]; var value = this._values.get(index); return value === undefined ? this._defaultValues[k] : value; }; // @pragma Modification Record.prototype.set = function set (k, v) { if (this.has(k)) { var newValues = this._values.set( this._indices[k], v === this._defaultValues[k] ? undefined : v ); if (newValues !== this._values && !this.__ownerID) { return makeRecord(this, newValues); } } return this; }; Record.prototype.remove = function remove (k) { return this.set(k); }; Record.prototype.clear = function clear () { var newValues = this._values.clear().setSize(this._keys.length); return this.__ownerID ? this : makeRecord(this, newValues); }; Record.prototype.wasAltered = function wasAltered () { return this._values.wasAltered(); }; Record.prototype.toSeq = function toSeq () { return recordSeq(this); }; Record.prototype.toJS = function toJS$1 () { return toJS(this); }; Record.prototype.entries = function entries () { return this.__iterator(ITERATE_ENTRIES); }; Record.prototype.__iterator = function __iterator (type, reverse) { return recordSeq(this).__iterator(type, reverse); }; Record.prototype.__iterate = function __iterate (fn, reverse) { return recordSeq(this).__iterate(fn, reverse); }; Record.prototype.__ensureOwner = function __ensureOwner (ownerID) { if (ownerID === this.__ownerID) { return this; } var newValues = this._values.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._values = newValues; return this; } return makeRecord(this, newValues, ownerID); }; Record.isRecord = isRecord; Record.getDescriptiveName = recordName; var RecordPrototype = Record.prototype; RecordPrototype[IS_RECORD_SYMBOL] = true; RecordPrototype[DELETE] = RecordPrototype.remove; RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn; RecordPrototype.getIn = getIn$1; RecordPrototype.hasIn = CollectionPrototype.hasIn; RecordPrototype.merge = merge; RecordPrototype.mergeWith = mergeWith; RecordPrototype.mergeIn = mergeIn; RecordPrototype.mergeDeep = mergeDeep$1; RecordPrototype.mergeDeepWith = mergeDeepWith$1; RecordPrototype.mergeDeepIn = mergeDeepIn; RecordPrototype.setIn = setIn$1; RecordPrototype.update = update$1; RecordPrototype.updateIn = updateIn$1; RecordPrototype.withMutations = withMutations; RecordPrototype.asMutable = asMutable; RecordPrototype.asImmutable = asImmutable; RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries; RecordPrototype.toJSON = RecordPrototype.toObject = CollectionPrototype.toObject; RecordPrototype.inspect = RecordPrototype.toSource = function() { return this.toString(); }; function makeRecord(likeRecord, values, ownerID) { var record = Object.create(Object.getPrototypeOf(likeRecord)); record._values = values; record.__ownerID = ownerID; return record; } function recordName(record) { return record.constructor.displayName || record.constructor.name || 'Record'; } function recordSeq(record) { return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; })); } function setProp(prototype, name) { try { Object.defineProperty(prototype, name, { get: function() { return this.get(name); }, set: function(value) { invariant(this.__ownerID, 'Cannot set on an immutable record.'); this.set(name, value); }, }); } catch (error) { // Object.defineProperty failed. Probably IE8. } } /** * Returns a lazy Seq of `value` repeated `times` times. When `times` is * undefined, returns an infinite sequence of `value`. */ var Repeat = /*@__PURE__*/(function (IndexedSeq$$1) { function Repeat(value, times) { if (!(this instanceof Repeat)) { return new Repeat(value, times); } this._value = value; this.size = times === undefined ? Infinity : Math.max(0, times); if (this.size === 0) { if (EMPTY_REPEAT) { return EMPTY_REPEAT; } EMPTY_REPEAT = this; } } if ( IndexedSeq$$1 ) Repeat.__proto__ = IndexedSeq$$1; Repeat.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype ); Repeat.prototype.constructor = Repeat; Repeat.prototype.toString = function toString () { if (this.size === 0) { return 'Repeat []'; } return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; }; Repeat.prototype.get = function get (index, notSetValue) { return this.has(index) ? this._value : notSetValue; }; Repeat.prototype.includes = function includes (searchValue) { return is(this._value, searchValue); }; Repeat.prototype.slice = function slice (begin, end) { var size = this.size; return wholeSlice(begin, end, size) ? this : new Repeat( this._value, resolveEnd(end, size) - resolveBegin(begin, size) ); }; Repeat.prototype.reverse = function reverse () { return this; }; Repeat.prototype.indexOf = function indexOf (searchValue) { if (is(this._value, searchValue)) { return 0; } return -1; }; Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) { if (is(this._value, searchValue)) { return this.size; } return -1; }; Repeat.prototype.__iterate = function __iterate (fn, reverse) { var size = this.size; var i = 0; while (i !== size) { if (fn(this._value, reverse ? size - ++i : i++, this) === false) { break; } } return i; }; Repeat.prototype.__iterator = function __iterator (type, reverse) { var this$1 = this; var size = this.size; var i = 0; return new Iterator( function () { return i === size ? iteratorDone() : iteratorValue(type, reverse ? size - ++i : i++, this$1._value); } ); }; Repeat.prototype.equals = function equals (other) { return other instanceof Repeat ? is(this._value, other._value) : deepEqual(other); }; return Repeat; }(IndexedSeq)); var EMPTY_REPEAT; function fromJS(value, converter) { return fromJSWith( [], converter || defaultConverter, value, '', converter && converter.length > 2 ? [] : undefined, { '': value } ); } function fromJSWith(stack, converter, value, key, keyPath, parentValue) { var toSeq = Array.isArray(value) ? IndexedSeq : isPlainObj(value) ? KeyedSeq : null; if (toSeq) { if (~stack.indexOf(value)) { throw new TypeError('Cannot convert circular structure to Immutable'); } stack.push(value); keyPath && key !== '' && keyPath.push(key); var converted = converter.call( parentValue, key, toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); } ), keyPath && keyPath.slice() ); stack.pop(); keyPath && keyPath.pop(); return converted; } return value; } function defaultConverter(k, v) { return isKeyed(v) ? v.toMap() : v.toList(); } var version = "4.0.0-rc.11"; var Immutable = { version: version, Collection: Collection, // Note: Iterable is deprecated Iterable: Collection, Seq: Seq, Map: Map, OrderedMap: OrderedMap, List: List, Stack: Stack, Set: Set, OrderedSet: OrderedSet, Record: Record, Range: Range, Repeat: Repeat, is: is, fromJS: fromJS, hash: hash, isImmutable: isImmutable, isCollection: isCollection, isKeyed: isKeyed, isIndexed: isIndexed, isAssociative: isAssociative, isOrdered: isOrdered, isValueObject: isValueObject, isSeq: isSeq, isList: isList, isMap: isMap, isOrderedMap: isOrderedMap, isStack: isStack, isSet: isSet, isOrderedSet: isOrderedSet, isRecord: isRecord, get: get, getIn: getIn, has: has, hasIn: hasIn, merge: merge$1, mergeDeep: mergeDeep, mergeWith: mergeWith$1, mergeDeepWith: mergeDeepWith, remove: remove, removeIn: removeIn, set: set, setIn: setIn, update: update, updateIn: updateIn, }; // Note: Iterable is deprecated var Iterable = Collection; exports.default = Immutable; exports.version = version; exports.Collection = Collection; exports.Iterable = Iterable; exports.Seq = Seq; exports.Map = Map; exports.OrderedMap = OrderedMap; exports.List = List; exports.Stack = Stack; exports.Set = Set; exports.OrderedSet = OrderedSet; exports.Record = Record; exports.Range = Range; exports.Repeat = Repeat; exports.is = is; exports.fromJS = fromJS; exports.hash = hash; exports.isImmutable = isImmutable; exports.isCollection = isCollection; exports.isKeyed = isKeyed; exports.isIndexed = isIndexed; exports.isAssociative = isAssociative; exports.isOrdered = isOrdered; exports.isValueObject = isValueObject; exports.get = get; exports.getIn = getIn; exports.has = has; exports.hasIn = hasIn; exports.merge = merge$1; exports.mergeDeep = mergeDeep; exports.mergeWith = mergeWith$1; exports.mergeDeepWith = mergeDeepWith; exports.remove = remove; exports.removeIn = removeIn; exports.set = set; exports.setIn = setIn; exports.update = update; exports.updateIn = updateIn; Object.defineProperty(exports, '__esModule', { value: true }); }))); }); _commonjsHelpers.unwrapExports(immutable); var draftjsUtils = _commonjsHelpers.createCommonjsModule(function (module, exports) { !function(t,e){module.exports=e(Draft.Draft,immutable);}(window,function(n,r){return u={},o.m=i=[function(t,e){t.exports=n;},function(t,e){t.exports=r;},function(t,e,n){t.exports=n(3);},function(t,e,n){n.r(e);var C=n(0),i=n(1);function m(t){var e=t.getSelection(),n=t.getCurrentContent(),r=e.getStartKey(),o=e.getEndKey(),i=n.getBlockMap();return i.toSeq().skipUntil(function(t,e){return e===r}).takeUntil(function(t,e){return e===o}).concat([[o,i.get(o)]])}function a(t){return m(t).toList()}function f(t){if(t)return a(t).get(0)}function r(t){if(t){var n=f(t),e=t.getCurrentContent().getBlockMap().toSeq().toList(),r=0;if(e.forEach(function(t,e){t.get("key")===n.get("key")&&(r=e-1);}),-1= mutation.offset && originalOffset + originalLength <= mutation.offset + mutation.length; if (mutationContainsChange) { return Object.assign({}, mutation, { length: mutation.length + lengthDiff }); } var mutationWithinPrefixChange = mutation.offset >= originalOffset && mutation.offset + mutation.length <= originalOffset + originalLength && prefixLength > 0; if (mutationWithinPrefixChange) { return Object.assign({}, mutation, { offset: mutation.offset + prefixLength }); } var mutationContainsPrefix = mutation.offset < originalOffset && mutation.offset + mutation.length <= originalOffset + originalLength && mutation.offset + mutation.length > originalOffset && prefixLength > 0; if (mutationContainsPrefix) { return [Object.assign({}, mutation, { length: originalOffset - mutation.offset }), Object.assign({}, mutation, { offset: originalOffset + prefixLength, length: mutation.offset - originalOffset + mutation.length })]; } var mutationContainsSuffix = mutation.offset >= originalOffset && mutation.offset + mutation.length > originalOffset + originalLength && originalOffset + originalLength > mutation.offset && suffixLength > 0; if (mutationContainsSuffix) { return [Object.assign({}, mutation, { offset: mutation.offset + prefixLength, length: originalOffset + originalLength - mutation.offset }), Object.assign({}, mutation, { offset: originalOffset + originalLength + prefixLength + suffixLength, length: mutation.offset + mutation.length - (originalOffset + originalLength) })]; } return mutation; } }); _commonjsHelpers.unwrapExports(updateMutation_1); var rangeSort = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _default = function _default(r1, r2) { if (r1.offset === r2.offset) { return r2.length - r1.length; } return r1.offset - r2.offset; }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(rangeSort); var encodeBlock = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _toConsumableArray2 = interopRequireDefault(toConsumableArray); var _updateMutation = interopRequireDefault(updateMutation_1); var _rangeSort = interopRequireDefault(rangeSort); var ENTITY_MAP = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`', '\n': '
' }; var _default = function _default(block) { var blockText = (0, _toConsumableArray2["default"])(block.text); var entities = block.entityRanges.sort(_rangeSort["default"]); var styles = block.inlineStyleRanges.sort(_rangeSort["default"]); var resultText = ''; var _loop = function _loop(index) { var _char = blockText[index]; if (ENTITY_MAP[_char] !== undefined) { var encoded = ENTITY_MAP[_char]; var resultIndex = (0, _toConsumableArray2["default"])(resultText).length; resultText += encoded; var updateForChar = function updateForChar(mutation) { return (0, _updateMutation["default"])(mutation, resultIndex, _char.length, encoded.length, 0, 0); }; entities = entities.map(updateForChar); styles = styles.map(updateForChar); } else { resultText += _char; } }; for (var index = 0; index < blockText.length; index++) { _loop(index); } return Object.assign({}, block, { text: resultText, inlineStyleRanges: styles, entityRanges: entities }); }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(encodeBlock); var _typeof_1 = _commonjsHelpers.createCommonjsModule(function (module) { function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { module.exports = _typeof = function _typeof(obj) { return typeof obj; }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = _typeof; }); var splitReactElement_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = splitReactElement; var _invariant = interopRequireDefault(browser); var _react = interopRequireDefault(React__default); var _server = interopRequireDefault(server); // see http://w3c.github.io/html/syntax.html#writing-html-documents-elements var VOID_TAGS = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']; function splitReactElement(element) { if (VOID_TAGS.indexOf(element.type) !== -1) { return _server["default"].renderToStaticMarkup(element); } var tags = _server["default"].renderToStaticMarkup(_react["default"].cloneElement(element, {}, '\r')).split('\r'); (0, _invariant["default"])(tags.length > 1, "convertToHTML: Element of type ".concat(element.type, " must render children")); (0, _invariant["default"])(tags.length < 3, "convertToHTML: Element of type ".concat(element.type, " cannot use carriage return character")); return { start: tags[0], end: tags[1] }; } }); _commonjsHelpers.unwrapExports(splitReactElement_1); var getElementHTML_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = getElementHTML; var _typeof2 = interopRequireDefault(_typeof_1); var _invariant = interopRequireDefault(browser); var _react = interopRequireDefault(React__default); var _server = interopRequireDefault(server); var _splitReactElement = interopRequireDefault(splitReactElement_1); function hasChildren(element) { return _react["default"].isValidElement(element) && _react["default"].Children.count(element.props.children) > 0; } function getElementHTML(element) { var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (element === undefined || element === null) { return element; } if (typeof element === 'string') { return element; } if (_react["default"].isValidElement(element)) { if (hasChildren(element)) { return _server["default"].renderToStaticMarkup(element); } var tags = (0, _splitReactElement["default"])(element); if (text !== null && (0, _typeof2["default"])(tags) === 'object') { var start = tags.start, end = tags.end; return start + text + end; } return tags; } (0, _invariant["default"])(Object.prototype.hasOwnProperty.call(element, 'start') && Object.prototype.hasOwnProperty.call(element, 'end'), 'convertToHTML: received conversion data without either an HTML string, ReactElement or an object with start/end tags'); if (text !== null) { var _start = element.start, _end = element.end; return _start + text + _end; } return element; } }); _commonjsHelpers.unwrapExports(getElementHTML_1); var getElementTagLength_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _typeof2 = interopRequireDefault(_typeof_1); var _react = interopRequireDefault(React__default); var _splitReactElement = interopRequireDefault(splitReactElement_1); var getElementTagLength = function getElementTagLength(element) { var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'start'; if (_react["default"].isValidElement(element)) { var splitElement = (0, _splitReactElement["default"])(element); if (typeof splitElement === 'string') { return 0; } var length = splitElement[type].length; var child = _react["default"].Children.toArray(element.props.children)[0]; return length + (child && _react["default"].isValidElement(child) ? getElementTagLength(child, type) : 0); } if ((0, _typeof2["default"])(element) === 'object') { return element[type] ? element[type].length : 0; } return 0; }; var _default = getElementTagLength; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(getElementTagLength_1); var blockEntities = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _toConsumableArray2 = interopRequireDefault(toConsumableArray); var _updateMutation = interopRequireDefault(updateMutation_1); var _rangeSort = interopRequireDefault(rangeSort); var _getElementHTML = interopRequireDefault(getElementHTML_1); var _getElementTagLength = interopRequireDefault(getElementTagLength_1); var converter = function converter() { var originalText = arguments.length > 1 ? arguments[1] : undefined; return originalText; }; var _default = function _default(block, entityMap) { var entityConverter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : converter; var resultText = (0, _toConsumableArray2["default"])(block.text); var getEntityHTML = entityConverter; if (entityConverter.__isMiddleware) { getEntityHTML = entityConverter(converter); } if (Object.prototype.hasOwnProperty.call(block, 'entityRanges') && block.entityRanges.length > 0) { var entities = block.entityRanges.sort(_rangeSort["default"]); var styles = block.inlineStyleRanges; var _loop = function _loop(index) { var entityRange = entities[index]; var entity = entityMap[entityRange.key]; var originalText = resultText.slice(entityRange.offset, entityRange.offset + entityRange.length).join(''); var entityHTML = getEntityHTML(entity, originalText); var converted = (0, _toConsumableArray2["default"])((0, _getElementHTML["default"])(entityHTML, originalText) || originalText); var prefixLength = (0, _getElementTagLength["default"])(entityHTML, 'start'); var suffixLength = (0, _getElementTagLength["default"])(entityHTML, 'end'); var updateLaterMutation = function updateLaterMutation(mutation, mutationIndex) { if (mutationIndex > index || Object.prototype.hasOwnProperty.call(mutation, 'style')) { return (0, _updateMutation["default"])(mutation, entityRange.offset, entityRange.length, converted.length, prefixLength, suffixLength); } return mutation; }; var updateLaterMutations = function updateLaterMutations(mutationList) { return mutationList.reduce(function (acc, mutation, mutationIndex) { var updatedMutation = updateLaterMutation(mutation, mutationIndex); if (Array.isArray(updatedMutation)) { return acc.concat(updatedMutation); } return acc.concat([updatedMutation]); }, []); }; entities = updateLaterMutations(entities); styles = updateLaterMutations(styles); resultText = [].concat((0, _toConsumableArray2["default"])(resultText.slice(0, entityRange.offset)), (0, _toConsumableArray2["default"])(converted), (0, _toConsumableArray2["default"])(resultText.slice(entityRange.offset + entityRange.length))); }; for (var index = 0; index < entities.length; index++) { _loop(index); } return Object.assign({}, block, { text: resultText.join(''), inlineStyleRanges: styles, entityRanges: entities }); } return block; }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(blockEntities); var styleObjectFunction = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _default = function _default(object) { return function (style) { if (typeof object === 'function') { return object(style); } return object[style]; }; }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(styleObjectFunction); var accumulateFunction = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _default = function _default(newFn, rest) { return function () { var newResult = newFn.apply(void 0, arguments); if (newResult !== undefined && newResult !== null) { return newResult; } return rest.apply(void 0, arguments); }; }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(accumulateFunction); var defaultInlineHTML_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = defaultInlineHTML; var _react = interopRequireDefault(React__default); function defaultInlineHTML(style) { switch (style) { case 'BOLD': return _react["default"].createElement("strong", null); case 'ITALIC': return _react["default"].createElement("em", null); case 'UNDERLINE': return _react["default"].createElement("u", null); case 'CODE': return _react["default"].createElement("code", null); default: return { start: '', end: '' }; } } }); _commonjsHelpers.unwrapExports(defaultInlineHTML_1); var blockInlineStyles = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _toConsumableArray2 = interopRequireDefault(toConsumableArray); var _invariant = interopRequireDefault(browser); var _styleObjectFunction = interopRequireDefault(styleObjectFunction); var _accumulateFunction = interopRequireDefault(accumulateFunction); var _getElementHTML = interopRequireDefault(getElementHTML_1); var _rangeSort = interopRequireDefault(rangeSort); var _defaultInlineHTML = interopRequireDefault(defaultInlineHTML_1); var subtractStyles = function subtractStyles(original, toRemove) { return original.filter(function (el) { return !toRemove.some(function (elToRemove) { return elToRemove.style === el.style; }); }); }; var popEndingStyles = function popEndingStyles(styleStack, endingStyles) { return endingStyles.reduceRight(function (stack, style) { var styleToRemove = stack[stack.length - 1]; (0, _invariant["default"])(styleToRemove.style === style.style, "Style ".concat(styleToRemove.style, " to be removed doesn't match expected ").concat(style.style)); return stack.slice(0, -1); }, styleStack); }; var characterStyles = function characterStyles(offset, ranges) { return ranges.filter(function (range) { return offset >= range.offset && offset < range.offset + range.length; }); }; var rangeIsSubset = function rangeIsSubset(firstRange, secondRange) { // returns true if the second range is a subset of the first var secondStartWithinFirst = firstRange.offset <= secondRange.offset; var secondEndWithinFirst = firstRange.offset + firstRange.length >= secondRange.offset + secondRange.length; return secondStartWithinFirst && secondEndWithinFirst; }; var latestStyleLast = function latestStyleLast(s1, s2) { // make sure longer-lasting styles are added first var s2endIndex = s2.offset + s2.length; var s1endIndex = s1.offset + s1.length; return s2endIndex - s1endIndex; }; var getStylesToReset = function getStylesToReset(remainingStyles, newStyles) { var i = 0; while (i < remainingStyles.length) { if (newStyles.every(rangeIsSubset.bind(null, remainingStyles[i]))) { i++; } else { return remainingStyles.slice(i); } } return []; }; var appendStartMarkup = function appendStartMarkup(inlineHTML, string, styleRange) { return string + (0, _getElementHTML["default"])(inlineHTML(styleRange.style)).start; }; var prependEndMarkup = function prependEndMarkup(inlineHTML, string, styleRange) { return (0, _getElementHTML["default"])(inlineHTML(styleRange.style)).end + string; }; var defaultCustomInlineHTML = function defaultCustomInlineHTML(next) { return function (style) { return next(style); }; }; defaultCustomInlineHTML.__isMiddleware = true; var _default = function _default(rawBlock) { var customInlineHTML = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultCustomInlineHTML; (0, _invariant["default"])(rawBlock !== null && rawBlock !== undefined, 'Expected raw block to be non-null'); var inlineHTML; if (customInlineHTML.__isMiddleware === true) { inlineHTML = customInlineHTML(_defaultInlineHTML["default"]); } else { inlineHTML = (0, _accumulateFunction["default"])((0, _styleObjectFunction["default"])(customInlineHTML), (0, _styleObjectFunction["default"])(_defaultInlineHTML["default"])); } var result = ''; var styleStack = []; var sortedRanges = rawBlock.inlineStyleRanges.sort(_rangeSort["default"]); var originalTextArray = (0, _toConsumableArray2["default"])(rawBlock.text); for (var i = 0; i < originalTextArray.length; i++) { var styles = characterStyles(i, sortedRanges); var endingStyles = subtractStyles(styleStack, styles); var newStyles = subtractStyles(styles, styleStack); var remainingStyles = subtractStyles(styleStack, endingStyles); // reset styles: look for any already existing styles that will need to // end before styles that are being added on this character. to solve this // close out those current tags and all nested children, // then open new ones nested within the new styles. var resetStyles = getStylesToReset(remainingStyles, newStyles); var openingStyles = resetStyles.concat(newStyles).sort(latestStyleLast); var openingStyleTags = openingStyles.reduce(appendStartMarkup.bind(null, inlineHTML), ''); var endingStyleTags = endingStyles.concat(resetStyles).reduce(prependEndMarkup.bind(null, inlineHTML), ''); result += endingStyleTags + openingStyleTags + originalTextArray[i]; styleStack = popEndingStyles(styleStack, resetStyles.concat(endingStyles)); styleStack = styleStack.concat(openingStyles); (0, _invariant["default"])(styleStack.length === styles.length, "Character ".concat(i, ": ").concat(styleStack.length - styles.length, " styles left on stack that should no longer be there")); } result = styleStack.reduceRight(function (res, openStyle) { return res + (0, _getElementHTML["default"])(inlineHTML(openStyle.style)).end; }, result); return result; }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(blockInlineStyles); var blockTypeObjectFunction = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _default = function _default(typeObject) { return function (block) { if (typeof typeObject === 'function') { // handle case where typeObject is already a function return typeObject(block); } return typeObject[block.type]; }; }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(blockTypeObjectFunction); var getBlockTags_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = getBlockTags; var _invariant = interopRequireDefault(browser); var _react = interopRequireDefault(React__default); var _server = interopRequireDefault(server); var _splitReactElement = interopRequireDefault(splitReactElement_1); function hasChildren(element) { return _react["default"].isValidElement(element) && _react["default"].Children.count(element.props.children) > 0; } function getBlockTags(blockHTML) { (0, _invariant["default"])(blockHTML !== null && blockHTML !== undefined, 'Expected block HTML value to be non-null'); if (typeof blockHTML === 'string') { return blockHTML; } if (_react["default"].isValidElement(blockHTML)) { if (hasChildren(blockHTML)) { return _server["default"].renderToStaticMarkup(blockHTML); } return (0, _splitReactElement["default"])(blockHTML); } if (Object.prototype.hasOwnProperty.call(blockHTML, 'element') && _react["default"].isValidElement(blockHTML.element)) { return Object.assign({}, blockHTML, (0, _splitReactElement["default"])(blockHTML.element)); } (0, _invariant["default"])(Object.prototype.hasOwnProperty.call(blockHTML, 'start') && Object.prototype.hasOwnProperty.call(blockHTML, 'end'), 'convertToHTML: received block information without either a ReactElement or an object with start/end tags'); return blockHTML; } }); _commonjsHelpers.unwrapExports(getBlockTags_1); var getNestedBlockTags_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = getNestedBlockTags; var _invariant = interopRequireDefault(browser); var _react = interopRequireDefault(React__default); var _splitReactElement2 = interopRequireDefault(splitReactElement_1); function getNestedBlockTags(blockHTML) { (0, _invariant["default"])(blockHTML !== null && blockHTML !== undefined, 'Expected block HTML value to be non-null'); if (_react["default"].isValidElement(blockHTML.nest)) { var _splitReactElement = (0, _splitReactElement2["default"])(blockHTML.nest), start = _splitReactElement.start, end = _splitReactElement.end; return Object.assign({}, blockHTML, { nestStart: start, nestEnd: end }); } (0, _invariant["default"])(Object.prototype.hasOwnProperty.call(blockHTML, 'nestStart') && Object.prototype.hasOwnProperty.call(blockHTML, 'nestEnd'), 'convertToHTML: received block information without either a ReactElement or an object with start/end tags'); return blockHTML; } }); _commonjsHelpers.unwrapExports(getNestedBlockTags_1); var defaultBlockHTML = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = interopRequireDefault(React__default); var _default = { unstyled: _react["default"].createElement("p", null), paragraph: _react["default"].createElement("p", null), 'header-one': _react["default"].createElement("h1", null), 'header-two': _react["default"].createElement("h2", null), 'header-three': _react["default"].createElement("h3", null), 'header-four': _react["default"].createElement("h4", null), 'header-five': _react["default"].createElement("h5", null), 'header-six': _react["default"].createElement("h6", null), blockquote: _react["default"].createElement("blockquote", null), 'unordered-list-item': { element: _react["default"].createElement("li", null), nest: _react["default"].createElement("ul", null) }, 'ordered-list-item': { element: _react["default"].createElement("li", null), nest: _react["default"].createElement("ol", null) }, media: _react["default"].createElement("figure", null), atomic: _react["default"].createElement("figure", null) }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(defaultBlockHTML); var convertToHTML_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _invariant = interopRequireDefault(browser); var _react = interopRequireDefault(React__default); var _server = interopRequireDefault(server); var _encodeBlock = interopRequireDefault(encodeBlock); var _blockEntities = interopRequireDefault(blockEntities); var _blockInlineStyles = interopRequireDefault(blockInlineStyles); var _accumulateFunction = interopRequireDefault(accumulateFunction); var _blockTypeObjectFunction = interopRequireDefault(blockTypeObjectFunction); var _getBlockTags = interopRequireDefault(getBlockTags_1); var _getNestedBlockTags = interopRequireDefault(getNestedBlockTags_1); var _defaultBlockHTML = interopRequireDefault(defaultBlockHTML); // import Immutable from 'immutable'; // eslint-disable-line no-unused-vars var defaultEntityToHTML = function defaultEntityToHTML(entity, originalText) { return originalText; }; var convertToHTML = function convertToHTML(_ref) { var _ref$styleToHTML = _ref.styleToHTML, styleToHTML = _ref$styleToHTML === void 0 ? {} : _ref$styleToHTML, _ref$blockToHTML = _ref.blockToHTML, blockToHTML = _ref$blockToHTML === void 0 ? {} : _ref$blockToHTML, _ref$entityToHTML = _ref.entityToHTML, entityToHTML = _ref$entityToHTML === void 0 ? defaultEntityToHTML : _ref$entityToHTML; return function (contentState) { (0, _invariant["default"])(contentState !== null && contentState !== undefined, 'Expected contentState to be non-null'); var getBlockHTML; if (blockToHTML.__isMiddleware === true) { getBlockHTML = blockToHTML((0, _blockTypeObjectFunction["default"])(_defaultBlockHTML["default"])); } else { getBlockHTML = (0, _accumulateFunction["default"])((0, _blockTypeObjectFunction["default"])(blockToHTML), (0, _blockTypeObjectFunction["default"])(_defaultBlockHTML["default"])); } var rawState = (0, Draft.Draft.convertToRaw)(contentState); var listStack = []; var result = rawState.blocks.map(function (block) { var type = block.type, depth = block.depth; var closeNestTags = ''; var openNestTags = ''; var blockHTMLResult = getBlockHTML(block); if (!blockHTMLResult) { throw new Error("convertToHTML: missing HTML definition for block with type ".concat(block.type)); } if (!blockHTMLResult.nest) { // this block can't be nested, so reset all nesting if necessary closeNestTags = listStack.reduceRight(function (string, nestedBlock) { return string + (0, _getNestedBlockTags["default"])(getBlockHTML(nestedBlock)).nestEnd; }, ''); listStack = []; } else { while (depth + 1 !== listStack.length || type !== listStack[depth].type) { if (depth + 1 === listStack.length) { // depth is right but doesn't match type var blockToClose = listStack[depth]; closeNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(blockToClose)).nestEnd; openNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(block)).nestStart; listStack[depth] = block; } else if (depth + 1 < listStack.length) { var _blockToClose = listStack[listStack.length - 1]; closeNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(_blockToClose)).nestEnd; listStack = listStack.slice(0, -1); } else { openNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(block)).nestStart; listStack.push(block); } } } var innerHTML = (0, _blockInlineStyles["default"])((0, _blockEntities["default"])((0, _encodeBlock["default"])(block), rawState.entityMap, entityToHTML), styleToHTML); var blockHTML = (0, _getBlockTags["default"])(getBlockHTML(block)); var html; if (typeof blockHTML === 'string') { html = blockHTML; } else { html = blockHTML.start + innerHTML + blockHTML.end; } if (innerHTML.length === 0 && Object.prototype.hasOwnProperty.call(blockHTML, 'empty')) { if (_react["default"].isValidElement(blockHTML.empty)) { html = _server["default"].renderToStaticMarkup(blockHTML.empty); } else { html = blockHTML.empty; } } return closeNestTags + openNestTags + html; }).join(''); result = listStack.reduce(function (res, nestBlock) { return res + (0, _getNestedBlockTags["default"])(getBlockHTML(nestBlock)).nestEnd; }, result); return result; }; }; var _default = function _default() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 1 && Object.prototype.hasOwnProperty.call(args[0], '_map') && args[0].getBlockMap != null) { // skip higher-order function and use defaults return convertToHTML({}).apply(void 0, args); } return convertToHTML.apply(void 0, args); }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(convertToHTML_1); var immutable$1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { /** * Copyright (c) 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ (function (global, factory) { module.exports = factory() ; }(_commonjsHelpers.commonjsGlobal, function () {var SLICE$0 = Array.prototype.slice; function createClass(ctor, superClass) { if (superClass) { ctor.prototype = Object.create(superClass.prototype); } ctor.prototype.constructor = ctor; } function Iterable(value) { return isIterable(value) ? value : Seq(value); } createClass(KeyedIterable, Iterable); function KeyedIterable(value) { return isKeyed(value) ? value : KeyedSeq(value); } createClass(IndexedIterable, Iterable); function IndexedIterable(value) { return isIndexed(value) ? value : IndexedSeq(value); } createClass(SetIterable, Iterable); function SetIterable(value) { return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); } function isIterable(maybeIterable) { return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); } function isKeyed(maybeKeyed) { return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); } function isIndexed(maybeIndexed) { return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); } function isAssociative(maybeAssociative) { return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); } function isOrdered(maybeOrdered) { return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); } Iterable.isIterable = isIterable; Iterable.isKeyed = isKeyed; Iterable.isIndexed = isIndexed; Iterable.isAssociative = isAssociative; Iterable.isOrdered = isOrdered; Iterable.Keyed = KeyedIterable; Iterable.Indexed = IndexedIterable; Iterable.Set = SetIterable; var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; // Used for setting prototype methods that IE8 chokes on. var DELETE = 'delete'; // Constants describing the size of trie nodes. var SHIFT = 5; // Resulted in best performance after ______? var SIZE = 1 << SHIFT; var MASK = SIZE - 1; // A consistent shared value representing "not set" which equals nothing other // than itself, and nothing that could be provided externally. var NOT_SET = {}; // Boolean references, Rough equivalent of `bool &`. var CHANGE_LENGTH = { value: false }; var DID_ALTER = { value: false }; function MakeRef(ref) { ref.value = false; return ref; } function SetRef(ref) { ref && (ref.value = true); } // A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {} // http://jsperf.com/copy-array-inline function arrCopy(arr, offset) { offset = offset || 0; var len = Math.max(0, arr.length - offset); var newArr = new Array(len); for (var ii = 0; ii < len; ii++) { newArr[ii] = arr[ii + offset]; } return newArr; } function ensureSize(iter) { if (iter.size === undefined) { iter.size = iter.__iterate(returnTrue); } return iter.size; } function wrapIndex(iter, index) { // This implements "is array index" which the ECMAString spec defines as: // // A String property name P is an array index if and only if // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal // to 2^32−1. // // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects if (typeof index !== 'number') { var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 if ('' + uint32Index !== index || uint32Index === 4294967295) { return NaN; } index = uint32Index; } return index < 0 ? ensureSize(iter) + index : index; } function returnTrue() { return true; } function wholeSlice(begin, end, size) { return (begin === 0 || (size !== undefined && begin <= -size)) && (end === undefined || (size !== undefined && end >= size)); } function resolveBegin(begin, size) { return resolveIndex(begin, size, 0); } function resolveEnd(end, size) { return resolveIndex(end, size, size); } function resolveIndex(index, size, defaultIndex) { return index === undefined ? defaultIndex : index < 0 ? Math.max(0, size + index) : size === undefined ? index : Math.min(size, index); } /* global Symbol */ var ITERATE_KEYS = 0; var ITERATE_VALUES = 1; var ITERATE_ENTRIES = 2; var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; function Iterator(next) { this.next = next; } Iterator.prototype.toString = function() { return '[Iterator]'; }; Iterator.KEYS = ITERATE_KEYS; Iterator.VALUES = ITERATE_VALUES; Iterator.ENTRIES = ITERATE_ENTRIES; Iterator.prototype.inspect = Iterator.prototype.toSource = function () { return this.toString(); }; Iterator.prototype[ITERATOR_SYMBOL] = function () { return this; }; function iteratorValue(type, k, v, iteratorResult) { var value = type === 0 ? k : type === 1 ? v : [k, v]; iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { value: value, done: false }); return iteratorResult; } function iteratorDone() { return { value: undefined, done: true }; } function hasIterator(maybeIterable) { return !!getIteratorFn(maybeIterable); } function isIterator(maybeIterator) { return maybeIterator && typeof maybeIterator.next === 'function'; } function getIterator(iterable) { var iteratorFn = getIteratorFn(iterable); return iteratorFn && iteratorFn.call(iterable); } function getIteratorFn(iterable) { var iteratorFn = iterable && ( (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || iterable[FAUX_ITERATOR_SYMBOL] ); if (typeof iteratorFn === 'function') { return iteratorFn; } } function isArrayLike(value) { return value && typeof value.length === 'number'; } createClass(Seq, Iterable); function Seq(value) { return value === null || value === undefined ? emptySequence() : isIterable(value) ? value.toSeq() : seqFromValue(value); } Seq.of = function(/*...values*/) { return Seq(arguments); }; Seq.prototype.toSeq = function() { return this; }; Seq.prototype.toString = function() { return this.__toString('Seq {', '}'); }; Seq.prototype.cacheResult = function() { if (!this._cache && this.__iterateUncached) { this._cache = this.entrySeq().toArray(); this.size = this._cache.length; } return this; }; // abstract __iterateUncached(fn, reverse) Seq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, true); }; // abstract __iteratorUncached(type, reverse) Seq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, true); }; createClass(KeyedSeq, Seq); function KeyedSeq(value) { return value === null || value === undefined ? emptySequence().toKeyedSeq() : isIterable(value) ? (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : keyedSeqFromValue(value); } KeyedSeq.prototype.toKeyedSeq = function() { return this; }; createClass(IndexedSeq, Seq); function IndexedSeq(value) { return value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); } IndexedSeq.of = function(/*...values*/) { return IndexedSeq(arguments); }; IndexedSeq.prototype.toIndexedSeq = function() { return this; }; IndexedSeq.prototype.toString = function() { return this.__toString('Seq [', ']'); }; IndexedSeq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, false); }; IndexedSeq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, false); }; createClass(SetSeq, Seq); function SetSeq(value) { return ( value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value ).toSetSeq(); } SetSeq.of = function(/*...values*/) { return SetSeq(arguments); }; SetSeq.prototype.toSetSeq = function() { return this; }; Seq.isSeq = isSeq; Seq.Keyed = KeyedSeq; Seq.Set = SetSeq; Seq.Indexed = IndexedSeq; var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; Seq.prototype[IS_SEQ_SENTINEL] = true; createClass(ArraySeq, IndexedSeq); function ArraySeq(array) { this._array = array; this.size = array.length; } ArraySeq.prototype.get = function(index, notSetValue) { return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; ArraySeq.prototype.__iterate = function(fn, reverse) { var array = this._array; var maxIndex = array.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { return ii + 1; } } return ii; }; ArraySeq.prototype.__iterator = function(type, reverse) { var array = this._array; var maxIndex = array.length - 1; var ii = 0; return new Iterator(function() {return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} ); }; createClass(ObjectSeq, KeyedSeq); function ObjectSeq(object) { var keys = Object.keys(object); this._object = object; this._keys = keys; this.size = keys.length; } ObjectSeq.prototype.get = function(key, notSetValue) { if (notSetValue !== undefined && !this.has(key)) { return notSetValue; } return this._object[key]; }; ObjectSeq.prototype.has = function(key) { return this._object.hasOwnProperty(key); }; ObjectSeq.prototype.__iterate = function(fn, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var key = keys[reverse ? maxIndex - ii : ii]; if (fn(object[key], key, this) === false) { return ii + 1; } } return ii; }; ObjectSeq.prototype.__iterator = function(type, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; var ii = 0; return new Iterator(function() { var key = keys[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, key, object[key]); }); }; ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; createClass(IterableSeq, IndexedSeq); function IterableSeq(iterable) { this._iterable = iterable; this.size = iterable.length || iterable.size; } IterableSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); var iterations = 0; if (isIterator(iterator)) { var step; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } } return iterations; }; IterableSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); if (!isIterator(iterator)) { return new Iterator(iteratorDone); } var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; createClass(IteratorSeq, IndexedSeq); function IteratorSeq(iterator) { this._iterator = iterator; this._iteratorCache = []; } IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; while (iterations < cache.length) { if (fn(cache[iterations], iterations++, this) === false) { return iterations; } } var step; while (!(step = iterator.next()).done) { var val = step.value; cache[iterations] = val; if (fn(val, iterations++, this) === false) { break; } } return iterations; }; IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; return new Iterator(function() { if (iterations >= cache.length) { var step = iterator.next(); if (step.done) { return step; } cache[iterations] = step.value; } return iteratorValue(type, iterations, cache[iterations++]); }); }; // # pragma Helper functions function isSeq(maybeSeq) { return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); } var EMPTY_SEQ; function emptySequence() { return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } function keyedSeqFromValue(value) { var seq = Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : typeof value === 'object' ? new ObjectSeq(value) : undefined; if (!seq) { throw new TypeError( 'Expected Array or iterable object of [k, v] entries, '+ 'or keyed object: ' + value ); } return seq; } function indexedSeqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values: ' + value ); } return seq; } function seqFromValue(value) { var seq = maybeIndexedSeqFromValue(value) || (typeof value === 'object' && new ObjectSeq(value)); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values, or keyed object: ' + value ); } return seq; } function maybeIndexedSeqFromValue(value) { return ( isArrayLike(value) ? new ArraySeq(value) : isIterator(value) ? new IteratorSeq(value) : hasIterator(value) ? new IterableSeq(value) : undefined ); } function seqIterate(seq, fn, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var entry = cache[reverse ? maxIndex - ii : ii]; if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { return ii + 1; } } return ii; } return seq.__iterateUncached(fn, reverse); } function seqIterator(seq, type, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; var ii = 0; return new Iterator(function() { var entry = cache[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); }); } return seq.__iteratorUncached(type, reverse); } function fromJS(json, converter) { return converter ? fromJSWith(converter, json, '', {'': json}) : fromJSDefault(json); } function fromJSWith(converter, json, key, parentJSON) { if (Array.isArray(json)) { return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } if (isPlainObj(json)) { return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } return json; } function fromJSDefault(json) { if (Array.isArray(json)) { return IndexedSeq(json).map(fromJSDefault).toList(); } if (isPlainObj(json)) { return KeyedSeq(json).map(fromJSDefault).toMap(); } return json; } function isPlainObj(value) { return value && (value.constructor === Object || value.constructor === undefined); } /** * An extension of the "same-value" algorithm as [described for use by ES6 Map * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) * * NaN is considered the same as NaN, however -0 and 0 are considered the same * value, which is different from the algorithm described by * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * This is extended further to allow Objects to describe the values they * represent, by way of `valueOf` or `equals` (and `hashCode`). * * Note: because of this extension, the key equality of Immutable.Map and the * value equality of Immutable.Set will differ from ES6 Map and Set. * * ### Defining custom values * * The easiest way to describe the value an object represents is by implementing * `valueOf`. For example, `Date` represents a value by returning a unix * timestamp for `valueOf`: * * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... * var date2 = new Date(1234567890000); * date1.valueOf(); // 1234567890000 * assert( date1 !== date2 ); * assert( Immutable.is( date1, date2 ) ); * * Note: overriding `valueOf` may have other implications if you use this object * where JavaScript expects a primitive, such as implicit string coercion. * * For more complex types, especially collections, implementing `valueOf` may * not be performant. An alternative is to implement `equals` and `hashCode`. * * `equals` takes another object, presumably of similar type, and returns true * if the it is equal. Equality is symmetrical, so the same result should be * returned if this and the argument are flipped. * * assert( a.equals(b) === b.equals(a) ); * * `hashCode` returns a 32bit integer number representing the object which will * be used to determine how to store the value object in a Map or Set. You must * provide both or neither methods, one must not exist without the other. * * Also, an important relationship between these methods must be upheld: if two * values are equal, they *must* return the same hashCode. If the values are not * equal, they might have the same hashCode; this is called a hash collision, * and while undesirable for performance reasons, it is acceptable. * * if (a.equals(b)) { * assert( a.hashCode() === b.hashCode() ); * } * * All Immutable collections implement `equals` and `hashCode`. * */ function is(valueA, valueB) { if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } if (typeof valueA.valueOf === 'function' && typeof valueB.valueOf === 'function') { valueA = valueA.valueOf(); valueB = valueB.valueOf(); if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } } if (typeof valueA.equals === 'function' && typeof valueB.equals === 'function' && valueA.equals(valueB)) { return true; } return false; } function deepEqual(a, b) { if (a === b) { return true; } if ( !isIterable(b) || a.size !== undefined && b.size !== undefined && a.size !== b.size || a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || isKeyed(a) !== isKeyed(b) || isIndexed(a) !== isIndexed(b) || isOrdered(a) !== isOrdered(b) ) { return false; } if (a.size === 0 && b.size === 0) { return true; } var notAssociative = !isAssociative(a); if (isOrdered(a)) { var entries = a.entries(); return b.every(function(v, k) { var entry = entries.next().value; return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); }) && entries.next().done; } var flipped = false; if (a.size === undefined) { if (b.size === undefined) { if (typeof a.cacheResult === 'function') { a.cacheResult(); } } else { flipped = true; var _ = a; a = b; b = _; } } var allEqual = true; var bSize = b.__iterate(function(v, k) { if (notAssociative ? !a.has(v) : flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { allEqual = false; return false; } }); return allEqual && a.size === bSize; } createClass(Repeat, IndexedSeq); function Repeat(value, times) { if (!(this instanceof Repeat)) { return new Repeat(value, times); } this._value = value; this.size = times === undefined ? Infinity : Math.max(0, times); if (this.size === 0) { if (EMPTY_REPEAT) { return EMPTY_REPEAT; } EMPTY_REPEAT = this; } } Repeat.prototype.toString = function() { if (this.size === 0) { return 'Repeat []'; } return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; }; Repeat.prototype.get = function(index, notSetValue) { return this.has(index) ? this._value : notSetValue; }; Repeat.prototype.includes = function(searchValue) { return is(this._value, searchValue); }; Repeat.prototype.slice = function(begin, end) { var size = this.size; return wholeSlice(begin, end, size) ? this : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); }; Repeat.prototype.reverse = function() { return this; }; Repeat.prototype.indexOf = function(searchValue) { if (is(this._value, searchValue)) { return 0; } return -1; }; Repeat.prototype.lastIndexOf = function(searchValue) { if (is(this._value, searchValue)) { return this.size; } return -1; }; Repeat.prototype.__iterate = function(fn, reverse) { for (var ii = 0; ii < this.size; ii++) { if (fn(this._value, ii, this) === false) { return ii + 1; } } return ii; }; Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; var ii = 0; return new Iterator(function() {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} ); }; Repeat.prototype.equals = function(other) { return other instanceof Repeat ? is(this._value, other._value) : deepEqual(other); }; var EMPTY_REPEAT; function invariant(condition, error) { if (!condition) throw new Error(error); } createClass(Range, IndexedSeq); function Range(start, end, step) { if (!(this instanceof Range)) { return new Range(start, end, step); } invariant(step !== 0, 'Cannot step a Range by 0'); start = start || 0; if (end === undefined) { end = Infinity; } step = step === undefined ? 1 : Math.abs(step); if (end < start) { step = -step; } this._start = start; this._end = end; this._step = step; this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); if (this.size === 0) { if (EMPTY_RANGE) { return EMPTY_RANGE; } EMPTY_RANGE = this; } } Range.prototype.toString = function() { if (this.size === 0) { return 'Range []'; } return 'Range [ ' + this._start + '...' + this._end + (this._step > 1 ? ' by ' + this._step : '') + ' ]'; }; Range.prototype.get = function(index, notSetValue) { return this.has(index) ? this._start + wrapIndex(this, index) * this._step : notSetValue; }; Range.prototype.includes = function(searchValue) { var possibleIndex = (searchValue - this._start) / this._step; return possibleIndex >= 0 && possibleIndex < this.size && possibleIndex === Math.floor(possibleIndex); }; Range.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } begin = resolveBegin(begin, this.size); end = resolveEnd(end, this.size); if (end <= begin) { return new Range(0, 0); } return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); }; Range.prototype.indexOf = function(searchValue) { var offsetValue = searchValue - this._start; if (offsetValue % this._step === 0) { var index = offsetValue / this._step; if (index >= 0 && index < this.size) { return index } } return -1; }; Range.prototype.lastIndexOf = function(searchValue) { return this.indexOf(searchValue); }; Range.prototype.__iterate = function(fn, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(value, ii, this) === false) { return ii + 1; } value += reverse ? -step : step; } return ii; }; Range.prototype.__iterator = function(type, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; var ii = 0; return new Iterator(function() { var v = value; value += reverse ? -step : step; return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); }); }; Range.prototype.equals = function(other) { return other instanceof Range ? this._start === other._start && this._end === other._end && this._step === other._step : deepEqual(this, other); }; var EMPTY_RANGE; createClass(Collection, Iterable); function Collection() { throw TypeError('Abstract'); } createClass(KeyedCollection, Collection);function KeyedCollection() {} createClass(IndexedCollection, Collection);function IndexedCollection() {} createClass(SetCollection, Collection);function SetCollection() {} Collection.Keyed = KeyedCollection; Collection.Indexed = IndexedCollection; Collection.Set = SetCollection; var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? Math.imul : function imul(a, b) { a = a | 0; // int b = b | 0; // int var c = a & 0xffff; var d = b & 0xffff; // Shift by 0 fixes the sign on the high part. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int }; // v8 has an optimization for storing 31-bit signed numbers. // Values which have either 00 or 11 as the high order bits qualify. // This function drops the highest order bit in a signed number, maintaining // the sign bit. function smi(i32) { return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); } function hash(o) { if (o === false || o === null || o === undefined) { return 0; } if (typeof o.valueOf === 'function') { o = o.valueOf(); if (o === false || o === null || o === undefined) { return 0; } } if (o === true) { return 1; } var type = typeof o; if (type === 'number') { var h = o | 0; if (h !== o) { h ^= o * 0xFFFFFFFF; } while (o > 0xFFFFFFFF) { o /= 0xFFFFFFFF; h ^= o; } return smi(h); } if (type === 'string') { return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); } if (typeof o.hashCode === 'function') { return o.hashCode(); } if (type === 'object') { return hashJSObj(o); } if (typeof o.toString === 'function') { return hashString(o.toString()); } throw new Error('Value type ' + type + ' cannot be hashed.'); } function cachedHashString(string) { var hash = stringHashCache[string]; if (hash === undefined) { hash = hashString(string); if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { STRING_HASH_CACHE_SIZE = 0; stringHashCache = {}; } STRING_HASH_CACHE_SIZE++; stringHashCache[string] = hash; } return hash; } // http://jsperf.com/hashing-strings function hashString(string) { // This is the hash from JVM // The hash code for a string is computed as // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], // where s[i] is the ith character of the string and n is the length of // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 // (exclusive) by dropping high bits. var hash = 0; for (var ii = 0; ii < string.length; ii++) { hash = 31 * hash + string.charCodeAt(ii) | 0; } return smi(hash); } function hashJSObj(obj) { var hash; if (usingWeakMap) { hash = weakMap.get(obj); if (hash !== undefined) { return hash; } } hash = obj[UID_HASH_KEY]; if (hash !== undefined) { return hash; } if (!canDefineProperty) { hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; if (hash !== undefined) { return hash; } hash = getIENodeHash(obj); if (hash !== undefined) { return hash; } } hash = ++objHashUID; if (objHashUID & 0x40000000) { objHashUID = 0; } if (usingWeakMap) { weakMap.set(obj, hash); } else if (isExtensible !== undefined && isExtensible(obj) === false) { throw new Error('Non-extensible objects are not allowed as keys.'); } else if (canDefineProperty) { Object.defineProperty(obj, UID_HASH_KEY, { 'enumerable': false, 'configurable': false, 'writable': false, 'value': hash }); } else if (obj.propertyIsEnumerable !== undefined && obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { // Since we can't define a non-enumerable property on the object // we'll hijack one of the less-used non-enumerable properties to // save our hash on it. Since this is a function it will not show up in // `JSON.stringify` which is what we want. obj.propertyIsEnumerable = function() { return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); }; obj.propertyIsEnumerable[UID_HASH_KEY] = hash; } else if (obj.nodeType !== undefined) { // At this point we couldn't get the IE `uniqueID` to use as a hash // and we couldn't use a non-enumerable property to exploit the // dontEnum bug so we simply add the `UID_HASH_KEY` on the node // itself. obj[UID_HASH_KEY] = hash; } else { throw new Error('Unable to set a non-enumerable property on object.'); } return hash; } // Get references to ES5 object methods. var isExtensible = Object.isExtensible; // True if Object.defineProperty works as expected. IE8 fails this test. var canDefineProperty = (function() { try { Object.defineProperty({}, '@', {}); return true; } catch (e) { return false; } }()); // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it // and avoid memory leaks from the IE cloneNode bug. function getIENodeHash(node) { if (node && node.nodeType > 0) { switch (node.nodeType) { case 1: // Element return node.uniqueID; case 9: // Document return node.documentElement && node.documentElement.uniqueID; } } } // If possible, use a WeakMap. var usingWeakMap = typeof WeakMap === 'function'; var weakMap; if (usingWeakMap) { weakMap = new WeakMap(); } var objHashUID = 0; var UID_HASH_KEY = '__immutablehash__'; if (typeof Symbol === 'function') { UID_HASH_KEY = Symbol(UID_HASH_KEY); } var STRING_HASH_CACHE_MIN_STRLEN = 16; var STRING_HASH_CACHE_MAX_SIZE = 255; var STRING_HASH_CACHE_SIZE = 0; var stringHashCache = {}; function assertNotInfinite(size) { invariant( size !== Infinity, 'Cannot perform this action with an infinite size.' ); } createClass(Map, KeyedCollection); // @pragma Construction function Map(value) { return value === null || value === undefined ? emptyMap() : isMap(value) && !isOrdered(value) ? value : emptyMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } Map.prototype.toString = function() { return this.__toString('Map {', '}'); }; // @pragma Access Map.prototype.get = function(k, notSetValue) { return this._root ? this._root.get(0, undefined, k, notSetValue) : notSetValue; }; // @pragma Modification Map.prototype.set = function(k, v) { return updateMap(this, k, v); }; Map.prototype.setIn = function(keyPath, v) { return this.updateIn(keyPath, NOT_SET, function() {return v}); }; Map.prototype.remove = function(k) { return updateMap(this, k, NOT_SET); }; Map.prototype.deleteIn = function(keyPath) { return this.updateIn(keyPath, function() {return NOT_SET}); }; Map.prototype.update = function(k, notSetValue, updater) { return arguments.length === 1 ? k(this) : this.updateIn([k], notSetValue, updater); }; Map.prototype.updateIn = function(keyPath, notSetValue, updater) { if (!updater) { updater = notSetValue; notSetValue = undefined; } var updatedValue = updateInDeepMap( this, forceIterator(keyPath), notSetValue, updater ); return updatedValue === NOT_SET ? undefined : updatedValue; }; Map.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }; // @pragma Composition Map.prototype.merge = function(/*...iters*/) { return mergeIntoMapWith(this, undefined, arguments); }; Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, merger, iters); }; Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.merge === 'function' ? m.merge.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoMapWith(this, deepMerger, arguments); }; Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, deepMergerWith(merger), iters); }; Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.mergeDeep === 'function' ? m.mergeDeep.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.sort = function(comparator) { // Late binding return OrderedMap(sortFactory(this, comparator)); }; Map.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedMap(sortFactory(this, comparator, mapper)); }; // @pragma Mutability Map.prototype.withMutations = function(fn) { var mutable = this.asMutable(); fn(mutable); return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; }; Map.prototype.asMutable = function() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); }; Map.prototype.asImmutable = function() { return this.__ensureOwner(); }; Map.prototype.wasAltered = function() { return this.__altered; }; Map.prototype.__iterator = function(type, reverse) { return new MapIterator(this, type, reverse); }; Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; this._root && this._root.iterate(function(entry ) { iterations++; return fn(entry[1], entry[0], this$0); }, reverse); return iterations; }; Map.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }; function isMap(maybeMap) { return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); } Map.isMap = isMap; var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; var MapPrototype = Map.prototype; MapPrototype[IS_MAP_SENTINEL] = true; MapPrototype[DELETE] = MapPrototype.remove; MapPrototype.removeIn = MapPrototype.deleteIn; // #pragma Trie Nodes function ArrayMapNode(ownerID, entries) { this.ownerID = ownerID; this.entries = entries; } ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && entries.length === 1) { return; // undefined } if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { return createNodes(ownerID, entries, key, value); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new ArrayMapNode(ownerID, newEntries); }; function BitmapIndexedNode(ownerID, bitmap, nodes) { this.ownerID = ownerID; this.bitmap = bitmap; this.nodes = nodes; } BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); var bitmap = this.bitmap; return (bitmap & bit) === 0 ? notSetValue : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); }; BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var bit = 1 << keyHashFrag; var bitmap = this.bitmap; var exists = (bitmap & bit) !== 0; if (!exists && value === NOT_SET) { return this; } var idx = popCount(bitmap & (bit - 1)); var nodes = this.nodes; var node = exists ? nodes[idx] : undefined; var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); } if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { return nodes[idx ^ 1]; } if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { return newNode; } var isEditable = ownerID && ownerID === this.ownerID; var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; var newNodes = exists ? newNode ? setIn(nodes, idx, newNode, isEditable) : spliceOut(nodes, idx, isEditable) : spliceIn(nodes, idx, newNode, isEditable); if (isEditable) { this.bitmap = newBitmap; this.nodes = newNodes; return this; } return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; function HashArrayMapNode(ownerID, count, nodes) { this.ownerID = ownerID; this.count = count; this.nodes = nodes; } HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var node = this.nodes[idx]; return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; }; HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var removed = value === NOT_SET; var nodes = this.nodes; var node = nodes[idx]; if (removed && !node) { return this; } var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } var newCount = this.count; if (!node) { newCount++; } else if (!newNode) { newCount--; if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { return packNodes(ownerID, nodes, newCount, idx); } } var isEditable = ownerID && ownerID === this.ownerID; var newNodes = setIn(nodes, idx, newNode, isEditable); if (isEditable) { this.count = newCount; this.nodes = newNodes; return this; } return new HashArrayMapNode(ownerID, newCount, newNodes); }; function HashCollisionNode(ownerID, keyHash, entries) { this.ownerID = ownerID; this.keyHash = keyHash; this.entries = entries; } HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var removed = value === NOT_SET; if (keyHash !== this.keyHash) { if (removed) { return this; } SetRef(didAlter); SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); } var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && len === 2) { return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new HashCollisionNode(ownerID, this.keyHash, newEntries); }; function ValueNode(ownerID, keyHash, entry) { this.ownerID = ownerID; this.keyHash = keyHash; this.entry = entry; } ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { return is(key, this.entry[0]) ? this.entry[1] : notSetValue; }; ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var keyMatch = is(key, this.entry[0]); if (keyMatch ? value === this.entry[1] : removed) { return this; } SetRef(didAlter); if (removed) { SetRef(didChangeSize); return; // undefined } if (keyMatch) { if (ownerID && ownerID === this.ownerID) { this.entry[1] = value; return this; } return new ValueNode(ownerID, this.keyHash, [key, value]); } SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); }; // #pragma Iterators ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) { var entries = this.entries; for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { return false; } } }; BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) { var nodes = this.nodes; for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { var node = nodes[reverse ? maxIndex - ii : ii]; if (node && node.iterate(fn, reverse) === false) { return false; } } }; ValueNode.prototype.iterate = function (fn, reverse) { return fn(this.entry); }; createClass(MapIterator, Iterator); function MapIterator(map, type, reverse) { this._type = type; this._reverse = reverse; this._stack = map._root && mapIteratorFrame(map._root); } MapIterator.prototype.next = function() { var type = this._type; var stack = this._stack; while (stack) { var node = stack.node; var index = stack.index++; var maxIndex; if (node.entry) { if (index === 0) { return mapIteratorValue(type, node.entry); } } else if (node.entries) { maxIndex = node.entries.length - 1; if (index <= maxIndex) { return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); } } else { maxIndex = node.nodes.length - 1; if (index <= maxIndex) { var subNode = node.nodes[this._reverse ? maxIndex - index : index]; if (subNode) { if (subNode.entry) { return mapIteratorValue(type, subNode.entry); } stack = this._stack = mapIteratorFrame(subNode, stack); } continue; } } stack = this._stack = this._stack.__prev; } return iteratorDone(); }; function mapIteratorValue(type, entry) { return iteratorValue(type, entry[0], entry[1]); } function mapIteratorFrame(node, prev) { return { node: node, index: 0, __prev: prev }; } function makeMap(size, root, ownerID, hash) { var map = Object.create(MapPrototype); map.size = size; map._root = root; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_MAP; function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); } function updateMap(map, k, v) { var newRoot; var newSize; if (!map._root) { if (v === NOT_SET) { return map; } newSize = 1; newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); } else { var didChangeSize = MakeRef(CHANGE_LENGTH); var didAlter = MakeRef(DID_ALTER); newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); if (!didAlter.value) { return map; } newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); } if (map.__ownerID) { map.size = newSize; map._root = newRoot; map.__hash = undefined; map.__altered = true; return map; } return newRoot ? makeMap(newSize, newRoot) : emptyMap(); } function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (!node) { if (value === NOT_SET) { return node; } SetRef(didAlter); SetRef(didChangeSize); return new ValueNode(ownerID, keyHash, [key, value]); } return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); } function isLeafNode(node) { return node.constructor === ValueNode || node.constructor === HashCollisionNode; } function mergeIntoNode(node, ownerID, shift, keyHash, entry) { if (node.keyHash === keyHash) { return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); } var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var newNode; var nodes = idx1 === idx2 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); } function createNodes(ownerID, entries, key, value) { if (!ownerID) { ownerID = new OwnerID(); } var node = new ValueNode(ownerID, hash(key), [key, value]); for (var ii = 0; ii < entries.length; ii++) { var entry = entries[ii]; node = node.update(ownerID, 0, undefined, entry[0], entry[1]); } return node; } function packNodes(ownerID, nodes, count, excluding) { var bitmap = 0; var packedII = 0; var packedNodes = new Array(count); for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { var node = nodes[ii]; if (node !== undefined && ii !== excluding) { bitmap |= bit; packedNodes[packedII++] = node; } } return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } function expandNodes(ownerID, nodes, bitmap, including, node) { var count = 0; var expandedNodes = new Array(SIZE); for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; } expandedNodes[including] = node; return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } function mergeIntoMapWith(map, merger, iterables) { var iters = []; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = KeyedIterable(value); if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } return mergeIntoCollectionWith(map, merger, iters); } function deepMerger(existing, value, key) { return existing && existing.mergeDeep && isIterable(value) ? existing.mergeDeep(value) : is(existing, value) ? existing : value; } function deepMergerWith(merger) { return function(existing, value, key) { if (existing && existing.mergeDeepWith && isIterable(value)) { return existing.mergeDeepWith(merger, value); } var nextValue = merger(existing, value, key); return is(existing, nextValue) ? existing : nextValue; }; } function mergeIntoCollectionWith(collection, merger, iters) { iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return collection; } if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { return collection.constructor(iters[0]); } return collection.withMutations(function(collection ) { var mergeIntoMap = merger ? function(value, key) { collection.update(key, NOT_SET, function(existing ) {return existing === NOT_SET ? value : merger(existing, value, key)} ); } : function(value, key) { collection.set(key, value); }; for (var ii = 0; ii < iters.length; ii++) { iters[ii].forEach(mergeIntoMap); } }); } function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { var isNotSet = existing === NOT_SET; var step = keyPathIter.next(); if (step.done) { var existingValue = isNotSet ? notSetValue : existing; var newValue = updater(existingValue); return newValue === existingValue ? existing : newValue; } invariant( isNotSet || (existing && existing.set), 'invalid keyPath' ); var key = step.value; var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); var nextUpdated = updateInDeepMap( nextExisting, keyPathIter, notSetValue, updater ); return nextUpdated === nextExisting ? existing : nextUpdated === NOT_SET ? existing.remove(key) : (isNotSet ? emptyMap() : existing).set(key, nextUpdated); } function popCount(x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x = x + (x >> 8); x = x + (x >> 16); return x & 0x7f; } function setIn(array, idx, val, canEdit) { var newArray = canEdit ? array : arrCopy(array); newArray[idx] = val; return newArray; } function spliceIn(array, idx, val, canEdit) { var newLen = array.length + 1; if (canEdit && idx + 1 === newLen) { array[idx] = val; return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { newArray[ii] = val; after = -1; } else { newArray[ii] = array[ii + after]; } } return newArray; } function spliceOut(array, idx, canEdit) { var newLen = array.length - 1; if (canEdit && idx === newLen) { array.pop(); return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { after = 1; } newArray[ii] = array[ii + after]; } return newArray; } var MAX_ARRAY_MAP_SIZE = SIZE / 4; var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; createClass(List, IndexedCollection); // @pragma Construction function List(value) { var empty = emptyList(); if (value === null || value === undefined) { return empty; } if (isList(value)) { return value; } var iter = IndexedIterable(value); var size = iter.size; if (size === 0) { return empty; } assertNotInfinite(size); if (size > 0 && size < SIZE) { return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); } return empty.withMutations(function(list ) { list.setSize(size); iter.forEach(function(v, i) {return list.set(i, v)}); }); } List.of = function(/*...values*/) { return this(arguments); }; List.prototype.toString = function() { return this.__toString('List [', ']'); }; // @pragma Access List.prototype.get = function(index, notSetValue) { index = wrapIndex(this, index); if (index >= 0 && index < this.size) { index += this._origin; var node = listNodeFor(this, index); return node && node.array[index & MASK]; } return notSetValue; }; // @pragma Modification List.prototype.set = function(index, value) { return updateList(this, index, value); }; List.prototype.remove = function(index) { return !this.has(index) ? this : index === 0 ? this.shift() : index === this.size - 1 ? this.pop() : this.splice(index, 1); }; List.prototype.insert = function(index, value) { return this.splice(index, 0, value); }; List.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = this._origin = this._capacity = 0; this._level = SHIFT; this._root = this._tail = null; this.__hash = undefined; this.__altered = true; return this; } return emptyList(); }; List.prototype.push = function(/*...values*/) { var values = arguments; var oldSize = this.size; return this.withMutations(function(list ) { setListBounds(list, 0, oldSize + values.length); for (var ii = 0; ii < values.length; ii++) { list.set(oldSize + ii, values[ii]); } }); }; List.prototype.pop = function() { return setListBounds(this, 0, -1); }; List.prototype.unshift = function(/*...values*/) { var values = arguments; return this.withMutations(function(list ) { setListBounds(list, -values.length); for (var ii = 0; ii < values.length; ii++) { list.set(ii, values[ii]); } }); }; List.prototype.shift = function() { return setListBounds(this, 1); }; // @pragma Composition List.prototype.merge = function(/*...iters*/) { return mergeIntoListWith(this, undefined, arguments); }; List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, merger, iters); }; List.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoListWith(this, deepMerger, arguments); }; List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, deepMergerWith(merger), iters); }; List.prototype.setSize = function(size) { return setListBounds(this, 0, size); }; // @pragma Iteration List.prototype.slice = function(begin, end) { var size = this.size; if (wholeSlice(begin, end, size)) { return this; } return setListBounds( this, resolveBegin(begin, size), resolveEnd(end, size) ); }; List.prototype.__iterator = function(type, reverse) { var index = 0; var values = iterateList(this, reverse); return new Iterator(function() { var value = values(); return value === DONE ? iteratorDone() : iteratorValue(type, index++, value); }); }; List.prototype.__iterate = function(fn, reverse) { var index = 0; var values = iterateList(this, reverse); var value; while ((value = values()) !== DONE) { if (fn(value, index++, this) === false) { break; } } return index; }; List.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; return this; } return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); }; function isList(maybeList) { return !!(maybeList && maybeList[IS_LIST_SENTINEL]); } List.isList = isList; var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; var ListPrototype = List.prototype; ListPrototype[IS_LIST_SENTINEL] = true; ListPrototype[DELETE] = ListPrototype.remove; ListPrototype.setIn = MapPrototype.setIn; ListPrototype.deleteIn = ListPrototype.removeIn = MapPrototype.removeIn; ListPrototype.update = MapPrototype.update; ListPrototype.updateIn = MapPrototype.updateIn; ListPrototype.mergeIn = MapPrototype.mergeIn; ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; ListPrototype.withMutations = MapPrototype.withMutations; ListPrototype.asMutable = MapPrototype.asMutable; ListPrototype.asImmutable = MapPrototype.asImmutable; ListPrototype.wasAltered = MapPrototype.wasAltered; function VNode(array, ownerID) { this.array = array; this.ownerID = ownerID; } // TODO: seems like these methods are very similar VNode.prototype.removeBefore = function(ownerID, level, index) { if (index === level ? 1 << level : this.array.length === 0) { return this; } var originIndex = (index >>> level) & MASK; if (originIndex >= this.array.length) { return new VNode([], ownerID); } var removingFirst = originIndex === 0; var newChild; if (level > 0) { var oldChild = this.array[originIndex]; newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); if (newChild === oldChild && removingFirst) { return this; } } if (removingFirst && !newChild) { return this; } var editable = editableVNode(this, ownerID); if (!removingFirst) { for (var ii = 0; ii < originIndex; ii++) { editable.array[ii] = undefined; } } if (newChild) { editable.array[originIndex] = newChild; } return editable; }; VNode.prototype.removeAfter = function(ownerID, level, index) { if (index === (level ? 1 << level : 0) || this.array.length === 0) { return this; } var sizeIndex = ((index - 1) >>> level) & MASK; if (sizeIndex >= this.array.length) { return this; } var newChild; if (level > 0) { var oldChild = this.array[sizeIndex]; newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); if (newChild === oldChild && sizeIndex === this.array.length - 1) { return this; } } var editable = editableVNode(this, ownerID); editable.array.splice(sizeIndex + 1); if (newChild) { editable.array[sizeIndex] = newChild; } return editable; }; var DONE = {}; function iterateList(list, reverse) { var left = list._origin; var right = list._capacity; var tailPos = getTailOffset(right); var tail = list._tail; return iterateNodeOrLeaf(list._root, list._level, 0); function iterateNodeOrLeaf(node, level, offset) { return level === 0 ? iterateLeaf(node, offset) : iterateNode(node, level, offset); } function iterateLeaf(node, offset) { var array = offset === tailPos ? tail && tail.array : node && node.array; var from = offset > left ? 0 : left - offset; var to = right - offset; if (to > SIZE) { to = SIZE; } return function() { if (from === to) { return DONE; } var idx = reverse ? --to : from++; return array && array[idx]; }; } function iterateNode(node, level, offset) { var values; var array = node && node.array; var from = offset > left ? 0 : (left - offset) >> level; var to = ((right - offset) >> level) + 1; if (to > SIZE) { to = SIZE; } return function() { do { if (values) { var value = values(); if (value !== DONE) { return value; } values = null; } if (from === to) { return DONE; } var idx = reverse ? --to : from++; values = iterateNodeOrLeaf( array && array[idx], level - SHIFT, offset + (idx << level) ); } while (true); }; } } function makeList(origin, capacity, level, root, tail, ownerID, hash) { var list = Object.create(ListPrototype); list.size = capacity - origin; list._origin = origin; list._capacity = capacity; list._level = level; list._root = root; list._tail = tail; list.__ownerID = ownerID; list.__hash = hash; list.__altered = false; return list; } var EMPTY_LIST; function emptyList() { return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); } function updateList(list, index, value) { index = wrapIndex(list, index); if (index !== index) { return list; } if (index >= list.size || index < 0) { return list.withMutations(function(list ) { index < 0 ? setListBounds(list, index).set(0, value) : setListBounds(list, 0, index + 1).set(index, value); }); } index += list._origin; var newTail = list._tail; var newRoot = list._root; var didAlter = MakeRef(DID_ALTER); if (index >= getTailOffset(list._capacity)) { newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); } else { newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); } if (!didAlter.value) { return list; } if (list.__ownerID) { list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(list._origin, list._capacity, list._level, newRoot, newTail); } function updateVNode(node, ownerID, level, index, value, didAlter) { var idx = (index >>> level) & MASK; var nodeHas = node && idx < node.array.length; if (!nodeHas && value === undefined) { return node; } var newNode; if (level > 0) { var lowerNode = node && node.array[idx]; var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); if (newLowerNode === lowerNode) { return node; } newNode = editableVNode(node, ownerID); newNode.array[idx] = newLowerNode; return newNode; } if (nodeHas && node.array[idx] === value) { return node; } SetRef(didAlter); newNode = editableVNode(node, ownerID); if (value === undefined && idx === newNode.array.length - 1) { newNode.array.pop(); } else { newNode.array[idx] = value; } return newNode; } function editableVNode(node, ownerID) { if (ownerID && node && ownerID === node.ownerID) { return node; } return new VNode(node ? node.array.slice() : [], ownerID); } function listNodeFor(list, rawIndex) { if (rawIndex >= getTailOffset(list._capacity)) { return list._tail; } if (rawIndex < 1 << (list._level + SHIFT)) { var node = list._root; var level = list._level; while (node && level > 0) { node = node.array[(rawIndex >>> level) & MASK]; level -= SHIFT; } return node; } } function setListBounds(list, begin, end) { // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } var owner = list.__ownerID || new OwnerID(); var oldOrigin = list._origin; var oldCapacity = list._capacity; var newOrigin = oldOrigin + begin; var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; if (newOrigin === oldOrigin && newCapacity === oldCapacity) { return list; } // If it's going to end after it starts, it's empty. if (newOrigin >= newCapacity) { return list.clear(); } var newLevel = list._level; var newRoot = list._root; // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); newLevel += SHIFT; offsetShift += 1 << newLevel; } if (offsetShift) { newOrigin += offsetShift; oldOrigin += offsetShift; newCapacity += offsetShift; oldCapacity += offsetShift; } var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); newLevel += SHIFT; } // Locate or create the new tail. var oldTail = list._tail; var newTail = newTailOffset < oldTailOffset ? listNodeFor(list, newCapacity - 1) : newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; // Merge Tail into tree. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { newRoot = editableVNode(newRoot, owner); var node = newRoot; for (var level = newLevel; level > SHIFT; level -= SHIFT) { var idx = (oldTailOffset >>> level) & MASK; node = node.array[idx] = editableVNode(node.array[idx], owner); } node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } // If the size has been reduced, there's a chance the tail needs to be trimmed. if (newCapacity < oldCapacity) { newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } // If the new origin is within the tail, then we do not need a root. if (newOrigin >= newTailOffset) { newOrigin -= newTailOffset; newCapacity -= newTailOffset; newLevel = SHIFT; newRoot = null; newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); // Otherwise, if the root has been trimmed, garbage collect. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { offsetShift = 0; // Identify the new top root node of the subtree of the old root. while (newRoot) { var beginIndex = (newOrigin >>> newLevel) & MASK; if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { break; } if (beginIndex) { offsetShift += (1 << newLevel) * beginIndex; } newLevel -= SHIFT; newRoot = newRoot.array[beginIndex]; } // Trim the new sides of the new root. if (newRoot && newOrigin > oldOrigin) { newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } if (newRoot && newTailOffset < oldTailOffset) { newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); } if (offsetShift) { newOrigin -= offsetShift; newCapacity -= offsetShift; } } if (list.__ownerID) { list.size = newCapacity - newOrigin; list._origin = newOrigin; list._capacity = newCapacity; list._level = newLevel; list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); } function mergeIntoListWith(list, merger, iterables) { var iters = []; var maxSize = 0; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = IndexedIterable(value); if (iter.size > maxSize) { maxSize = iter.size; } if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } if (maxSize > list.size) { list = list.setSize(maxSize); } return mergeIntoCollectionWith(list, merger, iters); } function getTailOffset(size) { return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); } createClass(OrderedMap, Map); // @pragma Construction function OrderedMap(value) { return value === null || value === undefined ? emptyOrderedMap() : isOrderedMap(value) ? value : emptyOrderedMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } OrderedMap.of = function(/*...values*/) { return this(arguments); }; OrderedMap.prototype.toString = function() { return this.__toString('OrderedMap {', '}'); }; // @pragma Access OrderedMap.prototype.get = function(k, notSetValue) { var index = this._map.get(k); return index !== undefined ? this._list.get(index)[1] : notSetValue; }; // @pragma Modification OrderedMap.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._map.clear(); this._list.clear(); return this; } return emptyOrderedMap(); }; OrderedMap.prototype.set = function(k, v) { return updateOrderedMap(this, k, v); }; OrderedMap.prototype.remove = function(k) { return updateOrderedMap(this, k, NOT_SET); }; OrderedMap.prototype.wasAltered = function() { return this._map.wasAltered() || this._list.wasAltered(); }; OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._list.__iterate( function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, reverse ); }; OrderedMap.prototype.__iterator = function(type, reverse) { return this._list.fromEntrySeq().__iterator(type, reverse); }; OrderedMap.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); var newList = this._list.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; this._list = newList; return this; } return makeOrderedMap(newMap, newList, ownerID, this.__hash); }; function isOrderedMap(maybeOrderedMap) { return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } OrderedMap.isOrderedMap = isOrderedMap; OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; function makeOrderedMap(map, list, ownerID, hash) { var omap = Object.create(OrderedMap.prototype); omap.size = map ? map.size : 0; omap._map = map; omap._list = list; omap.__ownerID = ownerID; omap.__hash = hash; return omap; } var EMPTY_ORDERED_MAP; function emptyOrderedMap() { return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); } function updateOrderedMap(omap, k, v) { var map = omap._map; var list = omap._list; var i = map.get(k); var has = i !== undefined; var newMap; var newList; if (v === NOT_SET) { // removed if (!has) { return omap; } if (list.size >= SIZE && list.size >= map.size * 2) { newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); if (omap.__ownerID) { newMap.__ownerID = newList.__ownerID = omap.__ownerID; } } else { newMap = map.remove(k); newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); } } else { if (has) { if (v === list.get(i)[1]) { return omap; } newMap = map; newList = list.set(i, [k, v]); } else { newMap = map.set(k, list.size); newList = list.set(list.size, [k, v]); } } if (omap.__ownerID) { omap.size = newMap.size; omap._map = newMap; omap._list = newList; omap.__hash = undefined; return omap; } return makeOrderedMap(newMap, newList); } createClass(ToKeyedSequence, KeyedSeq); function ToKeyedSequence(indexed, useKeys) { this._iter = indexed; this._useKeys = useKeys; this.size = indexed.size; } ToKeyedSequence.prototype.get = function(key, notSetValue) { return this._iter.get(key, notSetValue); }; ToKeyedSequence.prototype.has = function(key) { return this._iter.has(key); }; ToKeyedSequence.prototype.valueSeq = function() { return this._iter.valueSeq(); }; ToKeyedSequence.prototype.reverse = function() {var this$0 = this; var reversedSequence = reverseFactory(this, true); if (!this._useKeys) { reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; } return reversedSequence; }; ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; var mappedSequence = mapFactory(this, mapper, context); if (!this._useKeys) { mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; } return mappedSequence; }; ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var ii; return this._iter.__iterate( this._useKeys ? function(v, k) {return fn(v, k, this$0)} : ((ii = reverse ? resolveSize(this) : 0), function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), reverse ); }; ToKeyedSequence.prototype.__iterator = function(type, reverse) { if (this._useKeys) { return this._iter.__iterator(type, reverse); } var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var ii = reverse ? resolveSize(this) : 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, reverse ? --ii : ii++, step.value, step); }); }; ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; createClass(ToIndexedSequence, IndexedSeq); function ToIndexedSequence(iter) { this._iter = iter; this.size = iter.size; } ToIndexedSequence.prototype.includes = function(value) { return this._iter.includes(value); }; ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); }; ToIndexedSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value, step) }); }; createClass(ToSetSequence, SetSeq); function ToSetSequence(iter) { this._iter = iter; this.size = iter.size; } ToSetSequence.prototype.has = function(key) { return this._iter.includes(key); }; ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); }; ToSetSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, step.value, step.value, step); }); }; createClass(FromEntriesSequence, KeyedSeq); function FromEntriesSequence(entries) { this._iter = entries; this.size = entries.size; } FromEntriesSequence.prototype.entrySeq = function() { return this._iter.toSeq(); }; FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(entry ) { // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return fn( indexedIterable ? entry.get(1) : entry[1], indexedIterable ? entry.get(0) : entry[0], this$0 ); } }, reverse); }; FromEntriesSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return iteratorValue( type, indexedIterable ? entry.get(0) : entry[0], indexedIterable ? entry.get(1) : entry[1], step ); } } }); }; ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; function flipFactory(iterable) { var flipSequence = makeSequence(iterable); flipSequence._iter = iterable; flipSequence.size = iterable.size; flipSequence.flip = function() {return iterable}; flipSequence.reverse = function () { var reversedSequence = iterable.reverse.apply(this); // super.reverse() reversedSequence.flip = function() {return iterable.reverse()}; return reversedSequence; }; flipSequence.has = function(key ) {return iterable.includes(key)}; flipSequence.includes = function(key ) {return iterable.has(key)}; flipSequence.cacheResult = cacheResultThrough; flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); }; flipSequence.__iteratorUncached = function(type, reverse) { if (type === ITERATE_ENTRIES) { var iterator = iterable.__iterator(type, reverse); return new Iterator(function() { var step = iterator.next(); if (!step.done) { var k = step.value[0]; step.value[0] = step.value[1]; step.value[1] = k; } return step; }); } return iterable.__iterator( type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse ); }; return flipSequence; } function mapFactory(iterable, mapper, context) { var mappedSequence = makeSequence(iterable); mappedSequence.size = iterable.size; mappedSequence.has = function(key ) {return iterable.has(key)}; mappedSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v === NOT_SET ? notSetValue : mapper.call(context, v, key, iterable); }; mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate( function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, reverse ); }; mappedSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); return new Iterator(function() { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; return iteratorValue( type, key, mapper.call(context, entry[1], key, iterable), step ); }); }; return mappedSequence; } function reverseFactory(iterable, useKeys) { var reversedSequence = makeSequence(iterable); reversedSequence._iter = iterable; reversedSequence.size = iterable.size; reversedSequence.reverse = function() {return iterable}; if (iterable.flip) { reversedSequence.flip = function () { var flipSequence = flipFactory(iterable); flipSequence.reverse = function() {return iterable.flip()}; return flipSequence; }; } reversedSequence.get = function(key, notSetValue) {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; reversedSequence.has = function(key ) {return iterable.has(useKeys ? key : -1 - key)}; reversedSequence.includes = function(value ) {return iterable.includes(value)}; reversedSequence.cacheResult = cacheResultThrough; reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); }; reversedSequence.__iterator = function(type, reverse) {return iterable.__iterator(type, !reverse)}; return reversedSequence; } function filterFactory(iterable, predicate, context, useKeys) { var filterSequence = makeSequence(iterable); if (useKeys) { filterSequence.has = function(key ) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && !!predicate.call(context, v, key, iterable); }; filterSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && predicate.call(context, v, key, iterable) ? v : notSetValue; }; } filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }, reverse); return iterations; }; filterSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterations = 0; return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; var value = entry[1]; if (predicate.call(context, value, key, iterable)) { return iteratorValue(type, useKeys ? key : iterations++, value, step); } } }); }; return filterSequence; } function countByFactory(iterable, grouper, context) { var groups = Map().asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), 0, function(a ) {return a + 1} ); }); return groups.asImmutable(); } function groupByFactory(iterable, grouper, context) { var isKeyedIter = isKeyed(iterable); var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} ); }); var coerce = iterableClass(iterable); return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); } function sliceFactory(iterable, begin, end, useKeys) { var originalSize = iterable.size; // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } if (wholeSlice(begin, end, originalSize)) { return iterable; } var resolvedBegin = resolveBegin(begin, originalSize); var resolvedEnd = resolveEnd(end, originalSize); // begin or end will be NaN if they were provided as negative numbers and // this iterable's size is unknown. In that case, cache first so there is // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); } // Note: resolvedEnd is undefined when the original sequence's length is // unknown and this slice did not supply an end and should contain all // elements after resolvedBegin. // In that case, resolvedSize will be NaN and sliceSize will remain undefined. var resolvedSize = resolvedEnd - resolvedBegin; var sliceSize; if (resolvedSize === resolvedSize) { sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(iterable); // If iterable.size is undefined, the size of the realized sliceSeq is // unknown at this point unless the number of items to slice is 0 sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; if (!useKeys && isSeq(iterable) && sliceSize >= 0) { sliceSeq.get = function (index, notSetValue) { index = wrapIndex(this, index); return index >= 0 && index < sliceSize ? iterable.get(index + resolvedBegin, notSetValue) : notSetValue; }; } sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; if (sliceSize === 0) { return 0; } if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var skipped = 0; var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k) { if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0) !== false && iterations !== sliceSize; } }); return iterations; }; sliceSeq.__iteratorUncached = function(type, reverse) { if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new Iterator(function() { while (skipped++ < resolvedBegin) { iterator.next(); } if (++iterations > sliceSize) { return iteratorDone(); } var step = iterator.next(); if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations - 1, undefined, step); } else { return iteratorValue(type, iterations - 1, step.value[1], step); } }); }; return sliceSeq; } function takeWhileFactory(iterable, predicate, context) { var takeSequence = makeSequence(iterable); takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; iterable.__iterate(function(v, k, c) {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} ); return iterations; }; takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterating = true; return new Iterator(function() { if (!iterating) { return iteratorDone(); } var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var k = entry[0]; var v = entry[1]; if (!predicate.call(context, v, k, this$0)) { iterating = false; return iteratorDone(); } return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return takeSequence; } function skipWhileFactory(iterable, predicate, context, useKeys) { var skipSequence = makeSequence(iterable); skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k, c) { if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }); return iterations; }; skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var skipping = true; var iterations = 0; return new Iterator(function() { var step, k, v; do { step = iterator.next(); if (step.done) { if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations++, undefined, step); } else { return iteratorValue(type, iterations++, step.value[1], step); } } var entry = step.value; k = entry[0]; v = entry[1]; skipping && (skipping = predicate.call(context, v, k, this$0)); } while (skipping); return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return skipSequence; } function concatFactory(iterable, values) { var isKeyedIterable = isKeyed(iterable); var iters = [iterable].concat(values).map(function(v ) { if (!isIterable(v)) { v = isKeyedIterable ? keyedSeqFromValue(v) : indexedSeqFromValue(Array.isArray(v) ? v : [v]); } else if (isKeyedIterable) { v = KeyedIterable(v); } return v; }).filter(function(v ) {return v.size !== 0}); if (iters.length === 0) { return iterable; } if (iters.length === 1) { var singleton = iters[0]; if (singleton === iterable || isKeyedIterable && isKeyed(singleton) || isIndexed(iterable) && isIndexed(singleton)) { return singleton; } } var concatSeq = new ArraySeq(iters); if (isKeyedIterable) { concatSeq = concatSeq.toKeyedSeq(); } else if (!isIndexed(iterable)) { concatSeq = concatSeq.toSetSeq(); } concatSeq = concatSeq.flatten(true); concatSeq.size = iters.reduce( function(sum, seq) { if (sum !== undefined) { var size = seq.size; if (size !== undefined) { return sum + size; } } }, 0 ); return concatSeq; } function flattenFactory(iterable, depth, useKeys) { var flatSequence = makeSequence(iterable); flatSequence.__iterateUncached = function(fn, reverse) { var iterations = 0; var stopped = false; function flatDeep(iter, currentDepth) {var this$0 = this; iter.__iterate(function(v, k) { if ((!depth || currentDepth < depth) && isIterable(v)) { flatDeep(v, currentDepth + 1); } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { stopped = true; } return !stopped; }, reverse); } flatDeep(iterable, 0); return iterations; }; flatSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(type, reverse); var stack = []; var iterations = 0; return new Iterator(function() { while (iterator) { var step = iterator.next(); if (step.done !== false) { iterator = stack.pop(); continue; } var v = step.value; if (type === ITERATE_ENTRIES) { v = v[1]; } if ((!depth || stack.length < depth) && isIterable(v)) { stack.push(iterator); iterator = v.__iterator(type, reverse); } else { return useKeys ? step : iteratorValue(type, iterations++, v, step); } } return iteratorDone(); }); }; return flatSequence; } function flatMapFactory(iterable, mapper, context) { var coerce = iterableClass(iterable); return iterable.toSeq().map( function(v, k) {return coerce(mapper.call(context, v, k, iterable))} ).flatten(true); } function interposeFactory(iterable, separator) { var interposedSequence = makeSequence(iterable); interposedSequence.size = iterable.size && iterable.size * 2 -1; interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k) {return (!iterations || fn(separator, iterations++, this$0) !== false) && fn(v, iterations++, this$0) !== false}, reverse ); return iterations; }; interposedSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(ITERATE_VALUES, reverse); var iterations = 0; var step; return new Iterator(function() { if (!step || iterations % 2) { step = iterator.next(); if (step.done) { return step; } } return iterations % 2 ? iteratorValue(type, iterations++, separator) : iteratorValue(type, iterations++, step.value, step); }); }; return interposedSequence; } function sortFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } var isKeyedIterable = isKeyed(iterable); var index = 0; var entries = iterable.toSeq().map( function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} ).toArray(); entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( isKeyedIterable ? function(v, i) { entries[i].length = 2; } : function(v, i) { entries[i] = v[1]; } ); return isKeyedIterable ? KeyedSeq(entries) : isIndexed(iterable) ? IndexedSeq(entries) : SetSeq(entries); } function maxFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } if (mapper) { var entry = iterable.toSeq() .map(function(v, k) {return [v, mapper(v, k, iterable)]}) .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); return entry && entry[0]; } else { return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); } } function maxCompare(comparator, a, b) { var comp = comparator(b, a); // b is considered the new max if the comparator declares them equal, but // they are not equal and b is in fact a nullish value. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; } function zipWithFactory(keyIter, zipper, iters) { var zipSequence = makeSequence(keyIter); zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); // Note: this a generic base implementation of __iterate in terms of // __iterator which may be more generically useful in the future. zipSequence.__iterate = function(fn, reverse) { /* generic: var iterator = this.__iterator(ITERATE_ENTRIES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { iterations++; if (fn(step.value[1], step.value[0], this) === false) { break; } } return iterations; */ // indexed: var iterator = this.__iterator(ITERATE_VALUES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } return iterations; }; zipSequence.__iteratorUncached = function(type, reverse) { var iterators = iters.map(function(i ) {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} ); var iterations = 0; var isDone = false; return new Iterator(function() { var steps; if (!isDone) { steps = iterators.map(function(i ) {return i.next()}); isDone = steps.some(function(s ) {return s.done}); } if (isDone) { return iteratorDone(); } return iteratorValue( type, iterations++, zipper.apply(null, steps.map(function(s ) {return s.value})) ); }); }; return zipSequence } // #pragma Helper Functions function reify(iter, seq) { return isSeq(iter) ? seq : iter.constructor(seq); } function validateEntry(entry) { if (entry !== Object(entry)) { throw new TypeError('Expected [K, V] tuple: ' + entry); } } function resolveSize(iter) { assertNotInfinite(iter.size); return ensureSize(iter); } function iterableClass(iterable) { return isKeyed(iterable) ? KeyedIterable : isIndexed(iterable) ? IndexedIterable : SetIterable; } function makeSequence(iterable) { return Object.create( ( isKeyed(iterable) ? KeyedSeq : isIndexed(iterable) ? IndexedSeq : SetSeq ).prototype ); } function cacheResultThrough() { if (this._iter.cacheResult) { this._iter.cacheResult(); this.size = this._iter.size; return this; } else { return Seq.prototype.cacheResult.call(this); } } function defaultComparator(a, b) { return a > b ? 1 : a < b ? -1 : 0; } function forceIterator(keyPath) { var iter = getIterator(keyPath); if (!iter) { // Array might not be iterable in this environment, so we need a fallback // to our wrapped type. if (!isArrayLike(keyPath)) { throw new TypeError('Expected iterable or array-like: ' + keyPath); } iter = getIterator(Iterable(keyPath)); } return iter; } createClass(Record, KeyedCollection); function Record(defaultValues, name) { var hasInitialized; var RecordType = function Record(values) { if (values instanceof RecordType) { return values; } if (!(this instanceof RecordType)) { return new RecordType(values); } if (!hasInitialized) { hasInitialized = true; var keys = Object.keys(defaultValues); setProps(RecordTypePrototype, keys); RecordTypePrototype.size = keys.length; RecordTypePrototype._name = name; RecordTypePrototype._keys = keys; RecordTypePrototype._defaultValues = defaultValues; } this._map = Map(values); }; var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); RecordTypePrototype.constructor = RecordType; return RecordType; } Record.prototype.toString = function() { return this.__toString(recordName(this) + ' {', '}'); }; // @pragma Access Record.prototype.has = function(k) { return this._defaultValues.hasOwnProperty(k); }; Record.prototype.get = function(k, notSetValue) { if (!this.has(k)) { return notSetValue; } var defaultVal = this._defaultValues[k]; return this._map ? this._map.get(k, defaultVal) : defaultVal; }; // @pragma Modification Record.prototype.clear = function() { if (this.__ownerID) { this._map && this._map.clear(); return this; } var RecordType = this.constructor; return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); }; Record.prototype.set = function(k, v) { if (!this.has(k)) { throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); } var newMap = this._map && this._map.set(k, v); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.remove = function(k) { if (!this.has(k)) { return this; } var newMap = this._map && this._map.remove(k); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.wasAltered = function() { return this._map.wasAltered(); }; Record.prototype.__iterator = function(type, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); }; Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); }; Record.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map && this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return makeRecord(this, newMap, ownerID); }; var RecordPrototype = Record.prototype; RecordPrototype[DELETE] = RecordPrototype.remove; RecordPrototype.deleteIn = RecordPrototype.removeIn = MapPrototype.removeIn; RecordPrototype.merge = MapPrototype.merge; RecordPrototype.mergeWith = MapPrototype.mergeWith; RecordPrototype.mergeIn = MapPrototype.mergeIn; RecordPrototype.mergeDeep = MapPrototype.mergeDeep; RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; RecordPrototype.setIn = MapPrototype.setIn; RecordPrototype.update = MapPrototype.update; RecordPrototype.updateIn = MapPrototype.updateIn; RecordPrototype.withMutations = MapPrototype.withMutations; RecordPrototype.asMutable = MapPrototype.asMutable; RecordPrototype.asImmutable = MapPrototype.asImmutable; function makeRecord(likeRecord, map, ownerID) { var record = Object.create(Object.getPrototypeOf(likeRecord)); record._map = map; record.__ownerID = ownerID; return record; } function recordName(record) { return record._name || record.constructor.name || 'Record'; } function setProps(prototype, names) { try { names.forEach(setProp.bind(undefined, prototype)); } catch (error) { // Object.defineProperty failed. Probably IE8. } } function setProp(prototype, name) { Object.defineProperty(prototype, name, { get: function() { return this.get(name); }, set: function(value) { invariant(this.__ownerID, 'Cannot set on an immutable record.'); this.set(name, value); } }); } createClass(Set, SetCollection); // @pragma Construction function Set(value) { return value === null || value === undefined ? emptySet() : isSet(value) && !isOrdered(value) ? value : emptySet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } Set.of = function(/*...values*/) { return this(arguments); }; Set.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; Set.prototype.toString = function() { return this.__toString('Set {', '}'); }; // @pragma Access Set.prototype.has = function(value) { return this._map.has(value); }; // @pragma Modification Set.prototype.add = function(value) { return updateSet(this, this._map.set(value, true)); }; Set.prototype.remove = function(value) { return updateSet(this, this._map.remove(value)); }; Set.prototype.clear = function() { return updateSet(this, this._map.clear()); }; // @pragma Composition Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && iters.length === 1) { return this.constructor(iters[0]); } return this.withMutations(function(set ) { for (var ii = 0; ii < iters.length; ii++) { SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); } }); }; Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (!iters.every(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (iters.some(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.merge = function() { return this.union.apply(this, arguments); }; Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return this.union.apply(this, iters); }; Set.prototype.sort = function(comparator) { // Late binding return OrderedSet(sortFactory(this, comparator)); }; Set.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedSet(sortFactory(this, comparator, mapper)); }; Set.prototype.wasAltered = function() { return this._map.wasAltered(); }; Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); }; Set.prototype.__iterator = function(type, reverse) { return this._map.map(function(_, k) {return k}).__iterator(type, reverse); }; Set.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return this.__make(newMap, ownerID); }; function isSet(maybeSet) { return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); } Set.isSet = isSet; var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; var SetPrototype = Set.prototype; SetPrototype[IS_SET_SENTINEL] = true; SetPrototype[DELETE] = SetPrototype.remove; SetPrototype.mergeDeep = SetPrototype.merge; SetPrototype.mergeDeepWith = SetPrototype.mergeWith; SetPrototype.withMutations = MapPrototype.withMutations; SetPrototype.asMutable = MapPrototype.asMutable; SetPrototype.asImmutable = MapPrototype.asImmutable; SetPrototype.__empty = emptySet; SetPrototype.__make = makeSet; function updateSet(set, newMap) { if (set.__ownerID) { set.size = newMap.size; set._map = newMap; return set; } return newMap === set._map ? set : newMap.size === 0 ? set.__empty() : set.__make(newMap); } function makeSet(map, ownerID) { var set = Object.create(SetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_SET; function emptySet() { return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); } createClass(OrderedSet, Set); // @pragma Construction function OrderedSet(value) { return value === null || value === undefined ? emptyOrderedSet() : isOrderedSet(value) ? value : emptyOrderedSet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } OrderedSet.of = function(/*...values*/) { return this(arguments); }; OrderedSet.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; OrderedSet.prototype.toString = function() { return this.__toString('OrderedSet {', '}'); }; function isOrderedSet(maybeOrderedSet) { return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } OrderedSet.isOrderedSet = isOrderedSet; var OrderedSetPrototype = OrderedSet.prototype; OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; OrderedSetPrototype.__empty = emptyOrderedSet; OrderedSetPrototype.__make = makeOrderedSet; function makeOrderedSet(map, ownerID) { var set = Object.create(OrderedSetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_ORDERED_SET; function emptyOrderedSet() { return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); } createClass(Stack, IndexedCollection); // @pragma Construction function Stack(value) { return value === null || value === undefined ? emptyStack() : isStack(value) ? value : emptyStack().unshiftAll(value); } Stack.of = function(/*...values*/) { return this(arguments); }; Stack.prototype.toString = function() { return this.__toString('Stack [', ']'); }; // @pragma Access Stack.prototype.get = function(index, notSetValue) { var head = this._head; index = wrapIndex(this, index); while (head && index--) { head = head.next; } return head ? head.value : notSetValue; }; Stack.prototype.peek = function() { return this._head && this._head.value; }; // @pragma Modification Stack.prototype.push = function(/*...values*/) { if (arguments.length === 0) { return this; } var newSize = this.size + arguments.length; var head = this._head; for (var ii = arguments.length - 1; ii >= 0; ii--) { head = { value: arguments[ii], next: head }; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pushAll = function(iter) { iter = IndexedIterable(iter); if (iter.size === 0) { return this; } assertNotInfinite(iter.size); var newSize = this.size; var head = this._head; iter.reverse().forEach(function(value ) { newSize++; head = { value: value, next: head }; }); if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pop = function() { return this.slice(1); }; Stack.prototype.unshift = function(/*...values*/) { return this.push.apply(this, arguments); }; Stack.prototype.unshiftAll = function(iter) { return this.pushAll(iter); }; Stack.prototype.shift = function() { return this.pop.apply(this, arguments); }; Stack.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._head = undefined; this.__hash = undefined; this.__altered = true; return this; } return emptyStack(); }; Stack.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } var resolvedBegin = resolveBegin(begin, this.size); var resolvedEnd = resolveEnd(end, this.size); if (resolvedEnd !== this.size) { // super.slice(begin, end); return IndexedCollection.prototype.slice.call(this, begin, end); } var newSize = this.size - resolvedBegin; var head = this._head; while (resolvedBegin--) { head = head.next; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; // @pragma Mutability Stack.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeStack(this.size, this._head, ownerID, this.__hash); }; // @pragma Iteration Stack.prototype.__iterate = function(fn, reverse) { if (reverse) { return this.reverse().__iterate(fn); } var iterations = 0; var node = this._head; while (node) { if (fn(node.value, iterations++, this) === false) { break; } node = node.next; } return iterations; }; Stack.prototype.__iterator = function(type, reverse) { if (reverse) { return this.reverse().__iterator(type); } var iterations = 0; var node = this._head; return new Iterator(function() { if (node) { var value = node.value; node = node.next; return iteratorValue(type, iterations++, value); } return iteratorDone(); }); }; function isStack(maybeStack) { return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); } Stack.isStack = isStack; var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; var StackPrototype = Stack.prototype; StackPrototype[IS_STACK_SENTINEL] = true; StackPrototype.withMutations = MapPrototype.withMutations; StackPrototype.asMutable = MapPrototype.asMutable; StackPrototype.asImmutable = MapPrototype.asImmutable; StackPrototype.wasAltered = MapPrototype.wasAltered; function makeStack(size, head, ownerID, hash) { var map = Object.create(StackPrototype); map.size = size; map._head = head; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_STACK; function emptyStack() { return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); } /** * Contributes additional methods to a constructor */ function mixin(ctor, methods) { var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor; } Iterable.Iterator = Iterator; mixin(Iterable, { // ### Conversion to other types toArray: function() { assertNotInfinite(this.size); var array = new Array(this.size || 0); this.valueSeq().__iterate(function(v, i) { array[i] = v; }); return array; }, toIndexedSeq: function() { return new ToIndexedSequence(this); }, toJS: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} ).__toJS(); }, toJSON: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} ).__toJS(); }, toKeyedSeq: function() { return new ToKeyedSequence(this, true); }, toMap: function() { // Use Late Binding here to solve the circular dependency. return Map(this.toKeyedSeq()); }, toObject: function() { assertNotInfinite(this.size); var object = {}; this.__iterate(function(v, k) { object[k] = v; }); return object; }, toOrderedMap: function() { // Use Late Binding here to solve the circular dependency. return OrderedMap(this.toKeyedSeq()); }, toOrderedSet: function() { // Use Late Binding here to solve the circular dependency. return OrderedSet(isKeyed(this) ? this.valueSeq() : this); }, toSet: function() { // Use Late Binding here to solve the circular dependency. return Set(isKeyed(this) ? this.valueSeq() : this); }, toSetSeq: function() { return new ToSetSequence(this); }, toSeq: function() { return isIndexed(this) ? this.toIndexedSeq() : isKeyed(this) ? this.toKeyedSeq() : this.toSetSeq(); }, toStack: function() { // Use Late Binding here to solve the circular dependency. return Stack(isKeyed(this) ? this.valueSeq() : this); }, toList: function() { // Use Late Binding here to solve the circular dependency. return List(isKeyed(this) ? this.valueSeq() : this); }, // ### Common JavaScript methods and properties toString: function() { return '[Iterable]'; }, __toString: function(head, tail) { if (this.size === 0) { return head + tail; } return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; }, // ### ES6 Collection methods (ES6 Array and Map) concat: function() {var values = SLICE$0.call(arguments, 0); return reify(this, concatFactory(this, values)); }, includes: function(searchValue) { return this.some(function(value ) {return is(value, searchValue)}); }, entries: function() { return this.__iterator(ITERATE_ENTRIES); }, every: function(predicate, context) { assertNotInfinite(this.size); var returnValue = true; this.__iterate(function(v, k, c) { if (!predicate.call(context, v, k, c)) { returnValue = false; return false; } }); return returnValue; }, filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, true)); }, find: function(predicate, context, notSetValue) { var entry = this.findEntry(predicate, context); return entry ? entry[1] : notSetValue; }, findEntry: function(predicate, context) { var found; this.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { found = [k, v]; return false; } }); return found; }, findLastEntry: function(predicate, context) { return this.toSeq().reverse().findEntry(predicate, context); }, forEach: function(sideEffect, context) { assertNotInfinite(this.size); return this.__iterate(context ? sideEffect.bind(context) : sideEffect); }, join: function(separator) { assertNotInfinite(this.size); separator = separator !== undefined ? '' + separator : ','; var joined = ''; var isFirst = true; this.__iterate(function(v ) { isFirst ? (isFirst = false) : (joined += separator); joined += v !== null && v !== undefined ? v.toString() : ''; }); return joined; }, keys: function() { return this.__iterator(ITERATE_KEYS); }, map: function(mapper, context) { return reify(this, mapFactory(this, mapper, context)); }, reduce: function(reducer, initialReduction, context) { assertNotInfinite(this.size); var reduction; var useFirst; if (arguments.length < 2) { useFirst = true; } else { reduction = initialReduction; } this.__iterate(function(v, k, c) { if (useFirst) { useFirst = false; reduction = v; } else { reduction = reducer.call(context, reduction, v, k, c); } }); return reduction; }, reduceRight: function(reducer, initialReduction, context) { var reversed = this.toKeyedSeq().reverse(); return reversed.reduce.apply(reversed, arguments); }, reverse: function() { return reify(this, reverseFactory(this, true)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, true)); }, some: function(predicate, context) { return !this.every(not(predicate), context); }, sort: function(comparator) { return reify(this, sortFactory(this, comparator)); }, values: function() { return this.__iterator(ITERATE_VALUES); }, // ### More sequential methods butLast: function() { return this.slice(0, -1); }, isEmpty: function() { return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); }, count: function(predicate, context) { return ensureSize( predicate ? this.toSeq().filter(predicate, context) : this ); }, countBy: function(grouper, context) { return countByFactory(this, grouper, context); }, equals: function(other) { return deepEqual(this, other); }, entrySeq: function() { var iterable = this; if (iterable._cache) { // We cache as an entries array, so we can just return the cache! return new ArraySeq(iterable._cache); } var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; return entriesSequence; }, filterNot: function(predicate, context) { return this.filter(not(predicate), context); }, findLast: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); }, first: function() { return this.find(returnTrue); }, flatMap: function(mapper, context) { return reify(this, flatMapFactory(this, mapper, context)); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, true)); }, fromEntrySeq: function() { return new FromEntriesSequence(this); }, get: function(searchKey, notSetValue) { return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); }, getIn: function(searchKeyPath, notSetValue) { var nested = this; // Note: in an ES6 environment, we would prefer: // for (var key of searchKeyPath) { var iter = forceIterator(searchKeyPath); var step; while (!(step = iter.next()).done) { var key = step.value; nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; if (nested === NOT_SET) { return notSetValue; } } return nested; }, groupBy: function(grouper, context) { return groupByFactory(this, grouper, context); }, has: function(searchKey) { return this.get(searchKey, NOT_SET) !== NOT_SET; }, hasIn: function(searchKeyPath) { return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; }, isSubset: function(iter) { iter = typeof iter.includes === 'function' ? iter : Iterable(iter); return this.every(function(value ) {return iter.includes(value)}); }, isSuperset: function(iter) { iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); return iter.isSubset(this); }, keySeq: function() { return this.toSeq().map(keyMapper).toIndexedSeq(); }, last: function() { return this.toSeq().reverse().first(); }, max: function(comparator) { return maxFactory(this, comparator); }, maxBy: function(mapper, comparator) { return maxFactory(this, comparator, mapper); }, min: function(comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); }, minBy: function(mapper, comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); }, rest: function() { return this.slice(1); }, skip: function(amount) { return this.slice(Math.max(0, amount)); }, skipLast: function(amount) { return reify(this, this.toSeq().reverse().skip(amount).reverse()); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, true)); }, skipUntil: function(predicate, context) { return this.skipWhile(not(predicate), context); }, sortBy: function(mapper, comparator) { return reify(this, sortFactory(this, comparator, mapper)); }, take: function(amount) { return this.slice(0, Math.max(0, amount)); }, takeLast: function(amount) { return reify(this, this.toSeq().reverse().take(amount).reverse()); }, takeWhile: function(predicate, context) { return reify(this, takeWhileFactory(this, predicate, context)); }, takeUntil: function(predicate, context) { return this.takeWhile(not(predicate), context); }, valueSeq: function() { return this.toIndexedSeq(); }, // ### Hashable Object hashCode: function() { return this.__hash || (this.__hash = hashIterable(this)); } // ### Internal // abstract __iterate(fn, reverse) // abstract __iterator(type, reverse) }); // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; var IterablePrototype = Iterable.prototype; IterablePrototype[IS_ITERABLE_SENTINEL] = true; IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; IterablePrototype.__toJS = IterablePrototype.toArray; IterablePrototype.__toStringMapper = quoteString; IterablePrototype.inspect = IterablePrototype.toSource = function() { return this.toString(); }; IterablePrototype.chain = IterablePrototype.flatMap; IterablePrototype.contains = IterablePrototype.includes; // Temporary warning about using length (function () { try { Object.defineProperty(IterablePrototype, 'length', { get: function () { if (!Iterable.noLengthWarning) { var stack; try { throw new Error(); } catch (error) { stack = error.stack; } if (stack.indexOf('_wrapObject') === -1) { console && console.warn && console.warn( 'iterable.length has been deprecated, '+ 'use iterable.size or iterable.count(). '+ 'This warning will become a silent error in a future version. ' + stack ); return this.size; } } } }); } catch (e) {} })(); mixin(KeyedIterable, { // ### More sequential methods flip: function() { return reify(this, flipFactory(this)); }, findKey: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLastKey: function(predicate, context) { return this.toSeq().reverse().findKey(predicate, context); }, keyOf: function(searchValue) { return this.findKey(function(value ) {return is(value, searchValue)}); }, lastKeyOf: function(searchValue) { return this.findLastKey(function(value ) {return is(value, searchValue)}); }, mapEntries: function(mapper, context) {var this$0 = this; var iterations = 0; return reify(this, this.toSeq().map( function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} ).fromEntrySeq() ); }, mapKeys: function(mapper, context) {var this$0 = this; return reify(this, this.toSeq().flip().map( function(k, v) {return mapper.call(context, k, v, this$0)} ).flip() ); } }); var KeyedIterablePrototype = KeyedIterable.prototype; KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; KeyedIterablePrototype.__toJS = IterablePrototype.toObject; KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; mixin(IndexedIterable, { // ### Conversion to other types toKeyedSeq: function() { return new ToKeyedSequence(this, false); }, // ### ES6 Collection methods (ES6 Array and Map) filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, false)); }, findIndex: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry ? entry[0] : -1; }, indexOf: function(searchValue) { var key = this.toKeyedSeq().keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function(searchValue) { var key = this.toKeyedSeq().reverse().keyOf(searchValue); return key === undefined ? -1 : key; // var index = // return this.toSeq().reverse().indexOf(searchValue); }, reverse: function() { return reify(this, reverseFactory(this, false)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, false)); }, splice: function(index, removeNum /*, ...values*/) { var numArgs = arguments.length; removeNum = Math.max(removeNum | 0, 0); if (numArgs === 0 || (numArgs === 2 && !removeNum)) { return this; } // If index is negative, it should resolve relative to the size of the // collection. However size may be expensive to compute if not cached, so // only call count() if the number is in fact negative. index = resolveBegin(index, index < 0 ? this.count() : this.size); var spliced = this.slice(0, index); return reify( this, numArgs === 1 ? spliced : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) ); }, // ### More collection methods findLastIndex: function(predicate, context) { var key = this.toKeyedSeq().findLastKey(predicate, context); return key === undefined ? -1 : key; }, first: function() { return this.get(0); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, false)); }, get: function(index, notSetValue) { index = wrapIndex(this, index); return (index < 0 || (this.size === Infinity || (this.size !== undefined && index > this.size))) ? notSetValue : this.find(function(_, key) {return key === index}, undefined, notSetValue); }, has: function(index) { index = wrapIndex(this, index); return index >= 0 && (this.size !== undefined ? this.size === Infinity || index < this.size : this.indexOf(index) !== -1 ); }, interpose: function(separator) { return reify(this, interposeFactory(this, separator)); }, interleave: function(/*...iterables*/) { var iterables = [this].concat(arrCopy(arguments)); var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); var interleaved = zipped.flatten(true); if (zipped.size) { interleaved.size = zipped.size * iterables.length; } return reify(this, interleaved); }, last: function() { return this.get(-1); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, false)); }, zip: function(/*, ...iterables */) { var iterables = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, iterables)); }, zipWith: function(zipper/*, ...iterables */) { var iterables = arrCopy(arguments); iterables[0] = this; return reify(this, zipWithFactory(this, zipper, iterables)); } }); IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; mixin(SetIterable, { // ### ES6 Collection methods (ES6 Array and Map) get: function(value, notSetValue) { return this.has(value) ? value : notSetValue; }, includes: function(value) { return this.has(value); }, // ### More sequential methods keySeq: function() { return this.valueSeq(); } }); SetIterable.prototype.has = IterablePrototype.includes; // Mixin subclasses mixin(KeyedSeq, KeyedIterable.prototype); mixin(IndexedSeq, IndexedIterable.prototype); mixin(SetSeq, SetIterable.prototype); mixin(KeyedCollection, KeyedIterable.prototype); mixin(IndexedCollection, IndexedIterable.prototype); mixin(SetCollection, SetIterable.prototype); // #pragma Helper functions function keyMapper(v, k) { return k; } function entryMapper(v, k) { return [k, v]; } function not(predicate) { return function() { return !predicate.apply(this, arguments); } } function neg(predicate) { return function() { return -predicate.apply(this, arguments); } } function quoteString(value) { return typeof value === 'string' ? JSON.stringify(value) : value; } function defaultZipper() { return arrCopy(arguments); } function defaultNegComparator(a, b) { return a < b ? 1 : a > b ? -1 : 0; } function hashIterable(iterable) { if (iterable.size === Infinity) { return 0; } var ordered = isOrdered(iterable); var keyed = isKeyed(iterable); var h = ordered ? 1 : 0; var size = iterable.__iterate( keyed ? ordered ? function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : ordered ? function(v ) { h = 31 * h + hash(v) | 0; } : function(v ) { h = h + hash(v) | 0; } ); return murmurHashOfSize(size, h); } function murmurHashOfSize(size, h) { h = imul(h, 0xCC9E2D51); h = imul(h << 15 | h >>> -15, 0x1B873593); h = imul(h << 13 | h >>> -13, 5); h = (h + 0xE6546B64 | 0) ^ size; h = imul(h ^ h >>> 16, 0x85EBCA6B); h = imul(h ^ h >>> 13, 0xC2B2AE35); h = smi(h ^ h >>> 16); return h; } function hashMerge(a, b) { return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int } var Immutable = { Iterable: Iterable, Seq: Seq, Collection: Collection, Map: Map, OrderedMap: OrderedMap, List: List, Stack: Stack, Set: Set, OrderedSet: OrderedSet, Record: Record, Range: Range, Repeat: Repeat, is: is, fromJS: fromJS }; return Immutable; })); }); var parseHTML_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = parseHTML; var fallback = function fallback(html) { var doc = document.implementation.createHTMLDocument(''); doc.documentElement.innerHTML = html; return doc; }; function parseHTML(html) { var doc; if (typeof DOMParser !== 'undefined') { var parser = new DOMParser(); doc = parser.parseFromString(html, 'text/html'); if (doc === null || doc.body === null) { doc = fallback(html); } } else { doc = fallback(html); } return doc.body; } }); _commonjsHelpers.unwrapExports(parseHTML_1); var convertFromHTML_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _parseHTML = interopRequireDefault(parseHTML_1); var _rangeSort = interopRequireDefault(rangeSort); /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the /src directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var NBSP = ' '; var SPACE = ' '; // Arbitrary max indent var MAX_DEPTH = 4; // used for replacing characters in HTML /* eslint-disable no-control-regex */ var REGEX_CR = new RegExp('\r', 'g'); var REGEX_LF = new RegExp('\n', 'g'); var REGEX_NBSP = new RegExp(NBSP, 'g'); var REGEX_BLOCK_DELIMITER = new RegExp('\r', 'g'); /* eslint-enable no-control-regex */ // Block tag flow is different because LIs do not have // a deterministic style ;_; var blockTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre']; var inlineTags = { b: 'BOLD', code: 'CODE', del: 'STRIKETHROUGH', em: 'ITALIC', i: 'ITALIC', s: 'STRIKETHROUGH', strike: 'STRIKETHROUGH', strong: 'BOLD', u: 'UNDERLINE' }; var handleMiddleware = function handleMiddleware(maybeMiddleware, base) { if (maybeMiddleware && maybeMiddleware.__isMiddleware === true) { return maybeMiddleware(base); } return maybeMiddleware; }; var defaultHTMLToBlock = function defaultHTMLToBlock(nodeName, node, lastList) { return undefined; }; var defaultHTMLToStyle = function defaultHTMLToStyle(nodeName, node, currentStyle) { return currentStyle; }; var defaultHTMLToEntity = function defaultHTMLToEntity(nodeName, node) { return undefined; }; var defaultTextToEntity = function defaultTextToEntity(text) { return []; }; var nullthrows = function nullthrows(x) { if (x != null) { return x; } throw new Error('Got unexpected null or undefined'); }; var sanitizeDraftText = function sanitizeDraftText(input) { return input.replace(REGEX_BLOCK_DELIMITER, ''); }; function getEmptyChunk() { return { text: '', inlines: [], entities: [], blocks: [] }; } function getWhitespaceChunk(inEntity) { var entities = new Array(1); if (inEntity) { entities[0] = inEntity; } return { text: SPACE, inlines: [(0, immutable$1.OrderedSet)()], entities: entities, blocks: [] }; } function getSoftNewlineChunk(block, depth) { var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : (0, immutable$1.Map)(); if (flat === true) { return { text: '\r', inlines: [(0, immutable$1.OrderedSet)()], entities: new Array(1), blocks: [{ type: block, data: data, depth: Math.max(0, Math.min(MAX_DEPTH, depth)) }], isNewline: true }; } return { text: '\n', inlines: [(0, immutable$1.OrderedSet)()], entities: new Array(1), blocks: [] }; } function getBlockDividerChunk(block, depth) { var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (0, immutable$1.Map)(); return { text: '\r', inlines: [(0, immutable$1.OrderedSet)()], entities: new Array(1), blocks: [{ type: block, data: data, depth: Math.max(0, Math.min(MAX_DEPTH, depth)) }] }; } function getBlockTypeForTag(tag, lastList) { switch (tag) { case 'h1': return 'header-one'; case 'h2': return 'header-two'; case 'h3': return 'header-three'; case 'h4': return 'header-four'; case 'h5': return 'header-five'; case 'h6': return 'header-six'; case 'li': if (lastList === 'ol') { return 'ordered-list-item'; } return 'unordered-list-item'; case 'blockquote': return 'blockquote'; case 'pre': return 'code-block'; case 'div': case 'p': return 'unstyled'; default: return null; } } function baseCheckBlockType(nodeName, node, lastList) { return getBlockTypeForTag(nodeName, lastList); } function processInlineTag(tag, node, currentStyle) { var styleToCheck = inlineTags[tag]; if (styleToCheck) { currentStyle = currentStyle.add(styleToCheck).toOrderedSet(); } else if (node instanceof HTMLElement) { var htmlElement = node; currentStyle = currentStyle.withMutations(function (style) { if (htmlElement.style.fontWeight === 'bold') { style.add('BOLD'); } if (htmlElement.style.fontStyle === 'italic') { style.add('ITALIC'); } if (htmlElement.style.textDecoration === 'underline') { style.add('UNDERLINE'); } if (htmlElement.style.textDecoration === 'line-through') { style.add('STRIKETHROUGH'); } }).toOrderedSet(); } return currentStyle; } function baseProcessInlineTag(tag, node) { var inlineStyles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (0, immutable$1.OrderedSet)(); return processInlineTag(tag, node, inlineStyles); } function joinChunks(A, B) { var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // Sometimes two blocks will touch in the DOM and we need to strip the // extra delimiter to preserve niceness. var firstInB = B.text.slice(0, 1); var lastInA = A.text.slice(-1); var adjacentDividers = lastInA === '\r' && firstInB === '\r'; var isJoiningBlocks = A.text !== '\r' && B.text !== '\r'; // when joining two full blocks like this we want to pop one divider var addingNewlineToEmptyBlock = A.text === '\r' && !A.isNewline && B.isNewline; // when joining a newline to an empty block we want to remove the newline if (adjacentDividers && (isJoiningBlocks || addingNewlineToEmptyBlock)) { A.text = A.text.slice(0, -1); A.inlines.pop(); A.entities.pop(); A.blocks.pop(); } // Kill whitespace after blocks if flat mode is on if (A.text.slice(-1) === '\r' && flat === true) { if (B.text === SPACE || B.text === '\n') { return A; } else if (firstInB === SPACE || firstInB === '\n') { B.text = B.text.slice(1); B.inlines.shift(); B.entities.shift(); } } var isNewline = A.text.length === 0 && B.isNewline; return { text: A.text + B.text, inlines: A.inlines.concat(B.inlines), entities: A.entities.concat(B.entities), blocks: A.blocks.concat(B.blocks), isNewline: isNewline }; } /* * Check to see if we have anything like

... to create * block tags from. If we do, we can use those and ignore
tags. If we * don't, we can treat
tags as meaningful (unstyled) blocks. */ function containsSemanticBlockMarkup(html) { return blockTags.some(function (tag) { return html.indexOf("<".concat(tag)) !== -1; }); } function genFragment(node, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, inEntity) { var nodeName = node.nodeName.toLowerCase(); var newBlock = false; var nextBlockType = 'unstyled'; // Base Case if (nodeName === '#text') { var text = node.textContent; if (text.trim() === '' && inBlock === null) { return getEmptyChunk(); } if (text.trim() === '' && inBlock !== 'code-block') { return getWhitespaceChunk(inEntity); } if (inBlock !== 'code-block') { // Can't use empty string because MSWord text = text.replace(REGEX_LF, SPACE); } var entities = Array(text.length).fill(inEntity); var offsetChange = 0; var textEntities = checkEntityText(text, createEntity, getEntity, mergeEntityData, replaceEntityData).sort(_rangeSort["default"]); textEntities.forEach(function (_ref) { var entity = _ref.entity, offset = _ref.offset, length = _ref.length, result = _ref.result; var adjustedOffset = offset + offsetChange; if (result === null || result === undefined) { result = text.substr(adjustedOffset, length); } var textArray = text.split(''); textArray.splice.bind(textArray, adjustedOffset, length).apply(textArray, result.split('')); text = textArray.join(''); entities.splice.bind(entities, adjustedOffset, length).apply(entities, Array(result.length).fill(entity)); offsetChange += result.length - length; }); return { text: text, inlines: Array(text.length).fill(inlineStyle), entities: entities, blocks: [] }; } // BR tags if (nodeName === 'br') { var _blockType = inBlock; if (_blockType === null) { // BR tag is at top level, treat it as an unstyled block return getSoftNewlineChunk('unstyled', depth, true); } return getSoftNewlineChunk(_blockType || 'unstyled', depth, options.flat); } var chunk = getEmptyChunk(); var newChunk = null; // Inline tags inlineStyle = processInlineTag(nodeName, node, inlineStyle); inlineStyle = processCustomInlineStyles(nodeName, node, inlineStyle); // Handle lists if (nodeName === 'ul' || nodeName === 'ol') { if (lastList) { depth += 1; } lastList = nodeName; inBlock = null; } // Block Tags var blockInfo = checkBlockType(nodeName, node, lastList, inBlock); var blockType; var blockDataMap; if (blockInfo === false) { return getEmptyChunk(); } blockInfo = blockInfo || {}; if (typeof blockInfo === 'string') { blockType = blockInfo; blockDataMap = (0, immutable$1.Map)(); } else { blockType = typeof blockInfo === 'string' ? blockInfo : blockInfo.type; blockDataMap = blockInfo.data ? (0, immutable$1.Map)(blockInfo.data) : (0, immutable$1.Map)(); } if (!inBlock && (fragmentBlockTags.indexOf(nodeName) !== -1 || blockType)) { chunk = getBlockDividerChunk(blockType || getBlockTypeForTag(nodeName, lastList), depth, blockDataMap); inBlock = blockType || getBlockTypeForTag(nodeName, lastList); newBlock = true; } else if (lastList && (inBlock === 'ordered-list-item' || inBlock === 'unordered-list-item') && nodeName === 'li') { var listItemBlockType = getBlockTypeForTag(nodeName, lastList); chunk = getBlockDividerChunk(listItemBlockType, depth); inBlock = listItemBlockType; newBlock = true; nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item'; } else if (inBlock && inBlock !== 'atomic' && blockType === 'atomic') { inBlock = blockType; newBlock = true; chunk = getSoftNewlineChunk(blockType, depth, true, // atomic blocks within non-atomic blocks must always be split out blockDataMap); } // Recurse through children var child = node.firstChild; // hack to allow conversion of atomic blocks from HTML (e.g.
). since metadata must be stored on an entity text // must exist for the entity to apply to. the way chunks are joined strips // whitespace at the end so it cannot be a space character. if (child == null && inEntity && (blockType === 'atomic' || inBlock === 'atomic')) { child = document.createTextNode('a'); } if (child != null) { nodeName = child.nodeName.toLowerCase(); } var entityId = null; while (child) { entityId = checkEntityNode(nodeName, child, createEntity, getEntity, mergeEntityData, replaceEntityData); newChunk = genFragment(child, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, entityId || inEntity); chunk = joinChunks(chunk, newChunk, options.flat); var sibling = child.nextSibling; // Put in a newline to break up blocks inside blocks if (sibling && fragmentBlockTags.indexOf(nodeName) >= 0 && inBlock) { var newBlockInfo = checkBlockType(nodeName, child, lastList, inBlock); var newBlockType = void 0; var newBlockData = void 0; if (newBlockInfo !== false) { newBlockInfo = newBlockInfo || {}; if (typeof newBlockInfo === 'string') { newBlockType = newBlockInfo; newBlockData = (0, immutable$1.Map)(); } else { newBlockType = newBlockInfo.type || getBlockTypeForTag(nodeName, lastList); newBlockData = newBlockInfo.data ? (0, immutable$1.Map)(newBlockInfo.data) : (0, immutable$1.Map)(); } chunk = joinChunks(chunk, getSoftNewlineChunk(newBlockType, depth, options.flat, newBlockData), options.flat); } } if (sibling) { nodeName = sibling.nodeName.toLowerCase(); } child = sibling; } if (newBlock) { chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, (0, immutable$1.Map)()), options.flat); } return chunk; } function getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder) { html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE); var safeBody = DOMBuilder(html); if (!safeBody) { return null; } // Sometimes we aren't dealing with content that contains nice semantic // tags. In this case, use divs to separate everything out into paragraphs // and hope for the best. var workingBlocks = containsSemanticBlockMarkup(html) ? blockTags.concat(['div']) : ['div']; // Start with -1 block depth to offset the fact that we are passing in a fake // UL block to sta rt with. var chunk = genFragment(safeBody, (0, immutable$1.OrderedSet)(), 'ul', null, workingBlocks, -1, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options); // join with previous block to prevent weirdness on paste if (chunk.text.indexOf('\r') === 0) { chunk = { text: chunk.text.slice(1), inlines: chunk.inlines.slice(1), entities: chunk.entities.slice(1), blocks: chunk.blocks }; } // Kill block delimiter at the end if (chunk.text.slice(-1) === '\r') { chunk.text = chunk.text.slice(0, -1); chunk.inlines = chunk.inlines.slice(0, -1); chunk.entities = chunk.entities.slice(0, -1); chunk.blocks.pop(); } // If we saw no block tags, put an unstyled one in if (chunk.blocks.length === 0) { chunk.blocks.push({ type: 'unstyled', data: (0, immutable$1.Map)(), depth: 0 }); } // Sometimes we start with text that isn't in a block, which is then // followed by blocks. Need to fix up the blocks to add in // an unstyled block for this content if (chunk.text.split('\r').length === chunk.blocks.length + 1) { chunk.blocks.unshift({ type: 'unstyled', data: (0, immutable$1.Map)(), depth: 0 }); } return chunk; } function convertFromHTMLtoContentBlocks(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder, generateKey) { // Be ABSOLUTELY SURE that the dom builder you pass hare won't execute // arbitrary code in whatever environment you're running this in. For an // example of how we try to do this in-browser, see getSafeBodyFromHTML. var chunk = getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder); if (chunk == null) { return []; } var start = 0; return chunk.text.split('\r').map(function (textBlock, blockIndex) { // Make absolutely certain that our text is acceptable. textBlock = sanitizeDraftText(textBlock); var end = start + textBlock.length; var inlines = nullthrows(chunk).inlines.slice(start, end); var entities = nullthrows(chunk).entities.slice(start, end); var characterList = (0, immutable$1.List)(inlines.map(function (style, entityIndex) { var data = { style: style, entity: null }; if (entities[entityIndex]) { data.entity = entities[entityIndex]; } return Draft.Draft.CharacterMetadata.create(data); })); start = end + 1; return new Draft.Draft.ContentBlock({ key: generateKey(), type: nullthrows(chunk).blocks[blockIndex].type, data: nullthrows(chunk).blocks[blockIndex].data, depth: nullthrows(chunk).blocks[blockIndex].depth, text: textBlock, characterList: characterList }); }); } var convertFromHTML = function convertFromHTML(_ref2) { var _ref2$htmlToStyle = _ref2.htmlToStyle, htmlToStyle = _ref2$htmlToStyle === void 0 ? defaultHTMLToStyle : _ref2$htmlToStyle, _ref2$htmlToEntity = _ref2.htmlToEntity, htmlToEntity = _ref2$htmlToEntity === void 0 ? defaultHTMLToEntity : _ref2$htmlToEntity, _ref2$textToEntity = _ref2.textToEntity, textToEntity = _ref2$textToEntity === void 0 ? defaultTextToEntity : _ref2$textToEntity, _ref2$htmlToBlock = _ref2.htmlToBlock, htmlToBlock = _ref2$htmlToBlock === void 0 ? defaultHTMLToBlock : _ref2$htmlToBlock; return function (html) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { flat: false }; var DOMBuilder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _parseHTML["default"]; var generateKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Draft.Draft.genKey; var contentState = Draft.Draft.ContentState.createFromText(''); var createEntityWithContentState = function createEntityWithContentState() { if (contentState.createEntity) { var _contentState; contentState = (_contentState = contentState).createEntity.apply(_contentState, arguments); return contentState.getLastCreatedEntityKey(); } return Draft.Draft.Entity.create.apply(Draft.Draft.Entity, arguments); }; var getEntityWithContentState = function getEntityWithContentState() { if (contentState.getEntity) { var _contentState2; return (_contentState2 = contentState).getEntity.apply(_contentState2, arguments); } return Draft.Draft.Entity.get.apply(Draft.Draft.Entity, arguments); }; var mergeEntityDataWithContentState = function mergeEntityDataWithContentState() { if (contentState.mergeEntityData) { var _contentState3; contentState = (_contentState3 = contentState).mergeEntityData.apply(_contentState3, arguments); return; } Draft.Draft.Entity.mergeData.apply(Draft.Draft.Entity, arguments); }; var replaceEntityDataWithContentState = function replaceEntityDataWithContentState() { if (contentState.replaceEntityData) { var _contentState4; contentState = (_contentState4 = contentState).replaceEntityData.apply(_contentState4, arguments); return; } Draft.Draft.Entity.replaceData.apply(Draft.Draft.Entity, arguments); }; var contentBlocks = convertFromHTMLtoContentBlocks(html, handleMiddleware(htmlToStyle, baseProcessInlineTag), handleMiddleware(htmlToEntity, defaultHTMLToEntity), handleMiddleware(textToEntity, defaultTextToEntity), handleMiddleware(htmlToBlock, baseCheckBlockType), createEntityWithContentState, getEntityWithContentState, mergeEntityDataWithContentState, replaceEntityDataWithContentState, options, DOMBuilder, generateKey); var blockMap = Draft.Draft.BlockMapBuilder.createFromArray(contentBlocks); var firstBlockKey = contentBlocks[0].getKey(); return contentState.merge({ blockMap: blockMap, selectionBefore: Draft.Draft.SelectionState.createEmpty(firstBlockKey), selectionAfter: Draft.Draft.SelectionState.createEmpty(firstBlockKey) }); }; }; var _default = function _default() { if (arguments.length >= 1 && typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') { return convertFromHTML({}).apply(void 0, arguments); } return convertFromHTML.apply(void 0, arguments); }; exports["default"] = _default; }); _commonjsHelpers.unwrapExports(convertFromHTML_1); var lib = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "convertToHTML", { enumerable: true, get: function get() { return _convertToHTML["default"]; } }); Object.defineProperty(exports, "convertFromHTML", { enumerable: true, get: function get() { return _convertFromHTML["default"]; } }); Object.defineProperty(exports, "parseHTML", { enumerable: true, get: function get() { return _parseHTML["default"]; } }); var _convertToHTML = interopRequireDefault(convertToHTML_1); var _convertFromHTML = interopRequireDefault(convertFromHTML_1); var _parseHTML = interopRequireDefault(parseHTML_1); }); _commonjsHelpers.unwrapExports(lib); var configs = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.getFromHTMLConfig = exports.getToHTMLConfig = exports.blocks = exports.getHexColor = exports.defaultFontFamilies = exports.namedColors = undefined; var _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; }; var _react2 = _interopRequireDefault(React__default); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var namedColors = exports.namedColors = { "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a", "burlywood": "#deb887", "cadetblue": "#5f9ea0", "chartreuse": "#7fff00", "chocolate": "#d2691e", "coral": "#ff7f50", "cornflowerblue": "#6495ed", "cornsilk": "#fff8dc", "crimson": "#dc143c", "cyan": "#00ffff", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgoldenrod": "#b8860b", "darkgray": "#a9a9a9", "darkgreen": "#006400", "darkkhaki": "#bdb76b", "darkmagenta": "#8b008b", "darkolivegreen": "#556b2f", "darkorange": "#ff8c00", "darkorchid": "#9932cc", "darkred": "#8b0000", "darksalmon": "#e9967a", "darkseagreen": "#8fbc8f", "darkslateblue": "#483d8b", "darkslategray": "#2f4f4f", "darkturquoise": "#00ced1", "darkviolet": "#9400d3", "deeppink": "#ff1493", "deepskyblue": "#00bfff", "dimgray": "#696969", "dodgerblue": "#1e90ff", "firebrick": "#b22222", "floralwhite": "#fffaf0", "forestgreen": "#228b22", "fuchsia": "#ff00ff", "gainsboro": "#dcdcdc", "ghostwhite": "#f8f8ff", "gold": "#ffd700", "goldenrod": "#daa520", "gray": "#808080", "green": "#008000", "greenyellow": "#adff2f", "honeydew": "#f0fff0", "hotpink": "#ff69b4", "indianred ": "#cd5c5c", "indigo": "#4b0082", "ivory": "#fffff0", "khaki": "#f0e68c", "lavender": "#e6e6fa", "lavenderblush": "#fff0f5", "lawngreen": "#7cfc00", "lemonchiffon": "#fffacd", "lightblue": "#add8e6", "lightcoral": "#f08080", "lightcyan": "#e0ffff", "lightgoldenrodyellow": "#fafad2", "lightgrey": "#d3d3d3", "lightgreen": "#90ee90", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightseagreen": "#20b2aa", "lightskyblue": "#87cefa", "lightslategray": "#778899", "lightsteelblue": "#b0c4de", "lightyellow": "#ffffe0", "lime": "#00ff00", "limegreen": "#32cd32", "linen": "#faf0e6", "magenta": "#ff00ff", "maroon": "#800000", "mediumaquamarine": "#66cdaa", "mediumblue": "#0000cd", "mediumorchid": "#ba55d3", "mediumpurple": "#9370d8", "mediumseagreen": "#3cb371", "mediumslateblue": "#7b68ee", "mediumspringgreen": "#00fa9a", "mediumturquoise": "#48d1cc", "mediumvioletred": "#c71585", "midnightblue": "#191970", "mintcream": "#f5fffa", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "navy": "#000080", "oldlace": "#fdf5e6", "olive": "#808000", "olivedrab": "#6b8e23", "orange": "#ffa500", "orangered": "#ff4500", "orchid": "#da70d6", "palegoldenrod": "#eee8aa", "palegreen": "#98fb98", "paleturquoise": "#afeeee", "palevioletred": "#d87093", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "peru": "#cd853f", "pink": "#ffc0cb", "plum": "#dda0dd", "powderblue": "#b0e0e6", "purple": "#800080", "rebeccapurple": "#663399", "red": "#ff0000", "rosybrown": "#bc8f8f", "royalblue": "#4169e1", "saddlebrown": "#8b4513", "salmon": "#fa8072", "sandybrown": "#f4a460", "seagreen": "#2e8b57", "seashell": "#fff5ee", "sienna": "#a0522d", "silver": "#c0c0c0", "skyblue": "#87ceeb", "slateblue": "#6a5acd", "slategray": "#708090", "snow": "#fffafa", "springgreen": "#00ff7f", "steelblue": "#4682b4", "tan": "#d2b48c", "teal": "#008080", "thistle": "#d8bfd8", "tomato": "#ff6347", "turquoise": "#40e0d0", "violet": "#ee82ee", "wheat": "#f5deb3", "white": "#ffffff", "whitesmoke": "#f5f5f5", "yellow": "#ffff00", "yellowgreen": "#9acd32" }; var getStyleValue = function getStyleValue(style) { return style.split('-')[1]; }; var defaultUnitExportFn = function defaultUnitExportFn(unit) { return unit + 'px'; }; var defaultUnitImportFn = function defaultUnitImportFn(unit) { return unit.replace('px', ''); }; var ignoredNodeAttributes = ['style']; var ignoredEntityNodeAttributes = ['style', 'href', 'target', 'alt', 'title', 'id', 'controls', 'autoplay', 'loop', 'poster']; var spreadNodeAttributes = function spreadNodeAttributes(attributesObject) { return Object.keys(attributesObject).reduce(function (attributeString, attributeName) { return attributeString + " " + attributeName + "=\"" + attributesObject[attributeName] + "\""; }, '').replace(/^\s$/, ''); }; var defaultFontFamilies = exports.defaultFontFamilies = [{ name: 'Araial', family: 'Arial, Helvetica, sans-serif' }, { name: 'Georgia', family: 'Georgia, serif' }, { name: 'Impact', family: 'Impact, serif' }, { name: 'Monospace', family: '"Courier New", Courier, monospace' }, { name: 'Tahoma', family: "tahoma, arial, 'Hiragino Sans GB', 宋体, sans-serif" }]; var getHexColor = exports.getHexColor = function getHexColor(color) { color = color.replace('color:', '').replace(';', '').replace(' ', ''); if (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(color)) { return color; } else if (namedColors[color]) { return namedColors[color]; } else if (color.indexOf('rgb') === 0) { var rgbArray = color.split(','); var convertedColor = rgbArray.length < 3 ? null : '#' + [rgbArray[0], rgbArray[1], rgbArray[2]].map(function (x) { var hex = parseInt(x.replace(/\D/g, ''), 10).toString(16); return hex.length === 1 ? '0' + hex : hex; }).join(''); return (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(convertedColor) ? convertedColor : null ); } else { return null; } }; var blocks = exports.blocks = { 'header-one': 'h1', 'header-two': 'h2', 'header-three': 'h3', 'header-four': 'h4', 'header-five': 'h5', 'header-six': 'h6', 'unstyled': 'p', 'blockquote': 'blockquote' }; var blockTypes = Object.keys(blocks); var blockNames = blockTypes.map(function (key) { return blocks[key]; }); var convertAtomicBlock = function convertAtomicBlock(block, contentState, blockNodeAttributes) { if (!block || !block.key) { return _react2.default.createElement("p", null); } var contentBlock = contentState.getBlockForKey(block.key); var className = blockNodeAttributes.class, nodeAttrAsProps = _objectWithoutProperties(blockNodeAttributes, ["class"]); nodeAttrAsProps.className = className; if (!contentBlock) { return _react2.default.createElement("p", null); } var entityKey = contentBlock.getEntityAt(0); if (!entityKey) { return _react2.default.createElement("p", null); } var entity = contentState.getEntity(entityKey); var mediaType = entity.getType().toLowerCase(); var _block$data = block.data, float = _block$data.float, alignment = _block$data.alignment; var _entity$getData = entity.getData(), url = _entity$getData.url, link = _entity$getData.link, link_target = _entity$getData.link_target, width = _entity$getData.width, height = _entity$getData.height, meta = _entity$getData.meta; if (mediaType === 'image') { var imageWrapStyle = {}; var styledClassName = ''; if (float) { imageWrapStyle.float = float; styledClassName += ' float-' + float; } else if (alignment) { imageWrapStyle.textAlign = alignment; styledClassName += ' align-' + alignment; } if (link) { return _react2.default.createElement( "div", { className: "media-wrap image-wrap" + styledClassName, style: imageWrapStyle }, _react2.default.createElement( "a", { style: { display: 'inline-block' }, href: link, target: link_target }, _react2.default.createElement("img", _extends({}, nodeAttrAsProps, meta, { src: url, width: width, height: height, style: { width: width, height: height } })) ) ); } else { return _react2.default.createElement( "div", { className: "media-wrap image-wrap" + styledClassName, style: imageWrapStyle }, _react2.default.createElement("img", _extends({}, nodeAttrAsProps, meta, { src: url, width: width, height: height, style: { width: width, height: height } })) ); } } else if (mediaType === 'audio') { return _react2.default.createElement( "div", { className: "media-wrap audio-wrap" }, _react2.default.createElement("audio", _extends({ controls: true }, nodeAttrAsProps, meta, { src: url })) ); } else if (mediaType === 'video') { return _react2.default.createElement( "div", { className: "media-wrap video-wrap" }, _react2.default.createElement("video", _extends({ controls: true }, nodeAttrAsProps, meta, { src: url, width: width, height: height })) ); } else if (mediaType === 'embed') { return _react2.default.createElement( "div", { className: "media-wrap embed-wrap" }, _react2.default.createElement("div", { dangerouslySetInnerHTML: { __html: url } }) ); } else if (mediaType === 'hr') { return _react2.default.createElement("hr", null); } else { return _react2.default.createElement("p", null); } }; var entityToHTML = function entityToHTML(options) { return function (entity, originalText) { var entityExportFn = options.entityExportFn; var entityType = entity.type.toLowerCase(); if (entityExportFn) { var customOutput = entityExportFn(entity, originalText); if (customOutput) { return customOutput; } } if (entityType === 'link') { var _ref = entity.data.nodeAttributes || {}, className = _ref.class, nodeAttrAsProps = _objectWithoutProperties(_ref, ["class"]); nodeAttrAsProps.className = className; return _react2.default.createElement("a", _extends({ href: entity.data.href, target: entity.data.target }, nodeAttrAsProps)); } }; }; var styleToHTML = function styleToHTML(options) { return function (style) { var unitExportFn = options.unitExportFn || defaultUnitExportFn; if (options.styleExportFn) { var customOutput = options.styleExportFn(style, options); if (customOutput) { return customOutput; } } style = style.toLowerCase(); if (style === 'strikethrough') { return _react2.default.createElement("span", { style: { textDecoration: 'line-through' } }); } else if (style === 'superscript') { return _react2.default.createElement("sup", null); } else if (style === 'subscript') { return _react2.default.createElement("sub", null); } else if (style.indexOf('color-') === 0) { return _react2.default.createElement("span", { style: { color: '#' + getStyleValue(style) } }); } else if (style.indexOf('bgcolor-') === 0) { return _react2.default.createElement("span", { style: { backgroundColor: '#' + getStyleValue(style) } }); } else if (style.indexOf('fontsize-') === 0) { return _react2.default.createElement("span", { style: { fontSize: unitExportFn(getStyleValue(style), 'font-size', 'html') } }); } else if (style.indexOf('lineheight-') === 0) { return _react2.default.createElement("span", { style: { lineHeight: unitExportFn(getStyleValue(style), 'line-height', 'html') } }); } else if (style.indexOf('letterspacing-') === 0) { return _react2.default.createElement("span", { style: { letterSpacing: unitExportFn(getStyleValue(style), 'letter-spacing', 'html') } }); } else if (style.indexOf('fontfamily-') === 0) { var fontFamily = options.fontFamilies.find(function (item) { return item.name.toLowerCase() === getStyleValue(style); }); if (!fontFamily) return; return _react2.default.createElement("span", { style: { fontFamily: fontFamily.family } }); } }; }; var blockToHTML = function blockToHTML(options) { return function (block) { var blockExportFn = options.blockExportFn, contentState = options.contentState; if (blockExportFn) { var customOutput = blockExportFn(contentState, block); if (customOutput) { return customOutput; } } var blockStyle = ''; var blockType = block.type.toLowerCase(); var _block$data2 = block.data, textAlign = _block$data2.textAlign, textIndent = _block$data2.textIndent, _block$data2$nodeAttr = _block$data2.nodeAttributes, nodeAttributes = _block$data2$nodeAttr === undefined ? {} : _block$data2$nodeAttr; var attributeString = spreadNodeAttributes(nodeAttributes); if (textAlign || textIndent) { blockStyle = ' style="'; if (textAlign) { blockStyle += "text-align:" + textAlign + ";"; } if (textIndent && !isNaN(textIndent) && textIndent > 0) { blockStyle += "text-indent:" + textIndent * 2 + "em;"; } blockStyle += '"'; } if (blockType === 'atomic') { return convertAtomicBlock(block, contentState, nodeAttributes); } else if (blockType === 'code-block') { var previousBlock = contentState.getBlockBefore(block.key); var nextBlock = contentState.getBlockAfter(block.key); var previousBlockType = previousBlock && previousBlock.getType(); var nextBlockType = nextBlock && nextBlock.getType(); var start = ''; var end = ''; if (previousBlockType !== 'code-block') { start = ""; } else { start = ''; } if (nextBlockType !== 'code-block') { end = ''; } else { end = '
'; } return { start: start, end: end }; } else if (blocks[blockType]) { return { start: "<" + blocks[blockType] + blockStyle + attributeString + ">", end: "" }; } else if (blockType === 'unordered-list-item') { return { start: "", end: '', nest: _react2.default.createElement("ul", null) }; } else if (blockType === 'ordered-list-item') { return { start: "", end: '', nest: _react2.default.createElement("ol", null) }; } }; }; var htmlToStyle = function htmlToStyle(options, source) { return function (nodeName, node, currentStyle) { if (!node || !node.style) { return currentStyle; } var unitImportFn = options.unitImportFn || defaultUnitImportFn; var newStyle = currentStyle; [].forEach.call(node.style, function (style) { if (nodeName === 'span' && style === 'color') { var color = getHexColor(node.style.color); newStyle = color ? newStyle.add('COLOR-' + color.replace('#', '').toUpperCase()) : newStyle; } else if (nodeName === 'span' && style === 'background-color') { var _color = getHexColor(node.style.backgroundColor); newStyle = _color ? newStyle.add('BGCOLOR-' + _color.replace('#', '').toUpperCase()) : newStyle; } else if (nodeName === 'span' && style === 'font-size') { newStyle = newStyle.add('FONTSIZE-' + unitImportFn(node.style.fontSize, 'font-size', source)); } else if (nodeName === 'span' && style === 'line-height' && !isNaN(parseFloat(node.style.lineHeight, 10))) { newStyle = newStyle.add('LINEHEIGHT-' + unitImportFn(node.style.lineHeight, 'line-height', source)); } else if (nodeName === 'span' && style === 'letter-spacing' && !isNaN(parseFloat(node.style.letterSpacing, 10))) { newStyle = newStyle.add('LETTERSPACING-' + unitImportFn(node.style.letterSpacing, 'letter-spacing', source)); } else if (nodeName === 'span' && style === 'text-decoration') { if (node.style.textDecoration === 'line-through') { newStyle = newStyle.add('STRIKETHROUGH'); } else if (node.style.textDecoration === 'underline') { newStyle = newStyle.add('UNDERLINE'); } } else if (nodeName === 'span' && style === 'font-family') { var fontFamily = options.fontFamilies.find(function (item) { return item.family.toLowerCase() === node.style.fontFamily.toLowerCase(); }); if (!fontFamily) return; newStyle = newStyle.add('FONTFAMILY-' + fontFamily.name.toUpperCase()); } }); if (nodeName === 'sup') { newStyle = newStyle.add('SUPERSCRIPT'); } else if (nodeName === 'sub') { newStyle = newStyle.add('SUBSCRIPT'); } options.styleImportFn && (newStyle = options.styleImportFn(nodeName, node, newStyle, source) || newStyle); return newStyle; }; }; var htmlToEntity = function htmlToEntity(options, source) { return function (nodeName, node, createEntity) { if (options && options.entityImportFn) { var customInput = options.entityImportFn(nodeName, node, createEntity, source); if (customInput) { return customInput; } } nodeName = nodeName.toLowerCase(); var alt = node.alt, title = node.title, id = node.id, controls = node.controls, autoplay = node.autoplay, loop = node.loop, poster = node.poster; var meta = {}; var nodeAttributes = {}; id && (meta.id = id); alt && (meta.alt = alt); title && (meta.title = title); controls && (meta.controls = controls); autoplay && (meta.autoPlay = autoplay); loop && (meta.loop = loop); poster && (meta.poster = poster); node.attributes && Object.keys(node.attributes).forEach(function (key) { var attr = node.attributes[key]; ignoredEntityNodeAttributes.indexOf(attr.name) === -1 && (nodeAttributes[attr.name] = attr.value); }); if (nodeName === 'a' && !node.querySelectorAll('img').length) { var href = node.getAttribute('href'); var _target = node.getAttribute('target'); return createEntity('LINK', 'MUTABLE', { href: href, target: _target, nodeAttributes: nodeAttributes }); } else if (nodeName === 'audio') { return createEntity('AUDIO', 'IMMUTABLE', { url: node.getAttribute('src'), meta: meta, nodeAttributes: nodeAttributes }); } else if (nodeName === 'video') { return createEntity('VIDEO', 'IMMUTABLE', { url: node.getAttribute('src'), meta: meta, nodeAttributes: nodeAttributes }); } else if (nodeName === 'img') { var parentNode = node.parentNode; var entityData = { meta: meta }; var _node$style = node.style, width = _node$style.width, height = _node$style.height; entityData.url = node.getAttribute('src'); width && (entityData.width = width); height && (entityData.height = height); if (parentNode.nodeName.toLowerCase() === 'a') { entityData.link = parentNode.getAttribute('href'); entityData.link_target = parentNode.getAttribute('target'); } return createEntity('IMAGE', 'IMMUTABLE', entityData); } else if (nodeName === 'hr') { return createEntity('HR', 'IMMUTABLE', {}); } else if (node.parentNode && node.parentNode.classList.contains('embed-wrap')) { var embedContent = node.innerHTML || node.outerHTML; if (embedContent) { return createEntity('EMBED', 'IMMUTABLE', { url: embedContent }); } } }; }; var htmlToBlock = function htmlToBlock(options, source) { return function (nodeName, node) { if (options && options.blockImportFn) { var customInput = options.blockImportFn(nodeName, node, source); if (customInput) { return customInput; } } var nodeAttributes = {}; var nodeStyle = node.style || {}; node.attributes && Object.keys(node.attributes).forEach(function (key) { var attr = node.attributes[key]; ignoredNodeAttributes.indexOf(attr.name) === -1 && (nodeAttributes[attr.name] = attr.value); }); if (node.classList && node.classList.contains('media-wrap')) { return { type: 'atomic', data: { nodeAttributes: nodeAttributes, float: nodeStyle.float, alignment: nodeStyle.textAlign } }; } else if (nodeName === 'img') { return { type: 'atomic', data: { nodeAttributes: nodeAttributes, float: nodeStyle.float, alignment: nodeStyle.textAlign } }; } else if (nodeName === 'hr') { return { type: 'atomic', data: { nodeAttributes: nodeAttributes } }; } else if (nodeName === 'pre') { node.innerHTML = node.innerHTML.replace(//g, '').replace(/<\/code>/g, ''); return { type: 'code-block', data: { nodeAttributes: nodeAttributes } }; } else if (blockNames.indexOf(nodeName) !== -1) { var blockData = { nodeAttributes: nodeAttributes }; if (nodeStyle.textAlign) { blockData.textAlign = nodeStyle.textAlign; } if (nodeStyle.textIndent) { blockData.textIndent = /^\d+em$/.test(nodeStyle.textIndent) ? Math.ceil(parseInt(nodeStyle.textIndent, 10) / 2) : 1; } return { type: blockTypes[blockNames.indexOf(nodeName)], data: blockData }; } }; }; var getToHTMLConfig = exports.getToHTMLConfig = function getToHTMLConfig(options) { return { styleToHTML: styleToHTML(options), entityToHTML: entityToHTML(options), blockToHTML: blockToHTML(options) }; }; var getFromHTMLConfig = exports.getFromHTMLConfig = function getFromHTMLConfig(options) { var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'unknow'; return { htmlToStyle: htmlToStyle(options, source), htmlToEntity: htmlToEntity(options, source), htmlToBlock: htmlToBlock(options, source) }; }; }); _commonjsHelpers.unwrapExports(configs); var configs_1 = configs.getFromHTMLConfig; var configs_2 = configs.getToHTMLConfig; var configs_3 = configs.blocks; var configs_4 = configs.getHexColor; var configs_5 = configs.defaultFontFamilies; var configs_6 = configs.namedColors; var dist = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.convertRawToEditorState = exports.convertEditorStateToRaw = exports.convertHTMLToEditorState = exports.convertEditorStateToHTML = exports.convertHTMLToRaw = exports.convertRawToHTML = undefined; var _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; }; var defaultConvertOptions = { fontFamilies: configs.defaultFontFamilies }; var convertRawToHTML = exports.convertRawToHTML = function convertRawToHTML(rawContent, options) { options = _extends({}, defaultConvertOptions, options); try { var contentState = (0, Draft.Draft.convertFromRaw)(rawContent); options.contentState = contentState; return (0, lib.convertToHTML)((0, configs.getToHTMLConfig)(options))(contentState); } catch (error) { console.warn(error); return ''; } }; var convertHTMLToRaw = exports.convertHTMLToRaw = function convertHTMLToRaw(HTMLString, options, source) { options = _extends({}, defaultConvertOptions, options); try { var contentState = (0, lib.convertFromHTML)((0, configs.getFromHTMLConfig)(options, source))(HTMLString); return (0, Draft.Draft.convertToRaw)(contentState); } catch (error) { console.warn(error); return {}; } }; var convertEditorStateToHTML = exports.convertEditorStateToHTML = function convertEditorStateToHTML(editorState, options) { options = _extends({}, defaultConvertOptions, options); try { var contentState = editorState.getCurrentContent(); options.contentState = contentState; return (0, lib.convertToHTML)((0, configs.getToHTMLConfig)(options))(contentState); } catch (error) { console.warn(error); return ''; } }; var convertHTMLToEditorState = exports.convertHTMLToEditorState = function convertHTMLToEditorState(HTMLString, editorDecorators, options, source) { options = _extends({}, defaultConvertOptions, options); try { return Draft.Draft.EditorState.createWithContent((0, lib.convertFromHTML)((0, configs.getFromHTMLConfig)(options, source))(HTMLString), editorDecorators); } catch (error) { console.warn(error); return Draft.Draft.EditorState.createEmpty(editorDecorators); } }; var convertEditorStateToRaw = exports.convertEditorStateToRaw = function convertEditorStateToRaw(editorState) { return (0, Draft.Draft.convertToRaw)(editorState.getCurrentContent()); }; var convertRawToEditorState = exports.convertRawToEditorState = function convertRawToEditorState(rawContent, editorDecorators) { try { return Draft.Draft.EditorState.createWithContent((0, Draft.Draft.convertFromRaw)(rawContent), editorDecorators); } catch (error) { console.warn(error); return Draft.Draft.EditorState.createEmpty(editorDecorators); } }; }); _commonjsHelpers.unwrapExports(dist); var dist_1 = dist.convertRawToEditorState; var dist_2 = dist.convertEditorStateToRaw; var dist_3 = dist.convertHTMLToEditorState; var dist_4 = dist.convertEditorStateToHTML; var dist_5 = dist.convertHTMLToRaw; var dist_6 = dist.convertRawToHTML; var content = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.redo = exports.undo = exports.handleKeyCommand = exports.clear = exports.setMediaPosition = exports.removeMedia = exports.setMediaData = exports.insertMedias = exports.insertHorizontalLine = exports.insertAtomicBlock = exports.insertHTML = exports.insertText = exports.toggleSelectionLetterSpacing = exports.toggleSelectionFontFamily = exports.toggleSelectionLineHeight = exports.toggleSelectionFontSize = exports.toggleSelectionBackgroundColor = exports.toggleSelectionColor = exports.decreaseSelectionIndent = exports.increaseSelectionIndent = exports.toggleSelectionIndent = exports.toggleSelectionAlignment = exports.removeSelectionInlineStyles = exports.toggleSelectionInlineStyle = exports.selectionHasInlineStyle = exports.getSelectionInlineStyle = exports.toggleSelectionLink = exports.toggleSelectionEntity = exports.getSelectionEntityData = exports.getSelectionEntityType = exports.toggleSelectionBlockType = exports.getSelectionText = exports.getSelectionBlockType = exports.getSelectionBlockData = exports.setSelectionBlockData = exports.getSelectedBlocks = exports.updateEachCharacterOfSelection = exports.getSelectionBlock = exports.removeBlock = exports.selectNextBlock = exports.selectBlock = exports.selectionContainsStrictBlock = exports.selectionContainsBlockType = exports.isSelectionCollapsed = exports.createEditorState = exports.createEmptyEditorState = exports.isEditorState = exports.registerStrictBlockType = undefined; var _immutable2 = _interopRequireDefault(immutable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var strictBlockTypes = ['atomic']; var registerStrictBlockType = exports.registerStrictBlockType = function registerStrictBlockType(blockType) { strictBlockTypes.indexOf(blockType) === -1 && strictBlockTypes.push(blockType); }; var isEditorState = exports.isEditorState = function isEditorState(editorState) { return editorState instanceof Draft.Draft.EditorState; }; var createEmptyEditorState = exports.createEmptyEditorState = function createEmptyEditorState(editorDecorators) { return Draft.Draft.EditorState.createEmpty(editorDecorators); }; var createEditorState = exports.createEditorState = function createEditorState(contentState, editorDecorators) { return Draft.Draft.EditorState.createWithContent(contentState, editorDecorators); }; var isSelectionCollapsed = exports.isSelectionCollapsed = function isSelectionCollapsed(editorState) { return editorState.getSelection().isCollapsed(); }; var selectionContainsBlockType = exports.selectionContainsBlockType = function selectionContainsBlockType(editorState, blockType) { return getSelectedBlocks(editorState).find(function (block) { return block.getType() === blockType; }); }; var selectionContainsStrictBlock = exports.selectionContainsStrictBlock = function selectionContainsStrictBlock(editorState) { return getSelectedBlocks(editorState).find(function (block) { return ~strictBlockTypes.indexOf(block.getType()); }); }; var selectBlock = exports.selectBlock = function selectBlock(editorState, block) { var blockKey = block.getKey(); return Draft.Draft.EditorState.forceSelection(editorState, new Draft.Draft.SelectionState({ anchorKey: blockKey, anchorOffset: 0, focusKey: blockKey, focusOffset: block.getLength() })); }; var selectNextBlock = exports.selectNextBlock = function selectNextBlock(editorState, block) { var nextBlock = editorState.getCurrentContent().getBlockAfter(block.getKey()); return nextBlock ? selectBlock(editorState, nextBlock) : editorState; }; var removeBlock = exports.removeBlock = function removeBlock(editorState, block) { var lastSelection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var nextContentState = void 0, nextEditorState = void 0; var blockKey = block.getKey(); nextContentState = Draft.Draft.Modifier.removeRange(editorState.getCurrentContent(), new Draft.Draft.SelectionState({ anchorKey: blockKey, anchorOffset: 0, focusKey: blockKey, focusOffset: block.getLength() }), 'backward'); nextContentState = Draft.Draft.Modifier.setBlockType(nextContentState, nextContentState.getSelectionAfter(), 'unstyled'); nextEditorState = Draft.Draft.EditorState.push(editorState, nextContentState, 'remove-range'); return Draft.Draft.EditorState.forceSelection(nextEditorState, lastSelection || nextContentState.getSelectionAfter()); }; var getSelectionBlock = exports.getSelectionBlock = function getSelectionBlock(editorState) { return editorState.getCurrentContent().getBlockForKey(editorState.getSelection().getAnchorKey()); }; var updateEachCharacterOfSelection = exports.updateEachCharacterOfSelection = function updateEachCharacterOfSelection(editorState, callback) { var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); var contentBlocks = contentState.getBlockMap(); var selectedBlocks = getSelectedBlocks(editorState); if (selectedBlocks.length === 0) { return editorState; } var startKey = selectionState.getStartKey(); var startOffset = selectionState.getStartOffset(); var endKey = selectionState.getEndKey(); var endOffset = selectionState.getEndOffset(); var nextContentBlocks = contentBlocks.map(function (block) { if (selectedBlocks.indexOf(block) === -1) { return block; } var blockKey = block.getKey(); var charactersList = block.getCharacterList(); var nextCharactersList = null; if (blockKey === startKey && blockKey === endKey) { nextCharactersList = charactersList.map(function (character, index) { if (index >= startOffset && index < endOffset) { return callback(character); } return character; }); } else if (blockKey === startKey) { nextCharactersList = charactersList.map(function (character, index) { if (index >= startOffset) { return callback(character); } return character; }); } else if (blockKey === endKey) { nextCharactersList = charactersList.map(function (character, index) { if (index < endOffset) { return callback(character); } return character; }); } else { nextCharactersList = charactersList.map(function (character) { return callback(character); }); } return block.merge({ 'characterList': nextCharactersList }); }); return Draft.Draft.EditorState.push(editorState, contentState.merge({ blockMap: nextContentBlocks, selectionBefore: selectionState, selectionAfter: selectionState }), 'update-selection-character-list'); }; var getSelectedBlocks = exports.getSelectedBlocks = function getSelectedBlocks(editorState) { var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); var startKey = selectionState.getStartKey(); var endKey = selectionState.getEndKey(); var isSameBlock = startKey === endKey; var startingBlock = contentState.getBlockForKey(startKey); var selectedBlocks = [startingBlock]; if (!isSameBlock) { var blockKey = startKey; while (blockKey !== endKey) { var nextBlock = contentState.getBlockAfter(blockKey); selectedBlocks.push(nextBlock); blockKey = nextBlock.getKey(); } } return selectedBlocks; }; var setSelectionBlockData = exports.setSelectionBlockData = function setSelectionBlockData(editorState, blockData, override) { var newBlockData = override ? blockData : Object.assign({}, getSelectionBlockData(editorState).toJS(), blockData); Object.keys(newBlockData).forEach(function (key) { if (newBlockData.hasOwnProperty(key) && newBlockData[key] === undefined) { delete newBlockData[key]; } }); return (0, draftjsUtils.setBlockData)(editorState, newBlockData); }; var getSelectionBlockData = exports.getSelectionBlockData = function getSelectionBlockData(editorState, name) { var blockData = getSelectionBlock(editorState).getData(); return name ? blockData.get(name) : blockData; }; var getSelectionBlockType = exports.getSelectionBlockType = function getSelectionBlockType(editorState) { return getSelectionBlock(editorState).getType(); }; var getSelectionText = exports.getSelectionText = function getSelectionText(editorState) { var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return ''; } var anchorKey = selectionState.getAnchorKey(); var currentContentBlock = contentState.getBlockForKey(anchorKey); var start = selectionState.getStartOffset(); var end = selectionState.getEndOffset(); return currentContentBlock.getText().slice(start, end); }; var toggleSelectionBlockType = exports.toggleSelectionBlockType = function toggleSelectionBlockType(editorState, blockType) { if (selectionContainsStrictBlock(editorState)) { return editorState; } return Draft.Draft.RichUtils.toggleBlockType(editorState, blockType); }; var getSelectionEntityType = exports.getSelectionEntityType = function getSelectionEntityType(editorState) { var entityKey = (0, draftjsUtils.getSelectionEntity)(editorState); if (entityKey) { var entity = editorState.getCurrentContent().getEntity(entityKey); return entity ? entity.get('type') : null; } return null; }; var getSelectionEntityData = exports.getSelectionEntityData = function getSelectionEntityData(editorState, type) { var entityKey = (0, draftjsUtils.getSelectionEntity)(editorState); if (entityKey) { var entity = editorState.getCurrentContent().getEntity(entityKey); if (entity && entity.get('type') === type) { return entity.getData(); } else { return {}; } } else { return {}; } }; var toggleSelectionEntity = exports.toggleSelectionEntity = function toggleSelectionEntity(editorState, entity) { var contentState = editorState.getCurrentContent(); var selectionState = editorState.getSelection(); if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return editorState; } if (!entity || !entity.type || getSelectionEntityType(editorState) === entity.type) { return Draft.Draft.EditorState.push(editorState, Draft.Draft.Modifier.applyEntity(contentState, selectionState, null), 'apply-entity'); } try { var nextContentState = contentState.createEntity(entity.type, entity.mutability, entity.data); var entityKey = nextContentState.getLastCreatedEntityKey(); var nextEditorState = Draft.Draft.EditorState.set(editorState, { currentContent: nextContentState }); return Draft.Draft.EditorState.push(nextEditorState, Draft.Draft.Modifier.applyEntity(nextContentState, selectionState, entityKey), 'apply-entity'); } catch (error) { console.warn(error); return editorState; } }; var toggleSelectionLink = exports.toggleSelectionLink = function toggleSelectionLink(editorState, href, target) { var contentState = editorState.getCurrentContent(); var selectionState = editorState.getSelection(); var entityData = { href: href, target: target }; if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return editorState; } if (href === false) { return Draft.Draft.RichUtils.toggleLink(editorState, selectionState, null); } if (href === null) { delete entityData.href; } try { var nextContentState = contentState.createEntity('LINK', 'MUTABLE', entityData); var entityKey = nextContentState.getLastCreatedEntityKey(); var nextEditorState = Draft.Draft.EditorState.set(editorState, { currentContent: nextContentState }); nextEditorState = Draft.Draft.RichUtils.toggleLink(nextEditorState, selectionState, entityKey); nextEditorState = Draft.Draft.EditorState.forceSelection(nextEditorState, selectionState.merge({ anchorOffset: selectionState.getEndOffset(), focusOffset: selectionState.getEndOffset() })); nextEditorState = Draft.Draft.EditorState.push(nextEditorState, Draft.Draft.Modifier.insertText(nextEditorState.getCurrentContent(), nextEditorState.getSelection(), ''), 'insert-text'); return nextEditorState; } catch (error) { console.warn(error); return editorState; } }; var getSelectionInlineStyle = exports.getSelectionInlineStyle = function getSelectionInlineStyle(editorState) { return editorState.getCurrentInlineStyle(); }; var selectionHasInlineStyle = exports.selectionHasInlineStyle = function selectionHasInlineStyle(editorState, style) { return getSelectionInlineStyle(editorState).has(style.toUpperCase()); }; var toggleSelectionInlineStyle = exports.toggleSelectionInlineStyle = function toggleSelectionInlineStyle(editorState, style) { var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var nextEditorState = editorState; style = prefix + style.toUpperCase(); if (prefix) { nextEditorState = updateEachCharacterOfSelection(nextEditorState, function (characterMetadata) { return characterMetadata.toJS().style.reduce(function (characterMetadata, characterStyle) { if (characterStyle.indexOf(prefix) === 0 && style !== characterStyle) { return Draft.Draft.CharacterMetadata.removeStyle(characterMetadata, characterStyle); } else { return characterMetadata; } }, characterMetadata); }); } return Draft.Draft.RichUtils.toggleInlineStyle(nextEditorState, style); }; var removeSelectionInlineStyles = exports.removeSelectionInlineStyles = function removeSelectionInlineStyles(editorState) { return updateEachCharacterOfSelection(editorState, function (characterMetadata) { return characterMetadata.merge({ style: _immutable2.default.OrderedSet([]) }); }); }; var toggleSelectionAlignment = exports.toggleSelectionAlignment = function toggleSelectionAlignment(editorState, alignment) { return setSelectionBlockData(editorState, { textAlign: getSelectionBlockData(editorState, 'textAlign') !== alignment ? alignment : undefined }); }; var toggleSelectionIndent = exports.toggleSelectionIndent = function toggleSelectionIndent(editorState, textIndent) { var maxIndent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 6; return textIndent < 0 || textIndent > maxIndent || isNaN(textIndent) ? editorState : setSelectionBlockData(editorState, { textIndent: textIndent || undefined }); }; var increaseSelectionIndent = exports.increaseSelectionIndent = function increaseSelectionIndent(editorState) { var maxIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6; var currentIndent = getSelectionBlockData(editorState, 'textIndent') || 0; return toggleSelectionIndent(editorState, currentIndent + 1, maxIndent); }; var decreaseSelectionIndent = exports.decreaseSelectionIndent = function decreaseSelectionIndent(editorState) { var currentIndent = getSelectionBlockData(editorState, 'textIndent') || 0; return toggleSelectionIndent(editorState, currentIndent - 1); }; var toggleSelectionColor = exports.toggleSelectionColor = function toggleSelectionColor(editorState, color) { return toggleSelectionInlineStyle(editorState, color.replace('#', ''), 'COLOR-'); }; var toggleSelectionBackgroundColor = exports.toggleSelectionBackgroundColor = function toggleSelectionBackgroundColor(editorState, color) { return toggleSelectionInlineStyle(editorState, color.replace('#', ''), 'BGCOLOR-'); }; var toggleSelectionFontSize = exports.toggleSelectionFontSize = function toggleSelectionFontSize(editorState, fontSize) { return toggleSelectionInlineStyle(editorState, fontSize, 'FONTSIZE-'); }; var toggleSelectionLineHeight = exports.toggleSelectionLineHeight = function toggleSelectionLineHeight(editorState, lineHeight) { return toggleSelectionInlineStyle(editorState, lineHeight, 'LINEHEIGHT-'); }; var toggleSelectionFontFamily = exports.toggleSelectionFontFamily = function toggleSelectionFontFamily(editorState, fontFamily) { return toggleSelectionInlineStyle(editorState, fontFamily, 'FONTFAMILY-'); }; var toggleSelectionLetterSpacing = exports.toggleSelectionLetterSpacing = function toggleSelectionLetterSpacing(editorState, letterSpacing) { return toggleSelectionInlineStyle(editorState, letterSpacing, 'LETTERSPACING-'); }; var insertText = exports.insertText = function insertText(editorState, text, inlineStyle, entity) { var selectionState = editorState.getSelection(); var currentSelectedBlockType = getSelectionBlockType(editorState); if (currentSelectedBlockType === 'atomic') { return editorState; } var entityKey = void 0; var contentState = editorState.getCurrentContent(); if (entity && entity.type) { contentState = contentState.createEntity(entity.type, entity.mutability || 'MUTABLE', entity.data || entityData); entityKey = contentState.getLastCreatedEntityKey(); } if (!selectionState.isCollapsed()) { return Draft.Draft.EditorState.push(editorState, Draft.Draft.Modifier.replaceText(contentState, selectionState, text, inlineStyle, entityKey), 'replace-text'); } else { return Draft.Draft.EditorState.push(editorState, Draft.Draft.Modifier.insertText(contentState, selectionState, text, inlineStyle, entityKey), 'insert-text'); } }; var insertHTML = exports.insertHTML = function insertHTML(editorState, htmlString, source) { if (!htmlString) { return editorState; } var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); var options = editorState.convertOptions || {}; try { var _convertFromRaw = (0, Draft.Draft.convertFromRaw)((0, dist.convertHTMLToRaw)(htmlString, options, source)), blockMap = _convertFromRaw.blockMap; return Draft.Draft.EditorState.push(editorState, Draft.Draft.Modifier.replaceWithFragment(contentState, selectionState, blockMap), 'insert-fragment'); } catch (error) { console.warn(error); return editorState; } }; var insertAtomicBlock = exports.insertAtomicBlock = function insertAtomicBlock(editorState, type) { var immutable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (selectionContainsStrictBlock(editorState)) { return insertAtomicBlock(selectNextBlock(editorState, getSelectionBlock(editorState)), type, immutable, data); } var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); if (!selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return editorState; } var contentStateWithEntity = contentState.createEntity(type, immutable ? 'IMMUTABLE' : 'MUTABLE', data); var entityKey = contentStateWithEntity.getLastCreatedEntityKey(); var newEditorState = Draft.Draft.AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' '); return newEditorState; }; var insertHorizontalLine = exports.insertHorizontalLine = function insertHorizontalLine(editorState) { return insertAtomicBlock(editorState, 'HR'); }; var insertMedias = exports.insertMedias = function insertMedias(editorState) { var medias = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (!medias.length) { return editorState; } return medias.reduce(function (editorState, media) { var url = media.url, link = media.link, link_target = media.link_target, name = media.name, type = media.type, width = media.width, height = media.height, meta = media.meta; return insertAtomicBlock(editorState, type, true, { url: url, link: link, link_target: link_target, name: name, type: type, width: width, height: height, meta: meta }); }, editorState); }; var setMediaData = exports.setMediaData = function setMediaData(editorState, entityKey, data) { return Draft.Draft.EditorState.push(editorState, editorState.getCurrentContent().mergeEntityData(entityKey, data), 'change-block-data'); }; var removeMedia = exports.removeMedia = function removeMedia(editorState, mediaBlock) { return removeBlock(editorState, mediaBlock); }; var setMediaPosition = exports.setMediaPosition = function setMediaPosition(editorState, mediaBlock, position) { var newPosition = {}; var float = position.float, alignment = position.alignment; if (typeof float !== 'undefined') { newPosition.float = mediaBlock.getData().get('float') === float ? null : float; } if (typeof alignment !== 'undefined') { newPosition.alignment = mediaBlock.getData().get('alignment') === alignment ? null : alignment; } return setSelectionBlockData(selectBlock(editorState, mediaBlock), newPosition); }; var clear = exports.clear = function clear(editorState) { var contentState = editorState.getCurrentContent(); var firstBlock = contentState.getFirstBlock(); var lastBlock = contentState.getLastBlock(); var allSelected = new Draft.Draft.SelectionState({ anchorKey: firstBlock.getKey(), anchorOffset: 0, focusKey: lastBlock.getKey(), focusOffset: lastBlock.getLength(), hasFocus: true }); return Draft.Draft.RichUtils.toggleBlockType(Draft.Draft.EditorState.push(editorState, Draft.Draft.Modifier.removeRange(contentState, allSelected, 'backward'), 'remove-range'), 'unstyled'); }; var handleKeyCommand = exports.handleKeyCommand = function handleKeyCommand(editorState, command) { return Draft.Draft.RichUtils.handleKeyCommand(editorState, command); }; var undo = exports.undo = function undo(editorState) { return Draft.Draft.EditorState.undo(editorState); }; var redo = exports.redo = function redo(editorState) { return Draft.Draft.EditorState.redo(editorState); }; }); _commonjsHelpers.unwrapExports(content); var content_1 = content.redo; var content_2 = content.undo; var content_3 = content.handleKeyCommand; var content_4 = content.clear; var content_5 = content.setMediaPosition; var content_6 = content.removeMedia; var content_7 = content.setMediaData; var content_8 = content.insertMedias; var content_9 = content.insertHorizontalLine; var content_10 = content.insertAtomicBlock; var content_11 = content.insertHTML; var content_12 = content.insertText; var content_13 = content.toggleSelectionLetterSpacing; var content_14 = content.toggleSelectionFontFamily; var content_15 = content.toggleSelectionLineHeight; var content_16 = content.toggleSelectionFontSize; var content_17 = content.toggleSelectionBackgroundColor; var content_18 = content.toggleSelectionColor; var content_19 = content.decreaseSelectionIndent; var content_20 = content.increaseSelectionIndent; var content_21 = content.toggleSelectionIndent; var content_22 = content.toggleSelectionAlignment; var content_23 = content.removeSelectionInlineStyles; var content_24 = content.toggleSelectionInlineStyle; var content_25 = content.selectionHasInlineStyle; var content_26 = content.getSelectionInlineStyle; var content_27 = content.toggleSelectionLink; var content_28 = content.toggleSelectionEntity; var content_29 = content.getSelectionEntityData; var content_30 = content.getSelectionEntityType; var content_31 = content.toggleSelectionBlockType; var content_32 = content.getSelectionText; var content_33 = content.getSelectionBlockType; var content_34 = content.getSelectionBlockData; var content_35 = content.setSelectionBlockData; var content_36 = content.getSelectedBlocks; var content_37 = content.updateEachCharacterOfSelection; var content_38 = content.getSelectionBlock; var content_39 = content.removeBlock; var content_40 = content.selectNextBlock; var content_41 = content.selectBlock; var content_42 = content.selectionContainsStrictBlock; var content_43 = content.selectionContainsBlockType; var content_44 = content.isSelectionCollapsed; var content_45 = content.createEditorState; var content_46 = content.createEmptyEditorState; var content_47 = content.isEditorState; var content_48 = content.registerStrictBlockType; var base = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); var braftUniqueIndex = 0; var UniqueIndex = exports.UniqueIndex = function UniqueIndex() { return braftUniqueIndex += 1; }; }); _commonjsHelpers.unwrapExports(base); var base_1 = base.UniqueIndex; var color = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); var _namedColors = { "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a", "burlywood": "#deb887", "cadetblue": "#5f9ea0", "chartreuse": "#7fff00", "chocolate": "#d2691e", "coral": "#ff7f50", "cornflowerblue": "#6495ed", "cornsilk": "#fff8dc", "crimson": "#dc143c", "cyan": "#00ffff", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgoldenrod": "#b8860b", "darkgray": "#a9a9a9", "darkgreen": "#006400", "darkkhaki": "#bdb76b", "darkmagenta": "#8b008b", "darkolivegreen": "#556b2f", "darkorange": "#ff8c00", "darkorchid": "#9932cc", "darkred": "#8b0000", "darksalmon": "#e9967a", "darkseagreen": "#8fbc8f", "darkslateblue": "#483d8b", "darkslategray": "#2f4f4f", "darkturquoise": "#00ced1", "darkviolet": "#9400d3", "deeppink": "#ff1493", "deepskyblue": "#00bfff", "dimgray": "#696969", "dodgerblue": "#1e90ff", "firebrick": "#b22222", "floralwhite": "#fffaf0", "forestgreen": "#228b22", "fuchsia": "#ff00ff", "gainsboro": "#dcdcdc", "ghostwhite": "#f8f8ff", "gold": "#ffd700", "goldenrod": "#daa520", "gray": "#808080", "green": "#008000", "greenyellow": "#adff2f", "honeydew": "#f0fff0", "hotpink": "#ff69b4", "indianred ": "#cd5c5c", "indigo": "#4b0082", "ivory": "#fffff0", "khaki": "#f0e68c", "lavender": "#e6e6fa", "lavenderblush": "#fff0f5", "lawngreen": "#7cfc00", "lemonchiffon": "#fffacd", "lightblue": "#add8e6", "lightcoral": "#f08080", "lightcyan": "#e0ffff", "lightgoldenrodyellow": "#fafad2", "lightgrey": "#d3d3d3", "lightgreen": "#90ee90", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightseagreen": "#20b2aa", "lightskyblue": "#87cefa", "lightslategray": "#778899", "lightsteelblue": "#b0c4de", "lightyellow": "#ffffe0", "lime": "#00ff00", "limegreen": "#32cd32", "linen": "#faf0e6", "magenta": "#ff00ff", "maroon": "#800000", "mediumaquamarine": "#66cdaa", "mediumblue": "#0000cd", "mediumorchid": "#ba55d3", "mediumpurple": "#9370d8", "mediumseagreen": "#3cb371", "mediumslateblue": "#7b68ee", "mediumspringgreen": "#00fa9a", "mediumturquoise": "#48d1cc", "mediumvioletred": "#c71585", "midnightblue": "#191970", "mintcream": "#f5fffa", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "navy": "#000080", "oldlace": "#fdf5e6", "olive": "#808000", "olivedrab": "#6b8e23", "orange": "#ffa500", "orangered": "#ff4500", "orchid": "#da70d6", "palegoldenrod": "#eee8aa", "palegreen": "#98fb98", "paleturquoise": "#afeeee", "palevioletred": "#d87093", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "peru": "#cd853f", "pink": "#ffc0cb", "plum": "#dda0dd", "powderblue": "#b0e0e6", "purple": "#800080", "rebeccapurple": "#663399", "red": "#ff0000", "rosybrown": "#bc8f8f", "royalblue": "#4169e1", "saddlebrown": "#8b4513", "salmon": "#fa8072", "sandybrown": "#f4a460", "seagreen": "#2e8b57", "seashell": "#fff5ee", "sienna": "#a0522d", "silver": "#c0c0c0", "skyblue": "#87ceeb", "slateblue": "#6a5acd", "slategray": "#708090", "snow": "#fffafa", "springgreen": "#00ff7f", "steelblue": "#4682b4", "tan": "#d2b48c", "teal": "#008080", "thistle": "#d8bfd8", "tomato": "#ff6347", "turquoise": "#40e0d0", "violet": "#ee82ee", "wheat": "#f5deb3", "white": "#ffffff", "whitesmoke": "#f5f5f5", "yellow": "#ffff00", "yellowgreen": "#9acd32" }; var _getHexColor = function _getHexColor(color) { color = color.replace('color:', '').replace(';', '').replace(' ', ''); if (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(color)) { return color; } else if (namedColors[color]) { return namedColors[color]; } else if (color.indexOf('rgb') === 0) { var rgbArray = color.split(','); var convertedColor = rgbArray.length < 3 ? null : '#' + [rgbArray[0], rgbArray[1], rgbArray[2]].map(function (x) { var hex = parseInt(x.replace(/\D/g, ''), 10).toString(16); return hex.length === 1 ? '0' + hex : hex; }).join(''); return (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(convertedColor) ? convertedColor : null ); } else { return null; } }; var namedColors = exports.namedColors = _namedColors; var getHexColor = exports.getHexColor = _getHexColor; var detectColorsFromHTMLString = exports.detectColorsFromHTMLString = function detectColorsFromHTMLString(html) { return typeof html !== 'string' ? [] : (html.match(/color:[^;]{3,24};/g) || []).map(getHexColor).filter(function (color) { return color; }); }; var detectColorsFromDraftState = exports.detectColorsFromDraftState = function detectColorsFromDraftState(draftState) { var result = []; if (!draftState || !draftState.blocks || !draftState.blocks.length) { return result; } draftState.blocks.forEach(function (block) { if (block && block.inlineStyleRanges && block.inlineStyleRanges.length) { block.inlineStyleRanges.forEach(function (inlineStyle) { if (inlineStyle.style && inlineStyle.style.indexOf('COLOR-') >= 0) { result.push('#' + inlineStyle.style.split('COLOR-')[1]); } }); } }); return result.filter(function (color) { return color; }); }; }); _commonjsHelpers.unwrapExports(color); var color_1 = color.namedColors; var color_2 = color.getHexColor; var color_3 = color.detectColorsFromHTMLString; var color_4 = color.detectColorsFromDraftState; var dist$1 = _commonjsHelpers.createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorUtils = exports.BaseUtils = exports.ContentUtils = undefined; var _ContentUtils = _interopRequireWildcard(content); var _BaseUtils = _interopRequireWildcard(base); var _ColorUtils = _interopRequireWildcard(color); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var ContentUtils = exports.ContentUtils = _ContentUtils; var BaseUtils = exports.BaseUtils = _BaseUtils; var ColorUtils = exports.ColorUtils = _ColorUtils; }); _commonjsHelpers.unwrapExports(dist$1); var dist_1$1 = dist$1.ColorUtils; var dist_2$1 = dist$1.BaseUtils; var dist_3$1 = dist$1.ContentUtils; var immutable$2 = _commonjsHelpers.createCommonjsModule(function (module, exports) { /** * Copyright (c) 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ (function (global, factory) { module.exports = factory() ; }(_commonjsHelpers.commonjsGlobal, function () {var SLICE$0 = Array.prototype.slice; function createClass(ctor, superClass) { if (superClass) { ctor.prototype = Object.create(superClass.prototype); } ctor.prototype.constructor = ctor; } function Iterable(value) { return isIterable(value) ? value : Seq(value); } createClass(KeyedIterable, Iterable); function KeyedIterable(value) { return isKeyed(value) ? value : KeyedSeq(value); } createClass(IndexedIterable, Iterable); function IndexedIterable(value) { return isIndexed(value) ? value : IndexedSeq(value); } createClass(SetIterable, Iterable); function SetIterable(value) { return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); } function isIterable(maybeIterable) { return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); } function isKeyed(maybeKeyed) { return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); } function isIndexed(maybeIndexed) { return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); } function isAssociative(maybeAssociative) { return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); } function isOrdered(maybeOrdered) { return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); } Iterable.isIterable = isIterable; Iterable.isKeyed = isKeyed; Iterable.isIndexed = isIndexed; Iterable.isAssociative = isAssociative; Iterable.isOrdered = isOrdered; Iterable.Keyed = KeyedIterable; Iterable.Indexed = IndexedIterable; Iterable.Set = SetIterable; var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; // Used for setting prototype methods that IE8 chokes on. var DELETE = 'delete'; // Constants describing the size of trie nodes. var SHIFT = 5; // Resulted in best performance after ______? var SIZE = 1 << SHIFT; var MASK = SIZE - 1; // A consistent shared value representing "not set" which equals nothing other // than itself, and nothing that could be provided externally. var NOT_SET = {}; // Boolean references, Rough equivalent of `bool &`. var CHANGE_LENGTH = { value: false }; var DID_ALTER = { value: false }; function MakeRef(ref) { ref.value = false; return ref; } function SetRef(ref) { ref && (ref.value = true); } // A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {} // http://jsperf.com/copy-array-inline function arrCopy(arr, offset) { offset = offset || 0; var len = Math.max(0, arr.length - offset); var newArr = new Array(len); for (var ii = 0; ii < len; ii++) { newArr[ii] = arr[ii + offset]; } return newArr; } function ensureSize(iter) { if (iter.size === undefined) { iter.size = iter.__iterate(returnTrue); } return iter.size; } function wrapIndex(iter, index) { // This implements "is array index" which the ECMAString spec defines as: // // A String property name P is an array index if and only if // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal // to 2^32−1. // // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects if (typeof index !== 'number') { var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 if ('' + uint32Index !== index || uint32Index === 4294967295) { return NaN; } index = uint32Index; } return index < 0 ? ensureSize(iter) + index : index; } function returnTrue() { return true; } function wholeSlice(begin, end, size) { return (begin === 0 || (size !== undefined && begin <= -size)) && (end === undefined || (size !== undefined && end >= size)); } function resolveBegin(begin, size) { return resolveIndex(begin, size, 0); } function resolveEnd(end, size) { return resolveIndex(end, size, size); } function resolveIndex(index, size, defaultIndex) { return index === undefined ? defaultIndex : index < 0 ? Math.max(0, size + index) : size === undefined ? index : Math.min(size, index); } /* global Symbol */ var ITERATE_KEYS = 0; var ITERATE_VALUES = 1; var ITERATE_ENTRIES = 2; var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; function Iterator(next) { this.next = next; } Iterator.prototype.toString = function() { return '[Iterator]'; }; Iterator.KEYS = ITERATE_KEYS; Iterator.VALUES = ITERATE_VALUES; Iterator.ENTRIES = ITERATE_ENTRIES; Iterator.prototype.inspect = Iterator.prototype.toSource = function () { return this.toString(); }; Iterator.prototype[ITERATOR_SYMBOL] = function () { return this; }; function iteratorValue(type, k, v, iteratorResult) { var value = type === 0 ? k : type === 1 ? v : [k, v]; iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { value: value, done: false }); return iteratorResult; } function iteratorDone() { return { value: undefined, done: true }; } function hasIterator(maybeIterable) { return !!getIteratorFn(maybeIterable); } function isIterator(maybeIterator) { return maybeIterator && typeof maybeIterator.next === 'function'; } function getIterator(iterable) { var iteratorFn = getIteratorFn(iterable); return iteratorFn && iteratorFn.call(iterable); } function getIteratorFn(iterable) { var iteratorFn = iterable && ( (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || iterable[FAUX_ITERATOR_SYMBOL] ); if (typeof iteratorFn === 'function') { return iteratorFn; } } function isArrayLike(value) { return value && typeof value.length === 'number'; } createClass(Seq, Iterable); function Seq(value) { return value === null || value === undefined ? emptySequence() : isIterable(value) ? value.toSeq() : seqFromValue(value); } Seq.of = function(/*...values*/) { return Seq(arguments); }; Seq.prototype.toSeq = function() { return this; }; Seq.prototype.toString = function() { return this.__toString('Seq {', '}'); }; Seq.prototype.cacheResult = function() { if (!this._cache && this.__iterateUncached) { this._cache = this.entrySeq().toArray(); this.size = this._cache.length; } return this; }; // abstract __iterateUncached(fn, reverse) Seq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, true); }; // abstract __iteratorUncached(type, reverse) Seq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, true); }; createClass(KeyedSeq, Seq); function KeyedSeq(value) { return value === null || value === undefined ? emptySequence().toKeyedSeq() : isIterable(value) ? (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : keyedSeqFromValue(value); } KeyedSeq.prototype.toKeyedSeq = function() { return this; }; createClass(IndexedSeq, Seq); function IndexedSeq(value) { return value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); } IndexedSeq.of = function(/*...values*/) { return IndexedSeq(arguments); }; IndexedSeq.prototype.toIndexedSeq = function() { return this; }; IndexedSeq.prototype.toString = function() { return this.__toString('Seq [', ']'); }; IndexedSeq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, false); }; IndexedSeq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, false); }; createClass(SetSeq, Seq); function SetSeq(value) { return ( value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value ).toSetSeq(); } SetSeq.of = function(/*...values*/) { return SetSeq(arguments); }; SetSeq.prototype.toSetSeq = function() { return this; }; Seq.isSeq = isSeq; Seq.Keyed = KeyedSeq; Seq.Set = SetSeq; Seq.Indexed = IndexedSeq; var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; Seq.prototype[IS_SEQ_SENTINEL] = true; createClass(ArraySeq, IndexedSeq); function ArraySeq(array) { this._array = array; this.size = array.length; } ArraySeq.prototype.get = function(index, notSetValue) { return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; ArraySeq.prototype.__iterate = function(fn, reverse) { var array = this._array; var maxIndex = array.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { return ii + 1; } } return ii; }; ArraySeq.prototype.__iterator = function(type, reverse) { var array = this._array; var maxIndex = array.length - 1; var ii = 0; return new Iterator(function() {return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} ); }; createClass(ObjectSeq, KeyedSeq); function ObjectSeq(object) { var keys = Object.keys(object); this._object = object; this._keys = keys; this.size = keys.length; } ObjectSeq.prototype.get = function(key, notSetValue) { if (notSetValue !== undefined && !this.has(key)) { return notSetValue; } return this._object[key]; }; ObjectSeq.prototype.has = function(key) { return this._object.hasOwnProperty(key); }; ObjectSeq.prototype.__iterate = function(fn, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var key = keys[reverse ? maxIndex - ii : ii]; if (fn(object[key], key, this) === false) { return ii + 1; } } return ii; }; ObjectSeq.prototype.__iterator = function(type, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; var ii = 0; return new Iterator(function() { var key = keys[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, key, object[key]); }); }; ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; createClass(IterableSeq, IndexedSeq); function IterableSeq(iterable) { this._iterable = iterable; this.size = iterable.length || iterable.size; } IterableSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); var iterations = 0; if (isIterator(iterator)) { var step; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } } return iterations; }; IterableSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); if (!isIterator(iterator)) { return new Iterator(iteratorDone); } var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; createClass(IteratorSeq, IndexedSeq); function IteratorSeq(iterator) { this._iterator = iterator; this._iteratorCache = []; } IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; while (iterations < cache.length) { if (fn(cache[iterations], iterations++, this) === false) { return iterations; } } var step; while (!(step = iterator.next()).done) { var val = step.value; cache[iterations] = val; if (fn(val, iterations++, this) === false) { break; } } return iterations; }; IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; return new Iterator(function() { if (iterations >= cache.length) { var step = iterator.next(); if (step.done) { return step; } cache[iterations] = step.value; } return iteratorValue(type, iterations, cache[iterations++]); }); }; // # pragma Helper functions function isSeq(maybeSeq) { return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); } var EMPTY_SEQ; function emptySequence() { return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } function keyedSeqFromValue(value) { var seq = Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : typeof value === 'object' ? new ObjectSeq(value) : undefined; if (!seq) { throw new TypeError( 'Expected Array or iterable object of [k, v] entries, '+ 'or keyed object: ' + value ); } return seq; } function indexedSeqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values: ' + value ); } return seq; } function seqFromValue(value) { var seq = maybeIndexedSeqFromValue(value) || (typeof value === 'object' && new ObjectSeq(value)); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values, or keyed object: ' + value ); } return seq; } function maybeIndexedSeqFromValue(value) { return ( isArrayLike(value) ? new ArraySeq(value) : isIterator(value) ? new IteratorSeq(value) : hasIterator(value) ? new IterableSeq(value) : undefined ); } function seqIterate(seq, fn, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var entry = cache[reverse ? maxIndex - ii : ii]; if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { return ii + 1; } } return ii; } return seq.__iterateUncached(fn, reverse); } function seqIterator(seq, type, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; var ii = 0; return new Iterator(function() { var entry = cache[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); }); } return seq.__iteratorUncached(type, reverse); } function fromJS(json, converter) { return converter ? fromJSWith(converter, json, '', {'': json}) : fromJSDefault(json); } function fromJSWith(converter, json, key, parentJSON) { if (Array.isArray(json)) { return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } if (isPlainObj(json)) { return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } return json; } function fromJSDefault(json) { if (Array.isArray(json)) { return IndexedSeq(json).map(fromJSDefault).toList(); } if (isPlainObj(json)) { return KeyedSeq(json).map(fromJSDefault).toMap(); } return json; } function isPlainObj(value) { return value && (value.constructor === Object || value.constructor === undefined); } /** * An extension of the "same-value" algorithm as [described for use by ES6 Map * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) * * NaN is considered the same as NaN, however -0 and 0 are considered the same * value, which is different from the algorithm described by * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * This is extended further to allow Objects to describe the values they * represent, by way of `valueOf` or `equals` (and `hashCode`). * * Note: because of this extension, the key equality of Immutable.Map and the * value equality of Immutable.Set will differ from ES6 Map and Set. * * ### Defining custom values * * The easiest way to describe the value an object represents is by implementing * `valueOf`. For example, `Date` represents a value by returning a unix * timestamp for `valueOf`: * * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... * var date2 = new Date(1234567890000); * date1.valueOf(); // 1234567890000 * assert( date1 !== date2 ); * assert( Immutable.is( date1, date2 ) ); * * Note: overriding `valueOf` may have other implications if you use this object * where JavaScript expects a primitive, such as implicit string coercion. * * For more complex types, especially collections, implementing `valueOf` may * not be performant. An alternative is to implement `equals` and `hashCode`. * * `equals` takes another object, presumably of similar type, and returns true * if the it is equal. Equality is symmetrical, so the same result should be * returned if this and the argument are flipped. * * assert( a.equals(b) === b.equals(a) ); * * `hashCode` returns a 32bit integer number representing the object which will * be used to determine how to store the value object in a Map or Set. You must * provide both or neither methods, one must not exist without the other. * * Also, an important relationship between these methods must be upheld: if two * values are equal, they *must* return the same hashCode. If the values are not * equal, they might have the same hashCode; this is called a hash collision, * and while undesirable for performance reasons, it is acceptable. * * if (a.equals(b)) { * assert( a.hashCode() === b.hashCode() ); * } * * All Immutable collections implement `equals` and `hashCode`. * */ function is(valueA, valueB) { if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } if (typeof valueA.valueOf === 'function' && typeof valueB.valueOf === 'function') { valueA = valueA.valueOf(); valueB = valueB.valueOf(); if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } } if (typeof valueA.equals === 'function' && typeof valueB.equals === 'function' && valueA.equals(valueB)) { return true; } return false; } function deepEqual(a, b) { if (a === b) { return true; } if ( !isIterable(b) || a.size !== undefined && b.size !== undefined && a.size !== b.size || a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || isKeyed(a) !== isKeyed(b) || isIndexed(a) !== isIndexed(b) || isOrdered(a) !== isOrdered(b) ) { return false; } if (a.size === 0 && b.size === 0) { return true; } var notAssociative = !isAssociative(a); if (isOrdered(a)) { var entries = a.entries(); return b.every(function(v, k) { var entry = entries.next().value; return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); }) && entries.next().done; } var flipped = false; if (a.size === undefined) { if (b.size === undefined) { if (typeof a.cacheResult === 'function') { a.cacheResult(); } } else { flipped = true; var _ = a; a = b; b = _; } } var allEqual = true; var bSize = b.__iterate(function(v, k) { if (notAssociative ? !a.has(v) : flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { allEqual = false; return false; } }); return allEqual && a.size === bSize; } createClass(Repeat, IndexedSeq); function Repeat(value, times) { if (!(this instanceof Repeat)) { return new Repeat(value, times); } this._value = value; this.size = times === undefined ? Infinity : Math.max(0, times); if (this.size === 0) { if (EMPTY_REPEAT) { return EMPTY_REPEAT; } EMPTY_REPEAT = this; } } Repeat.prototype.toString = function() { if (this.size === 0) { return 'Repeat []'; } return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; }; Repeat.prototype.get = function(index, notSetValue) { return this.has(index) ? this._value : notSetValue; }; Repeat.prototype.includes = function(searchValue) { return is(this._value, searchValue); }; Repeat.prototype.slice = function(begin, end) { var size = this.size; return wholeSlice(begin, end, size) ? this : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); }; Repeat.prototype.reverse = function() { return this; }; Repeat.prototype.indexOf = function(searchValue) { if (is(this._value, searchValue)) { return 0; } return -1; }; Repeat.prototype.lastIndexOf = function(searchValue) { if (is(this._value, searchValue)) { return this.size; } return -1; }; Repeat.prototype.__iterate = function(fn, reverse) { for (var ii = 0; ii < this.size; ii++) { if (fn(this._value, ii, this) === false) { return ii + 1; } } return ii; }; Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; var ii = 0; return new Iterator(function() {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} ); }; Repeat.prototype.equals = function(other) { return other instanceof Repeat ? is(this._value, other._value) : deepEqual(other); }; var EMPTY_REPEAT; function invariant(condition, error) { if (!condition) throw new Error(error); } createClass(Range, IndexedSeq); function Range(start, end, step) { if (!(this instanceof Range)) { return new Range(start, end, step); } invariant(step !== 0, 'Cannot step a Range by 0'); start = start || 0; if (end === undefined) { end = Infinity; } step = step === undefined ? 1 : Math.abs(step); if (end < start) { step = -step; } this._start = start; this._end = end; this._step = step; this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); if (this.size === 0) { if (EMPTY_RANGE) { return EMPTY_RANGE; } EMPTY_RANGE = this; } } Range.prototype.toString = function() { if (this.size === 0) { return 'Range []'; } return 'Range [ ' + this._start + '...' + this._end + (this._step > 1 ? ' by ' + this._step : '') + ' ]'; }; Range.prototype.get = function(index, notSetValue) { return this.has(index) ? this._start + wrapIndex(this, index) * this._step : notSetValue; }; Range.prototype.includes = function(searchValue) { var possibleIndex = (searchValue - this._start) / this._step; return possibleIndex >= 0 && possibleIndex < this.size && possibleIndex === Math.floor(possibleIndex); }; Range.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } begin = resolveBegin(begin, this.size); end = resolveEnd(end, this.size); if (end <= begin) { return new Range(0, 0); } return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); }; Range.prototype.indexOf = function(searchValue) { var offsetValue = searchValue - this._start; if (offsetValue % this._step === 0) { var index = offsetValue / this._step; if (index >= 0 && index < this.size) { return index } } return -1; }; Range.prototype.lastIndexOf = function(searchValue) { return this.indexOf(searchValue); }; Range.prototype.__iterate = function(fn, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(value, ii, this) === false) { return ii + 1; } value += reverse ? -step : step; } return ii; }; Range.prototype.__iterator = function(type, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; var ii = 0; return new Iterator(function() { var v = value; value += reverse ? -step : step; return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); }); }; Range.prototype.equals = function(other) { return other instanceof Range ? this._start === other._start && this._end === other._end && this._step === other._step : deepEqual(this, other); }; var EMPTY_RANGE; createClass(Collection, Iterable); function Collection() { throw TypeError('Abstract'); } createClass(KeyedCollection, Collection);function KeyedCollection() {} createClass(IndexedCollection, Collection);function IndexedCollection() {} createClass(SetCollection, Collection);function SetCollection() {} Collection.Keyed = KeyedCollection; Collection.Indexed = IndexedCollection; Collection.Set = SetCollection; var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? Math.imul : function imul(a, b) { a = a | 0; // int b = b | 0; // int var c = a & 0xffff; var d = b & 0xffff; // Shift by 0 fixes the sign on the high part. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int }; // v8 has an optimization for storing 31-bit signed numbers. // Values which have either 00 or 11 as the high order bits qualify. // This function drops the highest order bit in a signed number, maintaining // the sign bit. function smi(i32) { return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); } function hash(o) { if (o === false || o === null || o === undefined) { return 0; } if (typeof o.valueOf === 'function') { o = o.valueOf(); if (o === false || o === null || o === undefined) { return 0; } } if (o === true) { return 1; } var type = typeof o; if (type === 'number') { var h = o | 0; if (h !== o) { h ^= o * 0xFFFFFFFF; } while (o > 0xFFFFFFFF) { o /= 0xFFFFFFFF; h ^= o; } return smi(h); } if (type === 'string') { return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); } if (typeof o.hashCode === 'function') { return o.hashCode(); } if (type === 'object') { return hashJSObj(o); } if (typeof o.toString === 'function') { return hashString(o.toString()); } throw new Error('Value type ' + type + ' cannot be hashed.'); } function cachedHashString(string) { var hash = stringHashCache[string]; if (hash === undefined) { hash = hashString(string); if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { STRING_HASH_CACHE_SIZE = 0; stringHashCache = {}; } STRING_HASH_CACHE_SIZE++; stringHashCache[string] = hash; } return hash; } // http://jsperf.com/hashing-strings function hashString(string) { // This is the hash from JVM // The hash code for a string is computed as // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], // where s[i] is the ith character of the string and n is the length of // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 // (exclusive) by dropping high bits. var hash = 0; for (var ii = 0; ii < string.length; ii++) { hash = 31 * hash + string.charCodeAt(ii) | 0; } return smi(hash); } function hashJSObj(obj) { var hash; if (usingWeakMap) { hash = weakMap.get(obj); if (hash !== undefined) { return hash; } } hash = obj[UID_HASH_KEY]; if (hash !== undefined) { return hash; } if (!canDefineProperty) { hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; if (hash !== undefined) { return hash; } hash = getIENodeHash(obj); if (hash !== undefined) { return hash; } } hash = ++objHashUID; if (objHashUID & 0x40000000) { objHashUID = 0; } if (usingWeakMap) { weakMap.set(obj, hash); } else if (isExtensible !== undefined && isExtensible(obj) === false) { throw new Error('Non-extensible objects are not allowed as keys.'); } else if (canDefineProperty) { Object.defineProperty(obj, UID_HASH_KEY, { 'enumerable': false, 'configurable': false, 'writable': false, 'value': hash }); } else if (obj.propertyIsEnumerable !== undefined && obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { // Since we can't define a non-enumerable property on the object // we'll hijack one of the less-used non-enumerable properties to // save our hash on it. Since this is a function it will not show up in // `JSON.stringify` which is what we want. obj.propertyIsEnumerable = function() { return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); }; obj.propertyIsEnumerable[UID_HASH_KEY] = hash; } else if (obj.nodeType !== undefined) { // At this point we couldn't get the IE `uniqueID` to use as a hash // and we couldn't use a non-enumerable property to exploit the // dontEnum bug so we simply add the `UID_HASH_KEY` on the node // itself. obj[UID_HASH_KEY] = hash; } else { throw new Error('Unable to set a non-enumerable property on object.'); } return hash; } // Get references to ES5 object methods. var isExtensible = Object.isExtensible; // True if Object.defineProperty works as expected. IE8 fails this test. var canDefineProperty = (function() { try { Object.defineProperty({}, '@', {}); return true; } catch (e) { return false; } }()); // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it // and avoid memory leaks from the IE cloneNode bug. function getIENodeHash(node) { if (node && node.nodeType > 0) { switch (node.nodeType) { case 1: // Element return node.uniqueID; case 9: // Document return node.documentElement && node.documentElement.uniqueID; } } } // If possible, use a WeakMap. var usingWeakMap = typeof WeakMap === 'function'; var weakMap; if (usingWeakMap) { weakMap = new WeakMap(); } var objHashUID = 0; var UID_HASH_KEY = '__immutablehash__'; if (typeof Symbol === 'function') { UID_HASH_KEY = Symbol(UID_HASH_KEY); } var STRING_HASH_CACHE_MIN_STRLEN = 16; var STRING_HASH_CACHE_MAX_SIZE = 255; var STRING_HASH_CACHE_SIZE = 0; var stringHashCache = {}; function assertNotInfinite(size) { invariant( size !== Infinity, 'Cannot perform this action with an infinite size.' ); } createClass(Map, KeyedCollection); // @pragma Construction function Map(value) { return value === null || value === undefined ? emptyMap() : isMap(value) && !isOrdered(value) ? value : emptyMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } Map.prototype.toString = function() { return this.__toString('Map {', '}'); }; // @pragma Access Map.prototype.get = function(k, notSetValue) { return this._root ? this._root.get(0, undefined, k, notSetValue) : notSetValue; }; // @pragma Modification Map.prototype.set = function(k, v) { return updateMap(this, k, v); }; Map.prototype.setIn = function(keyPath, v) { return this.updateIn(keyPath, NOT_SET, function() {return v}); }; Map.prototype.remove = function(k) { return updateMap(this, k, NOT_SET); }; Map.prototype.deleteIn = function(keyPath) { return this.updateIn(keyPath, function() {return NOT_SET}); }; Map.prototype.update = function(k, notSetValue, updater) { return arguments.length === 1 ? k(this) : this.updateIn([k], notSetValue, updater); }; Map.prototype.updateIn = function(keyPath, notSetValue, updater) { if (!updater) { updater = notSetValue; notSetValue = undefined; } var updatedValue = updateInDeepMap( this, forceIterator(keyPath), notSetValue, updater ); return updatedValue === NOT_SET ? undefined : updatedValue; }; Map.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }; // @pragma Composition Map.prototype.merge = function(/*...iters*/) { return mergeIntoMapWith(this, undefined, arguments); }; Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, merger, iters); }; Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.merge === 'function' ? m.merge.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoMapWith(this, deepMerger, arguments); }; Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, deepMergerWith(merger), iters); }; Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.mergeDeep === 'function' ? m.mergeDeep.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.sort = function(comparator) { // Late binding return OrderedMap(sortFactory(this, comparator)); }; Map.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedMap(sortFactory(this, comparator, mapper)); }; // @pragma Mutability Map.prototype.withMutations = function(fn) { var mutable = this.asMutable(); fn(mutable); return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; }; Map.prototype.asMutable = function() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); }; Map.prototype.asImmutable = function() { return this.__ensureOwner(); }; Map.prototype.wasAltered = function() { return this.__altered; }; Map.prototype.__iterator = function(type, reverse) { return new MapIterator(this, type, reverse); }; Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; this._root && this._root.iterate(function(entry ) { iterations++; return fn(entry[1], entry[0], this$0); }, reverse); return iterations; }; Map.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }; function isMap(maybeMap) { return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); } Map.isMap = isMap; var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; var MapPrototype = Map.prototype; MapPrototype[IS_MAP_SENTINEL] = true; MapPrototype[DELETE] = MapPrototype.remove; MapPrototype.removeIn = MapPrototype.deleteIn; // #pragma Trie Nodes function ArrayMapNode(ownerID, entries) { this.ownerID = ownerID; this.entries = entries; } ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && entries.length === 1) { return; // undefined } if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { return createNodes(ownerID, entries, key, value); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new ArrayMapNode(ownerID, newEntries); }; function BitmapIndexedNode(ownerID, bitmap, nodes) { this.ownerID = ownerID; this.bitmap = bitmap; this.nodes = nodes; } BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); var bitmap = this.bitmap; return (bitmap & bit) === 0 ? notSetValue : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); }; BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var bit = 1 << keyHashFrag; var bitmap = this.bitmap; var exists = (bitmap & bit) !== 0; if (!exists && value === NOT_SET) { return this; } var idx = popCount(bitmap & (bit - 1)); var nodes = this.nodes; var node = exists ? nodes[idx] : undefined; var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); } if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { return nodes[idx ^ 1]; } if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { return newNode; } var isEditable = ownerID && ownerID === this.ownerID; var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; var newNodes = exists ? newNode ? setIn(nodes, idx, newNode, isEditable) : spliceOut(nodes, idx, isEditable) : spliceIn(nodes, idx, newNode, isEditable); if (isEditable) { this.bitmap = newBitmap; this.nodes = newNodes; return this; } return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; function HashArrayMapNode(ownerID, count, nodes) { this.ownerID = ownerID; this.count = count; this.nodes = nodes; } HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var node = this.nodes[idx]; return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; }; HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var removed = value === NOT_SET; var nodes = this.nodes; var node = nodes[idx]; if (removed && !node) { return this; } var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } var newCount = this.count; if (!node) { newCount++; } else if (!newNode) { newCount--; if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { return packNodes(ownerID, nodes, newCount, idx); } } var isEditable = ownerID && ownerID === this.ownerID; var newNodes = setIn(nodes, idx, newNode, isEditable); if (isEditable) { this.count = newCount; this.nodes = newNodes; return this; } return new HashArrayMapNode(ownerID, newCount, newNodes); }; function HashCollisionNode(ownerID, keyHash, entries) { this.ownerID = ownerID; this.keyHash = keyHash; this.entries = entries; } HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var removed = value === NOT_SET; if (keyHash !== this.keyHash) { if (removed) { return this; } SetRef(didAlter); SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); } var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && len === 2) { return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new HashCollisionNode(ownerID, this.keyHash, newEntries); }; function ValueNode(ownerID, keyHash, entry) { this.ownerID = ownerID; this.keyHash = keyHash; this.entry = entry; } ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { return is(key, this.entry[0]) ? this.entry[1] : notSetValue; }; ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var keyMatch = is(key, this.entry[0]); if (keyMatch ? value === this.entry[1] : removed) { return this; } SetRef(didAlter); if (removed) { SetRef(didChangeSize); return; // undefined } if (keyMatch) { if (ownerID && ownerID === this.ownerID) { this.entry[1] = value; return this; } return new ValueNode(ownerID, this.keyHash, [key, value]); } SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); }; // #pragma Iterators ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) { var entries = this.entries; for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { return false; } } }; BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) { var nodes = this.nodes; for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { var node = nodes[reverse ? maxIndex - ii : ii]; if (node && node.iterate(fn, reverse) === false) { return false; } } }; ValueNode.prototype.iterate = function (fn, reverse) { return fn(this.entry); }; createClass(MapIterator, Iterator); function MapIterator(map, type, reverse) { this._type = type; this._reverse = reverse; this._stack = map._root && mapIteratorFrame(map._root); } MapIterator.prototype.next = function() { var type = this._type; var stack = this._stack; while (stack) { var node = stack.node; var index = stack.index++; var maxIndex; if (node.entry) { if (index === 0) { return mapIteratorValue(type, node.entry); } } else if (node.entries) { maxIndex = node.entries.length - 1; if (index <= maxIndex) { return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); } } else { maxIndex = node.nodes.length - 1; if (index <= maxIndex) { var subNode = node.nodes[this._reverse ? maxIndex - index : index]; if (subNode) { if (subNode.entry) { return mapIteratorValue(type, subNode.entry); } stack = this._stack = mapIteratorFrame(subNode, stack); } continue; } } stack = this._stack = this._stack.__prev; } return iteratorDone(); }; function mapIteratorValue(type, entry) { return iteratorValue(type, entry[0], entry[1]); } function mapIteratorFrame(node, prev) { return { node: node, index: 0, __prev: prev }; } function makeMap(size, root, ownerID, hash) { var map = Object.create(MapPrototype); map.size = size; map._root = root; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_MAP; function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); } function updateMap(map, k, v) { var newRoot; var newSize; if (!map._root) { if (v === NOT_SET) { return map; } newSize = 1; newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); } else { var didChangeSize = MakeRef(CHANGE_LENGTH); var didAlter = MakeRef(DID_ALTER); newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); if (!didAlter.value) { return map; } newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); } if (map.__ownerID) { map.size = newSize; map._root = newRoot; map.__hash = undefined; map.__altered = true; return map; } return newRoot ? makeMap(newSize, newRoot) : emptyMap(); } function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (!node) { if (value === NOT_SET) { return node; } SetRef(didAlter); SetRef(didChangeSize); return new ValueNode(ownerID, keyHash, [key, value]); } return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); } function isLeafNode(node) { return node.constructor === ValueNode || node.constructor === HashCollisionNode; } function mergeIntoNode(node, ownerID, shift, keyHash, entry) { if (node.keyHash === keyHash) { return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); } var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var newNode; var nodes = idx1 === idx2 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); } function createNodes(ownerID, entries, key, value) { if (!ownerID) { ownerID = new OwnerID(); } var node = new ValueNode(ownerID, hash(key), [key, value]); for (var ii = 0; ii < entries.length; ii++) { var entry = entries[ii]; node = node.update(ownerID, 0, undefined, entry[0], entry[1]); } return node; } function packNodes(ownerID, nodes, count, excluding) { var bitmap = 0; var packedII = 0; var packedNodes = new Array(count); for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { var node = nodes[ii]; if (node !== undefined && ii !== excluding) { bitmap |= bit; packedNodes[packedII++] = node; } } return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } function expandNodes(ownerID, nodes, bitmap, including, node) { var count = 0; var expandedNodes = new Array(SIZE); for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; } expandedNodes[including] = node; return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } function mergeIntoMapWith(map, merger, iterables) { var iters = []; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = KeyedIterable(value); if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } return mergeIntoCollectionWith(map, merger, iters); } function deepMerger(existing, value, key) { return existing && existing.mergeDeep && isIterable(value) ? existing.mergeDeep(value) : is(existing, value) ? existing : value; } function deepMergerWith(merger) { return function(existing, value, key) { if (existing && existing.mergeDeepWith && isIterable(value)) { return existing.mergeDeepWith(merger, value); } var nextValue = merger(existing, value, key); return is(existing, nextValue) ? existing : nextValue; }; } function mergeIntoCollectionWith(collection, merger, iters) { iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return collection; } if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { return collection.constructor(iters[0]); } return collection.withMutations(function(collection ) { var mergeIntoMap = merger ? function(value, key) { collection.update(key, NOT_SET, function(existing ) {return existing === NOT_SET ? value : merger(existing, value, key)} ); } : function(value, key) { collection.set(key, value); }; for (var ii = 0; ii < iters.length; ii++) { iters[ii].forEach(mergeIntoMap); } }); } function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { var isNotSet = existing === NOT_SET; var step = keyPathIter.next(); if (step.done) { var existingValue = isNotSet ? notSetValue : existing; var newValue = updater(existingValue); return newValue === existingValue ? existing : newValue; } invariant( isNotSet || (existing && existing.set), 'invalid keyPath' ); var key = step.value; var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); var nextUpdated = updateInDeepMap( nextExisting, keyPathIter, notSetValue, updater ); return nextUpdated === nextExisting ? existing : nextUpdated === NOT_SET ? existing.remove(key) : (isNotSet ? emptyMap() : existing).set(key, nextUpdated); } function popCount(x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x = x + (x >> 8); x = x + (x >> 16); return x & 0x7f; } function setIn(array, idx, val, canEdit) { var newArray = canEdit ? array : arrCopy(array); newArray[idx] = val; return newArray; } function spliceIn(array, idx, val, canEdit) { var newLen = array.length + 1; if (canEdit && idx + 1 === newLen) { array[idx] = val; return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { newArray[ii] = val; after = -1; } else { newArray[ii] = array[ii + after]; } } return newArray; } function spliceOut(array, idx, canEdit) { var newLen = array.length - 1; if (canEdit && idx === newLen) { array.pop(); return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { after = 1; } newArray[ii] = array[ii + after]; } return newArray; } var MAX_ARRAY_MAP_SIZE = SIZE / 4; var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; createClass(List, IndexedCollection); // @pragma Construction function List(value) { var empty = emptyList(); if (value === null || value === undefined) { return empty; } if (isList(value)) { return value; } var iter = IndexedIterable(value); var size = iter.size; if (size === 0) { return empty; } assertNotInfinite(size); if (size > 0 && size < SIZE) { return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); } return empty.withMutations(function(list ) { list.setSize(size); iter.forEach(function(v, i) {return list.set(i, v)}); }); } List.of = function(/*...values*/) { return this(arguments); }; List.prototype.toString = function() { return this.__toString('List [', ']'); }; // @pragma Access List.prototype.get = function(index, notSetValue) { index = wrapIndex(this, index); if (index >= 0 && index < this.size) { index += this._origin; var node = listNodeFor(this, index); return node && node.array[index & MASK]; } return notSetValue; }; // @pragma Modification List.prototype.set = function(index, value) { return updateList(this, index, value); }; List.prototype.remove = function(index) { return !this.has(index) ? this : index === 0 ? this.shift() : index === this.size - 1 ? this.pop() : this.splice(index, 1); }; List.prototype.insert = function(index, value) { return this.splice(index, 0, value); }; List.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = this._origin = this._capacity = 0; this._level = SHIFT; this._root = this._tail = null; this.__hash = undefined; this.__altered = true; return this; } return emptyList(); }; List.prototype.push = function(/*...values*/) { var values = arguments; var oldSize = this.size; return this.withMutations(function(list ) { setListBounds(list, 0, oldSize + values.length); for (var ii = 0; ii < values.length; ii++) { list.set(oldSize + ii, values[ii]); } }); }; List.prototype.pop = function() { return setListBounds(this, 0, -1); }; List.prototype.unshift = function(/*...values*/) { var values = arguments; return this.withMutations(function(list ) { setListBounds(list, -values.length); for (var ii = 0; ii < values.length; ii++) { list.set(ii, values[ii]); } }); }; List.prototype.shift = function() { return setListBounds(this, 1); }; // @pragma Composition List.prototype.merge = function(/*...iters*/) { return mergeIntoListWith(this, undefined, arguments); }; List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, merger, iters); }; List.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoListWith(this, deepMerger, arguments); }; List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, deepMergerWith(merger), iters); }; List.prototype.setSize = function(size) { return setListBounds(this, 0, size); }; // @pragma Iteration List.prototype.slice = function(begin, end) { var size = this.size; if (wholeSlice(begin, end, size)) { return this; } return setListBounds( this, resolveBegin(begin, size), resolveEnd(end, size) ); }; List.prototype.__iterator = function(type, reverse) { var index = 0; var values = iterateList(this, reverse); return new Iterator(function() { var value = values(); return value === DONE ? iteratorDone() : iteratorValue(type, index++, value); }); }; List.prototype.__iterate = function(fn, reverse) { var index = 0; var values = iterateList(this, reverse); var value; while ((value = values()) !== DONE) { if (fn(value, index++, this) === false) { break; } } return index; }; List.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; return this; } return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); }; function isList(maybeList) { return !!(maybeList && maybeList[IS_LIST_SENTINEL]); } List.isList = isList; var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; var ListPrototype = List.prototype; ListPrototype[IS_LIST_SENTINEL] = true; ListPrototype[DELETE] = ListPrototype.remove; ListPrototype.setIn = MapPrototype.setIn; ListPrototype.deleteIn = ListPrototype.removeIn = MapPrototype.removeIn; ListPrototype.update = MapPrototype.update; ListPrototype.updateIn = MapPrototype.updateIn; ListPrototype.mergeIn = MapPrototype.mergeIn; ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; ListPrototype.withMutations = MapPrototype.withMutations; ListPrototype.asMutable = MapPrototype.asMutable; ListPrototype.asImmutable = MapPrototype.asImmutable; ListPrototype.wasAltered = MapPrototype.wasAltered; function VNode(array, ownerID) { this.array = array; this.ownerID = ownerID; } // TODO: seems like these methods are very similar VNode.prototype.removeBefore = function(ownerID, level, index) { if (index === level ? 1 << level : this.array.length === 0) { return this; } var originIndex = (index >>> level) & MASK; if (originIndex >= this.array.length) { return new VNode([], ownerID); } var removingFirst = originIndex === 0; var newChild; if (level > 0) { var oldChild = this.array[originIndex]; newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); if (newChild === oldChild && removingFirst) { return this; } } if (removingFirst && !newChild) { return this; } var editable = editableVNode(this, ownerID); if (!removingFirst) { for (var ii = 0; ii < originIndex; ii++) { editable.array[ii] = undefined; } } if (newChild) { editable.array[originIndex] = newChild; } return editable; }; VNode.prototype.removeAfter = function(ownerID, level, index) { if (index === (level ? 1 << level : 0) || this.array.length === 0) { return this; } var sizeIndex = ((index - 1) >>> level) & MASK; if (sizeIndex >= this.array.length) { return this; } var newChild; if (level > 0) { var oldChild = this.array[sizeIndex]; newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); if (newChild === oldChild && sizeIndex === this.array.length - 1) { return this; } } var editable = editableVNode(this, ownerID); editable.array.splice(sizeIndex + 1); if (newChild) { editable.array[sizeIndex] = newChild; } return editable; }; var DONE = {}; function iterateList(list, reverse) { var left = list._origin; var right = list._capacity; var tailPos = getTailOffset(right); var tail = list._tail; return iterateNodeOrLeaf(list._root, list._level, 0); function iterateNodeOrLeaf(node, level, offset) { return level === 0 ? iterateLeaf(node, offset) : iterateNode(node, level, offset); } function iterateLeaf(node, offset) { var array = offset === tailPos ? tail && tail.array : node && node.array; var from = offset > left ? 0 : left - offset; var to = right - offset; if (to > SIZE) { to = SIZE; } return function() { if (from === to) { return DONE; } var idx = reverse ? --to : from++; return array && array[idx]; }; } function iterateNode(node, level, offset) { var values; var array = node && node.array; var from = offset > left ? 0 : (left - offset) >> level; var to = ((right - offset) >> level) + 1; if (to > SIZE) { to = SIZE; } return function() { do { if (values) { var value = values(); if (value !== DONE) { return value; } values = null; } if (from === to) { return DONE; } var idx = reverse ? --to : from++; values = iterateNodeOrLeaf( array && array[idx], level - SHIFT, offset + (idx << level) ); } while (true); }; } } function makeList(origin, capacity, level, root, tail, ownerID, hash) { var list = Object.create(ListPrototype); list.size = capacity - origin; list._origin = origin; list._capacity = capacity; list._level = level; list._root = root; list._tail = tail; list.__ownerID = ownerID; list.__hash = hash; list.__altered = false; return list; } var EMPTY_LIST; function emptyList() { return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); } function updateList(list, index, value) { index = wrapIndex(list, index); if (index !== index) { return list; } if (index >= list.size || index < 0) { return list.withMutations(function(list ) { index < 0 ? setListBounds(list, index).set(0, value) : setListBounds(list, 0, index + 1).set(index, value); }); } index += list._origin; var newTail = list._tail; var newRoot = list._root; var didAlter = MakeRef(DID_ALTER); if (index >= getTailOffset(list._capacity)) { newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); } else { newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); } if (!didAlter.value) { return list; } if (list.__ownerID) { list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(list._origin, list._capacity, list._level, newRoot, newTail); } function updateVNode(node, ownerID, level, index, value, didAlter) { var idx = (index >>> level) & MASK; var nodeHas = node && idx < node.array.length; if (!nodeHas && value === undefined) { return node; } var newNode; if (level > 0) { var lowerNode = node && node.array[idx]; var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); if (newLowerNode === lowerNode) { return node; } newNode = editableVNode(node, ownerID); newNode.array[idx] = newLowerNode; return newNode; } if (nodeHas && node.array[idx] === value) { return node; } SetRef(didAlter); newNode = editableVNode(node, ownerID); if (value === undefined && idx === newNode.array.length - 1) { newNode.array.pop(); } else { newNode.array[idx] = value; } return newNode; } function editableVNode(node, ownerID) { if (ownerID && node && ownerID === node.ownerID) { return node; } return new VNode(node ? node.array.slice() : [], ownerID); } function listNodeFor(list, rawIndex) { if (rawIndex >= getTailOffset(list._capacity)) { return list._tail; } if (rawIndex < 1 << (list._level + SHIFT)) { var node = list._root; var level = list._level; while (node && level > 0) { node = node.array[(rawIndex >>> level) & MASK]; level -= SHIFT; } return node; } } function setListBounds(list, begin, end) { // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } var owner = list.__ownerID || new OwnerID(); var oldOrigin = list._origin; var oldCapacity = list._capacity; var newOrigin = oldOrigin + begin; var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; if (newOrigin === oldOrigin && newCapacity === oldCapacity) { return list; } // If it's going to end after it starts, it's empty. if (newOrigin >= newCapacity) { return list.clear(); } var newLevel = list._level; var newRoot = list._root; // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); newLevel += SHIFT; offsetShift += 1 << newLevel; } if (offsetShift) { newOrigin += offsetShift; oldOrigin += offsetShift; newCapacity += offsetShift; oldCapacity += offsetShift; } var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); newLevel += SHIFT; } // Locate or create the new tail. var oldTail = list._tail; var newTail = newTailOffset < oldTailOffset ? listNodeFor(list, newCapacity - 1) : newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; // Merge Tail into tree. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { newRoot = editableVNode(newRoot, owner); var node = newRoot; for (var level = newLevel; level > SHIFT; level -= SHIFT) { var idx = (oldTailOffset >>> level) & MASK; node = node.array[idx] = editableVNode(node.array[idx], owner); } node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } // If the size has been reduced, there's a chance the tail needs to be trimmed. if (newCapacity < oldCapacity) { newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } // If the new origin is within the tail, then we do not need a root. if (newOrigin >= newTailOffset) { newOrigin -= newTailOffset; newCapacity -= newTailOffset; newLevel = SHIFT; newRoot = null; newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); // Otherwise, if the root has been trimmed, garbage collect. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { offsetShift = 0; // Identify the new top root node of the subtree of the old root. while (newRoot) { var beginIndex = (newOrigin >>> newLevel) & MASK; if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { break; } if (beginIndex) { offsetShift += (1 << newLevel) * beginIndex; } newLevel -= SHIFT; newRoot = newRoot.array[beginIndex]; } // Trim the new sides of the new root. if (newRoot && newOrigin > oldOrigin) { newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } if (newRoot && newTailOffset < oldTailOffset) { newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); } if (offsetShift) { newOrigin -= offsetShift; newCapacity -= offsetShift; } } if (list.__ownerID) { list.size = newCapacity - newOrigin; list._origin = newOrigin; list._capacity = newCapacity; list._level = newLevel; list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); } function mergeIntoListWith(list, merger, iterables) { var iters = []; var maxSize = 0; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = IndexedIterable(value); if (iter.size > maxSize) { maxSize = iter.size; } if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } if (maxSize > list.size) { list = list.setSize(maxSize); } return mergeIntoCollectionWith(list, merger, iters); } function getTailOffset(size) { return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); } createClass(OrderedMap, Map); // @pragma Construction function OrderedMap(value) { return value === null || value === undefined ? emptyOrderedMap() : isOrderedMap(value) ? value : emptyOrderedMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } OrderedMap.of = function(/*...values*/) { return this(arguments); }; OrderedMap.prototype.toString = function() { return this.__toString('OrderedMap {', '}'); }; // @pragma Access OrderedMap.prototype.get = function(k, notSetValue) { var index = this._map.get(k); return index !== undefined ? this._list.get(index)[1] : notSetValue; }; // @pragma Modification OrderedMap.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._map.clear(); this._list.clear(); return this; } return emptyOrderedMap(); }; OrderedMap.prototype.set = function(k, v) { return updateOrderedMap(this, k, v); }; OrderedMap.prototype.remove = function(k) { return updateOrderedMap(this, k, NOT_SET); }; OrderedMap.prototype.wasAltered = function() { return this._map.wasAltered() || this._list.wasAltered(); }; OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._list.__iterate( function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, reverse ); }; OrderedMap.prototype.__iterator = function(type, reverse) { return this._list.fromEntrySeq().__iterator(type, reverse); }; OrderedMap.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); var newList = this._list.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; this._list = newList; return this; } return makeOrderedMap(newMap, newList, ownerID, this.__hash); }; function isOrderedMap(maybeOrderedMap) { return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } OrderedMap.isOrderedMap = isOrderedMap; OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; function makeOrderedMap(map, list, ownerID, hash) { var omap = Object.create(OrderedMap.prototype); omap.size = map ? map.size : 0; omap._map = map; omap._list = list; omap.__ownerID = ownerID; omap.__hash = hash; return omap; } var EMPTY_ORDERED_MAP; function emptyOrderedMap() { return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); } function updateOrderedMap(omap, k, v) { var map = omap._map; var list = omap._list; var i = map.get(k); var has = i !== undefined; var newMap; var newList; if (v === NOT_SET) { // removed if (!has) { return omap; } if (list.size >= SIZE && list.size >= map.size * 2) { newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); if (omap.__ownerID) { newMap.__ownerID = newList.__ownerID = omap.__ownerID; } } else { newMap = map.remove(k); newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); } } else { if (has) { if (v === list.get(i)[1]) { return omap; } newMap = map; newList = list.set(i, [k, v]); } else { newMap = map.set(k, list.size); newList = list.set(list.size, [k, v]); } } if (omap.__ownerID) { omap.size = newMap.size; omap._map = newMap; omap._list = newList; omap.__hash = undefined; return omap; } return makeOrderedMap(newMap, newList); } createClass(ToKeyedSequence, KeyedSeq); function ToKeyedSequence(indexed, useKeys) { this._iter = indexed; this._useKeys = useKeys; this.size = indexed.size; } ToKeyedSequence.prototype.get = function(key, notSetValue) { return this._iter.get(key, notSetValue); }; ToKeyedSequence.prototype.has = function(key) { return this._iter.has(key); }; ToKeyedSequence.prototype.valueSeq = function() { return this._iter.valueSeq(); }; ToKeyedSequence.prototype.reverse = function() {var this$0 = this; var reversedSequence = reverseFactory(this, true); if (!this._useKeys) { reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; } return reversedSequence; }; ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; var mappedSequence = mapFactory(this, mapper, context); if (!this._useKeys) { mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; } return mappedSequence; }; ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var ii; return this._iter.__iterate( this._useKeys ? function(v, k) {return fn(v, k, this$0)} : ((ii = reverse ? resolveSize(this) : 0), function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), reverse ); }; ToKeyedSequence.prototype.__iterator = function(type, reverse) { if (this._useKeys) { return this._iter.__iterator(type, reverse); } var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var ii = reverse ? resolveSize(this) : 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, reverse ? --ii : ii++, step.value, step); }); }; ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; createClass(ToIndexedSequence, IndexedSeq); function ToIndexedSequence(iter) { this._iter = iter; this.size = iter.size; } ToIndexedSequence.prototype.includes = function(value) { return this._iter.includes(value); }; ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); }; ToIndexedSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value, step) }); }; createClass(ToSetSequence, SetSeq); function ToSetSequence(iter) { this._iter = iter; this.size = iter.size; } ToSetSequence.prototype.has = function(key) { return this._iter.includes(key); }; ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); }; ToSetSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, step.value, step.value, step); }); }; createClass(FromEntriesSequence, KeyedSeq); function FromEntriesSequence(entries) { this._iter = entries; this.size = entries.size; } FromEntriesSequence.prototype.entrySeq = function() { return this._iter.toSeq(); }; FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(entry ) { // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return fn( indexedIterable ? entry.get(1) : entry[1], indexedIterable ? entry.get(0) : entry[0], this$0 ); } }, reverse); }; FromEntriesSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return iteratorValue( type, indexedIterable ? entry.get(0) : entry[0], indexedIterable ? entry.get(1) : entry[1], step ); } } }); }; ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; function flipFactory(iterable) { var flipSequence = makeSequence(iterable); flipSequence._iter = iterable; flipSequence.size = iterable.size; flipSequence.flip = function() {return iterable}; flipSequence.reverse = function () { var reversedSequence = iterable.reverse.apply(this); // super.reverse() reversedSequence.flip = function() {return iterable.reverse()}; return reversedSequence; }; flipSequence.has = function(key ) {return iterable.includes(key)}; flipSequence.includes = function(key ) {return iterable.has(key)}; flipSequence.cacheResult = cacheResultThrough; flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); }; flipSequence.__iteratorUncached = function(type, reverse) { if (type === ITERATE_ENTRIES) { var iterator = iterable.__iterator(type, reverse); return new Iterator(function() { var step = iterator.next(); if (!step.done) { var k = step.value[0]; step.value[0] = step.value[1]; step.value[1] = k; } return step; }); } return iterable.__iterator( type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse ); }; return flipSequence; } function mapFactory(iterable, mapper, context) { var mappedSequence = makeSequence(iterable); mappedSequence.size = iterable.size; mappedSequence.has = function(key ) {return iterable.has(key)}; mappedSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v === NOT_SET ? notSetValue : mapper.call(context, v, key, iterable); }; mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate( function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, reverse ); }; mappedSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); return new Iterator(function() { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; return iteratorValue( type, key, mapper.call(context, entry[1], key, iterable), step ); }); }; return mappedSequence; } function reverseFactory(iterable, useKeys) { var reversedSequence = makeSequence(iterable); reversedSequence._iter = iterable; reversedSequence.size = iterable.size; reversedSequence.reverse = function() {return iterable}; if (iterable.flip) { reversedSequence.flip = function () { var flipSequence = flipFactory(iterable); flipSequence.reverse = function() {return iterable.flip()}; return flipSequence; }; } reversedSequence.get = function(key, notSetValue) {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; reversedSequence.has = function(key ) {return iterable.has(useKeys ? key : -1 - key)}; reversedSequence.includes = function(value ) {return iterable.includes(value)}; reversedSequence.cacheResult = cacheResultThrough; reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); }; reversedSequence.__iterator = function(type, reverse) {return iterable.__iterator(type, !reverse)}; return reversedSequence; } function filterFactory(iterable, predicate, context, useKeys) { var filterSequence = makeSequence(iterable); if (useKeys) { filterSequence.has = function(key ) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && !!predicate.call(context, v, key, iterable); }; filterSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && predicate.call(context, v, key, iterable) ? v : notSetValue; }; } filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }, reverse); return iterations; }; filterSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterations = 0; return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; var value = entry[1]; if (predicate.call(context, value, key, iterable)) { return iteratorValue(type, useKeys ? key : iterations++, value, step); } } }); }; return filterSequence; } function countByFactory(iterable, grouper, context) { var groups = Map().asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), 0, function(a ) {return a + 1} ); }); return groups.asImmutable(); } function groupByFactory(iterable, grouper, context) { var isKeyedIter = isKeyed(iterable); var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} ); }); var coerce = iterableClass(iterable); return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); } function sliceFactory(iterable, begin, end, useKeys) { var originalSize = iterable.size; // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } if (wholeSlice(begin, end, originalSize)) { return iterable; } var resolvedBegin = resolveBegin(begin, originalSize); var resolvedEnd = resolveEnd(end, originalSize); // begin or end will be NaN if they were provided as negative numbers and // this iterable's size is unknown. In that case, cache first so there is // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); } // Note: resolvedEnd is undefined when the original sequence's length is // unknown and this slice did not supply an end and should contain all // elements after resolvedBegin. // In that case, resolvedSize will be NaN and sliceSize will remain undefined. var resolvedSize = resolvedEnd - resolvedBegin; var sliceSize; if (resolvedSize === resolvedSize) { sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(iterable); // If iterable.size is undefined, the size of the realized sliceSeq is // unknown at this point unless the number of items to slice is 0 sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; if (!useKeys && isSeq(iterable) && sliceSize >= 0) { sliceSeq.get = function (index, notSetValue) { index = wrapIndex(this, index); return index >= 0 && index < sliceSize ? iterable.get(index + resolvedBegin, notSetValue) : notSetValue; }; } sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; if (sliceSize === 0) { return 0; } if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var skipped = 0; var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k) { if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0) !== false && iterations !== sliceSize; } }); return iterations; }; sliceSeq.__iteratorUncached = function(type, reverse) { if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new Iterator(function() { while (skipped++ < resolvedBegin) { iterator.next(); } if (++iterations > sliceSize) { return iteratorDone(); } var step = iterator.next(); if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations - 1, undefined, step); } else { return iteratorValue(type, iterations - 1, step.value[1], step); } }); }; return sliceSeq; } function takeWhileFactory(iterable, predicate, context) { var takeSequence = makeSequence(iterable); takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; iterable.__iterate(function(v, k, c) {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} ); return iterations; }; takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterating = true; return new Iterator(function() { if (!iterating) { return iteratorDone(); } var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var k = entry[0]; var v = entry[1]; if (!predicate.call(context, v, k, this$0)) { iterating = false; return iteratorDone(); } return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return takeSequence; } function skipWhileFactory(iterable, predicate, context, useKeys) { var skipSequence = makeSequence(iterable); skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k, c) { if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }); return iterations; }; skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var skipping = true; var iterations = 0; return new Iterator(function() { var step, k, v; do { step = iterator.next(); if (step.done) { if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations++, undefined, step); } else { return iteratorValue(type, iterations++, step.value[1], step); } } var entry = step.value; k = entry[0]; v = entry[1]; skipping && (skipping = predicate.call(context, v, k, this$0)); } while (skipping); return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return skipSequence; } function concatFactory(iterable, values) { var isKeyedIterable = isKeyed(iterable); var iters = [iterable].concat(values).map(function(v ) { if (!isIterable(v)) { v = isKeyedIterable ? keyedSeqFromValue(v) : indexedSeqFromValue(Array.isArray(v) ? v : [v]); } else if (isKeyedIterable) { v = KeyedIterable(v); } return v; }).filter(function(v ) {return v.size !== 0}); if (iters.length === 0) { return iterable; } if (iters.length === 1) { var singleton = iters[0]; if (singleton === iterable || isKeyedIterable && isKeyed(singleton) || isIndexed(iterable) && isIndexed(singleton)) { return singleton; } } var concatSeq = new ArraySeq(iters); if (isKeyedIterable) { concatSeq = concatSeq.toKeyedSeq(); } else if (!isIndexed(iterable)) { concatSeq = concatSeq.toSetSeq(); } concatSeq = concatSeq.flatten(true); concatSeq.size = iters.reduce( function(sum, seq) { if (sum !== undefined) { var size = seq.size; if (size !== undefined) { return sum + size; } } }, 0 ); return concatSeq; } function flattenFactory(iterable, depth, useKeys) { var flatSequence = makeSequence(iterable); flatSequence.__iterateUncached = function(fn, reverse) { var iterations = 0; var stopped = false; function flatDeep(iter, currentDepth) {var this$0 = this; iter.__iterate(function(v, k) { if ((!depth || currentDepth < depth) && isIterable(v)) { flatDeep(v, currentDepth + 1); } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { stopped = true; } return !stopped; }, reverse); } flatDeep(iterable, 0); return iterations; }; flatSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(type, reverse); var stack = []; var iterations = 0; return new Iterator(function() { while (iterator) { var step = iterator.next(); if (step.done !== false) { iterator = stack.pop(); continue; } var v = step.value; if (type === ITERATE_ENTRIES) { v = v[1]; } if ((!depth || stack.length < depth) && isIterable(v)) { stack.push(iterator); iterator = v.__iterator(type, reverse); } else { return useKeys ? step : iteratorValue(type, iterations++, v, step); } } return iteratorDone(); }); }; return flatSequence; } function flatMapFactory(iterable, mapper, context) { var coerce = iterableClass(iterable); return iterable.toSeq().map( function(v, k) {return coerce(mapper.call(context, v, k, iterable))} ).flatten(true); } function interposeFactory(iterable, separator) { var interposedSequence = makeSequence(iterable); interposedSequence.size = iterable.size && iterable.size * 2 -1; interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k) {return (!iterations || fn(separator, iterations++, this$0) !== false) && fn(v, iterations++, this$0) !== false}, reverse ); return iterations; }; interposedSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(ITERATE_VALUES, reverse); var iterations = 0; var step; return new Iterator(function() { if (!step || iterations % 2) { step = iterator.next(); if (step.done) { return step; } } return iterations % 2 ? iteratorValue(type, iterations++, separator) : iteratorValue(type, iterations++, step.value, step); }); }; return interposedSequence; } function sortFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } var isKeyedIterable = isKeyed(iterable); var index = 0; var entries = iterable.toSeq().map( function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} ).toArray(); entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( isKeyedIterable ? function(v, i) { entries[i].length = 2; } : function(v, i) { entries[i] = v[1]; } ); return isKeyedIterable ? KeyedSeq(entries) : isIndexed(iterable) ? IndexedSeq(entries) : SetSeq(entries); } function maxFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } if (mapper) { var entry = iterable.toSeq() .map(function(v, k) {return [v, mapper(v, k, iterable)]}) .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); return entry && entry[0]; } else { return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); } } function maxCompare(comparator, a, b) { var comp = comparator(b, a); // b is considered the new max if the comparator declares them equal, but // they are not equal and b is in fact a nullish value. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; } function zipWithFactory(keyIter, zipper, iters) { var zipSequence = makeSequence(keyIter); zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); // Note: this a generic base implementation of __iterate in terms of // __iterator which may be more generically useful in the future. zipSequence.__iterate = function(fn, reverse) { /* generic: var iterator = this.__iterator(ITERATE_ENTRIES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { iterations++; if (fn(step.value[1], step.value[0], this) === false) { break; } } return iterations; */ // indexed: var iterator = this.__iterator(ITERATE_VALUES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } return iterations; }; zipSequence.__iteratorUncached = function(type, reverse) { var iterators = iters.map(function(i ) {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} ); var iterations = 0; var isDone = false; return new Iterator(function() { var steps; if (!isDone) { steps = iterators.map(function(i ) {return i.next()}); isDone = steps.some(function(s ) {return s.done}); } if (isDone) { return iteratorDone(); } return iteratorValue( type, iterations++, zipper.apply(null, steps.map(function(s ) {return s.value})) ); }); }; return zipSequence } // #pragma Helper Functions function reify(iter, seq) { return isSeq(iter) ? seq : iter.constructor(seq); } function validateEntry(entry) { if (entry !== Object(entry)) { throw new TypeError('Expected [K, V] tuple: ' + entry); } } function resolveSize(iter) { assertNotInfinite(iter.size); return ensureSize(iter); } function iterableClass(iterable) { return isKeyed(iterable) ? KeyedIterable : isIndexed(iterable) ? IndexedIterable : SetIterable; } function makeSequence(iterable) { return Object.create( ( isKeyed(iterable) ? KeyedSeq : isIndexed(iterable) ? IndexedSeq : SetSeq ).prototype ); } function cacheResultThrough() { if (this._iter.cacheResult) { this._iter.cacheResult(); this.size = this._iter.size; return this; } else { return Seq.prototype.cacheResult.call(this); } } function defaultComparator(a, b) { return a > b ? 1 : a < b ? -1 : 0; } function forceIterator(keyPath) { var iter = getIterator(keyPath); if (!iter) { // Array might not be iterable in this environment, so we need a fallback // to our wrapped type. if (!isArrayLike(keyPath)) { throw new TypeError('Expected iterable or array-like: ' + keyPath); } iter = getIterator(Iterable(keyPath)); } return iter; } createClass(Record, KeyedCollection); function Record(defaultValues, name) { var hasInitialized; var RecordType = function Record(values) { if (values instanceof RecordType) { return values; } if (!(this instanceof RecordType)) { return new RecordType(values); } if (!hasInitialized) { hasInitialized = true; var keys = Object.keys(defaultValues); setProps(RecordTypePrototype, keys); RecordTypePrototype.size = keys.length; RecordTypePrototype._name = name; RecordTypePrototype._keys = keys; RecordTypePrototype._defaultValues = defaultValues; } this._map = Map(values); }; var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); RecordTypePrototype.constructor = RecordType; return RecordType; } Record.prototype.toString = function() { return this.__toString(recordName(this) + ' {', '}'); }; // @pragma Access Record.prototype.has = function(k) { return this._defaultValues.hasOwnProperty(k); }; Record.prototype.get = function(k, notSetValue) { if (!this.has(k)) { return notSetValue; } var defaultVal = this._defaultValues[k]; return this._map ? this._map.get(k, defaultVal) : defaultVal; }; // @pragma Modification Record.prototype.clear = function() { if (this.__ownerID) { this._map && this._map.clear(); return this; } var RecordType = this.constructor; return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); }; Record.prototype.set = function(k, v) { if (!this.has(k)) { throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); } var newMap = this._map && this._map.set(k, v); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.remove = function(k) { if (!this.has(k)) { return this; } var newMap = this._map && this._map.remove(k); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.wasAltered = function() { return this._map.wasAltered(); }; Record.prototype.__iterator = function(type, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); }; Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); }; Record.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map && this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return makeRecord(this, newMap, ownerID); }; var RecordPrototype = Record.prototype; RecordPrototype[DELETE] = RecordPrototype.remove; RecordPrototype.deleteIn = RecordPrototype.removeIn = MapPrototype.removeIn; RecordPrototype.merge = MapPrototype.merge; RecordPrototype.mergeWith = MapPrototype.mergeWith; RecordPrototype.mergeIn = MapPrototype.mergeIn; RecordPrototype.mergeDeep = MapPrototype.mergeDeep; RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; RecordPrototype.setIn = MapPrototype.setIn; RecordPrototype.update = MapPrototype.update; RecordPrototype.updateIn = MapPrototype.updateIn; RecordPrototype.withMutations = MapPrototype.withMutations; RecordPrototype.asMutable = MapPrototype.asMutable; RecordPrototype.asImmutable = MapPrototype.asImmutable; function makeRecord(likeRecord, map, ownerID) { var record = Object.create(Object.getPrototypeOf(likeRecord)); record._map = map; record.__ownerID = ownerID; return record; } function recordName(record) { return record._name || record.constructor.name || 'Record'; } function setProps(prototype, names) { try { names.forEach(setProp.bind(undefined, prototype)); } catch (error) { // Object.defineProperty failed. Probably IE8. } } function setProp(prototype, name) { Object.defineProperty(prototype, name, { get: function() { return this.get(name); }, set: function(value) { invariant(this.__ownerID, 'Cannot set on an immutable record.'); this.set(name, value); } }); } createClass(Set, SetCollection); // @pragma Construction function Set(value) { return value === null || value === undefined ? emptySet() : isSet(value) && !isOrdered(value) ? value : emptySet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } Set.of = function(/*...values*/) { return this(arguments); }; Set.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; Set.prototype.toString = function() { return this.__toString('Set {', '}'); }; // @pragma Access Set.prototype.has = function(value) { return this._map.has(value); }; // @pragma Modification Set.prototype.add = function(value) { return updateSet(this, this._map.set(value, true)); }; Set.prototype.remove = function(value) { return updateSet(this, this._map.remove(value)); }; Set.prototype.clear = function() { return updateSet(this, this._map.clear()); }; // @pragma Composition Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && iters.length === 1) { return this.constructor(iters[0]); } return this.withMutations(function(set ) { for (var ii = 0; ii < iters.length; ii++) { SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); } }); }; Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (!iters.every(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (iters.some(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.merge = function() { return this.union.apply(this, arguments); }; Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return this.union.apply(this, iters); }; Set.prototype.sort = function(comparator) { // Late binding return OrderedSet(sortFactory(this, comparator)); }; Set.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedSet(sortFactory(this, comparator, mapper)); }; Set.prototype.wasAltered = function() { return this._map.wasAltered(); }; Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); }; Set.prototype.__iterator = function(type, reverse) { return this._map.map(function(_, k) {return k}).__iterator(type, reverse); }; Set.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return this.__make(newMap, ownerID); }; function isSet(maybeSet) { return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); } Set.isSet = isSet; var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; var SetPrototype = Set.prototype; SetPrototype[IS_SET_SENTINEL] = true; SetPrototype[DELETE] = SetPrototype.remove; SetPrototype.mergeDeep = SetPrototype.merge; SetPrototype.mergeDeepWith = SetPrototype.mergeWith; SetPrototype.withMutations = MapPrototype.withMutations; SetPrototype.asMutable = MapPrototype.asMutable; SetPrototype.asImmutable = MapPrototype.asImmutable; SetPrototype.__empty = emptySet; SetPrototype.__make = makeSet; function updateSet(set, newMap) { if (set.__ownerID) { set.size = newMap.size; set._map = newMap; return set; } return newMap === set._map ? set : newMap.size === 0 ? set.__empty() : set.__make(newMap); } function makeSet(map, ownerID) { var set = Object.create(SetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_SET; function emptySet() { return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); } createClass(OrderedSet, Set); // @pragma Construction function OrderedSet(value) { return value === null || value === undefined ? emptyOrderedSet() : isOrderedSet(value) ? value : emptyOrderedSet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } OrderedSet.of = function(/*...values*/) { return this(arguments); }; OrderedSet.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; OrderedSet.prototype.toString = function() { return this.__toString('OrderedSet {', '}'); }; function isOrderedSet(maybeOrderedSet) { return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } OrderedSet.isOrderedSet = isOrderedSet; var OrderedSetPrototype = OrderedSet.prototype; OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; OrderedSetPrototype.__empty = emptyOrderedSet; OrderedSetPrototype.__make = makeOrderedSet; function makeOrderedSet(map, ownerID) { var set = Object.create(OrderedSetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_ORDERED_SET; function emptyOrderedSet() { return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); } createClass(Stack, IndexedCollection); // @pragma Construction function Stack(value) { return value === null || value === undefined ? emptyStack() : isStack(value) ? value : emptyStack().unshiftAll(value); } Stack.of = function(/*...values*/) { return this(arguments); }; Stack.prototype.toString = function() { return this.__toString('Stack [', ']'); }; // @pragma Access Stack.prototype.get = function(index, notSetValue) { var head = this._head; index = wrapIndex(this, index); while (head && index--) { head = head.next; } return head ? head.value : notSetValue; }; Stack.prototype.peek = function() { return this._head && this._head.value; }; // @pragma Modification Stack.prototype.push = function(/*...values*/) { if (arguments.length === 0) { return this; } var newSize = this.size + arguments.length; var head = this._head; for (var ii = arguments.length - 1; ii >= 0; ii--) { head = { value: arguments[ii], next: head }; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pushAll = function(iter) { iter = IndexedIterable(iter); if (iter.size === 0) { return this; } assertNotInfinite(iter.size); var newSize = this.size; var head = this._head; iter.reverse().forEach(function(value ) { newSize++; head = { value: value, next: head }; }); if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pop = function() { return this.slice(1); }; Stack.prototype.unshift = function(/*...values*/) { return this.push.apply(this, arguments); }; Stack.prototype.unshiftAll = function(iter) { return this.pushAll(iter); }; Stack.prototype.shift = function() { return this.pop.apply(this, arguments); }; Stack.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._head = undefined; this.__hash = undefined; this.__altered = true; return this; } return emptyStack(); }; Stack.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } var resolvedBegin = resolveBegin(begin, this.size); var resolvedEnd = resolveEnd(end, this.size); if (resolvedEnd !== this.size) { // super.slice(begin, end); return IndexedCollection.prototype.slice.call(this, begin, end); } var newSize = this.size - resolvedBegin; var head = this._head; while (resolvedBegin--) { head = head.next; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; // @pragma Mutability Stack.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeStack(this.size, this._head, ownerID, this.__hash); }; // @pragma Iteration Stack.prototype.__iterate = function(fn, reverse) { if (reverse) { return this.reverse().__iterate(fn); } var iterations = 0; var node = this._head; while (node) { if (fn(node.value, iterations++, this) === false) { break; } node = node.next; } return iterations; }; Stack.prototype.__iterator = function(type, reverse) { if (reverse) { return this.reverse().__iterator(type); } var iterations = 0; var node = this._head; return new Iterator(function() { if (node) { var value = node.value; node = node.next; return iteratorValue(type, iterations++, value); } return iteratorDone(); }); }; function isStack(maybeStack) { return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); } Stack.isStack = isStack; var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; var StackPrototype = Stack.prototype; StackPrototype[IS_STACK_SENTINEL] = true; StackPrototype.withMutations = MapPrototype.withMutations; StackPrototype.asMutable = MapPrototype.asMutable; StackPrototype.asImmutable = MapPrototype.asImmutable; StackPrototype.wasAltered = MapPrototype.wasAltered; function makeStack(size, head, ownerID, hash) { var map = Object.create(StackPrototype); map.size = size; map._head = head; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_STACK; function emptyStack() { return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); } /** * Contributes additional methods to a constructor */ function mixin(ctor, methods) { var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor; } Iterable.Iterator = Iterator; mixin(Iterable, { // ### Conversion to other types toArray: function() { assertNotInfinite(this.size); var array = new Array(this.size || 0); this.valueSeq().__iterate(function(v, i) { array[i] = v; }); return array; }, toIndexedSeq: function() { return new ToIndexedSequence(this); }, toJS: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} ).__toJS(); }, toJSON: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} ).__toJS(); }, toKeyedSeq: function() { return new ToKeyedSequence(this, true); }, toMap: function() { // Use Late Binding here to solve the circular dependency. return Map(this.toKeyedSeq()); }, toObject: function() { assertNotInfinite(this.size); var object = {}; this.__iterate(function(v, k) { object[k] = v; }); return object; }, toOrderedMap: function() { // Use Late Binding here to solve the circular dependency. return OrderedMap(this.toKeyedSeq()); }, toOrderedSet: function() { // Use Late Binding here to solve the circular dependency. return OrderedSet(isKeyed(this) ? this.valueSeq() : this); }, toSet: function() { // Use Late Binding here to solve the circular dependency. return Set(isKeyed(this) ? this.valueSeq() : this); }, toSetSeq: function() { return new ToSetSequence(this); }, toSeq: function() { return isIndexed(this) ? this.toIndexedSeq() : isKeyed(this) ? this.toKeyedSeq() : this.toSetSeq(); }, toStack: function() { // Use Late Binding here to solve the circular dependency. return Stack(isKeyed(this) ? this.valueSeq() : this); }, toList: function() { // Use Late Binding here to solve the circular dependency. return List(isKeyed(this) ? this.valueSeq() : this); }, // ### Common JavaScript methods and properties toString: function() { return '[Iterable]'; }, __toString: function(head, tail) { if (this.size === 0) { return head + tail; } return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; }, // ### ES6 Collection methods (ES6 Array and Map) concat: function() {var values = SLICE$0.call(arguments, 0); return reify(this, concatFactory(this, values)); }, includes: function(searchValue) { return this.some(function(value ) {return is(value, searchValue)}); }, entries: function() { return this.__iterator(ITERATE_ENTRIES); }, every: function(predicate, context) { assertNotInfinite(this.size); var returnValue = true; this.__iterate(function(v, k, c) { if (!predicate.call(context, v, k, c)) { returnValue = false; return false; } }); return returnValue; }, filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, true)); }, find: function(predicate, context, notSetValue) { var entry = this.findEntry(predicate, context); return entry ? entry[1] : notSetValue; }, findEntry: function(predicate, context) { var found; this.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { found = [k, v]; return false; } }); return found; }, findLastEntry: function(predicate, context) { return this.toSeq().reverse().findEntry(predicate, context); }, forEach: function(sideEffect, context) { assertNotInfinite(this.size); return this.__iterate(context ? sideEffect.bind(context) : sideEffect); }, join: function(separator) { assertNotInfinite(this.size); separator = separator !== undefined ? '' + separator : ','; var joined = ''; var isFirst = true; this.__iterate(function(v ) { isFirst ? (isFirst = false) : (joined += separator); joined += v !== null && v !== undefined ? v.toString() : ''; }); return joined; }, keys: function() { return this.__iterator(ITERATE_KEYS); }, map: function(mapper, context) { return reify(this, mapFactory(this, mapper, context)); }, reduce: function(reducer, initialReduction, context) { assertNotInfinite(this.size); var reduction; var useFirst; if (arguments.length < 2) { useFirst = true; } else { reduction = initialReduction; } this.__iterate(function(v, k, c) { if (useFirst) { useFirst = false; reduction = v; } else { reduction = reducer.call(context, reduction, v, k, c); } }); return reduction; }, reduceRight: function(reducer, initialReduction, context) { var reversed = this.toKeyedSeq().reverse(); return reversed.reduce.apply(reversed, arguments); }, reverse: function() { return reify(this, reverseFactory(this, true)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, true)); }, some: function(predicate, context) { return !this.every(not(predicate), context); }, sort: function(comparator) { return reify(this, sortFactory(this, comparator)); }, values: function() { return this.__iterator(ITERATE_VALUES); }, // ### More sequential methods butLast: function() { return this.slice(0, -1); }, isEmpty: function() { return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); }, count: function(predicate, context) { return ensureSize( predicate ? this.toSeq().filter(predicate, context) : this ); }, countBy: function(grouper, context) { return countByFactory(this, grouper, context); }, equals: function(other) { return deepEqual(this, other); }, entrySeq: function() { var iterable = this; if (iterable._cache) { // We cache as an entries array, so we can just return the cache! return new ArraySeq(iterable._cache); } var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; return entriesSequence; }, filterNot: function(predicate, context) { return this.filter(not(predicate), context); }, findLast: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); }, first: function() { return this.find(returnTrue); }, flatMap: function(mapper, context) { return reify(this, flatMapFactory(this, mapper, context)); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, true)); }, fromEntrySeq: function() { return new FromEntriesSequence(this); }, get: function(searchKey, notSetValue) { return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); }, getIn: function(searchKeyPath, notSetValue) { var nested = this; // Note: in an ES6 environment, we would prefer: // for (var key of searchKeyPath) { var iter = forceIterator(searchKeyPath); var step; while (!(step = iter.next()).done) { var key = step.value; nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; if (nested === NOT_SET) { return notSetValue; } } return nested; }, groupBy: function(grouper, context) { return groupByFactory(this, grouper, context); }, has: function(searchKey) { return this.get(searchKey, NOT_SET) !== NOT_SET; }, hasIn: function(searchKeyPath) { return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; }, isSubset: function(iter) { iter = typeof iter.includes === 'function' ? iter : Iterable(iter); return this.every(function(value ) {return iter.includes(value)}); }, isSuperset: function(iter) { iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); return iter.isSubset(this); }, keySeq: function() { return this.toSeq().map(keyMapper).toIndexedSeq(); }, last: function() { return this.toSeq().reverse().first(); }, max: function(comparator) { return maxFactory(this, comparator); }, maxBy: function(mapper, comparator) { return maxFactory(this, comparator, mapper); }, min: function(comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); }, minBy: function(mapper, comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); }, rest: function() { return this.slice(1); }, skip: function(amount) { return this.slice(Math.max(0, amount)); }, skipLast: function(amount) { return reify(this, this.toSeq().reverse().skip(amount).reverse()); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, true)); }, skipUntil: function(predicate, context) { return this.skipWhile(not(predicate), context); }, sortBy: function(mapper, comparator) { return reify(this, sortFactory(this, comparator, mapper)); }, take: function(amount) { return this.slice(0, Math.max(0, amount)); }, takeLast: function(amount) { return reify(this, this.toSeq().reverse().take(amount).reverse()); }, takeWhile: function(predicate, context) { return reify(this, takeWhileFactory(this, predicate, context)); }, takeUntil: function(predicate, context) { return this.takeWhile(not(predicate), context); }, valueSeq: function() { return this.toIndexedSeq(); }, // ### Hashable Object hashCode: function() { return this.__hash || (this.__hash = hashIterable(this)); } // ### Internal // abstract __iterate(fn, reverse) // abstract __iterator(type, reverse) }); // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; var IterablePrototype = Iterable.prototype; IterablePrototype[IS_ITERABLE_SENTINEL] = true; IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; IterablePrototype.__toJS = IterablePrototype.toArray; IterablePrototype.__toStringMapper = quoteString; IterablePrototype.inspect = IterablePrototype.toSource = function() { return this.toString(); }; IterablePrototype.chain = IterablePrototype.flatMap; IterablePrototype.contains = IterablePrototype.includes; // Temporary warning about using length (function () { try { Object.defineProperty(IterablePrototype, 'length', { get: function () { if (!Iterable.noLengthWarning) { var stack; try { throw new Error(); } catch (error) { stack = error.stack; } if (stack.indexOf('_wrapObject') === -1) { console && console.warn && console.warn( 'iterable.length has been deprecated, '+ 'use iterable.size or iterable.count(). '+ 'This warning will become a silent error in a future version. ' + stack ); return this.size; } } } }); } catch (e) {} })(); mixin(KeyedIterable, { // ### More sequential methods flip: function() { return reify(this, flipFactory(this)); }, findKey: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLastKey: function(predicate, context) { return this.toSeq().reverse().findKey(predicate, context); }, keyOf: function(searchValue) { return this.findKey(function(value ) {return is(value, searchValue)}); }, lastKeyOf: function(searchValue) { return this.findLastKey(function(value ) {return is(value, searchValue)}); }, mapEntries: function(mapper, context) {var this$0 = this; var iterations = 0; return reify(this, this.toSeq().map( function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} ).fromEntrySeq() ); }, mapKeys: function(mapper, context) {var this$0 = this; return reify(this, this.toSeq().flip().map( function(k, v) {return mapper.call(context, k, v, this$0)} ).flip() ); } }); var KeyedIterablePrototype = KeyedIterable.prototype; KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; KeyedIterablePrototype.__toJS = IterablePrototype.toObject; KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; mixin(IndexedIterable, { // ### Conversion to other types toKeyedSeq: function() { return new ToKeyedSequence(this, false); }, // ### ES6 Collection methods (ES6 Array and Map) filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, false)); }, findIndex: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry ? entry[0] : -1; }, indexOf: function(searchValue) { var key = this.toKeyedSeq().keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function(searchValue) { var key = this.toKeyedSeq().reverse().keyOf(searchValue); return key === undefined ? -1 : key; // var index = // return this.toSeq().reverse().indexOf(searchValue); }, reverse: function() { return reify(this, reverseFactory(this, false)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, false)); }, splice: function(index, removeNum /*, ...values*/) { var numArgs = arguments.length; removeNum = Math.max(removeNum | 0, 0); if (numArgs === 0 || (numArgs === 2 && !removeNum)) { return this; } // If index is negative, it should resolve relative to the size of the // collection. However size may be expensive to compute if not cached, so // only call count() if the number is in fact negative. index = resolveBegin(index, index < 0 ? this.count() : this.size); var spliced = this.slice(0, index); return reify( this, numArgs === 1 ? spliced : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) ); }, // ### More collection methods findLastIndex: function(predicate, context) { var key = this.toKeyedSeq().findLastKey(predicate, context); return key === undefined ? -1 : key; }, first: function() { return this.get(0); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, false)); }, get: function(index, notSetValue) { index = wrapIndex(this, index); return (index < 0 || (this.size === Infinity || (this.size !== undefined && index > this.size))) ? notSetValue : this.find(function(_, key) {return key === index}, undefined, notSetValue); }, has: function(index) { index = wrapIndex(this, index); return index >= 0 && (this.size !== undefined ? this.size === Infinity || index < this.size : this.indexOf(index) !== -1 ); }, interpose: function(separator) { return reify(this, interposeFactory(this, separator)); }, interleave: function(/*...iterables*/) { var iterables = [this].concat(arrCopy(arguments)); var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); var interleaved = zipped.flatten(true); if (zipped.size) { interleaved.size = zipped.size * iterables.length; } return reify(this, interleaved); }, last: function() { return this.get(-1); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, false)); }, zip: function(/*, ...iterables */) { var iterables = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, iterables)); }, zipWith: function(zipper/*, ...iterables */) { var iterables = arrCopy(arguments); iterables[0] = this; return reify(this, zipWithFactory(this, zipper, iterables)); } }); IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; mixin(SetIterable, { // ### ES6 Collection methods (ES6 Array and Map) get: function(value, notSetValue) { return this.has(value) ? value : notSetValue; }, includes: function(value) { return this.has(value); }, // ### More sequential methods keySeq: function() { return this.valueSeq(); } }); SetIterable.prototype.has = IterablePrototype.includes; // Mixin subclasses mixin(KeyedSeq, KeyedIterable.prototype); mixin(IndexedSeq, IndexedIterable.prototype); mixin(SetSeq, SetIterable.prototype); mixin(KeyedCollection, KeyedIterable.prototype); mixin(IndexedCollection, IndexedIterable.prototype); mixin(SetCollection, SetIterable.prototype); // #pragma Helper functions function keyMapper(v, k) { return k; } function entryMapper(v, k) { return [k, v]; } function not(predicate) { return function() { return !predicate.apply(this, arguments); } } function neg(predicate) { return function() { return -predicate.apply(this, arguments); } } function quoteString(value) { return typeof value === 'string' ? JSON.stringify(value) : value; } function defaultZipper() { return arrCopy(arguments); } function defaultNegComparator(a, b) { return a < b ? 1 : a > b ? -1 : 0; } function hashIterable(iterable) { if (iterable.size === Infinity) { return 0; } var ordered = isOrdered(iterable); var keyed = isKeyed(iterable); var h = ordered ? 1 : 0; var size = iterable.__iterate( keyed ? ordered ? function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : ordered ? function(v ) { h = 31 * h + hash(v) | 0; } : function(v ) { h = h + hash(v) | 0; } ); return murmurHashOfSize(size, h); } function murmurHashOfSize(size, h) { h = imul(h, 0xCC9E2D51); h = imul(h << 15 | h >>> -15, 0x1B873593); h = imul(h << 13 | h >>> -13, 5); h = (h + 0xE6546B64 | 0) ^ size; h = imul(h ^ h >>> 16, 0x85EBCA6B); h = imul(h ^ h >>> 13, 0xC2B2AE35); h = smi(h ^ h >>> 16); return h; } function hashMerge(a, b) { return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int } var Immutable = { Iterable: Iterable, Seq: Seq, Collection: Collection, Map: Map, OrderedMap: OrderedMap, List: List, Stack: Stack, Set: Set, OrderedSet: OrderedSet, Record: Record, Range: Range, Repeat: Repeat, is: is, fromJS: fromJS }; return Immutable; })); }); var dist$2 = _commonjsHelpers.createCommonjsModule(function (module, exports) { (function webpackUniversalModuleDefinition(root, factory) { module.exports = factory(React__default); })(window, function(__WEBPACK_EXTERNAL_MODULE__2__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 20); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); var compressImage = exports.compressImage = function compressImage(url) { var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1280; var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 800; return new Promise(function (resolve, reject) { var image = new Image(); image.src = url; image.onerror = function (error) { reject(error); }; image.onload = function () { try { var compressCanvas = document.createElement('canvas'); var scale = this.width > width || this.height > height ? this.width > this.height ? width / this.width : height / this.height : 1; compressCanvas.width = this.width * scale; compressCanvas.height = this.height * scale; var canvasContext = compressCanvas.getContext('2d'); canvasContext.drawImage(this, 0, 0, compressCanvas.width, compressCanvas.height); resolve({ url: compressCanvas.toDataURL('image/png', 1), width: compressCanvas.width, height: compressCanvas.height }); } catch (error) { reject(error); } }; }); }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); var UniqueIndex = exports.UniqueIndex = function UniqueIndex() { if (isNaN(window.__BRAFT_MM_UNIQUE_INDEX__)) { window.__BRAFT_MM_UNIQUE_INDEX__ = 1; } else { window.__BRAFT_MM_UNIQUE_INDEX__ += 1; } return window.__BRAFT_MM_UNIQUE_INDEX__; }; /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__2__; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: 'Kaldır', cancel: 'İptal', confirm: 'Onayla', insert: 'Seçilenleri ekle', width: 'Genişlik', height: 'Yükseklik', image: 'Resim', video: 'Görüntü', audio: 'Ses', embed: 'Nesne göm', caption: 'Kitaplık', dragTip: 'Tıkla ya da dosya sürükle', dropTip: 'Yüklemek için sürükleyin', selectAll: 'Tümünü seç', deselect: 'Seçimi kaldır', removeSelected: 'Seçilenleri kaldır', externalInputPlaceHolder: 'Kaynak adı|Kaynak bağlantısı', externalInputTip: 'Kaynak asını ve bağlantısını "|" ile ayırın ve Enter\' a basın.', addLocalFile: 'Yerel\' den ekle', addExternalSource: 'Harici kaynaktan ekle', unnamedItem: 'Adlandırılmamış giriş', confirmInsert: 'Seçilenleri ekle' }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: '削除する', cancel: 'キャンセル', confirm: '確認する', insert: '選択したアイテムを挿入', width: '幅', height: '身長', image: '絵', video: 'ビデオ', audio: '音声', embed: '埋め込みメディア', caption: 'メディアライブラリー', dragTip: 'ファイルをこの位置までクリックまたはドラッグします', dropTip: 'アップロードするマウスを放します', selectAll: 'すべて選択', deselect: '選択を解除', removeSelected: '選択したアイテムを削除', externalInputPlaceHolder: 'リソース名|リソースアドレス', externalInputTip: 'リソース名とリソースアドレスは "|"で区切ります。', addLocalFile: 'ローカルリソースを追加する', addExternalSource: 'ネットワークリソースを追加する', unnamedItem: '名前のないアイテム', confirmInsert: '選択したアイテムを挿入' }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: '삭제', cancel: '취소', confirm: '확인', insert: '선택한항목삽입', width: '너비', height: '높이', image: '그림', video: '비디오', audio: '오디오', embed: '임베디드미디어', caption: '미디어라이브러리', dragTip: '파일을 클릭하거나이 지점으로 드래그하십시오.', dropTip: '업로드하려면마우스를놓으십시오.', selectAll: '모두 선택', deselect: '선택 취소', removeSelected: '선택한 항목 삭제', externalInputPlaceHolder: '리소스 이름 | 리소스 주소', externalInputTip: '자원 이름과 자원 주소를 "|"', addLocalFile: '로컬 리소스 추가', addExternalSource: '네트워크 리소스 추가', unnamedItem: '이름없는 항목', confirmInsert: '선택한 항목 삽입' }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: 'Usuń', cancel: 'Anuluj', confirm: 'Potwierdź', insert: 'Wstaw wybrane elementy', width: 'Szerokość', height: 'Wysokość', image: 'Obraz', video: 'Wideo', audio: 'Dźwięk', embed: 'Obiekt', caption: 'Biblioteka mediów', dragTip: 'Kliknij lub przenieś tu pliki', dropTip: 'Upuść aby dodać plik', selectAll: 'Zaznacz wszystko', deselect: 'Odznacz', removeSelected: 'Usuń wybrane', externalInputPlaceHolder: 'Nazwa źródła|Adres URL', externalInputTip: 'Oddziel nazwę i adres URL źródła z pomocą "|", Potwierdź Enter-em', addLocalFile: 'Dodaj z komputera', addExternalSource: 'Dodaj z Internetu', unnamedItem: 'Bez nazwy', confirmInsert: 'Dodaj wybrane elementy' }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: '删除', cancel: '取消', confirm: '确认', insert: '插入所选项目', width: '宽度', height: '高度', image: '图片', video: '视频', audio: '音频', embed: '嵌入式媒体', caption: '媒体库', dragTip: '点击或拖动文件至此', dropTip: '放开鼠标以上传', selectAll: '选择全部', deselect: '取消选择', removeSelected: '删除选中项目', externalInputPlaceHolder: '资源名称|资源地址', externalInputTip: '使用“|”分隔资源名称和资源地址', addLocalFile: '添加本地资源', addExternalSource: '添加网络资源', unnamedItem: '未命名项目', confirmInsert: '插入选中项目' }; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: '删除', cancel: '取消', confirm: '确认', insert: '插入所选项目', width: '宽度', height: '高度', image: '图片', video: '视频', audio: '音频', embed: '嵌入式媒体', caption: '媒体库', dragTip: '点击或拖动文件至此', dropTip: '放开鼠标以上传', selectAll: '选择全部', deselect: '取消选择', removeSelected: '删除选中项目', externalInputPlaceHolder: '资源名称|资源地址', externalInputTip: '使用“|”分隔资源名称和资源地址', addLocalFile: '添加本地资源', addExternalSource: '添加网络资源', unnamedItem: '未命名项目', confirmInsert: '插入选中项目' }; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { remove: 'Remove', cancel: 'Cancel', confirm: 'Confirm', insert: 'Insert Selected Items', width: 'Width', height: 'Height', image: 'Image', video: 'Video', audio: 'Audio', embed: 'Embed', caption: 'Media Library', dragTip: 'Click Or Drag Files Here', dropTip: 'Drop To Upload', selectAll: 'Select All', deselect: 'Deselect', removeSelected: 'Remove Selected Items', externalInputPlaceHolder: 'Source Name|Source URL', externalInputTip: 'Split source name and source URL with "|", confirm by hit Enter.', addLocalFile: 'Add from local', addExternalSource: 'Add from Internet', unnamedItem: 'Unnamed Item', confirmInsert: 'Insert selected items' }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", { value: true }); var _en = __webpack_require__(9); var _en2 = _interopRequireDefault(_en); var _zh = __webpack_require__(8); var _zh2 = _interopRequireDefault(_zh); var _zhHant = __webpack_require__(7); var _zhHant2 = _interopRequireDefault(_zhHant); var _pl = __webpack_require__(6); var _pl2 = _interopRequireDefault(_pl); var _kr = __webpack_require__(5); var _kr2 = _interopRequireDefault(_kr); var _jpn = __webpack_require__(4); var _jpn2 = _interopRequireDefault(_jpn); var _tr = __webpack_require__(3); var _tr2 = _interopRequireDefault(_tr); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { "en": _en2.default, "zh": _zh2.default, "zh-hant": _zhHant2.default, "pl": _pl2.default, "kr": _kr2.default, "jpn": _jpn2.default, "tr": _tr2.default }; /***/ }), /* 11 */ /***/ (function(module, exports) { /** * When source maps are enabled, `style-loader` uses a link element with a data-uri to * embed the css on the page. This breaks all relative urls because now they are relative to a * bundle instead of the current page. * * One solution is to only use full urls, but that may be impossible. * * Instead, this function "fixes" the relative urls to be absolute according to the current page location. * * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command. * */ module.exports = function (css) { // get current location var location = typeof window !== "undefined" && window.location; if (!location) { throw new Error("fixUrls requires window.location"); } // blank or null? if (!css || typeof css !== "string") { return css; } var baseUrl = location.protocol + "//" + location.host; var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/"); // convert each url(...) /* This regular expression is just a way to recursively match brackets within a string. /url\s*\( = Match on the word "url" with any whitespace after it and then a parens ( = Start a capturing group (?: = Start a non-capturing group [^)(] = Match anything that isn't a parentheses | = OR \( = Match a start parentheses (?: = Start another non-capturing groups [^)(]+ = Match anything that isn't a parentheses | = OR \( = Match a start parentheses [^)(]* = Match anything that isn't a parentheses \) = Match a end parentheses ) = End Group *\) = Match anything and then a close parens ) = Close non-capturing group * = Match anything ) = Close capturing group \) = Match a close parens /gi = Get all matches, not the first. Be case insensitive. */ var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) { // strip quotes (if they exist) var unquotedOrigUrl = origUrl .trim() .replace(/^"(.*)"$/, function(o, $1){ return $1; }) .replace(/^'(.*)'$/, function(o, $1){ return $1; }); // already a full url? no change if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) { return fullMatch; } // convert the url to a full url var newUrl; if (unquotedOrigUrl.indexOf("//") === 0) { //TODO: should we add protocol? newUrl = unquotedOrigUrl; } else if (unquotedOrigUrl.indexOf("/") === 0) { // path should be relative to the base url newUrl = baseUrl + unquotedOrigUrl; // already starts with '/' } else { // path should be relative to current directory newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './' } // send back the fixed url(...) return "url(" + JSON.stringify(newUrl) + ")"; }); // send back the fixed css return fixedCss; }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}; var memoize = function (fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }; var isOldIE = memoize(function () { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 return window && document && document.all && !window.atob; }); var getTarget = function (target) { return document.querySelector(target); }; var getElement = (function (fn) { var memo = {}; return function(target) { // If passing function in options, then use it for resolve "head" element. // Useful for Shadow Root style i.e // { // insertInto: function () { return document.querySelector("#foo").shadowRoot } // } if (typeof target === 'function') { return target(); } if (typeof memo[target] === "undefined") { var styleTarget = getTarget.call(this, target); // Special case to return head of iframe instead of iframe itself if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { try { // This will throw an exception if access to iframe is blocked // due to cross-origin restrictions styleTarget = styleTarget.contentDocument.head; } catch(e) { styleTarget = null; } } memo[target] = styleTarget; } return memo[target] }; })(); var singleton = null; var singletonCounter = 0; var stylesInsertedAtTop = []; var fixUrls = __webpack_require__(11); module.exports = function(list, options) { if (typeof DEBUG !== "undefined" && DEBUG) { if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; options.attrs = typeof options.attrs === "object" ? options.attrs : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of