(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["SirTrevor"] = factory(); else root["SirTrevor"] = factory(); })(window, function() { 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 = 93); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.isEmpty = __webpack_require__(119); exports.isFunction = __webpack_require__(28); exports.isObject = __webpack_require__(18); exports.isString = __webpack_require__(129); exports.isUndefined = __webpack_require__(130); exports.result = __webpack_require__(131); exports.template = __webpack_require__(132); exports.uniqueId = __webpack_require__(139); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var config = __webpack_require__(2); var Dom = __webpack_require__(3); var urlRegex = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/; var utils = { getInstance: function getInstance(identifier) { if (_.isUndefined(identifier)) { return config.instances[0]; } if (_.isString(identifier)) { return config.instances.find(function (editor) { return editor.ID === identifier; }); } return config.instances[identifier]; }, getInstanceBySelection: function getInstanceBySelection() { return utils.getInstance(Dom.getClosest(window.getSelection().anchorNode.parentNode, '.st-block').getAttribute('data-instance')); }, getBlockBySelection: function getBlockBySelection() { var instance = utils.getInstanceBySelection(); if (!instance) return; return instance.findBlockById(Dom.getClosest(window.getSelection().anchorNode.parentNode, '.st-block').id); }, log: function log() { if (!_.isUndefined(console) && config.debug) { console.log.apply(console, arguments); } }, isURI: function isURI(string) { return urlRegex.test(string); }, titleize: function titleize(str) { if (str === null) { return ''; } str = String(str).toLowerCase(); return str.replace(/(?:^|\s|-)\S/g, function (c) { return c.toUpperCase(); }); }, classify: function classify(str) { return utils.titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, ''); }, capitalize: function capitalize(string) { return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); }, flatten: function flatten(obj) { var x = {}; (Array.isArray(obj) ? obj : Object.keys(obj)).forEach(function (i) { x[i] = true; }); return x; }, underscored: function underscored(str) { return str.trim().replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase(); }, reverse: function reverse(str) { return str.split("").reverse().join(""); }, toSlug: function toSlug(str) { return str.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-'); }, leftTrim: function leftTrim(str) { return str.replace(/^\s+/, ''); } }; module.exports = utils; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var drop_options = { html: ['
', '"/>', '

<%= i18n.t("general:drop", { block: "" + _.result(block, "title") + "" }) %>', '

'].join('\n'), re_render_on_reorder: false }; var paste_options = { html: ['"', ' class="st-block__paste-input st-paste-block">'].join('') }; var upload_options = { html: ['
', '', '', '
'].join('\n') }; module.exports = { debug: false, scribeDebug: false, skipValidation: false, version: "0.4.0", language: "en", instances: [], defaults: { defaultType: false, spinner: { className: 'st-spinner', lines: 9, length: 8, width: 3, radius: 6, color: '#000', speed: 1.4, trail: 57, shadow: false, left: '50%', top: '50%' }, Block: { drop_options: drop_options, paste_options: paste_options, upload_options: upload_options }, blockLimit: 0, blockTypeLimits: {}, required: [], uploadUrl: '/attachments', attachmentName: 'attachment[name]', attachmentFile: 'attachment[file]', attachmentUid: 'attachment[uid]', baseImageUrl: '/sir-trevor-uploads/', iconUrl: '../src/icons/sir-trevor-icons.svg', errorsContainer: undefined, convertFromMarkdown: true, joinListBlocksOnBlockRemove: false, formatBar: { commands: [{ name: "Bold", title: "bold", iconName: "fmt-bold", cmd: "bold", keyCode: 66, text: "B" }, { name: "Italic", title: "italic", iconName: "fmt-italic", cmd: "italic", keyCode: 73, text: "i" }, { name: "Link", title: "link", iconName: "fmt-link", cmd: "linkPrompt", keyCode: 75, text: "link" }, { name: "Unlink", title: "unlink", iconName: "fmt-unlink", cmd: "unlink", text: "link" }, { name: "Heading", title: "heading", iconName: "fmt-heading", cmd: "heading", text: "heading" }, { name: "Quote", title: "quote", iconName: "fmt-quote", cmd: "quote", text: "quote" }] }, ajaxOptions: { headers: {} }, focusOnInit: true, selectionMouse: true, selectionCopy: true, selectionCut: true, selectionPaste: true, selectionLimitToEditor: true } }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); // disabling undefined warnings until jshint can handle argument destructing var Dom = Object.create(null); Dom.setAttributes = function (el) { var attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (attributes.html) { el.innerHTML = _.result(attributes, 'html'); delete attributes.html; } if (attributes.text) { el.textContent = attributes.text; delete attributes.text; } Object.keys(attributes).forEach(function (key) { el.setAttribute(key, attributes[key]); }); return el; }; Dom.createElement = function (tagName) { var attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var el = document.createElement(tagName); Dom.setAttributes(el, attributes); return el; }; Dom.insertAfter = function (el, referenceNode) { referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling); }; Dom.remove = function (el) { if (el && el.parentNode) { el.parentNode.removeChild(el); } }; Dom.replaceWith = function (el, referenceNode) { Dom.remove(referenceNode); el.parentNode.replaceChild(referenceNode, el); }; Dom.hide = function (el) { el.style.display = 'none'; }; Dom.show = function (el) { el.style.display = ''; }; Dom.matches = function (proto) { var matcher = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector || function (selector) { var element = this; var matches = (element.document || element.ownerDocument).querySelectorAll(selector); var i = 0; while (matches[i] && matches[i] !== element) { i++; } return matches[i] ? true : false; }; return function (el, selector) { return matcher.call(el, selector); }; }(Element.prototype); Dom.getClosest = function (elem, selector) { for (elem; elem && elem !== document.body; elem = elem.parentNode) { if (Dom.matches(elem, selector)) { break; } } return elem; }; Dom.wrap = function (toWrap, wrapper) { wrapper = wrapper || document.createElement('div'); if (toWrap.nextSibling) { toWrap.parentNode.insertBefore(wrapper, toWrap.nextSibling); } else { toWrap.parentNode.appendChild(wrapper); } return wrapper.appendChild(toWrap); }; Dom.createDocumentFragmentFromString = function (html) { var frag = document.createDocumentFragment(); var elem = document.createElement('div'); elem.innerHTML = html; while (elem.childNodes[0]) { frag.appendChild(elem.childNodes[0]); } return frag; }; module.exports = Dom; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = Object.assign({}, __webpack_require__(9)); /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /** * 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) { true ? module.exports = factory() : undefined; }(this, function () { 'use strict';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') { if (o !== o || o === Infinity) { return 0; } 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.of = function() {var keyValues = SLICE$0.call(arguments, 0); 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() { 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 : false || 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) { if (end === Infinity) { end = originalSize; } else { 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)); } if (this._map && !this._map.has(k)) { var defaultVal = this._defaultValues[k]; if (v === defaultVal) { return 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; }, 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); }, findEntry: function(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(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLast: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); }, findLastEntry: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue); }, findLastKey: function(predicate, context) { return this.toKeyedSeq().reverse().findKey(predicate, context); }, 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); }, keyOf: function(searchValue) { return this.findKey(function(value ) {return is(value, searchValue)}); }, keySeq: function() { return this.toSeq().map(keyMapper).toIndexedSeq(); }, last: function() { return this.toSeq().reverse().first(); }, lastKeyOf: function(searchValue) { return this.toKeyedSeq().reverse().keyOf(searchValue); }, 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; mixin(KeyedIterable, { // ### More sequential methods flip: function() { return reify(this, flipFactory(this)); }, 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.keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function(searchValue) { var key = this.lastKeyOf(searchValue); return key === undefined ? -1 : key; }, 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 entry = this.findLastEntry(predicate, context); return entry ? entry[0] : -1; }, 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); }, keySeq: function() { return Range(0, this.size); }, 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; SetIterable.prototype.contains = SetIterable.prototype.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) : String(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; })); /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* Generic function binding utility, used by lots of our classes */ module.exports = { bound: [], _bindFunctions: function _bindFunctions() { this.bound.forEach(function (f) { this[f] = this[f].bind(this); }, this); } }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * Used as the maximum length of an array-like value. * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * for more details. */ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on ES `ToLength`. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength) * for more details. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } return isLength; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var ScribeInterface = __webpack_require__(68); var config = __webpack_require__(2); var utils = __webpack_require__(1); var Dom = __webpack_require__(3); var Events = __webpack_require__(10); var BlockMixins = __webpack_require__(65); var SimpleBlock = __webpack_require__(87); var BlockReorder = __webpack_require__(39); var BlockDeletion = __webpack_require__(83); var BlockPositioner = __webpack_require__(81); var EventBus = __webpack_require__(4); var _require = __webpack_require__(226), Spinner = _require.Spinner; var _require2 = __webpack_require__(16), trimScribeContent = _require2.trimScribeContent; ; var DELETE_TEMPLATE = __webpack_require__(227); var Block = function Block(data, instance_id, mediator, options, editorOptions) { SimpleBlock.apply(this, arguments); }; Block.prototype = Object.create(SimpleBlock.prototype); Block.prototype.constructor = Block; Object.assign(Block.prototype, SimpleBlock.fn, __webpack_require__(84), { bound: ["_handleContentPaste", "_onFocus", "_onBlur", "onDrop", "onDeleteClick", "clearInsertedStyles", "getSelectionForFormatter", "onBlockRender", "onDeleteConfirm", "onPositionerClick"], className: 'st-block', attributes: function attributes() { return Object.assign(SimpleBlock.fn.attributes.call(this)); }, icon_name: 'default', validationFailMsg: function validationFailMsg() { return i18n.t('errors:validation_fail', { type: _.isFunction(this.title) ? this.title() : this.title }); }, editorHTML: "
", toolbarEnabled: true, availableMixins: ['droppable', 'pastable', 'uploadable', 'fetchable', 'ajaxable', 'controllable', 'multi_editable', 'textable'], droppable: false, pastable: false, uploadable: false, fetchable: false, ajaxable: false, mergeable: false, multi_editable: false, textable: false, drop_options: {}, paste_options: {}, upload_options: {}, formattable: true, supressKeyListeners: false, _previousSelection: '', initialize: function initialize() {}, toMarkdown: function toMarkdown(markdown) { return markdown; }, toHTML: function toHTML(html) { return html; }, withMixin: function withMixin(mixin) { if (!_.isObject(mixin)) { return; } var initializeMethod = "initialize" + mixin.mixinName; if (_.isUndefined(this[initializeMethod])) { Object.assign(this, mixin); this[initializeMethod](); } }, render: function render() { this.beforeBlockRender(); this._setBlockInner(); this.editor = this.inner.children[0]; this.mixinsRequireInputs = false; this.availableMixins.forEach(function (mixin) { if (this[mixin]) { var blockMixin = BlockMixins[utils.classify(mixin)]; if (!_.isUndefined(blockMixin.requireInputs) && blockMixin.requireInputs) { this.mixinsRequireInputs = true; } } }, this); if (this.mixinsRequireInputs) { var input_html = document.createElement("div"); input_html.classList.add('st-block__inputs'); this.inner.appendChild(input_html); this.inputs = input_html; } if (this.hasTextBlock()) { this._initTextBlocks(); } this.availableMixins.forEach(function (mixin) { if (this[mixin]) { this.withMixin(BlockMixins[utils.classify(mixin)]); } }, this); if (this.formattable) { this._initFormatting(); } this._blockPrepare(); return this; }, remove: function remove() { if (this.ajaxable) { this.resolveAllInQueue(); } Dom.remove(this.el); }, loading: function loading() { if (!_.isUndefined(this.spinner)) { this.ready(); } this.spinner = new Spinner(config.defaults.spinner); this.spinner.spin(this.el); this.el.classList.add('st--is-loading'); }, ready: function ready() { this.el.classList.remove('st--is-loading'); if (!_.isUndefined(this.spinner)) { this.spinner.stop(); delete this.spinner; } }, //Generic _serializeData implementation to serialize the block into a plain object. //Can be overwritten, although hopefully this will cover most situations. //If you want to get the data of your block use block.getBlockData() // jshint maxdepth:4 _serializeData: function _serializeData() { utils.log("toData for " + this.blockID); var data = {}; //[> Simple to start. Add conditions later <] if (this.hasTextBlock()) { data.text = this.getTextBlockHTML(); data.format = 'html'; } // Add any inputs to the data attr var matcher = ['input:not([class="st-paste-block"])', 'textarea:not([class="st-paste-block"])', 'select:not([class="st-paste-block"])', 'button:not([class="st-paste-block"])'].join(","); if (this.$(matcher).length > 0) { Array.prototype.forEach.call(this.$('input, textarea, select, button'), function (input) { // Reference elements by their `name` attribute. For elements such as radio buttons // which require a unique reference per group of elements a `data-name` attribute can // be used to provide the same `name` per block. var name = input.getAttribute('data-name') || input.getAttribute('name'); if (name) { if (input.getAttribute('type') === 'number') { data[name] = parseInt(input.value); } else if (input.getAttribute('type') === 'checkbox') { var value = ""; if (input.getAttribute('data-toggle') || input.getAttribute('data-bs-toggle')) { value = "off"; if (input.checked === true) { value = "on"; } } else if (input.checked === true) { value = input.value; } data[name] = value; } else if (input.getAttribute('type') === 'radio') { if (input.checked === true) { data[name] = input.value; } } else { data[name] = input.value; } } }); } return data; }, //[> Generic implementation to tell us when the block is active <] focus: function focus() { Array.prototype.forEach.call(this.getTextBlock(), function (el) { el.focus(); }); }, focusAtStart: function focusAtStart() { this.focus(); }, focusAtEnd: function focusAtEnd() { this.focus(); }, blur: function blur() { Array.prototype.forEach.call(this.getTextBlock(), function (el) { el.blur(); }); }, onFocus: function onFocus() { var _this = this; Array.prototype.forEach.call(this.getTextBlock(), function (el) { el.addEventListener('focus', _this._onFocus); }); }, onBlur: function onBlur() { var _this2 = this; Array.prototype.forEach.call(this.getTextBlock(), function (el) { el.addEventListener('blur', _this2._onBlur); }); }, //Event handlers _onFocus: function _onFocus() { this.trigger('blockFocus', this.el); }, _onBlur: function _onBlur() {}, onDrop: function onDrop(dataTransferObj) {}, onDeleteConfirm: function onDeleteConfirm(e) { e.preventDefault(); this.mediator.trigger('block:remove', this.blockID, { focusOnPrevious: true }); }, // REFACTOR: have one set of delete controls that moves around like the // block controls? addDeleteControls: function addDeleteControls() { var _this3 = this; var onDeleteDeny = function onDeleteDeny(e) { e.preventDefault(); _this3.deleteEl.classList.remove("active"); }; this.ui.insertAdjacentHTML("beforeend", DELETE_TEMPLATE()); Events.delegate(this.el, ".js-st-block-confirm-delete", "click", this.onDeleteConfirm); Events.delegate(this.el, ".js-st-block-deny-delete", "click", onDeleteDeny); }, onDeleteClick: function onDeleteClick(e) { e.preventDefault(); e.stopPropagation(); if (this.isEmpty()) { this.onDeleteConfirm.call(this, new CustomEvent('click')); return; } this.deleteEl = this.el.querySelector('.st-block__ui-delete-controls'); this.deleteEl.classList.toggle('active'); }, onPositionerClick: function onPositionerClick(e) { e.preventDefault(); this.positioner.toggle(); }, beforeLoadingData: function beforeLoadingData() { this.loading(); if (this.mixinsRequireInputs) { Dom.show(this.editor); Dom.hide(this.inputs); } SimpleBlock.fn.beforeLoadingData.call(this); this.ready(); }, execTextBlockCommand: function execTextBlockCommand(cmdName) { if (_.isUndefined(this._scribe)) { throw "No Scribe instance found to send a command to"; } return ScribeInterface.execTextBlockCommand(this._scribe, cmdName); }, queryTextBlockCommandState: function queryTextBlockCommandState(cmdName) { if (_.isUndefined(this._scribe)) { throw "No Scribe instance found to query command"; } return ScribeInterface.queryTextBlockCommandState(this._scribe, cmdName); }, _handleContentPaste: function _handleContentPaste(ev) { setTimeout(this.onContentPasted.bind(this, ev, ev.currentTarget), 0); }, _getBlockClass: function _getBlockClass() { return 'st-block--' + this.className; }, //Init functions for adding functionality _initUIComponents: function _initUIComponents() { this.addDeleteControls(); this.positioner = new BlockPositioner(this.el, this.mediator); this._withUIComponent(this.positioner, '.st-block-ui-btn__reorder', this.onPositionerClick); this._withUIComponent(new BlockReorder(this.el, this.mediator)); this._withUIComponent(new BlockDeletion(), '.st-block-ui-btn__delete', this.onDeleteClick); this.onFocus(); this.onBlur(); }, _initFormatting: function _initFormatting() { // Enable formatting keyboard input var block = this; if (!this.options.formatBar) { return; } this.options.formatBar.commands.forEach(function (cmd) { if (_.isUndefined(cmd.keyCode)) { return; } Events.delegate(block.el, '.st-text-block', 'keydown', function (ev) { if ((ev.metaKey || ev.ctrlKey) && ev.keyCode === cmd.keyCode) { ev.preventDefault(); block.execTextBlockCommand(cmd.cmd); } }); }); }, _initTextBlocks: function _initTextBlocks() { var _this4 = this; Array.prototype.forEach.call(this.getTextBlock(), function (el) { el.addEventListener('keyup', _this4.getSelectionForFormatter); el.addEventListener('mousedown', _this4.addMouseupListener.bind(_this4)); el.addEventListener('DOMNodeInserted', _this4.clearInsertedStyles); }); var textBlock = this.getTextBlock()[0]; if (!_.isUndefined(textBlock) && _.isUndefined(this._scribe)) { var configureScribe = _.isFunction(this.configureScribe) ? this.configureScribe.bind(this) : null; this._scribe = ScribeInterface.initScribeInstance(textBlock, this.scribeOptions, configureScribe); } }, addMouseupListener: function addMouseupListener() { var _this5 = this; var listener = function listener() { _this5.getSelectionForFormatter(); window.removeEventListener('mouseup', listener); }; window.addEventListener('mouseup', listener); }, getSelectionForFormatter: function getSelectionForFormatter() { var _this6 = this; setTimeout(function () { var selection = window.getSelection(), selectionStr = selection.toString().trim(), en = 'formatter:' + (selectionStr === '' ? 'hide' : 'position'); _this6.mediator.trigger(en, _this6); EventBus.trigger(en, _this6); }, 1); }, clearInsertedStyles: function clearInsertedStyles(e) { var target = e.target; if (_.isUndefined(target.tagName)) { target = target.parentNode; } target.removeAttribute('style'); // Hacky fix for Chrome. }, hasTextBlock: function hasTextBlock() { return this.getTextBlock().length > 0; }, getTextBlock: function getTextBlock() { if (_.isUndefined(this.text_block)) { this.text_block = this.$('.st-text-block'); } return this.text_block; }, getTextBlockHTML: function getTextBlockHTML() { return this._scribe.getContent(); }, setTextBlockHTML: function setTextBlockHTML(html) { var returnVal = this._scribe.setContent(html); trimScribeContent(this._scribe); return returnVal; }, isEmpty: function isEmpty() { return _.isEmpty(this.getBlockData()); }, select: function select(selected) { this.el.classList.toggle("st-block--is-selected", selected); }, split: function split() {}, asClipboardHTML: function asClipboardHTML() {} }); Block.extend = __webpack_require__(89); // Allow our Block to be extended. module.exports = Block; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(141); /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Dom = __webpack_require__(3); var fixEvent = function fixEvent(e, target) { var obj = {}; // Events don't work as normal objects, so need to copy properties directly. // List and matchers taken from jQuery.Event.fix. // For other properties refer to the originalEvent object. var props = { shared: ("altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + "metaKey relatedTarget shiftKey target timeStamp view which").split(" "), mouseEvent: ("button buttons clientX clientY offsetX offsetY pageX pageY " + "screenX screenY toElement").split(" "), keyEvent: "char charCode key keyCode".split(" ") }; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/; var propsToCopy = rmouseEvent.test(e.type) ? props.shared.concat(props.mouseEvent) : rkeyEvent.test(e.type) ? props.shared.concat(props.keyEvent) : props.shared; var prop; for (var i = 0; i < propsToCopy.length; i++) { prop = propsToCopy[i]; obj[prop] = e[prop]; } obj.currentTarget = target; obj.originalEvent = e; obj.preventDefault = function () { if (this.originalEvent) { this.originalEvent.preventDefault(); } }; obj.stopPropagation = function () { if (this.originalEvent) { this.originalEvent.stopPropagation(); } }; return obj; }; module.exports.delegate = function delegate(el, selector, event, fn) { var useCapture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; el.addEventListener(event, function (e) { var target = e.target; for (target; target && target !== el; target = target.parentNode) { if (Dom.matches(target, selector)) { fn.call(target, fixEvent(e, target)); break; } } target = null; }, useCapture); }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var Dom = __webpack_require__(3); module.exports = { tagName: 'div', className: 'sir-trevor__view', attributes: {}, $: function $(selector) { return this.el.querySelectorAll(selector); }, render: function render() { return this; }, destroy: function destroy() { if (!_.isUndefined(this.stopListening)) { this.stopListening(); } Dom.remove(this.el); }, _ensureElement: function _ensureElement() { if (!this.el) { var attrs = Object.assign({}, _.result(this, 'attributes')); if (this.id) { attrs.id = this.id; } if (this.className) { attrs['class'] = this.className; } var el = Dom.createElement(this.tagName, attrs); this._setElement(el); } else { this._setElement(this.el); } }, _setElement: function _setElement(element) { this.el = element; return this; } }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var isNative = __webpack_require__(25), isObject = __webpack_require__(18), shimKeys = __webpack_require__(128); /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys; /** * Creates an array composed of the own enumerable property names of an object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } return nativeKeys(object); }; module.exports = keys; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /** * Module Dependencies */ var iterator = __webpack_require__(151); var selection = window.getSelection(); /** * Expose position fn */ module.exports = position; /** * Get or set cursor, selection, relative to * an element. * * @param {Element} el * @param {Object} pos selection range * @return {Object|Undefined} */ function position(el, pos){ /** * Get cursor or selection position */ if (1 == arguments.length) { if (!selection.rangeCount) return; var indexes = {}; var range = selection.getRangeAt(0); var clone = range.cloneRange(); clone.selectNodeContents(el); clone.setEnd(range.endContainer, range.endOffset); indexes.end = clone.toString().length; clone.setStart(range.startContainer, range.startOffset); indexes.start = indexes.end - clone.toString().length; indexes.atStart = clone.startOffset === 0; return indexes; } /** * Set cursor or selection position */ var setSelection = pos.end && (pos.end !== pos.start); var length = 0; var range = document.createRange(); var it = iterator(el).select(Node.TEXT_NODE).revisit(false); var next; var startindex; var start = pos.start > el.textContent.length ? el.textContent.length : pos.start; var end = pos.end > el.textContent.length ? el.textContent.length : pos.end; var atStart = pos.atStart; while (next = it.next()){ var olen = length; length += next.textContent.length; // Set start point of selection var atLength = atStart ? length > start : length >= start; if (!startindex && atLength) { startindex = true; range.setStart(next, start - olen); if (!setSelection) { range.collapse(true); makeSelection(el, range); break; } } // Set end point of selection if (setSelection && (length >= end)) { range.setEnd(next, end - olen); makeSelection(el, range); break; } } } /** * add selection / insert cursor. * * @param {Element} el * @param {Range} range */ function makeSelection(el, range){ el.focus(); selection.removeAllRanges(); selection.addRange(range); } /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * Checks if `value` is the language type of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return type == 'function' || (value && type == 'object') || false; } return isObject; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return (value && typeof value == 'object') || false; } return isObjectLike; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 16 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBlocksFromParagraphs", function() { return createBlocksFromParagraphs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTotalLength", function() { return getTotalLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAtStart", function() { return isAtStart; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAtEnd", function() { return isAtEnd; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectToEnd", function() { return selectToEnd; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSelectedFromStart", function() { return isSelectedFromStart; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSelectedToEnd", function() { return isSelectedToEnd; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rangeToHTML", function() { return rangeToHTML; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trimScribeContent", function() { return trimScribeContent; }); var selectionRange = __webpack_require__(13); var utils = __webpack_require__(1); var selectToEnd = function selectToEnd(scribe) { var selection = new scribe.api.Selection(); var range = selection.range.cloneRange(); range.setEndAfter(scribe.el.lastChild, 0); return range; }; var isAtStart = function isAtStart(scribe) { var currentRange = selectionRange(scribe.el); return currentRange.start === 0 && currentRange.end === 0 && currentRange.atStart; }; var getTotalLength = function getTotalLength(scribe) { var selection = new scribe.api.Selection(); var range = selection.range.cloneRange(); range.selectNodeContents(scribe.el); return range.toString().length; }; var isAtEnd = function isAtEnd(scribe) { var currentRange = selectionRange(scribe.el); return getTotalLength(scribe) === currentRange.end && currentRange.start === currentRange.end; }; var isSelectedToEnd = function isSelectedToEnd(scribe) { var currentRange = selectionRange(scribe.el); return getTotalLength(scribe) === currentRange.end; }; var isSelectedFromStart = function isSelectedFromStart(scribe) { var currentRange = selectionRange(scribe.el); return currentRange.atStart && currentRange.start === 0; }; // Remove any empty elements at the start of the range. var stripFirstEmptyElement = function stripFirstEmptyElement(div) { if (div.firstChild === null) { return; } var firstChild = div.firstChild.childNodes[0]; if (firstChild && firstChild.nodeName !== '#text') { if (firstChild.innerText === '') { div.firstChild.removeChild(firstChild); } } }; var createBlocksFromParagraphs = function createBlocksFromParagraphs(block, scribe) { var fakeContent = document.createElement('div'); fakeContent.appendChild(selectToEnd(scribe).extractContents()); stripFirstEmptyElement(fakeContent); // Add wrapper div which is missing in non blockElement scribe. if (!scribe.allowsBlockElements()) { var tempContent = document.createElement('div'); tempContent.appendChild(fakeContent); fakeContent = tempContent; } if (fakeContent.childNodes.length >= 1) { var data; var nodes = [].slice.call(fakeContent.childNodes); nodes.reverse().forEach(function (node) { if (node.innerText !== '') { data = { format: 'html', text: node.innerHTML.trim() }; block.mediator.trigger("block:create", block.type, data, block.el, { autoFocus: true }); } }); } }; var rangeToHTML = function rangeToHTML(range) { var div = document.createElement('div'); div.appendChild(range.extractContents()); return div.innerHTML; }; var trimScribeContent = function trimScribeContent(scribe) { // Remove any whitespace in the first node, otherwise selections won't work. var firstNode = scribe.node.firstDeepestChild(scribe.el); if (firstNode.nodeName === '#text') { firstNode.textContent = utils.leftTrim(firstNode.textContent); } // Remove all empty nodes at the front to get blocks working. // Don't remove nodes that can't contain text content (e.g. ) while (scribe.el.firstChild && scribe.el.firstChild.textContent === '' && document.createElement(scribe.el.firstChild.tagName).outerHTML.indexOf("/") != -1) { scribe.el.removeChild(scribe.el.firstChild); } // Remove all empty nodes at the end to get blocks working. // Don't remove nodes that can't contain text content (e.g. ) while (scribe.el.lastChild && scribe.el.lastChild.textContent === '' && document.createElement(scribe.el.lastChild.tagName).outerHTML.indexOf("/") != -1) { scribe.el.removeChild(scribe.el.lastChild); } // Firefox adds empty br tags at the end of content. while (scribe.el.lastChild && scribe.el.lastChild.nodeName === 'BR') { scribe.el.removeChild(scribe.el.lastChild); } }; /***/ }), /* 17 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var objectTypes = __webpack_require__(26); /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return !!(value && objectTypes[typeof value]); } module.exports = isObject; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(202), __webpack_require__(15)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(escapeRegExp, isObjectLike) { /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** * Used to resolve the `toStringTag` of values. * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * for more details. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reNative = RegExp('^' + escapeRegExp(objToString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reNative.test(fnToString.call(value)); } return (isObjectLike(value) && reHostCtor.test(value)) || false; } return isNative; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(19), __webpack_require__(15)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(isLength, isNative, isObjectLike) { /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the `toStringTag` of values. * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * for more details. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false; }; return isArray; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { Text: __webpack_require__(222), Quote: __webpack_require__(229), Image: __webpack_require__(230), Heading: __webpack_require__(231), List: __webpack_require__(232), Tweet: __webpack_require__(234), Video: __webpack_require__(235) }; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var utils = __webpack_require__(1); module.exports = function (markdown, type) { // Deferring requiring these to sidestep a circular dependency: // Block -> this -> Blocks -> Block var Blocks = __webpack_require__(21); // MD -> HTML type = utils.classify(type); var html = markdown, shouldWrap = type === "Text"; if (_.isUndefined(shouldWrap)) { shouldWrap = false; } if (shouldWrap) { html = "

" + html; } html = html.replace(/\[([^\]]+)\]\(([^\)]+)\)/gm, function (match, p1, p2) { return "" + p1.replace(/\n/g, '') + ""; }); // This may seem crazy, but because JS doesn't have a look behind, // we reverse the string to regex out the italic items (and bold) // and look for something that doesn't start (or end in the reversed strings case) // with a slash. html = utils.reverse(utils.reverse(html).replace(/_(?!\\)((_\\|[^_])*)_(?=$|[^\\])/gm, function (match, p1) { return ">i/<" + p1.replace(/\n/g, '').replace(/[\s]+$/, '') + ">i<"; }).replace(/\*\*(?!\\)((\*\*\\|[^\*\*])*)\*\*(?=$|[^\\])/gm, function (match, p1) { return ">b/<" + p1.replace(/\n/g, '').replace(/[\s]+$/, '') + ">b<"; })); html = html.replace(/^\> (.+)$/mg, "$1"); // Use custom block toHTML functions (if any exist) var block; if (Blocks.hasOwnProperty(type)) { block = Blocks[type]; // Do we have a toHTML function? if (!_.isUndefined(block.prototype.toHTML) && _.isFunction(block.prototype.toHTML)) { html = block.prototype.toHTML(html); } } if (shouldWrap) { html = html.replace(/\n\s*\n/gm, "

"); html = html.replace(/\n/gm, "
"); } html = html.replace(/\t/g, "    ").replace(/\n/g, "
").replace(/\*\*/, "").replace(/__/, ""); // Cleanup any markdown characters left // Replace escaped html = html.replace(/\\\*/g, "*").replace(/\\\[/g, "[").replace(/\\\]/g, "]").replace(/\\\_/g, "_").replace(/\\\(/g, "(").replace(/\\\)/g, ")").replace(/\\\-/g, "-"); if (shouldWrap) { html += "

"; } return html; }; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keys = __webpack_require__(42); var foreach = __webpack_require__(98); var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { enumerable: false, value: obj }); /* eslint-disable no-unused-vars, no-restricted-syntax */ for (var _ in obj) { return false; } /* eslint-enable no-unused-vars, no-restricted-syntax */ return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = props.concat(Object.getOwnPropertySymbols(map)); } foreach(props, function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(99); module.exports = Function.prototype.bind || implementation; /***/ }), /* 25 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** Used for native method references */ var objectProto = Object.prototype; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); /** * Checks if `value` is a native function. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. */ function isNative(value) { return typeof value == 'function' && reNative.test(value); } module.exports = isNative; /***/ }), /* 26 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; module.exports = objectTypes; /***/ }), /* 27 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used instead of `Array#slice` to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|string} collection The collection to slice. * @param {number} start The start index. * @param {number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } module.exports = slice; /***/ }), /* 28 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } module.exports = isFunction; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(157), __webpack_require__(158), __webpack_require__(5) ], __WEBPACK_AMD_DEFINE_RESULT__ = (function (inlineElementNames, blockElementNames, Immutable) { 'use strict'; function isBlockElement(node) { return blockElementNames.includes(node.nodeName); } function isInlineElement(node) { return inlineElementNames.includes(node.nodeName); } function hasContent(node) { if(node && node.children && node.children.length > 0) { return true; } if(node && node.nodeName === 'BR') { return true; } return false; } // return true if nested inline tags ultimately just contain
or "" function isEmptyInlineElement(node) { if( node.children.length > 1 ) return false; if( node.children.length === 1 && node.textContent.trim() !== '' ) return false; if( node.children.length === 0 ) return node.textContent.trim() === ''; return isEmptyInlineElement(node.children[0]); } function isText(node) { return node.nodeType === Node.TEXT_NODE; } function isEmptyTextNode(node) { var isEmpty = false; try { isEmpty = isText(node) && node.data === ''; } catch(err) { isEmpty = true; } return isEmpty; } function isFragment(node) { return node.nodeType === Node.DOCUMENT_FRAGMENT_NODE; } function isBefore(node1, node2) { return node1.compareDocumentPosition(node2) & Node.DOCUMENT_POSITION_FOLLOWING; } function elementHasClass(Node, className) { return function(node) { return (node.nodeType === Node.ELEMENT_NODE && node.className === className) } } function isSelectionMarkerNode(node) { return elementHasClass(Node, 'scribe-marker')(node); } function isCaretPositionNode(node) { return elementHasClass(Node, 'caret-position')(node); } function isWhitespaceOnlyTextNode(Node, node) { if(node.nodeType === Node.TEXT_NODE && /^\s*$/.test(node.nodeValue)) { return true; } return false; } function isTextNodeWithContent(Node, node) { return node.nodeType === Node.TEXT_NODE && !isWhitespaceOnlyTextNode(Node, node); } function firstDeepestChild(node) { var fs = node.firstChild; return !fs || fs.nodeName === 'BR' ? node : firstDeepestChild(fs); } function insertAfter(newNode, referenceNode) { return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } function removeNode(node) { return node.parentNode.removeChild(node); } function getAncestor(node, rootElement, nodeFilter) { function isTopContainerElement (element) { return rootElement === element; } // TODO: should this happen here? if (isTopContainerElement(node)) { return; } var currentNode = node.parentNode; // If it's a `contenteditable` then it's likely going to be the Scribe // instance, so stop traversing there. while (currentNode && ! isTopContainerElement(currentNode)) { if (nodeFilter(currentNode)) { return currentNode; } currentNode = currentNode.parentNode; } } function nextSiblings(node) { var all = Immutable.List(); while (node = node.nextSibling) { all = all.push(node); } return all; } function wrap(nodes, parentNode) { nodes[0].parentNode.insertBefore(parentNode, nodes[0]); nodes.forEach(function (node) { parentNode.appendChild(node); }); return parentNode; } function unwrap(node, childNode) { while (childNode.childNodes.length > 0) { node.insertBefore(childNode.childNodes[0], childNode); } node.removeChild(childNode); } /** * Chrome: If a parent node has a CSS `line-height` when we apply the * insertHTML command, Chrome appends a SPAN to plain content with * inline styling replicating that `line-height`, and adjusts the * `line-height` on inline elements. * * As per: http://jsbin.com/ilEmudi/4/edit?css,js,output * More from the web: http://stackoverflow.com/q/15015019/40352 */ function removeChromeArtifacts(parentElement) { function isInlineWithStyle(parentStyle, element) { return window.getComputedStyle(element).lineHeight === parentStyle.lineHeight; } var nodes = Immutable.List(parentElement.querySelectorAll(inlineElementNames .map(function(elName) { return elName + '[style*="line-height"]' }) .join(',') )); nodes = nodes.filter(isInlineWithStyle.bind(null, window.getComputedStyle(parentElement))); var emptySpans = Immutable.List(); nodes.forEach(function(node) { node.style.lineHeight = null; if (node.getAttribute('style') === '') { node.removeAttribute('style'); } if (node.nodeName === 'SPAN' && node.attributes.length === 0) { emptySpans = emptySpans.push(node); } }); emptySpans.forEach(function(node) { unwrap(node.parentNode, node); }); } return { isInlineElement: isInlineElement, isBlockElement: isBlockElement, isEmptyInlineElement: isEmptyInlineElement, isText: isText, isEmptyTextNode: isEmptyTextNode, isWhitespaceOnlyTextNode: isWhitespaceOnlyTextNode, isTextNodeWithContent: isTextNodeWithContent, isFragment: isFragment, isBefore: isBefore, isSelectionMarkerNode: isSelectionMarkerNode, isCaretPositionNode: isCaretPositionNode, firstDeepestChild: firstDeepestChild, insertAfter: insertAfter, removeNode: removeNode, getAncestor: getAncestor, nextSiblings: nextSiblings, wrap: wrap, unwrap: unwrap, removeChromeArtifacts: removeChromeArtifacts, elementHasClass: elementHasClass, hasContent: hasContent }; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { mediatedEvents: {}, eventNamespace: null, _bindMediatedEvents: function _bindMediatedEvents() { Object.keys(this.mediatedEvents).forEach(function (eventName) { var cb = this.mediatedEvents[eventName]; eventName = this.eventNamespace ? this.eventNamespace + ':' + eventName : eventName; this.mediator.on(eventName, this[cb].bind(this)); }, this); } }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(24); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fnToStr = Function.prototype.toString; var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var isNative = __webpack_require__(25), noop = __webpack_require__(57); /** Used as the property descriptor for `__bindData__` */ var descriptor = { 'configurable': false, 'enumerable': false, 'value': null, 'writable': false }; /** Used to set meta data on functions */ var defineProperty = (function() { // IE 8 only accepts DOM elements try { var o = {}, func = isNative(func = Object.defineProperty) && func, result = func(o, o, o) && func; } catch(e) { } return result; }()); /** * Sets `this` binding data on a given function. * * @private * @param {Function} func The function to set data on. * @param {Array} value The data array to set. */ var setBindData = !defineProperty ? noop : function(func, value) { descriptor.value = value; defineProperty(func, '__bindData__', descriptor); }; module.exports = setBindData; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(1); module.exports = { mixinName: "Ajaxable", ajaxable: true, initializeAjaxable: function initializeAjaxable() { this._queued = []; }, addQueuedItem: function addQueuedItem(name, deferred) { utils.log("Adding queued item for " + this.blockID + " called " + name); this._queued.push({ name: name, deferred: deferred }); }, removeQueuedItem: function removeQueuedItem(name) { utils.log("Removing queued item for " + this.blockID + " called " + name); this._queued = this._queued.filter(function (queued) { return queued.name !== name; }); }, hasItemsInQueue: function hasItemsInQueue() { return this._queued.length > 0; }, resolveAllInQueue: function resolveAllInQueue() { this._queued.forEach(function (item) { utils.log("Aborting queued request: " + item.name); item.deferred.cancel(); }, this); } }; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function dragEnter(e) { e.preventDefault(); e.stopPropagation(); } function dragOver(e) { e.dataTransfer.dropEffect = "copy"; e.currentTarget.classList.add('st-drag-over'); e.preventDefault(); e.stopPropagation(); } function dragLeave(e) { e.currentTarget.classList.remove('st-drag-over'); e.preventDefault(); e.stopPropagation(); } module.exports = { dropArea: function dropArea(el) { el.addEventListener("dragenter", dragEnter); el.addEventListener("dragover", dragOver); el.addEventListener("dragleave", dragLeave); return el; }, noDropArea: function noDropArea(el) { el.removeEventListener("dragenter"); el.removeEventListener("dragover"); el.removeEventListener("dragleave"); return el; } }; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(15)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(isLength, isObjectLike) { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the `toStringTag` of values. * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * for more details. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { var length = isObjectLike(value) ? value.length : undefined; return (isLength(length) && objToString.call(value) == argsTag) || false; } return isArguments; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * Used as the maximum length of an array-like value. * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * for more details. */ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = +value; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } return isIndex; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(36), __webpack_require__(20), __webpack_require__(37), __webpack_require__(7), __webpack_require__(14), __webpack_require__(75)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(isArguments, isArray, isIndex, isLength, isObject, support) { /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } return keysIn; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var dropEvents = __webpack_require__(35); var EventBus = __webpack_require__(4); var Dom = __webpack_require__(3); var config = __webpack_require__(2); var BlockReorder = function BlockReorder(block_element, mediator) { this.block = block_element; this.blockID = this.block.getAttribute('id'); this.mediator = mediator; this._ensureElement(); this._bindFunctions(); this.initialize(); }; Object.assign(BlockReorder.prototype, __webpack_require__(6), __webpack_require__(11), { bound: ['onMouseDown', 'onDragStart', 'onDragEnd', 'onDrop'], className: 'st-block-ui-btn__reorder', tagName: 'a', attributes: function attributes() { return { 'html': "\n \n "), 'draggable': 'true', 'data-icon': 'move' }; }, initialize: function initialize() { this.el.addEventListener('mousedown', this.onMouseDown); this.el.addEventListener('dragstart', this.onDragStart); this.el.addEventListener('dragend', this.onDragEnd); dropEvents.dropArea(this.block); this.block.addEventListener('drop', this.onDrop); }, blockId: function blockId() { return this.block.getAttribute('id'); }, onMouseDown: function onMouseDown() { EventBus.trigger("block:reorder:down"); }, onDrop: function onDrop(ev) { ev.preventDefault(); var dropped_on = this.block, item_id = ev.dataTransfer.getData("text/plain"), block = document.querySelector('#' + item_id); if (!!item_id, !!block, dropped_on.id !== item_id) { Dom.insertAfter(block, dropped_on); } this.mediator.trigger("block:rerender", item_id); EventBus.trigger("block:reorder:dropped", item_id); }, onDragStart: function onDragStart(ev) { var block = this.block; this.dragEl = block.cloneNode(true); this.dragEl.classList.add("st-drag-element"); this.dragEl.style.top = "".concat(block.offsetTop, "px"); this.dragEl.style.left = "".concat(block.offsetLeft, "px"); block.parentNode.appendChild(this.dragEl); ev.dataTransfer.setDragImage(this.dragEl, 0, 0); ev.dataTransfer.setData("text/plain", this.blockId()); this.mediator.trigger("block-controls:hide"); EventBus.trigger("block:reorder:dragstart"); block.classList.add('st-block--dragging'); }, onDragEnd: function onDragEnd(ev) { EventBus.trigger("block:reorder:dragend"); this.block.classList.remove('st-block--dragging'); this.dragEl.parentNode.removeChild(this.dragEl); }, render: function render() { return this; } }); module.exports = BlockReorder; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var scribeHeadingPlugin = function scribeHeadingPlugin(block) { return function (scribe) { var headingCommand = new scribe.api.Command('heading'); headingCommand.queryEnabled = function () { return block.inline_editable; }; headingCommand.queryState = function () { return block.type === 'heading'; }; var getBlockType = function getBlockType() { return headingCommand.queryState() ? 'Text' : 'Heading'; }; headingCommand.execute = function headingCommandExecute(value) { var data = { format: 'html', text: block.getScribeInnerContent() }; block.mediator.trigger("block:replace", block.el, getBlockType(), data); }; scribe.commands.heading = headingCommand; }; }; module.exports = scribeHeadingPlugin; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var scribeQuotePlugin = function scribeQuotePlugin(block) { return function (scribe) { var quoteCommand = new scribe.api.Command('quote'); quoteCommand.queryEnabled = function () { return block.inline_editable; }; quoteCommand.queryState = function () { return block.type === 'quote'; }; var getBlockType = function getBlockType() { return quoteCommand.queryState() ? 'Text' : 'Quote'; }; quoteCommand.execute = function quoteCommandExecute(value) { var data = { format: 'html', text: block.getScribeInnerContent() }; block.mediator.trigger("block:replace", block.el, getBlockType(), data); }; scribe.commands.quote = quoteCommand; }; }; module.exports = scribeQuotePlugin; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(97); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es6-shim var keys = __webpack_require__(42); var bind = __webpack_require__(24); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = __webpack_require__(44)(); var toObject = Object; var push = bind.call(Function.call, Array.prototype.push); var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable); var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; module.exports = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = toObject(target); var s, source, i, props, syms, value, key; for (s = 1; s < arguments.length; ++s) { source = toObject(arguments[s]); props = keys(source); var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols); if (getSymbols) { syms = getSymbols(source); for (i = 0; i < syms.length; ++i) { key = syms[i]; if (propIsEnumerable(source, key)) { push(props, key); } } } for (i = 0; i < props.length; ++i) { key = props[i]; value = source[key]; if (propIsEnumerable(source, key)) { objTarget[key] = value; } } } return objTarget; }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint complexity: [2, 17], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(43); var lacksProperEnumerationOrder = function () { if (!Object.assign) { return false; } // v8, specifically in node 4.x, has a bug with incorrect property enumeration order // note: this does not detect the bug unless there's 20 characters var str = 'abcdefghijklmnopqrst'; var letters = str.split(''); var map = {}; for (var i = 0; i < letters.length; ++i) { map[letters[i]] = letters[i]; } var obj = Object.assign({}, map); var actual = ''; for (var k in obj) { actual += k; } return str !== actual; }; var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } return false; }; module.exports = function getPolyfill() { if (!Object.assign) { return implementation; } if (lacksProperEnumerationOrder()) { return implementation; } if (assignHasPendingExceptions()) { return implementation; } return Object.assign; }; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(102); /***/ }), /* 47 */ /***/ (function(module, exports) { module.exports = function isPrimitive(value) { return value === null || (typeof value !== 'function' && typeof value !== 'object'); }; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* globals Set, Map, WeakSet, WeakMap, Promise, Symbol, Proxy, Atomics, SharedArrayBuffer, ArrayBuffer, DataView, Uint8Array, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8ClampedArray, Uint16Array, Uint32Array, */ var undefined; // eslint-disable-line no-shadow-restricted-names var ThrowTypeError = Object.getOwnPropertyDescriptor ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }()) : function () { throw new TypeError(); }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var generator; // = function * () {}; var generatorFunction = generator ? getProto(generator) : undefined; var asyncFn; // async function() {}; var asyncFunction = asyncFn ? asyncFn.constructor : undefined; var asyncGen; // async function * () {}; var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; var asyncGenIterator = asyncGen ? asyncGen() : undefined; var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); var INTRINSICS = { '$ %Array%': Array, '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, '$ %ArrayPrototype%': Array.prototype, '$ %ArrayProto_entries%': Array.prototype.entries, '$ %ArrayProto_forEach%': Array.prototype.forEach, '$ %ArrayProto_keys%': Array.prototype.keys, '$ %ArrayProto_values%': Array.prototype.values, '$ %AsyncFromSyncIteratorPrototype%': undefined, '$ %AsyncFunction%': asyncFunction, '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, '$ %AsyncGeneratorFunction%': asyncGenFunction, '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '$ %Boolean%': Boolean, '$ %BooleanPrototype%': Boolean.prototype, '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView, '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, '$ %Date%': Date, '$ %DatePrototype%': Date.prototype, '$ %decodeURI%': decodeURI, '$ %decodeURIComponent%': decodeURIComponent, '$ %encodeURI%': encodeURI, '$ %encodeURIComponent%': encodeURIComponent, '$ %Error%': Error, '$ %ErrorPrototype%': Error.prototype, '$ %eval%': eval, // eslint-disable-line no-eval '$ %EvalError%': EvalError, '$ %EvalErrorPrototype%': EvalError.prototype, '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, '$ %Function%': Function, '$ %FunctionPrototype%': Function.prototype, '$ %Generator%': generator ? getProto(generator()) : undefined, '$ %GeneratorFunction%': generatorFunction, '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, '$ %isFinite%': isFinite, '$ %isNaN%': isNaN, '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, '$ %JSON%': JSON, '$ %JSONParse%': JSON.parse, '$ %Map%': typeof Map === 'undefined' ? undefined : Map, '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, '$ %Math%': Math, '$ %Number%': Number, '$ %NumberPrototype%': Number.prototype, '$ %Object%': Object, '$ %ObjectPrototype%': Object.prototype, '$ %ObjProto_toString%': Object.prototype.toString, '$ %ObjProto_valueOf%': Object.prototype.valueOf, '$ %parseFloat%': parseFloat, '$ %parseInt%': parseInt, '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise, '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '$ %RangeError%': RangeError, '$ %RangeErrorPrototype%': RangeError.prototype, '$ %ReferenceError%': ReferenceError, '$ %ReferenceErrorPrototype%': ReferenceError.prototype, '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '$ %RegExp%': RegExp, '$ %RegExpPrototype%': RegExp.prototype, '$ %Set%': typeof Set === 'undefined' ? undefined : Set, '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, '$ %String%': String, '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, '$ %StringPrototype%': String.prototype, '$ %Symbol%': hasSymbols ? Symbol : undefined, '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, '$ %SyntaxError%': SyntaxError, '$ %SyntaxErrorPrototype%': SyntaxError.prototype, '$ %ThrowTypeError%': ThrowTypeError, '$ %TypedArray%': TypedArray, '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, '$ %TypeError%': TypeError, '$ %TypeErrorPrototype%': TypeError.prototype, '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, '$ %URIError%': URIError, '$ %URIErrorPrototype%': URIError.prototype, '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype }; module.exports = function GetIntrinsic(name, allowMissing) { if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new TypeError('"allowMissing" argument must be a boolean'); } var key = '$ ' + name; if (!(key in INTRINSICS)) { throw new SyntaxError('intrinsic ' + name + ' does not exist!'); } // istanbul ignore if // hopefully this is impossible to test :-) if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) { throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return INTRINSICS[key]; }; /***/ }), /* 49 */ /***/ (function(module, exports) { module.exports = Number.isNaN || function isNaN(a) { return a !== a; }; /***/ }), /* 50 */ /***/ (function(module, exports) { var $isNaN = Number.isNaN || function (a) { return a !== a; }; module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; /***/ }), /* 51 */ /***/ (function(module, exports) { module.exports = function sign(number) { return number >= 0 ? 1 : -1; }; /***/ }), /* 52 */ /***/ (function(module, exports) { module.exports = function mod(number, modulo) { var remain = number % modulo; return Math.floor(remain >= 0 ? remain : remain + modulo); }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ES = __webpack_require__(46); module.exports = function find(predicate) { var list = ES.ToObject(this); var length = ES.ToInteger(ES.ToLength(list.length)); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } if (length === 0) { return undefined; } var thisArg = arguments[1]; for (var i = 0, value; i < length; i++) { value = list[i]; if (ES.Call(predicate, thisArg, [value, i, list])) { return value; } } return undefined; }; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function getPolyfill() { // Detect if an implementation exists // Detect early implementations which skipped holes in sparse arrays // eslint-disable-next-line no-sparse-arrays var implemented = Array.prototype.find && [, 1].find(function () { return true; }) !== 1; // eslint-disable-next-line global-require return implemented ? Array.prototype.find : __webpack_require__(53); }; /***/ }), /* 55 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var isNative = __webpack_require__(25), isObject = __webpack_require__(18), noop = __webpack_require__(57); /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(prototype, properties) { return isObject(prototype) ? nativeCreate(prototype) : {}; } // fallback for browsers without `Object.create` if (!nativeCreate) { baseCreate = (function() { function Object() {} return function(prototype) { if (isObject(prototype)) { Object.prototype = prototype; var result = new Object; Object.prototype = null; } return result || global.Object(); }; }()); } module.exports = baseCreate; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(17))) /***/ }), /* 57 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** * A no-operation function. * * @static * @memberOf _ * @category Utilities * @example * * var object = { 'name': 'fred' }; * _.noop(object) === undefined; * // => true */ function noop() { // no operation performed } module.exports = noop; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var escapeHtmlChar = __webpack_require__(134), keys = __webpack_require__(12), reUnescapedHtml = __webpack_require__(135); /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('Fred, Wilma, & Pebbles'); * // => 'Fred, Wilma, & Pebbles' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } module.exports = escape; /***/ }), /* 59 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** * Used to convert characters to HTML entities: * * Though the `>` character is escaped for symmetry, characters like `>` and `/` * don't require escaping in HTML and have no special meaning unless they're part * of a tag or an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; module.exports = htmlEscapes; /***/ }), /* 60 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; module.exports = reInterpolate; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Sir Trevor Editor Store * By default we store the complete data on the instances $el * We can easily extend this and store it on some server or something */ var _ = __webpack_require__(0); var utils = __webpack_require__(1); var EditorStore = function EditorStore(data, mediator) { this.mediator = mediator; this.initialize(data ? data.trim() : ''); }; Object.assign(EditorStore.prototype, { initialize: function initialize(data) { this.store = this._parseData(data) || { data: [] }; }, retrieve: function retrieve() { return this.store; }, toString: function toString(space) { return JSON.stringify(this.store, undefined, space); }, reset: function reset() { utils.log("Resetting the EditorStore"); this.store = { data: [] }; }, addData: function addData(data) { this.store.data.push(data); return this.store; }, _parseData: function _parseData(data) { var result; if (data.length === 0) { return result; } try { // Ensure the JSON string has a data element that's an array var jsonStr = JSON.parse(data); if (!_.isUndefined(jsonStr.data)) { result = jsonStr; } } catch (e) { this.mediator.trigger('errors:add', { text: i18n.t("errors:load_fail") }); this.mediator.trigger('errors:render'); console.log('Sorry there has been a problem with parsing the JSON'); console.log(e); } return result; } }); module.exports = EditorStore; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * SirTrevor.Submittable * -- * We need a global way of setting if the editor can and can't be submitted, * and a way to disable the submit button and add messages (when appropriate) * We also need this to be highly extensible so it can be overridden. * This will be triggered *by anything* so it needs to subscribe to events. */ var utils = __webpack_require__(1); var EventBus = __webpack_require__(4); var Submittable = function Submittable(form) { this.form = form; this.initialize(); }; Object.assign(Submittable.prototype, { initialize: function initialize() { this.submitBtns = this.form.querySelectorAll("input[type='submit']"); var btnTitles = []; Array.prototype.forEach.call(this.submitBtns, function (btn, i) { btnTitles.push(btn.getAttribute('value')); }); this.submitBtnTitles = btnTitles; this.canSubmit = true; this.globalUploadCount = 0; this._bindEvents(); }, setSubmitButton: function setSubmitButton(e, message) { Array.prototype.forEach.call(this.submitBtns, function (btn, i) { btn.setAttribute('value', message); }); }, resetSubmitButton: function resetSubmitButton() { var titles = this.submitBtnTitles; Array.prototype.forEach.call(this.submitBtns, function (item, index) { item.setAttribute('value', titles[index]); }); }, onUploadStart: function onUploadStart(e) { this.globalUploadCount++; utils.log('onUploadStart called ' + this.globalUploadCount); if (this.globalUploadCount === 1) { this._disableSubmitButton(); } }, onUploadStop: function onUploadStop(e) { this.globalUploadCount = this.globalUploadCount <= 0 ? 0 : this.globalUploadCount - 1; utils.log('onUploadStop called ' + this.globalUploadCount); if (this.globalUploadCount === 0) { this._enableSubmitButton(); } }, onError: function onError(e) { utils.log('onError called'); this.canSubmit = false; }, _disableSubmitButton: function _disableSubmitButton(message) { this.setSubmitButton(null, message || i18n.t("general:wait")); Array.prototype.forEach.call(this.submitBtns, function (btn, i) { btn.setAttribute('disabled', 'disabled'); btn.classList.add('disabled'); }); }, _enableSubmitButton: function _enableSubmitButton() { this.resetSubmitButton(); Array.prototype.forEach.call(this.submitBtns, function (btn, i) { btn.removeAttribute('disabled'); btn.classList.remove('disabled'); }); }, _events: { "disableSubmitButton": "_disableSubmitButton", "enableSubmitButton": "_enableSubmitButton", "setSubmitButton": "setSubmitButton", "resetSubmitButton": "resetSubmitButton", "onError": "onError", "onUploadStart": "onUploadStart", "onUploadStop": "onUploadStop" }, _bindEvents: function _bindEvents() { Object.keys(this._events).forEach(function (type) { EventBus.on(type, this[this._events[type]], this); }, this); } }); module.exports = Submittable; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Sir Trevor Uploader * Generic Upload implementation that can be extended for blocks */ var _ = __webpack_require__(0); var config = __webpack_require__(2); var utils = __webpack_require__(1); var Ajax = __webpack_require__(64); var EventBus = __webpack_require__(4); module.exports = function (block, file, success, error) { var uid = [block.blockID, new Date().getTime(), 'raw'].join('-'); var data = new FormData(); var attachmentName = block.attachmentName || config.defaults.attachmentName; var attachmentFile = block.attachmentFile || config.defaults.attachmentFile; var attachmentUid = block.attachmentUid || config.defaults.attachmentUid; data.append(attachmentName, file.name); data.append(attachmentFile, file); data.append(attachmentUid, uid); EventBus.trigger('onUploadStart', data); block.resetMessages(); var callbackSuccess = function callbackSuccess(data) { utils.log('Upload callback called'); EventBus.trigger('onUploadStop', data); if (!_.isUndefined(success) && _.isFunction(success)) { success.apply(block, arguments, data); } block.removeQueuedItem(uid); }; var callbackError = function callbackError(jqXHR, status, errorThrown) { utils.log('Upload callback error called'); EventBus.trigger('onUploadStop', undefined, errorThrown, status, jqXHR); if (!_.isUndefined(error) && _.isFunction(error)) { error.call(block, status); } block.removeQueuedItem(uid); }; var url = block.uploadUrl || config.defaults.uploadUrl; var xhr = Ajax.fetch(url, { body: data, method: 'POST', dataType: 'json' }); block.addQueuedItem(uid, xhr); xhr.then(callbackSuccess).catch(callbackError); return xhr; }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; __webpack_require__(142); var fetchJsonP = __webpack_require__(143); var cancellablePromise = __webpack_require__(144); var config = __webpack_require__(2); var Ajax = Object.create(null); Ajax.fetch = function (url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options = Object.assign({}, config.defaults.ajaxOptions, options); var promise; if (options.jsonp) { promise = fetchJsonP(url).promise; } else { promise = fetch(url, options).then(function (response) { if (options.dataType === 'json') { return response.json(); } return response.text(); }); } return cancellablePromise(promise); }; module.exports = Ajax; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { Ajaxable: __webpack_require__(34), Controllable: __webpack_require__(145), Droppable: __webpack_require__(146), Fetchable: __webpack_require__(147), Pastable: __webpack_require__(148), Uploadable: __webpack_require__(149), MultiEditable: __webpack_require__(150), Textable: __webpack_require__(221) }; /***/ }), /* 66 */ /***/ (function(module, exports) { /** * Expose `xor` */ module.exports = xor; /** * XOR utility * * T T F * T F T * F T T * F F F * * @param {Boolean} a * @param {Boolean} b * @return {Boolean} */ function xor(a, b) { return !a != !b; } /***/ }), /* 67 */ /***/ (function(module, exports) { /** * Global Names */ var globals = /\b(Array|Date|Object|Math|JSON)\b/g; /** * Return immediate identifiers parsed from `str`. * * @param {String} str * @param {String|Function} map function or prefix * @return {Array} * @api public */ module.exports = function(str, fn){ var p = unique(props(str)); if (fn && 'string' == typeof fn) fn = prefixed(fn); if (fn) return map(str, p, fn); return p; }; /** * Return immediate identifiers in `str`. * * @param {String} str * @return {Array} * @api private */ function props(str) { return str .replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '') .replace(globals, '') .match(/[a-zA-Z_]\w*/g) || []; } /** * Return `str` with `props` mapped with `fn`. * * @param {String} str * @param {Array} props * @param {Function} fn * @return {String} * @api private */ function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); } /** * Return unique array. * * @param {Array} arr * @return {Array} * @api private */ function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; } /** * Map with prefix `str`. */ function prefixed(str) { return function(_){ return str + _; }; } /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var Scribe = __webpack_require__(152); var config = __webpack_require__(2); var scribePluginFormatterPlainTextConvertNewLinesToHTML = __webpack_require__(191); var scribePluginLinkPromptCommand = __webpack_require__(192); var scribePluginSanitizer = __webpack_require__(197); var sanitizeDefaults = { p: true, a: { href: true, target: '_blank', rel: true }, i: true, b: true, strong: true, em: true }; module.exports = { initScribeInstance: function initScribeInstance(el, scribeOptions, configureScribe) { scribeOptions = scribeOptions || {}; var scribeConfig = { debug: config.scribeDebug }; var tags = sanitizeDefaults; if (_.isObject(scribeOptions)) { scribeConfig = Object.assign(scribeConfig, scribeOptions); } var scribe = new Scribe(el, scribeConfig); if (scribeOptions.hasOwnProperty("tags")) { tags = Object.assign(sanitizeDefaults, scribeOptions.tags); } scribe.use(scribePluginFormatterPlainTextConvertNewLinesToHTML()); scribe.use(scribePluginLinkPromptCommand()); scribe.use(scribePluginSanitizer({ tags: tags })); if (_.isFunction(configureScribe)) { configureScribe.call(this, scribe); } return scribe; }, execTextBlockCommand: function execTextBlockCommand(scribeInstance, cmdName) { if (_.isUndefined(scribeInstance)) { throw "No Scribe instance found to query command"; } var cmd = scribeInstance.getCommand(cmdName); scribeInstance.el.focus(); return cmd.execute(); }, queryTextBlockCommandState: function queryTextBlockCommandState(scribeInstance, cmdName) { if (_.isUndefined(scribeInstance)) { throw "No Scribe instance found to query command"; } var cmd = scribeInstance.getCommand(cmdName), sel = new scribeInstance.api.Selection(); return sel.range && cmd.queryState(); } }; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { 'use strict'; function isUndoKeyCombination(event) { return !event.shiftKey && (event.metaKey || (event.ctrlKey && !event.altKey)) && event.keyCode === 90; } function isRedoKeyCombination(event) { return event.shiftKey && (event.metaKey || (event.ctrlKey && !event.altKey)) && event.keyCode === 90; } return { isUndoKeyCombination: isUndoKeyCombination, isRedoKeyCombination: isRedoKeyCombination }; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { 'use strict'; return { contentChanged: "scribe:content-changed", legacyContentChanged: "content-changed", destroy: "scribe:destroy" }; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } return arrayEach; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(73), __webpack_require__(74)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(baseFor, keys) { /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } return baseForOwn; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(201)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(toObject) { /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iterator functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ function baseFor(object, iteratee, keysFunc) { var index = -1, iterable = toObject(object), props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; } return baseFor; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(19), __webpack_require__(14), __webpack_require__(204)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(isLength, isNative, isObject, shimKeys) { /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { if (object) { var Ctor = object.constructor, length = object.length; } if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && (length && isLength(length)))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; return keys; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(19), __webpack_require__(76)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(isNative, root) { /** Used to detect functions containing a `this` reference. */ var reThis = /\bthis\b/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to detect DOM support. */ var document = (document = root.window) && document.document; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { /** * Detect if functions can be decompiled by `Function#toString` * (all but Firefox OS certified apps, older Opera mobile browsers, and * the PlayStation 3; forced `false` for Windows 8 apps). * * @memberOf _.support * @type boolean */ support.funcDecomp = !isNative(root.WinRTError) && reThis.test(function() { return this; }); /** * Detect if `Function#name` is supported (all but IE). * * @memberOf _.support * @type boolean */ support.funcNames = typeof Function.name == 'string'; /** * Detect if the DOM is supported. * * @memberOf _.support * @type boolean */ try { support.dom = document.createDocumentFragment().nodeType === 11; } catch(e) { support.dom = false; } /** * Detect if `arguments` object indexes are non-enumerable. * * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat * `arguments` object indexes as non-enumerable and fail `hasOwnProperty` * checks for indexes that exceed their function's formal parameters with * associated values of `0`. * * @memberOf _.support * @type boolean */ try { support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1); } catch(e) { support.nonEnumArgs = true; } }(0, 0)); return support; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Detect free variable `exports`. */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect free variable `global` from Node.js. */ var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; /** Detect free variable `window`. */ var freeWindow = objectTypes[typeof window] && window; /** * Used as a reference to the global object. * * The `this` value is used if it is the global object to avoid Greasemonkey's * restricted `window` object, otherwise the `window` object is used. */ var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || this; return root; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(205)(module), __webpack_require__(17))) /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } return arrayCopy; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(15)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(isLength, isObjectLike) { /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the `toStringTag` of values. * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * for more details. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false; } return isTypedArray; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { /** * Copies the properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Object} [object={}] The object to copy properties to. * @param {Array} props The property names to copy. * @returns {Object} Returns `object`. */ function baseCopy(source, object, props) { if (!props) { props = object; object = {}; } var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } return baseCopy; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(212)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(identity) { /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (typeof thisArg == 'undefined') { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } return bindCallback; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var BlockPositioner = function BlockPositioner(block, mediator) { this.mediator = mediator; this.block = block; this._ensureElement(); this._bindFunctions(); this.initialize(); }; Object.assign(BlockPositioner.prototype, __webpack_require__(6), __webpack_require__(11), { bound: ['toggle', 'show', 'hide'], className: 'st-block-positioner', visibleClass: 'active', initialize: function initialize() {}, toggle: function toggle() { this.mediator.trigger('block-positioner-select:render', this); this.el.classList.toggle(this.visibleClass); }, show: function show() { this.el.classList.add(this.visibleClass); }, hide: function hide() { this.el.classList.remove(this.visibleClass); } }); module.exports = BlockPositioner; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Dom = __webpack_require__(3); var template = ["", ""].join("\n"); var BlockPositionerSelect = function BlockPositionerSelect(mediator) { this.mediator = mediator; this._ensureElement(); this._bindFunctions(); this.initialize(); }; Object.assign(BlockPositionerSelect.prototype, __webpack_require__(6), __webpack_require__(11), { total_blocks: 0, bound: ['onBlockCountChange', 'onSelectChange'], className: 'st-block-positioner__inner', initialize: function initialize() { this.el.insertAdjacentHTML("beforeend", template); this.select = this.el.querySelector('.st-block-positioner__select'); this.positioner = null; this.select.addEventListener('change', this.onSelectChange); }, onBlockCountChange: function onBlockCountChange(new_count) { if (new_count !== this.total_blocks) { this.total_blocks = new_count; this.renderPositionList(); } }, onSelectChange: function onSelectChange() { var val = this.select.value; if (val !== 0) { this.mediator.trigger("block:changePosition", this.positioner.block, val, val === 1 ? 'before' : 'after'); this.positioner.toggle(); } }, renderPositionList: function renderPositionList() { var inner = ""; for (var i = 1; i <= this.total_blocks; i++) { inner += ""; } this.select.innerHTML = inner; }, renderInBlock: function renderInBlock(positioner) { // hide old if (this.positioner && this.positioner !== positioner) { this.positioner.hide(); } // add new this.positioner = positioner; this.select.value = 0; Dom.remove(this.el); positioner.el.appendChild(this.el); } }); module.exports = BlockPositionerSelect; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var config = __webpack_require__(2); var BlockDeletion = function BlockDeletion() { this._ensureElement(); this._bindFunctions(); }; Object.assign(BlockDeletion.prototype, __webpack_require__(6), __webpack_require__(11), { tagName: 'a', className: 'st-block-ui-btn__delete', attributes: { html: function html() { return "\n \n "); }, 'data-icon': 'close' } }); module.exports = BlockDeletion; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var utils = __webpack_require__(1); var bestNameFromField = function bestNameFromField(field) { var msg = field.getAttribute("data-st-name") || field.getAttribute("name"); if (!msg) { msg = 'Field'; } return utils.capitalize(msg); }; module.exports = { errors: [], valid: function valid() { this.performValidations(); return this.errors.length === 0; }, // This method actually does the leg work // of running our validators and custom validators performValidations: function performValidations() { this.resetErrors(); var required_fields = this.$('.st-required'); Array.prototype.forEach.call(required_fields, function (f, i) { this.validateField(f); }.bind(this)); this.validations.forEach(this.runValidator, this); this.el.classList.toggle('st-block--with-errors', this.errors.length > 0); }, // Everything in here should be a function that returns true or false validations: [], validateField: function validateField(field) { var content = field.getAttribute('contenteditable') ? field.textContent : field.value; if (content.length === 0) { this.setError(field, i18n.t("errors:block_empty", { name: bestNameFromField(field) })); } }, runValidator: function runValidator(validator) { if (!_.isUndefined(this[validator])) { this[validator].call(this); } }, setError: function setError(field, reason) { var msg = this.addMessage(reason, "st-msg--error"); field.classList.add('st-error'); this.errors.push({ field: field, reason: reason, msg: msg }); }, resetErrors: function resetErrors() { this.errors.forEach(function (error) { error.field.classList.remove('st-error'); error.msg.remove(); }); this.messages.classList.remove("st-block__messages--is-visible"); this.errors = []; } }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var utils = __webpack_require__(1); var EventBus = __webpack_require__(4); module.exports = { /** * Internal storage object for the block */ blockStorage: {}, /** * Initialize the store, including the block type */ createStore: function createStore(blockData) { this.blockStorage = { type: utils.underscored(this.type), data: blockData || {} }; }, /** * Serialize the block and save the data into the store */ save: function save() { var data = this._serializeData(); if (!_.isEmpty(data)) { this.setData(data); } }, getData: function getData() { this.save(); return this.blockStorage; }, getBlockData: function getBlockData() { this.save(); return this.blockStorage.data; }, _getData: function _getData() { return this.blockStorage.data; }, /** * Set the block data. * This is used by the save() method. */ setData: function setData(blockData) { utils.log("Setting data for block " + this.blockID); Object.assign(this.blockStorage.data, blockData || {}); }, setAndLoadData: function setAndLoadData(blockData) { this.setData(blockData); this.beforeLoadingData(); }, _serializeData: function _serializeData() {}, loadData: function loadData() {}, beforeLoadingData: function beforeLoadingData() { utils.log("loadData for " + this.blockID); EventBus.trigger("editor/block/loadData"); this.loadData(this._getData()); }, _loadData: function _loadData() { utils.log("_loadData is deprecated and will be removed in the future. Please use beforeLoadingData instead."); this.beforeLoadingData(); }, checkAndLoadData: function checkAndLoadData() { if (!_.isEmpty(this._getData())) { this.beforeLoadingData(); } } }; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var selectionRange = __webpack_require__(13); var _ = __webpack_require__(0); var utils = __webpack_require__(1); var config = __webpack_require__(2); var EventBus = __webpack_require__(4); var Blocks = __webpack_require__(21); var Dom = __webpack_require__(3); var BLOCK_OPTION_KEYS = ['convertToMarkdown', 'convertFromMarkdown', 'formatBar']; var BlockManager = function BlockManager(SirTrevor) { this.options = SirTrevor.options; this.blockOptions = BLOCK_OPTION_KEYS.reduce(function (acc, key) { acc[key] = SirTrevor.options[key]; return acc; }, {}); this.instance_scope = SirTrevor.ID; this.mediator = SirTrevor.mediator; this.editor = SirTrevor; // REFACTOR: this is a hack until I can focus on reworking the blockmanager this.wrapper = SirTrevor.wrapper; this.blocks = []; this.blockCounts = {}; this.blockTypes = []; this._setBlocksTypes(); this._setRequired(); this._bindMediatedEvents(); this.initialize(); }; Object.assign(BlockManager.prototype, __webpack_require__(6), __webpack_require__(30), __webpack_require__(9), { eventNamespace: 'block', mediatedEvents: { 'create': 'createBlock', 'createBefore': 'createBlockBefore', 'remove': 'removeBlock', 'rerender': 'rerenderBlock', 'replace': 'replaceBlock', 'focusPrevious': 'focusPreviousBlock', 'focusNext': 'focusNextBlock', 'paste': 'paste' }, initialize: function initialize() {}, createBlock: function createBlock(type, data, previousSibling) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; options = Object.assign({ autoFocus: false, focusAtEnd: false }, options); type = utils.classify(type); // Run validations if (!this.canCreateBlock(type)) { return; } var block = new Blocks[type](data, this.instance_scope, this.mediator, this.blockOptions, this.options); this.blocks.push(block); this._incrementBlockTypeCount(type); this.renderBlock(block, previousSibling); if (options.autoFocus) { block.focus(); } else if (options.focusAtEnd) { block.focusAtEnd(); } this.triggerBlockCountUpdate(); this.mediator.trigger('block:limitReached', this.blockLimitReached()); this.mediator.trigger('block:created', block); EventBus.trigger(data ? "block:create:existing" : "block:create:new", block); utils.log("Block created of type " + type); }, createBlockBefore: function createBlockBefore(type, data, nextBlock) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; options = Object.assign({ autoFocus: false, focusAtEnd: false }, options); type = utils.classify(type); // Run validations if (!this.canCreateBlock(type)) { return; } var block = new Blocks[type](data, this.instance_scope, this.mediator, this.blockOptions, this.options); this.blocks.push(block); this._incrementBlockTypeCount(type); var previousBlock = this.getPreviousBlock(nextBlock); if (previousBlock) { this.renderBlock(block, previousBlock.el); } else { this.renderBlock(block, this.wrapper.querySelector(".st-top-controls")); } if (options.autoFocus) { block.focus(); } else if (options.focusAtEnd) { block.focusAtEnd(); } this.triggerBlockCountUpdate(); this.mediator.trigger('block:limitReached', this.blockLimitReached()); this.mediator.trigger('block:created', block); EventBus.trigger(data ? "block:create:existing" : "block:create:new", block); utils.log("Block created of type " + type); }, removeBlock: function removeBlock(blockID, options) { options = Object.assign({ transposeContent: false, focusOnPrevious: false, focusOnNext: false, createNextBlock: false }, options); var block = this.findBlockById(blockID); var type = utils.classify(block.type); var previousBlock = this.getPreviousBlock(block); var nextBlock = this.getNextBlock(block); if (options.transposeContent && block.mergeable) { // Don't allow removal of first block if it's the only block. if (!previousBlock && this.blocks.length === 1) { return; } // If previous block can transpose content then append content. if (previousBlock && previousBlock.type === "list") { previousBlock.focusAtEnd(); previousBlock.appendToCurrentItem(block.getScribeInnerContent()); } else if (previousBlock && previousBlock.mergeable) { previousBlock.appendContent(block.getScribeInnerContent(), { keepCaretPosition: true }); } else { // If there's content and the block above isn't mergeable then // cancel remove. if (block.getScribeInnerContent() !== '') { return; } // If block before isn't mergeable then we want to still focus. if (previousBlock) { previousBlock.focusAtEnd(); } else if (nextBlock) { // If there wasn't a previous block then // we'll want to focus on the next block. nextBlock.focus(); } } } this.mediator.trigger('block-controls:reset'); this.blocks = this.blocks.filter(function (item) { return item.blockID !== block.blockID; }); block.remove(); if (previousBlock && nextBlock) { // Join blocks if they span the removed block if (this.options.joinListBlocksOnBlockRemove && previousBlock.type === "list" && nextBlock.type === "list") { var listItems = nextBlock._serializeData().listItems; nextBlock.remove(); var currentListItem = previousBlock.getCurrentTextEditor(); var currentSelection = selectionRange(currentListItem.scribe.el); listItems.forEach(function (item) { previousBlock.addListItem(item.content); }); previousBlock.focusOn(currentListItem, { caretPosition: currentSelection.start }); } } if (options.focusOnPrevious && previousBlock) { previousBlock.focusAtEnd(); } if (options.focusOnNext) { if (nextBlock) { nextBlock.focus(); } else if (options.createNextBlock) { this.createBlock("text", null, null, { autoFocus: true }); } } this._decrementBlockTypeCount(type); this.triggerBlockCountUpdate(); this.mediator.trigger('block:limitReached', this.blockLimitReached()); EventBus.trigger('block:remove', blockID); }, replaceBlock: function replaceBlock(blockNode, type, data) { var block = this.findBlockById(blockNode.id); this.createBlock(type, data || null, blockNode); this.removeBlock(blockNode.id); block.remove(); }, renderBlock: function renderBlock(block, previousSibling) { var _this = this; // REFACTOR: this will have to do until we're able to address // the block manager var blockElement = block.render().el; if (previousSibling) { Dom.insertAfter(blockElement, previousSibling); } else { this.wrapper.appendChild(blockElement); } block.trigger("onRender"); if (this.options.selectionMouse) { blockElement.addEventListener("mouseenter", function () { if (!_this.editor.mouseDown) return; var blockPosition = _this.getBlockPosition(block.el); _this.mediator.trigger("selection:update", blockPosition); }); blockElement.addEventListener("mousedown", function (ev) { var blockPosition = _this.getBlockPosition(block.el); var options = { mouseEnabled: true, expand: ev.shiftKey || ev.metaKey }; _this.mediator.trigger("selection:start", blockPosition, options); }); } }, rerenderBlock: function rerenderBlock(blockID) { var block = this.findBlockById(blockID); if (!_.isUndefined(block) && !block.isEmpty() && block.drop_options.re_render_on_reorder) { block.beforeLoadingData(); } }, getPreviousBlock: function getPreviousBlock(block) { var blockPosition = this.getBlockPosition(block.el); if (blockPosition < 1) { return; } var previousBlock = this.wrapper.querySelectorAll('.st-block')[blockPosition - 1]; return this.findBlockById(previousBlock.getAttribute('id')); }, getNextBlock: function getNextBlock(block) { var blockPosition = this.getBlockPosition(block.el); if (blockPosition < 0 || blockPosition >= this.blocks.length - 1) { return; } return this.findBlockById(this.wrapper.querySelectorAll('.st-block')[blockPosition + 1].getAttribute('id')); }, getBlockPosition: function getBlockPosition(block) { return Array.prototype.indexOf.call(this.wrapper.querySelectorAll('.st-block'), block); }, focusPreviousBlock: function focusPreviousBlock(blockID) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options = Object.assign({ force: false }, options); var block = this.findBlockById(blockID); if (block && (block.mergeable || options.force)) { var previousBlock = this.getPreviousBlock(block); if (previousBlock && previousBlock.mergeable) { previousBlock.focusAtEnd(); } else if (options.force) { block.focus(); } } }, focusNextBlock: function focusNextBlock(blockID) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options = Object.assign({ force: false }, options); var block = this.findBlockById(blockID); if (block && (block.mergeable || options.force)) { var nextBlock = this.getNextBlock(block); if (nextBlock && nextBlock.mergeable) { nextBlock.focusAtStart(); } else if (options.force) { block.focusAtEnd(); } } }, paste: function paste(blocks) { var _this2 = this; var currentBlock = utils.getBlockBySelection(); if (currentBlock) { currentBlock.split(); var nextBlock = this.getNextBlock(currentBlock); if (currentBlock.isEmpty()) { this.removeBlock(currentBlock.blockID); } if (nextBlock) { blocks.forEach(function (block) { _this2.createBlockBefore(block.type, block.data, nextBlock, { focusAtEnd: true }); }); return; } } blocks.forEach(function (block) { _this2.createBlock(block.type, block.data, undefined, { focusAtEnd: true }); }); }, triggerBlockCountUpdate: function triggerBlockCountUpdate() { this.mediator.trigger('block:countUpdate', this.blocks.length); }, canCreateBlock: function canCreateBlock(type) { if (this.blockLimitReached()) { utils.log("Cannot add any more blocks. Limit reached."); return false; } if (!this.isBlockTypeAvailable(type)) { utils.log("Block type not available " + type); return false; } // Can we have another one of these blocks? if (!this.canAddBlockType(type)) { utils.log("Block Limit reached for type " + type); return false; } return true; }, validateBlockTypesExist: function validateBlockTypesExist(shouldValidate) { if (config.skipValidation || !shouldValidate) { return false; } (this.required || []).forEach(function (type, index) { if (!this.isBlockTypeAvailable(type)) { return; } if (this._getBlockTypeCount(type) === 0) { utils.log("Failed validation on required block type " + type); this.mediator.trigger('errors:add', { text: i18n.t("errors:type_missing", { type: type }) }); } else { var blocks = this.getBlocksByType(type).filter(function (b) { return !b.isEmpty(); }); if (blocks.length > 0) { return false; } this.mediator.trigger('errors:add', { text: i18n.t("errors:required_type_empty", { type: type }) }); utils.log("A required block type " + type + " is empty"); } }, this); }, findBlockById: function findBlockById(blockID) { return this.blocks.find(function (b) { return b.blockID === blockID; }); }, getBlocksByType: function getBlocksByType(type) { return this.blocks.filter(function (b) { return utils.classify(b.type) === type; }); }, getBlocksByIDs: function getBlocksByIDs(block_ids) { return this.blocks.filter(function (b) { return block_ids.includes(b.blockID); }); }, blockLimitReached: function blockLimitReached() { return this.options.blockLimit !== 0 && this.blocks.length >= this.options.blockLimit; }, isBlockTypeAvailable: function isBlockTypeAvailable(t) { return this.blockTypes.includes(t); }, canAddBlockType: function canAddBlockType(type) { var block_type_limit = this._getBlockTypeLimit(type); return !(block_type_limit !== 0 && this._getBlockTypeCount(type) >= block_type_limit); }, _setBlocksTypes: function _setBlocksTypes() { this.blockTypes = this.options.blockTypes || Object.keys(Blocks); }, _setRequired: function _setRequired() { this.required = false; if (Array.isArray(this.options.required) && !_.isEmpty(this.options.required)) { this.required = this.options.required; } }, _incrementBlockTypeCount: function _incrementBlockTypeCount(type) { this.blockCounts[type] = _.isUndefined(this.blockCounts[type]) ? 1 : this.blockCounts[type] + 1; }, _decrementBlockTypeCount: function _decrementBlockTypeCount(type) { this.blockCounts[type] = _.isUndefined(this.blockCounts[type]) ? 1 : this.blockCounts[type] - 1; }, _getBlockTypeCount: function _getBlockTypeCount(type) { return _.isUndefined(this.blockCounts[type]) ? 0 : this.blockCounts[type]; }, _blockLimitReached: function _blockLimitReached() { return this.options.blockLimit !== 0 && this.blocks.length >= this.options.blockLimit; }, _getBlockTypeLimit: function _getBlockTypeLimit(t) { if (!this.isBlockTypeAvailable(t)) { return 0; } return parseInt(_.isUndefined(this.options.blockTypeLimits[t]) ? 0 : this.options.blockTypeLimits[t], 10); } }); module.exports = BlockManager; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var utils = __webpack_require__(1); var Dom = __webpack_require__(3); var Events = __webpack_require__(10); var BlockReorder = __webpack_require__(39); var BLOCK_TEMPLATE = __webpack_require__(223); var SimpleBlock = function SimpleBlock(data, instance_id, mediator, options, editorOptions) { this.createStore(data); this.blockID = _.uniqueId('st-block-'); this.instanceID = instance_id; this.mediator = mediator; this.options = options || {}; this.editorOptions = editorOptions || {}; this._ensureElement(); this._bindFunctions(); this.initialize.apply(this, arguments); }; Object.assign(SimpleBlock.prototype, __webpack_require__(6), __webpack_require__(9), __webpack_require__(11), __webpack_require__(85), { focus: function focus() {}, valid: function valid() { return true; }, className: 'st-block', block_template: BLOCK_TEMPLATE, attributes: function attributes() { return { 'id': this.blockID, 'data-type': this.type, 'data-instance': this.instanceID }; }, title: function title() { return i18n.t("blocks:".concat(this.type, ":title")) || utils.titleize(this.type.replace(/[\W_]/g, ' ')); }, blockCSSClass: function blockCSSClass() { this.blockCSSClass = utils.toSlug(this.type); return this.blockCSSClass; }, type: '', class: function _class() { return utils.classify(this.type); }, editorHTML: '', initialize: function initialize() {}, onBlockRender: function onBlockRender() {}, beforeBlockRender: function beforeBlockRender() {}, _setBlockInner: function _setBlockInner() { var editor_html = _.result(this, 'editorHTML'); this.el.insertAdjacentHTML("beforeend", this.block_template(editor_html)); this.inner = this.el.querySelector('.st-block__inner'); }, render: function render() { this.beforeBlockRender(); this._setBlockInner(); this._blockPrepare(); return this; }, _blockPrepare: function _blockPrepare() { this._initUI(); this._initMessages(); this.checkAndLoadData(); this.el.classList.add('st-item-ready'); this.on("onRender", this.onBlockRender); this.save(); }, _withUIComponent: function _withUIComponent(component, className, callback) { this.ui.appendChild(component.render().el); if (className && callback) { Events.delegate(this.ui, className, 'click', callback); } }, _initUI: function _initUI() { var ui_element = Dom.createElement("div", { 'class': 'st-block__ui' }); this.el.appendChild(ui_element); this.ui = ui_element; this._initUIComponents(); }, _initMessages: function _initMessages() { var msgs_element = Dom.createElement("div", { 'class': 'st-block__messages' }); this.inner.insertBefore(msgs_element, this.inner.firstChild); this.messages = msgs_element; }, addMessage: function addMessage(msg, additionalClass) { msg = Dom.createElement("span", { html: msg, class: "st-msg " + additionalClass }); this.messages.appendChild(msg); this.messages.classList.add('st-block__messages--is-visible'); return msg; }, resetMessages: function resetMessages() { this.messages.innerHTML = ''; this.messages.classList.remove('st-block__messages--is-visible'); }, _initUIComponents: function _initUIComponents() { this._withUIComponent(new BlockReorder(this.el)); } }); SimpleBlock.fn = SimpleBlock.prototype; // Allow our Block to be extended. SimpleBlock.extend = __webpack_require__(89); module.exports = SimpleBlock; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var config = __webpack_require__(2); module.exports = function () { return "\n \n "); }; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* Backbone Inheritence -- From: https://github.com/documentcloud/backbone/blob/master/backbone.js Backbone.js 0.9.2 (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. */ module.exports = function (protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function child() { return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. Object.assign(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function Surrogate() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); // jshint ignore:line // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) { Object.assign(child.prototype, protoProps); } // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _require = __webpack_require__(16), createBlocksFromParagraphs = _require.createBlocksFromParagraphs, isAtStart = _require.isAtStart, isAtEnd = _require.isAtEnd, isSelectedFromStart = _require.isSelectedFromStart, isSelectedToEnd = _require.isSelectedToEnd, selectToEnd = _require.selectToEnd; var ScribeTextBlockPlugin = function ScribeTextBlockPlugin(block) { return function (scribe) { var isAtStartBoolean = false; scribe.el.addEventListener('keydown', function (ev) { if (block.supressKeyListeners) { return; } if (ev.key === "Enter" && !ev.shiftKey) { // enter pressed ev.preventDefault(); if (isAtEnd(scribe)) { // Remove any bad characters after current selection. selectToEnd(scribe).extractContents(); block.mediator.trigger("block:create", 'Text', null, block.el, { autoFocus: true }); } else { createBlocksFromParagraphs(block, scribe); } // If the block is left empty then we need to reset the placeholder content. if (scribe.allowsBlockElements() && scribe.getTextContent() === '') { scribe.setContent('


'); } } else if (["Left", "ArrowLeft", "Up", "ArrowUp"].indexOf(ev.key) > -1) { if (ev.shiftKey && isSelectedFromStart(scribe)) { ev.preventDefault(); ev.stopPropagation(); document.activeElement && document.activeElement.blur(); block.mediator.trigger("selection:block", block); } else if (isAtStart(scribe)) { ev.preventDefault(); ev.stopPropagation(); block.mediator.trigger("block:focusPrevious", block.blockID); } } else if (ev.keyCode === 8 && isAtStart(scribe)) { ev.preventDefault(); isAtStartBoolean = true; } else if (["Right", "ArrowRight", "Down", "ArrowDown"].indexOf(ev.key) > -1) { if (ev.shiftKey && isSelectedToEnd(scribe)) { ev.preventDefault(); ev.stopPropagation(); document.activeElement && document.activeElement.blur(); block.mediator.trigger("selection:block", block); } else if (isAtEnd(scribe)) { ev.preventDefault(); block.mediator.trigger("block:focusNext", block.blockID); } } }); scribe.el.addEventListener('keyup', function (ev) { if (block.supressKeyListeners) { return; } if (ev.key === "Backspace" && isAtStartBoolean) { ev.preventDefault(); block.mediator.trigger('block:remove', block.blockID, { transposeContent: true }); isAtStartBoolean = false; } }); }; }; module.exports = ScribeTextBlockPlugin; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Format Bar * -- * Displayed on focus on a text area. * Renders with all available options for the editor instance */ var _ = __webpack_require__(0); var config = __webpack_require__(2); var Dom = __webpack_require__(3); var Events = __webpack_require__(10); var FORMAT_BUTTON_TEMPLATE = __webpack_require__(236); var FormatBar = function FormatBar(options, mediator, editor) { this.editor = editor; this.options = Object.assign({}, config.defaults.formatBar, options || {}); this.commands = this.options.commands; this.mediator = mediator; this.isShown = false; this._ensureElement(); this._bindFunctions(); this._bindMediatedEvents(); this.initialize.apply(this, arguments); }; Object.assign(FormatBar.prototype, __webpack_require__(6), __webpack_require__(30), __webpack_require__(9), __webpack_require__(11), { className: 'st-format-bar', bound: ["onFormatButtonClick", "renderBySelection", "hide"], eventNamespace: 'formatter', mediatedEvents: { 'position': 'renderBySelection', 'show': 'show', 'hide': 'hide' }, initialize: function initialize() { var buttons = this.commands.reduce(function (memo, format) { return memo += FORMAT_BUTTON_TEMPLATE(format); }, ""); this.el.insertAdjacentHTML("beforeend", buttons); // We use mousedown rather than click as that allows us to keep focus on the contenteditable field. Events.delegate(this.el, '.st-format-btn', 'mousedown', this.onFormatButtonClick); }, hide: function hide() { this.block = undefined; this.isShown = false; this.el.classList.remove('st-format-bar--is-ready'); Dom.remove(this.el); }, show: function show() { if (this.isShown) { return; } this.isShown = true; this.editor.outer.appendChild(this.el); this.el.classList.add('st-format-bar--is-ready'); }, remove: function remove() { Dom.remove(this.el); }, renderBySelection: function renderBySelection(block) { this.block = block; this.highlightSelectedButtons(); this.show(); this.calculatePosition(); }, calculatePosition: function calculatePosition() { var selection = window.getSelection(), range = selection.getRangeAt(0), boundary = range.getBoundingClientRect(), coords = {}, outer = this.editor.outer, outerBoundary = outer.getBoundingClientRect(); coords.top = boundary.top - outerBoundary.top + 'px'; coords.left = (boundary.left + boundary.right) / 2 - this.el.offsetWidth / 2 - outerBoundary.left + 'px'; this.el.style.top = coords.top; this.el.style.left = coords.left; }, highlightSelectedButtons: function highlightSelectedButtons() { var _this = this; [].forEach.call(this.el.querySelectorAll(".st-format-btn"), function (btn) { var cmd = btn.getAttribute('data-cmd'); btn.classList.toggle("st-format-btn--is-active", _this.block.queryTextBlockCommandState(cmd)); btn = null; }); }, onFormatButtonClick: function onFormatButtonClick(ev) { ev.preventDefault(); ev.stopPropagation(); if (_.isUndefined(this.block)) { throw "Associated block not found"; } var btn = ev.currentTarget, cmd = btn.getAttribute('data-cmd'); if (_.isUndefined(cmd)) { return false; } this.block.execTextBlockCommand(cmd); this.highlightSelectedButtons(); // Re-select the contenteditable field. document.activeElement.focus(); return false; } }); module.exports = FormatBar; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var config = __webpack_require__(2); var utils = __webpack_require__(1); var EventBus = __webpack_require__(4); var Submittable = __webpack_require__(62); var formBound = false; // Flag to tell us once we've bound our submit event var FormEvents = { bindFormSubmit: function bindFormSubmit(form) { if (!formBound) { // XXX: should we have a formBound and submittable per-editor? // telling JSHint to ignore as it'll complain we shouldn't be creating // a new object, but otherwise `this` won't be set in the Submittable // initialiser. Bit weird. new Submittable(form); // jshint ignore:line form.addEventListener('submit', this.onFormSubmit); formBound = true; } }, onBeforeSubmit: function onBeforeSubmit(shouldValidate) { // Loop through all of our instances and do our form submits on them var errors = 0; config.instances.forEach(function (inst, i) { errors += inst.onFormSubmit(shouldValidate); }); utils.log("Total errors: " + errors); return errors; }, onFormSubmit: function onFormSubmit(ev) { var errors = FormEvents.onBeforeSubmit(); if (errors > 0) { EventBus.trigger("onError"); ev.preventDefault(); } } }; module.exports = FormEvents; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(94); __webpack_require__(246); /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; __webpack_require__(95); // ES6 shims __webpack_require__(96).shim(); __webpack_require__(101).shim(); __webpack_require__(114); // shims ES7 Array.prototype.includes __webpack_require__(115).polyfill(); // Old IE support __webpack_require__(116); __webpack_require__(117); __webpack_require__(118); var utils = __webpack_require__(1); var SirTrevor = { config: __webpack_require__(2), log: utils.log, Locales: __webpack_require__(140), Events: __webpack_require__(9), EventBus: __webpack_require__(4), EditorStore: __webpack_require__(61), Submittable: __webpack_require__(62), FileUploader: __webpack_require__(63), BlockMixins: __webpack_require__(65), BlockPositioner: __webpack_require__(81), BlockPositionerSelect: __webpack_require__(82), BlockReorder: __webpack_require__(39), BlockDeletion: __webpack_require__(83), BlockValidations: __webpack_require__(84), BlockStore: __webpack_require__(85), BlockManager: __webpack_require__(86), SimpleBlock: __webpack_require__(87), Block: __webpack_require__(8), Blocks: __webpack_require__(21), FormatBar: __webpack_require__(91), Editor: __webpack_require__(237), toMarkdown: __webpack_require__(245), toHTML: __webpack_require__(22), setDefaults: function setDefaults(options) { Object.assign(SirTrevor.config.defaults, options || {}); }, getInstance: utils.getInstance, setBlockOptions: function setBlockOptions(type, options) { var block = SirTrevor.Blocks[type]; if (typeof block === "undefined") { return; } Object.assign(block.prototype, options || {}); }, runOnAllInstances: function runOnAllInstances(method) { if (SirTrevor.Editor.prototype.hasOwnProperty(method)) { var methodArgs = Array.prototype.slice.call(arguments, 1); Array.prototype.forEach.call(SirTrevor.config.instances, function (i) { i[method].apply(null, methodArgs); }); } else { SirTrevor.log("method doesn't exist"); } } }; Object.assign(SirTrevor, __webpack_require__(92)); module.exports = SirTrevor; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__.p + "178289a66e4bc63fe9a24fba4c8acf36.svg"; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var defineProperties = __webpack_require__(23); var implementation = __webpack_require__(43); var getPolyfill = __webpack_require__(45); var shim = __webpack_require__(100); var polyfill = getPolyfill(); defineProperties(polyfill, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = polyfill; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /* 98 */ /***/ (function(module, exports) { var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var define = __webpack_require__(23); var getPolyfill = __webpack_require__(45); module.exports = function shimAssign() { var polyfill = getPolyfill(); define( Object, { assign: polyfill }, { assign: function () { return Object.assign !== polyfill; } } ); return polyfill; }; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var define = __webpack_require__(23); var ES = __webpack_require__(46); var implementation = __webpack_require__(53); var getPolyfill = __webpack_require__(54); var shim = __webpack_require__(113); var slice = Array.prototype.slice; var polyfill = getPolyfill(); var boundFindShim = function find(array, predicate) { // eslint-disable-line no-unused-vars ES.RequireObjectCoercible(array); var args = slice.call(arguments, 1); return polyfill.apply(array, args); }; define(boundFindShim, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = boundFindShim; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = __webpack_require__(31); var toPrimitive = __webpack_require__(103); var GetIntrinsic = __webpack_require__(48); var $TypeError = GetIntrinsic('%TypeError%'); var $SyntaxError = GetIntrinsic('%SyntaxError%'); var $Array = GetIntrinsic('%Array%'); var $String = GetIntrinsic('%String%'); var $Object = GetIntrinsic('%Object%'); var $Number = GetIntrinsic('%Number%'); var $Symbol = GetIntrinsic('%Symbol%', true); var $RegExp = GetIntrinsic('%RegExp%'); var hasSymbols = !!$Symbol; var $isNaN = __webpack_require__(49); var $isFinite = __webpack_require__(50); var MAX_SAFE_INTEGER = $Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1; var assign = __webpack_require__(108); var sign = __webpack_require__(51); var mod = __webpack_require__(52); var isPrimitive = __webpack_require__(109); var parseInteger = parseInt; var bind = __webpack_require__(24); var arraySlice = bind.call(Function.call, $Array.prototype.slice); var strSlice = bind.call(Function.call, $String.prototype.slice); var isBinary = bind.call(Function.call, $RegExp.prototype.test, /^0b[01]+$/i); var isOctal = bind.call(Function.call, $RegExp.prototype.test, /^0o[0-7]+$/i); var regexExec = bind.call(Function.call, $RegExp.prototype.exec); var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); var hasNonWS = bind.call(Function.call, $RegExp.prototype.test, nonWSregex); var invalidHexLiteral = /^[-+]0x[0-9a-f]+$/i; var isInvalidHexLiteral = bind.call(Function.call, $RegExp.prototype.test, invalidHexLiteral); var $charCodeAt = bind.call(Function.call, $String.prototype.charCodeAt); var toStr = bind.call(Function.call, Object.prototype.toString); var $floor = Math.floor; var $abs = Math.abs; var $ObjectCreate = Object.create; var $gOPD = $Object.getOwnPropertyDescriptor; var $isExtensible = $Object.isExtensible; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); var replace = bind.call(Function.call, $String.prototype.replace); var trim = function (value) { return replace(value, trimRegex, ''); }; var ES5 = __webpack_require__(110); var hasRegExpMatcher = __webpack_require__(112); // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-abstract-operations var ES6 = assign(assign({}, ES5), { // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args Call: function Call(F, V) { var args = arguments.length > 2 ? arguments[2] : []; if (!this.IsCallable(F)) { throw new $TypeError(F + ' is not a function'); } return F.apply(V, args); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toprimitive ToPrimitive: toPrimitive, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toboolean // ToBoolean: ES5.ToBoolean, // https://ecma-international.org/ecma-262/6.0/#sec-tonumber ToNumber: function ToNumber(argument) { var value = isPrimitive(argument) ? argument : toPrimitive(argument, $Number); if (typeof value === 'symbol') { throw new $TypeError('Cannot convert a Symbol value to a number'); } if (typeof value === 'string') { if (isBinary(value)) { return this.ToNumber(parseInteger(strSlice(value, 2), 2)); } else if (isOctal(value)) { return this.ToNumber(parseInteger(strSlice(value, 2), 8)); } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { return NaN; } else { var trimmed = trim(value); if (trimmed !== value) { return this.ToNumber(trimmed); } } } return $Number(value); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tointeger // ToInteger: ES5.ToNumber, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint32 // ToInt32: ES5.ToInt32, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint32 // ToUint32: ES5.ToUint32, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint16 ToInt16: function ToInt16(argument) { var int16bit = this.ToUint16(argument); return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint16 // ToUint16: ES5.ToUint16, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint8 ToInt8: function ToInt8(argument) { var int8bit = this.ToUint8(argument); return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8 ToUint8: function ToUint8(argument) { var number = this.ToNumber(argument); if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } var posInt = sign(number) * $floor($abs(number)); return mod(posInt, 0x100); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8clamp ToUint8Clamp: function ToUint8Clamp(argument) { var number = this.ToNumber(argument); if ($isNaN(number) || number <= 0) { return 0; } if (number >= 0xFF) { return 0xFF; } var f = $floor(argument); if (f + 0.5 < number) { return f + 1; } if (number < f + 0.5) { return f; } if (f % 2 !== 0) { return f + 1; } return f; }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring ToString: function ToString(argument) { if (typeof argument === 'symbol') { throw new $TypeError('Cannot convert a Symbol value to a string'); } return $String(argument); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toobject ToObject: function ToObject(value) { this.RequireObjectCoercible(value); return $Object(value); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey ToPropertyKey: function ToPropertyKey(argument) { var key = this.ToPrimitive(argument, $String); return typeof key === 'symbol' ? key : this.ToString(key); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength ToLength: function ToLength(argument) { var len = this.ToInteger(argument); if (len <= 0) { return 0; } // includes converting -0 to +0 if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } return len; }, // https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring CanonicalNumericIndexString: function CanonicalNumericIndexString(argument) { if (toStr(argument) !== '[object String]') { throw new $TypeError('must be a string'); } if (argument === '-0') { return -0; } var n = this.ToNumber(argument); if (this.SameValue(this.ToString(n), argument)) { return n; } return void 0; }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-requireobjectcoercible RequireObjectCoercible: ES5.CheckObjectCoercible, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray IsArray: $Array.isArray || function IsArray(argument) { return toStr(argument) === '[object Array]'; }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iscallable // IsCallable: ES5.IsCallable, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor IsConstructor: function IsConstructor(argument) { return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isextensible-o IsExtensible: Object.preventExtensions ? function IsExtensible(obj) { if (isPrimitive(obj)) { return false; } return $isExtensible(obj); } : function isExtensible(obj) { return true; }, // eslint-disable-line no-unused-vars // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isinteger IsInteger: function IsInteger(argument) { if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { return false; } var abs = $abs(argument); return $floor(abs) === abs; }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ispropertykey IsPropertyKey: function IsPropertyKey(argument) { return typeof argument === 'string' || typeof argument === 'symbol'; }, // https://ecma-international.org/ecma-262/6.0/#sec-isregexp IsRegExp: function IsRegExp(argument) { if (!argument || typeof argument !== 'object') { return false; } if (hasSymbols) { var isRegExp = argument[$Symbol.match]; if (typeof isRegExp !== 'undefined') { return ES5.ToBoolean(isRegExp); } } return hasRegExpMatcher(argument); }, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevalue // SameValue: ES5.SameValue, // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero SameValueZero: function SameValueZero(x, y) { return (x === y) || ($isNaN(x) && $isNaN(y)); }, /** * 7.3.2 GetV (V, P) * 1. Assert: IsPropertyKey(P) is true. * 2. Let O be ToObject(V). * 3. ReturnIfAbrupt(O). * 4. Return O.[[Get]](P, V). */ GetV: function GetV(V, P) { // 7.3.2.1 if (!this.IsPropertyKey(P)) { throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); } // 7.3.2.2-3 var O = this.ToObject(V); // 7.3.2.4 return O[P]; }, /** * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod * 1. Assert: IsPropertyKey(P) is true. * 2. Let func be GetV(O, P). * 3. ReturnIfAbrupt(func). * 4. If func is either undefined or null, return undefined. * 5. If IsCallable(func) is false, throw a TypeError exception. * 6. Return func. */ GetMethod: function GetMethod(O, P) { // 7.3.9.1 if (!this.IsPropertyKey(P)) { throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); } // 7.3.9.2 var func = this.GetV(O, P); // 7.3.9.4 if (func == null) { return void 0; } // 7.3.9.5 if (!this.IsCallable(func)) { throw new $TypeError(P + 'is not a function'); } // 7.3.9.6 return func; }, /** * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p * 1. Assert: Type(O) is Object. * 2. Assert: IsPropertyKey(P) is true. * 3. Return O.[[Get]](P, O). */ Get: function Get(O, P) { // 7.3.1.1 if (this.Type(O) !== 'Object') { throw new $TypeError('Assertion failed: Type(O) is not Object'); } // 7.3.1.2 if (!this.IsPropertyKey(P)) { throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); } // 7.3.1.3 return O[P]; }, Type: function Type(x) { if (typeof x === 'symbol') { return 'Symbol'; } return ES5.Type(x); }, // https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor SpeciesConstructor: function SpeciesConstructor(O, defaultConstructor) { if (this.Type(O) !== 'Object') { throw new $TypeError('Assertion failed: Type(O) is not Object'); } var C = O.constructor; if (typeof C === 'undefined') { return defaultConstructor; } if (this.Type(C) !== 'Object') { throw new $TypeError('O.constructor is not an Object'); } var S = hasSymbols && $Symbol.species ? C[$Symbol.species] : void 0; if (S == null) { return defaultConstructor; } if (this.IsConstructor(S)) { return S; } throw new $TypeError('no constructor found'); }, // https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor CompletePropertyDescriptor: function CompletePropertyDescriptor(Desc) { if (!this.IsPropertyDescriptor(Desc)) { throw new $TypeError('Desc must be a Property Descriptor'); } if (this.IsGenericDescriptor(Desc) || this.IsDataDescriptor(Desc)) { if (!has(Desc, '[[Value]]')) { Desc['[[Value]]'] = void 0; } if (!has(Desc, '[[Writable]]')) { Desc['[[Writable]]'] = false; } } else { if (!has(Desc, '[[Get]]')) { Desc['[[Get]]'] = void 0; } if (!has(Desc, '[[Set]]')) { Desc['[[Set]]'] = void 0; } } if (!has(Desc, '[[Enumerable]]')) { Desc['[[Enumerable]]'] = false; } if (!has(Desc, '[[Configurable]]')) { Desc['[[Configurable]]'] = false; } return Desc; }, // https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw Set: function Set(O, P, V, Throw) { if (this.Type(O) !== 'Object') { throw new $TypeError('O must be an Object'); } if (!this.IsPropertyKey(P)) { throw new $TypeError('P must be a Property Key'); } if (this.Type(Throw) !== 'Boolean') { throw new $TypeError('Throw must be a Boolean'); } if (Throw) { O[P] = V; return true; } else { try { O[P] = V; } catch (e) { return false; } } }, // https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty HasOwnProperty: function HasOwnProperty(O, P) { if (this.Type(O) !== 'Object') { throw new $TypeError('O must be an Object'); } if (!this.IsPropertyKey(P)) { throw new $TypeError('P must be a Property Key'); } return has(O, P); }, // https://ecma-international.org/ecma-262/6.0/#sec-hasproperty HasProperty: function HasProperty(O, P) { if (this.Type(O) !== 'Object') { throw new $TypeError('O must be an Object'); } if (!this.IsPropertyKey(P)) { throw new $TypeError('P must be a Property Key'); } return P in O; }, // https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable IsConcatSpreadable: function IsConcatSpreadable(O) { if (this.Type(O) !== 'Object') { return false; } if (hasSymbols && typeof $Symbol.isConcatSpreadable === 'symbol') { var spreadable = this.Get(O, Symbol.isConcatSpreadable); if (typeof spreadable !== 'undefined') { return this.ToBoolean(spreadable); } } return this.IsArray(O); }, // https://ecma-international.org/ecma-262/6.0/#sec-invoke Invoke: function Invoke(O, P) { if (!this.IsPropertyKey(P)) { throw new $TypeError('P must be a Property Key'); } var argumentsList = arraySlice(arguments, 2); var func = this.GetV(O, P); return this.Call(func, O, argumentsList); }, // https://ecma-international.org/ecma-262/6.0/#sec-getiterator GetIterator: function GetIterator(obj, method) { if (!hasSymbols) { throw new SyntaxError('ES.GetIterator depends on native iterator support.'); } var actualMethod = method; if (arguments.length < 2) { actualMethod = this.GetMethod(obj, $Symbol.iterator); } var iterator = this.Call(actualMethod, obj); if (this.Type(iterator) !== 'Object') { throw new $TypeError('iterator must return an object'); } return iterator; }, // https://ecma-international.org/ecma-262/6.0/#sec-iteratornext IteratorNext: function IteratorNext(iterator, value) { var result = this.Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); if (this.Type(result) !== 'Object') { throw new $TypeError('iterator next must return an object'); } return result; }, // https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete IteratorComplete: function IteratorComplete(iterResult) { if (this.Type(iterResult) !== 'Object') { throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); } return this.ToBoolean(this.Get(iterResult, 'done')); }, // https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue IteratorValue: function IteratorValue(iterResult) { if (this.Type(iterResult) !== 'Object') { throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); } return this.Get(iterResult, 'value'); }, // https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep IteratorStep: function IteratorStep(iterator) { var result = this.IteratorNext(iterator); var done = this.IteratorComplete(result); return done === true ? false : result; }, // https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose IteratorClose: function IteratorClose(iterator, completion) { if (this.Type(iterator) !== 'Object') { throw new $TypeError('Assertion failed: Type(iterator) is not Object'); } if (!this.IsCallable(completion)) { throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); } var completionThunk = completion; var iteratorReturn = this.GetMethod(iterator, 'return'); if (typeof iteratorReturn === 'undefined') { return completionThunk(); } var completionRecord; try { var innerResult = this.Call(iteratorReturn, iterator, []); } catch (e) { // if we hit here, then "e" is the innerResult completion that needs re-throwing // if the completion is of type "throw", this will throw. completionRecord = completionThunk(); completionThunk = null; // ensure it's not called twice. // if not, then return the innerResult completion throw e; } completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does completionThunk = null; // ensure it's not called twice. if (this.Type(innerResult) !== 'Object') { throw new $TypeError('iterator .return must return an object'); } return completionRecord; }, // https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject CreateIterResultObject: function CreateIterResultObject(value, done) { if (this.Type(done) !== 'Boolean') { throw new $TypeError('Assertion failed: Type(done) is not Boolean'); } return { value: value, done: done }; }, // https://ecma-international.org/ecma-262/6.0/#sec-regexpexec RegExpExec: function RegExpExec(R, S) { if (this.Type(R) !== 'Object') { throw new $TypeError('R must be an Object'); } if (this.Type(S) !== 'String') { throw new $TypeError('S must be a String'); } var exec = this.Get(R, 'exec'); if (this.IsCallable(exec)) { var result = this.Call(exec, R, [S]); if (result === null || this.Type(result) === 'Object') { return result; } throw new $TypeError('"exec" method must return `null` or an Object'); } return regexExec(R, S); }, // https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate ArraySpeciesCreate: function ArraySpeciesCreate(originalArray, length) { if (!this.IsInteger(length) || length < 0) { throw new $TypeError('Assertion failed: length must be an integer >= 0'); } var len = length === 0 ? 0 : length; var C; var isArray = this.IsArray(originalArray); if (isArray) { C = this.Get(originalArray, 'constructor'); // TODO: figure out how to make a cross-realm normal Array, a same-realm Array // if (this.IsConstructor(C)) { // if C is another realm's Array, C = undefined // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? // } if (this.Type(C) === 'Object' && hasSymbols && $Symbol.species) { C = this.Get(C, $Symbol.species); if (C === null) { C = void 0; } } } if (typeof C === 'undefined') { return $Array(len); } if (!this.IsConstructor(C)) { throw new $TypeError('C must be a constructor'); } return new C(len); // this.Construct(C, len); }, CreateDataProperty: function CreateDataProperty(O, P, V) { if (this.Type(O) !== 'Object') { throw new $TypeError('Assertion failed: Type(O) is not Object'); } if (!this.IsPropertyKey(P)) { throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); } var oldDesc = $gOPD(O, P); var extensible = oldDesc || (typeof $isExtensible !== 'function' || $isExtensible(O)); var immutable = oldDesc && (!oldDesc.writable || !oldDesc.configurable); if (immutable || !extensible) { return false; } var newDesc = { configurable: true, enumerable: true, value: V, writable: true }; Object.defineProperty(O, P, newDesc); return true; }, // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow CreateDataPropertyOrThrow: function CreateDataPropertyOrThrow(O, P, V) { if (this.Type(O) !== 'Object') { throw new $TypeError('Assertion failed: Type(O) is not Object'); } if (!this.IsPropertyKey(P)) { throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); } var success = this.CreateDataProperty(O, P, V); if (!success) { throw new $TypeError('unable to create data property'); } return success; }, // https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate ObjectCreate: function ObjectCreate(proto, internalSlotsList) { if (proto !== null && this.Type(proto) !== 'Object') { throw new $TypeError('Assertion failed: proto must be null or an object'); } var slots = arguments.length < 2 ? [] : internalSlotsList; if (slots.length > 0) { throw new $SyntaxError('es-abstract does not yet support internal slots'); } if (proto === null && !$ObjectCreate) { throw new $SyntaxError('native Object.create support is required to create null objects'); } return $ObjectCreate(proto); }, // https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex AdvanceStringIndex: function AdvanceStringIndex(S, index, unicode) { if (this.Type(S) !== 'String') { throw new $TypeError('S must be a String'); } if (!this.IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { throw new $TypeError('Assertion failed: length must be an integer >= 0 and <= 2**53'); } if (this.Type(unicode) !== 'Boolean') { throw new $TypeError('Assertion failed: unicode must be a Boolean'); } if (!unicode) { return index + 1; } var length = S.length; if ((index + 1) >= length) { return index + 1; } var first = $charCodeAt(S, index); if (first < 0xD800 || first > 0xDBFF) { return index + 1; } var second = $charCodeAt(S, index + 1); if (second < 0xDC00 || second > 0xDFFF) { return index + 1; } return index + 2; } }); delete ES6.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible module.exports = ES6; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(104); /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; var isPrimitive = __webpack_require__(47); var isCallable = __webpack_require__(32); var isDate = __webpack_require__(105); var isSymbol = __webpack_require__(106); var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) { if (typeof O === 'undefined' || O === null) { throw new TypeError('Cannot call method on ' + O); } if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) { throw new TypeError('hint must be "string" or "number"'); } var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString']; var method, result, i; for (i = 0; i < methodNames.length; ++i) { method = O[methodNames[i]]; if (isCallable(method)) { result = method.call(O); if (isPrimitive(result)) { return result; } } } throw new TypeError('No default value'); }; var GetMethod = function GetMethod(O, P) { var func = O[P]; if (func !== null && typeof func !== 'undefined') { if (!isCallable(func)) { throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function'); } return func; } return void 0; }; // http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive module.exports = function ToPrimitive(input) { if (isPrimitive(input)) { return input; } var hint = 'default'; if (arguments.length > 1) { if (arguments[1] === String) { hint = 'string'; } else if (arguments[1] === Number) { hint = 'number'; } } var exoticToPrim; if (hasSymbols) { if (Symbol.toPrimitive) { exoticToPrim = GetMethod(input, Symbol.toPrimitive); } else if (isSymbol(input)) { exoticToPrim = Symbol.prototype.valueOf; } } if (typeof exoticToPrim !== 'undefined') { var result = exoticToPrim.call(input, hint); if (isPrimitive(result)) { return result; } throw new TypeError('unable to convert exotic object to primitive'); } if (hint === 'default' && (isDate(input) || isSymbol(input))) { hint = 'string'; } return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint); }; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var getDay = Date.prototype.getDay; var tryDateObject = function tryDateObject(value) { try { getDay.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var dateClass = '[object Date]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isDateObject(value) { if (typeof value !== 'object' || value === null) { return false; } return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; }; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; var hasSymbols = __webpack_require__(107)(); if (hasSymbols) { var symToStr = Symbol.prototype.toString; var symStringRegex = /^Symbol\(.*\)$/; var isSymbolObject = function isRealSymbolObject(value) { if (typeof value.valueOf() !== 'symbol') { return false; } return symStringRegex.test(symToStr.call(value)); }; module.exports = function isSymbol(value) { if (typeof value === 'symbol') { return true; } if (toStr.call(value) !== '[object Symbol]') { return false; } try { return isSymbolObject(value); } catch (e) { return false; } }; } else { module.exports = function isSymbol(value) { // this environment does not support Symbols. return false && false; }; } /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { var origSymbol = global.Symbol; var hasSymbolSham = __webpack_require__(44); module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (typeof origSymbol('foo') !== 'symbol') { return false; } if (typeof Symbol('bar') !== 'symbol') { return false; } return hasSymbolSham(); }; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(17))) /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { var bind = __webpack_require__(24); var has = bind.call(Function.call, Object.prototype.hasOwnProperty); var $assign = Object.assign; module.exports = function assign(target, source) { if ($assign) { return $assign(target, source); } for (var key in source) { if (has(source, key)) { target[key] = source[key]; } } return target; }; /***/ }), /* 109 */ /***/ (function(module, exports) { module.exports = function isPrimitive(value) { return value === null || (typeof value !== 'function' && typeof value !== 'object'); }; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var GetIntrinsic = __webpack_require__(48); var $Object = GetIntrinsic('%Object%'); var $TypeError = GetIntrinsic('%TypeError%'); var $String = GetIntrinsic('%String%'); var $isNaN = __webpack_require__(49); var $isFinite = __webpack_require__(50); var sign = __webpack_require__(51); var mod = __webpack_require__(52); var IsCallable = __webpack_require__(32); var toPrimitive = __webpack_require__(111); var has = __webpack_require__(31); // https://es5.github.io/#x9 var ES5 = { ToPrimitive: toPrimitive, ToBoolean: function ToBoolean(value) { return !!value; }, ToNumber: function ToNumber(value) { return +value; // eslint-disable-line no-implicit-coercion }, ToInteger: function ToInteger(value) { var number = this.ToNumber(value); if ($isNaN(number)) { return 0; } if (number === 0 || !$isFinite(number)) { return number; } return sign(number) * Math.floor(Math.abs(number)); }, ToInt32: function ToInt32(x) { return this.ToNumber(x) >> 0; }, ToUint32: function ToUint32(x) { return this.ToNumber(x) >>> 0; }, ToUint16: function ToUint16(value) { var number = this.ToNumber(value); if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } var posInt = sign(number) * Math.floor(Math.abs(number)); return mod(posInt, 0x10000); }, ToString: function ToString(value) { return $String(value); }, ToObject: function ToObject(value) { this.CheckObjectCoercible(value); return $Object(value); }, CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) { /* jshint eqnull:true */ if (value == null) { throw new $TypeError(optMessage || 'Cannot call method on ' + value); } return value; }, IsCallable: IsCallable, SameValue: function SameValue(x, y) { if (x === y) { // 0 === -0, but they are not identical. if (x === 0) { return 1 / x === 1 / y; } return true; } return $isNaN(x) && $isNaN(y); }, // https://www.ecma-international.org/ecma-262/5.1/#sec-8 Type: function Type(x) { if (x === null) { return 'Null'; } if (typeof x === 'undefined') { return 'Undefined'; } if (typeof x === 'function' || typeof x === 'object') { return 'Object'; } if (typeof x === 'number') { return 'Number'; } if (typeof x === 'boolean') { return 'Boolean'; } if (typeof x === 'string') { return 'String'; } }, // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type IsPropertyDescriptor: function IsPropertyDescriptor(Desc) { if (this.Type(Desc) !== 'Object') { return false; } var allowed = { '[[Configurable]]': true, '[[Enumerable]]': true, '[[Get]]': true, '[[Set]]': true, '[[Value]]': true, '[[Writable]]': true }; // jscs:disable for (var key in Desc) { // eslint-disable-line if (has(Desc, key) && !allowed[key]) { return false; } } // jscs:enable var isData = has(Desc, '[[Value]]'); var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); if (isData && IsAccessor) { throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 IsAccessorDescriptor: function IsAccessorDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } if (!this.IsPropertyDescriptor(Desc)) { throw new $TypeError('Desc must be a Property Descriptor'); } if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { return false; } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 IsDataDescriptor: function IsDataDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } if (!this.IsPropertyDescriptor(Desc)) { throw new $TypeError('Desc must be a Property Descriptor'); } if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { return false; } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 IsGenericDescriptor: function IsGenericDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } if (!this.IsPropertyDescriptor(Desc)) { throw new $TypeError('Desc must be a Property Descriptor'); } if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) { return true; } return false; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { if (typeof Desc === 'undefined') { return Desc; } if (!this.IsPropertyDescriptor(Desc)) { throw new $TypeError('Desc must be a Property Descriptor'); } if (this.IsDataDescriptor(Desc)) { return { value: Desc['[[Value]]'], writable: !!Desc['[[Writable]]'], enumerable: !!Desc['[[Enumerable]]'], configurable: !!Desc['[[Configurable]]'] }; } else if (this.IsAccessorDescriptor(Desc)) { return { get: Desc['[[Get]]'], set: Desc['[[Set]]'], enumerable: !!Desc['[[Enumerable]]'], configurable: !!Desc['[[Configurable]]'] }; } else { throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); } }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 ToPropertyDescriptor: function ToPropertyDescriptor(Obj) { if (this.Type(Obj) !== 'Object') { throw new $TypeError('ToPropertyDescriptor requires an object'); } var desc = {}; if (has(Obj, 'enumerable')) { desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable); } if (has(Obj, 'configurable')) { desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable); } if (has(Obj, 'value')) { desc['[[Value]]'] = Obj.value; } if (has(Obj, 'writable')) { desc['[[Writable]]'] = this.ToBoolean(Obj.writable); } if (has(Obj, 'get')) { var getter = Obj.get; if (typeof getter !== 'undefined' && !this.IsCallable(getter)) { throw new TypeError('getter must be a function'); } desc['[[Get]]'] = getter; } if (has(Obj, 'set')) { var setter = Obj.set; if (typeof setter !== 'undefined' && !this.IsCallable(setter)) { throw new $TypeError('setter must be a function'); } desc['[[Set]]'] = setter; } if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); } return desc; } }; module.exports = ES5; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; var isPrimitive = __webpack_require__(47); var isCallable = __webpack_require__(32); // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 var ES5internalSlots = { '[[DefaultValue]]': function (O) { var actualHint; if (arguments.length > 1) { actualHint = arguments[1]; } else { actualHint = toStr.call(O) === '[object Date]' ? String : Number; } if (actualHint === String || actualHint === Number) { var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; var value, i; for (i = 0; i < methods.length; ++i) { if (isCallable(O[methods[i]])) { value = O[methods[i]](); if (isPrimitive(value)) { return value; } } } throw new TypeError('No default value'); } throw new TypeError('invalid [[DefaultValue]] hint supplied'); } }; // http://ecma-international.org/ecma-262/5.1/#sec-9.1 module.exports = function ToPrimitive(input) { if (isPrimitive(input)) { return input; } if (arguments.length > 1) { return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); } return ES5internalSlots['[[DefaultValue]]'](input); }; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = __webpack_require__(31); var regexExec = RegExp.prototype.exec; var gOPD = Object.getOwnPropertyDescriptor; var tryRegexExecCall = function tryRegexExec(value) { try { var lastIndex = value.lastIndex; value.lastIndex = 0; regexExec.call(value); return true; } catch (e) { return false; } finally { value.lastIndex = lastIndex; } }; var toStr = Object.prototype.toString; var regexClass = '[object RegExp]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isRegex(value) { if (!value || typeof value !== 'object') { return false; } if (!hasToStringTag) { return toStr.call(value) === regexClass; } var descriptor = gOPD(value, 'lastIndex'); var hasLastIndexDataProperty = descriptor && has(descriptor, 'value'); if (!hasLastIndexDataProperty) { return false; } return tryRegexExecCall(value); }; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var define = __webpack_require__(23); var getPolyfill = __webpack_require__(54); module.exports = function shimArrayPrototypeFind() { var polyfill = getPolyfill(); define(Array.prototype, { find: polyfill }, { find: function () { return Array.prototype.find !== polyfill; } }); return polyfill; }; /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // jshint freeze: false, maxcomplexity: 11 if (!Array.prototype.includes) { Array.prototype.includes = function (searchElement /*, fromIndex*/ ) { var O = Object(this); var len = parseInt(O.length) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1]) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) { k = 0; } } var currentElement; while (k < len) { currentElement = O[k]; if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) { return true; } k++; } return false; }; } /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.5+7f2b526d */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = void 0; var customSchedulerFn = void 0; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = void 0; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { var callback = arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(2); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var TRY_CATCH_ERROR = { error: null }; function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { TRY_CATCH_ERROR.error = error; return TRY_CATCH_ERROR; } } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === TRY_CATCH_ERROR) { reject(promise, TRY_CATCH_ERROR.error); TRY_CATCH_ERROR.error = null; } else if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } } function resolve(promise, value) { if (promise === value) { reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = void 0, callback = void 0, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = void 0, error = void 0, succeeded = void 0, failed = void 0; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value.error = null; } else { succeeded = true; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { resolve(promise, value); }, function rejectPromise(reason) { reject(promise, reason); }); } catch (e) { reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function validationError() { return new Error('Array Methods must be provided an Array'); } var Enumerator = function () { function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } Enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise$1) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator.prototype._settledAt = function _settledAt(state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$1(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {Function} resolver Useful for tooling. @constructor */ var Promise$1 = function () { function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ Promise.prototype.catch = function _catch(onRejection) { return this.then(null, onRejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @return {Promise} */ Promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; if (isFunction(callback)) { return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); } return promise.then(callback, callback); }; return Promise; }(); Promise$1.prototype.then = then; Promise$1.all = all; Promise$1.race = race; Promise$1.resolve = resolve$1; Promise$1.reject = reject$1; Promise$1._setScheduler = setScheduler; Promise$1._setAsap = setAsap; Promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise$1; } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; return Promise$1; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(55), __webpack_require__(17))) /***/ }), /* 116 */ /***/ (function(module, exports) { (function () { 'use strict'; if (typeof window.CustomEvent === "function") return false; function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; } CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); /***/ }), /* 117 */ /***/ (function(module, exports) { (function () { "use strict"; var testElement = document.createElement("_"); testElement.classList.add("c1", "c2"); // Polyfill for IE 10/11 and Firefox <26, where classList.add and // classList.remove exist but support only one argument at a time. if (!testElement.classList.contains("c2")) { var createMethod = function createMethod(method) { var original = DOMTokenList.prototype[method]; DOMTokenList.prototype[method] = function (token) { var i, len = arguments.length; for (i = 0; i < len; i++) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle("c3", false); // Polyfill for IE 10 and Firefox <24, where classList.toggle does not // support the second argument. if (testElement.classList.contains("c3")) { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } testElement = null; })(); /***/ }), /* 118 */ /***/ (function(module, exports) { (function () { 'use strict'; // The IE's "contains" method does not work when a text node is passed as argument. if (/Trident/.test(navigator.userAgent)) { Object.defineProperty(HTMLElement.prototype, 'contains', { writable: true, enumerable: false, configurable: true, value: function value(node) { if (!node) return false; return this === node || !!(this.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_CONTAINED_BY); } }); } // IE does not implement `Document.prototype.contains` if (typeof Document.prototype.contains !== 'function') { Object.defineProperty(Document.prototype, 'contains', { writable: true, enumerable: false, configurable: true, value: function value(el) { if (!el) return false; return this.documentElement.contains(el); } }); } // IE does not implement `Range.prototype.intersectsNode` if (typeof Range.prototype.intersectsNode !== 'function') { Object.defineProperty(Range.prototype, 'intersectsNode', { writable: true, enumerable: false, configurable: true, value: function value(node) { if (!node) { throw new TypeError("Failed to execute 'intersectsNode' on 'Range': 1 argument required, but only 0 present."); } if (this.startContainer.ownerDocument !== node.ownerDocument) return false; if (!node.parentNode) return true; var targetRange = document.createRange(); targetRange.selectNode(node); var startEnd = this.compareBoundaryPoints(Range.START_TO_END, targetRange); var endStart = this.compareBoundaryPoints(Range.END_TO_START, targetRange); return startEnd === 1 && endStart === -1; } }); } })(); /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var forOwn = __webpack_require__(120), isFunction = __webpack_require__(28); /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', objectClass = '[object Object]', stringClass = '[object String]'; /** Used for native method references */ var objectProto = Object.prototype; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { var result = true; if (!value) { return result; } var className = toString.call(value), length = value.length; if ((className == arrayClass || className == stringClass || className == argsClass ) || (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { return !length; } forOwn(value, function() { return (result = false); }); return result; } module.exports = isEmpty; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var baseCreateCallback = __webpack_require__(121), keys = __webpack_require__(12), objectTypes = __webpack_require__(26); /** * Iterates over own enumerable properties of an object, executing the callback * for each property. The callback is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by * explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) */ var forOwn = function(collection, callback, thisArg) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; if (callback(iterable[index], index, collection) === false) return result; } return result }; module.exports = forOwn; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var bind = __webpack_require__(122), identity = __webpack_require__(126), setBindData = __webpack_require__(33), support = __webpack_require__(127); /** Used to detected named functions */ var reFuncName = /^\s*function[ \n\r\t]+\w/; /** Used to detect functions containing a `this` reference */ var reThis = /\bthis\b/; /** Native method shortcuts */ var fnToString = Function.prototype.toString; /** * The base implementation of `_.createCallback` without support for creating * "_.pluck" or "_.where" style callbacks. * * @private * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. */ function baseCreateCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } // exit early for no `thisArg` or already bound by `Function#bind` if (typeof thisArg == 'undefined' || !('prototype' in func)) { return func; } var bindData = func.__bindData__; if (typeof bindData == 'undefined') { if (support.funcNames) { bindData = !func.name; } bindData = bindData || !support.funcDecomp; if (!bindData) { var source = fnToString.call(func); if (!support.funcNames) { bindData = !reFuncName.test(source); } if (!bindData) { // checks if `func` references the `this` keyword and stores the result bindData = reThis.test(source); setBindData(func, bindData); } } } // exit early if there are no `this` references or `func` is bound if (bindData === false || (bindData !== true && bindData[1] & 1)) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 2: return function(a, b) { return func.call(thisArg, a, b); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; } return bind(func, thisArg); } module.exports = baseCreateCallback; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var createWrapper = __webpack_require__(123), slice = __webpack_require__(27); /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * provided to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'fred' }, 'hi'); * func(); * // => 'hi fred' */ function bind(func, thisArg) { return arguments.length > 2 ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) : createWrapper(func, 1, null, null, thisArg); } module.exports = bind; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var baseBind = __webpack_require__(124), baseCreateWrapper = __webpack_require__(125), isFunction = __webpack_require__(28), slice = __webpack_require__(27); /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Native method shortcuts */ var push = arrayRef.push, unshift = arrayRef.unshift; /** * Creates a function that, when called, either curries or invokes `func` * with an optional `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of method flags to compose. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` * 8 - `_.curry` (bound) * 16 - `_.partial` * 32 - `_.partialRight` * @param {Array} [partialArgs] An array of arguments to prepend to those * provided to the new function. * @param {Array} [partialRightArgs] An array of arguments to append to those * provided to the new function. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new function. */ function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, isPartial = bitmask & 16, isPartialRight = bitmask & 32; if (!isBindKey && !isFunction(func)) { throw new TypeError; } if (isPartial && !partialArgs.length) { bitmask &= ~16; isPartial = partialArgs = false; } if (isPartialRight && !partialRightArgs.length) { bitmask &= ~32; isPartialRight = partialRightArgs = false; } var bindData = func && func.__bindData__; if (bindData && bindData !== true) { // clone `bindData` bindData = slice(bindData); if (bindData[2]) { bindData[2] = slice(bindData[2]); } if (bindData[3]) { bindData[3] = slice(bindData[3]); } // set `thisBinding` is not previously bound if (isBind && !(bindData[1] & 1)) { bindData[4] = thisArg; } // set if previously bound but not currently (subsequent curried functions) if (!isBind && bindData[1] & 1) { bitmask |= 8; } // set curried arity if not yet set if (isCurry && !(bindData[1] & 4)) { bindData[5] = arity; } // append partial left arguments if (isPartial) { push.apply(bindData[2] || (bindData[2] = []), partialArgs); } // append partial right arguments if (isPartialRight) { unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); } // merge flags bindData[1] |= bitmask; return createWrapper.apply(null, bindData); } // fast path for `_.bind` var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); } module.exports = createWrapper; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var baseCreate = __webpack_require__(56), isObject = __webpack_require__(18), setBindData = __webpack_require__(33), slice = __webpack_require__(27); /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Native method shortcuts */ var push = arrayRef.push; /** * The base implementation of `_.bind` that creates the bound function and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new bound function. */ function baseBind(bindData) { var func = bindData[0], partialArgs = bindData[2], thisArg = bindData[4]; function bound() { // `Function#bind` spec // http://es5.github.io/#x15.3.4.5 if (partialArgs) { // avoid `arguments` object deoptimizations by using `slice` instead // of `Array.prototype.slice.call` and not assigning `arguments` to a // variable as a ternary expression var args = slice(partialArgs); push.apply(args, arguments); } // mimic the constructor's `return` behavior // http://es5.github.io/#x13.2.2 if (this instanceof bound) { // ensure `new bound` is an instance of `func` var thisBinding = baseCreate(func.prototype), result = func.apply(thisBinding, args || arguments); return isObject(result) ? result : thisBinding; } return func.apply(thisArg, args || arguments); } setBindData(bound, bindData); return bound; } module.exports = baseBind; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var baseCreate = __webpack_require__(56), isObject = __webpack_require__(18), setBindData = __webpack_require__(33), slice = __webpack_require__(27); /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Native method shortcuts */ var push = arrayRef.push; /** * The base implementation of `createWrapper` that creates the wrapper and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new function. */ function baseCreateWrapper(bindData) { var func = bindData[0], bitmask = bindData[1], partialArgs = bindData[2], partialRightArgs = bindData[3], thisArg = bindData[4], arity = bindData[5]; var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, key = func; function bound() { var thisBinding = isBind ? thisArg : this; if (partialArgs) { var args = slice(partialArgs); push.apply(args, arguments); } if (partialRightArgs || isCurry) { args || (args = slice(arguments)); if (partialRightArgs) { push.apply(args, partialRightArgs); } if (isCurry && args.length < arity) { bitmask |= 16 & ~32; return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); } } args || (args = arguments); if (isBindKey) { func = thisBinding[key]; } if (this instanceof bound) { thisBinding = baseCreate(func.prototype); var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } setBindData(bound, bindData); return bound; } module.exports = baseCreateWrapper; /***/ }), /* 126 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utilities * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'name': 'fred' }; * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var isNative = __webpack_require__(25); /** Used to detect functions containing a `this` reference */ var reThis = /\bthis\b/; /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = {}; /** * Detect if functions can be decompiled by `Function#toString` * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). * * @memberOf _.support * @type boolean */ support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; }); /** * Detect if `Function#name` is supported (all but IE). * * @memberOf _.support * @type boolean */ support.funcNames = typeof Function.name == 'string'; module.exports = support; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(17))) /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var objectTypes = __webpack_require__(26); /** Used for native method references */ var objectProto = Object.prototype; /** Native method shortcuts */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. */ var shimKeys = function(object) { var index, iterable = object, result = []; if (!iterable) return result; if (!(objectTypes[typeof object])) return result; for (index in iterable) { if (hasOwnProperty.call(iterable, index)) { result.push(index); } } return result }; module.exports = shimKeys; /***/ }), /* 129 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** `Object#toString` result shortcuts */ var stringClass = '[object String]'; /** Used for native method references */ var objectProto = Object.prototype; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a string, else `false`. * @example * * _.isString('fred'); * // => true */ function isString(value) { return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == stringClass || false; } module.exports = isString; /***/ }), /* 130 */ /***/ (function(module, exports) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } module.exports = isUndefined; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var isFunction = __webpack_require__(28); /** * Resolves the value of property `key` on `object`. If `key` is a function * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {string} key The name of the property to resolve. * @returns {*} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, key) { if (object) { var value = object[key]; return isFunction(value) ? object[key]() : value; } } module.exports = result; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ var defaults = __webpack_require__(133), escape = __webpack_require__(58), escapeStringChar = __webpack_require__(136), keys = __webpack_require__(12), reInterpolate = __webpack_require__(60), templateSettings = __webpack_require__(137), values = __webpack_require__(138); /** Used to match empty string literals in compiled template source */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** * Used to match ES6 template delimiters * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {string} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as local variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [sourceURL] The sourceURL of the template's compiled source. * @param {string} [variable] The data object variable name. * @returns {Function|string} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'fred' }); * // => 'hello fred' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<%- value %>', { 'value': '